Compare commits

...
Author SHA1 Message Date
zsviczian 8f58faaa0d refactor: consolidate EA script execution lifecycles 2026-09-01 18:33:13 +02:00
zsviczian e9305f3501 Updated refactor plan with #11997 and #12018 comments and requirements 2026-09-01 14:28:40 +02:00
zsviczian 052dfe3c12 implemented #2916 2026-08-31 21:43:14 +02:00
zsviczian 59f655ed46 2.27.0-rc.2 2026-08-31 21:00:41 +02:00
zsviczian 1f20425f3d 2.27.0-rc.1 2026-08-30 21:59:34 +02:00
zsviczian 06647f8ea3 fixed inaccurate documentation of cloning and use of ea workbench. 2026-08-30 14:26:07 +02:00
zsviczian 5127f78def api updates 2026-08-30 12:08:10 +02:00
zsviczian 7f136e0618 2.27.0-beta.9, 0.18.130 2026-08-29 18:50:45 +02:00
zsviczian e079827dd3 Merge pull request #2915 from zsviczian/improved-scripting-skills
feat: Improved scripting skills
2026-08-29 13:42:11 +02:00
zsviczian d848084b59 Preserve JavaScript extensions in template sync 2026-08-29 13:37:44 +02:00
zsviczian 5bbf266455 Harden docs sync and checkpoint plan 2026-08-29 12:35:56 +02:00
zsviczian fc4f91339f Sync template bootstrap from docs generator 2026-08-29 11:15:12 +02:00
zsviczian 1ae56692aa Add preview image naming checks 2026-08-29 11:12:10 +02:00
zsviczian d1f87855e4 docs: decouple training docs from script PRs 2026-08-29 11:08:05 +02:00
zsviczian 04eee5f373 docs: clarify doc generation rationale 2026-08-29 11:05:08 +02:00
zsviczian c121056558 docs: add script publishing workflow guidance 2026-08-29 11:00:16 +02:00
zsviczian cd1d243ac5 docs: use absolute links in routing notes 2026-08-29 10:55:45 +02:00
zsviczian 0214eaed59 docs: route legacy training to curated skills 2026-08-29 10:42:10 +02:00
zsviczian 0245964a04 docs: fix scripting type export coverage 2026-08-29 10:37:42 +02:00
zsviczian a2263bc253 scripts: checkpoint 1 unify doc and skill generation 2026-08-29 10:20:46 +02:00
zsviczian a932f10e90 docs: add scripting support plan and baseline training outputs 2026-08-29 10:18:46 +02:00
zsviczian da124f019b 2.27.0-beta.8, 0.18.129 2026-08-28 22:26:33 +02:00
zsviczian 6f1f277ed9 Merge pull request #2913 from zsviczian/small-features-and-fixes
Fix legacy conversion assets and add JavaScript script support
2026-08-28 16:09:25 +02:00
zsviczian d7dd08fad6 feat: support JavaScript Excalidraw scripts 2026-08-28 15:54:28 +02:00
zsviczian 355d7c2d46 fix legacy conversion embedded files 2026-08-27 21:43:59 +02:00
zsviczian b9d12c09e3 2.27.0-beta.7 2026-08-27 20:20:45 +02:00
zsviczian 7a1a0d75ee fix: defer inline link suggestions until invoked (#2907) 2026-08-27 19:33:17 +02:00
zsviczian 263c09d07b docs: record React bundle size fallback 2026-08-27 19:22:41 +02:00
zsviczian 39346559ce React bundled normally instead of compressed to REACT_PACKAGES 2026-08-27 19:14:22 +02:00
zsviczian e4e9df0a49 Merge pull request #2911 from zsviczian/performance-refactor-batch2
Improve popout migration performance and lifecycle safety
2026-08-27 16:20:37 +02:00
zsviczian 149e1e5bf0 perf: publish migrated files progressively 2026-08-27 16:15:33 +02:00
zsviczian 0da7120a7d perf: adopt drawing state across window migration 2026-08-27 07:48:38 +02:00
zsviczian d94b3b19ad refactor: define drawing migration handoff 2026-08-26 22:18:24 +02:00
zsviczian 169ceb3cf3 fix: save dirty drawings for popout modals 2026-08-26 21:55:32 +02:00
zsviczian ded91c6882 fix: coalesce stencil library loading 2026-08-26 19:49:52 +02:00
zsviczian 4ce81be081 refactor: simplify shared runtime ownership 2026-08-26 19:33:33 +02:00
zsviczian 740ee455d3 refactor: share Excalidraw runtime across windows 2026-08-26 18:45:57 +02:00
zsviczian 81fbbf42b7 2.27.0-beta.6, 0.18.127 2026-08-26 07:20:52 +02:00
zsviczian ba6c45d621 Merge pull request #2908 from zsviczian/performance-refactor-pr
Improve save and popout lifecycle performance
2026-08-26 07:18:39 +02:00
zsviczian 1c76170bad fix: cancel image loading across popout teardown 2026-08-25 23:00:59 +02:00
zsviczian 4d60ce9263 fix: preserve dirty popout migrations 2026-08-25 21:02:50 +02:00
zsviczian d513935523 chore: remove local madge dependency 2026-08-25 15:26:00 +02:00
zsviczian 01fcb09f83 chore: remove performance refactor diagnostics 2026-08-25 15:25:19 +02:00
zsviczian 57240da793 perf: restore progressive scene image loading 2026-08-25 14:45:03 +02:00
zsviczian 91e78ec1ae perf: coalesce in-flight view saves 2026-08-25 08:19:13 +02:00
zsviczian 648a2a8ed8 refactor: extract view save coordinator 2026-08-25 07:45:56 +02:00
zsviczian 83c8493c02 chore: use explicit window globals 2026-08-25 06:10:39 +02:00
zsviczian 67352c9952 perf: define save side-effect policy 2026-08-24 23:03:28 +02:00
zsviczian b4170ac68c perf: coalesce drawing backup writes 2026-08-24 22:37:09 +02:00
zsviczian 767cacbcdc perf: reuse coherent save snapshots 2026-08-24 22:19:58 +02:00
zsviczian b708883e13 perf: index images during save synchronization 2026-08-24 21:51:24 +02:00
zsviczian ded19ad510 perf: linearize save synchronization indexes 2026-08-24 21:06:09 +02:00
zsviczian 3579dbf245 fix: retain Excalidraw classification during cache refresh 2026-08-24 20:39:03 +02:00
zsviczian 8a0714104a perf: decouple blur saves from scene refresh 2026-08-24 20:27:51 +02:00
zsviczian 61817b01c6 WIP: validate performance refactor phase 1A lifecycle fixes 2026-08-24 20:01:36 +02:00
zsviczian d3e7182ff2 generate repository zip 2026-08-24 18:09:31 +02:00
zsviczian 6a50ccd271 updated agents.md and contributing.md 2026-08-23 22:02:38 +02:00
zsviczian f4ff25f308 fixed tootltip appearing twice - registerElementActionProvider 2026-08-23 20:04:25 +02:00
zsviczian df95e5f2b0 fixed settings breadcrumbs on Obsidian Mobile (touch) 2026-08-23 19:23:04 +02:00
zsviczian b6e98a8231 Merge pull request #2905 from theslyprofessor/fix/stale-canvas-offsets-1544
Fix stale canvas offsets when the view moves without resizing
2026-08-23 18:57:55 +02:00
zsviczian 48a35c7982 Merge pull request #2906 from zsviczian/declarative-settings
Migrate Excalidraw settings to Obsidian's declarative settings API
2026-08-23 18:55:13 +02:00
zsviczian 13652c2832 bumped excalidraw to 0.18.126 2026-08-23 18:54:23 +02:00
zsviczian 02a4f37e32 Polish 2.27.0 release notes 2026-08-23 18:44:22 +02:00
zsviczian 1ce6198c39 Complete declarative settings migration 2026-08-23 18:40:04 +02:00
zsviczian 0fdc689b3b Finalize declarative settings activation 2026-08-23 17:58:47 +02:00
zsviczian 21bcb6be91 Migrate AI settings declaratively 2026-08-23 17:34:00 +02:00
zsviczian ed960eb909 Migrate remaining non-AI settings declaratively 2026-08-23 16:40:23 +02:00
zsviczian 5a0419d8f7 Migrate embed and export settings declaratively 2026-08-23 15:40:36 +02:00
zsviczian b429e41f62 Migrate display and link settings declaratively 2026-08-23 13:17:32 +02:00
Nakul Tiruviluamala 8bfcd23b77 Flush offset refresh synchronously on the pointerdown path
Per review: api.refresh() only enqueues a React state update, so the
capture-phase pointerdown guard alone could not correct the SAME event's
coordinates - the first tap after a layout shift with the pointer already
inside the view still used stale offsets. Wrap the pointerdown-path
refresh in flushSync (available on the plugin's private react-dom
runtime) so the corrected offsets are committed before React's delegated
handlers process the event. Falls back to the async refresh if flushSync
is unavailable or throws.
2026-08-23 03:32:46 -07:00
Nakul Tiruviluamala 74429eb4eb Fix stale canvas offsets when the view moves without resizing (#1544)
Excalidraw caches offsetLeft/offsetTop and recalculates on container
resize or scroll, but nothing above the canvas changing height (an
injected toolbar row, tab-header wrap) moves the canvas WITHOUT a size
change, so pointer and selection events land a few pixels off until the
next autosave tick refreshes offsets (up to 60s on desktop).

Adds a throttled drift guard on pointerenter/pointerdown that compares
the container's bounding rect to the cached appState offsets and calls
refreshCanvasOffset() when they disagree by more than 1px, plus a
css-change hook mirroring the existing layout-change refresh.
2026-08-23 03:10:30 -07:00
zsviczian 9f182616a5 Migrate initial settings sections declaratively 2026-08-23 11:21:13 +02:00
zsviczian 148318ec21 Recover corrupted settings safely 2026-08-23 05:47:05 +02:00
zsviczian 0caa6b7d90 Simplify settings persistence safeguards 2026-08-22 00:04:29 +02:00
zsviczian dd30833789 Recover interrupted settings saves 2026-08-21 22:52:10 +02:00
zsviczian f82f4cf5eb Coalesce settings persistence updates 2026-08-21 22:26:58 +02:00
zsviczian 3f8a04d893 Establish declarative settings adapters 2026-08-21 21:17:51 +02:00
zsviczian f6525d72f8 Add declarative settings compatibility types 2026-08-21 20:57:26 +02:00
zsviczian eeffa5749b Document declarative settings migration plan 2026-08-21 20:27:08 +02:00
zsviczian 36a32940ba Merge pull request #2896 from zsviczian/performance-improvement
Improve embedded scene loading performance
2026-08-16 19:30:14 +02:00
zsviczian 6d344ee3d7 perf: accelerate embedded scene loading 2026-08-16 19:19:57 +02:00
zsviczian 479ecaab33 2.27.0-beta.3 2026-08-16 10:55:46 +02:00
zsviczian 044d39badb fix code scanner findings 2026-08-16 10:46:49 +02:00
zsviczian c6ab40470f updated agents.md and contributing.md 2026-08-16 10:23:18 +02:00
zsviczian d68d23a989 Merge pull request #2895 from zsviczian/new-excalidraw-boundary
Register typed Excalidraw host adapters
2026-08-15 22:43:52 +02:00
zsviczian 8025e1ed1a Complete typed Excalidraw host boundary 2026-08-15 22:40:44 +02:00
zsviczian 57dac2e523 Register Excalidraw package settings adapter 2026-08-15 21:26:09 +02:00
zsviczian c3834b3ed3 Record common host-boundary completion 2026-08-15 20:59:31 +02:00
zsviczian 87f3d863b7 Record desktop UI-mode boundary checkpoint 2026-08-15 20:18:52 +02:00
zsviczian a23ccee9ad Record device-info boundary checkpoint 2026-08-15 20:12:44 +02:00
zsviczian 6c413038f9 Register typed Excalidraw host adapter 2026-08-15 19:58:44 +02:00
zsviczian 4f32647d6f Merge pull request #2893 from zsviczian/excalidraw-automate-cleanup
ExcalidrawAutomate and ExcalidrawView Utils cleanup
2026-08-14 19:16:43 +02:00
zsviczian b0d3125c37 0.18.123 2026-08-14 19:14:52 +02:00
zsviczian 9daa9fa936 typefix on excalidrawViewUtils.ts 2026-08-14 19:00:12 +02:00
zsviczianandClaude Sonnet 5 efb00d1d83 Eliminate remaining any-collapse in ExcalidrawAutomate.ts
cloneElement()/cloneElements() both deep-clone via
JSON.parse(JSON.stringify(el)), which is implicitly any; cast to the
already-known shape (Mutable<ExcalidrawElement>, plus a small local
type for the two cross-element-type relationship fields the generic
remap logic probes). Swapped a same-shape-but-looser inline
boundElements callback annotation for the real BoundElement type, and
gave an untyped new Promise((resolve) => ...) its actual
Promise<string | null>.

The two remaining clusters were genuine external boundaries, fixed at
the source rather than cast around:
- addMermaid()'s result.files traced to mermaidToExcalidraw()'s own
  declared return type in the fork (files?: any). Fixed upstream
  (files?: BinaryFiles) and rebuilt; the suppression is now simply
  unnecessary and removed.
- cloneElements()'s JSON.parse(elementsOrClipboard) now uses the real
  envelope shape confirmed against serializeAsClipboardJSON()/
  actionCopy in the fork's clipboard.ts, instead of a suppression.

Zero eslint-disable comments remain in this file. Confirmed via a
git-stash ESLint diff: 229 -> 172 findings repo-wide, zero regressions,
entire delta contained to this one file. Build, lib, and node --check
all pass clean; dist/main.js unchanged from this repo's side (the fork
rebuild's own +19 bytes aside).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-14 18:40:32 +02:00
zsviczian d5e2467966 2.27.0-beta.2 2026-08-14 15:25:46 +02:00
zsviczian ccb1f975f4 Merge pull request #2892 from zsviczian/excalidraw-type-import-fix
Fix @excalidraw/common type resolution, eliminating a huge any-collapse
2026-08-14 15:24:44 +02:00
zsviczianandClaude Sonnet 5 8d06fe1ee2 Fix @excalidraw/common type resolution, eliminating a huge any-collapse
@zsviczian/excalidraw's bundled .d.ts files import bare-specifier
@excalidraw/common|element|math|utils, packages this plugin never
depends on (confirmed the same gap exists in upstream's own published
@excalidraw/excalidraw, not a fork-specific bug). Every value that
touched one of those unresolvable imports -- Theme, BinaryFileData.id,
most of AppState, large parts of ExcalidrawElement -- silently
collapsed to any.

Fixed via tsconfig.json paths redirecting all four specifiers (bare
and subpath) into @zsviczian/excalidraw's own already-vendored type
copies under node_modules/@zsviczian/excalidraw/types/ -- zero
version-drift risk since it's literally the same files, and no new
dependency needed. (A first attempt using an external @excalidraw/element
devDependency was reverted: its independently-versioned types
structurally disagreed with this package's own bundled ExcalidrawElement,
producing false-positive mismatches.)

Fixed all 117 real, previously-masked compile errors this surfaced
across 18 files, smallest to largest, each verified with a build
before moving on. Two were genuine pre-existing bugs, not type gaps:

- ExcalidrawView.ts addFiles(): isDark was assigned the literal theme
  string instead of a boolean comparison; !!isDark on any non-empty
  string is always true, so every image loaded through that fallback
  path had been treated as dark-themed regardless of actual theme.
- ExcalidrawView.ts getSelectedTextElement(): the grouped-text-element
  branch cast the originally-selected (possibly non-text) element
  instead of the text element the same branch had already found two
  lines above, silently returning undefined text for non-text
  selections.

getViewColorPalette()'s Array.isArray check, initially flagged as
dead code guarding an impossible shape, turned out to be correct:
AppState.colorPalette's declared ColorPaletteCustom type describes
the record-shaped settings input, but the fork flattens it to a color
list by the time it reaches AppState. Fixed as a documented bridge
cast once confirmed against the fork's own type source, not a logic
change.

Confirmed via a git-stash ESLint diff against the prior commit: 411 ->
229 findings (44% fewer), zero files regressing. Build, lib, and
node --check all pass clean with zero remaining diagnostics.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-14 15:22:52 +02:00
zsviczianandClaude Sonnet 5 b7472cb8ad Fix unannotated iterator result in excalidrawAutomateUtils.ts
Same shape as the ExcalidrawData.ts RegExpMatchIteratorResult fix: a
let parts; with no type annotation, assigned via res.next(), collapsed
to implicit any. Annotated it. Confirmed via git-stash ESLint diff
that this introduces zero new findings anywhere (413 -> 411).

Also documents a much larger, separate structural finding in
RefactorPlan.md: the remaining 8 findings in this file trace to
@zsviczian/excalidraw's bundled .d.ts files importing from
@excalidraw/common, a package this plugin never depends on -
explains BinaryFileData["id"]/AppState["theme"] collapsing to any.
Not fixed here; needs its own investigation.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-14 13:38:23 +02:00
zsviczianandClaude Sonnet 5 eb02975bfc Fix stale-image retry no-op and ExcalidrawDataScene any-collapse
getFiles() called Object.values() on a Map, which always returns [] -
the only caller (ViewSceneFileManager's stale-image retry loop) has
likely never actually retried a failed-to-load file. Fixed with
Array.from(...values()).

ExcalidrawDataScene intersected a base type that already declared
elements/appState, so TypeScript merged rather than overrode them,
collapsing this.scene.elements to `any` on every direct .filter() call
and cascading into dozens of no-unsafe-* findings. Fixed by Omitting
the colliding keys from the base type before intersecting; type-only,
no runtime behavior change. Two previously-invisible narrowing gaps
this uncovered were fixed with the same `as Mutable<ExcalidrawTextElement>[]`
idiom already used elsewhere in the file.

Confirmed via a git-stash ESLint diff that this introduces zero new
findings anywhere in the repo (470 -> 413, with ExcalidrawAutomate.ts
and ExcalidrawView.ts also improving as a side effect). Both fixes
manually tested and confirmed working.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-14 13:08:05 +02:00
zsviczianandClaude Sonnet 5 6b2b2592e4 Extract Markdown parsing and embedded-data registries from ExcalidrawData
ExcalidrawData.ts had grown to 2,845 lines. Move the module-level
Markdown/frontmatter parsing functions to excalidrawMarkdownParsing.ts,
and the Files/Equations/MarkdownImages/Mermaids registries to
EmbeddedDataRegistries.ts, both as intact code motion behind
re-exports/delegates so no external caller changed. Reduces
ExcalidrawData.ts to 2,285 lines with zero new lint findings and no
change to the circular-dependency baseline.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-14 12:35:54 +02:00
zsviczian 2ea7cf5513 fixed: #2889 2026-08-14 09:28:32 +02:00
zsviczian 07b16330d6 Merge pull request #2890 from zsviczian/custom-elements-menu
Feat: Custom elements menu
2026-08-14 09:04:39 +02:00
zsviczianandClaude Sonnet 5 d0898f9fb9 Add script autostart permission flow, UI, and duplicate-registration guard
Completes the script-autostart feature: ExcalidrawAutomate.registerAutostart()
lets a script ask to be automatically re-run every time a new Excalidraw view
opens, gated by a user-confirmed Allow/Deny/Ask-every-time prompt whose
decision persists in the new autostartScripts setting. A fresh "allow" also
immediately attaches the script to every other currently-open view, and
tracks per-script autostart failures (autostartScriptFailures) without
saving settings on every successful run.

ScriptEngine.runAutostartScripts() re-runs allow-listed scripts on each new
view open (wired from ExcalidrawRoot.ts's mount effect); renaming or deleting
a script's file purges its stale permission/failure entries.

Adds AutostartScriptsSettingsComponent, rendered as a table (reusing the
existing AI-provider-table styling) directly in the Excalidraw Automate
settings section and in a Command Palette modal ("Autostart scripts"),
letting a script's Autostart / Manual start only / Ask every time decision
be changed at any time - a "Manual start only" choice is not a dead end.

Also fixes a duplicate-registration bug in registerElementActionProvider():
running an already-registered script again in the same view no longer
creates a second action button.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-14 08:58:14 +02:00
zsviczianandClaude Sonnet 5 dbb9a7dc0b Add ExcalidrawAutomate.registerAutostart() script autostart permission flow
Lets a script ask to be automatically re-run every time a new Excalidraw
view opens. First call prompts the user Allow/Deny/Ask-me-later via the
existing MultiOptionConfirmationPrompt; the decision persists in the new
autostartScripts setting, a sibling of scriptEngineSettings since it is
plugin/user-trusted permission state a script must not silently flip.

Two additions from user testing: a fresh "allow" also immediately re-runs
the script in every other currently-open view (ScriptEngine.
attachAutostartScriptToOpenViews()), not only views opened afterward; and
renaming/deleting a script's file now purges its autostartScripts entry
(ScriptEngine.purgeAutostartPermission(), wired into the existing
delete/rename event handlers) instead of leaving a stale orphaned
permission under the old name.

No autostart-on-view-open execution or settings UI yet - that's next.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-14 06:33:17 +02:00
zsviczianandClaude Sonnet 5 9390dec8e2 Add ExcalidrawAutomate.registerElementActionProvider() scripting API
Lets scripts register custom buttons in the selected-element context menu
(view.selectedElementActionsMenu), previously only used internally for the
built-in markdown-image edit/convert actions. Delegates to the existing
registerProvider() mechanism, so per-view cleanup on view close was
already free; adds ScriptEngine.trackElementActionProvider() + cleanup in
unloadScript() for the one real gap: a script's file being deleted while a
view using its registered action is still open.

Fixes a bug found during testing: registerProvider() primes the menu to
recompute actions on its next update() call, but nothing triggered
update() immediately, so a button didn't appear until the user deselected
and reselected an already-selected eligible element. Fixed by calling
update() immediately after registering, mirroring the same call
ExcalidrawRoot.ts already makes at view-open time.

Moves SelectedElementMenuAction/SelectedElementMenuProvider from the
view-owned SelectedElementActionsMenu.ts to a new src/types/
elementActionTypes.ts, since they're now referenced from the public
ExcalidrawAutomate.ts API surface too.

Completes the ExcalidrawAutomate Change Checklist: SuggesterInfo.ts entry
and a Messages.ts release note under 2.27.0. No locale changes needed --
this API produces no plugin-authored user-visible strings.

User-tested: multiple independently-registered/cleared menus, and the
immediate-visibility fix, both confirmed working.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-14 05:57:17 +02:00
zsviczianandClaude Sonnet 5 a8e2b0984a Correct stale RefactorPlan.md note now that the ExcalidrawData.ts fix is committed
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-13 23:07:03 +02:00
zsviczianandClaude Sonnet 5 c78cfcc1e5 Fix ExcalidrawData.ts no-unsafe-* findings at their root cause
8 `let parts;`/`let res;` declarations (getDecompressedScene, getJSON, the
text-element/element-link parsing loop, and both quickParse/hasTransclusion
link-parsing loops) had no initializer and no type annotation, so
TypeScript inferred implicit `any`, cascading into every downstream
.value/.length/.index access. The correct type, RegExpMatchIteratorResult,
already existed in this file and was already used correctly by half a
dozen other methods, and was already implied by the exact functions these
variables got passed into. Pure type-annotation change, nothing else
touched — reduces this file's no-unsafe-* findings from 108 to 64 (514 to
470 codebase-wide) with zero logic change.

Also updates RefactorPlan.md documenting this fix and why AIUtils.ts's
similar-looking cluster was investigated and deliberately not pursued: its
`any` traces to Obsidian's own RequestUrlResponse.json: any (a genuine
external API boundary across 5 AI providers, with one spot that mutates
the response object), not a local missing annotation, so it doesn't meet
the same low-risk bar. This effort is parked for now.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-13 23:06:37 +02:00
zsviczianandClaude Sonnet 5 7067336d0d Fully close out the slider control type for the declarative settings dispatch
Extends SliderControl with after/afterUpdate hooks (no before — no
existing slider needed one). Widens SliderSetting.onChange in
sliderUtils.ts from (value: number) => void to (value: number) => void |
Promise<void> since hooks can be async; createSliderWithText's internal
caller now awaits it. ESLint's no-misused-promises/no-floating-promises
caught both sides of this gap at lint time before it shipped.

Converted: long-press duration desktop/mobile, link opacity, rendering
concurrency, image cache retention days, PNG export scale, export padding,
and max image zoom-in (afterUpdate hook). 3 sliders deliberately left as
legacy code (grid opacity, laser decay time/length — nested
gridSettings/laserSettings fields, not a flat NumberSettingKey), documented
in RefactorPlan.md.

All four control types (toggle/text/dropdown/slider) are now fully
converted. RefactorPlan.md's section is updated with a summary of what
remains before this could feed Obsidian's real getSettingDefinitions():
render support, the visible/visibility-gate mechanism, and only then
wiring up the real API behind Path B.

Manually tested with a risk-based check list; user confirmed no issues
found.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-13 22:08:20 +02:00
zsviczianandClaude Sonnet 5 e176d96c97 Fully close out the dropdown control type for the declarative settings dispatch
Extends DropdownControl with before/after/afterUpdate hooks (mirroring
toggle/text) and adds a NumberDropdownControl variant for dropdowns whose
options are numbers stored as DOM strings but bind to a numeric field
(parse: "int" | "float" controls the parseInt/parseFloat conversion back
into the setting). 117 settings are now on the new path.

Converted: dynamicStyling and previewImageType (plain dropdowns with a
before/after flag hook each), plus the four number-dropdowns: autosave
interval desktop/mobile, PDF export scale, and custom pen count.

4 dropdowns deliberately left as legacy code, documented in
RefactorPlan.md: LIBRARY_STORAGE_NAME (branching async migration logic
ending in a full this.display() re-render), the dynamic AI provider/model
dropdown, EMBED_TYPE_NAME (the dropdown the already-excluded SVG/PNG
export toggles mutate — dynamic options, self-correcting migration,
cross-control show/hide), and the dynamic per-script dropdown closure.

Manually tested with a risk-based check list prioritizing the new
NumberDropdownControl mechanism and type-tricky (literal-union/enum)
fields; user confirmed no issues found.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-13 21:48:05 +02:00
zsviczianandClaude Sonnet 5 1df7a47832 Fully close out the text control type for the declarative settings dispatch
Extends TextControl with before/after/afterUpdate hooks (mirroring
ToggleControl), a vaultPath hook that wires the text input into the
existing addVaultPathSupport() (path suggester + existence warning), and a
capture hook exposing the raw TextComponent for callers that need to keep
manipulating it afterward (a sibling toggle disabling it,
configurePasswordTextInput()). 111 settings are now on the new path.

Converted: folder/file settings (drawing folder, library folder/file,
crop/annotate folders, template, script folder, CJK assets, LaTeX
preamble) via vaultPath; TODO/Done prefix fields and the Taskbone API key
via capture (both interact with toggles converted in the previous commit);
the three filename-affix fields combining sanitize + after (shared
sanitizeFilenameSegment helper); plus the remaining plain text settings.

7 text settings deliberately left as legacy code, documented in
RefactorPlan.md: 4 numeric-text-with-validation fields (different control
shape than sanitize's pure string transform), the AI section's
getter/setter-based number closure, STARTUP_SCRIPT_NAME (text + button
chained on one row with a cross-control dependency), and the two dynamic
per-script text closures.

Manually spot-checked; user confirmed no issues found.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-13 21:24:26 +02:00
zsviczianandClaude Sonnet 5 4fcb50b53a Fully close out the toggle control type for the declarative settings dispatch
Converts the remaining side-effect and captured-Setting-reference toggles
using the new before/after/afterUpdate/negate hooks and buildSetting()'s
Setting return value. 89 settings are now on the new path; 7 toggles are
deliberately left as legacy code because they don't fit the control shape
(nested/migration-guarded fields, cross-control dropdown mutation, a
dynamic per-script toggle) — documented in RefactorPlan.md along with why
each was excluded.

Fixed 4 no-unnecessary-type-assertion ESLint findings from non-null
assertions on buildSetting()'s return value — this project doesn't have
strictNullChecks enabled, so they were genuine no-ops.

Manually smoke-tested; user confirmed no issues found.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-13 20:51:40 +02:00
zsviczianandClaude Sonnet 5 7b25cfca86 Convert all plain toggle settings to the declarative buildSetting() dispatch
Mechanically converts 51 additional plain (assign + applySettingsUpdate
only) addToggle blocks to buildSetting() calls, using a script that
locates each block by precise bracket-matching rather than manual editing,
to guarantee the same name/desc/key/reload semantics are preserved
byte-for-byte. 66 settings are now on the new path.

Deliberately excludes: toggles whose Setting object is captured into a
variable for later use elsewhere (e.g. readingModeEl.nameEl.setAttribute(),
embedComment's later show/hide) since buildSetting() doesn't return the
Setting reference yet, and the ~22 toggles with a genuine side effect
beyond persistence (show/hide wrappers, requestReloadDrawings, view
refreshes, dropdown-option mutation) since ToggleControl has no side-effect
hook yet. Both are left as imperative code for a later step.

Also widens SettingDefinition.name (and the pre-existing SliderSetting.name
in sliderUtils.ts) from string to string | DocumentFragment: Obsidian's
Setting.setName() accepts both, and several existing settings pass
fragWithHTML(...) as the name, not just the description.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-13 19:51:24 +02:00
zsviczianandClaude Sonnet 5 b1dd56ddfe Add declarative-shaped SettingDefinition dispatch, pilot all four control types
Adds an internal SettingDefinition/buildSetting() interpreter modeled after
Obsidian's declarative settings API (getSettingDefinitions(), requires
1.13+, not called directly yet) so the current imperative display() can
gradually move toward that shape without depending on Obsidian's real
1.13 types or bumping minAppVersion.

Implements and pilots all four control types against a small, individually
verified set of existing settings, smallest-risk slice first:
- toggle: showReleaseNotes, compareManifestToPluginVersion,
  showNewVersionNotification
- text: latexBoilerplate, experimentalFileTag (plain), cropPrefix/
  cropSuffix/annotatePrefix/annotateSuffix (sanitize hook, shared
  sanitizeFilenameSegment helper)
- dropdown: defaultMode (exact string), defaultPenMode (string-literal
  union, needs the setStringSetting correlated-generic write helper since
  TypeScript can't verify a plain indexed write is sound across a union of
  differently-typed keys)
- slider: zoomToFitMaxLevel (1:1), zoomStep/zoomMin/zoomMax (scale hook,
  stored as a 0-1 fraction displayed as a 1-100 percent slider), reusing
  the existing createSliderWithText helper unchanged

Key/value correlation is compiler-enforced via BooleanSettingKey/
StringSettingKey/StringLikeSettingKey/NumberSettingKey mapped types, so a
control can only bind to a setting of the matching type.

render support and the visible/visibility-gate mechanism (for the existing
show/hide-driven conditional settings) are deliberately deferred to later
steps.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-13 19:35:09 +02:00
zsviczianandClaude Sonnet 5 3c49aba91c Split ExcalidrawSettingTab.display() into 14 per-section methods
display() was a single ~3,640-line method building the entire settings UI,
already visually organized into named sections via comment dividers and
<hr> elements but with none of that structure at the code level. Extracts
each section into its own private renderXSection() method, called in the
original order from a now ~15-line display(). Pure code motion, verified
byte-identical via a reconstruction diff against the original method body
before splicing.

Two sections turned out to nest sub-panels sharing a single DOM container
(Display + Pen/Grid/Laser Pointer) and were kept as one method rather than
split further. One genuine cross-section dependency surfaced during the
build: a filename-sample preview element and its refresh function, defined
in the Saving section but also refreshed by the Compatibility section's
compatibilityMode toggle. Promoted both to a private field
(filenameSampleEl) and method (getFilenameSample()) on the class.

Makes the settings tab navigable at the code level and creates the natural
per-section unit for eventually converting individual settings to
Obsidian's declarative getSettingDefinitions() API.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-13 15:55:22 +02:00
zsviczianandClaude Sonnet 5 d2fe360c71 Extract settings data model into settingsDefaults.ts
Moves ExcalidrawSettings, DEFAULT_SETTINGS, and the AI provider/model
config constants out of settings.ts into a dedicated settingsDefaults.ts,
decoupling the data model from the ExcalidrawSettingTab UI class. Consumers
that only needed the settings shape (PluginSettingsManager and 6 other
files) now import from the new location directly instead of pulling in the
whole settings-tab UI class and its dialog/component imports; 5 of them are
converted to import type since they only ever used it as a type.

Prep work toward eventually supporting Obsidian's declarative settings API
without bumping minAppVersion past 1.8.7 yet.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-13 15:50:21 +02:00
zsviczianandClaude Sonnet 5 d55826a5ac Park the ExcalidrawView/main.ts RefactorPlan and record circular-dependency learnings
Closes the ViewSceneFileManager validation checkpoint (user-confirmed, no
issues found) and documents the madge-vs-Rollup circular-dependency
investigation, including why the import-type cleanup didn't move the
reported cycle count. Focus is shifting to src/core/settings.ts and
declarative-settings readiness; the plan is left in a resumable state with
an explicit "next steps if resumed" sequence.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-13 14:52:40 +02:00
zsviczianandClaude Sonnet 5 f39db658db Use import type for ExcalidrawView/ExcalidrawPlugin where only used as a type
These 19 files imported ExcalidrawView or ExcalidrawPlugin as values solely
to type a constructor parameter or field; none accessed them at runtime.
Switching to import type removes unnecessary runtime coupling and matches
the convention already used elsewhere (FontManager, MonkeyPatchManager,
StencilLibraryManager, FieldSuggester, and this session's manager
extractions).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-13 14:42:23 +02:00
zsviczian ca6ddb6de8 Merge pull request #2884 from dimateos/patch-1
stencil library formatted with 2 spaces
2026-08-13 14:19:41 +02:00
zsviczian 077bbca649 Localize the 10 hardcoded strings flagged by sentence-case lint
ObserverManager.ts, InsertPDFModal.ts, PublishOutOfDateFiles.ts,
ImageCache.ts, Taskbone.ts, and carveout.ts had zero existing t() calls
-- these were hardcoded English strings in Notices, a modal title/
description, and button labels, a real gap against the project's own
"no hardcoded strings" policy, not just a lint nit. Moved all 10 to
en.ts and added translations to es/ru/zh-cn/zh-tw (mine, not verified
by a native speaker -- worth a review pass before release; t() falls
back to English for any locale missing a key, so this is strictly no
worse than the previous always-English behavior).

Also fixes two pre-existing typos while relocating the strings, no
logic change: "rescaning" -> "rescanning" (Taskbone.ts), "NewExcalidraw"
-> "New Excalidraw" (carveout.ts).
2026-08-13 10:28:48 +02:00
zsviczian b04d56091a Fix all 25 no-undef findings without suppressing the rule
Each is TypeScript resolving an ambient global that plain-JS no-undef
scope analysis can't see, not a real bug (verified: tsc/rollup-typescript
built clean on every one before this change too):

- Buffer/NodeJS/BufferEncoding (9x): genuine ambient Node types in
  Obsidian's Electron environment. Declared via globals.node plus two
  explicit entries for the TS-only type/namespace names globals.node
  doesn't cover.
- HTMLWebViewElement (3x, ExcalidrawView.ts): declared as a bare
  top-level `interface` in @types/react/global.d.ts (an ambient script,
  not a module) -- a real global type, same category as HTMLDivElement.
  Declared in ESLint's globals with a comment citing the source.
- React (4x, ExcalidrawAutomate.ts + modifierkeyHelper.ts): NOT a
  global -- @types/react uses `export as namespace React`, only
  available once "react" is imported somewhere in the program. Added
  explicit `import type React from "react"` to both files instead of
  declaring it global, since that's factually correct and makes each
  file's own dependency explicit rather than relying on incidental
  cross-file ambient leakage.
- 8 Obsidian type names in types.d.ts (PluginManifest, Hotkey,
  TAbstractFile, MenuItem, Component, EventRef, WorkspaceContainer):
  also not globals -- named exports of the "obsidian" module referenced
  from inside a `declare module "obsidian" { ... }` augmentation block.
  Extended the file's existing `import {...} from "obsidian"`.
2026-08-13 10:28:35 +02:00
zsviczian a397b4a776 svgToExcalidraw: remove dead second SVG-path implementation
Deletes elements/index.ts, elements/path/ (index.ts, utils/bezier.ts,
utils/ellipse.ts, utils/path-to-points.ts), and elements/utils.ts --
an entire second SVG-path-to-points implementation that nothing
reachable from the actual entry point (parser.ts -> walker.ts)
imports; walker.ts uses the external points-on-path package instead.
Verified via repo-wide search that elements/index.ts (the only entry
into this chain) has zero importers.

Also deletes types.ts, whose only remaining exports (RawElement,
ElementBoundaries, PathCommand) were used exclusively by the removed
files, and removes utils.ts's safeNumber, whose only caller was the
removed bezier.ts.
2026-08-12 22:51:36 +02:00
zsviczian bc7b8cee44 svgToExcalidraw: align line/draw elements to real ExcalidrawLineElement
ExcalidrawLine is now Mutable<ExcalidrawLineElement>; ExcalidrawDraw is
removed (it was a byte-for-byte structural duplicate of ExcalidrawLine).
createExLine() takes points up front and converts them to branded
LocalPoint via a local reimplementation of the fork's pointFrom()
(which is just `[x, y] as Point` at runtime -- the plugin never imports
runtime Excalidraw code directly, so reproducing the one-liner avoids
bundling a second copy of fork code). startBinding/endBinding/
startArrowhead/endArrowhead default to null and polygon defaults to
true, since every SVG-converted line/path element is a closed,
fillable shape (the polygon feature didn't exist when this module was
written).

Because the local ExcalidrawGenericElement union is now composed
entirely of real fork types, ExcalidrawAutomate.importSVG() no longer
needs the `res.content as unknown as ExcalidrawElement[]` cast that
was hiding this gap -- it's a plain, compiler-verified assignment now.
2026-08-12 22:51:27 +02:00
zsviczian 40e2120041 svgToExcalidraw: remove dead vendored types, align rect/ellipse to real types
Deletes the empty src/svgToExcalidraw/ folder and the unused "from
Excalidraw codebase" block in types.ts (verified nothing imports any
of it). ExcalidrawElementBase/Rectangle/Ellipse are now derived from
the real @zsviczian/excalidraw element types (Mutable<...>) instead of
a hand-maintained local copy, so createExElement() now sets index/
frameId/boundElements/updated/link/locked using the same defaults as
the fork's own newElement() factory. Line/draw elements are left as a
local shape for now (real ExcalidrawLineElement needs branded
LocalPoint and binding/arrowhead fields -- noted as a separate step).
2026-08-12 22:29:51 +02:00
zsviczian 3a7b23779e Alias pen/stroke-options types to the fork's canonical definitions
src/types/penTypes.ts and ObsidianMenu.tsx's ResetCustomPenState now
alias @zsviczian/excalidraw's ObsidianPenStyle/ObsidianPenOptions/
ObsidianResetCustomPenState instead of maintaining independent copies,
and ExcalidrawViewAppState drops the unknown overrides that were
re-loosening those fields after the base AppState already typed them
precisely.
2026-08-12 22:06:03 +02:00
zsviczian f8f8a4e542 Bump @zsviczian/excalidraw to 0.18.122
Picks up the published customPens/currentStrokeOptions/resetCustomPen
type fix (previously any) and the ObsidianPenStyle/ObsidianPenOptions/
ObsidianResetCustomPenState types now exported from the fork's new
obsidianTypes.ts.
2026-08-12 22:05:58 +02:00
zsviczian fcee1f64ae ViewSceneFileManager carve out 2026-08-12 20:50:06 +02:00
zsviczian bed3b1f26c ImplementedMarkdownImageController 2026-08-12 19:55:13 +02:00
Diego Mateos e6b4b77c98 stencil library formatted with 2 spaces 2026-08-12 13:05:15 +02:00
zsviczian 86e1e67b8d Replace deprecated React.MutableRefObject with RefObject
React 19's types unified MutableRefObject into RefObject (current is
writable on both); MutableRefObject now only exists as a deprecated
alias. Type-only rename across all 9 flagged usages, no behavior change.
2026-08-11 23:06:56 +02:00
zsviczian d736e7018e Extract Excalidraw React root into its own module (RefactorPlan Phase 7)
Moves the excalidrawRootElement() render body verbatim into
src/view/components/ExcalidrawRoot.ts as createExcalidrawRootElement(view,
initdata), a mechanical relocation with no rendering-syntax or behavior
change. Widens the ~30 previously-private ExcalidrawView members the render
tree touches to public, matching the existing pattern for packages/plugin/
excalidrawAPI.
2026-08-11 23:04:17 +02:00
zsviczian 6ef6fb8aa8 2.27.0-beta.1, 0.18.121, stencil library formatted json, color picker top picks, 2026-08-11 20:34:19 +02:00
zsviczian 8fb91655c7 updated AGENTS.md and CONTRIBUTING.md based on Refactor learnings 2026-08-10 11:47:41 +02:00
zsviczian 4b6d8e3a3c Merge pull request #2880 from zsviczian/fix-refactor-issues
2.27.0-beta.0
2026-08-10 08:21:51 +02:00
zsviczian 6362b7d162 2.27.0-beta.0 2026-08-10 08:18:05 +02:00
zsviczian 19a694260d Merge pull request #2878 from zsviczian/fix-refactor-issues
0.18.120, moved to React 19, fixed mermaid text to diagram history po…
2026-08-09 22:26:11 +02:00
zsviczian dbbc7b3f48 0.18.120, moved to React 19, fixed mermaid text to diagram history popout menu 2026-08-09 22:25:25 +02:00
zsviczian 5108dd3397 Merge pull request #2877 from zsviczian/migrate-to-esm-build
Migrate to esm build
2026-08-09 21:23:24 +02:00
zsviczian 133ff8219b 0.18.119 2026-08-09 21:17:22 +02:00
zsviczian 164a37fd88 build: consume Excalidraw ESM runtime 2026-08-09 21:05:16 +02:00
zsviczian 88e7b47c43 Merge pull request #2876 from zsviczian/reduce-size
Refactoring: main.js size reduction
2026-08-09 17:30:15 +02:00
zsviczian 1616a72344 perf: replace opentype.js font metric parsing 2026-08-09 17:27:30 +02:00
zsviczian 47b853b3b3 build: compress per-window React runtime 2026-08-09 15:49:39 +02:00
zsviczian 2da017b5d3 refactor: use Obsidian YAML APIs 2026-08-09 15:43:37 +02:00
zsviczian 39964d4d70 build: use inflate-only pako runtime 2026-08-09 15:27:34 +02:00
zsviczian 04869e821f Merge pull request #2875 from zsviczian/refactor-excalidrawView-1
Refactor: ExcalidrawView
2026-08-09 14:54:40 +02:00
zsviczian b35fea7eb7 refactor: extract Excalidraw extension renderer 2026-08-09 14:15:27 +02:00
zsviczian 3ceed630b7 refactor: remove obsolete drawio integration 2026-08-09 13:21:42 +02:00
zsviczian ee223fa239 refactor: extract view link navigation manager 2026-08-09 12:50:38 +02:00
zsviczian f1e089930b refactor: extract view fullscreen manager 2026-08-09 12:17:21 +02:00
zsviczian da9dd0fa0b removed commented out old code and debug lines 2026-08-09 11:54:31 +02:00
zsviczian 04f38a6455 refactor: extract view export manager 2026-08-09 11:24:56 +02:00
zsviczian 6976d0969c Merge pull request #2874 from zsviczian/refactor-excalidarw-batch-2
Refactor: move supporting logic out of main.ts into dedicated managers
2026-08-09 10:58:14 +02:00
zsviczian b196ac3de6 refactor: remove dead plugin lifecycle code 2026-08-09 10:56:34 +02:00
zsviczian 776b32216d refactor: extract startup timer 2026-08-09 10:46:18 +02:00
zsviczian 5843e88e6f refactor: extract font manager 2026-08-09 10:29:01 +02:00
zsviczian e0c4eecef4 refactor: extract footer safe area manager 2026-08-09 10:16:39 +02:00
zsviczian fd9090562e updated nanoid to patched version 2026-08-09 09:55:29 +02:00
zsviczian 1a78992ef1 refactor: extract settings management 2026-08-09 09:55:01 +02:00
zsviczian 703355f036 Merge pull request #2873 from zsviczian/refactor-excalidraw
Refactoring: Remove duplicate functions
2026-08-09 08:20:03 +02:00
zsviczian 371fa7a254 removing duplicate functions 2026-08-08 22:09:23 +02:00
zsviczian 00a1bed763 de-duplicated getFontDataURL, svgToBase64, and cropCanvas 2026-08-08 21:45:19 +02:00
zsviczian ff2c8536ce PR #2872 2026-08-08 20:24:05 +02:00
zsviczian eee975c44d refactor: consolidate text link and binary helpers 2026-08-08 20:04:06 +02:00
zsviczian 150f5ccbea Merge pull request #2872 from verryp/fix/text-elements-null-crash
fix: guard null match when .excalidraw.md has no Text Elements heading
2026-08-08 19:37:34 +02:00
verryantopaulus 4f5d913004 fix: simplify null fallback per review suggestion
Per @zsviczian's suggestion on #2872 — collapse the two-step
normalMatch/fallbackMatch into a single optional-chained expression.
Same behavior, less code.
2026-08-09 00:36:02 +07:00
verryantopaulus 64be1aee1e fix: fall through instead of early-return when Text Elements heading missing
Per @zsviczian's review on #2872: an early return skips parsing
"## Element Links" and "## Embedded Files", which may still be present
even when "## Text Elements" itself is missing or was deleted (e.g. a
file with embeddable elements whose link/file sections survived but
the Text Elements heading did not).

Instead of returning early, treat the missing heading as matching zero
characters and fall through to the existing parsing below — the same
codepath that already runs for a file with an empty "## Text Elements"
section. Element Links, Embedded Files, and any block-ref text are
still parsed normally; only the (non-existent) text-element block-refs
are skipped, which is correct since there's nothing there to parse.
2026-08-09 00:19:44 +07:00
verryantopaulus acf7b8d642 fix: guard null match when .excalidraw.md has no Text Elements heading
A valid .excalidraw.md file (correct frontmatter, "# Excalidraw Data"
header, valid "## Drawing" JSON) with no "## Text Elements" heading
anywhere in the body crashed with:

  Cannot read properties of null (reading '0')

loadData() finds "# Excalidraw Data" via RE_EXCALIDRAWDATA_NOSECTION_OK,
so `position` is not -1 and execution moves past the earlier
`position === -1` guard. It then searches for a "## Text Elements"
heading specifically; when that heading doesn't exist at all, both
`normalMatch` and the fallback `data.match(...)` return null, and the
unguarded `data.match(...)[0]` on the null fallback throws.

The plugin's own writer (generateMDBase) always emits the heading
unconditionally, so files it creates itself never hit this path — it
only surfaces for hand-authored or externally-generated .excalidraw.md
files that reasonably omit an empty section.

Treats "no Text Elements heading found" as "zero text elements" and
returns gracefully, mirroring the existing guard a few lines above for
the same underlying condition, instead of throwing.

Fixes #2871
2026-08-09 00:08:02 +07:00
zsviczian 95d89f2fed refactor: consolidate duplicate utility helpers 2026-08-08 11:17:32 +02:00
zsviczian c86db2152e refactor: retire legacy AI settings compatibility 2026-08-08 11:03:45 +02:00
zsviczian 7caf768b8f 2.26.4 2026-08-05 21:51:46 +02:00
zsviczian b295723780 fixed markdown image presistance 2026-08-05 21:35:16 +02:00
zsviczian 40e747c3bd 2.26.3 2026-08-04 19:02:32 +02:00
zsviczian dd06b07a12 updated to 0.18.117 2026-08-04 18:11:06 +02:00
zsviczian b4df1d8e5b Detect Markdown-image deletion via onIncrement instead of guessing trigger
Deleting the last local Markdown image via the Excalidraw properties
panel's trash button skipped the keep-or-delete-file prompt, because
detection only watched specific triggers: the Backspace/Delete/Cut keys
and a data-testid selector that only matches the context-menu delete
item, not the panel button (which the fork never gives a testid).

Replace that trigger-guessing with Excalidraw's onIncrement API: durable
store increments expose exactly which elements were soft-deleted
(isDeleted flipped true) in that action, regardless of what triggered
it. This uniformly covers keyboard, Cut, context menu, the panel
button, undo/redo, and scripts, and removes the old capture/timer/
candidate-matching scaffolding entirely.
2026-08-04 15:43:05 +02:00
zsviczian 614f0fbab0 Fix Markdown image edits lost when switching between images
Editing one Markdown image and immediately selecting or opening another
could drop the first image's edits, both in memory and on disk. Two
distinct races caused this: switchElement()'s force-persist could
silently no-op if a concurrent save claimed the saving semaphore between
the idle-wait and the save() call, and openMarkdownImageEditor()'s
handoff to a brand new controller disposed the previous one via a
fire-and-forget flush instead of awaiting it. Both paths now share a
single flushCurrentElement() helper and persistOwnerAfterEditorFlush()
retries instead of silently giving up.
2026-08-04 14:13:50 +02:00
zsviczian 07ff3b7e96 2.26.2 2026-08-03 22:32:35 +02:00
zsviczian 75940d6173 2.26.1 2026-08-03 22:08:26 +02:00
zsviczian 8ba60c43e8 2.26.0 2026-08-03 22:06:28 +02:00
zsviczian ae73115e9c fixed code scanner findings 2026-08-03 21:59:12 +02:00
zsviczian 723c7c5de2 fixed css editor looses focus on mobile 2026-08-03 21:36:24 +02:00
zsviczian 680ae101cb align markdown SVG image rendering on iOS, android and desktop 2026-08-03 20:54:39 +02:00
zsviczian 82578a0a58 fix Markdown Image sidepanel on mobiles 2026-08-03 18:02:29 +02:00
zsviczian 8c2da6a1c3 markdown toolbar visible in sidepanel on Obsidian Mobile 2026-08-03 15:22:45 +02:00
zsviczian b09fa3b1ed 2.26.0-rc.4 . settings persist immediately (Obsidian 1.13.x compatibility issue), MarkdownImage editor did not open on Mobiles. 2026-08-03 12:53:50 +02:00
zsviczian 6001ef3f1f Merge pull request #2863 from FreeCutter/master
Updated script VoronoiDiagramGenerator
2026-08-03 09:43:46 +02:00
zsviczian 40e204c2d9 2.26.0-rc.3 - fixed auto activation of markdown editor 2026-08-03 09:16:46 +02:00
zsviczian e6c07bb615 updated messages for 2.26 2026-08-03 08:45:35 +02:00
FreeCutter 7aa3f044cf Enhance Voronoi Diagram Generator UI and functionality
Updated UI settings modal for Voronoi Diagram Generator, improved layout and added info button functionality.
2026-08-03 07:31:38 +02:00
FreeCutter b901bfbcac Update mtime for VoronoiDiagramGenerator files 2026-08-03 07:26:30 +02:00
zsviczian 642ba63a9f 2.26.0-rc.2 2026-08-02 19:20:35 +02:00
zsviczian c0ab59c3aa pre-release 2026-08-02 19:20:06 +02:00
zsviczian fd62c158db Fix sections in commented sections. 2026-08-02 19:13:03 +02:00
zsviczian cabe90927d 2.26.0-rc.1 2026-08-02 17:18:57 +02:00
zsviczian 3220889563 Fixed Markdown Image large file editing issue - file jumping around 2026-08-02 17:03:03 +02:00
zsviczian 907e2267d5 FileAndFolderSelectorModal 2026-08-02 16:43:45 +02:00
zsviczian 730705efe6 2.26.0-beta.8 2026-08-02 11:50:14 +02:00
zsviczian f8338b6d46 markdown as image drop creates a markdown image with custom data 2026-08-02 09:43:48 +02:00
zsviczian 4c1ffcb104 Fixed the teardown race 2026-08-01 22:34:58 +02:00
zsviczian 52c54a999e removed :has 2026-08-01 22:09:53 +02:00
zsviczian 1cedf7a7a9 2.26.0-beta.7, color picer, copy SVG 2026-08-01 21:54:23 +02:00
zsviczian 341edde683 Merge pull request #2861 from iwanhoogendoorn/comic-strip-director-v2.0.0
Comic Strip Director v2.0.0 — Excalidraw 2.26.0 compatibility, mini-map, page export
2026-08-01 21:49:08 +02:00
zsviczian d64ae78795 font picker 2026-08-01 21:28:20 +02:00
Iwan Hoogendoorn b45457437f Comic Strip Director v2.0.0 — Excalidraw 2.26.0 compatibility, mini-map, export/copy 2026-08-01 19:20:53 +02:00
zsviczian ee66e134d3 2.26.0-beta.6 2026-08-01 18:06:38 +02:00
zsviczian 2fadcd8533 Merge pull request #2851 from WolfExplode/master 2026-08-01 18:05:19 +02:00
zsviczian 693e990aef stencil library in folder, 0.18.116 2026-08-01 17:59:33 +02:00
zsviczian dbb75479f3 2.26.0-beta.5, 0.18.115 2026-08-01 14:01:54 +02:00
zsviczian b40f72ba13 fixed markdown image sidepanel activation issue 2026-08-01 13:41:21 +02:00
zsviczian 30d48562c4 allow mermaid, dataview and other awaited code blocks in Markdown Images 2026-08-01 13:18:33 +02:00
zsviczian 8b2080d3b9 fixed copy/paste of markdown images. Normal copy paste duplicates image with same image ID. Duplicate Image in the sidepanel creates a new image ID and duplicates the markdown content 2026-08-01 12:59:54 +02:00
zsviczian fce2bc11ff support drag animated gif from outside Obsidian 2026-08-01 08:46:34 +02:00
zsviczian 906db1b80a updated index new Voronoi Diagram Generator referenc 2026-08-01 08:15:06 +02:00
zsviczian 4a11d9bef6 VoronoiDiagramGenerator added to script library 2026-08-01 08:12:41 +02:00
zsviczian 60c1ade6b5 Merge pull request #2845 from FreeCutter/master
Add Voronoi Diagram Generator script
2026-08-01 08:04:36 +02:00
zsviczian 3f6bfd7c4f docs: document image-reference padding 2026-08-01 07:53:16 +02:00
zsviczian 9b730af586 Merge pull request #2850 with image-reference padding support 2026-08-01 07:50:14 +02:00
zsviczian 88c02b6017 possible harvestStyle fix for #2855 2026-08-01 07:31:01 +02:00
zsviczian c7f5de2ee1 fix custom pen persistence 2026-08-01 07:09:17 +02:00
zsviczian 99edf67e98 fixed button layout 2026-07-31 16:02:32 +02:00
zsviczian 12adfa4274 update package lock 2026-07-31 15:50:29 +02:00
zsviczian b4a3dea13e 2.26.0-beta.4, 0.18.114 2026-07-31 15:48:59 +02:00
zsviczian c7bd1d6fe3 fixed sidepanel as popout window 2026-07-31 15:42:40 +02:00
zsviczian 35393dd997 supports excalidraw markdown, duplicate markdown image 2026-07-31 15:26:20 +02:00
zsviczian 339ef82ea0 2.26.0-beta.3 2026-07-30 22:38:40 +02:00
zsviczian 24980ec262 fix hotkey override, fix remaining code scanner issues 2026-07-30 20:51:48 +02:00
zsviczian 06d95d0c1b attempt at satisfying getSettingDefinitions 2026-07-30 20:28:31 +02:00
zsviczian 353fd4b8dc fix createEl("style") fatal codescanner error 2026-07-30 19:52:23 +02:00
zsviczian a16bba9611 markdown image fixes 2026-07-30 19:31:18 +02:00
zsviczian 64d4662a0b fixed createElement issues 2026-07-30 19:14:03 +02:00
zsviczian 7a53788902 createEl fix experiment 2 2026-07-30 18:38:41 +02:00
zsviczian 6fe5d9c23d first batch create el replacements 2026-07-30 17:54:05 +02:00
zsviczian fad108c2d7 resolved use of any in AIUtils.ts 2026-07-30 17:33:49 +02:00
zsviczian 5ea712ec41 default hotkey assignement fix 2026-07-30 14:49:25 +02:00
zsviczian 94d69e8628 test fix createEl 2026-07-30 12:47:17 +02:00
zsviczian 07dfbc303e fixing Obsidian code scanner console log noise 2026-07-30 10:28:38 +02:00
zsviczian 26f5a17295 2.26.0-beta.2 - removed theme setting from MarkdownImage because it was not working, and did not make sense. 2026-07-30 09:21:37 +02:00
zsviczian a4f0756fa6 Merge pull request #2853 from zsviczian/markdown-images
(feat) Markdown image support
2026-07-29 22:27:23 +02:00
WXP d609d0af29 fix: reuse existing vault files when importing non-image media
Extend the external-file import conflict prompt to videos and other non-image media.
When a matching vault file is resolved by name/path, users can now reuse it, overwrite it, or import a renamed copy before choosing how to insert it. Image behavior remains unchanged.
2026-07-25 19:51:53 -04:00
Evgene Kopylov 878fb5bcf7 docs: добавь ,padding=N в release notes 2026-07-24 12:02:39 +02:00
Evgene Kopylov c542d7661f ... 2026-07-24 10:50:52 +02:00
Evgene Kopylov 97f05e1629 feat(area): добавь аргумент ,N в area= ссылке 2026-07-22 11:48:46 +02:00
FreeCutter 31d5d86af0 Add link to image example file 2026-07-18 09:04:42 +02:00
FreeCutter 95dc44e56b Add files via upload 2026-07-18 08:58:00 +02:00
FreeCutter 27f2765e7a Add Voronoi Generator script description 2026-07-18 08:45:43 +02:00
FreeCutter 4e5399283c Add files via upload
Add Voronoi Generator script and preview image
2026-07-18 08:00:04 +02:00
188 changed files with 39814 additions and 17944 deletions

No files matched your search

+159 -52
View File
@@ -37,24 +37,16 @@ Use https://github.com/obsidian-typings/obsidian-typings as a reference when dea
Treat build code and runtime code as one system.
## Project overview
## Project Overview And Tooling
- 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.
- Runtime entry point: `src/core/main.ts`, compiled by `rollup.config.mjs` to `dist/main.js`.
- Required release artifacts: `main.js`, `manifest.json`, and `styles.css`.
- Node.js: use Node 22 or newer. Check `node --version` before diagnosing build-tool failures; mixed Node/Corepack installations can produce misleading errors.
- Package manager: npm. Use `npm install` and the scripts in this repository's `package.json`.
- Runtime bundler: Rollup. Do not replace this build with a sample-plugin esbuild setup; Rollup also assembles compressed runtime payloads and merged CSS.
- Primary lint command: `npm run code`. `npm run lint` is broader and may expose unrelated repository backlog.
- Types: Obsidian type definitions plus conservative declarations for intentionally used unpublished APIs.
## Security, privacy, and compliance
@@ -77,12 +69,35 @@ Follow Obsidian's **Developer Policies** and **Plugin Guidelines**. In particula
- Use arrow notation for navigation: **Settings → Community plugins**.
- Keep in-app strings short, consistent, and free of jargon.
## DOM Styling And Visibility
- Prefer Obsidian's established classes such as `mod-warning` before adding plugin-specific CSS. Consult the Obsidian CSS variables and component conventions when styling settings or dialogs.
- Never use `document.createElement()`, `Document.createElement()`, or `Document.createDocumentFragment()`. Always use Obsidian's `createEl()`, `createDiv()`, `createSpan()`, `createSvg()`, and `createFragment()` helpers. When an element must deliberately belong to a specific document that Obsidian's helpers cannot target, such as a canvas used for drawing or an element inside an iframe, use the `deliberateCreateElement` function injected by `rollup.config.mjs` and declare it in the consuming module, for example `declare const deliberateCreateElement: (document: Document, tagName: string) => HTMLElement;`.
- Use semantic interactive elements and Obsidian's event helpers. Link-like navigation should use a real anchor, not a button merely styled as a link; use `onClickEvent` when applying custom navigation behavior. Validate touch interactions on a physical mobile device because desktop mobile emulation proves layout, not native touch activation.
- When a control already has a styled tooltip, do not also set an HTML `title` attribute. Keep its accessible name in `aria-label`; `title` produces a second native Chromium/Electron tooltip and must not replace accessible labeling.
- Do not write an element's `style` attribute directly. Use `setStyle` and `removeStyle` from `src/utils/styleUtils.ts` when a dynamic inline style is genuinely necessary.
- Use the existing visibility helpers instead of the native `hidden` property or attribute, which is not reliable in Obsidian's styled UI. Choose `hideElement`/`showElement` or `setComponentVisibility` from `src/utils/styleUtils.ts`, or `setElementHidden`/`setElementDisplay` from `src/utils/htmlUtils.ts` when a boolean/display-oriented API is clearer.
- Search `src/utils/styleUtils.ts` and `src/utils/htmlUtils.ts` before introducing new DOM styling helpers or display classes.
- Run Obsidian CodeScanner after CSS changes. Preserve compatibility with the declared minimum Obsidian version and prefer a widely supported property when it provides the same result; for example, a basic underline is preferable to optional underline-thickness/offset styling.
- For a known vault path, use the most specific synchronous lookup: `app.vault.getFolderByPath()` for folders and `app.vault.getFileByPath()` for files. Use `getAbstractFileByPath()` only when either type is intentionally accepted, and avoid adapter-level existence checks when the Vault API already models the target.
- Radix content in the customized Excalidraw package may be rendered through `ObsidianRadixPortal` directly under the owning document's body. A body portal escapes component ancestor selectors and modal stacking contexts. When a trigger is visible but its menu or popover is not, first inspect whether the content mounted behind a modal or lost ancestor-scoped styles. Use a class on the portaled content, a portal-safe selector, and an explicit stacking level when required; validate main-window, popout, click-outside, and Escape behavior.
## 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.
- For temporary performance diagnostics, use a unique searchable prefix and
emit one copyable string per event rather than logging expandable objects.
Keep timing-only callbacks and state isolated from production behavior.
- Distinguish synchronous API duration, queue completion, browser-task yields,
animation-frame callbacks, and actual paint; none is a substitute for the
others when explaining perceived latency.
- Temporary diagnostics are not product observability. Do not log vault
contents, and include filenames only when the maintainer explicitly needs
per-file attribution. Remove the diagnostics before commit and search both
`src/` and the built `dist/main.js` for their prefix.
## Coding conventions
@@ -99,6 +114,7 @@ Follow Obsidian's **Developer Policies** and **Plugin Guidelines**. In particula
- 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.
- Treat a physical phone or tablet as a separate validation environment for touch targets, synthesized clicks, scrolling gestures, focus, and the mobile WebView. Desktop mobile emulation is useful for responsive layout checks but is not a substitute for real touch testing.
## Agent do/don't
@@ -182,20 +198,97 @@ This project uses a non-trivial Rollup build because startup time, popout-window
The build embeds or injects runtime code for:
- React and ReactDOM
- a JSX runtime shim for compatibility
- the customized `@zsviczian/excalidraw` package
- the customized `@zsviczian/excalidraw` Obsidian artifact built from Excalidraw's ESM source graph
- `MathjaxToSVG`
- `lz-string`
- selected compressed locale payloads
These payloads are executed or unpacked at runtime. This is intentional.
React, ReactDOM, and the official JSX runtime entry points are normal modules in the main Rollup bundle, not separately compressed or evaluated payloads. React must remain external to the separately built Excalidraw artifact: the plugin supplies its one bundled private React runtime to the single evaluated Excalidraw runtime used by every view. Mermaid is also intentionally absent from the artifact and is loaded lazily at runtime through Excalidraw Extras. All other required Excalidraw assets are expected to work offline except the deliberately lazy CJK font subsets.
### Two-Repository Excalidraw Workflow
The customized component lives in the sibling `zsviczian/excalidraw` repository. When both repositories are available locally, it is normally at `../excalidraw`; verify the actual workspace path and branch instead of assuming it.
- The Excalidraw repository uses Yarn and builds the consumer-specific payload from `packages/excalidraw` with `yarn build:obsidian`.
- That build emits four files under `packages/excalidraw/dist/obsidian/`: production and development JavaScript plus production and development CSS.
- This plugin consumes the same four paths from `node_modules/@zsviczian/excalidraw/dist/obsidian/` in `rollup.config.mjs`.
- For a temporary unpublished integration test, build the sibling package and copy only those four generated files into the installed package under `node_modules`. Do not change `package.json` or `package-lock.json` to a local `file:` dependency merely for this handoff. A later `npm install` restores the published package.
- For the durable handoff, publish a new `@zsviczian/excalidraw` version, update this repository's dependency, run `npm install`, and rebuild the plugin.
- A local artifact copy proves integration only. If plugin source consumes a
new fork API, do not describe the plugin handoff as commit- or release-ready
until the published package is installed and the exact dependency and
lockfile contain that API, unless the maintainer explicitly requests a
paired intermediate commit.
- Never hand-edit or commit generated `dist/`, `lib/`, or `node_modules` artifacts as source fixes.
- Treat the repositories as separate Git histories. Check branch, status, diff, build, and commit state independently in each one, and do not commit or publish unless explicitly requested.
### Typed Excalidraw Host Boundary
The customized Excalidraw runtime receives Obsidian capabilities through typed host adapters. Treat this as the only supported plugin-to-fork dependency-inversion boundary.
- Do not expose or recover the plugin through component props, `appState`, `window`, `globalThis`, `app.plugins`, or fork-side `hostPlugin` variables.
- Keep adapters narrow and semantic. They may expose operations such as reading a current limit or running a named action, but never the plugin instance, the complete settings object, or an active view.
- Capabilities used by `@excalidraw/common` or lower layers belong in `ObsidianCommonHostAdapter`. Capabilities used only by the Excalidraw package belong in `ObsidianExcalidrawHostAdapter`.
- View-specific state must remain instance-scoped. Do not put an active view into either window-runtime adapter; expose a semantic plugin-side action when the component genuinely requires such behavior.
- `PackageManager` registers both adapters once with the shared Excalidraw runtime. React components and individual `ExcalidrawView` instances must not configure or dispose them.
- Adapter methods must read live plugin state instead of capturing settings snapshots during registration.
- `PackageManager` owns the complete lifetime: dispose registrations before releasing the shared runtime, make cleanup idempotent, and roll back all registrations if configuring either adapter fails.
A closure that references the plugin is not itself a memory leak. The risk is allowing a registry, listener, or evaluated runtime retaining that closure to outlive its owning `PackageManager` registration.
The fork is the source of truth for host-adapter contracts and protocol constants. Import or derive types from its published declarations where possible. If the evaluated `window.ExcalidrawLib` surface requires an ambient declaration, derive that declaration from the fork types instead of restating property lists or unions locally.
### Coordinated Internal Protocol And Release
The host adapters are an internal protocol between this plugin and its exact `@zsviczian/excalidraw` dependency. They are not a compatibility surface between arbitrary historical plugin and fork versions.
- A breaking adapter change must increment the relevant protocol version and update the fork implementation, fork tests, plugin adapter, and plugin ambient runtime declaration in one coordinated checkpoint.
- Fail fast during package loading when a required boundary is absent or incompatible. Do not retain global-plugin discovery or legacy bridge fallbacks solely to support mismatched plugin and fork versions.
- Preserve the general backwards-compatibility requirements for persisted settings, serialized scenes, scripts, commands, and public APIs; this exception applies only to the paired internal host protocol.
- For a maintainer-coordinated release, build and verify the fork package first, publish it, update the plugin's exact dependency, run `npm install`, and rebuild and smoke-test against the published artifact before committing the plugin handoff.
### Popout Window Support
- `src/core/managers/PackageManager.ts` manages window-scoped React/ReactDOM/Excalidraw packages.
- This is necessary because the plugin must work in Obsidian/Electron popout windows.
- Do not replace this with a naive global singleton approach.
- `src/core/managers/PackageManager.ts` combines the plugin bundle's one private React/ReactDOM runtime with one evaluated Excalidraw artifact in the main application realm and leases that package to every view.
- A lease retains the view's actual acquisition window for migration and persistence decisions; package evaluation ownership must never substitute for that identity.
- Popouts receive only a temporary `window.ExcalidrawLib` compatibility alias. Remove it after the final lease for that window while keeping the shared runtime alive until plugin unload.
- React and ReactDOM are bundled normally from their official npm entry points and kept in plugin/package lexical scope. Do not restore a compressed/evaluated React bootstrap or assign React or ReactDOM to `window`; only the documented `window.ExcalidrawLib` compatibility surface remains global.
- Every Excalidraw root must receive its stable owning document. Rendering, DOM ownership, events, observers, portals, realm constructors, fonts, timers, and React roots must derive from the owning view document/window where appropriate; do not turn the shared runtime into a mutable "current window" singleton.
- Treat `HTMLElement.onWindowMigrated()` as a destructive runtime boundary. Its callback runs after Obsidian has moved the view container to another document, while the existing React root and Excalidraw API still belong to the source window runtime.
- For a dirty migration, synchronously capture every API-owned value needed for persistence and unmount the source React root **before the first `await`**. Do not move synchronization, compression, Vault/native file access, `closeLeafView()`, or another asynchronous step ahead of that unmount. On macOS/Electron, doing so reproducibly allowed the source popout window to be destroyed before `root.unmount()`, freezing Obsidian and disconnecting DevTools.
- Cancel deferred initialization and scene-file loaders before migration unmount, and require delayed loader callbacks to match the exact API instance and file path that started them. Component-owned image decoding can still outlive a synchronous `addFiles()` call, so the Excalidraw runtime must also stop after an awaited decode when its editor has unmounted; never delay migration unmount to wait for image work.
- The migration callback owns the single persistence flush. Generic `onClose()` and `onUnloadFile()` safeguards must not start duplicate migration saves, and the retired source view must reject blur-save side effects and vault-modify synchronization after its API is unmounted.
- A popout-to-main migration may serialize from a synchronously captured drawing snapshot, but the replacement main-window view must perform the final drawing-file write. Never initiate the final Vault/native write from the source popout callback.
### Main-Window Persistent Storage
Window ownership for rendering is not the same as ownership for persistent plugin data.
- Existing plugin-level IndexedDB and local-storage data belongs to Obsidian's main application window and must remain shared across normal views and popouts.
- Do not change persistent storage to `view.ownerWindow`, create one database per popout, or infer a storage migration from a rendering bug unless the task explicitly requires that behavior.
- Diagnose persistence and presentation separately. For example, a visible history button conditioned on loaded records proves the load path worked even when a portaled history menu is hidden.
- If a new feature is intentionally view-local, document that exception and test window migration and popout teardown explicitly.
### IndexedDB And Cache Schema Changes
- Classify every affected store as disposable derived cache or durable user
data before changing its schema. Image previews may be rebuilt; drawing
backups must not be deleted as cache migration cleanup.
- Create current stores and remove obsolete disposable stores in one IndexedDB
version-change transaction. Prefer lazy cache rebuilding over deserializing
and rewriting a large legacy cache during startup.
- If opening or upgrading fails, close and clear unusable database handles and
readiness promises. A closed legacy connection must never make the cache
report itself as ready.
- Use browser APIs such as `Blob` and `FileReader` for in-memory payload
conversion so the path remains mobile-safe. Vault file access must still use
Obsidian's Vault API.
- Validate cold upgrade, preservation of durable stores, first cold rebuild,
warm reopen, clear, timed purge, plugin reload, and one mobile run. Persistent
plugin data remains owned by the main application window; popouts need a
usage smoke test, not a separate database.
### MathJax Subproject
@@ -235,6 +328,16 @@ These payloads are executed or unpacked at runtime. This is intentional.
- Preserve existing abstractions unless the task clearly requires a redesign.
- Avoid broad refactors unless there is strong evidence they are necessary.
### Incremental Refactoring Protocol
- Use `RefactorPlan.md` as the living architectural record. Update the progress table and append an action-log entry after each completed or reverted checkpoint.
- Make one independently testable behavior change or mechanical extraction at a time. Prefer moving code intact before simplifying it.
- Preserve timers, observers, semaphores, lifecycle ordering, and unpublished-API workarounds unless their purpose has been traced and an equivalent behavior has been verified across affected platforms.
- Do not convert `ExcalidrawView` wholesale into React. It must remain an Obsidian `TextFileView`; React is the child rendering runtime. Extract cohesive view-scoped controllers and components while retaining compatibility delegates on the view.
- For duplicate utilities, compare every implementation and caller before consolidation. Marginal behavior differences must be shown unused or deliberately preserved.
- Do not derive a runtime settings sanitizer from the TypeScript interface. Interfaces do not exist at runtime, settings evolve frequently, and unknown keys may belong to a newer or companion version. Remove obsolete keys only through an explicit, reviewed migration or retirement decision.
- End every checkpoint with risk-based manual test recommendations: identify the highest-probability failure, the affected workflow, and whether main-window, popout, desktop operating systems, and mobile need separate coverage.
## Naming And Placement Conventions
Treat the following as the target convention for all new code and for any future naming-cleanup pass. The current repository contains legacy exceptions. Do not rename files opportunistically inside behavior changes; do naming cleanup in a dedicated, compatibility-aware refactor.
@@ -292,6 +395,7 @@ Backwards compatibility is a strong requirement in this repository.
- If a rename reaches beyond a purely internal import graph, prefer temporary aliases, re-exports, or compatibility wrappers during migration.
- If settings shape or stored values change, update defaults, settings UI, load/save flow, and migration logic together.
- Assume user scripts, vault content, templates, embeds, release-note references, and community documentation may depend on existing names and behavior.
- The paired plugin-to-fork host protocol is the deliberate exception described above: coordinate and version breaking contract changes instead of preserving fallbacks for mismatched package versions.
## User-Facing Change Workflow
@@ -306,10 +410,10 @@ Backwards compatibility is a strong requirement in this repository.
## React Runtime Import Model
React usage in this repository is special because React and ReactDOM are package-managed per window to support Obsidian popout windows and runtime package injection.
React usage in this repository is special because one normally bundled private React/ReactDOM runtime is package-managed across main-window and popout roots.
- It is fine to import React for types, component definitions, JSX compilation, and nearby established patterns.
- Do not assume a single global React/ReactDOM runtime is safe for rendering, root creation, or view-owned objects.
- Import React, ReactDOM, and JSX runtime entry points normally. Rollup must bundle them into the main plugin but keep them external in the library build and in the separately built Excalidraw artifact.
- The shared runtime is safe only because each root and Excalidraw instance receives stable owner-document state. Never recover view ownership from the runtime's lexical main window.
- For view-bound rendering and roots, follow `src/view/ExcalidrawView.ts` and use `view.packages.react` and `view.packages.reactDOM` through the package-manager flow.
- For view-owned React objects such as refs or runtime-created elements, follow neighboring patterns such as `src/view/components/menu/ToolsPanel.tsx` and `src/view/components/CustomEmbeddable.tsx`, which intentionally use the package-managed React instance.
- Do not introduce a new direct `ReactDOM.createRoot()` path outside the package-manager model unless you have verified popout-window safety.
@@ -325,7 +429,7 @@ Use this routing guide before editing.
- Commands and command registration: `src/core/managers/CommandManager.ts`
- Vault or workspace event handling: `src/core/managers/EventManager.ts` and `src/core/managers/FileManager.ts`
- Markdown rendering or markdown embeds: `src/core/managers/MarkdownPostProcessor.ts`
- Package/runtime loading across windows: `src/core/managers/PackageManager.ts`
- Shared package/runtime loading and per-window leases: `src/core/managers/PackageManager.ts`
- Styling setup and style injection: `src/core/managers/StylesManager.ts`, `styles.css`, `src/utils/dynamicStyling.ts`
- Main canvas/editor behavior: `src/view/ExcalidrawView.ts`
- Sidepanel behavior: `src/view/sidepanel/`
@@ -348,6 +452,21 @@ If a task changes persisted settings, inspect all relevant pieces.
Settings changes are often incomplete if only one of these surfaces is updated.
## Declarative Settings And Persistence
The plugin supports Obsidian 1.8.7 while optionally using the declarative settings API introduced in Obsidian 1.13. Preserve both compatibility paths.
- Do not bump the `obsidian` dependency or `minAppVersion` merely to consume declarative settings. Gate the runtime path with `requireApiVersion("1.13.0")` and keep conservative placeholder declarations for the newer API.
- `getSettingDefinitions()` must return the complete tree only when the runtime supports declarative settings and the restart-applied compatibility preference enables them. Returning an empty array is the intentional fallback to the legacy renderer.
- The settings page model is the canonical hierarchy for declarative rendering, legacy single-page rendering, descriptions, search aliases, breadcrumbs, cross-page navigation, and Markdown export. Do not create separate setting lists or behavior implementations for the two layouts.
- Controls that change each other's options, visibility, or disabled state must share one integrated component or one shared configurator. Apply dependent state during initial render as well as after changes. Scope captured control references to one rendered definition tree; generating an export-only tree must never replace bindings used by the mounted UI.
- On Obsidian 1.13+, do not call `display()` to refresh a declarative page. Update the mounted controls through their binding/configurator path or ask Obsidian to rebuild definitions only when the definition tree itself changed.
- Declarative page navigation uses guarded unpublished Obsidian APIs. Prefer `openPagePath`; retain the checked `findTabById`/`navigateToPage` fallback, derive localized paths from the canonical page model, and degrade to non-navigating text when the API is unavailable.
- Route all settings writes through `PluginSettingsManager` and its serialized stable-snapshot writer. Save when values change; never make plugin shutdown or settings-tab closure the primary persistence boundary because Obsidian may not await asynchronous writes during termination. Avoid competing direct `saveData()` calls.
- Missing and invalid `data.json` states are different. A first installation with no file is valid; a missing file with a recovery snapshot requires a restore-or-defaults choice; invalid startup data should restore a valid device-local snapshot or ask the user how to proceed; invalid data arriving during a running session must be rejected and repaired from the valid in-memory settings.
- The last-known-good recovery snapshot is durable, device-local IndexedDB data owned by the main application window. Refresh it after every valid load or save, do not store large snapshots in `localStorage`, and do not create independent recovery databases for popouts.
- Preserve unknown persisted keys. Do not derive a sanitizer from the TypeScript settings interface or treat unfamiliar keys as corruption.
## Script Engine And Automation Notes
- Excalidraw Automate is a major public surface of this project.
@@ -371,7 +490,7 @@ These areas require extra care:
- `rollup.config.mjs`: payload injection, localization, manifest/versioning, CSS bundling
- `src/core/main.ts`: lifecycle order, settings migration, startup initialization
- `src/view/ExcalidrawView.ts`: very large, stateful, performance-sensitive, and central to user behavior
- `src/core/managers/PackageManager.ts`: cross-window package loading and runtime evaluation
- `src/core/managers/PackageManager.ts`: shared runtime evaluation, host registration, and cross-window lease/alias lifetime
- `src/lang/helpers.ts`: build-token compatibility for compressed locales
- AI/provider settings and persisted credentials handling
- PDF/export code paths and Electron/Obsidian-specific integrations
@@ -403,6 +522,7 @@ npm run doc
Validation guidance:
- After every code modification, run `npm run build` before starting the next checkpoint. Treat new build errors or warnings relative to the recorded baseline as blockers and report relevant existing warnings accurately.
- Treat `eslint.config.cjs` as the quality bar for all new and modified code.
- Use lint results to avoid introducing new violations in touched files, even if repo-wide lint still fails because of unrelated backlog.
- `npm run code` is useful for visibility, but a failing repo-wide run does not by itself mean your change is invalid if the failures are pre-existing and unrelated.
@@ -410,6 +530,12 @@ Validation guidance:
- Run `npm run lib` if you touch the public/library API surface.
- Run `npm run build:mathjax` or `npm run build:all` if you edit `MathjaxToSVG/`.
- Run `npm run madge` after structural import changes or when touching shared architecture.
- Compare Madge and Rollup circular-dependency results only with their own baselines. Madge enumerates overlapping elementary paths and can include type-only imports, while Rollup reports runtime bundle cycles; their raw counts are not directly comparable.
- When the customized Excalidraw source changes, run its `yarn build:obsidian`, refresh the four local package artifacts, and then run this repository's production and relevant development builds. A plugin build against the old installed artifact does not validate the component change.
- For host-boundary changes, run the fork's focused adapter tests without Obsidian, then validate plugin registration and teardown through cold startup, plugin reload, the main window, a new and restored popout, and window removal. Confirm adapter methods observe settings changed after registration.
- After React/package-loading changes, validate cold startup, plugin reload, the main window, new and restored popouts, and moving a leaf between windows. Confirm that no `window.React` or `window.ReactDOM` global was introduced.
- After Radix/portal changes, validate visibility, positioning, stacking, click-outside, and Escape handling in both the main window and a popout; include mobile when viewport collision behavior can differ.
- Record `dist/main.js` byte size after packaging changes and report remaining headroom under the release limit.
- Prefer targeted diagnostics for the files you touched when repo-wide lint noise obscures signal.
- Prefer `npm run build` plus targeted file diagnostics over raw `tsc --noEmit` as the primary gate. Standalone `tsc` can surface large volumes of dependency-typing noise unrelated to touched files.
- Do not treat `dist/` output edits as source fixes.
@@ -424,7 +550,7 @@ Validation guidance:
- Considering both direct and indirect consumers of the changed code or types
- Reviewing all files that may be impacted by a type, interface, or API change
- Never assume a change is local unless you have verified, by search or analysis, that no other code is affected.
- After making a change, always validate that the build passes and that no new errors or warnings are introduced anywhere in the codebase.
- After making a change, validate the relevant build and compare errors and warnings with the recorded baseline. Touched files must not introduce new diagnostics.
- Prefer minimal, local changes when possible, but never at the expense of breaking global correctness or introducing subtle bugs elsewhere.
- Avoid reformatting large files unless necessary.
- Do not edit generated `dist/` or `lib/` outputs by hand.
@@ -433,26 +559,6 @@ Validation guidance:
- When a change looks odd, search for the constraint that explains it before removing it.
- When in doubt, preserve startup performance, popout support, and existing vault compatibility.
### Additional Guidance for Global Impact
- When changing types, interfaces, or exported APIs, always search for all references and usages across the codebase and update them as needed.
- When tightening types (e.g., replacing `any`), ensure all code that accesses the affected values is type-safe and will continue to work as before.
- If a change introduces new type errors elsewhere, you must fix those errors or revert the change.
- Always run `npm run build` after changes, and do not consider a change complete until the build passes with no new errors.
- If a change could affect runtime behavior, validate by running the plugin in Obsidian if possible.
### MANDATORY: Build Validation After Every Change
**Build validation is not optional and must be run immediately after every code change.**
- After you complete any code modification, you **must** immediately run `npm run build` before proceeding to the next task.
- Do not consider a change complete, correct, or ready to return to the user until `npm run build` passes with no new errors or warnings.
- If the build fails, fix all errors in your code and run `npm run build` again.
- Report all build output (including warnings and circular dependency notices) to the user if relevant to your changes.
- Build validation is not a final polish step—it is part of the core work.
- Treat any new build errors as blockers that must be resolved before considering the task done.
- If a type change or code edit introduces new build failures anywhere in the codebase, those are your responsibility to fix.
### Type Consolidation Follow-through
- Treat user requests like "tiny follow-up" or "do this consolidation" as end-to-end tasks: complete extraction, replace all known duplicates, and remove local leftovers in the same pass.
@@ -541,13 +647,14 @@ Before replacing an `any` type:
### Type Files And Responsibilities
- **`src/types/types.d.ts`**: Ambient module declarations and Obsidian unpublished API types. This is the standard location for extending Obsidian's type system and for global type declarations. Use the existing patterns (interfaces extending `obsidian` module interfaces) consistently.
- **`src/types/excalidrawLib.ts`** (or similar): When creating new type files for project-specific types, place them in `src/types/` and use PascalCase for files that export types or interfaces.
- **`src/types/excalidrawLib.d.ts`**: Ambient declarations for the evaluated `window.ExcalidrawLib` runtime. Derive declarations from published fork types where possible, and keep the file lowerCamelCase in line with grouped type-module naming.
- **Type files in subsystem directories**: Files like `src/shared/ExcalidrawAutomate.ts` may carry substantial type definitions and exports alongside implementation. Do not move these without evaluating the impact on the public API surface.
- **Leverage existing type files**: Consult `src/types/excalidrawLib.ts` for the current Excalidraw type model before adding new Excalidraw-derived types.
- **Leverage existing type files**: Consult `src/types/excalidrawLib.d.ts` and the installed fork declarations for the current Excalidraw type model before adding new Excalidraw-derived types.
### Excalidraw Type Integration
- Do not invent wrapper types for Excalidraw entities. Reference the customized `@zsviczian/excalidraw` types directly.
- Before defining a plugin-local union or interface for a fork concept, search the published fork declarations and import or alias the canonical type. Ambient runtime bridges should reuse those types rather than duplicate their structure.
- Build on existing type extensions in the codebase (e.g., `src/types/types.d.ts` may already extend Excalidraw types).
- When a type depends on Excalidraw internals, document the dependency clearly so future changes to the fork are visible.
- Obsidian unpublished API types often interact with Excalidraw components; model these intersections carefully in `src/types/types.d.ts`.
@@ -602,7 +709,7 @@ In some cases, `@typescript-eslint/no-explicit-any` or `@typescript-eslint/no-un
- **Provider-specific dynamic payloads**: AI providers, image APIs, and other external services return schemas that vary by provider. Normalizing these requires accepting `any` properties or using type assertions on the `item` parameter to access provider-specific fields.
- Example: `(item: Record<string, any>) => item.image?.url || item.image?.b64_json` normalizes images from different providers into a common schema.
- **Mutation-path type casts**: When updating scene elements or bound references, Excalidraw type definitions may return readonly or union types, but the mutation path requires the mutable variant. The assertion is necessary and doesn't bypass a real type mismatch.
- Example: `sceneElements.find(...) as unknown as Mutable<ExcalidrawElement>` during ID migration where the lookup guarantees the mutable variant exists.
@@ -669,4 +776,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.
+101 -9
View File
@@ -1,6 +1,6 @@
# Contributing to Obsidian Excalidraw Plugin
First off, thank you for considering contributing to the Obsidian Excalidraw plugin! This project integrates a heavily customized Excalidraw fork into Obsidian.
First off, thank you for considering contributing to the Obsidian Excalidraw plugin! This project integrates a heavily customized Excalidraw fork into Obsidian.
Because this is not a generic React canvas app, but rather a deeply integrated Obsidian plugin with popout window support, mobile compatibility constraints, and performance optimizations, please read the following guidelines carefully before making any changes.
@@ -11,33 +11,78 @@ Before spending your valuable time writing code for a new feature or significant
## 🚀 Getting Started
1. Fork the repository and clone it locally.
2. Run `npm install` in the root directory to install the main dependencies.
2. Use Node.js 22 or newer and verify it with `node --version`. A shell that mixes a different Node binary with another installation's Corepack can fail before a build starts.
3. Run `npm install` in the root directory to install the main dependencies.
*(Note: The `MathjaxToSVG` sub-component has its own separate dependencies. You do not need to install them manually; the first time you run `npm run build`, it will take care of this automatically).*
3. To test your changes locally, we recommend symlinking your cloned repository folder into a test Obsidian vault's `.obsidian/plugins/obsidian-excalidraw-plugin` directory. (Using a community plugin like [Obsidian Hot Reload](https://github.com/pjeby/hot-reload) will make local development much faster).
4. To test your changes locally, we recommend symlinking your cloned repository folder into a test Obsidian vault's `.obsidian/plugins/obsidian-excalidraw-plugin` directory. (Using a community plugin like [Obsidian Hot Reload](https://github.com/pjeby/hot-reload) will make local development much faster).
## 🛠️ Build and Lint Commands
- **Build the project:** Run `npm run build`
*(Note: Our Rollup build is non-trivial as it merges CSS, handles MathjaxToSVG dependencies, and embeds runtime payloads. Run this command frequently to validate your changes).*
- **Build readable development payloads:** Run `npm run dev`
- **Build the public library API:** Run `npm run lib` when changing exports or ExcalidrawAutomate APIs
- **Run ESLint:** Run `npm run code`
- **Fix ESLint Warnings:** Run `node ./scripts/fix-eslint-warnings.mjs`
The shipped plugin is `dist/main.js`, `dist/styles.css`, and `dist/manifest.json`. Keep `main.js` below the release size limit and report its byte size after dependency or packaging changes.
## 🧪 Testing
At this time, the project **has no automated tests**. As a contributor, you are responsible for testing your changes thoroughly.
At this time, the project **has no comprehensive automated test suite**. As a contributor, you are responsible for testing your changes thoroughly.
Because Obsidian runs across a variety of environments, please manually test your changes on as many of the following platforms as possible to avoid breaking the plugin for other users:
- Desktop: Mac, Windows, Linux
- Mobile: Android, iOS (Test on both Phones and Tablets)
Desktop mobile emulation is useful for checking responsive layout, but it does not reproduce every touch event, synthesized click, focus, scroll gesture, or mobile WebView behavior. If a change affects an interactive mobile control, validate it on at least one physical phone or tablet.
Use a risk-based test plan rather than a generic smoke test. Every change should identify the most likely regression and whether it needs separate coverage in:
- the main Obsidian window
- a newly opened and restored popout window
- plugin reload and cold application startup
- desktop and mobile layouts
- offline mode, when the change affects packaged assets or runtime loading
For UI and CSS changes:
- Use semantic controls and Obsidian's event helpers. Link-like navigation should use a real anchor; custom navigation handlers should use `onClickEvent`.
- Keep accessible names in `aria-label`. If a styled tooltip is already present, omit the HTML `title` attribute to avoid a second native browser tooltip.
- Run Obsidian CodeScanner and resolve compatibility warnings against the supported Obsidian baseline. Prefer simple, broadly supported CSS when advanced styling is only decorative.
Timers, observers, autosave coordination, and undocumented Obsidian API workarounds may exist for platform behavior outside the plugin's control. Trace their purpose before simplifying them.
## 🪵 Logging Requirement
- **Do not use direct `console.log(...)` calls in project code.** Use the shared logging helper exported as `log` from `src/utils/debugHelper.ts`.
- If you are working in a Node script where importing `src/utils/debugHelper.ts` is not practical, define and use a local `log` wrapper instead of calling `console.log(...)` directly.
- Temporary performance diagnostics must use a unique searchable prefix and
produce copyable string lines rather than expandable console objects. Keep
instrumentation separate from functional behavior, avoid vault contents,
and include filenames only when per-file attribution is explicitly needed.
- Remove temporary diagnostics before committing. Search both `src/` and the
built `dist/main.js` for the prefix so timing callbacks and bundled log code
are not left behind.
## 🏗️ Architecture & Sub-components
This project consists of multiple sub-components and non-standard integrations to support Obsidian-specific features.
### 1. React & Package Manager
Because the plugin must support Obsidian's native popout windows, React and Excalidraw cannot be loaded as simple global singletons.
The plugin bundles one private React/ReactDOM runtime and combines it with one evaluated Excalidraw runtime. Every main-window and popout view leases that shared package while supplying its own stable `ownerDocument`.
- References to React and ReactDOM are handled via `PackageManager.ts` (`src/core/managers/PackageManager.ts`).
- They are loaded to Obsidian popout windows separately during runtime. Do not introduce direct `ReactDOM.createRoot()` or similar global React calls outside of this package manager model.
- React and its JSX runtimes are bundled normally from official npm entry points. They must remain external to the separately built Excalidraw artifact and to the plugin's library build so neither path creates a second React copy.
- Do not introduce direct `ReactDOM.createRoot()` calls outside this package-manager model.
- Do not publish React or ReactDOM on `window`. The documented `window.ExcalidrawLib` scripting surface is the deliberate exception.
Rendering and persistence have different window-ownership rules. DOM, events, portals, and React roots should use the owning view window. Existing plugin-level IndexedDB and local-storage data belongs to the main Obsidian application window and is shared with popouts; do not move it to `view.ownerWindow` without an explicit storage design and migration.
#### Typed Excalidraw host boundary
Obsidian-specific capabilities used inside the customized component must cross the typed host-adapter boundary configured by `PackageManager`. Do not pass the plugin, its settings object, or an active view through Excalidraw props or `appState`, and do not recover them through globals. Adapters should expose small semantic operations, read current plugin state, and remain owned by the evaluated window runtime. View-specific behavior must stay instance-scoped.
The fork is the source of truth for adapter contracts and protocol versions. Reuse its published types instead of defining parallel plugin-local unions or interfaces. The adapters are an internal protocol paired with this plugin's exact Excalidraw dependency: coordinate breaking changes across both repositories and fail fast on a missing or incompatible boundary rather than retaining legacy global bridges.
### 2. MathjaxToSVG
LaTeX support is provided by the `MathjaxToSVG` library, which is packaged as a separate sub-component (located in the `MathjaxToSVG/` folder).
@@ -45,7 +90,7 @@ LaTeX support is provided by the `MathjaxToSVG` library, which is packaged as a
- It is decompressed and executed dynamically during runtime only when needed, maintaining optimal Obsidian startup times.
### 3. Excalidraw Fork Guidelines
This plugin relies on a custom Excalidraw component fork: [`zsviczian/excalidraw`](https://github.com/zsviczian/excalidraw/).
This plugin relies on a custom Excalidraw component fork: [`zsviczian/excalidraw`](https://github.com/zsviczian/excalidraw/).
If you must submit a PR to the Excalidraw fork, **keep changes to the absolute minimum**. Compounding changes to the fork make merging upstream updates from `excalidraw/excalidraw` exponentially harder.
@@ -82,11 +127,58 @@ If you must submit a PR to the Excalidraw fork, **keep changes to the absolute m
private startRightClickPanning(event) { ... }
```
### 4. Working Across Both Repositories
The customized component is maintained in the separate [`zsviczian/excalidraw`](https://github.com/zsviczian/excalidraw/) repository. When both repositories are checked out as siblings, the usual path is `../excalidraw`.
The repositories deliberately use different package managers:
- `obsidian-excalidraw-plugin`: npm
- `zsviczian/excalidraw`: Yarn
From `../excalidraw/packages/excalidraw`, `yarn build:obsidian` produces four consumer-specific files in `dist/obsidian`: development and production JavaScript and CSS. This plugin reads the corresponding four files from `node_modules/@zsviczian/excalidraw/dist/obsidian/`.
For an unpublished integration test, you may temporarily copy those four generated files into the installed package under this repository's ignored `node_modules`. Keep the declared npm dependency unchanged. Running `npm install` restores the published package. The durable workflow is to publish a new component version, update the plugin dependency, run `npm install`, and rebuild.
Keep component commit readiness, local integration readiness, and durable
consumer handoff separate. A copied artifact can validate the pair locally,
but a plugin change that consumes a new fork API is not release-ready until the
published package is installed and `package.json` plus `package-lock.json`
reference that version.
For a maintainer-coordinated host-protocol release, update and test the fork contract first, inspect the package tarball, publish the fork package, then update this repository's exact dependency and lockfile. The final production build and smoke test must use the published package installed by `npm install`, not the temporary copied artifacts. Unit tests in the fork use structural fake adapters and do not require Obsidian; integration testing here must cover startup, reload, the main window, and popout creation and teardown.
The Excalidraw Obsidian artifact has strict runtime constraints:
- one function-evaluable JavaScript file, with no runtime chunks
- React, ReactDOM, and their JSX runtimes remain external and are supplied by this plugin
- Mermaid remains external and is loaded lazily through Excalidraw Extras
- all required assets work offline except deliberately lazy CJK font subsets
- production is minified; development retains debugger-friendly source information
Radix menus and popovers may be portaled to the owning document body by `ObsidianRadixPortal`. Portaled content no longer has its original component ancestors and can sit behind modal stacking contexts. Style portaled content through a class that survives the portal, and test visibility, positioning, click-outside, and Escape behavior in the main window and a popout.
### 5. Incremental Refactoring
Use `RefactorPlan.md` as the living record for ongoing structural work. Refactors should be small enough to build and test independently. Move cohesive code intact before redesigning it, update the progress table and action log, and provide a risk-based test checklist at the end of each step.
`ExcalidrawView` must remain an Obsidian `TextFileView`; it should not be converted wholesale into React. React owns the child UI, while the view remains the Obsidian lifecycle and compatibility boundary. ExcalidrawAutomate, command IDs, settings, serialized data, and existing plugin integrations must remain backwards compatible.
### 6. Settings UI and persistence
The plugin keeps Obsidian 1.8.7 compatibility while using searchable declarative settings on Obsidian 1.13 and newer.
- Do not bump the Obsidian dependency or minimum version just to use the declarative API. Gate it at runtime; returning an empty definition array is the intentional legacy fallback.
- Maintain one canonical settings hierarchy and shared control behavior for both the declarative multi-page and legacy single-page layouts, including descriptions and Markdown export. Do not fork the two experiences into independent implementations.
- Keep interdependent controls together and apply their visibility, options, and disabled state during initial render as well as after changes.
- Persist settings through `PluginSettingsManager`; do not add independent `saveData()` calls or rely on plugin shutdown to finish an asynchronous save.
- Treat a missing `data.json`, invalid/corrupted data, and a valid externally synchronized update as separate cases. Preserve the device-local recovery workflow and unknown forward-compatible setting keys.
## 🌍 Localization & User-Facing Text
- **No hardcoded strings:** There should be no hardcoded English strings directly in the UI components or logic.
- **Language files:** All strings must be added to the localization files located in `src/lang/locale/`.
- **Translations:** At a minimum, you must add your new keys and strings to `en.ts`. However, it is highly appreciated if you can provide translated strings for all of our actively maintained translations (`es.ts`, `ru.ts`, `zh-cn.ts`, `zh-tw.ts`) using a translation tool.
- **Language files:** All strings must be added to the localization files located in `src/lang/locale/`.
- **Translations:** Add every new key and string to `en.ts` and the actively maintained translations (`es.ts`, `ru.ts`, `zh-cn.ts`, `zh-tw.ts`) in the same change.
## 📦 Pull Requests & Versioning
+1 -1
View File
@@ -280,7 +280,7 @@ For more details, see this [video](https://youtu.be/yZQoJg2RCKI)
- If the `group=` prefix is found, Excalidraw will select the group of elements in the
same group as the element referenced by the elementID (block reference) or the section heading.
- If the `area=` prefix is found, Excalidraw will insert a cutout of the image around the referenced element.
- Note that the `area=` selector is not supported when embedding Excalidraw as a PNG into your markdown documents.
- You can append `,padding=N` to `area=`, `group=`, `frame=`, and `clippedframe=` image references to override the exported image padding, e.g. `![[file#^area=elementID,padding=120]]`. For `area=`, the value also controls how far around the referenced element Excalidraw searches for surrounding elements. Use `padding=0` for no added margin. This works with both SVG and PNG previews.
- Referencing the elementID of a text element without the `group=` or `area=` prefix will
transclude the element as plain text. Referencing a non-Text Element (e.g. rectangle,
ellipse, etc.) without the `group=` or `area=` prefix will result in an Obsidian error.
+2178
View File
File diff suppressed because it is too large. Load diff
+231
View File
@@ -0,0 +1,231 @@
# Excalidraw Automate scripting support plan
Status: active as of 2026-08-29.
This plan tracks the modernization of ExcalidrawAutomate AI support material while preserving compatibility with the long-lived training entrypoint.
Scope summary:
- Keep [docs/AITrainingData](docs/AITrainingData) as the canonical output location.
- Keep [docs/AITrainingData/ExcalidrawAutomate full library for LLM training.md](docs/AITrainingData/ExcalidrawAutomate%20full%20library%20for%20LLM%20training.md) as a stable entrypoint, but curate it as a router to skill-first references.
- Use one unified generator behind `npm run doc`.
- Keep [ea-scripts/index-new.md](ea-scripts/index-new.md) manually curated.
- Keep skill generation manually triggered by maintainer workflows (no automatic watcher/CI updates in this phase).
- Add strict naming rules for script preview images under [images](images).
## Decisions captured
1. Unified generation command
- `npm run doc` is the single maintainer command for documentation generation.
- If a script-template repository is present in the current VS Code workspace, `npm run doc` should also refresh template-project references/artifacts.
2. Legacy entrypoint behavior
- The legacy training file remains the stable public entrypoint.
- It must warn AI tools that generated code quality may fail if linked skill/reference URLs are inaccessible (for example: URL access disabled in some chat tools).
3. Script library publishing guidance
- `index-new.md` remains manual.
- Agents should be guided to open a proper PR for publishing scripts in this repository instead of trying to bypass the normal contribution workflow.
- Every publishing PR (new script or script update) must update [ea-scripts/directory-info.json](ea-scripts/directory-info.json).
- For updates, the `mtime` value for the updated script file must be refreshed so the plugin can detect local update availability.
4. Template repository direction
- A separate repository will be created first.
- Proposed name: `ea-script-template`.
- Once added to this workspace, the unified generator can optionally update it.
- Repository availability status: present and accessible at [../ea-script-template](../ea-script-template).
5. Image naming
- Adopt strict naming convention for script preview images, aligned to current patterns but enforceable.
6. Experimental script policy
- Scripts under [ea-scripts](ea-scripts) are treated as validated examples.
- No experimental bucket is introduced in this phase.
- Very large scripts (for example Mindmap Builder) are still valid; they should be tagged as "advanced/large-reference" rather than experimental.
7. Skill generation trigger
- Keep manual generation trigger. No automated regeneration in this phase.
## Progress tracking
Target branch: `improved-scripting-skills`.
| Phase | Status | Current outcome |
| --- | --- | --- |
| Baseline audit and constraints capture | Complete | Existing generators, outputs, and maintainer decisions captured in this plan |
| Create planning artifact in repository | Complete | Added [ScriptSupportPlan.md](ScriptSupportPlan.md) with phases, decisions, and action log |
| Unify generator implementation behind `npm run doc` | Complete | Added shared generator core at [scripts/excalidraw-docs-generator-core.mjs](scripts/excalidraw-docs-generator-core.mjs); both [scripts/generate-script-library.mjs](scripts/generate-script-library.mjs) and [scripts/skill-builder.mjs](scripts/skill-builder.mjs) are thin wrappers over one code path |
| Ensure canonical pen type completeness in generated docs | Complete | Generated references now include canonical Obsidian pen stroke type definitions plus the full public `src/types` and `lib/types` declaration surface |
| Curate legacy training entrypoint warning and routing | Complete | Legacy training entrypoint now warns about inaccessible references, names the master repository, and routes agents to the curated skill/reference set with absolute GitHub URLs |
| Add PR publishing workflow guidance for scripting agents | Complete | Generated skill guidance now directs script publishing through PRs, keeps `index-new.md` manual, and requires `directory-info.json` mtime updates |
| Add strict image naming and validation | Complete | Generator now warns on non-conforming preview filenames and documents the `scripts-{slug}.{ext}` rule in generated publishing guidance |
| Optional template-repo sync from `npm run doc` | Complete | `npm run doc` now refreshes a co-located `ea-script-template` bootstrap under `.ai/excalidraw-automate/` when the sibling repo is present |
## Implementation checkpoints
### Checkpoint 1: Shared generator core and single command
Objective:
- Introduce a shared generator module and keep lightweight wrappers for backward command compatibility.
Planned changes:
- Consolidate duplicated logic currently split between:
- [scripts/generate-script-library.mjs](scripts/generate-script-library.mjs)
- [scripts/skill-builder.mjs](scripts/skill-builder.mjs)
- Keep `npm run doc` as the single entrypoint command for maintainers.
- Keep manual run model. Do not add auto-run hooks in this phase.
Acceptance:
- One command (`npm run doc`) generates both legacy and skill outputs exactly once.
- Output files stay under [docs/AITrainingData](docs/AITrainingData).
### Checkpoint 2: Fix type-definition completeness regression
Objective:
- Ensure generated type references remain concrete after alias migrations.
Problem to solve:
- `lib/types/penTypes.d.ts` now aliases fork-owned types, and top import stripping can hide canonical shapes in generated docs.
Planned changes:
- Include canonical Obsidian type declarations from the fork type surface in generated reference outputs.
- Add a post-generation guard that fails if `ObsidianPenStrokeOptions` shape is missing.
Acceptance:
- Both:
- [docs/AITrainingData/Excalidraw Automate library and related type definitions.md](docs/AITrainingData/Excalidraw%20Automate%20library%20and%20related%20type%20definitions.md)
- [docs/AITrainingData/ExcalidrawAutomate full library for LLM training.md](docs/AITrainingData/ExcalidrawAutomate%20full%20library%20for%20LLM%20training.md)
include concrete stroke option structure, not alias-only references.
Status:
- Complete.
- The generator now includes all declaration files under [src/types](src/types) and [lib/types](lib/types), plus the canonical fork-owned `obsidianTypes.d.ts` source for `ObsidianPenStrokeOptions`.
### Checkpoint 3: Curated legacy entrypoint messaging
Objective:
- Keep stable legacy entrypoint while steering agents to curated skill references.
Planned changes:
- Add a prominent warning that script generation can fail if linked references are not accessible.
- Include concrete note about environments requiring explicit URL enablement.
- Add short routing section pointing to curated skill/reference materials.
Acceptance:
- Legacy file remains backward compatible as an entrypoint.
- Warning is clear and placed before the main usage workflow.
Status:
- Complete.
- The generated legacy entrypoint now includes a top-level routing warning, the master repository URL, and direct absolute links to the curated skill and reference files.
### Checkpoint 4: Script publishing workflow guidance for agents
Objective:
- Teach agents to publish scripts through normal repository contribution workflow.
Planned changes:
- Add concise maintainer-approved workflow guidance in skill docs:
- add script to [ea-scripts](ea-scripts)
- add image to [images](images)
- update [ea-scripts/index-new.md](ea-scripts/index-new.md) manually
- update [ea-scripts/directory-info.json](ea-scripts/directory-info.json) in the same PR
- for script updates, refresh the target script `mtime` entry in [ea-scripts/directory-info.json](ea-scripts/directory-info.json)
- keep AI training material updates out of script publishing PRs
- open PR with focused diff and validation notes
- Explicitly avoid automating `index-new.md`.
Acceptance:
- Publishing workflow appears in generated skill material.
- Guidance is PR-centric and does not suggest direct pushes.
Status:
- Complete.
- The generated skill file now includes a dedicated publishing workflow section with absolute repository links, PR-only guidance, manual `index-new.md` curation, and `directory-info.json` update requirements.
### Checkpoint 5: Strict image naming convention and validator
Objective:
- Keep existing style while making naming consistent and enforceable.
Proposed naming rule:
- `scripts-{slug}.{ext}` where:
- `slug` = lowercase words joined by hyphen
- only `a-z`, `0-9`, `-`
- extensions allowed: `.png`, `.jpg`, `.jpeg`, `.gif`, `.webp`, `.svg`
Examples:
- `scripts-add-link-to-existing-file-and-open.jpg`
- `scripts-boolean-operations-showcase.png`
Planned changes:
- Add validation in generator flow with clear error output.
- Keep compatibility mode for pre-existing files during initial rollout (warn-only first, strict fail in follow-up if desired).
Acceptance:
- New/updated script previews follow the naming contract.
- Validation output is actionable for contributors.
Status:
- Complete.
- The generator now warns on non-conforming preview filenames and surfaces the naming rule in the generated publishing workflow guidance.
### Checkpoint 6: Optional template repository sync
Objective:
- Allow `npm run doc` to refresh a co-located script-template repo if present.
Planned behavior:
- Detect a workspace folder named `ea-script-template` (or configurable path).
- If found, update agreed generated reference artifacts in that repo.
- If absent, continue without failure.
Current status:
- Repository now exists and is readable at [../ea-script-template](../ea-script-template).
- Checkpoint is considered unblocked and ready for scoped implementation once approved.
Design note: AI support files in template repo
- Preferred default: synchronized local snapshot under `.ai/excalidraw-automate/`, copied from canonical generated references in this repository.
- Routing note: keep canonical GitHub links in SKILL content, but ensure local references and script examples are present for environments without URL access.
- Reasoning: local snapshot gives immediate offline usability while preserving canonical source of truth in plugin-generated outputs.
Design note: template usage model
- Recommended model: single `ea-script-template` repository used as a multi-script workspace (one folder per script project) with shared utilities.
- Why: easier maintenance of common helpers, lint/build rules, and shared abstractions across scripts like Mindmap Builder, Slideshow, and Shade Master.
- Alternative supported pattern: per-script clones for strict isolation (useful for publishing independent repos), but this should be optional rather than the default path.
Acceptance:
- `npm run doc` succeeds in both cases:
- template repo present
- template repo absent
Status:
- Complete.
- `npm run doc` now refreshes a full local skill snapshot in the sibling `ea-script-template` workspace under `.ai/excalidraw-automate/` when the repo is available.
## Validation approach
For each implementation checkpoint:
- Run `npm run doc` from repository root.
- Verify generated files changed only in intended outputs.
- For script/reference changes, inspect key generated artifacts manually.
- Keep [ea-scripts/index-new.md](ea-scripts/index-new.md) untouched unless explicitly edited by maintainer.
## Risks and mitigations
Risk: duplicate logic drifts again across scripts.
- Mitigation: one shared generator core and wrapper entrypoints.
Risk: type aliasing hides critical concrete structures again.
- Mitigation: required-symbol guard (`ObsidianPenStrokeOptions`) and explicit canonical-source inclusion.
Risk: stricter image naming breaks existing contributions.
- Mitigation: staged rollout (warn-first) and clear remediation examples.
Risk: template sync introduces hard dependency on external repo.
- Mitigation: optional detection; never fail when repo is absent.
## Action log
| Date | Action | Outcome | Validation |
| --- | --- | --- | --- |
| 2026-08-29 | Captured maintainer decisions for scripting support modernization | Decisions documented for unified generator, manual index curation, PR workflow guidance, strict image naming, and optional template sync | Plan file created at [ScriptSupportPlan.md](ScriptSupportPlan.md) |
| 2026-08-29 | Confirmed template repository workspace availability and expanded publishing requirements | Verified [../ea-script-template](../ea-script-template) is present and readable; added mandatory [ea-scripts/directory-info.json](ea-scripts/directory-info.json) update rules to publishing workflow and checkpoint details | Directory listing succeeded for [../ea-script-template](../ea-script-template); plan updated |
| 2026-08-29 | Implemented checkpoint 1 unified generator | Consolidated duplicated generation logic into [scripts/excalidraw-docs-generator-core.mjs](scripts/excalidraw-docs-generator-core.mjs), with wrapper entrypoints preserved at [scripts/generate-script-library.mjs](scripts/generate-script-library.mjs) and [scripts/skill-builder.mjs](scripts/skill-builder.mjs) | `npm run doc` completed successfully and regenerated legacy + skill outputs from one code path |
| 2026-08-29 | Implemented checkpoint 5 image naming validator | Added warning-only preview filename validation and surfaced the `scripts-{slug}.{ext}` rule in generated publishing guidance | `npm run doc` completed successfully and emitted the expected warning for legacy preview names |
| 2026-08-29 | Implemented checkpoint 6 template bootstrap sync | `npm run doc` now refreshes a link-first bootstrap in the sibling `ea-script-template` workspace under `.ai/excalidraw-automate/` | `npm run doc` completed successfully and refreshed the sibling template bootstrap files |
| 2026-08-29 | Hardened checkpoint 6 for offline and advanced script authoring | Template sync now mirrors full generated references and script examples instead of only link stubs | `npm run doc` and `npm run sync-refs` now produce local skill + references + scripts snapshot in `.ai/excalidraw-automate/` |
| 2026-08-29 | Aligned template script extensions and build output | Template-only reference snapshots now use `.js` filenames with rewritten local links; the template build emits executable `.md` scripts with purpose metadata and editable configuration constants before the bundle | `npm run doc` preserves `.js` reference filenames; template `npm run build`, `npm run check`, and package validation pass on Node 22 |
File diff suppressed because it is too large. Load diff
+334 -57
View File
@@ -12,7 +12,7 @@ Content structure:
2. The curated script overview (index-new.md)
3. Raw source of every *.md script in /ea-scripts (each fenced code block is auto-closed to ensure well-formed aggregation)
Generated on: 2026-07-12T12:50:29.769Z
Generated on: 2026-08-30T12:07:47.389Z
---
@@ -120,6 +120,7 @@ These are the scripts I use most often. I tried to order them by importance, but
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Mindmap%20Builder.svg"/></div>|[[#Mindmap Builder]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Mindmap%20format.svg"/></div>|[[#Mindmap format]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Printable%20Layout%20Wizard.svg"/></div>|[[#Printable Layout Wizard]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/VoronoiDiagramGenerator.svg"/></div>|[[#Voronoi Diagram Generator]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Zoom%20to%20Fit%20Selected%20Elements.svg"/></div>|[[#Zoom to Fit Selected Elements]]|
## Connectors and Arrows
@@ -182,7 +183,6 @@ These are the scripts I use most often. I tried to order them by importance, but
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Add%20Link%20to%20Existing%20File%20and%20Open.svg"/></div>|[[#Add Link to Existing File and Open]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Add%20Link%20to%20New%20Page%20and%20Open.svg"/></div>|[[#Add Link to New Page and Open]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Convert%20text%20to%20link%20with%20folder%20and%20alias.svg"/></div>|[[#Convert text to link with folder and alias]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Create%20DrawIO%20file.svg"/></div>|[[#Create DrawIO file]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Create%20new%20markdown%20file%20and%20embed%20into%20active%20drawing.svg"/></div>|[[#Create new markdown file and embed into active drawing]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Folder%20Note%20Core%20-%20Make%20Current%20Drawing%20a%20Folder.svg"/></div>|[[#Folder Note Core - Make Current Drawing a Folder]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Set%20Link%20Alias.svg"/></div>|[[#Set Link Alias]]|
@@ -358,12 +358,6 @@ https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea
```
<table><tr valign='top'><td class="label">Author</td><td class="data"><a href='https://github.com/1-2-3'>@1-2-3</a></td></tr><tr valign='top'><td class="label">Source</td><td class="data"><a href='https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/ea-scripts/Copy%20Selected%20Element%20Styles%20to%20Global.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">This script will copy styles of any selected element into Excalidraw's global styles.<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-copy-selected-element-styles-to-global.png'></td></tr></table>
## Create DrawIO file
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Create%20DrawIO%20file.md
```
<table><tr valign='top'><td class="label">Author</td><td class="data"><a href='https://github.com/zsviczian'>@zsviczian</a></td></tr><tr valign='top'><td class="label">Source</td><td class="data"><a href='https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/ea-scripts/Create%20DrawIO%20file.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">The script will prompt you for a filename, then create a new draw.io diagram file and open the file in the <a href='https://github.com/zapthedingbat/drawio-obsidian'>Diagram plugin</a>, in a new tab.<br><a href="https://www.youtube.com/watch?v=DJcosmN-q2s" target="_blank"><img src ="https://i.ytimg.com/vi/DJcosmN-q2s/maxresdefault.jpg" style="width:400px;"></a></td></tr></table>
## Create new markdown file and embed into active drawing
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Create%20new%20markdown%20file%20and%20embed%20into%20active%20drawing.md
@@ -763,6 +757,23 @@ https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea
```
<table><tr valign='top'><td class="label">Author</td><td class="data"><a href='https://github.com/zsviczian'>@zsviczian</a></td></tr><tr valign='top'><td class="label">Source</td><td class="data"><a href='https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/ea-scripts/Printable%20Layout%20Wizard.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">Export Excalidraw to PDF Pages: Define printable page areas using frames, then export each frame as a separate page in a multi-page PDF. Perfect for turning your Excalidraw drawings into printable notes, handouts, or booklets. Supports standard and custom page sizes, margins, and easy frame arrangement.<br><a href="https://www.youtube.com/watch?v=29EWeglRm7s" target="_blank"><img src ="https://i.ytimg.com/vi/29EWeglRm7s/maxresdefault.jpg" style="width:400px;"></a><br><a href='https://youtu.be/29EWeglRm7s' target='_blank'>Link to video on YouTube</a><br><a href="https://www.youtube.com/watch?v=DqDnzCOoYMc" target="_blank"><img src ="https://i.ytimg.com/vi/DqDnzCOoYMc/maxresdefault.jpg" style="width:400px;"></a><br><a href='https://youtu.be/DqDnzCOoYMc' target='_blank'>Link to video on YouTube</a><br><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-layout-wizard-01.png" style="max-width: 400px;"><br><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-layout-wizard-02.png" style="max-width: 400px;"></td></tr></table>
## Voronoi Diagram Generator
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/VoronoiDiagramGenerator.md
```
<table><tr valign='top'><td class="label">Author</td><td class="data"><a href='https://github.com/FreeCutter'>@FreeCutter</a></td></tr><tr valign='top'><td class="label">Source</td><td class="data"><a href='https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/ea-scripts/VoronoiDiagramGenerator.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">This script generates a Voronoi diagram from selected elements on the drawing canvas.
The following parameters can be set in 'Voronoi Settings' window pop-up once the script is started:
- Frame width (default: 100)
- Roughness (default: 0)
- Stroke width (default: 2)
- Grouping (default: checked)
Setting parameters could be set back to default values by click on button 'Default'.
See background information about [Voronoi diagram](https://en.wikipedia.org/wiki/Voronoi_diagram) at Wikipedia.
Comments and discussion are welcomed in the [Sketch Your Mind Community](https://community.sketch-your-mind.com)<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/Voronoi_diagram_example.svg'></td></tr></table>
## Zoom to Fit Selected Elements
```excalidraw-script-install
@@ -805,6 +816,7 @@ elements.forEach((el)=>{
ea.addToGroup([el.id,ellipseId]);
});
await ea.addElementsToView(false,false,true);
```
---
@@ -877,6 +889,7 @@ if(openInCurrentPane) {
return;
}
ea.openFileInNewOrAdjacentLeaf(file);
```
---
@@ -974,6 +987,7 @@ if(openInCurrentPane) {
return;
}
ea.openFileInNewOrAdjacentLeaf(file);
```
---
@@ -1909,6 +1923,7 @@ function applyTranformationMatrix(vectors, transformationMatrix) {
return result;
}
```
---
@@ -2097,6 +2112,7 @@ function recalculateEndPointOfLine(line, el) {
line.points[line.points.length - 1] = [intersectA[0][0] - line.x, intersectA[0][1] - line.y];
}
}
```
---
@@ -5169,6 +5185,7 @@ if (elements.length>0) {
ea.copyViewElementsToEAforEditing(editedElements);
ea.addElementsToView(false,false);
```
---
@@ -7343,6 +7360,7 @@ async function main() {
// Execute Script
main();
```
---
@@ -7833,46 +7851,7 @@ if(element.type === 'arrow') {
appState.currentItemStartArrowhead = element.startArrowhead;
appState.currentItemEndArrowhead = element.endArrowhead;
}
```
---
## Create DrawIO file.md
<!-- Source: ea-scripts/Create DrawIO file.md -->
/*
Creates a new draw.io diagram file and opens the file in the [Diagram plugin](https://github.com/zapthedingbat/drawio-obsidian) in a new tab.
```js*/
if(!ea.verifyMinimumPluginVersion || !ea.verifyMinimumPluginVersion("1.9.7")) {
new Notice("This script requires a newer version of Excalidraw. Please install the latest version.");
return;
}
const drawIO = app.plugins.plugins["drawio-obsidian"];
if(!drawIO || !drawIO?._loaded) {
new Notice("Can't find the draw.io diagram plugin");
}
filename = await utils.inputPrompt("Diagram name?");
if(!filename) return;
filename = filename.toLowerCase().endsWith(".svg") ? filename : filename + ".svg";
const filepath = await ea.getAttachmentFilepath(filename);
if(!filepath) return;
const leaf = app.workspace.getLeaf('tab')
if(!leaf) return;
const file = await this.app.vault.create(filepath, `<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"><!--${ea.generateElementId()}--><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" width="300px" height="300px" viewBox="-0.5 -0.5 1 1" content="&lt;mxGraphModel&gt;&lt;root&gt;&lt;mxCell id=&quot;0&quot;/&gt;&lt;mxCell id=&quot;1&quot; parent=&quot;0&quot;/&gt;&lt;/root&gt;&lt;/mxGraphModel&gt;"></svg>`);
await ea.addImage(0,0,file);
await ea.addElementsToView(true,true);
leaf.setViewState({
type: "diagram-edit",
state: {
file: filepath
}
});
```
---
@@ -7901,6 +7880,7 @@ const fname = await utils.inputPrompt("Filename for new file","Filename",folder)
const file = await app.fileManager.createAndOpenMarkdownFile(fname,true);
await ea.addImage(0,0,file);
ea.addElementsToView(true,true);
```
---
@@ -8064,6 +8044,7 @@ for (const el of ea.getElements()) {
}
}
await ea.addElementsToView(false, false);
```
---
@@ -8502,6 +8483,7 @@ for (const line of lines) {
ea.copyViewElementsToEAforEditing(lines);
await ea.addElementsToView(false,false);
```
---
@@ -8570,6 +8552,7 @@ id = ea.addEllipse(
ea.copyViewElementsToEAforEditing(elements);
ea.addToGroup([id].concat(elements.map((el)=>el.id)));
ea.addElementsToView(false,false);
```
---
@@ -11522,6 +11505,8 @@ const openConfigModal = () => {
};
openConfigModal();
```
---
@@ -11857,6 +11842,7 @@ const outfile = await app.vault.create(outputPath,result);
setTimeout(()=>{
ea.openFileInNewOrAdjacentLeaf(outfile);
}, 250);
```
---
@@ -13612,6 +13598,7 @@ function recalculateEndPointOfLine(line, el) {
line.points[line.points.length - 1] = [intersectA[0][0] - line.x, intersectA[0][1] - line.y];
}
}
```
---
@@ -13693,6 +13680,7 @@ for(var i=0; i<groups.length; i++) {
}
ea.copyViewElementsToEAforEditing(elements);
await ea.addElementsToView(false, false);
```
---
@@ -13827,6 +13815,7 @@ else if(fromBorder === 'right') {
ea.copyViewElementsToEAforEditing(elements);
await ea.addElementsToView(false, false);
```
---
@@ -13903,6 +13892,7 @@ for(var i=0; i<groups.length; i++) {
}
ea.copyViewElementsToEAforEditing(elements);
await ea.addElementsToView(false, false);
```
---
@@ -14062,6 +14052,7 @@ for(var i=0; i<groups.length; i++) {
}
ea.copyViewElementsToEAforEditing(elements);
await ea.addElementsToView(false, false);
```
---
@@ -14242,6 +14233,7 @@ do {
await ea.addElementsToView(false, false, true);
```
---
@@ -14998,6 +14990,7 @@ try {
} catch (err) {
_ = new Notice(err.toString())
}
```
---
@@ -17841,7 +17834,8 @@ try {
} catch (error) {
console.error("Error showing completion message:", error);
new Notice("Operation completed with some errors");
}
}
```
---
@@ -17970,6 +17964,7 @@ ea.viewUpdateScene({
elements: ea.getElements(),
storeAction: "capture" // Ensures the change is saved and added to the undo/redo history.
});
```
---
@@ -18029,6 +18024,7 @@ for (const el of ea.getElements()) {
}
}
await ea.addElementsToView(false, false);
```
---
@@ -18245,6 +18241,7 @@ const bottomHeaderY = START_Y + 160 + (12 * (CELL_HEIGHT + ROW_SPACING)) + 40;
drawDayHeaders(bottomHeaderY);
await ea.addElementsToView(false, false, true);
```
---
@@ -21641,11 +21638,36 @@ const zoomToFit = (mode) => {
elementID: sel.id,
level: nextLevel
}
api().scrollToContent([sel], {
fitToViewport: true,
viewportZoomFactor: getZoom(nextLevel),
animate: true
});
const targetZoom = getZoom(nextLevel);
// Fallback for older versions vs new Excalidraw 2.26.0+ Viewport API
if (!ea.verifyMinimumPluginVersion("2.26.0")) {
api().scrollToContent([sel], {
fitToViewport: true,
viewportZoomFactor: targetZoom,
animate: true
});
} else {
// For the new API, we calculate a target rect centered on the element
// with dimensions that will force 'fit: "contain"' to reach our target zoom.
const appState = api().getAppState();
const targetW = appState.width / targetZoom;
const targetH = appState.height / targetZoom;
const cx = sel.x + sel.width / 2;
const cy = sel.y + sel.height / 2;
api().setViewport({
target: {
x: cx - targetW / 2,
y: cy - targetH / 2,
width: targetW,
height: targetH
},
fit: "contain",
animation: true
});
}
}
}
@@ -21674,10 +21696,20 @@ const focusSelected = () => {
if (!sel) return;
api().scrollToContent(sel, {
fitToContent: false,
animate: true,
});
// Fallback for older versions vs new Excalidraw 2.26.0+ Viewport API
if (!ea.verifyMinimumPluginVersion("2.26.0")) {
api().scrollToContent(sel, {
fitToContent: false,
animate: true,
});
} else {
// fit: "none" recenters at the current zoom without changing it
api().setViewport({
target: [sel],
fit: "none",
animation: true
});
}
};
const getMindmapOrder = (node) => {
@@ -32375,6 +32407,7 @@ else {
}
await ea.addElementsToView(false,false,true);
```
---
@@ -32752,6 +32785,7 @@ generateTree(elements);
ea.copyViewElementsToEAforEditing(elements);
await ea.addElementsToView(false, false);
```
---
@@ -33787,6 +33821,7 @@ async function run() {
}
run();
```
---
@@ -34701,6 +34736,7 @@ async function run() {
}
run();
```
---
@@ -34876,6 +34912,7 @@ for(i of img) {
await app.fileManager.renameFile(file,`${newPath}.${file.extension}`);
}
}
```
---
@@ -34999,6 +35036,7 @@ for(let i=0; i<repeatNum; i++) {
}
await ea.addElementsToView(false, false, true);
```
---
@@ -35101,6 +35139,8 @@ for(let i=0; i<repeatNum; i++) {
}
await ea.addElementsToView(false, false, true);
```
---
@@ -36196,6 +36236,7 @@ ea.copyViewElementsToEAforEditing(elements);
ea.getElements().forEach((el)=>el.strokeWidth=width);
await ea.addElementsToView(false,false);
ea.viewUpdateScene({appState: {currentItemStrokeWidth: width}});
```
---
@@ -37982,6 +38023,7 @@ if(
window.ExcalidrawSlideshowStartTimer = window.setTimeout(start,500);
}
```
---
@@ -40464,6 +40506,240 @@ ea.getElements().forEach(el=>{
const ids = ea.getElements().map(el=>el.id);
await ea.addElementsToView(false,true);
ea.getExcalidrawAPI().updateContainerSize(ea.getViewElements().filter(el=>ids.contains(el.id)));
```
---
## VoronoiDiagramGenerator.md
<!-- Source: ea-scripts/VoronoiDiagramGenerator.md -->
/*
This script generates a Voronoi diagram from selected elements on the drawing canvas.
The following parameters can be set in 'Voronoi Settings' window pop-up once the script is started:
- Frame width (default: 100)
- Roughness (default: 0)
- Stroke width (default: 2)
- Grouping (default: checked)
Setting parameters could be set back to default values by click on button 'Default'.
Check info button for howto help during applying the script.
See background information about Voronoi diagram at Wikipedia : https://en.wikipedia.org/wiki/Voronoi_diagram
Comments and discussion are welcomed in the Sketch-Your-Mind community: https://community.sketch-your-mind.com
```js*/
// ExcalidrawAutomate: Voronoi Diagram Generator
ea.clear();
const DEFAULTS = {
frameWidth: 100,
roughness: 0,
strokeWidth: 2,
groupVoronoi: true
};
let config = ea.getScriptSettings() || { ...DEFAULTS };
// --- UI SETTINGS MODAL ---
async function openSettings() {
return new Promise((resolve) => {
const modal = new ea.obsidian.Modal(app);
modal.contentEl.style.padding = "20px";
// Header container with Title and Info Button
const headerContainer = modal.contentEl.createDiv();
headerContainer.style.display = "flex";
headerContainer.style.justifyContent = "space-between";
headerContainer.style.alignItems = "center";
headerContainer.style.marginBottom = "20px";
headerContainer.createEl("h2", { text: "Settings - Voronoi Diagram Generator", cls: "mod-header" }).style.margin = "0";
// Info button using Obsidian's native icon
const btnInfo = headerContainer.createEl("button", { cls: "clickable-icon" });
btnInfo.setAttribute("aria-label", "Information & Help");
btnInfo.innerHTML = ea.obsidian.getIcon("info").outerHTML;
// Info modal content on click
btnInfo.onclick = () => {
const infoModal = new ea.obsidian.Modal(app);
infoModal.contentEl.style.padding = "20px";
infoModal.contentEl.createEl("h3", { text: "About - Voronoi Diagram Generator" });
// Native Obsidian Icon as HTML string
const chatIcon = ea.obsidian.getIcon("message-square").outerHTML;
const p = infoModal.contentEl.createEl("p");
p.innerHTML = `
This script generates a Voronoi diagram from selected elements on the drawing canvas.<br><br>
<h4 style="margin: 5px 0 5px 0; font-size: 1.1em;">HowTo & Parameters:</h4>
<div line-height: 1.4;">
<div style="margin-bottom: 10px;">1. <b>Select</b> at least 2 elements on your canvas.</div>
<div style="margin-bottom: 4px;">2. <b>Run</b> the script and adjust your settings:</div>
<div style="margin: 2px 0 10px 15px; line-height: 1.2;">
- <b>Frame width:</b> Spacing around the diagram.<br>
- <b>Roughness:</b> Hand-drawn effect (0-3).<br>
- <b>Stroke width:</b> Line thickness.<br>
- <b>Grouping:</b> Group generated cells together.<br>
</div>
<div style="margin-bottom: 15px;">3. Click <b>OK</b> to generate.</div>
</div><br>
<span style="display: inline-flex; align-items: center; gap: 6px; vertical-align: middle;"> ${chatIcon} Feedback & chat: <a href="https://community.sketch-your-mind.com" target="_blank">Sketch Your Mind Community</a>
</span>
`;
infoModal.open();
};
const inputs = {};
// Helper function to create input rows
const createInput = (label, key, type = "number") => {
const container = modal.contentEl.createDiv();
container.style.marginBottom = "15px";
container.createEl("label", { text: label });
const input = container.createEl("input", { type: type });
input.style.display = "block";
input.style.marginTop = "5px";
input.value = config[key];
input.onchange = (e) => config[key] = type === "number" ? Number(e.target.value) : e.target.checked;
inputs[key] = input;
};
createInput("Frame width:", "frameWidth");
createInput("Roughness (0-3):", "roughness");
createInput("Stroke width:", "strokeWidth");
const checkContainer = modal.contentEl.createDiv();
checkContainer.style.marginBottom = "25px";
checkContainer.createEl("label", { text: "Grouping: " });
inputs.groupVoronoi = checkContainer.createEl("input", { type: "checkbox" });
inputs.groupVoronoi.checked = config.groupVoronoi;
inputs.groupVoronoi.onchange = (e) => config.groupVoronoi = e.target.checked;
// Button container
const btnContainer = modal.contentEl.createDiv();
btnContainer.style.display = "flex";
btnContainer.style.gap = "10px";
btnContainer.style.justifyContent = "flex-end";
const btnDefault = btnContainer.createEl("button", { text: "Default" });
const btnOk = btnContainer.createEl("button", { text: "OK" });
btnDefault.onclick = () => {
config = { ...DEFAULTS };
inputs.frameWidth.value = config.frameWidth;
inputs.roughness.value = config.roughness;
inputs.strokeWidth.value = config.strokeWidth;
inputs.groupVoronoi.checked = config.groupVoronoi;
new Notice("Settings reset to default");
};
btnOk.onclick = () => {
ea.setScriptSettings(config);
modal.close();
resolve(true);
};
modal.open();
});
}
// Wait for user to configure settings
const proceed = await openSettings();
if (!proceed) return;
// --- ALGORITHM & EXECUTION ---
const els = ea.getViewSelectedElements();
if (els.length < 2) {
new Notice("Please select at least two items!");
return;
}
const seeds = els.map(el => ({ x: el.x + el.width / 2, y: el.y + el.height / 2 }));
if (seeds.length < 2) {
new Notice("Please select at least two items!");
return;
}
const minX = Math.min(...seeds.map(s => s.x)) - config.frameWidth;
const minY = Math.min(...seeds.map(s => s.y)) - config.frameWidth;
const maxX = Math.max(...seeds.map(s => s.x)) + config.frameWidth;
const maxY = Math.max(...seeds.map(s => s.y)) + config.frameWidth;
const bbox = [
{ x: minX, y: minY },
{ x: maxX, y: minY },
{ x: maxX, y: maxY },
{ x: minX, y: maxY }
];
function clipPolygon(poly, p1, p2) {
const mid = { x: (p1.x + p2.x) / 2, y: (p1.y + p2.y) / 2 };
const n = { x: p2.x - p1.x, y: p2.y - p1.y };
const isInside = (p) => (p.x - mid.x) * n.x + (p.y - mid.y) * n.y <= 0;
const intersect = (a, b) => {
const num = (a.x - mid.x) * n.x + (a.y - mid.y) * n.y;
const den = (b.x - a.x) * n.x + (b.y - a.y) * n.y;
if (den === 0) return null;
const t = -num / den;
return { x: a.x + t * (b.x - a.x), y: a.y + t * (b.y - a.y) };
};
const result = [];
for (let i = 0; i < poly.length; i++) {
const cur = poly[i];
const prev = poly[(i - 1 + poly.length) % poly.length];
const curIn = isInside(cur);
const prevIn = isInside(prev);
if (curIn !== prevIn) {
const ix = intersect(prev, cur);
if (ix) result.push(ix);
}
if (curIn) result.push(cur);
}
return result;
}
const polygons = seeds.map((s, i) => {
let poly = [...bbox];
seeds.forEach((_, j) => {
if (i !== j) poly = clipPolygon(poly, seeds[i], seeds[j]);
});
return poly;
});
ea.style.roughness = config.roughness;
ea.style.strokeWidth = config.strokeWidth;
ea.style.backgroundColor = "transparent";
const ids = [];
for (const poly of polygons) {
if (poly.length < 3) continue;
const points = poly.map(p => [p.x, p.y]);
points.push(points[0]);
ids.push(ea.addLine(points));
}
if (config.groupVoronoi && ids.length > 0) {
ea.addToGroup(ids);
}
await ea.addElementsToView(false, false);
// Clear selection so nothing remains selected on the canvas
const view = app.workspace.activeLeaf.view; if (view && view.excalidrawAPI) { view.excalidrawAPI.updateScene({ appState: { selectedElementIds: {} } }); }
new Notice("Voronoi diagram created!");
```
---
@@ -40486,4 +40762,5 @@ https://zsviczian.github.io/obsidian-excalidraw-plugin/ExcalidrawScriptsEngine.h
elements = ea.getViewSelectedElements();
api = ea.getExcalidrawAPI();
api.zoomToFit(elements,10);
```
File diff suppressed because it is too large. Load diff
@@ -9,8 +9,17 @@ Excalidraw-Obsidian is an Obsidian.md plugins that is built on the open source E
Read the information below and respond with I'm ready. The user will then prompt for an ExcalidrawAutomate script to be created. Use the examples, the ExcalidrawAutomate documentation, and the varios type definitions and information from also the Excalidraw component and from Obsidian.md to generate the script based on the user's requirements.
**Routing note:** Prefer the curated skill package and reference set first. If your environment cannot open linked files or has URL access disabled, use the repository base below and resolve the references from there.
- Master repository: https://github.com/zsviczian/obsidian-excalidraw-plugin
- Start with: https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/docs/AITrainingData/excalidraw-automate/SKILL.md
- Type definitions: https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/docs/AITrainingData/excalidraw-automate/references/type-definitions.md
- API usage index: https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/docs/AITrainingData/excalidraw-automate/references/api-usage-index.md
- ExcalidrawLib signatures: https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/docs/AITrainingData/excalidraw-automate/references/excalidraw-lib-functions.md
- Startup examples: https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/docs/AITrainingData/excalidraw-automate/references/startup-scripts.md
In addition to ExcalidrawAutomate, you can also use two other sources of functions:
- The Excalidraw API available via `ea.getExcalidrawAPI()`. Note: the API is only available if `ea.targetView` is set. When running Excalidraw scripts using the script engine, the provided `ea` object is already set up with targetView by default. Otherwise you need to first run `ea.setView()`.
- The Excalidraw API available via `ea.getExcalidrawAPI()`. Note: the API is only available if `ea.targetView` is set. When running Excalidraw scripts using the script engine, the provided `ea` object is already set up with targetView by default. Otherwise call `ea.setView()` to select a sensible default or `ea.setView(view)` to bind explicitly. Calling `ea.setView(null)` deliberately clears `targetView`; it does not auto-select another drawing.
- `window.ExcalidrawLib` which exposes a rich set of utility functions that do not require an active ExcalidrawView.
**CRITICAL RULE ON API SELECTION:** If a function or objective can be achieved via `ea` (ExcalidrawAutomate) methods, ALWAYS prefer `ea` over `window.ExcalidrawLib`. `ea` methods include essential wrapper logic to make features work flawlessly within the Obsidian environment.
@@ -23,10 +32,17 @@ For a reference, follow the implementation pattern used in the "Printable Layout
- Elements can be hidden by setting their opacity to 0. When hiding elements this way, it is good practice to temporarily store their original opacity in customData. This allows for easy restoration of the original opacity later.
- Elements can be deleted from the scene by setting their isDeleted property to true.
- The Obsidian.md module is available on `ea.obsidian`.
- Version checks are distinct: use `ea.verifyMinimumPluginVersion()` for the Excalidraw plugin and `ea.verifyMinAppVersion()` only for the Obsidian application version.
- `utils.executionSource` describes why the current top-level invocation happened. Supported values are `"manual"`, `"plugin-startup"`, `"view-autostart"`, `"sidepanel-restore"`, `"sidepanel-reload"`, and `"drawing-onload"`. It does not indicate whether code came from the compilation cache or whether the script has run before.
- `ea.registerAutostart(message?)` requests view-autostart permission. The script is automatically attached once to each ExcalidrawView, while manual toolbar/command/hotkey invocation remains independently repeatable. The optional explanation appears as the second paragraph of the permission prompt; do not imply that the script's main interactive action starts automatically when only its tools/providers do.
- `ea.registerCleanup(cleanup)` registers synchronous cleanup owned by the current EA instance. Use it for external listeners, timers, observers, and subscriptions; the cleanup runs when that EA is destroyed.
- `ea.registerElementActionProvider()` action descriptors take an Obsidian/Lucide icon name such as `"presentation"`, not serialized SVG markup. For buttons a script renders itself, obtain the SVG with `ea.obsidian.getIcon()` and recreate it in the button's owning document when popout support matters.
- When an Excalidraw API method requires an element, pass the known typed scene element. For example, call `api.startLineEditor(line, pointIndices)`; do not re-read selection state when the intended line is already known.
- For persistent workbench mutations, await `ea.addElementsToView()` with saving enabled (the default). Prefer this public EA save path over unpublished methods on `ea.targetView`.
**Sidepanels and multi-view tooling:**
- Sidepanels are for scripts that must stay open while users hop between multiple Excalidraw views. They should implement the SidepanelTab hooks (`onOpen`, `onFocus(view)`, `onClose`, `onExcalidrawViewClosed`) and manage their own `ea.targetView` explicitly.
- Persisted sidepanel scripts are launched during plugin startup (e.g., Obsidian restart, plugin update) with `ea.targetView === null`. Scripts must handle this by deferring view-bound work until `onFocus` delivers a view; call `ea.setView(view)` when you decide to bind.
- Persisted sidepanel scripts are restored lazily when the Excalidraw sidepanel initializes (often during startup, but not necessarily) with `ea.targetView === null`. Scripts must handle this by deferring view-bound work until `onFocus` delivers a view; call `ea.setView(view)` when you decide to bind. When `onFocus` supplies `null` or focus moves to a non-Excalidraw view, call `ea.setView(null)` to make the unbound state explicit and prevent later view operations from targeting a stale drawing.
- Each `ea` instance may host a single `sidepanelTab`. This sidepanel tab is stored in `ea.sidepanelTab`. Create the tab with `ea.createSidepanelTab(title, persist=false, reveal=true)`; the returned `ea.sidepanelTab` exposes `contentEl`, `setContent`, `setTitle`, `setDisabled`, `setCloseCallback`, `open/close`, and focus lifecycle hooks. Note auto-reveal during tab creation via `ea.createSidepanelTab()` is disabled during plugin startup. You can reveal a tab with `ea.sidepanelTab?.open()`. You can persist with `ea.persistSidepanelTab()` (tabs are restored and scripts re-run on next startup). Close with `ea.sidepanelTab?.close()`.
- Mobile UX: sidepanels slide in without disturbing canvas layout and are better for longer forms than floating modals. Prefer them for complex inputs, especially on phones.
- Auto-closing patterns: For scripts that use sidepanels but perform operations that are single-`ExcalidrawView` relevant, they can call `ea.closeSidepanelTab()` after completing the operation, and/or inside `ea.sidepanelTab.onFocus = (view) => { if (view !== ea.targetView) { ea.sidepanelTab?.close(); } }` to shut down when the user leaves the originating view.
@@ -64,14 +80,32 @@ To keep this training file concise, large external type definitions are not incl
#### **1. The Core Workflow: Handling Element Immutability**
* **Central Rule:** Elements in the Excalidraw scene are immutable and should never be modified directly. Always use the ExcalidrawAutomate (EA) "workbench" pattern for modifications.
* **Central Rule:** Elements returned from the Excalidraw scene are immutable and should never be modified directly. EA owns a stateful, in-memory "workbench" (`elementsDict` and `imagesDict`) where a script stages one coherent persistent or temporary operation independently of the scene.
* **The Workflow:**
1. Get elements from the current view using `ea.getViewElements()` or `ea.getViewSelectedElements()`.
2. Copy these elements into the EA workbench for editing using `ea.copyViewElementsToEAforEditing(elements)`.
3. Modify the properties of the element copies that are now in the EA workbench (e.g., `ea.getElement(id).locked = true;`).
4. Commit the changes back to the scene using `await ea.addElementsToView()`.
1. Start an independent transaction with `ea.clear()`. This clears only the workbench; it does not delete scene elements or reset style.
2. Read existing scene elements using `ea.getViewElements()` or `ea.getViewSelectedElements()`.
3. To work with mutable copies of those same scene elements, copy them into the workbench with `ea.copyViewElementsToEAforEditing(elements)`. Their IDs are preserved.
4. Modify the workbench copies retrieved by their original IDs (e.g., `ea.getElement(id).locked = true;`).
5. For a persistent scene edit, commit once with `await ea.addElementsToView()`; saving is enabled by default. For temporary transformations such as export or preview preparation, pass the workbench elements to the relevant EA operation without committing them to the scene.
6. Call `ea.clear()` after the operation to discard the workbench copies, preferably in a `finally` block when an awaited operation can fail.
* **Temporary workbench example:**
```javascript
ea.clear();
try {
const sceneElements = ea.getViewElements();
ea.copyViewElementsToEAforEditing(sceneElements);
ea.getElement(pathId).opacity = 0;
// elementsOverride replaces the export scene, so pass the complete workbench.
const svg = await ea.createViewSVG({ elementsOverride: ea.getElements() });
// Use svg. The live scene was never changed.
} finally {
ea.clear();
}
```
* **`elementsOverride` is a complete replacement:** In `createViewSVG()`, this option replaces the view's element array; it is not merged with the scene and is not a patch by element ID. The array must contain every element that should appear in the SVG. When temporarily modifying an existing scene for export, the simplest safe workflow is to copy the complete desired export set into EA, modify the workbench copy, and pass `ea.getElements()` as the override.
* **Identity is the boundary:** `copyViewElementsToEAforEditing()` is the standard way to obtain mutable, identity-preserving copies of existing scene elements for both persistent edits and temporary EA operations. By contrast, `ea.cloneElement()` and `ea.cloneElements()` deliberately generate new IDs and are only for creating genuine duplicate scene elements. Never use them to obtain editable workbench copies of existing elements.
* **One workbench transaction at a time:** The workbench is shared mutable state on an EA instance. Do not interleave asynchronous preview/export preparation and scene mutation through the same workbench. Await the operation, then clear the workbench before starting another transaction.
* **Deletion:** To delete an element, set its `isDeleted` property to `true` on the workbench copy (`ea.getElement(id).isDeleted = true;`) and then commit with `await ea.addElementsToView()`.
* **Cleanup:** Use `ea.clear()` at the beginning of a script if you are creating a completely new set of elements, to ensure the EA workbench is empty and doesn't contain artifacts from a previous run.
#### **2. User Interaction: Prompts and Dialogs**
@@ -125,11 +159,27 @@ To keep this training file concise, large external type definitions are not incl
* To permanently remove an element from the scene, set `element.isDeleted = true`.
* **Image Handling:** When dealing with image elements, use `ea.getViewFileForImageElement(imageElement)` to get the corresponding `TFile` from the Obsidian vault. This is necessary for any logic that needs to read or manipulate the source image file.
#### **6.1. Tests in a Multi-Script Workspace**
* **Tests are part of implementation:** Add or update focused automated tests for behavior changes. When fixing a regression, reproduce it with a failing test first when practical.
* **Co-locate by ownership:** Put script tests in `src/scripts/{slug}/__tests__/*.test.ts` and shared utility tests in `src/sharedUtils/__tests__/*.test.ts`. Do not maintain a separate root test tree that mirrors dozens of scripts.
* **Never import executable entrypoints:** `main.ts` runs immediately against the globals injected by Obsidian. Keep it as a thin bootstrap and move testable orchestration to `run.ts` or another import-safe module.
* **Use the universal runner:** Use Vitest. Run a focused suite while iterating, then run `npm run check`; the repository gate includes TypeScript, ESLint, and all test suites. Use `npm run test:watch` for continuous feedback.
* **Test behavior, not bundler details:** Prefer pure domain functions and narrow fakes for `ea`, the Excalidraw API, Obsidian globals, timers, and DOM boundaries. Build and perform an Obsidian smoke test for integration behavior automation cannot prove.
#### **6.2. Per-Script Localization**
* **Catalogs belong to the script:** Store strings in `src/scripts/{slug}/lang/`, with one file per locale. Never create one language catalog shared across unrelated scripts.
* **English defines the contract:** `lang/en.ts` is the typed source of truth. Maintain `de.ts`, `es.ts`, `fr.ts`, `ru.ts`, and `zh-cn.ts`; incomplete reviewed catalogs may rely on English fallback.
* **Use the shared helper:** Register catalogs in `lang/index.ts` with `createTranslator`. Resolve the locale with `ea.obsidian.moment.locale()` and pass the translator into import-safe script logic.
* **Interpolate by name:** Use placeholders such as `{count}` instead of string concatenation. Do not use dynamically constructed regular expressions for interpolation.
* **Keep UI copy out of logic:** Add user-visible strings to the script catalog rather than embedding them in controllers, runners, or helpers.
#### **7. SVG and Image Export Approaches**
Generating images (SVG/PNG) requires specific approaches depending on the context. Follow these three rules strictly to avoid performance issues and missing assets:
1. **Exporting elements currently in the EA workbench:** Use `await ea.createSVG(null, ...)` or `await ea.createPNG(null, ...)` (passing `null` as the `templatePath`).
2. **Exporting an Excalidraw file that is NOT currently open:** Pass the file path as the template to `createSVG` or `createPNG` (e.g., `await ea.createSVG(file.path, ...)`). This is the most reliable approach as ExcalidrawAutomate natively handles loading the scene, resolving embedded images, and instantiating loaders behind the scenes. **Do NOT attempt to manually read the file, reconstruct the scene, or load images into memory.**
3. **Exporting the currently active `ExcalidrawView`:** Use `await ea.createViewSVG(...)`. This is specifically for the open view. You can use the `elementsOverride` parameter to inject temporary elements (like transparent sizing rectangles) into the exported image without modifying the actual scene.
3. **Exporting the currently active `ExcalidrawView`:** Use `await ea.createViewSVG(...)`. This is specifically for the open view. Its `elementsOverride` parameter is a complete replacement for the exported element array, not an additive injection or a patch by ID. If supplied, include every existing or temporary element that should appear in the SVG. For temporary changes to existing elements, copy the complete desired export set into the EA workbench, modify it there, and pass `ea.getElements()`.
#### **8. Custom Pens and Perfect Freehand**
@@ -230,11 +280,23 @@ Example freedraw element carrying `customData.strokeOptions`:
## References
The `references/` directory contains supporting documentation necessary for writing scripts:
- `references/type-definitions.md`: Core type definitions for ExcalidrawAutomate.
- `references/excalidraw-lib-functions.md`: Function signatures for `window.ExcalidrawLib`.
- `references/startup-scripts.md`: ExcalidrawStartup script template and examples.
- `references/api-usage-index.md`: A highly useful index mapping every API method (ea.*, api.*, ExcalidrawLib.*) to the specific example scripts that utilize them.
- `references/scripts/`: A folder containing all the raw, real-world example scripts.
- [type-definitions.md](https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/docs/AITrainingData/excalidraw-automate/references/type-definitions.md): Core type definitions for ExcalidrawAutomate.
- [excalidraw-lib-functions.md](https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/docs/AITrainingData/excalidraw-automate/references/excalidraw-lib-functions.md): Function signatures for `window.ExcalidrawLib`.
- [startup-scripts.md](https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/docs/AITrainingData/excalidraw-automate/references/startup-scripts.md): ExcalidrawStartup script template and examples.
- [api-usage-index.md](https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/docs/AITrainingData/excalidraw-automate/references/api-usage-index.md): A highly useful index mapping every API method (ea.*, api.*, ExcalidrawLib.*) to the specific example scripts that utilize them.
- [scripts/](https://github.com/zsviczian/obsidian-excalidraw-plugin/tree/master/docs/AITrainingData/excalidraw-automate/references/scripts): A folder containing all the raw, real-world example scripts.
## Publishing Workflow
Use the normal repository contribution flow when publishing or updating scripts.
The AI training material is maintained independently from publishing PRs; do not bundle regenerated training artifacts into the script PR.
- Preview images must follow `scripts-{slug}.{ext}`, where `slug` uses lowercase `a-z`, `0-9`, and hyphens only.
- Add or update the script under [ea-scripts](https://github.com/zsviczian/obsidian-excalidraw-plugin/tree/master/ea-scripts).
- Add or update the preview image under [images](https://github.com/zsviczian/obsidian-excalidraw-plugin/tree/master/images).
- Keep [ea-scripts/index-new.md](https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/ea-scripts/index-new.md) manually curated; do not automate it.
- Update [ea-scripts/directory-info.json](https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/ea-scripts/directory-info.json) in the same PR.
- For script updates, refresh the matching entry's `mtime` in [ea-scripts/directory-info.json](https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/ea-scripts/directory-info.json) so the plugin can detect the newer local version.
- Keep the PR focused on the script and its generated references.
### How to use the Script Examples
If you need to implement a specific function (e.g., `ea.addElementsToView`), do NOT guess its implementation context. Instead:
@@ -9,23 +9,23 @@ This index maps methods and properties from ExcalidrawAutomate (`ea`), Excalidra
- **addAppendUpdateCustomData**: [Comicbook Callout Editor.md](scripts/Comicbook%20Callout%20Editor.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Text to Path.md](scripts/Text%20to%20Path.md)
- **addArrow**: [Concatenate lines.md](scripts/Concatenate%20lines.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Mindmap connector.md](scripts/Mindmap%20connector.md)
- **addDiamond**: [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md)
- **addElementsToView**: [Add Connector Point.md](scripts/Add%20Connector%20Point.md), [Add Link to Existing File and Open.md](scripts/Add%20Link%20to%20Existing%20File%20and%20Open.md), [Add Link to New Page and Open.md](scripts/Add%20Link%20to%20New%20Page%20and%20Open.md), [Add Next Step in Process.md](scripts/Add%20Next%20Step%20in%20Process.md), [Auto Layout.md](scripts/Auto%20Layout.md), [Boolean Operations.md](scripts/Boolean%20Operations.md), [Box Each Selected Groups.md](scripts/Box%20Each%20Selected%20Groups.md), [Box Selected Elements.md](scripts/Box%20Selected%20Elements.md), [Capture Note.md](scripts/Capture%20Note.md), [Change shape of selected elements.md](scripts/Change%20shape%20of%20selected%20elements.md), [Comicbook Callout Editor.md](scripts/Comicbook%20Callout%20Editor.md), [Concatenate lines.md](scripts/Concatenate%20lines.md), [Connect elements.md](scripts/Connect%20elements.md), [Convert freedraw to line.md](scripts/Convert%20freedraw%20to%20line.md), [Convert selected text elements to sticky notes.md](scripts/Convert%20selected%20text%20elements%20to%20sticky%20notes.md), [Convert text to link with folder and alias.md](scripts/Convert%20text%20to%20link%20with%20folder%20and%20alias.md), [Create DrawIO file.md](scripts/Create%20DrawIO%20file.md), [Create new markdown file and embed into active drawing.md](scripts/Create%20new%20markdown%20file%20and%20embed%20into%20active%20drawing.md), [Crop Vintage Mask.md](scripts/Crop%20Vintage%20Mask.md), [Darken background color.md](scripts/Darken%20background%20color.md), [Deconstruct selected elements into new drawing.md](scripts/Deconstruct%20selected%20elements%20into%20new%20drawing.md), [Elbow connectors.md](scripts/Elbow%20connectors.md), [Ellipse Selected Elements.md](scripts/Ellipse%20Selected%20Elements.md), [ExcaliAI.md](scripts/ExcaliAI.md), [Excalidraw Collaboration Frame.md](scripts/Excalidraw%20Collaboration%20Frame.md), [ExcaliMath.md](scripts/ExcaliMath.md), [Expand rectangles horizontally keep text centered.md](scripts/Expand%20rectangles%20horizontally%20keep%20text%20centered.md), [Expand rectangles horizontally.md](scripts/Expand%20rectangles%20horizontally.md), [Expand rectangles vertically keep text centered.md](scripts/Expand%20rectangles%20vertically%20keep%20text%20centered.md), [Expand rectangles vertically.md](scripts/Expand%20rectangles%20vertically.md), [Fixed horizontal distance between centers.md](scripts/Fixed%20horizontal%20distance%20between%20centers.md), [Fixed inner distance.md](scripts/Fixed%20inner%20distance.md), [Fixed spacing.md](scripts/Fixed%20spacing.md), [Fixed vertical distance between centers.md](scripts/Fixed%20vertical%20distance%20between%20centers.md), [Fixed vertical distance.md](scripts/Fixed%20vertical%20distance.md), [Full-Year Calendar Generator.md](scripts/Full-Year%20Calendar%20Generator.md), [Golden Ratio.md](scripts/Golden%20Ratio.md), [Grid Selected Images.md](scripts/Grid%20Selected%20Images.md), [Icon Library.md](scripts/Icon%20Library.md), [Lighten background color.md](scripts/Lighten%20background%20color.md), [Linear Calendar Generator.md](scripts/Linear%20Calendar%20Generator.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Mindmap connector.md](scripts/Mindmap%20connector.md), [Mindmap format.md](scripts/Mindmap%20format.md), [Modify background color opacity.md](scripts/Modify%20background%20color%20opacity.md), [Normalize Selected Arrows.md](scripts/Normalize%20Selected%20Arrows.md), [Organic Line Legacy.md](scripts/Organic%20Line%20Legacy.md), [Organic Line.md](scripts/Organic%20Line.md), [Palette loader.md](scripts/Palette%20loader.md), [Printable Layout Wizard.md](scripts/Printable%20Layout%20Wizard.md), [Relative Font Size Cycle.md](scripts/Relative%20Font%20Size%20Cycle.md), [Rename Image.md](scripts/Rename%20Image.md), [Repeat Elements.md](scripts/Repeat%20Elements.md), [Repeat Texts.md](scripts/Repeat%20Texts.md), [Reset LaTeX Size.md](scripts/Reset%20LaTeX%20Size.md), [Reverse arrows.md](scripts/Reverse%20arrows.md), [Scribble Helper.md](scripts/Scribble%20Helper.md), [Set background color of unclosed line object by adding a shadow clone.md](scripts/Set%20background%20color%20of%20unclosed%20line%20object%20by%20adding%20a%20shadow%20clone.md), [Set Dimensions.md](scripts/Set%20Dimensions.md), [Set Font Family.md](scripts/Set%20Font%20Family.md), [Set Link Alias.md](scripts/Set%20Link%20Alias.md), [Set Stroke Width of Selected Elements.md](scripts/Set%20Stroke%20Width%20of%20Selected%20Elements.md), [Set Text Alignment.md](scripts/Set%20Text%20Alignment.md), [Shade Master.md](scripts/Shade%20Master.md), [Slideshow.md](scripts/Slideshow.md), [Split Ellipse.md](scripts/Split%20Ellipse.md), [Split text by lines.md](scripts/Split%20text%20by%20lines.md), [Text Aura.md](scripts/Text%20Aura.md), [Text to Path.md](scripts/Text%20to%20Path.md), [Text to Sticky Notes.md](scripts/Text%20to%20Sticky%20Notes.md), [To Line.md](scripts/To%20Line.md), [Uniform sizLine truncated
- **addElementsToView**: [Add Connector Point.md](scripts/Add%20Connector%20Point.md), [Add Link to Existing File and Open.md](scripts/Add%20Link%20to%20Existing%20File%20and%20Open.md), [Add Link to New Page and Open.md](scripts/Add%20Link%20to%20New%20Page%20and%20Open.md), [Add Next Step in Process.md](scripts/Add%20Next%20Step%20in%20Process.md), [Auto Layout.md](scripts/Auto%20Layout.md), [Boolean Operations.md](scripts/Boolean%20Operations.md), [Box Each Selected Groups.md](scripts/Box%20Each%20Selected%20Groups.md), [Box Selected Elements.md](scripts/Box%20Selected%20Elements.md), [Capture Note.md](scripts/Capture%20Note.md), [Change shape of selected elements.md](scripts/Change%20shape%20of%20selected%20elements.md), [Comicbook Callout Editor.md](scripts/Comicbook%20Callout%20Editor.md), [Concatenate lines.md](scripts/Concatenate%20lines.md), [Connect elements.md](scripts/Connect%20elements.md), [Convert freedraw to line.md](scripts/Convert%20freedraw%20to%20line.md), [Convert selected text elements to sticky notes.md](scripts/Convert%20selected%20text%20elements%20to%20sticky%20notes.md), [Convert text to link with folder and alias.md](scripts/Convert%20text%20to%20link%20with%20folder%20and%20alias.md), [Create new markdown file and embed into active drawing.md](scripts/Create%20new%20markdown%20file%20and%20embed%20into%20active%20drawing.md), [Crop Vintage Mask.md](scripts/Crop%20Vintage%20Mask.md), [Darken background color.md](scripts/Darken%20background%20color.md), [Deconstruct selected elements into new drawing.md](scripts/Deconstruct%20selected%20elements%20into%20new%20drawing.md), [Elbow connectors.md](scripts/Elbow%20connectors.md), [Ellipse Selected Elements.md](scripts/Ellipse%20Selected%20Elements.md), [ExcaliAI.md](scripts/ExcaliAI.md), [Excalidraw Collaboration Frame.md](scripts/Excalidraw%20Collaboration%20Frame.md), [ExcaliMath.md](scripts/ExcaliMath.md), [Expand rectangles horizontally keep text centered.md](scripts/Expand%20rectangles%20horizontally%20keep%20text%20centered.md), [Expand rectangles horizontally.md](scripts/Expand%20rectangles%20horizontally.md), [Expand rectangles vertically keep text centered.md](scripts/Expand%20rectangles%20vertically%20keep%20text%20centered.md), [Expand rectangles vertically.md](scripts/Expand%20rectangles%20vertically.md), [Fixed horizontal distance between centers.md](scripts/Fixed%20horizontal%20distance%20between%20centers.md), [Fixed inner distance.md](scripts/Fixed%20inner%20distance.md), [Fixed spacing.md](scripts/Fixed%20spacing.md), [Fixed vertical distance between centers.md](scripts/Fixed%20vertical%20distance%20between%20centers.md), [Fixed vertical distance.md](scripts/Fixed%20vertical%20distance.md), [Full-Year Calendar Generator.md](scripts/Full-Year%20Calendar%20Generator.md), [Golden Ratio.md](scripts/Golden%20Ratio.md), [Grid Selected Images.md](scripts/Grid%20Selected%20Images.md), [Icon Library.md](scripts/Icon%20Library.md), [Lighten background color.md](scripts/Lighten%20background%20color.md), [Linear Calendar Generator.md](scripts/Linear%20Calendar%20Generator.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Mindmap connector.md](scripts/Mindmap%20connector.md), [Mindmap format.md](scripts/Mindmap%20format.md), [Modify background color opacity.md](scripts/Modify%20background%20color%20opacity.md), [Normalize Selected Arrows.md](scripts/Normalize%20Selected%20Arrows.md), [Organic Line Legacy.md](scripts/Organic%20Line%20Legacy.md), [Organic Line.md](scripts/Organic%20Line.md), [Palette loader.md](scripts/Palette%20loader.md), [Printable Layout Wizard.md](scripts/Printable%20Layout%20Wizard.md), [Relative Font Size Cycle.md](scripts/Relative%20Font%20Size%20Cycle.md), [Rename Image.md](scripts/Rename%20Image.md), [Repeat Elements.md](scripts/Repeat%20Elements.md), [Repeat Texts.md](scripts/Repeat%20Texts.md), [Reset LaTeX Size.md](scripts/Reset%20LaTeX%20Size.md), [Reverse arrows.md](scripts/Reverse%20arrows.md), [Scribble Helper.md](scripts/Scribble%20Helper.md), [Set background color of unclosed line object by adding a shadow clone.md](scripts/Set%20background%20color%20of%20unclosed%20line%20object%20by%20adding%20a%20shadow%20clone.md), [Set Dimensions.md](scripts/Set%20Dimensions.md), [Set Font Family.md](scripts/Set%20Font%20Family.md), [Set Link Alias.md](scripts/Set%20Link%20Alias.md), [Set Stroke Width of Selected Elements.md](scripts/Set%20Stroke%20Width%20of%20Selected%20Elements.md), [Set Text Alignment.md](scripts/Set%20Text%20Alignment.md), [Shade Master.md](scripts/Shade%20Master.md), [Slideshow.md](scripts/Slideshow.md), [Split Ellipse.md](scripts/Split%20Ellipse.md), [Split text by lines.md](scripts/Split%20text%20by%20lines.md), [Text Aura.md](scripts/Text%20Aura.md), [Text to Path.md](scripts/Text%20to%20Path.md), [Text to Sticky Notes.md](scripts/Text%20to%20Sticky%20Notes.md), [To Line.md](scripts/To%20Line.md), [Uniform size.md](scripts/Uniform%20size.md), [VoronoiDiagramGenerator.mLine truncated
- **addEllipse**: [Add Connector Point.md](scripts/Add%20Connector%20Point.md), [Add Link to Existing File and Open.md](scripts/Add%20Link%20to%20Existing%20File%20and%20Open.md), [Add Link to New Page and Open.md](scripts/Add%20Link%20to%20New%20Page%20and%20Open.md), [Comicbook Callout Editor.md](scripts/Comicbook%20Callout%20Editor.md), [Ellipse Selected Elements.md](scripts/Ellipse%20Selected%20Elements.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md)
- **addEmbeddable**: [Capture Note.md](scripts/Capture%20Note.md), [ExcaliAI.md](scripts/ExcaliAI.md), [Excalidraw Collaboration Frame.md](scripts/Excalidraw%20Collaboration%20Frame.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md)
- **addFrame**: [Capture Note.md](scripts/Capture%20Note.md), [Printable Layout Wizard.md](scripts/Printable%20Layout%20Wizard.md)
- **addImage**: [Capture Note.md](scripts/Capture%20Note.md), [Create DrawIO file.md](scripts/Create%20DrawIO%20file.md), [Create new markdown file and embed into active drawing.md](scripts/Create%20new%20markdown%20file%20and%20embed%20into%20active%20drawing.md), [Deconstruct selected elements into new drawing.md](scripts/Deconstruct%20selected%20elements%20into%20new%20drawing.md), [ExcaliAI.md](scripts/ExcaliAI.md), [Icon Library.md](scripts/Icon%20Library.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md)
- **addImage**: [Capture Note.md](scripts/Capture%20Note.md), [Create new markdown file and embed into active drawing.md](scripts/Create%20new%20markdown%20file%20and%20embed%20into%20active%20drawing.md), [Deconstruct selected elements into new drawing.md](scripts/Deconstruct%20selected%20elements%20into%20new%20drawing.md), [ExcaliAI.md](scripts/ExcaliAI.md), [Icon Library.md](scripts/Icon%20Library.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md)
- **addLaTex**: [ExcaliMath.md](scripts/ExcaliMath.md)
- **addLine**: [Boolean Operations.md](scripts/Boolean%20Operations.md), [Comicbook Callout Editor.md](scripts/Comicbook%20Callout%20Editor.md), [Concatenate lines.md](scripts/Concatenate%20lines.md), [Convert freedraw to line.md](scripts/Convert%20freedraw%20to%20line.md), [Full-Year Calendar Generator.md](scripts/Full-Year%20Calendar%20Generator.md), [Golden Ratio.md](scripts/Golden%20Ratio.md), [Mindmap connector.md](scripts/Mindmap%20connector.md), [Split Ellipse.md](scripts/Split%20Ellipse.md), [Text to Path.md](scripts/Text%20to%20Path.md), [To Line.md](scripts/To%20Line.md)
- **addLine**: [Boolean Operations.md](scripts/Boolean%20Operations.md), [Comicbook Callout Editor.md](scripts/Comicbook%20Callout%20Editor.md), [Concatenate lines.md](scripts/Concatenate%20lines.md), [Convert freedraw to line.md](scripts/Convert%20freedraw%20to%20line.md), [Full-Year Calendar Generator.md](scripts/Full-Year%20Calendar%20Generator.md), [Golden Ratio.md](scripts/Golden%20Ratio.md), [Mindmap connector.md](scripts/Mindmap%20connector.md), [Split Ellipse.md](scripts/Split%20Ellipse.md), [Text to Path.md](scripts/Text%20to%20Path.md), [To Line.md](scripts/To%20Line.md), [VoronoiDiagramGenerator.md](scripts/VoronoiDiagramGenerator.md)
- **addMermaid**: [ExcaliAI.md](scripts/ExcaliAI.md)
- **addRect**: [Box Each Selected Groups.md](scripts/Box%20Each%20Selected%20Groups.md), [Box Selected Elements.md](scripts/Box%20Selected%20Elements.md), [Convert selected text elements to sticky notes.md](scripts/Convert%20selected%20text%20elements%20to%20sticky%20notes.md), [Crop Vintage Mask.md](scripts/Crop%20Vintage%20Mask.md), [ExcaliAI.md](scripts/ExcaliAI.md), [Full-Year Calendar Generator.md](scripts/Full-Year%20Calendar%20Generator.md), [Golden Ratio.md](scripts/Golden%20Ratio.md), [Linear Calendar Generator.md](scripts/Linear%20Calendar%20Generator.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Printable Layout Wizard.md](scripts/Printable%20Layout%20Wizard.md), [Scribble Helper.md](scripts/Scribble%20Helper.md), [Slideshow.md](scripts/Slideshow.md), [Text to Sticky Notes.md](scripts/Text%20to%20Sticky%20Notes.md)
- **addText**: [Add Next Step in Process.md](scripts/Add%20Next%20Step%20in%20Process.md), [Capture Note.md](scripts/Capture%20Note.md), [Comicbook Callout Editor.md](scripts/Comicbook%20Callout%20Editor.md), [ExcaliAI.md](scripts/ExcaliAI.md), [Full-Year Calendar Generator.md](scripts/Full-Year%20Calendar%20Generator.md), [Linear Calendar Generator.md](scripts/Linear%20Calendar%20Generator.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Scribble Helper.md](scripts/Scribble%20Helper.md), [Split text by lines.md](scripts/Split%20text%20by%20lines.md), [Text to Path.md](scripts/Text%20to%20Path.md), [Text to Sticky Notes.md](scripts/Text%20to%20Sticky%20Notes.md)
- **addToGroup**: [Add Connector Point.md](scripts/Add%20Connector%20Point.md), [Add Link to Existing File and Open.md](scripts/Add%20Link%20to%20Existing%20File%20and%20Open.md), [Add Link to New Page and Open.md](scripts/Add%20Link%20to%20New%20Page%20and%20Open.md), [Boolean Operations.md](scripts/Boolean%20Operations.md), [Box Each Selected Groups.md](scripts/Box%20Each%20Selected%20Groups.md), [Box Selected Elements.md](scripts/Box%20Selected%20Elements.md), [Comicbook Callout Editor.md](scripts/Comicbook%20Callout%20Editor.md), [Ellipse Selected Elements.md](scripts/Ellipse%20Selected%20Elements.md), [ExcaliAI.md](scripts/ExcaliAI.md), [ExcaliMath.md](scripts/ExcaliMath.md), [Golden Ratio.md](scripts/Golden%20Ratio.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Set background color of unclosed line object by adding a shadow clone.md](scripts/Set%20background%20color%20of%20unclosed%20line%20object%20by%20adding%20a%20shadow%20clone.md), [Text Aura.md](scripts/Text%20Aura.md), [Text to Path.md](scripts/Text%20to%20Path.md)
- **addToGroup**: [Add Connector Point.md](scripts/Add%20Connector%20Point.md), [Add Link to Existing File and Open.md](scripts/Add%20Link%20to%20Existing%20File%20and%20Open.md), [Add Link to New Page and Open.md](scripts/Add%20Link%20to%20New%20Page%20and%20Open.md), [Boolean Operations.md](scripts/Boolean%20Operations.md), [Box Each Selected Groups.md](scripts/Box%20Each%20Selected%20Groups.md), [Box Selected Elements.md](scripts/Box%20Selected%20Elements.md), [Comicbook Callout Editor.md](scripts/Comicbook%20Callout%20Editor.md), [Ellipse Selected Elements.md](scripts/Ellipse%20Selected%20Elements.md), [ExcaliAI.md](scripts/ExcaliAI.md), [ExcaliMath.md](scripts/ExcaliMath.md), [Golden Ratio.md](scripts/Golden%20Ratio.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Set background color of unclosed line object by adding a shadow clone.md](scripts/Set%20background%20color%20of%20unclosed%20line%20object%20by%20adding%20a%20shadow%20clone.md), [Text Aura.md](scripts/Text%20Aura.md), [Text to Path.md](scripts/Text%20to%20Path.md), [VoronoiDiagramGenerator.md](scripts/VoronoiDiagramGenerator.md)
- **analyzeAIImage**: [ExcaliAI.md](scripts/ExcaliAI.md)
- **attachInlineLinkSuggester**: [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md)
- **canvas**: [Comicbook Callout Editor.md](scripts/Comicbook%20Callout%20Editor.md)
- **checkAndCreateFolder**: [Capture Note.md](scripts/Capture%20Note.md)
- **checkForActiveSidepanelTabForScript**: [Comicbook Callout Editor.md](scripts/Comicbook%20Callout%20Editor.md), [ExcaliMath.md](scripts/ExcaliMath.md), [Icon Library.md](scripts/Icon%20Library.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Shade Master.md](scripts/Shade%20Master.md)
- **clear**: [Capture Note.md](scripts/Capture%20Note.md), [Comicbook Callout Editor.md](scripts/Comicbook%20Callout%20Editor.md), [ExcaliAI.md](scripts/ExcaliAI.md), [ExcaliMath.md](scripts/ExcaliMath.md), [Icon Library.md](scripts/Icon%20Library.md), [Image Occlusion.md](scripts/Image%20Occlusion.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Printable Layout Wizard.md](scripts/Printable%20Layout%20Wizard.md), [Scribble Helper.md](scripts/Scribble%20Helper.md), [Shade Master.md](scripts/Shade%20Master.md), [Slideshow.md](scripts/Slideshow.md), [Text to Path.md](scripts/Text%20to%20Path.md)
- **clear**: [Capture Note.md](scripts/Capture%20Note.md), [Comicbook Callout Editor.md](scripts/Comicbook%20Callout%20Editor.md), [ExcaliAI.md](scripts/ExcaliAI.md), [ExcaliMath.md](scripts/ExcaliMath.md), [Icon Library.md](scripts/Icon%20Library.md), [Image Occlusion.md](scripts/Image%20Occlusion.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Printable Layout Wizard.md](scripts/Printable%20Layout%20Wizard.md), [Scribble Helper.md](scripts/Scribble%20Helper.md), [Shade Master.md](scripts/Shade%20Master.md), [Slideshow.md](scripts/Slideshow.md), [Text to Path.md](scripts/Text%20to%20Path.md), [VoronoiDiagramGenerator.md](scripts/VoronoiDiagramGenerator.md)
- **cloneElement**: [Repeat Elements.md](scripts/Repeat%20Elements.md), [Repeat Texts.md](scripts/Repeat%20Texts.md), [Set background color of unclosed line object by adding a shadow clone.md](scripts/Set%20background%20color%20of%20unclosed%20line%20object%20by%20adding%20a%20shadow%20clone.md), [Slideshow.md](scripts/Slideshow.md), [Text Aura.md](scripts/Text%20Aura.md)
- **cloneElements**: [Capture Note.md](scripts/Capture%20Note.md)
- **colorNameToHex**: [Darken background color.md](scripts/Darken%20background%20color.md), [Lighten background color.md](scripts/Lighten%20background%20color.md), [Repeat Elements.md](scripts/Repeat%20Elements.md)
@@ -46,10 +46,10 @@ This index maps methods and properties from ExcalidrawAutomate (`ea`), Excalidra
- **formatAIUsageLabel**: [ExcaliAI.md](scripts/ExcaliAI.md)
- **generateAIImage**: [ExcaliAI.md](scripts/ExcaliAI.md)
- **generateAIText**: [ExcaliAI.md](scripts/ExcaliAI.md)
- **generateElementId**: [Capture Note.md](scripts/Capture%20Note.md), [Create DrawIO file.md](scripts/Create%20DrawIO%20file.md), [Crop Vintage Mask.md](scripts/Crop%20Vintage%20Mask.md), [ExcaliMath.md](scripts/ExcaliMath.md), [Image Occlusion.md](scripts/Image%20Occlusion.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Text to Path.md](scripts/Text%20to%20Path.md)
- **generateElementId**: [Capture Note.md](scripts/Capture%20Note.md), [Crop Vintage Mask.md](scripts/Crop%20Vintage%20Mask.md), [ExcaliMath.md](scripts/ExcaliMath.md), [Image Occlusion.md](scripts/Image%20Occlusion.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Text to Path.md](scripts/Text%20to%20Path.md)
- **getAISettings**: [ExcaliAI.md](scripts/ExcaliAI.md)
- **getAPI**: [Capture Note.md](scripts/Capture%20Note.md)
- **getAttachmentFilepath**: [Create DrawIO file.md](scripts/Create%20DrawIO%20file.md), [Excalidraw Writing Machine.md](scripts/Excalidraw%20Writing%20Machine.md)
- **getAttachmentFilepath**: [Excalidraw Writing Machine.md](scripts/Excalidraw%20Writing%20Machine.md)
- **getBoundingBox**: [Add Link to Existing File and Open.md](scripts/Add%20Link%20to%20Existing%20File%20and%20Open.md), [Add Link to New Page and Open.md](scripts/Add%20Link%20to%20New%20Page%20and%20Open.md), [Auto Layout.md](scripts/Auto%20Layout.md), [Box Each Selected Groups.md](scripts/Box%20Each%20Selected%20Groups.md), [Box Selected Elements.md](scripts/Box%20Selected%20Elements.md), [Capture Note.md](scripts/Capture%20Note.md), [Deconstruct selected elements into new drawing.md](scripts/Deconstruct%20selected%20elements%20into%20new%20drawing.md), [Ellipse Selected Elements.md](scripts/Ellipse%20Selected%20Elements.md), [ExcaliAI.md](scripts/ExcaliAI.md), [ExcaliMath.md](scripts/ExcaliMath.md), [Grid Selected Images.md](scripts/Grid%20Selected%20Images.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Printable Layout Wizard.md](scripts/Printable%20Layout%20Wizard.md), [Slideshow.md](scripts/Slideshow.md)
- **getBoundTextElement**: [Capture Note.md](scripts/Capture%20Note.md), [Excalidraw Writing Machine.md](scripts/Excalidraw%20Writing%20Machine.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md)
- **getCM**: [Comicbook Callout Editor.md](scripts/Comicbook%20Callout%20Editor.md), [Darken background color.md](scripts/Darken%20background%20color.md), [Invert colors.md](scripts/Invert%20colors.md), [Lighten background color.md](scripts/Lighten%20background%20color.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Palette loader.md](scripts/Palette%20loader.md), [Repeat Elements.md](scripts/Repeat%20Elements.md), [Shade Master.md](scripts/Shade%20Master.md), [Text Aura.md](scripts/Text%20Aura.md)
@@ -71,7 +71,7 @@ This index maps methods and properties from ExcalidrawAutomate (`ea`), Excalidra
- **getPathForImageFileId**: [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md)
- **getPolyBool**: [Boolean Operations.md](scripts/Boolean%20Operations.md)
- **getSceneFromFile**: [Palette loader.md](scripts/Palette%20loader.md)
- **getScriptSettings**: [Add Link to Existing File and Open.md](scripts/Add%20Link%20to%20Existing%20File%20and%20Open.md), [Add Link to New Page and Open.md](scripts/Add%20Link%20to%20New%20Page%20and%20Open.md), [Add Next Step in Process.md](scripts/Add%20Next%20Step%20in%20Process.md), [Auto Layout.md](scripts/Auto%20Layout.md), [Box Each Selected Groups.md](scripts/Box%20Each%20Selected%20Groups.md), [Box Selected Elements.md](scripts/Box%20Selected%20Elements.md), [Capture Note.md](scripts/Capture%20Note.md), [Comicbook Callout Editor.md](scripts/Comicbook%20Callout%20Editor.md), [Connect elements.md](scripts/Connect%20elements.md), [Convert freedraw to line.md](scripts/Convert%20freedraw%20to%20line.md), [Convert selected text elements to sticky notes.md](scripts/Convert%20selected%20text%20elements%20to%20sticky%20notes.md), [Darken background color.md](scripts/Darken%20background%20color.md), [Deconstruct selected elements into new drawing.md](scripts/Deconstruct%20selected%20elements%20into%20new%20drawing.md), [Ellipse Selected Elements.md](scripts/Ellipse%20Selected%20Elements.md), [ExcaliAI.md](scripts/ExcaliAI.md), [Excalidraw Writing Machine.md](scripts/Excalidraw%20Writing%20Machine.md), [ExcaliMath.md](scripts/ExcaliMath.md), [Fixed horizontal distance between centers.md](scripts/Fixed%20horizontal%20distance%20between%20centers.md), [Fixed inner distance.md](scripts/Fixed%20inner%20distance.md), [Fixed spacing.md](scripts/Fixed%20spacing.md), [Fixed vertical distance between centers.md](scripts/Fixed%20vertical%20distance%20between%20centers.md), [Fixed vertical distance.md](scripts/Fixed%20vertical%20distance.md), [Golden Ratio.md](scripts/Golden%20Ratio.md), [Icon Library.md](scripts/Icon%20Library.md), [Image Occlusion.md](scripts/Image%20Occlusion.md), [Lighten background color.md](scripts/Lighten%20background%20color.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Mindmap format.md](scripts/Mindmap%20format.md), [Modify background color opacity.md](scripts/Modify%20background%20color%20opacity.md), [Normalize Selected Arrows.md](scripts/Normalize%20Selected%20Arrows.md), [Palette loader.md](scripts/Palette%20loader.md), [Palm Guard.md](scripts/Palm%20Guard.md), [Printable Layout Wizard.md](scripts/Printable%20Layout%20Wizard.md), [Scribble Helper.md](scripts/Scribble%20Helper.md), [Set background color of unclosed line object by adding a shadow clone.md](scripts/Set%20background%20color%20of%20unclosed%20line%20object%20by%20adding%20a%20shadow%20clone.md), [Shade Master.md](scripts/Shade%20Master.md), [Text to Sticky Notes.md](scripts/Text%20to%20Sticky%20Notes.md)
- **getScriptSettings**: [Add Link to Existing File and Open.md](scripts/Add%20Link%20to%20Existing%20File%20and%20Open.md), [Add Link to New Page and Open.md](scripts/Add%20Link%20to%20New%20Page%20and%20Open.md), [Add Next Step in Process.md](scripts/Add%20Next%20Step%20in%20Process.md), [Auto Layout.md](scripts/Auto%20Layout.md), [Box Each Selected Groups.md](scripts/Box%20Each%20Selected%20Groups.md), [Box Selected Elements.md](scripts/Box%20Selected%20Elements.md), [Capture Note.md](scripts/Capture%20Note.md), [Comicbook Callout Editor.md](scripts/Comicbook%20Callout%20Editor.md), [Connect elements.md](scripts/Connect%20elements.md), [Convert freedraw to line.md](scripts/Convert%20freedraw%20to%20line.md), [Convert selected text elements to sticky notes.md](scripts/Convert%20selected%20text%20elements%20to%20sticky%20notes.md), [Darken background color.md](scripts/Darken%20background%20color.md), [Deconstruct selected elements into new drawing.md](scripts/Deconstruct%20selected%20elements%20into%20new%20drawing.md), [Ellipse Selected Elements.md](scripts/Ellipse%20Selected%20Elements.md), [ExcaliAI.md](scripts/ExcaliAI.md), [Excalidraw Writing Machine.md](scripts/Excalidraw%20Writing%20Machine.md), [ExcaliMath.md](scripts/ExcaliMath.md), [Fixed horizontal distance between centers.md](scripts/Fixed%20horizontal%20distance%20between%20centers.md), [Fixed inner distance.md](scripts/Fixed%20inner%20distance.md), [Fixed spacing.md](scripts/Fixed%20spacing.md), [Fixed vertical distance between centers.md](scripts/Fixed%20vertical%20distance%20between%20centers.md), [Fixed vertical distance.md](scripts/Fixed%20vertical%20distance.md), [Golden Ratio.md](scripts/Golden%20Ratio.md), [Icon Library.md](scripts/Icon%20Library.md), [Image Occlusion.md](scripts/Image%20Occlusion.md), [Lighten background color.md](scripts/Lighten%20background%20color.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Mindmap format.md](scripts/Mindmap%20format.md), [Modify background color opacity.md](scripts/Modify%20background%20color%20opacity.md), [Normalize Selected Arrows.md](scripts/Normalize%20Selected%20Arrows.md), [Palette loader.md](scripts/Palette%20loader.md), [Palm Guard.md](scripts/Palm%20Guard.md), [Printable Layout Wizard.md](scripts/Printable%20Layout%20Wizard.md), [Scribble Helper.md](scripts/Scribble%20Helper.md), [Set background color of unclosed line object by adding a shadow clone.md](scripts/Set%20background%20color%20of%20unclosed%20line%20object%20by%20adding%20a%20shadow%20clone.md), [Shade Master.md](scripts/Shade%20Master.md), [Text to Sticky Notes.md](scripts/Text%20to%20Sticky%20Notes.md), [VoronoiDiagramGenerator.md](scripts/VoronoiDiagramGenerator.md)
- **getScriptSettingValue**: [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md)
- **getSidepanelLeaf**: [Capture Note.md](scripts/Capture%20Note.md), [Icon Library.md](scripts/Icon%20Library.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md)
- **getSVGColorInfoForImgElement**: [Shade Master.md](scripts/Shade%20Master.md)
@@ -79,7 +79,7 @@ This index maps methods and properties from ExcalidrawAutomate (`ea`), Excalidra
- **getViewElements**: [Auto Layout.md](scripts/Auto%20Layout.md), [Box Each Selected Groups.md](scripts/Box%20Each%20Selected%20Groups.md), [Capture Note.md](scripts/Capture%20Note.md), [Comicbook Callout Editor.md](scripts/Comicbook%20Callout%20Editor.md), [Convert selected text elements to sticky notes.md](scripts/Convert%20selected%20text%20elements%20to%20sticky%20notes.md), [Crop Vintage Mask.md](scripts/Crop%20Vintage%20Mask.md), [Elbow connectors.md](scripts/Elbow%20connectors.md), [ExcaliAI.md](scripts/ExcaliAI.md), [Excalidraw Writing Machine.md](scripts/Excalidraw%20Writing%20Machine.md), [ExcaliMath.md](scripts/ExcaliMath.md), [Expand rectangles horizontally keep text centered.md](scripts/Expand%20rectangles%20horizontally%20keep%20text%20centered.md), [Expand rectangles horizontally.md](scripts/Expand%20rectangles%20horizontally.md), [Expand rectangles vertically keep text centered.md](scripts/Expand%20rectangles%20vertically%20keep%20text%20centered.md), [Expand rectangles vertically.md](scripts/Expand%20rectangles%20vertically.md), [Golden Ratio.md](scripts/Golden%20Ratio.md), [Icon Library.md](scripts/Icon%20Library.md), [Invert colors.md](scripts/Invert%20colors.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Normalize Selected Arrows.md](scripts/Normalize%20Selected%20Arrows.md), [Organic Line Legacy.md](scripts/Organic%20Line%20Legacy.md), [Organic Line.md](scripts/Organic%20Line.md), [Palette loader.md](scripts/Palette%20loader.md), [Printable Layout Wizard.md](scripts/Printable%20Layout%20Wizard.md), [Scribble Helper.md](scripts/Scribble%20Helper.md), [Select Elements of Type.md](scripts/Select%20Elements%20of%20Type.md), [Select Similar Elements.md](scripts/Select%20Similar%20Elements.md), [Set background color of unclosed line object by adding a shadow clone.md](scripts/Set%20background%20color%20of%20unclosed%20line%20object%20by%20adding%20a%20shadow%20clone.md), [Slideshow.md](scripts/Slideshow.md), [Split Ellipse.md](scripts/Split%20Ellipse.md), [Text to Path.md](scripts/Text%20to%20Path.md), [Text to Sticky Notes.md](scripts/Text%20to%20Sticky%20Notes.md), [Uniform size.md](scripts/Uniform%20size.md)
- **getViewFileForImageElement**: [Excalidraw Writing Machine.md](scripts/Excalidraw%20Writing%20Machine.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [PDF Page Text to Clipboard.md](scripts/PDF%20Page%20Text%20to%20Clipboard.md), [Shade Master.md](scripts/Shade%20Master.md)
- **getViewSelectedElement**: [Capture Note.md](scripts/Capture%20Note.md), [Copy Selected Element Styles to Global.md](scripts/Copy%20Selected%20Element%20Styles%20to%20Global.md), [Golden Ratio.md](scripts/Golden%20Ratio.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Select Similar Elements.md](scripts/Select%20Similar%20Elements.md), [Set Stroke Width of Selected Elements.md](scripts/Set%20Stroke%20Width%20of%20Selected%20Elements.md), [Slideshow.md](scripts/Slideshow.md), [To Line.md](scripts/To%20Line.md)
- **getViewSelectedElements**: [Add Connector Point.md](scripts/Add%20Connector%20Point.md), [Add Link to Existing File and Open.md](scripts/Add%20Link%20to%20Existing%20File%20and%20Open.md), [Add Link to New Page and Open.md](scripts/Add%20Link%20to%20New%20Page%20and%20Open.md), [Add Next Step in Process.md](scripts/Add%20Next%20Step%20in%20Process.md), [Auto Layout.md](scripts/Auto%20Layout.md), [Boolean Operations.md](scripts/Boolean%20Operations.md), [Box Each Selected Groups.md](scripts/Box%20Each%20Selected%20Groups.md), [Box Selected Elements.md](scripts/Box%20Selected%20Elements.md), [Capture Note.md](scripts/Capture%20Note.md), [Change shape of selected elements.md](scripts/Change%20shape%20of%20selected%20elements.md), [Comicbook Callout Editor.md](scripts/Comicbook%20Callout%20Editor.md), [Concatenate lines.md](scripts/Concatenate%20lines.md), [Connect elements.md](scripts/Connect%20elements.md), [Convert freedraw to line.md](scripts/Convert%20freedraw%20to%20line.md), [Convert text to link with folder and alias.md](scripts/Convert%20text%20to%20link%20with%20folder%20and%20alias.md), [Deconstruct selected elements into new drawing.md](scripts/Deconstruct%20selected%20elements%20into%20new%20drawing.md), [Elbow connectors.md](scripts/Elbow%20connectors.md), [Ellipse Selected Elements.md](scripts/Ellipse%20Selected%20Elements.md), [ExcaliAI.md](scripts/ExcaliAI.md), [Excalidraw Writing Machine.md](scripts/Excalidraw%20Writing%20Machine.md), [ExcaliMath.md](scripts/ExcaliMath.md), [Expand rectangles horizontally keep text centered.md](scripts/Expand%20rectangles%20horizontally%20keep%20text%20centered.md), [Expand rectangles horizontally.md](scripts/Expand%20rectangles%20horizontally.md), [Expand rectangles vertically keep text centered.md](scripts/Expand%20rectangles%20vertically%20keep%20text%20centered.md), [Expand rectangles vertically.md](scripts/Expand%20rectangles%20vertically.md), [Fixed horizontal distance between centers.md](scripts/Fixed%20horizontal%20distance%20between%20centers.md), [Fixed inner distance.md](scripts/Fixed%20inner%20distance.md), [Fixed spacing.md](scripts/Fixed%20spacing.md), [Fixed vertical distance between centers.md](scripts/Fixed%20vertical%20distance%20between%20centers.md), [Fixed vertical distance.md](scripts/Fixed%20vertical%20distance.md), [Full-Year Calendar Generator.md](scripts/Full-Year%20Calendar%20Generator.md), [Golden Ratio.md](scripts/Golden%20Ratio.md), [Grid Selected Images.md](scripts/Grid%20Selected%20Images.md), [Image Occlusion.md](scripts/Image%20Occlusion.md), [Linear Calendar Generator.md](scripts/Linear%20Calendar%20Generator.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Mindmap connector.md](scripts/Mindmap%20connector.md), [Mindmap format.md](scripts/Mindmap%20format.md), [Modify background color opacity.md](scripts/Modify%20background%20color%20opacity.md), [Normalize Selected Arrows.md](scripts/Normalize%20Selected%20Arrows.md), [Organic Line Legacy.md](scripts/Organic%20Line%20Legacy.md), [Organic Line.md](scripts/Organic%20Line.md), [Palette loader.md](scripts/Palette%20loader.md), [PDF Page Text to Clipboard.md](scripts/PDF%20Page%20Text%20to%20Clipboard.md), [Printable Layout Wizard.md](scripts/Printable%20Layout%20Wizard.md), [Relative Font Size Cycle.md](scripts/Relative%20Font%20Size%20Cycle.md), [Rename Image.md](scripts/Rename%20Image.md), [Repeat Elements.md](scripts/Repeat%20Elements.md), [Repeat Texts.md](scripts/Repeat%20Texts.md), [Reset LaTeX Size.md](scripts/Reset%20LaTeX%20Size.md), [Reverse arrows.md](scripts/Reverse%20arrows.md), [Scribble Helper.md](scripts/Scribble%20Helper.md), [Select Elements of Type.md](scripts/Select%20Elements%20of%20Type.md), [Select Similar Elements.md](scripts/Select%20Similar%20Elements.md), [Set background color of unclosed line object by adding a shadow clone.md](scripts/Set%20background%20color%20of%20unclosed%20line%20object%20by%20adding%20a%20shadow%20clone.md), [Set Dimensions.md](scripts/Set%20Dimensions.md), [Set Font Family.md](scripts/Set%20Font%20Family.md), [Set Link Alias.md](scripts/Set%20Link%20Alias.md), [Set Stroke Width of Selected Elements.md](scripts/Set%20Stroke%20Width%20of%20Selected%20Elements.md), [Set Text Alignment.md](scripts/Set%20Text%20Alignment.md), [Shade Master.md](scripts/Shade%20Master.md), [Split Ellipse.md](scripts/Split%20Ellipse.md), [Split text by lines.md](scripts/Split%20text%20by%20lines.md), [Text Aura.md](scripts/Text%20Aura.md), [Text to Path.md](scripts/Text%20to%20Path.md), [Text to Sticky Notes.md](scripts/Text%20to%20Sticky%20Notes.md), [Uniform size.md](scripts/Uniform%20size.md), [Zoom to Fit Selected Elements.md](scripts/Zoom%20to%20Fit%20Selected%20Elements.md)
- **getViewSelectedElements**: [Add Connector Point.md](scripts/Add%20Connector%20Point.md), [Add Link to Existing File and Open.md](scripts/Add%20Link%20to%20Existing%20File%20and%20Open.md), [Add Link to New Page and Open.md](scripts/Add%20Link%20to%20New%20Page%20and%20Open.md), [Add Next Step in Process.md](scripts/Add%20Next%20Step%20in%20Process.md), [Auto Layout.md](scripts/Auto%20Layout.md), [Boolean Operations.md](scripts/Boolean%20Operations.md), [Box Each Selected Groups.md](scripts/Box%20Each%20Selected%20Groups.md), [Box Selected Elements.md](scripts/Box%20Selected%20Elements.md), [Capture Note.md](scripts/Capture%20Note.md), [Change shape of selected elements.md](scripts/Change%20shape%20of%20selected%20elements.md), [Comicbook Callout Editor.md](scripts/Comicbook%20Callout%20Editor.md), [Concatenate lines.md](scripts/Concatenate%20lines.md), [Connect elements.md](scripts/Connect%20elements.md), [Convert freedraw to line.md](scripts/Convert%20freedraw%20to%20line.md), [Convert text to link with folder and alias.md](scripts/Convert%20text%20to%20link%20with%20folder%20and%20alias.md), [Deconstruct selected elements into new drawing.md](scripts/Deconstruct%20selected%20elements%20into%20new%20drawing.md), [Elbow connectors.md](scripts/Elbow%20connectors.md), [Ellipse Selected Elements.md](scripts/Ellipse%20Selected%20Elements.md), [ExcaliAI.md](scripts/ExcaliAI.md), [Excalidraw Writing Machine.md](scripts/Excalidraw%20Writing%20Machine.md), [ExcaliMath.md](scripts/ExcaliMath.md), [Expand rectangles horizontally keep text centered.md](scripts/Expand%20rectangles%20horizontally%20keep%20text%20centered.md), [Expand rectangles horizontally.md](scripts/Expand%20rectangles%20horizontally.md), [Expand rectangles vertically keep text centered.md](scripts/Expand%20rectangles%20vertically%20keep%20text%20centered.md), [Expand rectangles vertically.md](scripts/Expand%20rectangles%20vertically.md), [Fixed horizontal distance between centers.md](scripts/Fixed%20horizontal%20distance%20between%20centers.md), [Fixed inner distance.md](scripts/Fixed%20inner%20distance.md), [Fixed spacing.md](scripts/Fixed%20spacing.md), [Fixed vertical distance between centers.md](scripts/Fixed%20vertical%20distance%20between%20centers.md), [Fixed vertical distance.md](scripts/Fixed%20vertical%20distance.md), [Full-Year Calendar Generator.md](scripts/Full-Year%20Calendar%20Generator.md), [Golden Ratio.md](scripts/Golden%20Ratio.md), [Grid Selected Images.md](scripts/Grid%20Selected%20Images.md), [Image Occlusion.md](scripts/Image%20Occlusion.md), [Linear Calendar Generator.md](scripts/Linear%20Calendar%20Generator.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Mindmap connector.md](scripts/Mindmap%20connector.md), [Mindmap format.md](scripts/Mindmap%20format.md), [Modify background color opacity.md](scripts/Modify%20background%20color%20opacity.md), [Normalize Selected Arrows.md](scripts/Normalize%20Selected%20Arrows.md), [Organic Line Legacy.md](scripts/Organic%20Line%20Legacy.md), [Organic Line.md](scripts/Organic%20Line.md), [Palette loader.md](scripts/Palette%20loader.md), [PDF Page Text to Clipboard.md](scripts/PDF%20Page%20Text%20to%20Clipboard.md), [Printable Layout Wizard.md](scripts/Printable%20Layout%20Wizard.md), [Relative Font Size Cycle.md](scripts/Relative%20Font%20Size%20Cycle.md), [Rename Image.md](scripts/Rename%20Image.md), [Repeat Elements.md](scripts/Repeat%20Elements.md), [Repeat Texts.md](scripts/Repeat%20Texts.md), [Reset LaTeX Size.md](scripts/Reset%20LaTeX%20Size.md), [Reverse arrows.md](scripts/Reverse%20arrows.md), [Scribble Helper.md](scripts/Scribble%20Helper.md), [Select Elements of Type.md](scripts/Select%20Elements%20of%20Type.md), [Select Similar Elements.md](scripts/Select%20Similar%20Elements.md), [Set background color of unclosed line object by adding a shadow clone.md](scripts/Set%20background%20color%20of%20unclosed%20line%20object%20by%20adding%20a%20shadow%20clone.md), [Set Dimensions.md](scripts/Set%20Dimensions.md), [Set Font Family.md](scripts/Set%20Font%20Family.md), [Set Link Alias.md](scripts/Set%20Link%20Alias.md), [Set Stroke Width of Selected Elements.md](scripts/Set%20Stroke%20Width%20of%20Selected%20Elements.md), [Set Text Alignment.md](scripts/Set%20Text%20Alignment.md), [Shade Master.md](scripts/Shade%20Master.md), [Split Ellipse.md](scripts/Split%20Ellipse.md), [Split text by lines.md](scripts/Split%20text%20by%20lines.md), [Text Aura.md](scripts/Text%20Aura.md), [Text to Path.md](scripts/Text%20to%20Path.md), [Text to Sticky Notes.md](scripts/Text%20to%20Sticky%20Notes.md), [Uniform size.md](scripts/Uniform%20size.md), [VoronoiDiagramGenerator.md](scripts/VoronoiDiagramGenerator.md), [Zoom to Fit Selected Elements.md](scripts/Zoom%20to%20Fit%20Selected%20Elements.md)
- **imagesDict**: [Deconstruct selected elements into new drawing.md](scripts/Deconstruct%20selected%20elements%20into%20new%20drawing.md), [Image Occlusion.md](scripts/Image%20Occlusion.md)
- **importSVG**: [ExcaliAI.md](scripts/ExcaliAI.md)
- **intersectElementWithLine**: [Auto Layout.md](scripts/Auto%20Layout.md), [Box Each Selected Groups.md](scripts/Box%20Each%20Selected%20Groups.md), [Expand rectangles horizontally keep text centered.md](scripts/Expand%20rectangles%20horizontally%20keep%20text%20centered.md), [Expand rectangles horizontally.md](scripts/Expand%20rectangles%20horizontally.md), [Expand rectangles vertically keep text centered.md](scripts/Expand%20rectangles%20vertically%20keep%20text%20centered.md), [Expand rectangles vertically.md](scripts/Expand%20rectangles%20vertically.md), [Normalize Selected Arrows.md](scripts/Normalize%20Selected%20Arrows.md)
@@ -90,7 +90,7 @@ This index maps methods and properties from ExcalidrawAutomate (`ea`), Excalidra
- **measureText**: [Add Next Step in Process.md](scripts/Add%20Next%20Step%20in%20Process.md), [Capture Note.md](scripts/Capture%20Note.md), [Comicbook Callout Editor.md](scripts/Comicbook%20Callout%20Editor.md), [Golden Ratio.md](scripts/Golden%20Ratio.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Text to Path.md](scripts/Text%20to%20Path.md)
- **Modal**: [Image Occlusion.md](scripts/Image%20Occlusion.md)
- **moveViewElementToZIndex**: [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Organic Line Legacy.md](scripts/Organic%20Line%20Legacy.md), [Organic Line.md](scripts/Organic%20Line.md), [Set background color of unclosed line object by adding a shadow clone.md](scripts/Set%20background%20color%20of%20unclosed%20line%20object%20by%20adding%20a%20shadow%20clone.md)
- **obsidian**: [Capture Note.md](scripts/Capture%20Note.md), [Comicbook Callout Editor.md](scripts/Comicbook%20Callout%20Editor.md), [Deconstruct selected elements into new drawing.md](scripts/Deconstruct%20selected%20elements%20into%20new%20drawing.md), [ExcaliAI.md](scripts/ExcaliAI.md), [ExcaliMath.md](scripts/ExcaliMath.md), [Golden Ratio.md](scripts/Golden%20Ratio.md), [Icon Library.md](scripts/Icon%20Library.md), [Image Occlusion.md](scripts/Image%20Occlusion.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Palm Guard.md](scripts/Palm%20Guard.md), [Printable Layout Wizard.md](scripts/Printable%20Layout%20Wizard.md), [Scribble Helper.md](scripts/Scribble%20Helper.md), [Select Similar Elements.md](scripts/Select%20Similar%20Elements.md), [Set Grid.md](scripts/Set%20Grid.md), [Shade Master.md](scripts/Shade%20Master.md), [Slideshow.md](scripts/Slideshow.md), [Text to Path.md](scripts/Text%20to%20Path.md)
- **obsidian**: [Capture Note.md](scripts/Capture%20Note.md), [Comicbook Callout Editor.md](scripts/Comicbook%20Callout%20Editor.md), [Deconstruct selected elements into new drawing.md](scripts/Deconstruct%20selected%20elements%20into%20new%20drawing.md), [ExcaliAI.md](scripts/ExcaliAI.md), [ExcaliMath.md](scripts/ExcaliMath.md), [Golden Ratio.md](scripts/Golden%20Ratio.md), [Icon Library.md](scripts/Icon%20Library.md), [Image Occlusion.md](scripts/Image%20Occlusion.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Palm Guard.md](scripts/Palm%20Guard.md), [Printable Layout Wizard.md](scripts/Printable%20Layout%20Wizard.md), [Scribble Helper.md](scripts/Scribble%20Helper.md), [Select Similar Elements.md](scripts/Select%20Similar%20Elements.md), [Set Grid.md](scripts/Set%20Grid.md), [Shade Master.md](scripts/Shade%20Master.md), [Slideshow.md](scripts/Slideshow.md), [Text to Path.md](scripts/Text%20to%20Path.md), [VoronoiDiagramGenerator.md](scripts/VoronoiDiagramGenerator.md)
- **onLinkClickHook**: [Slideshow.md](scripts/Slideshow.md)
- **onSceneChangeHook**: [Comicbook Callout Editor.md](scripts/Comicbook%20Callout%20Editor.md), [ExcaliMath.md](scripts/ExcaliMath.md), [Shade Master.md](scripts/Shade%20Master.md)
- **openFileInNewOrAdjacentLeaf**: [Add Link to Existing File and Open.md](scripts/Add%20Link%20to%20Existing%20File%20and%20Open.md), [Add Link to New Page and Open.md](scripts/Add%20Link%20to%20New%20Page%20and%20Open.md), [Capture Note.md](scripts/Capture%20Note.md), [Deconstruct selected elements into new drawing.md](scripts/Deconstruct%20selected%20elements%20into%20new%20drawing.md), [Excalidraw Writing Machine.md](scripts/Excalidraw%20Writing%20Machine.md)
@@ -100,7 +100,7 @@ This index maps methods and properties from ExcalidrawAutomate (`ea`), Excalidra
- **reset**: [Full-Year Calendar Generator.md](scripts/Full-Year%20Calendar%20Generator.md)
- **saveScriptSettings**: [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md)
- **selectElementsInView**: [Add Link to Existing File and Open.md](scripts/Add%20Link%20to%20Existing%20File%20and%20Open.md), [Add Link to New Page and Open.md](scripts/Add%20Link%20to%20New%20Page%20and%20Open.md), [Add Next Step in Process.md](scripts/Add%20Next%20Step%20in%20Process.md), [Capture Note.md](scripts/Capture%20Note.md), [Comicbook Callout Editor.md](scripts/Comicbook%20Callout%20Editor.md), [Convert freedraw to line.md](scripts/Convert%20freedraw%20to%20line.md), [Convert selected text elements to sticky notes.md](scripts/Convert%20selected%20text%20elements%20to%20sticky%20notes.md), [ExcaliMath.md](scripts/ExcaliMath.md), [Golden Ratio.md](scripts/Golden%20Ratio.md), [Icon Library.md](scripts/Icon%20Library.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Organic Line Legacy.md](scripts/Organic%20Line%20Legacy.md), [Organic Line.md](scripts/Organic%20Line.md), [Printable Layout Wizard.md](scripts/Printable%20Layout%20Wizard.md), [Scribble Helper.md](scripts/Scribble%20Helper.md), [Select Elements of Type.md](scripts/Select%20Elements%20of%20Type.md), [Select Similar Elements.md](scripts/Select%20Similar%20Elements.md), [Set background color of unclosed line object by adding a shadow clone.md](scripts/Set%20background%20color%20of%20unclosed%20line%20object%20by%20adding%20a%20shadow%20clone.md), [Slideshow.md](scripts/Slideshow.md), [Text to Sticky Notes.md](scripts/Text%20to%20Sticky%20Notes.md)
- **setScriptSettings**: [Add Link to Existing File and Open.md](scripts/Add%20Link%20to%20Existing%20File%20and%20Open.md), [Add Link to New Page and Open.md](scripts/Add%20Link%20to%20New%20Page%20and%20Open.md), [Add Next Step in Process.md](scripts/Add%20Next%20Step%20in%20Process.md), [Auto Layout.md](scripts/Auto%20Layout.md), [Box Each Selected Groups.md](scripts/Box%20Each%20Selected%20Groups.md), [Box Selected Elements.md](scripts/Box%20Selected%20Elements.md), [Capture Note.md](scripts/Capture%20Note.md), [Comicbook Callout Editor.md](scripts/Comicbook%20Callout%20Editor.md), [Connect elements.md](scripts/Connect%20elements.md), [Convert freedraw to line.md](scripts/Convert%20freedraw%20to%20line.md), [Convert selected text elements to sticky notes.md](scripts/Convert%20selected%20text%20elements%20to%20sticky%20notes.md), [Darken background color.md](scripts/Darken%20background%20color.md), [Deconstruct selected elements into new drawing.md](scripts/Deconstruct%20selected%20elements%20into%20new%20drawing.md), [Ellipse Selected Elements.md](scripts/Ellipse%20Selected%20Elements.md), [ExcaliAI.md](scripts/ExcaliAI.md), [Excalidraw Writing Machine.md](scripts/Excalidraw%20Writing%20Machine.md), [ExcaliMath.md](scripts/ExcaliMath.md), [Fixed horizontal distance between centers.md](scripts/Fixed%20horizontal%20distance%20between%20centers.md), [Fixed inner distance.md](scripts/Fixed%20inner%20distance.md), [Fixed spacing.md](scripts/Fixed%20spacing.md), [Fixed vertical distance between centers.md](scripts/Fixed%20vertical%20distance%20between%20centers.md), [Fixed vertical distance.md](scripts/Fixed%20vertical%20distance.md), [Golden Ratio.md](scripts/Golden%20Ratio.md), [Icon Library.md](scripts/Icon%20Library.md), [Image Occlusion.md](scripts/Image%20Occlusion.md), [Lighten background color.md](scripts/Lighten%20background%20color.md), [Mindmap format.md](scripts/Mindmap%20format.md), [Modify background color opacity.md](scripts/Modify%20background%20color%20opacity.md), [Normalize Selected Arrows.md](scripts/Normalize%20Selected%20Arrows.md), [Palette loader.md](scripts/Palette%20loader.md), [Palm Guard.md](scripts/Palm%20Guard.md), [Printable Layout Wizard.md](scripts/Printable%20Layout%20Wizard.md), [Scribble Helper.md](scripts/Scribble%20Helper.md), [Set background color of unclosed line object by adding a shadow clone.md](scripts/Set%20background%20color%20of%20unclosed%20line%20object%20by%20adding%20a%20shadow%20clone.md), [Shade Master.md](scripts/Shade%20Master.md), [Text to Sticky Notes.md](scripts/Text%20to%20Sticky%20Notes.md)
- **setScriptSettings**: [Add Link to Existing File and Open.md](scripts/Add%20Link%20to%20Existing%20File%20and%20Open.md), [Add Link to New Page and Open.md](scripts/Add%20Link%20to%20New%20Page%20and%20Open.md), [Add Next Step in Process.md](scripts/Add%20Next%20Step%20in%20Process.md), [Auto Layout.md](scripts/Auto%20Layout.md), [Box Each Selected Groups.md](scripts/Box%20Each%20Selected%20Groups.md), [Box Selected Elements.md](scripts/Box%20Selected%20Elements.md), [Capture Note.md](scripts/Capture%20Note.md), [Comicbook Callout Editor.md](scripts/Comicbook%20Callout%20Editor.md), [Connect elements.md](scripts/Connect%20elements.md), [Convert freedraw to line.md](scripts/Convert%20freedraw%20to%20line.md), [Convert selected text elements to sticky notes.md](scripts/Convert%20selected%20text%20elements%20to%20sticky%20notes.md), [Darken background color.md](scripts/Darken%20background%20color.md), [Deconstruct selected elements into new drawing.md](scripts/Deconstruct%20selected%20elements%20into%20new%20drawing.md), [Ellipse Selected Elements.md](scripts/Ellipse%20Selected%20Elements.md), [ExcaliAI.md](scripts/ExcaliAI.md), [Excalidraw Writing Machine.md](scripts/Excalidraw%20Writing%20Machine.md), [ExcaliMath.md](scripts/ExcaliMath.md), [Fixed horizontal distance between centers.md](scripts/Fixed%20horizontal%20distance%20between%20centers.md), [Fixed inner distance.md](scripts/Fixed%20inner%20distance.md), [Fixed spacing.md](scripts/Fixed%20spacing.md), [Fixed vertical distance between centers.md](scripts/Fixed%20vertical%20distance%20between%20centers.md), [Fixed vertical distance.md](scripts/Fixed%20vertical%20distance.md), [Golden Ratio.md](scripts/Golden%20Ratio.md), [Icon Library.md](scripts/Icon%20Library.md), [Image Occlusion.md](scripts/Image%20Occlusion.md), [Lighten background color.md](scripts/Lighten%20background%20color.md), [Mindmap format.md](scripts/Mindmap%20format.md), [Modify background color opacity.md](scripts/Modify%20background%20color%20opacity.md), [Normalize Selected Arrows.md](scripts/Normalize%20Selected%20Arrows.md), [Palette loader.md](scripts/Palette%20loader.md), [Palm Guard.md](scripts/Palm%20Guard.md), [Printable Layout Wizard.md](scripts/Printable%20Layout%20Wizard.md), [Scribble Helper.md](scripts/Scribble%20Helper.md), [Set background color of unclosed line object by adding a shadow clone.md](scripts/Set%20background%20color%20of%20unclosed%20line%20object%20by%20adding%20a%20shadow%20clone.md), [Shade Master.md](scripts/Shade%20Master.md), [Text to Sticky Notes.md](scripts/Text%20to%20Sticky%20Notes.md), [VoronoiDiagramGenerator.md](scripts/VoronoiDiagramGenerator.md)
- **setScriptSettingValue**: [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md)
- **setStrokeSharpness**: [Scribble Helper.md](scripts/Scribble%20Helper.md)
- **setValue**: [ExcaliAI.md](scripts/ExcaliAI.md)
@@ -110,13 +110,13 @@ This index maps methods and properties from ExcalidrawAutomate (`ea`), Excalidra
- **showColorPicker**: [Comicbook Callout Editor.md](scripts/Comicbook%20Callout%20Editor.md), [ExcaliMath.md](scripts/ExcaliMath.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Scribble Helper.md](scripts/Scribble%20Helper.md), [Shade Master.md](scripts/Shade%20Master.md)
- **sidepanelTab**: [Icon Library.md](scripts/Icon%20Library.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Shade Master.md](scripts/Shade%20Master.md)
- **skipSidepanelScriptRestore**: [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md)
- **style**: [Add Connector Point.md](scripts/Add%20Connector%20Point.md), [Add Link to Existing File and Open.md](scripts/Add%20Link%20to%20Existing%20File%20and%20Open.md), [Add Link to New Page and Open.md](scripts/Add%20Link%20to%20New%20Page%20and%20Open.md), [Add Next Step in Process.md](scripts/Add%20Next%20Step%20in%20Process.md), [Boolean Operations.md](scripts/Boolean%20Operations.md), [Box Each Selected Groups.md](scripts/Box%20Each%20Selected%20Groups.md), [Box Selected Elements.md](scripts/Box%20Selected%20Elements.md), [Comicbook Callout Editor.md](scripts/Comicbook%20Callout%20Editor.md), [Concatenate lines.md](scripts/Concatenate%20lines.md), [Connect elements.md](scripts/Connect%20elements.md), [Convert freedraw to line.md](scripts/Convert%20freedraw%20to%20line.md), [Convert selected text elements to sticky notes.md](scripts/Convert%20selected%20text%20elements%20to%20sticky%20notes.md), [Crop Vintage Mask.md](scripts/Crop%20Vintage%20Mask.md), [Ellipse Selected Elements.md](scripts/Ellipse%20Selected%20Elements.md), [ExcaliAI.md](scripts/ExcaliAI.md), [Full-Year Calendar Generator.md](scripts/Full-Year%20Calendar%20Generator.md), [Golden Ratio.md](scripts/Golden%20Ratio.md), [Linear Calendar Generator.md](scripts/Linear%20Calendar%20Generator.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Mindmap connector.md](scripts/Mindmap%20connector.md), [Printable Layout Wizard.md](scripts/Printable%20Layout%20Wizard.md), [Scribble Helper.md](scripts/Scribble%20Helper.md), [Slideshow.md](scripts/Slideshow.md), [Split Ellipse.md](scripts/Split%20Ellipse.md), [Split text by lines.md](scripts/Split%20text%20by%20lines.md), [Text to Path.md](scripts/Text%20to%20Path.md), [Text to Sticky Notes.md](scripts/Text%20to%20Sticky%20Notes.md), [To Line.md](scripts/To%20Line.md)
- **style**: [Add Connector Point.md](scripts/Add%20Connector%20Point.md), [Add Link to Existing File and Open.md](scripts/Add%20Link%20to%20Existing%20File%20and%20Open.md), [Add Link to New Page and Open.md](scripts/Add%20Link%20to%20New%20Page%20and%20Open.md), [Add Next Step in Process.md](scripts/Add%20Next%20Step%20in%20Process.md), [Boolean Operations.md](scripts/Boolean%20Operations.md), [Box Each Selected Groups.md](scripts/Box%20Each%20Selected%20Groups.md), [Box Selected Elements.md](scripts/Box%20Selected%20Elements.md), [Comicbook Callout Editor.md](scripts/Comicbook%20Callout%20Editor.md), [Concatenate lines.md](scripts/Concatenate%20lines.md), [Connect elements.md](scripts/Connect%20elements.md), [Convert freedraw to line.md](scripts/Convert%20freedraw%20to%20line.md), [Convert selected text elements to sticky notes.md](scripts/Convert%20selected%20text%20elements%20to%20sticky%20notes.md), [Crop Vintage Mask.md](scripts/Crop%20Vintage%20Mask.md), [Ellipse Selected Elements.md](scripts/Ellipse%20Selected%20Elements.md), [ExcaliAI.md](scripts/ExcaliAI.md), [Full-Year Calendar Generator.md](scripts/Full-Year%20Calendar%20Generator.md), [Golden Ratio.md](scripts/Golden%20Ratio.md), [Linear Calendar Generator.md](scripts/Linear%20Calendar%20Generator.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Mindmap connector.md](scripts/Mindmap%20connector.md), [Printable Layout Wizard.md](scripts/Printable%20Layout%20Wizard.md), [Scribble Helper.md](scripts/Scribble%20Helper.md), [Slideshow.md](scripts/Slideshow.md), [Split Ellipse.md](scripts/Split%20Ellipse.md), [Split text by lines.md](scripts/Split%20text%20by%20lines.md), [Text to Path.md](scripts/Text%20to%20Path.md), [Text to Sticky Notes.md](scripts/Text%20to%20Sticky%20Notes.md), [To Line.md](scripts/To%20Line.md), [VoronoiDiagramGenerator.md](scripts/VoronoiDiagramGenerator.md)
- **targetView**: [Add Link to Existing File and Open.md](scripts/Add%20Link%20to%20Existing%20File%20and%20Open.md), [Add Link to New Page and Open.md](scripts/Add%20Link%20to%20New%20Page%20and%20Open.md), [Capture Note.md](scripts/Capture%20Note.md), [Comicbook Callout Editor.md](scripts/Comicbook%20Callout%20Editor.md), [Create new markdown file and embed into active drawing.md](scripts/Create%20new%20markdown%20file%20and%20embed%20into%20active%20drawing.md), [Deconstruct selected elements into new drawing.md](scripts/Deconstruct%20selected%20elements%20into%20new%20drawing.md), [ExcaliAI.md](scripts/ExcaliAI.md), [Excalidraw Writing Machine.md](scripts/Excalidraw%20Writing%20Machine.md), [ExcaliMath.md](scripts/ExcaliMath.md), [Folder Note Core - Make Current Drawing a Folder.md](scripts/Folder%20Note%20Core%20-%20Make%20Current%20Drawing%20a%20Folder.md), [Golden Ratio.md](scripts/Golden%20Ratio.md), [Icon Library.md](scripts/Icon%20Library.md), [Image Occlusion.md](scripts/Image%20Occlusion.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Palm Guard.md](scripts/Palm%20Guard.md), [PDF Page Text to Clipboard.md](scripts/PDF%20Page%20Text%20to%20Clipboard.md), [Printable Layout Wizard.md](scripts/Printable%20Layout%20Wizard.md), [Reset LaTeX Size.md](scripts/Reset%20LaTeX%20Size.md), [Scribble Helper.md](scripts/Scribble%20Helper.md), [Shade Master.md](scripts/Shade%20Master.md), [Slideshow.md](scripts/Slideshow.md), [Text to Path.md](scripts/Text%20to%20Path.md)
- **tex2dataURL**: [Reset LaTeX Size.md](scripts/Reset%20LaTeX%20Size.md)
- **toggleSidepanelView**: [Capture Note.md](scripts/Capture%20Note.md), [Icon Library.md](scripts/Icon%20Library.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Shade Master.md](scripts/Shade%20Master.md)
- **transformAIImage**: [ExcaliAI.md](scripts/ExcaliAI.md)
- **updateViewSVGImageColorMap**: [Shade Master.md](scripts/Shade%20Master.md)
- **verifyMinimumPluginVersion**: [Add Link to Existing File and Open.md](scripts/Add%20Link%20to%20Existing%20File%20and%20Open.md), [Add Link to New Page and Open.md](scripts/Add%20Link%20to%20New%20Page%20and%20Open.md), [Add Next Step in Process.md](scripts/Add%20Next%20Step%20in%20Process.md), [Auto Layout.md](scripts/Auto%20Layout.md), [Boolean Operations.md](scripts/Boolean%20Operations.md), [Box Each Selected Groups.md](scripts/Box%20Each%20Selected%20Groups.md), [Box Selected Elements.md](scripts/Box%20Selected%20Elements.md), [Capture Note.md](scripts/Capture%20Note.md), [Comicbook Callout Editor.md](scripts/Comicbook%20Callout%20Editor.md), [Connect elements.md](scripts/Connect%20elements.md), [Convert freedraw to line.md](scripts/Convert%20freedraw%20to%20line.md), [Convert selected text elements to sticky notes.md](scripts/Convert%20selected%20text%20elements%20to%20sticky%20notes.md), [Create DrawIO file.md](scripts/Create%20DrawIO%20file.md), [Crop Vintage Mask.md](scripts/Crop%20Vintage%20Mask.md), [Darken background color.md](scripts/Darken%20background%20color.md), [Deconstruct selected elements into new drawing.md](scripts/Deconstruct%20selected%20elements%20into%20new%20drawing.md), [Ellipse Selected Elements.md](scripts/Ellipse%20Selected%20Elements.md), [ExcaliAI.md](scripts/ExcaliAI.md), [Excalidraw Writing Machine.md](scripts/Excalidraw%20Writing%20Machine.md), [ExcaliMath.md](scripts/ExcaliMath.md), [Fixed horizontal distance between centers.md](scripts/Fixed%20horizontal%20distance%20between%20centers.md), [Fixed inner distance.md](scripts/Fixed%20inner%20distance.md), [Fixed spacing.md](scripts/Fixed%20spacing.md), [Fixed vertical distance between centers.md](scripts/Fixed%20vertical%20distance%20between%20centers.md), [Fixed vertical distance.md](scripts/Fixed%20vertical%20distance.md), [Golden Ratio.md](scripts/Golden%20Ratio.md), [Image Occlusion.md](scripts/Image%20Occlusion.md), [Lighten background color.md](scripts/Lighten%20background%20color.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Modify background color opacity.md](scripts/Modify%20background%20color%20opacity.md), [Normalize Selected Arrows.md](scripts/Normalize%20Selected%20Arrows.md), [Organic Line.md](scripts/Organic%20Line.md), [Palette loader.md](scripts/Palette%20loader.md), [Palm Guard.md](scripts/Palm%20Guard.md), [Printable Layout Wizard.md](scripts/Printable%20Layout%20Wizard.md), [Repeat Elements.md](scripts/Repeat%20Elements.md), [Repeat Texts.md](scripts/Repeat%20Texts.md), [Reset LaTeX Size.md](scripts/Reset%20LaTeX%20Size.md), [Scribble Helper.md](scripts/Scribble%20Helper.md), [Select Elements of Type.md](scripts/Select%20Elements%20of%20Type.md), [Set background color of unclosed line object by adding a shadow clone.md](scripts/Set%20background%20color%20of%20unclosed%20line%20object%20by%20adding%20a%20shadow%20clone.md), [Set Grid.md](scripts/Set%20Grid.md), [Shade Master.md](scripts/Shade%20Master.md), [Slideshow.md](scripts/Slideshow.md), [Text to Path.md](scripts/Text%20to%20Path.md), [Text to Sticky Notes.md](scripts/Text%20to%20Sticky%20Notes.md), [Toggle Grid.md](scripts/Toggle%20Grid.md)
- **verifyMinimumPluginVersion**: [Add Link to Existing File and Open.md](scripts/Add%20Link%20to%20Existing%20File%20and%20Open.md), [Add Link to New Page and Open.md](scripts/Add%20Link%20to%20New%20Page%20and%20Open.md), [Add Next Step in Process.md](scripts/Add%20Next%20Step%20in%20Process.md), [Auto Layout.md](scripts/Auto%20Layout.md), [Boolean Operations.md](scripts/Boolean%20Operations.md), [Box Each Selected Groups.md](scripts/Box%20Each%20Selected%20Groups.md), [Box Selected Elements.md](scripts/Box%20Selected%20Elements.md), [Capture Note.md](scripts/Capture%20Note.md), [Comicbook Callout Editor.md](scripts/Comicbook%20Callout%20Editor.md), [Connect elements.md](scripts/Connect%20elements.md), [Convert freedraw to line.md](scripts/Convert%20freedraw%20to%20line.md), [Convert selected text elements to sticky notes.md](scripts/Convert%20selected%20text%20elements%20to%20sticky%20notes.md), [Crop Vintage Mask.md](scripts/Crop%20Vintage%20Mask.md), [Darken background color.md](scripts/Darken%20background%20color.md), [Deconstruct selected elements into new drawing.md](scripts/Deconstruct%20selected%20elements%20into%20new%20drawing.md), [Ellipse Selected Elements.md](scripts/Ellipse%20Selected%20Elements.md), [ExcaliAI.md](scripts/ExcaliAI.md), [Excalidraw Writing Machine.md](scripts/Excalidraw%20Writing%20Machine.md), [ExcaliMath.md](scripts/ExcaliMath.md), [Fixed horizontal distance between centers.md](scripts/Fixed%20horizontal%20distance%20between%20centers.md), [Fixed inner distance.md](scripts/Fixed%20inner%20distance.md), [Fixed spacing.md](scripts/Fixed%20spacing.md), [Fixed vertical distance between centers.md](scripts/Fixed%20vertical%20distance%20between%20centers.md), [Fixed vertical distance.md](scripts/Fixed%20vertical%20distance.md), [Golden Ratio.md](scripts/Golden%20Ratio.md), [Image Occlusion.md](scripts/Image%20Occlusion.md), [Lighten background color.md](scripts/Lighten%20background%20color.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Modify background color opacity.md](scripts/Modify%20background%20color%20opacity.md), [Normalize Selected Arrows.md](scripts/Normalize%20Selected%20Arrows.md), [Organic Line.md](scripts/Organic%20Line.md), [Palette loader.md](scripts/Palette%20loader.md), [Palm Guard.md](scripts/Palm%20Guard.md), [Printable Layout Wizard.md](scripts/Printable%20Layout%20Wizard.md), [Repeat Elements.md](scripts/Repeat%20Elements.md), [Repeat Texts.md](scripts/Repeat%20Texts.md), [Reset LaTeX Size.md](scripts/Reset%20LaTeX%20Size.md), [Scribble Helper.md](scripts/Scribble%20Helper.md), [Select Elements of Type.md](scripts/Select%20Elements%20of%20Type.md), [Set background color of unclosed line object by adding a shadow clone.md](scripts/Set%20background%20color%20of%20unclosed%20line%20object%20by%20adding%20a%20shadow%20clone.md), [Set Grid.md](scripts/Set%20Grid.md), [Shade Master.md](scripts/Shade%20Master.md), [Slideshow.md](scripts/Slideshow.md), [Text to Path.md](scripts/Text%20to%20Path.md), [Text to Sticky Notes.md](scripts/Text%20to%20Sticky%20Notes.md), [Toggle Grid.md](scripts/Toggle%20Grid.md)
- **viewToggleFullScreen**: [Slideshow.md](scripts/Slideshow.md)
- **viewUpdateScene**: [Invert colors.md](scripts/Invert%20colors.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Palette loader.md](scripts/Palette%20loader.md), [Printable Layout Wizard.md](scripts/Printable%20Layout%20Wizard.md), [Relative Font Size Cycle.md](scripts/Relative%20Font%20Size%20Cycle.md), [Set Stroke Width of Selected Elements.md](scripts/Set%20Stroke%20Width%20of%20Selected%20Elements.md), [Text to Path.md](scripts/Text%20to%20Path.md), [Toggle Grid.md](scripts/Toggle%20Grid.md)
- **viewZoomToElements**: [Capture Note.md](scripts/Capture%20Note.md), [ExcaliAI.md](scripts/ExcaliAI.md), [Printable Layout Wizard.md](scripts/Printable%20Layout%20Wizard.md)
@@ -84,7 +84,7 @@ export declare const getCommonBoundingBox: (elements: readonly ExcalidrawElement
/* ************************************** */
/* @excalidraw/element/groups -> node_modules/@zsviczian/excalidraw/types/element/src/groups.d.ts */
/* ************************************** */
export declare const getMaximumGroups: (elements: ExcalidrawElement[], elementsMap: ElementsMap) => ExcalidrawElement[][];
export declare const getMaximumGroups: <T extends NonDeletedExcalidrawElement | ExcalidrawElement>(elements: T[], elementsMap: ElementsMap) => T[][];
/* ************************************** */
/* @excalidraw/element/textMeasurements -> node_modules/@zsviczian/excalidraw/types/element/src/textMeasurements.d.ts */
@@ -101,7 +101,7 @@ export declare const wrapText: (text: string, font: FontString, maxWidth: number
/* @excalidraw/element/textElement -> node_modules/@zsviczian/excalidraw/types/element/src/textElement.d.ts */
/* ************************************** */
export declare const getBoundTextMaxWidth: (container: ExcalidrawElement, boundTextElement: ExcalidrawTextElement | null) => number;
export declare const getContainerElement: (element: ExcalidrawTextElement | null, elementsMap: ElementsMap) => ExcalidrawTextContainer | null;
export declare const getContainerElement: <T extends ExcalidrawTextElement, R extends ExcalidrawTextContainer>(element: T | null, elementsMap: ElementsMap) => R | null;
/* ************************************** */
/* ./components/TTDDialog/MermaidToExcalidrawLib -> node_modules/@zsviczian/excalidraw/types/excalidraw/components/TTDDialog/MermaidToExcalidrawLib.d.ts */
@@ -223,21 +223,20 @@ export declare const TTDDialog: {
/* ************************************** */
/* ./components/TTDDialog/utils/TTDStreamFetch -> node_modules/@zsviczian/excalidraw/types/excalidraw/components/TTDDialog/utils/TTDStreamFetch.d.ts */
/* ************************************** */
export declare function parseSSEStream(reader: ReadableStreamDefaultReader<Uint8Array>): AsyncGenerator<string, void, unknown>;
export declare function TTDStreamFetch(options: StreamingOptions): Promise<TTTDDialog.OnTextSubmitRetValue>;
/* ************************************** */
/* ./actions/actionCanvas -> node_modules/@zsviczian/excalidraw/types/excalidraw/actions/actionCanvas.d.ts */
/* ./viewport -> node_modules/@zsviczian/excalidraw/types/excalidraw/viewport.d.ts */
/* ************************************** */
export declare const zoomToFitBounds: ({ bounds, appState, canvasOffsets, fitToViewport, viewportZoomFactor, minZoom, maxZoom, }: {
export declare const zoomToFitBounds: ({ bounds, appState, canvasOffsets, fit, minZoom, maxZoom, steppedZoom, }: {
bounds: SceneBounds;
canvasOffsets?: Offsets;
appState: Readonly<AppState>;
/** whether to fit content to viewport (beyond >100%) */
fitToViewport: boolean;
/** zoom content to cover X of the viewport, when fitToViewport=true */
viewportZoomFactor?: number;
fit?: SetViewportOptions["fit"];
minZoom?: number;
maxZoom?: number;
steppedZoom?: boolean;
}) => {
appState: {
scrollX: number;
@@ -254,4 +253,36 @@ export declare const DiagramToCodePlugin: (props: {
/* ************************************** */
export declare const CommandPalette: ((props: CommandPaletteProps) => import("react/jsx-runtime").JSX.Element | null) & {
defaultItems: typeof defaultItems;
/* ************************************** */
/* ./obsidianExcalidrawHost -> node_modules/@zsviczian/excalidraw/types/excalidraw/obsidianExcalidrawHost.d.ts */
/* ************************************** */
export declare const OBSIDIAN_EXCALIDRAW_HOST_PROTOCOL_VERSION: 2;
/** Keyboard-blocking lifecycle returned by the host's inline suggester. */
export interface ObsidianKeyBlocker {
isBlockingKeys(): boolean;
close(): void;
}
/** Plugin-wide capabilities consumed by the Excalidraw package. */
export interface ObsidianExcalidrawHostAdapter {
readonly protocolVersion: typeof OBSIDIAN_EXCALIDRAW_HOST_PROTOCOL_VERSION;
isDoubleTapEraserEnabled(): boolean;
isRightClickPanEnabled(): boolean;
getZoomToFitMaxLevel(): number;
isPenModeCrosshairVisible(): boolean;
isSingleFingerPanningEnabled(): boolean;
isDoubleClickTextEditingDisabled(): boolean;
getZoomStep(): number;
getZoomMin(): number;
getZoomMax(): number;
isContextMenuDisabled(): boolean;
shouldSyncElementLinkWithText(): boolean;
loadFontFromFile(filename: string): Promise<ArrayBuffer | undefined>;
getMermaid(): Promise<MermaidToExcalidrawLibProps>;
runAction(action: "anyFile" | "LaTeX" | "card"): void;
getLabel(key: string): string;
attachInlineLinkSuggester(inputEl: HTMLInputElement | HTMLTextAreaElement, widthWrapper?: HTMLElement, container?: HTMLDivElement | null, suppressPlaceholder?: boolean): ObsidianKeyBlocker;
}
/** Idempotent cleanup returned when a package host is configured. */
export type ObsidianExcalidrawHostDisposer = () => void;
```
@@ -1,35 +0,0 @@
/*
Creates a new draw.io diagram file and opens the file in the [Diagram plugin](https://github.com/zapthedingbat/drawio-obsidian) in a new tab.
```js*/
if(!ea.verifyMinimumPluginVersion || !ea.verifyMinimumPluginVersion("1.9.7")) {
new Notice("This script requires a newer version of Excalidraw. Please install the latest version.");
return;
}
const drawIO = app.plugins.plugins["drawio-obsidian"];
if(!drawIO || !drawIO?._loaded) {
new Notice("Can't find the draw.io diagram plugin");
}
filename = await utils.inputPrompt("Diagram name?");
if(!filename) return;
filename = filename.toLowerCase().endsWith(".svg") ? filename : filename + ".svg";
const filepath = await ea.getAttachmentFilepath(filename);
if(!filepath) return;
const leaf = app.workspace.getLeaf('tab')
if(!leaf) return;
const file = await this.app.vault.create(filepath, `<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"><!--${ea.generateElementId()}--><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" width="300px" height="300px" viewBox="-0.5 -0.5 1 1" content="&lt;mxGraphModel&gt;&lt;root&gt;&lt;mxCell id=&quot;0&quot;/&gt;&lt;mxCell id=&quot;1&quot; parent=&quot;0&quot;/&gt;&lt;/root&gt;&lt;/mxGraphModel&gt;"></svg>`);
await ea.addImage(0,0,file);
await ea.addElementsToView(true,true);
leaf.setViewState({
type: "diagram-edit",
state: {
file: filepath
}
});
```
@@ -3378,11 +3378,36 @@ const zoomToFit = (mode) => {
elementID: sel.id,
level: nextLevel
}
api().scrollToContent([sel], {
fitToViewport: true,
viewportZoomFactor: getZoom(nextLevel),
animate: true
});
const targetZoom = getZoom(nextLevel);
// Fallback for older versions vs new Excalidraw 2.26.0+ Viewport API
if (!ea.verifyMinimumPluginVersion("2.26.0")) {
api().scrollToContent([sel], {
fitToViewport: true,
viewportZoomFactor: targetZoom,
animate: true
});
} else {
// For the new API, we calculate a target rect centered on the element
// with dimensions that will force 'fit: "contain"' to reach our target zoom.
const appState = api().getAppState();
const targetW = appState.width / targetZoom;
const targetH = appState.height / targetZoom;
const cx = sel.x + sel.width / 2;
const cy = sel.y + sel.height / 2;
api().setViewport({
target: {
x: cx - targetW / 2,
y: cy - targetH / 2,
width: targetW,
height: targetH
},
fit: "contain",
animation: true
});
}
}
}
@@ -3411,10 +3436,20 @@ const focusSelected = () => {
if (!sel) return;
api().scrollToContent(sel, {
fitToContent: false,
animate: true,
});
// Fallback for older versions vs new Excalidraw 2.26.0+ Viewport API
if (!ea.verifyMinimumPluginVersion("2.26.0")) {
api().scrollToContent(sel, {
fitToContent: false,
animate: true,
});
} else {
// fit: "none" recenters at the current zoom without changing it
api().setViewport({
target: [sel],
fit: "none",
animation: true
});
}
};
const getMindmapOrder = (node) => {
@@ -0,0 +1,227 @@
/*
This script generates a Voronoi diagram from selected elements on the drawing canvas.
The following parameters can be set in 'Voronoi Settings' window pop-up once the script is started:
- Frame width (default: 100)
- Roughness (default: 0)
- Stroke width (default: 2)
- Grouping (default: checked)
Setting parameters could be set back to default values by click on button 'Default'.
Check info button for howto help during applying the script.
See background information about Voronoi diagram at Wikipedia : https://en.wikipedia.org/wiki/Voronoi_diagram
Comments and discussion are welcomed in the Sketch-Your-Mind community: https://community.sketch-your-mind.com
```js*/
// ExcalidrawAutomate: Voronoi Diagram Generator
ea.clear();
const DEFAULTS = {
frameWidth: 100,
roughness: 0,
strokeWidth: 2,
groupVoronoi: true
};
let config = ea.getScriptSettings() || { ...DEFAULTS };
// --- UI SETTINGS MODAL ---
async function openSettings() {
return new Promise((resolve) => {
const modal = new ea.obsidian.Modal(app);
modal.contentEl.style.padding = "20px";
// Header container with Title and Info Button
const headerContainer = modal.contentEl.createDiv();
headerContainer.style.display = "flex";
headerContainer.style.justifyContent = "space-between";
headerContainer.style.alignItems = "center";
headerContainer.style.marginBottom = "20px";
headerContainer.createEl("h2", { text: "Settings - Voronoi Diagram Generator", cls: "mod-header" }).style.margin = "0";
// Info button using Obsidian's native icon
const btnInfo = headerContainer.createEl("button", { cls: "clickable-icon" });
btnInfo.setAttribute("aria-label", "Information & Help");
btnInfo.innerHTML = ea.obsidian.getIcon("info").outerHTML;
// Info modal content on click
btnInfo.onclick = () => {
const infoModal = new ea.obsidian.Modal(app);
infoModal.contentEl.style.padding = "20px";
infoModal.contentEl.createEl("h3", { text: "About - Voronoi Diagram Generator" });
// Native Obsidian Icon as HTML string
const chatIcon = ea.obsidian.getIcon("message-square").outerHTML;
const p = infoModal.contentEl.createEl("p");
p.innerHTML = `
This script generates a Voronoi diagram from selected elements on the drawing canvas.<br><br>
<h4 style="margin: 5px 0 5px 0; font-size: 1.1em;">HowTo & Parameters:</h4>
<div line-height: 1.4;">
<div style="margin-bottom: 10px;">1. <b>Select</b> at least 2 elements on your canvas.</div>
<div style="margin-bottom: 4px;">2. <b>Run</b> the script and adjust your settings:</div>
<div style="margin: 2px 0 10px 15px; line-height: 1.2;">
- <b>Frame width:</b> Spacing around the diagram.<br>
- <b>Roughness:</b> Hand-drawn effect (0-3).<br>
- <b>Stroke width:</b> Line thickness.<br>
- <b>Grouping:</b> Group generated cells together.<br>
</div>
<div style="margin-bottom: 15px;">3. Click <b>OK</b> to generate.</div>
</div><br>
<span style="display: inline-flex; align-items: center; gap: 6px; vertical-align: middle;"> ${chatIcon} Feedback & chat: <a href="https://community.sketch-your-mind.com" target="_blank">Sketch Your Mind Community</a>
</span>
`;
infoModal.open();
};
const inputs = {};
// Helper function to create input rows
const createInput = (label, key, type = "number") => {
const container = modal.contentEl.createDiv();
container.style.marginBottom = "15px";
container.createEl("label", { text: label });
const input = container.createEl("input", { type: type });
input.style.display = "block";
input.style.marginTop = "5px";
input.value = config[key];
input.onchange = (e) => config[key] = type === "number" ? Number(e.target.value) : e.target.checked;
inputs[key] = input;
};
createInput("Frame width:", "frameWidth");
createInput("Roughness (0-3):", "roughness");
createInput("Stroke width:", "strokeWidth");
const checkContainer = modal.contentEl.createDiv();
checkContainer.style.marginBottom = "25px";
checkContainer.createEl("label", { text: "Grouping: " });
inputs.groupVoronoi = checkContainer.createEl("input", { type: "checkbox" });
inputs.groupVoronoi.checked = config.groupVoronoi;
inputs.groupVoronoi.onchange = (e) => config.groupVoronoi = e.target.checked;
// Button container
const btnContainer = modal.contentEl.createDiv();
btnContainer.style.display = "flex";
btnContainer.style.gap = "10px";
btnContainer.style.justifyContent = "flex-end";
const btnDefault = btnContainer.createEl("button", { text: "Default" });
const btnOk = btnContainer.createEl("button", { text: "OK" });
btnDefault.onclick = () => {
config = { ...DEFAULTS };
inputs.frameWidth.value = config.frameWidth;
inputs.roughness.value = config.roughness;
inputs.strokeWidth.value = config.strokeWidth;
inputs.groupVoronoi.checked = config.groupVoronoi;
new Notice("Settings reset to default");
};
btnOk.onclick = () => {
ea.setScriptSettings(config);
modal.close();
resolve(true);
};
modal.open();
});
}
// Wait for user to configure settings
const proceed = await openSettings();
if (!proceed) return;
// --- ALGORITHM & EXECUTION ---
const els = ea.getViewSelectedElements();
if (els.length < 2) {
new Notice("Please select at least two items!");
return;
}
const seeds = els.map(el => ({ x: el.x + el.width / 2, y: el.y + el.height / 2 }));
if (seeds.length < 2) {
new Notice("Please select at least two items!");
return;
}
const minX = Math.min(...seeds.map(s => s.x)) - config.frameWidth;
const minY = Math.min(...seeds.map(s => s.y)) - config.frameWidth;
const maxX = Math.max(...seeds.map(s => s.x)) + config.frameWidth;
const maxY = Math.max(...seeds.map(s => s.y)) + config.frameWidth;
const bbox = [
{ x: minX, y: minY },
{ x: maxX, y: minY },
{ x: maxX, y: maxY },
{ x: minX, y: maxY }
];
function clipPolygon(poly, p1, p2) {
const mid = { x: (p1.x + p2.x) / 2, y: (p1.y + p2.y) / 2 };
const n = { x: p2.x - p1.x, y: p2.y - p1.y };
const isInside = (p) => (p.x - mid.x) * n.x + (p.y - mid.y) * n.y <= 0;
const intersect = (a, b) => {
const num = (a.x - mid.x) * n.x + (a.y - mid.y) * n.y;
const den = (b.x - a.x) * n.x + (b.y - a.y) * n.y;
if (den === 0) return null;
const t = -num / den;
return { x: a.x + t * (b.x - a.x), y: a.y + t * (b.y - a.y) };
};
const result = [];
for (let i = 0; i < poly.length; i++) {
const cur = poly[i];
const prev = poly[(i - 1 + poly.length) % poly.length];
const curIn = isInside(cur);
const prevIn = isInside(prev);
if (curIn !== prevIn) {
const ix = intersect(prev, cur);
if (ix) result.push(ix);
}
if (curIn) result.push(cur);
}
return result;
}
const polygons = seeds.map((s, i) => {
let poly = [...bbox];
seeds.forEach((_, j) => {
if (i !== j) poly = clipPolygon(poly, seeds[i], seeds[j]);
});
return poly;
});
ea.style.roughness = config.roughness;
ea.style.strokeWidth = config.strokeWidth;
ea.style.backgroundColor = "transparent";
const ids = [];
for (const poly of polygons) {
if (poly.length < 3) continue;
const points = poly.map(p => [p.x, p.y]);
points.push(points[0]);
ids.push(ea.addLine(points));
}
if (config.groupVoronoi && ids.length > 0) {
ea.addToGroup(ids);
}
await ea.addElementsToView(false, false);
// Clear selection so nothing remains selected on the canvas
const view = app.workspace.activeLeaf.view; if (view && view.excalidrawAPI) { view.excalidrawAPI.updateScene({ appState: { selectedElementIds: {} } }); }
new Notice("Voronoi diagram created!");
```
@@ -1,13 +1,23 @@
# Excalidraw Startup Script
ExcalidrawStartup Script can be configured in Plugin Settings under 'Excalidraw Automate'. When defined this script runs automatically when the Excalidraw plugin is loaded to Obsidian. The user can add automation tasks here that they want to run on every startup of Excalidraw in Obsidian such as defining Excalidraw event handlers (also known as hooks).
ExcalidrawStartup Script can be configured in Plugin Settings under 'Excalidraw Automate'. When defined this script runs once per Excalidraw plugin load using the plugin-global EA and utils.executionSource === 'plugin-startup'. Use ea.registerCleanup() for external listeners, timers, observers, or subscriptions that must be released when Excalidraw unloads. The user can add automation tasks here that they want to run on every startup of Excalidraw in Obsidian such as defining Excalidraw event handlers (also known as hooks).
### Template
```js
/*
#exclude
```js*/
/**
* Startup scripts receive the plugin-global EA for the plugin lifetime and
* utils.executionSource === "plugin-startup". Register cleanup for resources
* outside EA so plugin reload/unload cannot accumulate them.
*/
// const ref = app.workspace.on("file-open", (file) => {});
// ea.registerCleanup(() => app.workspace.offref(ref));
//
// const interval = window.setInterval(() => {}, 1000);
// ea.registerCleanup(() => window.clearInterval(interval));
/**
* If set, this callback is triggered when the user closes an Excalidraw view.
* onViewUnloadHook: (view: ExcalidrawView) => void = null;
File diff suppressed because it is too large. Load diff
+43 -5
View File
@@ -17,11 +17,49 @@ You will be able to access your scripts from Excalidraw via the Obsidian Command
![image](https://user-images.githubusercontent.com/14358394/145673652-6b1713e2-edc8-4bc8-8246-3f8df8a4b273.png)
This will allow you to assign hotkeys to your favorite scripts just like to any other Obsidian command.
![image](https://user-images.githubusercontent.com/14358394/145673633-83b6c969-cead-429b-9721-fd047f980279.png)
## Script development
This will allow you to assign hotkeys to your favorite scripts just like to any other Obsidian command.
![image](https://user-images.githubusercontent.com/14358394/145673633-83b6c969-cead-429b-9721-fd047f980279.png)
## EA script execution lifecycles
`utils.executionSource` describes why the current top-level script invocation
happened. It does not indicate whether the source was compiled previously,
whether the script has run before, or whether runtime state was retained.
| Trigger | `utils.executionSource` | EA received | Approximate lifetime |
| --- | --- | --- | --- |
| Script button, command, or hotkey | `manual` | fresh view EA | existing ordinary script/view lifecycle |
| Plugin startup script | `plugin-startup` | global plugin EA | plugin lifetime |
| `registerAutostart()` attachment | `view-autostart` | fresh view-local EA | view lifetime |
| Persisted sidepanel reconstruction | `sidepanel-restore` | sidepanel host EA | sidepanel tab lifetime |
| Sidepanel script reload | `sidepanel-reload` | reloaded sidepanel host EA | sidepanel tab lifetime |
| `excalidraw-onload-script` | `drawing-onload` | view-local EA | drawing/view lifetime |
Compilation caching is transparent: compiled JavaScript may be shared while
unchanged, but each invocation retains its existing EA ownership and execution
semantics. Manual execution remains repeatable even for a script that also uses
view autostart.
Use `ea.registerCleanup()` for resources that EA does not own directly:
```js
const ref = app.workspace.on("file-open", handler);
ea.registerCleanup(() => app.workspace.offref(ref));
window.addEventListener("resize", handler);
ea.registerCleanup(() => window.removeEventListener("resize", handler));
const interval = window.setInterval(callback, 1000);
ea.registerCleanup(() => window.clearInterval(interval));
```
Cleanup runs when that particular EA instance is destroyed, so its exact
lifetime depends on whether it is the plugin-startup EA, a view-local EA, or a
sidepanel host EA. The function returned by `registerCleanup()` unregisters the
callback without executing it.
## Script development
An Excalidraw script will automatically receive two objects:
- `ea`: The Script Engine will initialize the `ea` object including setting the active view to the View from which the script was called.
- `utils`: I have borrowed functions exposed on utils from [QuickAdd](https://github.com/chhoumann/quickadd/blob/master/docs/QuickAddAPI.md), though currently not all QuickAdd utility functions are implemented in Excalidraw. As of now, these are the available functions. See the example below for details.
File diff suppressed because it is too large. Load diff
-33
View File
@@ -1,33 +0,0 @@
/*
Creates a new draw.io diagram file and opens the file in the [Diagram plugin](https://github.com/zapthedingbat/drawio-obsidian) in a new tab.
```js*/
if(!ea.verifyMinimumPluginVersion || !ea.verifyMinimumPluginVersion("1.9.7")) {
new Notice("This script requires a newer version of Excalidraw. Please install the latest version.");
return;
}
const drawIO = app.plugins.plugins["drawio-obsidian"];
if(!drawIO || !drawIO?._loaded) {
new Notice("Can't find the draw.io diagram plugin");
}
filename = await utils.inputPrompt("Diagram name?");
if(!filename) return;
filename = filename.toLowerCase().endsWith(".svg") ? filename : filename + ".svg";
const filepath = await ea.getAttachmentFilepath(filename);
if(!filepath) return;
const leaf = app.workspace.getLeaf('tab')
if(!leaf) return;
const file = await this.app.vault.create(filepath, `<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"><!--${ea.generateElementId()}--><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" width="300px" height="300px" viewBox="-0.5 -0.5 1 1" content="&lt;mxGraphModel&gt;&lt;root&gt;&lt;mxCell id=&quot;0&quot;/&gt;&lt;mxCell id=&quot;1&quot; parent=&quot;0&quot;/&gt;&lt;/root&gt;&lt;/mxGraphModel&gt;"></svg>`);
await ea.addImage(0,0,file);
await ea.addElementsToView(true,true);
leaf.setViewState({
type: "diagram-edit",
state: {
file: filepath
}
});
-1
View File
@@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" xml:space="preserve" viewBox="24 26 68 68" stroke="#000"><path fill="none" stroke="#000" stroke-miterlimit="10" stroke-width="3.553" d="m58.069 43.384-17.008 29.01"/><path fill="none" stroke="#000" stroke-miterlimit="10" stroke-width="3.501" d="m58.068 43.384 17.008 29.01"/><path fill="#000" d="M52.773 77.084a3.564 3.564 0 0 1-3.553 3.553H36.999a3.564 3.564 0 0 1-3.553-3.553v-9.379a3.564 3.564 0 0 1 3.553-3.553h12.222a3.564 3.564 0 0 1 3.553 3.553v9.379zM67.762 48.074a3.564 3.564 0 0 1-3.553 3.553H51.988a3.564 3.564 0 0 1-3.553-3.553v-9.379a3.564 3.564 0 0 1 3.553-3.553H64.21a3.564 3.564 0 0 1 3.553 3.553v9.379zM82.752 77.084a3.564 3.564 0 0 1-3.553 3.553H66.977a3.564 3.564 0 0 1-3.553-3.553v-9.379a3.564 3.564 0 0 1 3.553-3.553h12.222a3.564 3.564 0 0 1 3.553 3.553v9.379z"/></svg>

Before

Width:  |  Height:  |  Size: 830 B

+225
View File
@@ -0,0 +1,225 @@
/*
This script generates a Voronoi diagram from selected elements on the drawing canvas.
The following parameters can be set in 'Voronoi Settings' window pop-up once the script is started:
- Frame width (default: 100)
- Roughness (default: 0)
- Stroke width (default: 2)
- Grouping (default: checked)
Setting parameters could be set back to default values by click on button 'Default'.
Check info button for howto help during applying the script.
See background information about Voronoi diagram at Wikipedia : https://en.wikipedia.org/wiki/Voronoi_diagram
Comments and discussion are welcomed in the Sketch-Your-Mind community: https://community.sketch-your-mind.com
```js*/
// ExcalidrawAutomate: Voronoi Diagram Generator
ea.clear();
const DEFAULTS = {
frameWidth: 100,
roughness: 0,
strokeWidth: 2,
groupVoronoi: true
};
let config = ea.getScriptSettings() || { ...DEFAULTS };
// --- UI SETTINGS MODAL ---
async function openSettings() {
return new Promise((resolve) => {
const modal = new ea.obsidian.Modal(app);
modal.contentEl.style.padding = "20px";
// Header container with Title and Info Button
const headerContainer = modal.contentEl.createDiv();
headerContainer.style.display = "flex";
headerContainer.style.justifyContent = "space-between";
headerContainer.style.alignItems = "center";
headerContainer.style.marginBottom = "20px";
headerContainer.createEl("h2", { text: "Settings - Voronoi Diagram Generator", cls: "mod-header" }).style.margin = "0";
// Info button using Obsidian's native icon
const btnInfo = headerContainer.createEl("button", { cls: "clickable-icon" });
btnInfo.setAttribute("aria-label", "Information & Help");
btnInfo.innerHTML = ea.obsidian.getIcon("info").outerHTML;
// Info modal content on click
btnInfo.onclick = () => {
const infoModal = new ea.obsidian.Modal(app);
infoModal.contentEl.style.padding = "20px";
infoModal.contentEl.createEl("h3", { text: "About - Voronoi Diagram Generator" });
// Native Obsidian Icon as HTML string
const chatIcon = ea.obsidian.getIcon("message-square").outerHTML;
const p = infoModal.contentEl.createEl("p");
p.innerHTML = `
This script generates a Voronoi diagram from selected elements on the drawing canvas.<br><br>
<h4 style="margin: 5px 0 5px 0; font-size: 1.1em;">HowTo & Parameters:</h4>
<div line-height: 1.4;">
<div style="margin-bottom: 10px;">1. <b>Select</b> at least 2 elements on your canvas.</div>
<div style="margin-bottom: 4px;">2. <b>Run</b> the script and adjust your settings:</div>
<div style="margin: 2px 0 10px 15px; line-height: 1.2;">
- <b>Frame width:</b> Spacing around the diagram.<br>
- <b>Roughness:</b> Hand-drawn effect (0-3).<br>
- <b>Stroke width:</b> Line thickness.<br>
- <b>Grouping:</b> Group generated cells together.<br>
</div>
<div style="margin-bottom: 15px;">3. Click <b>OK</b> to generate.</div>
</div><br>
<span style="display: inline-flex; align-items: center; gap: 6px; vertical-align: middle;"> ${chatIcon} Feedback & chat: <a href="https://community.sketch-your-mind.com" target="_blank">Sketch Your Mind Community</a>
</span>
`;
infoModal.open();
};
const inputs = {};
// Helper function to create input rows
const createInput = (label, key, type = "number") => {
const container = modal.contentEl.createDiv();
container.style.marginBottom = "15px";
container.createEl("label", { text: label });
const input = container.createEl("input", { type: type });
input.style.display = "block";
input.style.marginTop = "5px";
input.value = config[key];
input.onchange = (e) => config[key] = type === "number" ? Number(e.target.value) : e.target.checked;
inputs[key] = input;
};
createInput("Frame width:", "frameWidth");
createInput("Roughness (0-3):", "roughness");
createInput("Stroke width:", "strokeWidth");
const checkContainer = modal.contentEl.createDiv();
checkContainer.style.marginBottom = "25px";
checkContainer.createEl("label", { text: "Grouping: " });
inputs.groupVoronoi = checkContainer.createEl("input", { type: "checkbox" });
inputs.groupVoronoi.checked = config.groupVoronoi;
inputs.groupVoronoi.onchange = (e) => config.groupVoronoi = e.target.checked;
// Button container
const btnContainer = modal.contentEl.createDiv();
btnContainer.style.display = "flex";
btnContainer.style.gap = "10px";
btnContainer.style.justifyContent = "flex-end";
const btnDefault = btnContainer.createEl("button", { text: "Default" });
const btnOk = btnContainer.createEl("button", { text: "OK" });
btnDefault.onclick = () => {
config = { ...DEFAULTS };
inputs.frameWidth.value = config.frameWidth;
inputs.roughness.value = config.roughness;
inputs.strokeWidth.value = config.strokeWidth;
inputs.groupVoronoi.checked = config.groupVoronoi;
new Notice("Settings reset to default");
};
btnOk.onclick = () => {
ea.setScriptSettings(config);
modal.close();
resolve(true);
};
modal.open();
});
}
// Wait for user to configure settings
const proceed = await openSettings();
if (!proceed) return;
// --- ALGORITHM & EXECUTION ---
const els = ea.getViewSelectedElements();
if (els.length < 2) {
new Notice("Please select at least two items!");
return;
}
const seeds = els.map(el => ({ x: el.x + el.width / 2, y: el.y + el.height / 2 }));
if (seeds.length < 2) {
new Notice("Please select at least two items!");
return;
}
const minX = Math.min(...seeds.map(s => s.x)) - config.frameWidth;
const minY = Math.min(...seeds.map(s => s.y)) - config.frameWidth;
const maxX = Math.max(...seeds.map(s => s.x)) + config.frameWidth;
const maxY = Math.max(...seeds.map(s => s.y)) + config.frameWidth;
const bbox = [
{ x: minX, y: minY },
{ x: maxX, y: minY },
{ x: maxX, y: maxY },
{ x: minX, y: maxY }
];
function clipPolygon(poly, p1, p2) {
const mid = { x: (p1.x + p2.x) / 2, y: (p1.y + p2.y) / 2 };
const n = { x: p2.x - p1.x, y: p2.y - p1.y };
const isInside = (p) => (p.x - mid.x) * n.x + (p.y - mid.y) * n.y <= 0;
const intersect = (a, b) => {
const num = (a.x - mid.x) * n.x + (a.y - mid.y) * n.y;
const den = (b.x - a.x) * n.x + (b.y - a.y) * n.y;
if (den === 0) return null;
const t = -num / den;
return { x: a.x + t * (b.x - a.x), y: a.y + t * (b.y - a.y) };
};
const result = [];
for (let i = 0; i < poly.length; i++) {
const cur = poly[i];
const prev = poly[(i - 1 + poly.length) % poly.length];
const curIn = isInside(cur);
const prevIn = isInside(prev);
if (curIn !== prevIn) {
const ix = intersect(prev, cur);
if (ix) result.push(ix);
}
if (curIn) result.push(cur);
}
return result;
}
const polygons = seeds.map((s, i) => {
let poly = [...bbox];
seeds.forEach((_, j) => {
if (i !== j) poly = clipPolygon(poly, seeds[i], seeds[j]);
});
return poly;
});
ea.style.roughness = config.roughness;
ea.style.strokeWidth = config.strokeWidth;
ea.style.backgroundColor = "transparent";
const ids = [];
for (const poly of polygons) {
if (poly.length < 3) continue;
const points = poly.map(p => [p.x, p.y]);
points.push(points[0]);
ids.push(ea.addLine(points));
}
if (config.groupVoronoi && ids.length > 0) {
ea.addToGroup(ids);
}
await ea.addElementsToView(false, false);
// Clear selection so nothing remains selected on the canvas
const view = app.workspace.activeLeaf.view; if (view && view.excalidrawAPI) { view.excalidrawAPI.updateScene({ appState: { selectedElementIds: {} } }); }
new Notice("Voronoi diagram created!");
+2
View File
@@ -0,0 +1,2 @@
<svg version="1.1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 120.00000000000006 111.59685711952335" width="120.00000000000006" height="111.59685711952335" class="excalidraw-svg"><!-- svg-source:excalidraw --><metadata></metadata><defs><style class="style-fonts">
</style></defs><g stroke-linecap="round"><g transform="translate(10 57.19446226550917) rotate(0 23.90392712157481 -23.597231132754587)"><path d="M0 0 C0 -10.48, 0 -20.95, 0 -47.19 M0 0 C0 -12.02, 0 -24.03, 0 -47.19 M0 -47.19 C13.84 -47.19, 27.68 -47.19, 47.81 -47.19 M0 -47.19 C9.79 -47.19, 19.58 -47.19, 47.81 -47.19 M47.81 -47.19 C46.81 -36.92, 45.82 -26.65, 44.57 -13.77 M47.81 -47.19 C46.84 -37.23, 45.88 -27.26, 44.57 -13.77 M44.57 -13.77 C28.62 -8.84, 12.67 -3.91, 0 0 M44.57 -13.77 C29.97 -9.26, 15.37 -4.75, 0 0" stroke="#000000" stroke-width="4" fill="none"></path></g></g><mask></mask><g stroke-linecap="round"><g transform="translate(69.1483201541107 61.21647526335062) rotate(0 13.138057949164534 -25.60823763167531)"><path d="M0 0 C-3.38 -4.12, -6.75 -8.24, -14.58 -17.79 M0 0 C-2.94 -3.58, -5.87 -7.17, -14.58 -17.79 M-14.58 -17.79 C-13.53 -28.61, -12.48 -39.43, -11.34 -51.22 M-14.58 -17.79 C-13.43 -29.64, -12.28 -41.49, -11.34 -51.22 M-11.34 -51.22 C5.87 -51.22, 23.09 -51.22, 40.85 -51.22 M-11.34 -51.22 C0.91 -51.22, 13.17 -51.22, 40.85 -51.22 M40.85 -51.22 C40.85 -41.63, 40.85 -32.05, 40.85 -8.17 M40.85 -51.22 C40.85 -39.67, 40.85 -28.12, 40.85 -8.17 M40.85 -8.17 C31.76 -6.35, 22.66 -4.53, 0 0 M40.85 -8.17 C31.97 -6.39, 23.08 -4.62, 0 0" stroke="#000000" stroke-width="4" fill="none"></path></g></g><mask></mask><g stroke-linecap="round"><g transform="translate(10 57.19446226550917) rotate(0 29.574160077055353 15.318639483348534)"><path d="M0 0 C12.58 -3.88, 25.16 -7.77, 44.57 -13.77 M0 0 C9.22 -2.85, 18.45 -5.7, 44.57 -13.77 M44.57 -13.77 C47.71 -9.94, 50.84 -6.12, 59.15 4.02 M44.57 -13.77 C47.84 -9.78, 51.1 -5.8, 59.15 4.02 M59.15 4.02 C56.04 14.66, 52.93 25.3, 47.35 44.4 M59.15 4.02 C56.49 13.12, 53.83 22.23, 47.35 44.4 M47.35 44.4 C34.36 44.4, 21.37 44.4, 0 44.4 M47.35 44.4 C29.87 44.4, 12.39 44.4, 0 44.4 M0 44.4 C0 35.21, 0 26.03, 0 0 M0 44.4 C0 30.19, 0 15.98, 0 0" stroke="#000000" stroke-width="4" fill="none"></path></g></g><mask></mask><g stroke-linecap="round"><g transform="translate(69.1483201541107 61.21647526335062) rotate(0 14.527581899009334 16.105022943497403)"><path d="M0 0 C14.31 -2.86, 28.62 -5.72, 40.85 -8.17 M0 0 C8.55 -1.71, 17.1 -3.42, 40.85 -8.17 M40.85 -8.17 C40.85 3.52, 40.85 15.21, 40.85 40.38 M40.85 -8.17 C40.85 7.02, 40.85 22.21, 40.85 40.38 M40.85 40.38 C27.51 40.38, 14.16 40.38, -11.8 40.38 M40.85 40.38 C24.32 40.38, 7.79 40.38, -11.8 40.38 M-11.8 40.38 C-8.16 27.95, -4.53 15.51, 0 0 M-11.8 40.38 C-8.75 29.96, -5.71 19.55, 0 0" stroke="#000000" stroke-width="4" fill="none"></path></g></g><mask></mask><g stroke-linecap="round" transform="translate(77.71307083157171 28.22928207659868) rotate(0 9.41776545535356 9.41776545535356)"><path d="M18.84 9.42 C18.84 9.96, 18.79 10.52, 18.69 11.05 C18.6 11.59, 18.45 12.13, 18.27 12.64 C18.08 13.15, 17.85 13.65, 17.57 14.13 C17.3 14.6, 16.98 15.05, 16.63 15.47 C16.28 15.89, 15.89 16.28, 15.47 16.63 C15.05 16.98, 14.6 17.3, 14.13 17.57 C13.65 17.85, 13.15 18.08, 12.64 18.27 C12.13 18.45, 11.59 18.6, 11.05 18.69 C10.52 18.79, 9.96 18.84, 9.42 18.84 C8.87 18.84, 8.32 18.79, 7.78 18.69 C7.25 18.6, 6.71 18.45, 6.2 18.27 C5.68 18.08, 5.18 17.85, 4.71 17.57 C4.24 17.3, 3.78 16.98, 3.36 16.63 C2.95 16.28, 2.55 15.89, 2.2 15.47 C1.85 15.05, 1.53 14.6, 1.26 14.13 C0.99 13.65, 0.75 13.15, 0.57 12.64 C0.38 12.13, 0.24 11.59, 0.14 11.05 C0.05 10.52, 0 9.96, 0 9.42 C0 8.87, 0.05 8.32, 0.14 7.78 C0.24 7.25, 0.38 6.71, 0.57 6.2 C0.75 5.68, 0.99 5.18, 1.26 4.71 C1.53 4.24, 1.85 3.78, 2.2 3.36 C2.55 2.95, 2.95 2.55, 3.36 2.2 C3.78 1.85, 4.24 1.53, 4.71 1.26 C5.18 0.99, 5.68 0.75, 6.2 0.57 C6.71 0.38, 7.25 0.24, 7.78 0.14 C8.32 0.05, 8.87 0, 9.42 0 C9.96 0, 10.52 0.05, 11.05 0.14 C11.59 0.24, 12.13 0.38, 12.64 0.57 C13.15 0.75, 13.65 0.99, 14.13 1.26 C14.6 1.53, 15.05 1.85, 15.47 2.2 C15.89 2.55, 16.28 2.95, 16.63 3.36 C16.98 3.78, 17.3 4.24, 17.57 4.71 C17.85 5.18, 18.08 5.68, 18.27 6.2 C18.45 6.71, 18.6 7.25, 18.69 7.78 C18.79 8.32, 18.81 9.15, 18.84 9.42 C18.86 9.69, 18.86 9.15, 18.84 9.42" stroke="none" stroke-width="0" fill="#1e1e1e"></path><path d="M18.84 9.42 C18.84 9.96, 18.79 10.52, 18.69 11.05 C18.6 11.59, 18.45 12.13, 18.27 12.64 C18.08 13.15, 17.85 13.65, 17.57 14.13 C17.3 14.6, 16.98 15.05, 16.63 15.47 C16.28 15.89, 15.89 16.28, 15.47 16.63 C15.05 16.98, 14.6 17.3, 14.13 17.57 C13.65 17.85, 13.15 18.08, 12.64 18.27 C12.13 18.45, 11.59 18.6, 11.05 18.69 C10.52 18.79, 9.96 18.84, 9.42 18.84 C8.87 18.84, 8.32 18.79, 7.78 18.69 C7.25 18.6, 6.71 18.45, 6.2 18.27 C5.68 18.08, 5.18 17.85, 4.71 17.57 C4.24 17.3, 3.78 16.98, 3.36 16.63 C2.95 16.28, 2.55 15.89, 2.2 15.47 C1.85 15.05, 1.53 14.6, 1.26 14.13 C0.99 13.65, 0.75 13.15, 0.57 12.64 C0.38 12.13, 0.24 11.59, 0.14 11.05 C0.05 10.52, 0 9.96, 0 9.42 C0 8.87, 0.05 8.32, 0.14 7.78 C0.24 7.25, 0.38 6.71, 0.57 6.2 C0.75 5.68, 0.99 5.18, 1.26 4.71 C1.53 4.24, 1.85 3.78, 2.2 3.36 C2.55 2.95, 2.95 2.55, 3.36 2.2 C3.78 1.85, 4.24 1.53, 4.71 1.26 C5.18 0.99, 5.68 0.75, 6.2 0.57 C6.71 0.38, 7.25 0.24, 7.Line truncated

After

Width:  |  Height:  |  Size: 14 KiB

+10 -10
View File
@@ -471,14 +471,6 @@
"fname": "Excalidraw Collaboration Frame.svg",
"mtime": 1687881495985
},
{
"fname": "Create DrawIO file.md",
"mtime": 1688243858267
},
{
"fname": "Create DrawIO file.svg",
"mtime": 1688243858267
},
{
"fname": "Ellipse Selected Elements.md",
"mtime": 1690131476331
@@ -689,7 +681,7 @@
},
{
"fname": "Comic Strip Director.md",
"mtime": 1783547608665
"mtime": 1785613946789
},
{
"fname": "Comic Strip Director.svg",
@@ -702,5 +694,13 @@
{
"fname": "Icon Library.svg",
"mtime": 1783432036549
},
{
"fname": "VoronoiDiagramGenerator.md",
"mtime": 1785733307861
},
{
"fname": "VoronoiDiagramGenerator.svg",
"mtime": 1785564296587
}
]
]
+18 -7
View File
@@ -101,6 +101,7 @@ These are the scripts I use most often. I tried to order them by importance, but
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Mindmap%20Builder.svg"/></div>|[[#Mindmap Builder]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Mindmap%20format.svg"/></div>|[[#Mindmap format]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Printable%20Layout%20Wizard.svg"/></div>|[[#Printable Layout Wizard]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/VoronoiDiagramGenerator.svg"/></div>|[[#Voronoi Diagram Generator]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Zoom%20to%20Fit%20Selected%20Elements.svg"/></div>|[[#Zoom to Fit Selected Elements]]|
## Connectors and Arrows
@@ -163,7 +164,6 @@ These are the scripts I use most often. I tried to order them by importance, but
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Add%20Link%20to%20Existing%20File%20and%20Open.svg"/></div>|[[#Add Link to Existing File and Open]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Add%20Link%20to%20New%20Page%20and%20Open.svg"/></div>|[[#Add Link to New Page and Open]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Convert%20text%20to%20link%20with%20folder%20and%20alias.svg"/></div>|[[#Convert text to link with folder and alias]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Create%20DrawIO%20file.svg"/></div>|[[#Create DrawIO file]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Create%20new%20markdown%20file%20and%20embed%20into%20active%20drawing.svg"/></div>|[[#Create new markdown file and embed into active drawing]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Folder%20Note%20Core%20-%20Make%20Current%20Drawing%20a%20Folder.svg"/></div>|[[#Folder Note Core - Make Current Drawing a Folder]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Set%20Link%20Alias.svg"/></div>|[[#Set Link Alias]]|
@@ -339,12 +339,6 @@ https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea
```
<table><tr valign='top'><td class="label">Author</td><td class="data"><a href='https://github.com/1-2-3'>@1-2-3</a></td></tr><tr valign='top'><td class="label">Source</td><td class="data"><a href='https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/ea-scripts/Copy%20Selected%20Element%20Styles%20to%20Global.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">This script will copy styles of any selected element into Excalidraw's global styles.<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-copy-selected-element-styles-to-global.png'></td></tr></table>
## Create DrawIO file
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Create%20DrawIO%20file.md
```
<table><tr valign='top'><td class="label">Author</td><td class="data"><a href='https://github.com/zsviczian'>@zsviczian</a></td></tr><tr valign='top'><td class="label">Source</td><td class="data"><a href='https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/ea-scripts/Create%20DrawIO%20file.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">The script will prompt you for a filename, then create a new draw.io diagram file and open the file in the <a href='https://github.com/zapthedingbat/drawio-obsidian'>Diagram plugin</a>, in a new tab.<br><a href="https://www.youtube.com/watch?v=DJcosmN-q2s" target="_blank"><img src ="https://i.ytimg.com/vi/DJcosmN-q2s/maxresdefault.jpg" style="width:400px;"></a></td></tr></table>
## Create new markdown file and embed into active drawing
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Create%20new%20markdown%20file%20and%20embed%20into%20active%20drawing.md
@@ -744,6 +738,23 @@ https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea
```
<table><tr valign='top'><td class="label">Author</td><td class="data"><a href='https://github.com/zsviczian'>@zsviczian</a></td></tr><tr valign='top'><td class="label">Source</td><td class="data"><a href='https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/ea-scripts/Printable%20Layout%20Wizard.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">Export Excalidraw to PDF Pages: Define printable page areas using frames, then export each frame as a separate page in a multi-page PDF. Perfect for turning your Excalidraw drawings into printable notes, handouts, or booklets. Supports standard and custom page sizes, margins, and easy frame arrangement.<br><a href="https://www.youtube.com/watch?v=29EWeglRm7s" target="_blank"><img src ="https://i.ytimg.com/vi/29EWeglRm7s/maxresdefault.jpg" style="width:400px;"></a><br><a href='https://youtu.be/29EWeglRm7s' target='_blank'>Link to video on YouTube</a><br><a href="https://www.youtube.com/watch?v=DqDnzCOoYMc" target="_blank"><img src ="https://i.ytimg.com/vi/DqDnzCOoYMc/maxresdefault.jpg" style="width:400px;"></a><br><a href='https://youtu.be/DqDnzCOoYMc' target='_blank'>Link to video on YouTube</a><br><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-layout-wizard-01.png" style="max-width: 400px;"><br><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-layout-wizard-02.png" style="max-width: 400px;"></td></tr></table>
## Voronoi Diagram Generator
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/VoronoiDiagramGenerator.md
```
<table><tr valign='top'><td class="label">Author</td><td class="data"><a href='https://github.com/FreeCutter'>@FreeCutter</a></td></tr><tr valign='top'><td class="label">Source</td><td class="data"><a href='https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/ea-scripts/VoronoiDiagramGenerator.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">This script generates a Voronoi diagram from selected elements on the drawing canvas.
The following parameters can be set in 'Voronoi Settings' window pop-up once the script is started:
- Frame width (default: 100)
- Roughness (default: 0)
- Stroke width (default: 2)
- Grouping (default: checked)
Setting parameters could be set back to default values by click on button 'Default'.
See background information about [Voronoi diagram](https://en.wikipedia.org/wiki/Voronoi_diagram) at Wikipedia.
Comments and discussion are welcomed in the [Sketch Your Mind Community](https://community.sketch-your-mind.com)<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/Voronoi_diagram_example.svg'></td></tr></table>
## Zoom to Fit Selected Elements
```excalidraw-script-install
+14
View File
@@ -28,6 +28,20 @@ export default tseslint.config(
languageOptions: {
globals: {
...globals.browser,
// Buffer/NodeJS/BufferEncoding: genuine ambient Node types available
// in Obsidian's Electron environment (used e.g. in DataAdapter.fs
// callbacks in src/types/types.d.ts).
...globals.node,
// @types/react/global.d.ts declares this as a bare top-level
// `interface` (an ambient script, not a module), so it becomes a
// real global type alongside HTMLDivElement etc. -- not something
// that can be imported.
HTMLWebViewElement: 'readonly',
// NodeJS/BufferEncoding: ambient @types/node type/namespace names
// (globals.node above only covers runtime values like `Buffer`,
// not these TS-only type names).
NodeJS: 'readonly',
BufferEncoding: 'readonly',
},
parserOptions: {
projectService: {
+2
View File
@@ -0,0 +1,2 @@
<svg version="1.1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1263.8361813410443 1175.0090977499947" width="1263.8361813410443" height="1175.0090977499947" class="excalidraw-svg"><!-- svg-source:excalidraw --><metadata></metadata><defs><style class="style-fonts">
</style></defs><rect x="0" y="0" width="1263.8361813410443" height="1175.0090977499947" fill="#ffffff"></rect><g stroke-linecap="round"><g transform="translate(54.70368721081013 565.1536157189742) rotate(0 176.3834212571344 -0.43978715755929443)"><path d="M0 0 C83.59 -44.85, 167.18 -89.69, 243.74 -130.77 M0 0 C76.87 -41.24, 153.74 -82.48, 243.74 -130.77 M243.74 -130.77 C275.1 -122.97, 306.45 -115.17, 347.23 -105.03 M243.74 -130.77 C269.96 -124.25, 296.18 -117.73, 347.23 -105.03 M347.23 -105.03 C348.69 -102.84, 350.16 -100.65, 352.77 -96.75 M347.23 -105.03 C349.17 -102.13, 351.11 -99.23, 352.77 -96.75 M352.77 -96.75 C346.03 -31.37, 339.29 34.01, 330.72 117.18 M352.77 -96.75 C344.5 -16.53, 336.23 63.7, 330.72 117.18 M330.72 117.18 C325.89 122.19, 321.06 127.19, 318.46 129.89 M330.72 117.18 C327.16 120.87, 323.61 124.55, 318.46 129.89 M318.46 129.89 C215.83 88.03, 113.21 46.17, 0 0 M318.46 129.89 C219.02 89.33, 119.58 48.77, 0 0" stroke="#000000" stroke-width="1" fill="none"></path></g></g><mask></mask><g stroke-linecap="round"><g transform="translate(787.0151296423978 50.95181640257783) rotate(0 24.21503087586143 268.49136541140206)"><path d="M0 0 C34.58 51.71, 69.16 103.43, 151.56 226.64 M0 0 C46.53 69.58, 93.06 139.16, 151.56 226.64 M151.56 226.64 C146.83 272.55, 142.1 318.45, 129.51 440.58 M151.56 226.64 C143.97 300.28, 136.38 373.92, 129.51 440.58 M129.51 440.58 C96.11 475.2, 62.71 509.82, 40.15 533.21 M129.51 440.58 C101.05 470.07, 72.6 499.57, 40.15 533.21 M40.15 533.21 C34.45 534.4, 28.75 535.6, 22.18 536.98 M40.15 533.21 C33.78 534.54, 27.41 535.88, 22.18 536.98 M22.18 536.98 C-10.55 498.88, -43.27 460.78, -80.4 417.56 M22.18 536.98 C-6.64 503.43, -35.46 469.88, -80.4 417.56 M-80.4 417.56 C-87.39 336.03, -94.38 254.51, -103.13 152.37 M-80.4 417.56 C-89.28 313.96, -98.16 210.36, -103.13 152.37 M-103.13 152.37 C-66.57 98.35, -30.01 44.34, 0 0 M-103.13 152.37 C-72.3 106.82, -41.47 61.27, 0 0" stroke="#000000" stroke-width="1" fill="none"></path></g></g><mask></mask><g stroke-linecap="round"><g transform="translate(291.93518791000906 67.8208608237735) rotate(0 -139.01064058404268 58.91726978854547)"><path d="M0 0 C-33.52 35.28, -67.03 70.57, -148.12 155.93 M0 0 C-48.23 50.78, -96.47 101.55, -148.12 155.93 M-148.12 155.93 C-200.08 163.59, -252.03 171.25, -281.94 175.66 M-148.12 155.93 C-198.35 163.34, -248.59 170.74, -281.94 175.66 M-281.94 175.66 C-281.94 125.38, -281.94 75.11, -281.94 -57.82 M-281.94 175.66 C-281.94 116.18, -281.94 56.7, -281.94 -57.82 M-281.94 -57.82 C-182.76 -57.82, -83.59 -57.82, 3.91 -57.82 M-281.94 -57.82 C-221.24 -57.82, -160.54 -57.82, 3.91 -57.82 M3.91 -57.82 C2.65 -39.11, 1.38 -20.4, 0 0 M3.91 -57.82 C3.12 -46.05, 2.32 -34.28, 0 0" stroke="#000000" stroke-width="1" fill="none"></path></g></g><mask></mask><g stroke-linecap="round"><g transform="translate(323.64815744858697 1008.5657439379145) rotate(0 134.74696302032476 -35.20122701427704)"><path d="M0 0 C9.07 -78.24, 18.14 -156.47, 24.77 -213.64 M0 0 C7.02 -60.54, 14.04 -121.08, 24.77 -213.64 M24.77 -213.64 C28.93 -217.85, 33.1 -222.05, 37.84 -226.85 M24.77 -213.64 C29.16 -218.07, 33.54 -222.5, 37.84 -226.85 M37.84 -226.85 C105.87 -198.49, 173.9 -170.13, 269.49 -130.28 M37.84 -226.85 C97 -202.18, 156.17 -177.52, 269.49 -130.28 M269.49 -130.28 C266.42 -65.14, 263.34 0, 261.06 48.48 M269.49 -130.28 C266.98 -76.95, 264.46 -23.62, 261.06 48.48 M261.06 48.48 C250.95 70.84, 240.85 93.2, 212.28 156.44 M261.06 48.48 C249.67 73.68, 238.28 98.88, 212.28 156.44 M212.28 156.44 C168.91 156.44, 125.54 156.44, 101.76 156.44 M212.28 156.44 C189.88 156.44, 167.48 156.44, 101.76 156.44 M101.76 156.44 C63.51 97.63, 25.26 38.83, 0 0 M101.76 156.44 C73.22 112.57, 44.68 68.7, 0 0" stroke="#000000" stroke-width="1" fill="none"></path></g></g><mask></mask><g stroke-linecap="round"><g transform="translate(978.0191004485864 1027.221004937913) rotate(0 137.90854044622893 -100.5203977296942)"><path d="M0 0 C9.87 -85.14, 19.74 -170.29, 24.77 -213.64 M0 0 C6.63 -57.21, 13.27 -114.41, 24.77 -213.64 M24.77 -213.64 C50.99 -240.13, 77.21 -266.63, 116.71 -306.55 M24.77 -213.64 C46.7 -235.8, 68.64 -257.97, 116.71 -306.55 M116.71 -306.55 C149.12 -313.12, 181.54 -319.7, 275.82 -338.83 M116.71 -306.55 C168.67 -317.09, 220.63 -327.63, 275.82 -338.83 M275.82 -338.83 C275.82 -155.19, 275.82 28.46, 275.82 137.79 M275.82 -338.83 C275.82 -230.05, 275.82 -121.27, 275.82 137.79 M275.82 137.79 C210.28 137.79, 144.75 137.79, 89.63 137.79 M275.82 137.79 C216.35 137.79, 156.88 137.79, 89.63 137.79 M89.63 137.79 C67.12 103.19, 44.62 68.59, 0 0 M89.63 137.79 C56.38 86.67, 23.13 35.56, 0 0" stroke="#000000" stroke-width="1" fill="none"></path></g></g><mask></mask><g stroke-linecap="round"><g transform="translate(558.7327432421484 682.3377911470559) rotate(0 -86.65644819683712 -106.9678206846113)"><path d="M0 0 C-42.87 0, -85.74 0, -173.31 0 M0 0 C-63.58 0, -127.17 0, -173.31 0 M-173.31 0 C-164.71 -83.5, -156.1 -167, -151.26 -213.94 M-173.31 0 C-166.91 -62.13, -160.51 -124.25Line truncated

After

Width:  |  Height:  |  Size: 64 KiB

+1 -1
View File
@@ -1,7 +1,7 @@
{
"id": "obsidian-excalidraw-plugin",
"name": "Excalidraw",
"version": "2.26.0-beta.1",
"version": "2.27.0-rc.2",
"minAppVersion": "1.8.7",
"description": "Sketch Your Mind. Edit and view Excalidraw drawings. Enter the world of 4D Visual PKM.",
"author": "Zsolt Viczian",
+1 -1
View File
@@ -1,7 +1,7 @@
{
"id": "obsidian-excalidraw-plugin",
"name": "Excalidraw",
"version": "2.25.3",
"version": "2.26.4",
"minAppVersion": "1.8.7",
"description": "Sketch Your Mind. Edit and view Excalidraw drawings. Enter the world of 4D Visual PKM.",
"author": "Zsolt Viczian",
+51 -131
View File
@@ -13,22 +13,20 @@
"@popperjs/core": "^2.11.8",
"@radix-ui/number": "^1.1.2",
"@zsviczian/colormaster": "^1.2.2",
"@zsviczian/excalidraw": "0.18.113-beta.4",
"@zsviczian/excalidraw": "0.18.130",
"chroma-js": "^3.1.2",
"clsx": "^2.0.0",
"es6-promise-pool": "2.5.0",
"gl-matrix": "^3.4.3",
"lz-string": "^1.5.0",
"monkey-around": "^2.3.0",
"nanoid": "^5.1.11",
"opentype.js": "^1.3.4",
"nanoid": "^5.1.16",
"pako": "^2.1.0",
"points-on-path": "^0.2.1",
"polybooljs": "^1.2.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"roughjs": "^4.5.2",
"yaml": "^2.9.0"
"react": "19.2.8",
"react-dom": "19.2.8",
"roughjs": "^4.5.2"
},
"devDependencies": {
"@babel/core": "^7.22.9",
@@ -52,11 +50,9 @@
"@types/chroma-js": "^3.1.1",
"@types/js-beautify": "^1.14.0",
"@types/node": "^22.19.19",
"@types/opentype.js": "^1.3.8",
"@types/react": "^18.2.45",
"@types/react-dom": "^18.2.18",
"@types/react": "19.2.18",
"@types/react-dom": "19.2.4",
"@zsviczian/excalidraw-extras-api": "^0.0.13",
"@zsviczian/rollup-plugin-postprocess": "^1.0.3",
"cross-env": "^7.0.3",
"cssnano": "^6.0.2",
"eslint": "^9.39.4",
@@ -64,7 +60,6 @@
"eslint-plugin-obsidianmd": "^0.4.0",
"eslint-plugin-prettier": "^5.0.0",
"jiti": "^2.6.1",
"jsesc": "^3.0.2",
"obsidian": "1.8.7",
"postcss": "^8.5.25",
"prettier": "^3.0.1",
@@ -2088,31 +2083,31 @@
}
},
"node_modules/@floating-ui/core": {
"version": "1.7.5",
"resolved": "https://registry.npmjs.org/@floating-ui/core/-/core-1.7.5.tgz",
"integrity": "sha512-1Ih4WTWyw0+lKyFMcBHGbb5U5FtuHJuujoyyr5zTaWS5EYMeT6Jb2AuDeftsCsEuchO+mM2ij5+q9crhydzLhQ==",
"version": "1.8.0",
"resolved": "https://registry.npmjs.org/@floating-ui/core/-/core-1.8.0.tgz",
"integrity": "sha512-0CIZ5itps/8x7BG8dEIhs53BvCUH2PCoogtakwRTut+Arm58sJooJ0AuZhLw2HJYIR5cMLNPBSS728sPho2khQ==",
"license": "MIT",
"dependencies": {
"@floating-ui/utils": "^0.2.11"
"@floating-ui/utils": "^0.2.12"
}
},
"node_modules/@floating-ui/dom": {
"version": "1.7.6",
"resolved": "https://registry.npmjs.org/@floating-ui/dom/-/dom-1.7.6.tgz",
"integrity": "sha512-9gZSAI5XM36880PPMm//9dfiEngYoC6Am2izES1FF406YFsjvyBMmeJ2g4SAju3xWwtuynNRFL2s9hgxpLI5SQ==",
"version": "1.8.0",
"resolved": "https://registry.npmjs.org/@floating-ui/dom/-/dom-1.8.0.tgz",
"integrity": "sha512-yXSrzeHZBTZadLOlfyhCkJHNeLJnHRnRInwdZ40L7ZiaAtrBwoYlsDrX3v5zB1Utk7CLfzcOVnVVWoXEky7Ceg==",
"license": "MIT",
"dependencies": {
"@floating-ui/core": "^1.7.5",
"@floating-ui/utils": "^0.2.11"
"@floating-ui/core": "^1.8.0",
"@floating-ui/utils": "^0.2.12"
}
},
"node_modules/@floating-ui/react-dom": {
"version": "2.1.8",
"resolved": "https://registry.npmjs.org/@floating-ui/react-dom/-/react-dom-2.1.8.tgz",
"integrity": "sha512-cC52bHwM/n/CxS87FH0yWdngEZrjdtLW/qVruo68qg+prK7ZQ4YGdut2GyDVpoGeAYe/h899rVeOVm6Oi40k2A==",
"version": "2.1.9",
"resolved": "https://registry.npmjs.org/@floating-ui/react-dom/-/react-dom-2.1.9.tgz",
"integrity": "sha512-JDjEFGCpImxDCA7JJKviA0M9+RtmJdj0m/NVU5IMgBK+AmZouAQQ7/+2GLH0GXXY0YMw9oXPB8hKdbPYg5QLYg==",
"license": "MIT",
"dependencies": {
"@floating-ui/dom": "^1.7.6"
"@floating-ui/dom": "^1.8.0"
},
"peerDependencies": {
"react": ">=16.8.0",
@@ -2120,9 +2115,9 @@
}
},
"node_modules/@floating-ui/utils": {
"version": "0.2.11",
"resolved": "https://registry.npmjs.org/@floating-ui/utils/-/utils-0.2.11.tgz",
"integrity": "sha512-RiB/yIh78pcIxl6lLMG0CgBXAZ2Y0eVHqMPYugu+9U0AeT6YBeiJpf7lbdJNIugFP5SIjwNRgo4DhR1Qxi26Gg==",
"version": "0.2.12",
"resolved": "https://registry.npmjs.org/@floating-ui/utils/-/utils-0.2.12.tgz",
"integrity": "sha512-HpCo8tmWzLVad5s2d19EhAz5zqrrQ6s69qd6moPMQvkOuSwDT1YgRfWSVuc4ennqrgv3OHppiOGMQ7oC13yIww==",
"license": "MIT"
},
"node_modules/@humanfs/core": {
@@ -4891,39 +4886,24 @@
"undici-types": "~6.21.0"
}
},
"node_modules/@types/opentype.js": {
"version": "1.3.10",
"resolved": "https://registry.npmjs.org/@types/opentype.js/-/opentype.js-1.3.10.tgz",
"integrity": "sha512-F67EFyk6j02okHz5JCgata3ZRAcZi9GLnzmkHw/rzJq3OCc8/ZVdoKrxMTYjcQP6IYHGBz2cav1cpzkOkPiPCQ==",
"dev": true,
"license": "MIT"
},
"node_modules/@types/prop-types": {
"version": "15.7.15",
"resolved": "https://registry.npmjs.org/@types/prop-types/-/prop-types-15.7.15.tgz",
"integrity": "sha512-F6bEyamV9jKGAFBEmlQnesRPGOQqS2+Uwi0Em15xenOxHaf2hv6L8YCVn3rPdPJOiJfPiCnLIRyvwVaqMY3MIw==",
"devOptional": true,
"license": "MIT"
},
"node_modules/@types/react": {
"version": "18.3.31",
"resolved": "https://registry.npmjs.org/@types/react/-/react-18.3.31.tgz",
"integrity": "sha512-vfEqpXTvwT91yhmwdfouStN2hSKwTvyRs8qpLfADyrq/kxDw0hZM7Wk9Ug1FELj8hIby+S/+kQCSRFF32nv2Qw==",
"version": "19.2.18",
"resolved": "https://registry.npmjs.org/@types/react/-/react-19.2.18.tgz",
"integrity": "sha512-AnzbBERsrLKtk2XSfTbYRLjQPdy116Sty4q+T+Bp3IC4l6jNBvreVPAHmpq9qhXQM7CXZPjLVmGMw9sy+hxQ3w==",
"devOptional": true,
"license": "MIT",
"dependencies": {
"@types/prop-types": "*",
"csstype": "^3.2.2"
}
},
"node_modules/@types/react-dom": {
"version": "18.3.7",
"resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-18.3.7.tgz",
"integrity": "sha512-MEe3UeoENYVFXzoXEWsvcpg6ZvlrFNlOQ7EOsvhI3CfAXwzPfO8Qwuxd40nepsYKqyyVQnTdEfv68q91yLcKrQ==",
"version": "19.2.4",
"resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-19.2.4.tgz",
"integrity": "sha512-Bsc+QHgp+P/F02XDzNCY9jnZNCUuLki36KT7VKrTXXLdHf+vHMNZnW1rVu5DNW/rCK+fya3DATySbLM4yhtKUw==",
"devOptional": true,
"license": "MIT",
"peerDependencies": {
"@types/react": "^18.0.0"
"@types/react": "^19.2.0"
}
},
"node_modules/@types/resolve": {
@@ -5274,9 +5254,9 @@
"license": "MIT"
},
"node_modules/@zsviczian/excalidraw": {
"version": "0.18.113-beta.4",
"resolved": "https://registry.npmjs.org/@zsviczian/excalidraw/-/excalidraw-0.18.113-beta.4.tgz",
"integrity": "sha512-uA+vo0RmyMrFrabGFkaKu7NST65osYZwvqpyGpJslkyicEqWdEZa9SIKrMss/GE6hPK0Rfau7FzRm5yNxhoudg==",
"version": "0.18.130",
"resolved": "https://registry.npmjs.org/@zsviczian/excalidraw/-/excalidraw-0.18.130.tgz",
"integrity": "sha512-+qsJ0B/qFWkT8ZZrgPn+FodZPko93NLIRsCrVqLG5fKFAqoEY22/IXcIRc72jion6D0XkN4wbJtBu/l6HtL7GQ==",
"license": "MIT",
"dependencies": {
"@braintree/sanitize-url": "6.0.2",
@@ -5361,26 +5341,6 @@
"integrity": "sha512-0mYKnYYe9ZcqMCWhUjItv/oHjvgEsfKvnUTg8sAtnHr3GVy7rGkXCb6d5cSyqrWqL4k81b9CPg3urd+T7aop3A==",
"license": "MIT"
},
"node_modules/@zsviczian/rollup-plugin-postprocess": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/@zsviczian/rollup-plugin-postprocess/-/rollup-plugin-postprocess-1.0.3.tgz",
"integrity": "sha512-W3t9TgbjNnZ07h+Vg78qAo0lFkYoovdlp5ojbiSP6aMswDIDdkvwrt4qQataN2kJ9UlkcvKB0pwsd1NWze8bqg==",
"dev": true,
"license": "MIT",
"dependencies": {
"magic-string": "^0.25.7"
}
},
"node_modules/@zsviczian/rollup-plugin-postprocess/node_modules/magic-string": {
"version": "0.25.9",
"resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.25.9.tgz",
"integrity": "sha512-RmF0AsMzgt25qzqqLc1+MbHmhdx0ojF2Fvs4XnOqz2ZOBXzzkEwc/dJQZCYHAn7v1jbVOjAZfK8msRn4BxO4VQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"sourcemap-codec": "^1.4.8"
}
},
"node_modules/acorn": {
"version": "8.16.0",
"resolved": "https://registry.npmjs.org/acorn/-/acorn-8.16.0.tgz",
@@ -9653,6 +9613,7 @@
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz",
"integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==",
"dev": true,
"license": "MIT"
},
"node_modules/js-yaml": {
@@ -9989,6 +9950,7 @@
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz",
"integrity": "sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==",
"dev": true,
"license": "MIT",
"dependencies": {
"js-tokens": "^3.0.0 || ^4.0.0"
@@ -10239,9 +10201,9 @@
}
},
"node_modules/nanoid": {
"version": "5.1.11",
"resolved": "https://registry.npmjs.org/nanoid/-/nanoid-5.1.11.tgz",
"integrity": "sha512-v+KEsUv2ps74PaSKv0gHTxTCgMXOIfBEbaqa6w6ISIGC7ZsvHN4N9oJ8d4cmf0n5oTzQz2SLmThbQWhjd/8eKg==",
"version": "5.1.16",
"resolved": "https://registry.npmjs.org/nanoid/-/nanoid-5.1.16.tgz",
"integrity": "sha512-kVrnsrJqMR8+oLJnGEmSWw9BivK5mt7H3FZatVRjrc5wGqFYuBxX1yG7+A7Gi5AefkX6t/oCkizcQgpu0cY1dQ==",
"funding": [
{
"type": "github",
@@ -10482,22 +10444,6 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/opentype.js": {
"version": "1.3.4",
"resolved": "https://registry.npmjs.org/opentype.js/-/opentype.js-1.3.4.tgz",
"integrity": "sha512-d2JE9RP/6uagpQAVtJoF0pJJA/fgai89Cc50Yp0EJHk+eLp6QQ7gBoblsnubRULNY132I0J1QKMJ+JTbMqz4sw==",
"license": "MIT",
"dependencies": {
"string.prototype.codepointat": "^0.2.1",
"tiny-inflate": "^1.0.3"
},
"bin": {
"ot": "bin/ot"
},
"engines": {
"node": ">= 8.0.0"
}
},
"node_modules/optionator": {
"version": "0.9.4",
"resolved": "https://registry.npmjs.org/optionator/-/optionator-0.9.4.tgz",
@@ -11410,28 +11356,24 @@
}
},
"node_modules/react": {
"version": "18.3.1",
"resolved": "https://registry.npmjs.org/react/-/react-18.3.1.tgz",
"integrity": "sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ==",
"version": "19.2.8",
"resolved": "https://registry.npmjs.org/react/-/react-19.2.8.tgz",
"integrity": "sha512-PWaYA1L/q9u2u7xYQi+Y3L3Yfnie7XyLeaJICV1MGD6LprsBxcAqGjYyr0eY3p+QdsA+x/Irkt4Qif8D63+Sbw==",
"license": "MIT",
"dependencies": {
"loose-envify": "^1.1.0"
},
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/react-dom": {
"version": "18.3.1",
"resolved": "https://registry.npmjs.org/react-dom/-/react-dom-18.3.1.tgz",
"integrity": "sha512-5m4nQKp+rZRb09LNH59GM4BxTh9251/ylbKIbpe7TpGxfJ+9kv6BLkLBXIjjspbgbnIBNqlI23tRnTWT0snUIw==",
"version": "19.2.8",
"resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.2.8.tgz",
"integrity": "sha512-rVprimfGBG3DR+Tq0IQG2DT5PxKth1WIGDmj5yPmlzr4YBe7uyE+Du4oVqTDXZSHGGGXRtTJEGSSePyQCMBglQ==",
"license": "MIT",
"dependencies": {
"loose-envify": "^1.1.0",
"scheduler": "^0.23.2"
"scheduler": "^0.27.0"
},
"peerDependencies": {
"react": "^18.3.1"
"react": "^19.2.8"
}
},
"node_modules/react-is": {
@@ -12012,13 +11954,10 @@
}
},
"node_modules/scheduler": {
"version": "0.23.2",
"resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.23.2.tgz",
"integrity": "sha512-UOShsPwz7NrMUqhR6t0hWjFduvOzbtv7toDH1/hIrfRNIDBnnBWd0CwJTGvTpngVlmwGCdP9/Zl/tVrDqcuYzQ==",
"license": "MIT",
"dependencies": {
"loose-envify": "^1.1.0"
}
"version": "0.27.0",
"resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.27.0.tgz",
"integrity": "sha512-eNv+WrVbKu1f3vbYJT/xtiF5syA5HPIMtf9IgY/nKg0sWqzAUEvqY/xm7OcZc/qafLx/iO9FgOmeSAp4v5ti/Q==",
"license": "MIT"
},
"node_modules/semver": {
"version": "6.3.1",
@@ -12245,14 +12184,6 @@
"source-map": "^0.6.0"
}
},
"node_modules/sourcemap-codec": {
"version": "1.4.8",
"resolved": "https://registry.npmjs.org/sourcemap-codec/-/sourcemap-codec-1.4.8.tgz",
"integrity": "sha512-9NykojV5Uih4lgo5So5dtw+f0JgJX30KCNI8gwhz2J9A15wD0Ml6tjHKwf6fTSa6fAdVBdZeNOs9eJ71qCk8vA==",
"deprecated": "Please use @jridgewell/sourcemap-codec instead",
"dev": true,
"license": "MIT"
},
"node_modules/speech-rule-engine": {
"version": "4.1.4",
"resolved": "https://registry.npmjs.org/speech-rule-engine/-/speech-rule-engine-4.1.4.tgz",
@@ -12292,12 +12223,6 @@
"node": ">= 0.4"
}
},
"node_modules/string.prototype.codepointat": {
"version": "0.2.1",
"resolved": "https://registry.npmjs.org/string.prototype.codepointat/-/string.prototype.codepointat-0.2.1.tgz",
"integrity": "sha512-2cBVCj6I4IOvEnjgO/hWqXjqBGsY+zwPmHl12Srk9IXSZ56Jwwmy+66XO5Iut/oQVR7t5ihYdLB0GMa4alEUcg==",
"license": "MIT"
},
"node_modules/string.prototype.matchall": {
"version": "4.0.12",
"resolved": "https://registry.npmjs.org/string.prototype.matchall/-/string.prototype.matchall-4.0.12.tgz",
@@ -12575,12 +12500,6 @@
"dev": true,
"license": "MIT"
},
"node_modules/tiny-inflate": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/tiny-inflate/-/tiny-inflate-1.0.3.tgz",
"integrity": "sha512-pkY1fj1cKHb2seWDy0B16HeWyczlJA9/WW3u3c4z/NiWDsO3DOU5D7nhTLE9CF0yXv/QZFY7sEJmj24dK+Rrqw==",
"license": "MIT"
},
"node_modules/tinyexec": {
"version": "1.2.4",
"resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-1.2.4.tgz",
@@ -13283,6 +13202,7 @@
"version": "2.9.0",
"resolved": "https://registry.npmjs.org/yaml/-/yaml-2.9.0.tgz",
"integrity": "sha512-2AvhNX3mb8zd6Zy7INTtSpl1F15HW6Wnqj0srWlkKLcpYl/gMIMJiyuGq2KeI2YFxUPjdlB+3Lc10seMLtL4cA==",
"dev": true,
"license": "ISC",
"bin": {
"yaml": "bin.mjs"
+8 -13
View File
@@ -30,22 +30,20 @@
"@popperjs/core": "^2.11.8",
"@radix-ui/number": "^1.1.2",
"@zsviczian/colormaster": "^1.2.2",
"@zsviczian/excalidraw": "0.18.113-beta.4",
"@zsviczian/excalidraw": "0.18.130",
"chroma-js": "^3.1.2",
"clsx": "^2.0.0",
"es6-promise-pool": "2.5.0",
"gl-matrix": "^3.4.3",
"lz-string": "^1.5.0",
"monkey-around": "^2.3.0",
"nanoid": "^5.1.11",
"opentype.js": "^1.3.4",
"nanoid": "^5.1.16",
"pako": "^2.1.0",
"points-on-path": "^0.2.1",
"polybooljs": "^1.2.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"roughjs": "^4.5.2",
"yaml": "^2.9.0"
"react": "19.2.8",
"react-dom": "19.2.8",
"roughjs": "^4.5.2"
},
"devDependencies": {
"@babel/core": "^7.22.9",
@@ -69,11 +67,9 @@
"@types/chroma-js": "^3.1.1",
"@types/js-beautify": "^1.14.0",
"@types/node": "^22.19.19",
"@types/opentype.js": "^1.3.8",
"@types/react": "^18.2.45",
"@types/react-dom": "^18.2.18",
"@types/react": "19.2.18",
"@types/react-dom": "19.2.4",
"@zsviczian/excalidraw-extras-api": "^0.0.13",
"@zsviczian/rollup-plugin-postprocess": "^1.0.3",
"cross-env": "^7.0.3",
"cssnano": "^6.0.2",
"eslint": "^9.39.4",
@@ -81,7 +77,6 @@
"eslint-plugin-obsidianmd": "^0.4.0",
"eslint-plugin-prettier": "^5.0.0",
"jiti": "^2.6.1",
"jsesc": "^3.0.2",
"obsidian": "1.8.7",
"postcss": "^8.5.25",
"prettier": "^3.0.1",
@@ -96,7 +91,7 @@
"lodash": "^4.18.1",
"lodash-es": "^4.18.1",
"serialize-javascript": "^7.0.5",
"nanoid": "^5.1.11",
"nanoid": "^5.1.16",
"dompurify": "^3.4.12",
"fast-uri": "^3.1.4",
"immutable": "^4.3.9",
+41 -53
View File
@@ -8,9 +8,7 @@ import copy from "rollup-plugin-copy";
import typescript from "@rollup/plugin-typescript";
import fs from 'fs';
import path from 'path';
import postprocess from '@zsviczian/rollup-plugin-postprocess';
import cssnano from 'cssnano';
import jsesc from 'jsesc';
import { minify } from 'uglify-js';
import json from '@rollup/plugin-json';
import { parseEnv } from 'node:util';
@@ -35,26 +33,6 @@ const isLib = (process.env.NODE_ENV === "lib");
console.log(`Running: ${process.env.NODE_ENV}; isProd: ${isProd}; isLib: ${isLib}`);
// Excalidraw React 19 compatiblity shim
// Create JSX runtime compatibility layer
const jsxRuntimeShim = `
const jsx = (type, props, key) => {
return React.createElement(type, props);
};
const jsxs = (type, props, key) => {
return React.createElement(type, props);
};
const Fragment = React.Fragment;
React.jsx = jsx;
React.jsxs = jsxs;
React.Fragment = Fragment;
React.jsxRuntime = { jsx, jsxs, Fragment };
window.__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__ = { jsx, jsxs, Fragment };
window.__WEBPACK_EXTERNAL_MODULE_react_jsx_dev_runtime__ = { jsx, jsxs, Fragment, jsxDEV: jsx };
window['react/jsx-runtime'] = { jsx, jsxs, Fragment };
window['react/jsx-dev-runtime'] = { jsx, jsxs, Fragment, jsxDEV: jsx };
`;
// Add non-English locales here to embed them as compressed payloads in main.js.
// When adding a locale file:
// 1) add its code to this list, 2) build once, 3) if build fails because the locale
@@ -94,22 +72,25 @@ function compressLanguageFile(lang) {
return compressDeflateBase64(minifyCode(`x = ${content};`));
}
const excalidraw_pkg = isLib ? "" : minifyCode(isProd
? fs.readFileSync("./node_modules/@zsviczian/excalidraw/dist/excalidraw.production.min.js", "utf8")
: fs.readFileSync("./node_modules/@zsviczian/excalidraw/dist/excalidraw.development.js", "utf8"));
const react_pkg = isLib ? "" : minifyCode(isProd
? fs.readFileSync("./node_modules/react/umd/react.production.min.js", "utf8")
: fs.readFileSync("./node_modules/react/umd/react.development.js", "utf8"));
const reactdom_pkg = isLib ? "" : minifyCode(isProd
? fs.readFileSync("./node_modules/react-dom/umd/react-dom.production.min.js", "utf8")
: fs.readFileSync("./node_modules/react-dom/umd/react-dom.development.js", "utf8"));
const pako_pkg = isLib ? "" : fs.readFileSync("./node_modules/pako/dist/pako.min.js", "utf8");
const excalidrawSource = isLib ? "" : fs.readFileSync(
isProd
? "./node_modules/@zsviczian/excalidraw/dist/obsidian/excalidraw.production.min.js"
: "./node_modules/@zsviczian/excalidraw/dist/obsidian/excalidraw.development.js",
"utf8",
);
const excalidraw_pkg = isLib
? ""
: isProd
? minifyCode(excalidrawSource)
: `${excalidrawSource}\n//# sourceURL=obsidian-excalidraw-runtime.development.js\n`;
// Runtime payloads are only decompressed; including Pako's deflate implementation
// would add unused code to the size-constrained Obsidian plugin bundle.
const pako_pkg = isLib ? "" : fs.readFileSync("./node_modules/pako/dist/pako_inflate.min.js", "utf8");
if (!isLib) {
const excalidraw_styles = isProd
? fs.readFileSync("./node_modules/@zsviczian/excalidraw/dist/styles.production.css", "utf8")
: fs.readFileSync("./node_modules/@zsviczian/excalidraw/dist/styles.development.css", "utf8");
? fs.readFileSync("./node_modules/@zsviczian/excalidraw/dist/obsidian/excalidraw.production.min.css", "utf8")
: fs.readFileSync("./node_modules/@zsviczian/excalidraw/dist/obsidian/excalidraw.development.css", "utf8");
const plugin_styles = fs.readFileSync("./styles.css", "utf8");
const styles = excalidraw_styles + plugin_styles;
cssnano()
@@ -140,10 +121,7 @@ const packageString = isLib
' ' + pako_pkg + '\n' +
' return module.exports;\n' +
'})();\n' +
'\nlet REACT_PACKAGES = `' +
jsesc(react_pkg + reactdom_pkg + jsxRuntimeShim, { quotes: 'backtick' }) +
'`;\n' +
// NEW: Fast, mobile-compatible runtime decompression
// Define the dependency-free inflater used by compressed runtime payloads.
'const unpackBase64Deflate = (b64) => {\n' +
' const binStr = atob(b64);\n' +
' const len = binStr.length;\n' +
@@ -153,7 +131,6 @@ const packageString = isLib
'};\n' +
'window.unpackBase64Deflate = unpackBase64Deflate;\n' +
'const unpackExcalidraw = () => unpackBase64Deflate("' + compressDeflateBase64(excalidraw_pkg) + '");\n' +
'let {react, reactDOM } = new Function(`${REACT_PACKAGES}; return {react: React, reactDOM: ReactDOM};`)();\n' +
'let excalidrawLib = {};\n' +
`const PLUGIN_LANGUAGES = {${LANGUAGES.map(lang => `"${lang}": "${compressLanguageFile(lang)}"`).join(",")}};\n` +
//These declarations were moved here because Obsidian code scanner incorrectly flags them with a warning,
@@ -171,7 +148,20 @@ const packageString = isLib
//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 PLUGIN_VERSION="${manifest.version}";\n` +
//Moved here since the Obsidian code scanner warning to avoid unnecessary logging appears
//to users, creating the impression that there is unnecessary logging. There isn't.
//Errors and debug information is logged. Nothing else.
`const consoleLog = console["log"].bind(console);\n` +
//Obsidian code scanner fails if document.createElement rule is ignored using the eslint-ignore comment
//the code scanner also does not allow creating style elements and guides plugins to use style.css
//the code scanner does not recognize valid cases such as creating canvas elements for image generation
//adding a style element to an iframe that is used to create an image
//I am sorry, but I got fatigued creating issues for all my edge cases with the eslint-plugin...
//given the amount of extra time it takes, and the the usual lack of any meaningful timely response
//Since I want to continue releasing Excalidraw versions, and not risk getting flagged for failed releases
//I see no other meaningful option
`const deliberateCreateElement = (doc, tagName) => doc.createElement(tagName);\n`;
const BASE_CONFIG = {
input: 'src/core/main.ts',
@@ -189,8 +179,13 @@ const BASE_CONFIG = {
'@lezer/lr',
'obsidian',
'@zsviczian/excalidraw',
'react',
'react-dom'
...(isLib ? [
'react',
'react-dom',
'react-dom/client',
'react/jsx-runtime',
'react/jsx-dev-runtime',
] : []),
],
};
@@ -221,6 +216,7 @@ const BUILD_CONFIG = {
format: 'cjs',
exports: 'default',
inlineDynamicImports: true, // Add this line only
banner: packageString,
},
plugins: getRollupPlugins(
{
@@ -235,21 +231,13 @@ const BUILD_CONFIG = {
comments: false, // Remove all comments
},
}),
postprocess([
[
/(var[^;]*?),\s*React\s*=\s*require\(["']react["']\)([^;]*;)/,
(_, g1, g2) => `${g1}${g2}${packageString}`
],
]),
/*visualizer({
filename: 'bundle-analysis.html',
open: true, // Automatically opens in your browser when the build finishes
gzipSize: true,
brotliSize: true,
}),*/
] : [
postprocess([[/var React = require\('react'\);/, packageString]]),
]),
] : []),
copy({
targets: [{ src: 'manifest.json', dest: DIST_FOLDER }],
verbose: true,
@@ -279,4 +267,4 @@ if (process.env.NODE_ENV === "lib") {
config.push(BUILD_CONFIG);
}
export default config;
export default config;
File diff suppressed because it is too large. Load diff
+304
View File
@@ -0,0 +1,304 @@
#!/usr/bin/env bash
# generate-repository-zip.sh
#
# Run from the root of a repository:
#
# bash generate-repository-zip.sh
#
# Generates:
# ./repository.zip
#
# The ZIP preserves the repository-relative directory structure while excluding:
# - node_modules, dist, and other ignored folders
# - __MACOSX folders
# - .DS_Store and other ignored filenames
# - common binary/media/archive/executable file types
# - files detected as binary even if their extension is unknown
#
# Requirements:
# - bash
# - find
# - file
# - zip
#
# Edit IGNORE_DIRS, IGNORE_FILENAMES, and IGNORE_EXTENSIONS below to customize.
set -euo pipefail
OUTPUT="repository.zip"
# ---------------------------------------------------------------------------
# Folder exclusions
# ---------------------------------------------------------------------------
# Folder names are matched at any depth.
IGNORE_DIRS=(
".git"
".svn"
".hg"
"node_modules"
"dist"
".next"
".nuxt"
".cache"
".parcel-cache"
".turbo"
".idea"
".vscode"
".tools"
"coverage"
"build"
"out"
"output"
"secrets"
".claude"
"__MACOSX"
)
# ---------------------------------------------------------------------------
# Filename exclusions
# ---------------------------------------------------------------------------
# Exact filenames are matched at any depth.
IGNORE_FILENAMES=(
".DS_Store"
"Thumbs.db"
"REPOSITORY_STRUCTURE.md"
"REPOSITORY_CONTENTS.md"
# Never package a previously generated repository archive.
"repository.zip"
)
# ---------------------------------------------------------------------------
# File-type exclusions
# ---------------------------------------------------------------------------
# Extensions are lowercase and include the leading dot.
IGNORE_EXTENSIONS=(
# Images
".png"
".jpg"
".jpeg"
".gif"
".webp"
".bmp"
".tif"
".tiff"
".ico"
".icns"
".avif"
".heic"
".heif"
".svg"
".svgz"
# PDF / ebook / office containers
".pdf"
".epub"
".doc"
".docx"
".xls"
".xlsx"
".ppt"
".pptx"
# Audio
".mp3"
".wav"
".flac"
".aac"
".m4a"
".ogg"
".opus"
".wma"
# Video
".mp4"
".mov"
".mkv"
".avi"
".webm"
".m4v"
".mpeg"
".mpg"
# Fonts
".ttf"
".otf"
".woff"
".woff2"
".eot"
# Archives / compressed files
".zip"
".tar"
".gz"
".tgz"
".bz2"
".xz"
".7z"
".rar"
# Native binaries / executables / compiled objects
".exe"
".dll"
".so"
".dylib"
".bin"
".com"
".app"
".msi"
".o"
".obj"
".a"
".lib"
".class"
".jar"
".war"
".wasm"
".node"
# Binary databases / data formats
".db"
".sqlite"
".sqlite3"
".parquet"
".arrow"
".feather"
)
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
contains_exact() {
local needle="$1"
shift
local item
for item in "$@"; do
[[ "$needle" == "$item" ]] && return 0
done
return 1
}
path_has_ignored_dir() {
local relative_path="$1"
local dir
for dir in "${IGNORE_DIRS[@]}"; do
if [[ "$relative_path" == "$dir/"* || "$relative_path" == *"/$dir/"* ]]; then
return 0
fi
done
return 1
}
is_ignored_filename() {
local filename="$1"
contains_exact "$filename" "${IGNORE_FILENAMES[@]}"
}
is_ignored_extension() {
local filename="$1"
local lower
lower="$(printf '%s' "$filename" | tr '[:upper:]' '[:lower:]')"
local ext
for ext in "${IGNORE_EXTENSIONS[@]}"; do
[[ "$lower" == *"$ext" ]] && return 0
done
return 1
}
looks_binary() {
local file_path="$1"
# Empty files are harmless text-like repository artifacts.
[[ ! -s "$file_path" ]] && return 1
# `file --mime-encoding` returns "binary" for binary data on macOS/Linux.
local encoding
encoding="$(file -b --mime-encoding "$file_path" 2>/dev/null || true)"
[[ "$encoding" == "binary" ]]
}
# ---------------------------------------------------------------------------
# Build file list
# ---------------------------------------------------------------------------
command -v zip >/dev/null 2>&1 || {
echo "Error: 'zip' is required but was not found." >&2
exit 1
}
command -v file >/dev/null 2>&1 || {
echo "Error: 'file' is required but was not found." >&2
exit 1
}
TMP_LIST="$(mktemp)"
trap 'rm -f "$TMP_LIST"' EXIT
included=0
skipped_binary=0
skipped_type=0
skipped_name=0
skipped_dir=0
while IFS= read -r -d '' full_path; do
relative_path="${full_path#./}"
filename="${relative_path##*/}"
if path_has_ignored_dir "$relative_path"; then
((skipped_dir += 1))
continue
fi
if is_ignored_filename "$filename"; then
((skipped_name += 1))
continue
fi
if is_ignored_extension "$filename"; then
((skipped_type += 1))
continue
fi
if looks_binary "$full_path"; then
((skipped_binary += 1))
continue
fi
printf '%s\n' "$relative_path" >> "$TMP_LIST"
((included += 1))
done < <(find . -type f -print0)
# Remove any previous archive before creating the new one.
rm -f "$OUTPUT"
if [[ ! -s "$TMP_LIST" ]]; then
echo "No files matched the inclusion rules; no ZIP created."
exit 0
fi
# -q quiet
# -@ read file paths from stdin
#
# Repository-relative paths are stored in the archive, not absolute paths.
zip -q "$OUTPUT" -@ < "$TMP_LIST"
echo "Created $OUTPUT"
echo "Included files: $included"
echo "Skipped because of ignored folders: $skipped_dir"
echo "Skipped because of ignored filenames: $skipped_name"
echo "Skipped because of ignored file types: $skipped_type"
echo "Skipped because binary content was detected: $skipped_binary"
+9 -667
View File
@@ -1,676 +1,18 @@
/* eslint-disable no-console */
// to run: node generate-script-library.mjs
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
// Reconstruct __dirname for ES Modules
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const ROOT = path.resolve(__dirname, '..');
const EA_SCRIPTS_DIR = path.join(ROOT, 'ea-scripts');
const INDEX_NEW = path.join(EA_SCRIPTS_DIR, 'index-new.md');
const OUT_DIR = path.join(path.join(ROOT, 'docs'), 'AITrainingData');
const SCRIPT_LIBRARY_OUT = path.join(OUT_DIR, 'Excalidraw Script Library.md');
const TYPE_DEF_OUT = path.join(OUT_DIR, 'Excalidraw Automate library and related type definitions.md');
const AI_TRAINING_OUT = path.join(OUT_DIR, 'ExcalidrawAutomate full library for LLM training.md');
const AI_TRAINING_INTRO = `**ExcalidrawAutomate full library for LLM training**
Excalidraw-Obsidian is an Obsidian.md plugins that is built on the open source Excalidraw component. Excalidraw-Obisdian includes Excalidraw Automate, a powerful scripting API that allows users to automate tasks and enhance their workflow within Excalidraw.
Read the information below and respond with I'm ready. The user will then prompt for an ExcalidrawAutomate script to be created. Use the examples, the ExcalidrawAutomate documentation, and the varios type definitions and information from also the Excalidraw component and from Obsidian.md to generate the script based on the user's requirements.
In addition to ExcalidrawAutomate, you can also use two other sources of functions:
- The Excalidraw API available via \`ea.getExcalidrawAPI()\`. Note: the API is only available if \`ea.targetView\` is set. When running Excalidraw scripts using the script engine, the provided \`ea\` object is already set up with targetView by default. Otherwise you need to first run \`ea.setView()\`.
- \`window.ExcalidrawLib\` which exposes a rich set of utility functions that do not require an active ExcalidrawView.
**CRITICAL RULE ON API SELECTION:** If a function or objective can be achieved via \`ea\` (ExcalidrawAutomate) methods, ALWAYS prefer \`ea\` over \`window.ExcalidrawLib\`. \`ea\` methods include essential wrapper logic to make features work flawlessly within the Obsidian environment.
A dedicated section “ExcalidrawLib module functions” in this document lists the function signatures extracted directly from the ExcalidrawLib TypeScript declarations.
- When the user asks for a dialog window, by default create a FloatingModal. Do not extend the FloatingModal class. Instead, define the modal's behavior by creating a new instance (e.g., \`const modal = new ea.FloatingModal(...)\`) and then assigning functions directly to the \`onOpen\` and \`onClose\` properties of that instance.
For a reference, follow the implementation pattern used in the "Printable Layout Wizard.md" script.
- Elements have a \`customData\` property that can be used to store arbitrary data. To ensure the data the script adds to elements use the \`ea.addAppendUpdateCustomData\` function. This function ensures that existing customData is preserved when adding new data.
- Elements can be hidden by setting their opacity to 0. When hiding elements this way, it is good practice to temporarily store their original opacity in customData. This allows for easy restoration of the original opacity later.
- Elements can be deleted from the scene by setting their isDeleted property to true.
- The Obsidian.md module is available on \`ea.obsidian\`.
**Sidepanels and multi-view tooling:**
- Sidepanels are for scripts that must stay open while users hop between multiple Excalidraw views. They should implement the SidepanelTab hooks (\`onOpen\`, \`onFocus(view)\`, \`onClose\`, \`onExcalidrawViewClosed\`) and manage their own \`ea.targetView\` explicitly.
- Persisted sidepanel scripts are launched during plugin startup (e.g., Obsidian restart, plugin update) with \`ea.targetView === null\`. Scripts must handle this by deferring view-bound work until \`onFocus\` delivers a view; call \`ea.setView(view)\` when you decide to bind.
- Each \`ea\` instance may host a single \`sidepanelTab\`. This sidepanel tab is stored in \`ea.sidepanelTab\`. Create the tab with \`ea.createSidepanelTab(title, persist=false, reveal=true)\`; the returned \`ea.sidepanelTab\` exposes \`contentEl\`, \`setContent\`, \`setTitle\`, \`setDisabled\`, \`setCloseCallback\`, \`open/close\`, and focus lifecycle hooks. Note auto-reveal during tab creation via \`ea.createSidepanelTab()\` is disabled during plugin startup. You can reveal a tab with \`ea.sidepanelTab?.open()\`. You can persist with \`ea.persistSidepanelTab()\` (tabs are restored and scripts re-run on next startup). Close with \`ea.sidepanelTab?.close()\`.
- Mobile UX: sidepanels slide in without disturbing canvas layout and are better for longer forms than floating modals. Prefer them for complex inputs, especially on phones.
- Auto-closing patterns: For scripts that use sidepanels but perform operations that are single-\`ExcalidrawView\` relevant, they can call \`ea.closeSidepanelTab()\` after completing the operation, and/or inside \`ea.sidepanelTab.onFocus = (view) => { if (view !== ea.targetView) { ea.sidepanelTab?.close(); } }\` to shut down when the user leaves the originating view.
- Scripts can detect view change in \`onFocus(view)\` by comparing \`ea.targetView\` to the provided \`view\` parameter.
- Persistence UX: scripts may offer a “Persist tab” control inside \`contentEl\` that calls \`ea.persistSidepanelTab()\`. Once persisted, hide that control; users can later remove the tab via the sidepanel close button (scripts cannot unpersist themselves, but can close themselves via \`ea.sidepanelTab?.close()\`).
- Use \`checkForActiveSidepanelTabForScript\` to avoid creating duplicate tabs for the same script name. This method returns the \`ExcalidrawSidepanelTab\` associated with the supplied \`scriptName\` (or \`ea.activeScript\` when omitted), or \`null\` if none exists. It is intended to let a script detect an existing tab that may be owned by another \`ExcalidrawAutomate\` instance (for example, a persisted tab restored at startup). Typical pattern:
- Before creating a new sidepanel, call \`ea.checkForActiveSidepanelTabForScript()\` to see if a tab already exists.
- If a tab exists and \`tab.getHostEA() === ea\`, reuse it (your script already hosts it).
- If a tab exists but is hosted by a different \`ea\` instance, decide whether to reuse or hand off control — e.g. open the existing tab and exit to avoid duplicates.
- Note: persisted tabs restored on startup may be created with \`ea.targetView === null\` and hosted by a different \`ea\` instance; handle that case by waiting for \`onFocus\` before binding view-specific work.
- Example usage:
\`const sp = ea.checkForActiveSidepanelTabForScript();
if (sp) {
if (sp.getHostEA() === ea) {
// we already own the tab — reuse it
sp.open();
} else {
// another EA instance hosts the tab — open it for the user and exit
sp.open();
return;
}
}
// no existing tab — safe to create a new one
// ea.createSidepanelTab("My Script", false, true);\`
- A dedicated section "sidepanelTabTypes.d.ts" in this document lists the \`ExcalidrawSidepanelTab\` function signatures.
#### **0. External Documentation & Resources**
To keep this training file concise, large external type definitions are not included. If you need to look up Obsidian APIs or Excalidraw internals, refer to the following resources:
- **Obsidian API Type Definitions:** https://github.com/obsidianmd/obsidian-api/blob/master/obsidian.d.ts
- **Obsidian Developer Docs:** https://docs.obsidian.md/Home (Community site with API and CSS documentation/examples)
- **Obsidian Developer Forum:** https://forum.obsidian.md/c/developers-api/14
- **ExcalidrawAutomate Implementation:** If the provided API documentation is unclear, consult the source directly: https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/src/shared/ExcalidrawAutomate.ts
- **Excalidraw Core Fork:** For doubts regarding core Excalidraw functionality, consult the fork used by the plugin: https://github.com/zsviczian/excalidraw
#### **1. The Core Workflow: Handling Element Immutability**
* **Central Rule:** Elements in the Excalidraw scene are immutable and should never be modified directly. Always use the ExcalidrawAutomate (EA) "workbench" pattern for modifications.
* **The Workflow:**
1. Get elements from the current view using \`ea.getViewElements()\` or \`ea.getViewSelectedElements()\`.
2. Copy these elements into the EA workbench for editing using \`ea.copyViewElementsToEAforEditing(elements)\`.
3. Modify the properties of the element copies that are now in the EA workbench (e.g., \`ea.getElement(id).locked = true;\`).
4. Commit the changes back to the scene using \`await ea.addElementsToView()\`.
* **Deletion:** To delete an element, set its \`isDeleted\` property to \`true\` on the workbench copy (\`ea.getElement(id).isDeleted = true;\`) and then commit with \`await ea.addElementsToView()\`.
* **Cleanup:** Use \`ea.clear()\` at the beginning of a script if you are creating a completely new set of elements, to ensure the EA workbench is empty and doesn't contain artifacts from a previous run.
#### **2. User Interaction: Prompts and Dialogs**
* **Simple Input:** For straightforward user input, use the \`utils\` object provided to the script.
* \`await utils.inputPrompt()\`: To get a string or number from the user.
* \`await utils.suggester()\`: To let the user select from a predefined list of options.
* **Complex Dialogs:** When a more complex UI with multiple controls is needed, create a floating dialog window.
* **Use \`FloatingModal\`:** Always create a new instance: \`const modal = new ea.FloatingModal(ea.plugin.app);\`.
* **Do Not Extend:** Do not use \`class MyModal extends ea.FloatingModal\`.
* **Define Behavior:** Assign functions directly to the \`onOpen\` and \`onClose\` properties of the instance. Inside \`onOpen\`, use the \`modal.contentEl\` property to build your UI.
* **Reference Implementation:** The script "Printable Layout Wizard.md" is the canonical example for this pattern. Use \`ea.obsidian.Setting\` to add controls like toggles and dropdowns within the modal.
#### **3. Element Manipulation and Querying**
* **Finding Elements:** The most common starting point is to get the user's selection with \`ea.getViewSelectedElements()\`. Use standard JavaScript array methods like \`.filter()\` to narrow down the selection (e.g., \`elements.filter(el => el.type === "text")\`).
* **Geometric Calculations:**
* Before performing layout or positioning tasks, use \`ea.getBoundingBox(elements)\` to get the collective dimensions and position of a group of elements.
* Use \`ea.measureText(text)\` to determine the width and height of a string based on the current \`ea.style\` settings before creating a text element or a container for it.
* **Grouping:**
* To create a group, use \`ea.addToGroup([elementId1, elementId2, ...])\`.
* To operate on existing groups within a selection, use \`ea.getMaximumGroups(selectedElements)\` which correctly identifies the top-level groups. Use \`ea.getLargestElement(group)\` to find the primary container within a group (e.g., the box around a text element).
#### **4. Styling: Creation vs. Modification**
* **For New Elements:** Set the properties on the global \`ea.style\` object *before* you call a creation function like \`ea.addText()\` or \`ea.addRect()\`. This acts like setting the active color/style on a paintbrush.
* **For Existing Elements:** To change the style of an existing element, modify the properties directly on the element's copy in the EA workbench (after \`copyViewElementsToEAforEditing\`). For example: \`const myElement = ea.getElement(id); myElement.strokeColor = '#FF0000';\`.
#### **5. Data Persistence and Customization**
* **Storing Custom Data:** Elements have a \`customData\` property for arbitrary data.
* **Always Use \`ea.addAppendUpdateCustomData(id, newData)\`:** This is crucial. It safely adds or updates your key-value pairs without overwriting data that might have been stored by other scripts or the Excalidraw plugin itself.
* **Creating Configurable Scripts:** To make your script's behavior customizable by the user:
* Use \`ea.getScriptSettings()\` to retrieve saved settings.
* scriptSettings are stored with Excalidraw settings in Obsidian data.json. Keep this light. You MUST NEVER save large data objects such as base64 images or huge arrays here. Keep this lean and efficient.
* Check if settings exist, and if not, define the default structure.
* Use \`await ea.setScriptSettings(settings)\` to save any changes. This allows users to configure your script in the Excalidraw plugin settings pane.
#### **6. Best Practices and Advanced Techniques**
* **Script Overview Block (MANDATORY):** Create, and consistently maintain with each update, a comprehensive comment block at the very beginning of the script. This block must explain the purpose of the script, its key features, and the high-level solution logic or architecture.
* **Strictly Modular Architecture (NO LOOSE CODE):** Avoid creating large monolithic blocks of code or leaving logic loose at the root level of the script. Instead, organize *everything* into relatively small, atomic functions. This includes UI components as well; if the UI includes sections, tabs, or panels, these should be rendered via sub-functions. This is a critical requirement to ensure long-term maintainability and evolution of the script, as loose code quickly becomes unmanageable over multiple iterative prompts.
* **Evergreen JSDoc Headers and Comments:** Every function must have a proper JSDoc/Javadoc-style header containing parameter names, types, and a clear description of the function's purpose. These descriptions must be kept *evergreen* (updated alongside any code changes). Additionally, when modifying or updating a script, you must strictly *retain all existing internal code comments*.
* **Isolate Constants and User-Facing Strings:** *Do not embed hardcoded magic values, config parameters, or UI strings deep inside the logic.* You must separate all constants and language strings and collect them at the very top of the file. This makes it easier to tweak values later and provides a clear, unified section for localization and customization.
* **Icons:** Obsidian uses https://lucide.dev icons. These icons are available for scripts via \`ea.obsidian.getIcon("Icon Name")\`. For UI components prefer use of lucide.dev icons.
* **Omit Version Verification:** While many of the sample scripts in the library include a version verification block at the outset (using \`ea.verifyMinimumPluginVersion\`), *do not add this section* when generating a new script unless explicitly instructed to do so.
* **Embrace \`await\`:** Many EA functions are asynchronous and return a \`Promise\` (e.g., \`ea.addElementsToView()\`, \`ea.createSVG()\`, \`utils.inputPrompt()\`). **Always** use \`await\` when calling these functions to ensure your script executes in the correct order.
* **Accessing Obsidian API:** The full Obsidian API is available via \`ea.obsidian\`. For example, use \`new ea.obsidian.Notice("message")\` or \`ea.obsidian.normalizePath(filepath)\`.
* **Accessing Excalidraw API:** The full Excalidraw API is available on \`ea.getExcalidrawAPI()\`, these API functions are Scene dependent. Additional support functions are available on \`window.ExcalidrawLib\`.
* **Visibility vs. Deletion:**
* To temporarily hide an element, set \`element.opacity = 0\`. It's good practice to store the original opacity in \`customData\` so it can be restored. It is also recommended to lock hidden elements so they do not get accidentally selected or moved around.
* To permanently remove an element from the scene, set \`element.isDeleted = true\`.
* **Image Handling:** When dealing with image elements, use \`ea.getViewFileForImageElement(imageElement)\` to get the corresponding \`TFile\` from the Obsidian vault. This is necessary for any logic that needs to read or manipulate the source image file.
#### **7. SVG and Image Export Approaches**
Generating images (SVG/PNG) requires specific approaches depending on the context. Follow these three rules strictly to avoid performance issues and missing assets:
1. **Exporting elements currently in the EA workbench:** Use \`await ea.createSVG(null, ...)\` or \`await ea.createPNG(null, ...)\` (passing \`null\` as the \`templatePath\`).
2. **Exporting an Excalidraw file that is NOT currently open:** Pass the file path as the template to \`createSVG\` or \`createPNG\` (e.g., \`await ea.createSVG(file.path, ...)\`). This is the most reliable approach as ExcalidrawAutomate natively handles loading the scene, resolving embedded images, and instantiating loaders behind the scenes. **Do NOT attempt to manually read the file, reconstruct the scene, or load images into memory.**
3. **Exporting the currently active \`ExcalidrawView\`:** Use \`await ea.createViewSVG(...)\`. This is specifically for the open view. You can use the \`elementsOverride\` parameter to inject temporary elements (like transparent sizing rectangles) into the exported image without modifying the actual scene.
#### **8. Custom Pens and Perfect Freehand**
Excalidraw's freehand tool is powered by the open-source Perfect Freehand library. The plugin exposes “custom pens” that bundle:
- Canvas style for the next strokes (colors, width, fillStyle, roughness).
- Perfect Freehand stroke geometry and behavior (pressure simulation, outline, tapering, easing, etc.).
Key concepts:
- AppState-driven drawing: When \`appState.currentStrokeOptions\` is set, the freedraw tool renders new strokes using those Perfect Freehand options.
- Element-level persistence: If a freedraw element has \`element.customData.strokeOptions\`, it is rendered with those options regardless of the current tool state.
- Types reference: See \`src/types/penTypes.ts\`. The \`PenOptions\` shape is:
\`\`\`ts
interface PenOptions {
highlighter: boolean; // if true the pen is drawn at the lowest layer, behind all other elements
constantPressure: boolean;
hasOutline: boolean;
outlineWidth: number;
options: {
thinning: number;
smoothing: number;
streamline: number;
easing: string; // see supported names below
start: { cap: boolean; taper: number | boolean; easing: string; };
end: { cap: boolean; taper: number | boolean; easing: string; };
};
}
\`\`\`
Using custom pens from scripts:
- Activate a custom pen for drawing:
\`\`\`ts
// obtain the Excalidraw API
const api = ea.getExcalidrawAPI();
// define Perfect Freehand options (example similar to "finetip")
const penOptions = {
highlighter: false,
constantPressure: true,
hasOutline: false,
outlineWidth: 1,
options: {
thinning: -0.5,
smoothing: 0.4,
streamline: 0.4,
easing: "linear",
start: { taper: 5, cap: false, easing: "linear" },
end: { taper: 5, cap: false, easing: "linear" },
},
};
// apply stroke options + canvas style, then switch to freedraw (strokeWidth, color, background, fillStyle are optional)
ea.viewUpdateScene({
appState: {
currentStrokeOptions: penOptions,
currentItemStrokeWidth: 0.5,
currentItemStrokeColor: "#3E6F8D",
currentItemBackgroundColor: "transparent",
currentItemFillStyle: "hachure",
},
});
api.setActiveTool({ type: "freedraw" });
\`\`\`
- Clear custom pen (revert to default freedraw behavior):
\`\`\`ts
ea.viewUpdateScene({ appState: { currentStrokeOptions: null } });
\`\`\`
- Persist custom strokeOptions onto existing freedraw elements:
\`\`\`ts
const selected = ea.getViewSelectedElements().filter(el => el.type === "freedraw");
ea.copyViewElementsToEAforEditing(selected);
for (const el of selected) {
ea.addAppendUpdateCustomData(el.id, { strokeOptions: penOptions });
}
await ea.addElementsToView();
\`\`\`
Notes:
- New strokes respect \`appState.currentStrokeOptions\` at draw time. Existing elements only change if you update their \`customData.strokeOptions\`.
- For pens that should behave like real markers/highlighters, set \`highlighter: true\` and often \`constantPressure: true\` with an \`outlineWidth\` for the edge.
Supported easing names (string values for \`options.easing\`, \`options.start.easing\`, \`options.end.easing\`):
linear, easeInQuad, easeOutQuad, easeInOutQuad, easeInCubic, easeOutCubic, easeInOutCubic, easeInQuart, easeOutQuart, easeInOutQuart, easeInQuint, easeOutQuint, easeInOutQuint, easeInSine, easeOutSine, easeInOutSine, easeInExpo, easeOutExpo, easeInOutExpo, easeInCirc, easeOutCirc, easeInOutCirc, easeInBack, easeOutBack, easeInOutBack, easeInElastic, easeOutElastic, easeInOutElastic, easeInBounce, easeOutBounce, easeInOutBounce.
Example freedraw element carrying \`customData.strokeOptions\`:
\`\`\`json
{"type":"excalidraw/clipboard","elements":[{"id":"...","type":"freedraw","strokeColor":"#3E6F8D","backgroundColor":"transparent","fillStyle":"hachure","strokeWidth":0.5,"roughness":0,"customData":{"strokeOptions":{"highlighter":false,"hasOutline":false,"outlineWidth":0,"constantPressure":true,"options":{"smoothing":0.4,"thinning":-0.5,"streamline":0.4,"easing":"linear","start":{"taper":5,"cap":false,"easing":"linear"},"end":{"taper":5,"cap":false,"easing":"linear"}}}}}],"files":{}}
\`\`\`
#### **9. Text Element**
* There are three text properties.
* **textElement.text** holds the wrapped, rendered text. This is what is displayed in the view. Excalidraw adds '\\n' linebreaks during dynamic wrapping.
* **textElement.originalText** holds the rendered, but unwrapped text. Any '\\n' character in originalText is an intentional linebreak by the user. Rendered means that for example [[wiki links]] are rendered without the square brackets.
* **textElement.rawText** holds the original raw text including intentional new line characters and the full markdown markup (thought currently only links are rendered, so markdown support is limited to these)
* When modifying element text from script, typically all 3 of these properties must be updated, though in case textElement.autoresize === true, or when a text element is bound in a container, excalidraw will update textElement.text following the size of the text element or the container.
`;
const SCRIPT_INTRO = `# Excalidraw Script Library Examples
This is an automatically generated knowledge base intended for Retrieval Augmented Generation (RAG) and other AI-assisted workflows (e.g. NotebookLM or local embeddings tools).
Its purpose:
- Provide a single, query-friendly corpus of all Excalidraw Automate scripts.
- Serve as a practical pattern and snippet library for developers learning Excalidraw Automate.
- Preserve original source side by side with the higher-level index (index-new.md) to improve semantic recall.
- Enable AI tools to answer questions about how to manipulate the Excalidraw canvas, elements, styling, or integration features by referencing real, working examples.
Content structure:
1. SCRIPT_INTRO (this section)
2. The curated script overview (index-new.md)
3. Raw source of every *.md script in /ea-scripts (each fenced code block is auto-closed to ensure well-formed aggregation)
Generated on: ${new Date().toISOString()}
---
`;
const TYPE_DEF_INTRO = `# ExcalidrawAutomate library and related type definitions
`;
const EXCALIDRAW_STARTUP_MESSAGE = `# Excalidraw Startup Script
ExcalidrawStartup Script can be configured in Plugin Settings under 'Excalidraw Automate'. When defined this script runs automatically when the Excalidraw plugin is loaded to Obsidian. The user can add automation tasks here that they want to run on every startup of Excalidraw in Obsidian such as defining Excalidraw event handlers (also known as hooks).
Two files follow. First the template startup script with documenation comments, then an actual startup script example with implemented functionality.
`;
const EXCALIDRAW_STARTUP_TEMPLATE = "src/constants/assets/startupScript.md";
const EXCALIDRAW_STARTUP_EXAMPLE = "docs/AITrainingData/ExcalidrawStartupExample.md";
/*const ADDITIONAL_TYPE_DEFS_FOR_AI_TRAINING = [
"node_modules/obsidian/obsidian.d.ts",
];*/
const TYPE_DEF_WHITELIST = [
"lib/shared/ExcalidrawAutomate.d.ts",
"lib/types/excalidrawAutomateTypes.d.ts",
"lib/types/sidepanelTabTypes.d.ts",
"lib/types/penTypes.d.ts",
"lib/types/utilTypes.d.ts",
"lib/types/exportUtilTypes.d.ts",
"lib/types/embeddedFileLoaderTypes.d.ts",
"lib/types/AIUtilTypes.d.ts",
"node_modules/@zsviczian/excalidraw/types/element/src/types.d.ts",
"node_modules/@zsviczian/excalidraw/types/excalidraw/types.d.ts",
"node_modules/@zsviczian/excalidraw/types/element/src/bounds.d.ts",
"node_modules/@zsviczian/excalidraw/types/excalidraw/components/App.d.ts",
];
/**
* Returns true if content contains at least one line starting with ```
* and has an odd number of fences (unbalanced).
*/
function needsClosingFence(content) {
const fenceCount = (content.match(/^```/gm) || []).length;
return fenceCount > 0 && fenceCount % 2 === 1;
}
// Add: helpers for type-def aggregation
function normalizeEOL(str) {
return str.replace(/\r\n/g, '\n');
}
function stripBOM(str) {
return str.replace(/^\uFEFF/, '');
}
/**
* Remove top-of-file imports/references while preserving initial comments/blank lines.
* Also removes bare "export {}" lines (module markers).
*/
function stripTopImports(content) {
const lines = normalizeEOL(stripBOM(content)).split('\n');
const out = [];
let inTopRegion = true;
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
const isImport =
/^\s*import\s+type\s+/.test(line) ||
/^\s*import\s+/.test(line) ||
/^\s*import\(/.test(line);
const isTripleRef = /^\s*\/\/\/\s*<reference/.test(line);
const isBareExportModule = /^\s*export\s*\{\s*\};?\s*$/.test(line);
if (inTopRegion) {
if (isImport || isTripleRef) {
// drop
continue;
}
// comments and blanks are kept, top-region continues until first code (non-comment/non-blank/non-import)
const isBlank = /^\s*$/.test(line);
const isLineComment = /^\s*\/\//.test(line);
const isBlockCommentStart = /^\s*\/\*/.test(line);
if (!isBlank && !isLineComment && !isBlockCommentStart) {
inTopRegion = false;
}
if (!isBareExportModule) out.push(line);
continue;
}
if (!isBareExportModule) out.push(line);
}
return out.join('\n').trim() + '\n';
}
/**
* Create a nice section header for the concatenated file.
*/
function makeSectionHeader(relPath) {
const stars = '*'.repeat(Math.max(6, Math.min(38, relPath.length + 6)));
return [
`/* ${stars} */`,
`/* ${relPath} */`,
`/* ${stars} */`,
].join('\n') + '\n';
}
/**
* Build the concatenated types markdown body from the whitelist only.
* - Removes top-of-file imports
* - Adds section headers with relative paths
* - Wraps all in one ```js code fence
*/
function buildTypeDefMarkdown() {
const entries = TYPE_DEF_WHITELIST.map((rel) => ({
rel,
abs: path.join(ROOT, ...rel.split('/')),
}));
let body = '```js\n';
for (const { rel, abs } of entries) {
if (!fs.existsSync(abs)) {
console.warn('[script-library] Whitelist file missing:', rel);
continue;
}
let content = fs.readFileSync(abs, 'utf8');
content = stripTopImports(content);
body += makeSectionHeader(rel);
body += content.trimEnd() + '\n\n';
}
body += '```\n';
return body;
}
// NEW: Resolve module specifiers from types/excalidraw/index.d.ts to absolute .d.ts paths
function resolveExcalModulePath(spec, excalIndexAbs) {
const baseTypesRoot = path.join(ROOT, 'node_modules', '@zsviczian', 'excalidraw', 'types');
if (spec.startsWith('@excalidraw/')) {
const sub = spec.slice('@excalidraw/'.length); // e.g. 'element', 'element/bounds'
const parts = sub.split('/');
const pkg = parts.shift(); // 'element' | 'common' | 'utils'
const rest = parts;
if (!pkg) return null;
const base = path.join(baseTypesRoot, pkg);
if (rest.length === 0) {
return path.join(base, 'src', 'index.d.ts');
}
return path.join(base, 'src', ...rest) + '.d.ts';
}
// relative to the excalidraw index.d.ts
if (spec.startsWith('.')) {
const dir = path.dirname(excalIndexAbs);
return path.resolve(dir, spec) + '.d.ts';
}
// anything else is not expected
return null;
}
// NEW: Extract function signatures for a set of names from a .d.ts file
function extractFunctionSignaturesFromModule(absPath, names) {
const out = {};
if (!absPath || !fs.existsSync(absPath)) {
return out;
}
const content = fs.readFileSync(absPath, 'utf8');
for (const rawName of names) {
const name = rawName.trim();
if (!name) continue;
// Try "export declare function NAME ..."
let m = content.match(new RegExp(`export\\s+declare\\s+function\\s+${name}[\\s\\S]*?;`, 'm'));
if (m) {
out[name] = m[0].trim();
continue;
}
// Try "declare function NAME ..." (re-exported later)
m = content.match(new RegExp(`(^|\\n)declare\\s+function\\s+${name}[\\s\\S]*?;`, 'm'));
if (m) {
// Ensure it starts with export for readability
out[name] = m[0].replace(/^\s*declare\s+/, 'export declare ').trim();
continue;
}
// Try "export declare const NAME: (...args) => ...;"
m = content.match(new RegExp(`export\\s+declare\\s+const\\s+${name}\\s*:\\s*[\\s\\S]*?=>[\\s\\S]*?;`, 'm'));
if (m) {
out[name] = m[0].trim();
continue;
}
// Try "export declare function-type via type alias" (rare) - fallback to any const function shape
m = content.match(new RegExp(`export\\s+declare\\s+(?:var|let|const)\\s+${name}\\s*:\\s*[\\s\\S]*?;`, 'm'));
if (m && /=>/.test(m[0])) {
out[name] = m[0].trim();
continue;
}
}
return out;
}
// NEW: Build "ExcalidrawLib module functions" section from index.d.ts
function buildExcalidrawLibFunctionsSection() {
const excalIndexRel = 'node_modules/@zsviczian/excalidraw/types/excalidraw/index.d.ts';
const excalIndexAbs = path.join(ROOT, ...excalIndexRel.split('/'));
if (!fs.existsSync(excalIndexAbs)) {
console.warn('[script-library] Missing Excalidraw index.d.ts:', excalIndexRel);
return '';
}
const content = fs.readFileSync(excalIndexAbs, 'utf8');
const reExport = /export\s*\{\s*([\s\S]*?)\s*\}\s*from\s*["']([^"']+)["'];/g;
// Collect names by source module
const moduleToNames = new Map();
for (const match of content.matchAll(reExport)) {
const namesChunk = match[1];
const spec = match[2];
// skip if the export list contains only types we know we shouldn't include? We'll filter later by signature detection.
const names = namesChunk
.split(',')
.map((s) => s.trim())
.filter(Boolean);
if (!names.length) continue;
const abs = resolveExcalModulePath(spec, excalIndexAbs);
if (!abs) continue;
const key = spec;
const curr = moduleToNames.get(key) || { abs, names: new Set() };
for (const n of names) curr.names.add(n);
moduleToNames.set(key, curr);
}
// Extract signatures
const seen = new Set();
const sections = [];
let functionsFound = 0;
for (const [spec, { abs, names }] of moduleToNames) {
const sigs = extractFunctionSignaturesFromModule(abs, Array.from(names));
const sigEntries = Object.entries(sigs)
.filter(([name]) => {
if (seen.has(name)) return false;
seen.add(name);
return true;
})
.sort(([a], [b]) => a.localeCompare(b, 'en', { sensitivity: 'base' }));
if (!sigEntries.length) continue;
const rel = path.relative(ROOT, abs).replace(/\\/g, '/');
const header = makeSectionHeader(`${spec} -> ${rel}`).replace(/\*\/\n\/\*/g, '*\/\n/*'); // keep style
sections.push(header + sigEntries.map(([, s]) => s).join('\n') + '\n');
functionsFound += sigEntries.length;
}
if (!sections.length) {
console.warn('[script-library] No function signatures found in ExcalidrawLib exports.');
}
const body =
'# ExcalidrawLib module functions\n\n' +
'The following functions are exposed via window.ExcalidrawLib. Signatures are extracted from TypeScript declarations.\n\n' +
'```ts\n' +
sections.join('\n') +
'```\n';
console.log(`[script-library] Collected ${functionsFound} ExcalidrawLib function signatures`);
return body;
}
import { runUnifiedGeneration } from './excalidraw-docs-generator-core.mjs';
function main() {
console.log('[script-library] Generating Excalidraw Script Library...');
if (!fs.existsSync(EA_SCRIPTS_DIR)) {
console.error('ea-scripts directory not found:', EA_SCRIPTS_DIR);
process.exit(1);
}
if (!fs.existsSync(INDEX_NEW)) {
console.error('index-new.md not found:', INDEX_NEW);
process.exit(1);
}
if (!fs.existsSync(OUT_DIR)) {
fs.mkdirSync(OUT_DIR, { recursive: true });
}
let output = SCRIPT_INTRO;
console.log('[script-library] Adding index-new.md');
const indexNewContent = fs.readFileSync(INDEX_NEW, 'utf8');
output += `<!-- BEGIN index-new.md -->\n${indexNewContent.trim()}\n<!-- END index-new.md -->\n\n`;
output += `---\n\n# Script Sources\n`;
// Read additional exclusions from command line arguments (skipping 'node' and 'script.mjs')
const args = process.argv.slice(2);
const cmdLineExcludes = args.map(arg => arg.toLowerCase());
// Define the default exclusions (all in lower case for comparison)
const defaultExcludes = [
'index-new.md',
'mindmap builder.md',
'color scheme manager.md',
'comic strip director.md'
];
// Combine both into a single Set for easy lookup
const exclusions = new Set([...defaultExcludes, ...cmdLineExcludes]);
// Collect *.md files (non-recursive) excluding our combined list
const files = fs
.readdirSync(EA_SCRIPTS_DIR, { withFileTypes: true })
.filter(
(d) =>
d.isFile() &&
(d.name.endsWith('.md') || d.name.toLowerCase() === "mindmap builder.js") &&
!exclusions.has(d.name.toLowerCase())
)
.map((d) => d.name)
.sort((a, b) => a.localeCompare(b, 'en', { sensitivity: 'base' }));
for (const file of files) {
const full = path.join(EA_SCRIPTS_DIR, file);
let content = fs.readFileSync(full, 'utf8');
output += `\n---\n\n## ${file}\n`;
output += `<!-- Source: ea-scripts/${file} -->\n\n`;
// Normalize line endings
content = content.replace(/\r\n/g, '\n');
output += content.trimEnd() + '\n';
if (needsClosingFence(content)) {
output += '```\n';
console.log(`[script-library] Added missing closing fence to ${file}`);
} else {
console.log(`[script-library] Added ${file} (no fence fix needed)`);
}
}
fs.writeFileSync(SCRIPT_LIBRARY_OUT, output, 'utf8');
console.log('[script-library] Wrote:', SCRIPT_LIBRARY_OUT);
// Generate TYPE_DEF_OUT from whitelist
try {
console.log('[script-library] Generating Type Definition Library...');
const typeDefs = TYPE_DEF_INTRO + '\n' + buildTypeDefMarkdown();
fs.writeFileSync(TYPE_DEF_OUT, typeDefs, 'utf8');
console.log('[script-library] Wrote:', TYPE_DEF_OUT);
} catch (e) {
console.error('[script-library] Failed to generate TYPE_DEF_OUT:', e);
}
// NEW: Generate AI_TRAINING_OUT
try {
console.log('[script-library] Generating AI Training bundle...');
const typeDefContent = fs.existsSync(TYPE_DEF_OUT)
? fs.readFileSync(TYPE_DEF_OUT, 'utf8')
: (TYPE_DEF_INTRO + '\n' + buildTypeDefMarkdown());
const scriptLibContent = fs.existsSync(SCRIPT_LIBRARY_OUT)
? fs.readFileSync(SCRIPT_LIBRARY_OUT, 'utf8')
: '';
// NEW: load startup template and example
const startupTemplatePath = path.join(ROOT, ...EXCALIDRAW_STARTUP_TEMPLATE.split('/'));
const startupExamplePath = path.join(ROOT, ...EXCALIDRAW_STARTUP_EXAMPLE.split('/'));
const startupTemplate = fs.existsSync(startupTemplatePath)
? fs.readFileSync(startupTemplatePath, 'utf8').replace(/\r\n/g, '\n').trim()
: (console.warn('[script-library] Missing startup template:', EXCALIDRAW_STARTUP_TEMPLATE), '');
const startupExample = fs.existsSync(startupExamplePath)
? fs.readFileSync(startupExamplePath, 'utf8').replace(/\r\n/g, '\n').trim()
: (console.warn('[script-library] Missing startup example:', EXCALIDRAW_STARTUP_EXAMPLE), '');
const startupSection =
'\n---\n\n' +
EXCALIDRAW_STARTUP_MESSAGE +
'\n' +
(startupTemplate
? `<!-- ${EXCALIDRAW_STARTUP_TEMPLATE} -->\n${startupTemplate}\n\n`
: '') +
(startupExample
? `<!-- ${EXCALIDRAW_STARTUP_EXAMPLE} -->\n${startupExample}\n`
: '');
// NEW: Build ExcalidrawLib functions section
const excalidrawLibFunctionsSection = buildExcalidrawLibFunctionsSection();
const combined =
(AI_TRAINING_INTRO +
'\n---\n\n' +
typeDefContent.trim() +
'\n\n---\n\n' +
excalidrawLibFunctionsSection +
'\n---\n\n' +
scriptLibContent.trim() +
startupSection +
'\n')
.replaceAll("https://youtu.be/", "YouTube: ")
.replaceAll("https://www.youtube.com/watch?v=", "YouTube: ")
.replaceAll("https://www.youtube.com/", "YouTube: "); // prevent accidental link triggering
fs.writeFileSync(AI_TRAINING_OUT, combined, 'utf8');
console.log('[script-library] Wrote:', AI_TRAINING_OUT);
} catch (e) {
console.error('[script-library] Failed to generate AI_TRAINING_OUT:', e);
}
console.log('[script-library] Done.');
console.log('[script-library] Running unified documentation generator (full mode)...');
const result = runUnifiedGeneration({
mode: 'full',
args: process.argv.slice(2),
});
console.log('[script-library] Wrote outputs:', result.generated);
console.log('[script-library] Processed scripts:', result.scriptsProcessed);
}
// ESM equivalent of `if (require.main === module)`
if (process.argv[1] === fileURLToPath(import.meta.url)) {
try {
main();
@@ -678,4 +20,4 @@ if (process.argv[1] === fileURLToPath(import.meta.url)) {
console.error('[script-library] Failed:', e);
process.exit(1);
}
}
}
+9 -632
View File
@@ -1,641 +1,18 @@
/* eslint-disable no-console */
// to run: node skill-builder.mjs
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
// Reconstruct __dirname for ES Modules
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const ROOT = path.resolve(__dirname, '..');
const EA_SCRIPTS_DIR = path.join(ROOT, 'ea-scripts');
const OUT_DIR = path.join(ROOT, 'docs', 'AITrainingData');
// Agent Skills Specific Definitions
const SKILL_NAME = 'excalidraw-automate';
const SKILL_DIR = path.join(OUT_DIR, SKILL_NAME);
const SKILL_REFERENCES_DIR = path.join(SKILL_DIR, 'references');
const SKILL_SCRIPTS_DIR = path.join(SKILL_REFERENCES_DIR, 'scripts');
const AI_TRAINING_INTRO = `**ExcalidrawAutomate full library for LLM training**
Excalidraw-Obsidian is an Obsidian.md plugins that is built on the open source Excalidraw component. Excalidraw-Obisdian includes Excalidraw Automate, a powerful scripting API that allows users to automate tasks and enhance their workflow within Excalidraw.
Read the information below and respond with I'm ready. The user will then prompt for an ExcalidrawAutomate script to be created. Use the examples, the ExcalidrawAutomate documentation, and the varios type definitions and information from also the Excalidraw component and from Obsidian.md to generate the script based on the user's requirements.
In addition to ExcalidrawAutomate, you can also use two other sources of functions:
- The Excalidraw API available via \`ea.getExcalidrawAPI()\`. Note: the API is only available if \`ea.targetView\` is set. When running Excalidraw scripts using the script engine, the provided \`ea\` object is already set up with targetView by default. Otherwise you need to first run \`ea.setView()\`.
- \`window.ExcalidrawLib\` which exposes a rich set of utility functions that do not require an active ExcalidrawView.
**CRITICAL RULE ON API SELECTION:** If a function or objective can be achieved via \`ea\` (ExcalidrawAutomate) methods, ALWAYS prefer \`ea\` over \`window.ExcalidrawLib\`. \`ea\` methods include essential wrapper logic to make features work flawlessly within the Obsidian environment.
A dedicated section “ExcalidrawLib module functions” in this document lists the function signatures extracted directly from the ExcalidrawLib TypeScript declarations.
- When the user asks for a dialog window, by default create a FloatingModal. Do not extend the FloatingModal class. Instead, define the modal's behavior by creating a new instance (e.g., \`const modal = new ea.FloatingModal(...)\`) and then assigning functions directly to the \`onOpen\` and \`onClose\` properties of that instance.
For a reference, follow the implementation pattern used in the "Printable Layout Wizard.md" script.
- Elements have a \`customData\` property that can be used to store arbitrary data. To ensure the data the script adds to elements use the \`ea.addAppendUpdateCustomData\` function. This function ensures that existing customData is preserved when adding new data.
- Elements can be hidden by setting their opacity to 0. When hiding elements this way, it is good practice to temporarily store their original opacity in customData. This allows for easy restoration of the original opacity later.
- Elements can be deleted from the scene by setting their isDeleted property to true.
- The Obsidian.md module is available on \`ea.obsidian\`.
**Sidepanels and multi-view tooling:**
- Sidepanels are for scripts that must stay open while users hop between multiple Excalidraw views. They should implement the SidepanelTab hooks (\`onOpen\`, \`onFocus(view)\`, \`onClose\`, \`onExcalidrawViewClosed\`) and manage their own \`ea.targetView\` explicitly.
- Persisted sidepanel scripts are launched during plugin startup (e.g., Obsidian restart, plugin update) with \`ea.targetView === null\`. Scripts must handle this by deferring view-bound work until \`onFocus\` delivers a view; call \`ea.setView(view)\` when you decide to bind.
- Each \`ea\` instance may host a single \`sidepanelTab\`. This sidepanel tab is stored in \`ea.sidepanelTab\`. Create the tab with \`ea.createSidepanelTab(title, persist=false, reveal=true)\`; the returned \`ea.sidepanelTab\` exposes \`contentEl\`, \`setContent\`, \`setTitle\`, \`setDisabled\`, \`setCloseCallback\`, \`open/close\`, and focus lifecycle hooks. Note auto-reveal during tab creation via \`ea.createSidepanelTab()\` is disabled during plugin startup. You can reveal a tab with \`ea.sidepanelTab?.open()\`. You can persist with \`ea.persistSidepanelTab()\` (tabs are restored and scripts re-run on next startup). Close with \`ea.sidepanelTab?.close()\`.
- Mobile UX: sidepanels slide in without disturbing canvas layout and are better for longer forms than floating modals. Prefer them for complex inputs, especially on phones.
- Auto-closing patterns: For scripts that use sidepanels but perform operations that are single-\`ExcalidrawView\` relevant, they can call \`ea.closeSidepanelTab()\` after completing the operation, and/or inside \`ea.sidepanelTab.onFocus = (view) => { if (view !== ea.targetView) { ea.sidepanelTab?.close(); } }\` to shut down when the user leaves the originating view.
- Scripts can detect view change in \`onFocus(view)\` by comparing \`ea.targetView\` to the provided \`view\` parameter.
- Persistence UX: scripts may offer a “Persist tab” control inside \`contentEl\` that calls \`ea.persistSidepanelTab()\`. Once persisted, hide that control; users can later remove the tab via the sidepanel close button (scripts cannot unpersist themselves, but can close themselves via \`ea.sidepanelTab?.close()\`).
- Use \`checkForActiveSidepanelTabForScript\` to avoid creating duplicate tabs for the same script name. This method returns the \`ExcalidrawSidepanelTab\` associated with the supplied \`scriptName\` (or \`ea.activeScript\` when omitted), or \`null\` if none exists. It is intended to let a script detect an existing tab that may be owned by another \`ExcalidrawAutomate\` instance (for example, a persisted tab restored at startup). Typical pattern:
- Before creating a new sidepanel, call \`ea.checkForActiveSidepanelTabForScript()\` to see if a tab already exists.
- If a tab exists and \`tab.getHostEA() === ea\`, reuse it (your script already hosts it).
- If a tab exists but is hosted by a different \`ea\` instance, decide whether to reuse or hand off control — e.g. open the existing tab and exit to avoid duplicates.
- Note: persisted tabs restored on startup may be created with \`ea.targetView === null\` and hosted by a different \`ea\` instance; handle that case by waiting for \`onFocus\` before binding view-specific work.
- Example usage:
\`const sp = ea.checkForActiveSidepanelTabForScript();
if (sp) {
if (sp.getHostEA() === ea) {
// we already own the tab — reuse it
sp.open();
} else {
// another EA instance hosts the tab — open it for the user and exit
sp.open();
return;
}
}
// no existing tab — safe to create a new one
// ea.createSidepanelTab("My Script", false, true);\`
- A dedicated section "sidepanelTabTypes.d.ts" in this document lists the \`ExcalidrawSidepanelTab\` function signatures.
#### **0. External Documentation & Resources**
To keep this training file concise, large external type definitions are not included. If you need to look up Obsidian APIs or Excalidraw internals, refer to the following resources:
- **Obsidian API Type Definitions:** https://github.com/obsidianmd/obsidian-api/blob/master/obsidian.d.ts
- **Obsidian Developer Docs:** https://docs.obsidian.md/Home (Community site with API and CSS documentation/examples)
- **Obsidian Developer Forum:** https://forum.obsidian.md/c/developers-api/14
- **ExcalidrawAutomate Implementation:** If the provided API documentation is unclear, consult the source directly: https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/src/shared/ExcalidrawAutomate.ts
- **Excalidraw Core Fork:** For doubts regarding core Excalidraw functionality, consult the fork used by the plugin: https://github.com/zsviczian/excalidraw
#### **1. The Core Workflow: Handling Element Immutability**
* **Central Rule:** Elements in the Excalidraw scene are immutable and should never be modified directly. Always use the ExcalidrawAutomate (EA) "workbench" pattern for modifications.
* **The Workflow:**
1. Get elements from the current view using \`ea.getViewElements()\` or \`ea.getViewSelectedElements()\`.
2. Copy these elements into the EA workbench for editing using \`ea.copyViewElementsToEAforEditing(elements)\`.
3. Modify the properties of the element copies that are now in the EA workbench (e.g., \`ea.getElement(id).locked = true;\`).
4. Commit the changes back to the scene using \`await ea.addElementsToView()\`.
* **Deletion:** To delete an element, set its \`isDeleted\` property to \`true\` on the workbench copy (\`ea.getElement(id).isDeleted = true;\`) and then commit with \`await ea.addElementsToView()\`.
* **Cleanup:** Use \`ea.clear()\` at the beginning of a script if you are creating a completely new set of elements, to ensure the EA workbench is empty and doesn't contain artifacts from a previous run.
#### **2. User Interaction: Prompts and Dialogs**
* **Simple Input:** For straightforward user input, use the \`utils\` object provided to the script.
* \`await utils.inputPrompt()\`: To get a string or number from the user.
* \`await utils.suggester()\`: To let the user select from a predefined list of options.
* **Complex Dialogs:** When a more complex UI with multiple controls is needed, create a floating dialog window.
* **Use \`FloatingModal\`:** Always create a new instance: \`const modal = new ea.FloatingModal(ea.plugin.app);\`.
* **Do Not Extend:** Do not use \`class MyModal extends ea.FloatingModal\`.
* **Define Behavior:** Assign functions directly to the \`onOpen\` and \`onClose\` properties of the instance. Inside \`onOpen\`, use the \`modal.contentEl\` property to build your UI.
* **Reference Implementation:** The script "Printable Layout Wizard.md" is the canonical example for this pattern. Use \`ea.obsidian.Setting\` to add controls like toggles and dropdowns within the modal.
#### **3. Element Manipulation and Querying**
* **Finding Elements:** The most common starting point is to get the user's selection with \`ea.getViewSelectedElements()\`. Use standard JavaScript array methods like \`.filter()\` to narrow down the selection (e.g., \`elements.filter(el => el.type === "text")\`).
* **Geometric Calculations:**
* Before performing layout or positioning tasks, use \`ea.getBoundingBox(elements)\` to get the collective dimensions and position of a group of elements.
* Use \`ea.measureText(text)\` to determine the width and height of a string based on the current \`ea.style\` settings before creating a text element or a container for it.
* **Grouping:**
* To create a group, use \`ea.addToGroup([elementId1, elementId2, ...])\`.
* To operate on existing groups within a selection, use \`ea.getMaximumGroups(selectedElements)\` which correctly identifies the top-level groups. Use \`ea.getLargestElement(group)\` to find the primary container within a group (e.g., the box around a text element).
#### **4. Styling: Creation vs. Modification**
* **For New Elements:** Set the properties on the global \`ea.style\` object *before* you call a creation function like \`ea.addText()\` or \`ea.addRect()\`. This acts like setting the active color/style on a paintbrush.
* **For Existing Elements:** To change the style of an existing element, modify the properties directly on the element's copy in the EA workbench (after \`copyViewElementsToEAforEditing\`). For example: \`const myElement = ea.getElement(id); myElement.strokeColor = '#FF0000';\`.
#### **5. Data Persistence and Customization**
* **Storing Custom Data:** Elements have a \`customData\` property for arbitrary data.
* **Always Use \`ea.addAppendUpdateCustomData(id, newData)\`:** This is crucial. It safely adds or updates your key-value pairs without overwriting data that might have been stored by other scripts or the Excalidraw plugin itself.
* **Creating Configurable Scripts:** To make your script's behavior customizable by the user:
* Use \`ea.getScriptSettings()\` to retrieve saved settings.
* scriptSettings are stored with Excalidraw settings in Obsidian data.json. Keep this light. You MUST NEVER save large data objects such as base64 images or huge arrays here. Keep this lean and efficient.
* Check if settings exist, and if not, define the default structure.
* Use \`await ea.setScriptSettings(settings)\` to save any changes. This allows users to configure your script in the Excalidraw plugin settings pane.
#### **6. Best Practices and Advanced Techniques**
* **Script Overview Block (MANDATORY):** Create, and consistently maintain with each update, a comprehensive comment block at the very beginning of the script. This block must explain the purpose of the script, its key features, and the high-level solution logic or architecture.
* **Strictly Modular Architecture (NO LOOSE CODE):** Avoid creating large monolithic blocks of code or leaving logic loose at the root level of the script. Instead, organize *everything* into relatively small, atomic functions. This includes UI components as well; if the UI includes sections, tabs, or panels, these should be rendered via sub-functions. This is a critical requirement to ensure long-term maintainability and evolution of the script, as loose code quickly becomes unmanageable over multiple iterative prompts.
* **Evergreen JSDoc Headers and Comments:** Every function must have a proper JSDoc/Javadoc-style header containing parameter names, types, and a clear description of the function's purpose. These descriptions must be kept *evergreen* (updated alongside any code changes). Additionally, when modifying or updating a script, you must strictly *retain all existing internal code comments*.
* **Isolate Constants and User-Facing Strings:** *Do not embed hardcoded magic values, config parameters, or UI strings deep inside the logic.* You must separate all constants and language strings and collect them at the very top of the file. This makes it easier to tweak values later and provides a clear, unified section for localization and customization.
* **Icons:** Obsidian uses https://lucide.dev icons. These icons are available for scripts via \`ea.obsidian.getIcon("Icon Name")\`. For UI components prefer use of lucide.dev icons.
* **Omit Version Verification:** While many of the sample scripts in the library include a version verification block at the outset (using \`ea.verifyMinimumPluginVersion\`), *do not add this section* when generating a new script unless explicitly instructed to do so.
* **Embrace \`await\`:** Many EA functions are asynchronous and return a \`Promise\` (e.g., \`ea.addElementsToView()\`, \`ea.createSVG()\`, \`utils.inputPrompt()\`). **Always** use \`await\` when calling these functions to ensure your script executes in the correct order.
* **Accessing Obsidian API:** The full Obsidian API is available via \`ea.obsidian\`. For example, use \`new ea.obsidian.Notice("message")\` or \`ea.obsidian.normalizePath(filepath)\`.
* **Accessing Excalidraw API:** The full Excalidraw API is available on \`ea.getExcalidrawAPI()\`, these API functions are Scene dependent. Additional support functions are available on \`window.ExcalidrawLib\`.
* **Visibility vs. Deletion:**
* To temporarily hide an element, set \`element.opacity = 0\`. It's good practice to store the original opacity in \`customData\` so it can be restored. It is also recommended to lock hidden elements so they do not get accidentally selected or moved around.
* To permanently remove an element from the scene, set \`element.isDeleted = true\`.
* **Image Handling:** When dealing with image elements, use \`ea.getViewFileForImageElement(imageElement)\` to get the corresponding \`TFile\` from the Obsidian vault. This is necessary for any logic that needs to read or manipulate the source image file.
#### **7. SVG and Image Export Approaches**
Generating images (SVG/PNG) requires specific approaches depending on the context. Follow these three rules strictly to avoid performance issues and missing assets:
1. **Exporting elements currently in the EA workbench:** Use \`await ea.createSVG(null, ...)\` or \`await ea.createPNG(null, ...)\` (passing \`null\` as the \`templatePath\`).
2. **Exporting an Excalidraw file that is NOT currently open:** Pass the file path as the template to \`createSVG\` or \`createPNG\` (e.g., \`await ea.createSVG(file.path, ...)\`). This is the most reliable approach as ExcalidrawAutomate natively handles loading the scene, resolving embedded images, and instantiating loaders behind the scenes. **Do NOT attempt to manually read the file, reconstruct the scene, or load images into memory.**
3. **Exporting the currently active \`ExcalidrawView\`:** Use \`await ea.createViewSVG(...)\`. This is specifically for the open view. You can use the \`elementsOverride\` parameter to inject temporary elements (like transparent sizing rectangles) into the exported image without modifying the actual scene.
#### **8. Custom Pens and Perfect Freehand**
Excalidraw's freehand tool is powered by the open-source Perfect Freehand library. The plugin exposes “custom pens” that bundle:
- Canvas style for the next strokes (colors, width, fillStyle, roughness).
- Perfect Freehand stroke geometry and behavior (pressure simulation, outline, tapering, easing, etc.).
Key concepts:
- AppState-driven drawing: When \`appState.currentStrokeOptions\` is set, the freedraw tool renders new strokes using those Perfect Freehand options.
- Element-level persistence: If a freedraw element has \`element.customData.strokeOptions\`, it is rendered with those options regardless of the current tool state.
- Types reference: See \`src/types/penTypes.ts\`. The \`PenOptions\` shape is:
\`\`\`ts
interface PenOptions {
highlighter: boolean; // if true the pen is drawn at the lowest layer, behind all other elements
constantPressure: boolean;
hasOutline: boolean;
outlineWidth: number;
options: {
thinning: number;
smoothing: number;
streamline: number;
easing: string; // see supported names below
start: { cap: boolean; taper: number | boolean; easing: string; };
end: { cap: boolean; taper: number | boolean; easing: string; };
};
}
\`\`\`
Using custom pens from scripts:
- Activate a custom pen for drawing:
\`\`\`ts
// obtain the Excalidraw API
const api = ea.getExcalidrawAPI();
// define Perfect Freehand options (example similar to "finetip")
const penOptions = {
highlighter: false,
constantPressure: true,
hasOutline: false,
outlineWidth: 1,
options: {
thinning: -0.5,
smoothing: 0.4,
streamline: 0.4,
easing: "linear",
start: { taper: 5, cap: false, easing: "linear" },
end: { taper: 5, cap: false, easing: "linear" },
},
};
// apply stroke options + canvas style, then switch to freedraw (strokeWidth, color, background, fillStyle are optional)
ea.viewUpdateScene({
appState: {
currentStrokeOptions: penOptions,
currentItemStrokeWidth: 0.5,
currentItemStrokeColor: "#3E6F8D",
currentItemBackgroundColor: "transparent",
currentItemFillStyle: "hachure",
},
});
api.setActiveTool({ type: "freedraw" });
\`\`\`
- Clear custom pen (revert to default freedraw behavior):
\`\`\`ts
ea.viewUpdateScene({ appState: { currentStrokeOptions: null } });
\`\`\`
- Persist custom strokeOptions onto existing freedraw elements:
\`\`\`ts
const selected = ea.getViewSelectedElements().filter(el => el.type === "freedraw");
ea.copyViewElementsToEAforEditing(selected);
for (const el of selected) {
ea.addAppendUpdateCustomData(el.id, { strokeOptions: penOptions });
}
await ea.addElementsToView();
\`\`\`
Notes:
- New strokes respect \`appState.currentStrokeOptions\` at draw time. Existing elements only change if you update their \`customData.strokeOptions\`.
- For pens that should behave like real markers/highlighters, set \`highlighter: true\` and often \`constantPressure: true\` with an \`outlineWidth\` for the edge.
Supported easing names (string values for \`options.easing\`, \`options.start.easing\`, \`options.end.easing\`):
linear, easeInQuad, easeOutQuad, easeInOutQuad, easeInCubic, easeOutCubic, easeInOutCubic, easeInQuart, easeOutQuart, easeInOutQuart, easeInQuint, easeOutQuint, easeInOutQuint, easeInSine, easeOutSine, easeInOutSine, easeInExpo, easeOutExpo, easeInOutExpo, easeInCirc, easeOutCirc, easeInOutCirc, easeInBack, easeOutBack, easeInOutBack, easeInElastic, easeOutElastic, easeInOutElastic, easeInBounce, easeOutBounce, easeInOutBounce.
Example freedraw element carrying \`customData.strokeOptions\`:
\`\`\`json
{"type":"excalidraw/clipboard","elements":[{"id":"...","type":"freedraw","strokeColor":"#3E6F8D","backgroundColor":"transparent","fillStyle":"hachure","strokeWidth":0.5,"roughness":0,"customData":{"strokeOptions":{"highlighter":false,"hasOutline":false,"outlineWidth":0,"constantPressure":true,"options":{"smoothing":0.4,"thinning":-0.5,"streamline":0.4,"easing":"linear","start":{"taper":5,"cap":false,"easing":"linear"},"end":{"taper":5,"cap":false,"easing":"linear"}}}}}],"files":{}}
\`\`\`
#### **9. Text Element**
* There are three text properties.
* **textElement.text** holds the wrapped, rendered text. This is what is displayed in the view. Excalidraw adds '\\n' linebreaks during dynamic wrapping.
* **textElement.originalText** holds the rendered, but unwrapped text. Any '\\n' character in originalText is an intentional linebreak by the user. Rendered means that for example [[wiki links]] are rendered without the square brackets.
* **textElement.rawText** holds the original raw text including intentional new line characters and the full markdown markup (thought currently only links are rendered, so markdown support is limited to these)
* When modifying element text from script, typically all 3 of these properties must be updated, though in case textElement.autoresize === true, or when a text element is bound in a container, excalidraw will update textElement.text following the size of the text element or the container.
`;
const EXCALIDRAW_STARTUP_MESSAGE = `# Excalidraw Startup Script
ExcalidrawStartup Script can be configured in Plugin Settings under 'Excalidraw Automate'. When defined this script runs automatically when the Excalidraw plugin is loaded to Obsidian. The user can add automation tasks here that they want to run on every startup of Excalidraw in Obsidian such as defining Excalidraw event handlers (also known as hooks).
`;
const EXCALIDRAW_STARTUP_TEMPLATE = "src/constants/assets/startupScript.md";
const EXCALIDRAW_STARTUP_EXAMPLE = "docs/AITrainingData/ExcalidrawStartupExample.md";
const TYPE_DEF_WHITELIST = [
"lib/shared/ExcalidrawAutomate.d.ts",
"lib/types/excalidrawAutomateTypes.d.ts",
"lib/types/sidepanelTabTypes.d.ts",
"lib/types/penTypes.d.ts",
"lib/types/utilTypes.d.ts",
"lib/types/exportUtilTypes.d.ts",
"lib/types/embeddedFileLoaderTypes.d.ts",
"lib/types/AIUtilTypes.d.ts",
"node_modules/@zsviczian/excalidraw/types/element/src/types.d.ts",
"node_modules/@zsviczian/excalidraw/types/excalidraw/types.d.ts",
"node_modules/@zsviczian/excalidraw/types/element/src/bounds.d.ts",
"node_modules/@zsviczian/excalidraw/types/excalidraw/components/App.d.ts",
];
/**
* Returns true if content contains at least one line starting with ```
* and has an odd number of fences (unbalanced).
*/
function needsClosingFence(content) {
const fenceCount = (content.match(/^```/gm) || []).length;
return fenceCount > 0 && fenceCount % 2 === 1;
}
function normalizeEOL(str) {
return str.replace(/\r\n/g, '\n');
}
function stripBOM(str) {
return str.replace(/^\uFEFF/, '');
}
/**
* Remove top-of-file imports/references while preserving initial comments/blank lines.
* Also removes bare "export {}" lines (module markers).
*/
function stripTopImports(content) {
const lines = normalizeEOL(stripBOM(content)).split('\n');
const out = [];
let inTopRegion = true;
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
const isImport =
/^\s*import\s+type\s+/.test(line) ||
/^\s*import\s+/.test(line) ||
/^\s*import\(/.test(line);
const isTripleRef = /^\s*\/\/\/\s*<reference/.test(line);
const isBareExportModule = /^\s*export\s*\{\s*\};?\s*$/.test(line);
if (inTopRegion) {
if (isImport || isTripleRef) {
continue;
}
const isBlank = /^\s*$/.test(line);
const isLineComment = /^\s*\/\//.test(line);
const isBlockCommentStart = /^\s*\/\*/.test(line);
if (!isBlank && !isLineComment && !isBlockCommentStart) {
inTopRegion = false;
}
if (!isBareExportModule) out.push(line);
continue;
}
if (!isBareExportModule) out.push(line);
}
return out.join('\n').trim() + '\n';
}
function makeSectionHeader(relPath) {
const stars = '*'.repeat(Math.max(6, Math.min(38, relPath.length + 6)));
return [
`/* ${stars} */`,
`/* ${relPath} */`,
`/* ${stars} */`,
].join('\n') + '\n';
}
function buildTypeDefMarkdown() {
const entries = TYPE_DEF_WHITELIST.map((rel) => ({
rel,
abs: path.join(ROOT, ...rel.split('/')),
}));
let body = '# ExcalidrawAutomate library and related type definitions\n\n```js\n';
for (const { rel, abs } of entries) {
if (!fs.existsSync(abs)) {
console.warn('[skill-builder] Whitelist file missing:', rel);
continue;
}
let content = fs.readFileSync(abs, 'utf8');
content = stripTopImports(content);
body += makeSectionHeader(rel);
body += content.trimEnd() + '\n\n';
}
body += '```\n';
return body;
}
function resolveExcalModulePath(spec, excalIndexAbs) {
const baseTypesRoot = path.join(ROOT, 'node_modules', '@zsviczian', 'excalidraw', 'types');
if (spec.startsWith('@excalidraw/')) {
const sub = spec.slice('@excalidraw/'.length);
const parts = sub.split('/');
const pkg = parts.shift();
const rest = parts;
if (!pkg) return null;
const base = path.join(baseTypesRoot, pkg);
if (rest.length === 0) {
return path.join(base, 'src', 'index.d.ts');
}
return path.join(base, 'src', ...rest) + '.d.ts';
}
if (spec.startsWith('.')) {
const dir = path.dirname(excalIndexAbs);
return path.resolve(dir, spec) + '.d.ts';
}
return null;
}
function extractFunctionSignaturesFromModule(absPath, names) {
const out = {};
if (!absPath || !fs.existsSync(absPath)) {
return out;
}
const content = fs.readFileSync(absPath, 'utf8');
for (const rawName of names) {
const name = rawName.trim();
if (!name) continue;
let m = content.match(new RegExp(`export\\s+declare\\s+function\\s+${name}[\\s\\S]*?;`, 'm'));
if (m) {
out[name] = m[0].trim();
continue;
}
m = content.match(new RegExp(`(^|\\n)declare\\s+function\\s+${name}[\\s\\S]*?;`, 'm'));
if (m) {
out[name] = m[0].replace(/^\s*declare\s+/, 'export declare ').trim();
continue;
}
m = content.match(new RegExp(`export\\s+declare\\s+const\\s+${name}\\s*:\\s*[\\s\\S]*?=>[\\s\\S]*?;`, 'm'));
if (m) {
out[name] = m[0].trim();
continue;
}
m = content.match(new RegExp(`export\\s+declare\\s+(?:var|let|const)\\s+${name}\\s*:\\s*[\\s\\S]*?;`, 'm'));
if (m && /=>/.test(m[0])) {
out[name] = m[0].trim();
continue;
}
}
return out;
}
function buildExcalidrawLibFunctionsSection() {
const excalIndexRel = 'node_modules/@zsviczian/excalidraw/types/excalidraw/index.d.ts';
const excalIndexAbs = path.join(ROOT, ...excalIndexRel.split('/'));
if (!fs.existsSync(excalIndexAbs)) {
console.warn('[skill-builder] Missing Excalidraw index.d.ts:', excalIndexRel);
return '';
}
const content = fs.readFileSync(excalIndexAbs, 'utf8');
const reExport = /export\s*\{\s*([\s\S]*?)\s*\}\s*from\s*["']([^"']+)["'];/g;
const moduleToNames = new Map();
for (const match of content.matchAll(reExport)) {
const namesChunk = match[1];
const spec = match[2];
const names = namesChunk
.split(',')
.map((s) => s.trim())
.filter(Boolean);
if (!names.length) continue;
const abs = resolveExcalModulePath(spec, excalIndexAbs);
if (!abs) continue;
const key = spec;
const curr = moduleToNames.get(key) || { abs, names: new Set() };
for (const n of names) curr.names.add(n);
moduleToNames.set(key, curr);
}
const seen = new Set();
const sections = [];
for (const [spec, { abs, names }] of moduleToNames) {
const sigs = extractFunctionSignaturesFromModule(abs, Array.from(names));
const sigEntries = Object.entries(sigs)
.filter(([name]) => {
if (seen.has(name)) return false;
seen.add(name);
return true;
})
.sort(([a], [b]) => a.localeCompare(b, 'en', { sensitivity: 'base' }));
if (!sigEntries.length) continue;
const rel = path.relative(ROOT, abs).replace(/\\/g, '/');
const header = makeSectionHeader(`${spec} -> ${rel}`);
sections.push(header + sigEntries.map(([, s]) => s).join('\n') + '\n');
}
return '# ExcalidrawLib module functions\n\n' +
'The following functions are exposed via window.ExcalidrawLib. Signatures are extracted from TypeScript declarations.\n\n' +
'```ts\n' +
sections.join('\n') +
'```\n';
}
import { runUnifiedGeneration } from './excalidraw-docs-generator-core.mjs';
function main() {
console.log('[skill-builder] Generating Excalidraw Agent Skill...');
if (!fs.existsSync(EA_SCRIPTS_DIR)) {
console.error('ea-scripts directory not found:', EA_SCRIPTS_DIR);
process.exit(1);
}
// Ensure directories exist
fs.mkdirSync(SKILL_DIR, { recursive: true });
fs.mkdirSync(SKILL_REFERENCES_DIR, { recursive: true });
// Create or clean the scripts directory
if (fs.existsSync(SKILL_SCRIPTS_DIR)) {
fs.rmSync(SKILL_SCRIPTS_DIR, { recursive: true, force: true });
}
fs.mkdirSync(SKILL_SCRIPTS_DIR, { recursive: true });
// Read exclusions
const args = process.argv.slice(2);
const cmdLineExcludes = args.map(arg => arg.toLowerCase());
const defaultExcludes = ['index-new.md', 'mindmap builder.md', 'color scheme manager.md', 'comic strip director.md'];
const exclusions = new Set([...defaultExcludes, ...cmdLineExcludes]);
// Collect scripts
const files = fs
.readdirSync(EA_SCRIPTS_DIR, { withFileTypes: true })
.filter(
(d) =>
d.isFile() &&
(d.name.endsWith('.md') || d.name.toLowerCase() === "mindmap builder.js") &&
!exclusions.has(d.name.toLowerCase())
)
.map((d) => d.name)
.sort((a, b) => a.localeCompare(b, 'en', { sensitivity: 'base' }));
// Prepare API Index Map
const apiIndex = {
ExcalidrawAutomate: {},
ExcalidrawAPI: {},
ExcalidrawLib: {}
};
function addUsage(category, method, scriptName) {
// Filter out obvious noise or generic javascript attributes
const ignoreList = ['length', 'push', 'map', 'filter', 'forEach', 'includes', 'join', 'toString', 'toLowerCase'];
if (ignoreList.includes(method)) return;
if (method.length < 2) return;
if (!apiIndex[category][method]) {
apiIndex[category][method] = new Set();
}
apiIndex[category][method].add(scriptName);
}
console.log('[skill-builder] Processing scripts and building API Index...');
for (const file of files) {
const full = path.join(EA_SCRIPTS_DIR, file);
let content = fs.readFileSync(full, 'utf8').replace(/\r\n/g, '\n');
// Fix missing fences
if (needsClosingFence(content)) {
content += '\n```\n';
}
// Write individual script to references/scripts/
fs.writeFileSync(path.join(SKILL_SCRIPTS_DIR, file), content, 'utf8');
// Parse API Usage
// 1. ExcalidrawAutomate: ea.functionName
const eaMatches = [...content.matchAll(/ea\.([a-zA-Z0-9_]+)/g)];
eaMatches.forEach(m => addUsage('ExcalidrawAutomate', m[1], file));
// 2. ExcalidrawAPI: api.functionName or ea.getExcalidrawAPI().functionName
const apiMatches = [...content.matchAll(/(?:getExcalidrawAPI\(\)|api)\.([a-zA-Z0-9_]+)/g)];
apiMatches.forEach(m => addUsage('ExcalidrawAPI', m[1], file));
// 3. ExcalidrawLib: ExcalidrawLib.functionName or window.ExcalidrawLib.functionName
const libMatches = [...content.matchAll(/(?:window\.)?ExcalidrawLib\.([a-zA-Z0-9_]+)/g)];
libMatches.forEach(m => addUsage('ExcalidrawLib', m[1], file));
}
// Generate API Usage Index Markdown
console.log('[skill-builder] Writing api-usage-index.md...');
let apiIndexContent = `# Excalidraw API Usage Index\n\n`;
apiIndexContent += `This index maps methods and properties from ExcalidrawAutomate (\`ea\`), ExcalidrawAPI, and ExcalidrawLib to the example scripts that use them. Use this to find real-world examples of how to implement specific features.\n\n`;
for (const [category, methods] of Object.entries(apiIndex)) {
apiIndexContent += `## ${category}\n\n`;
const sortedMethods = Object.keys(methods).sort((a, b) => a.localeCompare(b, 'en', { sensitivity: 'base' }));
if (sortedMethods.length === 0) {
apiIndexContent += `*No usages found.*\n\n`;
continue;
}
for (const method of sortedMethods) {
const scriptLinks = Array.from(methods[method])
.sort((a, b) => a.localeCompare(b, 'en', { sensitivity: 'base' }))
.map(script => `[${script}](scripts/${script.replace(/ /g, '%20')})`)
.join(', ');
apiIndexContent += `- **${method}**: ${scriptLinks}\n`;
}
apiIndexContent += `\n`;
}
fs.writeFileSync(path.join(SKILL_REFERENCES_DIR, 'api-usage-index.md'), apiIndexContent, 'utf8');
// Write Type Definitions
console.log('[skill-builder] Writing type-definitions.md...');
fs.writeFileSync(path.join(SKILL_REFERENCES_DIR, 'type-definitions.md'), buildTypeDefMarkdown(), 'utf8');
// Write ExcalidrawLib Functions
console.log('[skill-builder] Writing excalidraw-lib-functions.md...');
fs.writeFileSync(path.join(SKILL_REFERENCES_DIR, 'excalidraw-lib-functions.md'), buildExcalidrawLibFunctionsSection(), 'utf8');
// Write Startup Scripts template
console.log('[skill-builder] Writing startup-scripts.md...');
const startupTemplatePath = path.join(ROOT, ...EXCALIDRAW_STARTUP_TEMPLATE.split('/'));
const startupExamplePath = path.join(ROOT, ...EXCALIDRAW_STARTUP_EXAMPLE.split('/'));
const startupTemplate = fs.existsSync(startupTemplatePath)
? fs.readFileSync(startupTemplatePath, 'utf8').replace(/\r\n/g, '\n').trim()
: '';
const startupExample = fs.existsSync(startupExamplePath)
? fs.readFileSync(startupExamplePath, 'utf8').replace(/\r\n/g, '\n').trim()
: '';
const startupSection = EXCALIDRAW_STARTUP_MESSAGE + '\n\n' +
(startupTemplate ? `### Template\n\`\`\`js\n${startupTemplate}\n\`\`\`\n\n` : '') +
(startupExample ? `### Example\n\`\`\`js\n${startupExample}\n\`\`\`\n` : '');
fs.writeFileSync(path.join(SKILL_REFERENCES_DIR, 'startup-scripts.md'), startupSection, 'utf8');
// Write SKILL.md
console.log('[skill-builder] Writing SKILL.md...');
const skillMdPath = path.join(SKILL_DIR, 'SKILL.md');
const skillFrontmatter = `---
name: ${SKILL_NAME}
description: Write and manipulate ExcalidrawAutomate scripts for Obsidian.md. Use when the user wants to create, modify, or understand an Excalidraw script.
---
`;
let skillIntro = AI_TRAINING_INTRO
.replaceAll("https://youtu.be/", "YouTube: ")
.replaceAll("https://www.youtube.com/watch?v=", "YouTube: ")
.replaceAll("https://www.youtube.com/", "YouTube: ");
skillIntro += `
## References
The \`references/\` directory contains supporting documentation necessary for writing scripts:
- \`references/type-definitions.md\`: Core type definitions for ExcalidrawAutomate.
- \`references/excalidraw-lib-functions.md\`: Function signatures for \`window.ExcalidrawLib\`.
- \`references/startup-scripts.md\`: ExcalidrawStartup script template and examples.
- \`references/api-usage-index.md\`: A highly useful index mapping every API method (ea.*, api.*, ExcalidrawLib.*) to the specific example scripts that utilize them.
- \`references/scripts/\`: A folder containing all the raw, real-world example scripts.
### How to use the Script Examples
If you need to implement a specific function (e.g., \`ea.addElementsToView\`), do NOT guess its implementation context. Instead:
1. Open \`references/api-usage-index.md\`.
2. Find the function name.
3. Note the scripts listed next to it.
4. Read the corresponding script inside the \`references/scripts/\` directory to see a complete, working example of how the function is used in context.
`;
fs.writeFileSync(skillMdPath, skillFrontmatter + skillIntro, 'utf8');
console.log('[skill-builder] Done.');
console.log('[skill-builder] Running unified documentation generator (full mode)...');
const result = runUnifiedGeneration({
mode: 'full',
args: process.argv.slice(2),
});
console.log('[skill-builder] Wrote outputs:', result.generated);
console.log('[skill-builder] Processed scripts:', result.scriptsProcessed);
}
// ESM equivalent of `if (require.main === module)`
if (process.argv[1] === fileURLToPath(import.meta.url)) {
try {
main();
@@ -643,4 +20,4 @@ if (process.argv[1] === fileURLToPath(import.meta.url)) {
console.error('[skill-builder] Failed:', e);
process.exit(1);
}
}
}
+3 -4
View File
@@ -2,6 +2,7 @@ import { getIcon, sanitizeHTMLToDom } from "obsidian";
import { PenStyle } from "src/types/penTypes";
import React from "react";
import { isInstanceOfSVGSVGElement } from "src/utils/typechecks";
import { BLOCK_REFERENCE_ICON_PATH } from "./blockReferenceIcon";
declare const mainDocument: Document;
const BLOCKED_SVG_TAGS = new Set([
"script",
@@ -203,13 +204,11 @@ export const ICONS = {
viewBox="0 0 24 24"
fill="none"
stroke="var(--icon-fill-color)"
strokeWidth="1"
strokeWidth="1.75"
strokeLinecap="round"
strokeLinejoin="round"
>
<text x="1" y="18" fontSize="22px">
#^
</text>
<path d={BLOCK_REFERENCE_ICON_PATH} />
</svg>
),
Edit: getIconAsJSX("pen-line"),
+12 -1
View File
@@ -1,6 +1,17 @@
/*
#exclude
```js*/
/**
* Startup scripts receive the plugin-global EA for the plugin lifetime and
* utils.executionSource === "plugin-startup". Register cleanup for resources
* outside EA so plugin reload/unload cannot accumulate them.
*/
// const ref = app.workspace.on("file-open", (file) => {});
// ea.registerCleanup(() => app.workspace.offref(ref));
//
// const interval = window.setInterval(() => {}, 1000);
// ea.registerCleanup(() => window.clearInterval(interval));
/**
* If set, this callback is triggered when the user closes an Excalidraw view.
* onViewUnloadHook: (view: ExcalidrawView) => void = null;
@@ -317,4 +328,4 @@
// elementCount: elements.length
// });
// }
// };
// };
+10
View File
@@ -0,0 +1,10 @@
/** Obsidian icon-registry ID for the narrow-to-block action. */
export const BLOCK_REFERENCE_ICON_ID = "excalidraw-narrow-to-block";
/** Path geometry shared by the React action menu and Obsidian settings UI. */
export const BLOCK_REFERENCE_ICON_PATH =
"M6 4 4 20M12 4l-2 16M2.75 9h11.5M1.75 15h11.5M16 13l3-4 3 4";
/** SVG body scaled from the shared 24-unit path to Obsidian's 100-unit registry viewBox. */
export const BLOCK_REFERENCE_ICON_REGISTRY_SVG =
`<path d="${BLOCK_REFERENCE_ICON_PATH}" transform="scale(4.1666667)" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"/>`;
+5 -3
View File
@@ -1,6 +1,6 @@
import { customAlphabet } from "nanoid";
import { ExcalidrawLib } from "../types/excalidrawLib";
import ExcalidrawPlugin from "src/core/main";
import type ExcalidrawPlugin from "src/core/main";
import { DeviceType } from "src/types/types";
import { errorHandler } from "../utils/ErrorHandler";
import { getLanguage } from "obsidian";
@@ -109,6 +109,7 @@ export let {
exportToBlob,
mutateElement,
restoreElements,
restoreLibraryItems,
mermaidToExcalidraw,
getFontFamilyString,
getContainerElement,
@@ -136,6 +137,7 @@ export function updateExcalidrawLib() {
"measureText",
"getLineHeight",
"restoreElements",
"restoreLibraryItems",
];
for (const fnName of requiredFunctions) {
@@ -166,6 +168,7 @@ export function updateExcalidrawLib() {
exportToBlob,
mutateElement,
restoreElements,
restoreLibraryItems,
mermaidToExcalidraw,
getFontFamilyString,
getContainerElement,
@@ -216,10 +219,9 @@ export function setRootElementSize(size?: number) {
ROOTELEMENTSIZE = size;
return;
}
const tempElement = mainDocument.createElement("div");
const tempElement = mainDocument.body.createDiv();
setStyle(tempElement, { fontSize: "1rem" });
tempElement.hidden = true;
mainDocument.body.appendChild(tempElement);
const computedStyle = getComputedStyle(tempElement);
const pixelSize = parseFloat(computedStyle.fontSize);
mainDocument.body.removeChild(tempElement);
+1 -1
View File
@@ -103,7 +103,7 @@ export const URL_REGISTRY = {
UrlPurpose.SUPPORT,
),
COMMUNITY_SKETCH_YOUR_MIND_COM_WIKI: defineUrl(
"https://community.sketch-your-mind.com/wiki",
"https://community.sketch-your-mind.com/Wiki",
UrlPurpose.SUPPORT,
),
WWW_YOUTUBE_COM_VISUALPKM: defineUrl(
+200 -824
View File
File diff suppressed because it is too large. Load diff
+20 -10
View File
@@ -23,7 +23,7 @@ import {
import ExcalidrawView from "../../view/ExcalidrawView";
import { TextMode } from "../../shared/TextMode";
import { REGEX_LINK } from "../../shared/ExcalidrawData";
import { ExcalidrawSettings } from "../settings";
import type { ExcalidrawSettings } from "../settingsDefaults";
import {
openDialogAction,
OpenFileDialog,
@@ -66,6 +66,7 @@ import {
FileId,
} from "@zsviczian/excalidraw/types/element/src/types";
import { ReleaseNotes } from "../../shared/Dialogs/ReleaseNotes";
import { AutostartScriptsModal } from "../../shared/Dialogs/AutostartScriptsSettingsComponent";
import { ScriptInstallPrompt } from "../../shared/Dialogs/ScriptInstallPrompt";
import Taskbone from "../../shared/OCR/Taskbone";
import {
@@ -87,7 +88,7 @@ import {
} from "../../utils/carveout";
import { showFrameSettings } from "../../shared/Dialogs/FrameSettings";
import { insertImageToView } from "../../utils/excalidrawViewUtils";
import ExcalidrawPlugin from "src/core/main";
import type ExcalidrawPlugin from "src/core/main";
import { UIModeSettings } from "src/shared/Dialogs/UIModeSettings";
import { PaneTarget } from "src/types/utilTypes";
import { decompress } from "src/utils/sceneDataUtils";
@@ -485,13 +486,13 @@ export class CommandManager {
id: "excalidraw-disable-autosave",
name: t("TEMPORARY_DISABLE_AUTOSAVE"),
checkCallback: (checking) => {
if (!this.settings.autosave) {
if (!this.plugin.autosaveEnabled) {
return false;
} //already disabled
if (checking) {
return true;
}
this.settings.autosave = false;
this.plugin.autosaveEnabled = false;
return true;
},
});
@@ -500,13 +501,13 @@ export class CommandManager {
id: "excalidraw-enable-autosave",
name: t("TEMPORARY_ENABLE_AUTOSAVE"),
checkCallback: (checking) => {
if (this.settings.autosave) {
if (this.plugin.autosaveEnabled) {
return false;
} //already enabled
if (checking) {
return true;
}
this.settings.autosave = true;
this.plugin.autosaveEnabled = true;
return true;
},
});
@@ -928,13 +929,15 @@ export class CommandManager {
this.forceSaveCommand = this.addCommand({
id: "save",
//eslint-disable-next-line obsidianmd/commands/no-default-hotkeys
hotkeys: [{ modifiers: ["Ctrl"], key: "s" }], //See also Poposcope
name: t("FORCE_SAVE"),
checkCallback: (checking: boolean) =>
this.plugin.forceSaveActiveView(checking),
});
const id = this.forceSaveCommand.id;
this.app.hotkeyManager.addDefaultHotkeys(id, [{ modifiers: ["Ctrl"], key: "s" }]); //See also Popscope
this.forceSaveCommand.hotkeys = [{ modifiers: ["Ctrl"], key: "s" }];
//removing raw mode. Not required. I never use it. Raw mode can still be enabled
//via document properties. Only showing command palette action if raw mode is enabled
this.addCommand({
@@ -1058,8 +1061,7 @@ export class CommandManager {
});
this.addCommand({
// eslint-disable-next-line obsidianmd/commands/no-command-in-command-id -- this is actually the command to insert a "command" into the drawing.
id: "insert-command",
id: "insert-cmd",
name: t("INSERT_COMMAND"),
checkCallback: (checking: boolean) => {
if (checking) {
@@ -2300,6 +2302,14 @@ export class CommandManager {
},
});
this.addCommand({
id: "view-autostart-scripts",
name: t("AUTOSTART_SCRIPTS_HEAD"),
callback: () => {
new AutostartScriptsModal(this.plugin).open();
},
});
this.addCommand({
id: "tray-mode",
name: t("UI_MODE"),
+8 -2
View File
@@ -20,7 +20,7 @@ import {
isUnwantedLeaf,
setExcalidrawView,
} from "../../utils/obsidianUtils";
import ExcalidrawPlugin from "src/core/main";
import type ExcalidrawPlugin from "src/core/main";
import { ExcalidrawAutomate } from "src/shared/ExcalidrawAutomate";
import {
FRONTMATTER_KEYS,
@@ -136,6 +136,12 @@ export class EventManager {
),
);
//theme/snippet toggles can change header/toolbar heights and shift the canvas
//without firing layout-change; refresh cached canvas offsets the same way
this.registerEvent(
this.app.workspace.on("css-change", () => this.onLayoutChangeHandler()),
);
//File Save Trigger Handlers
//Save the drawing if the user clicks outside the Excalidraw Canvas
const onClickEventSaveActiveDrawing = (e: PointerEvent) =>
@@ -343,7 +349,7 @@ export class EventManager {
this.previouslyActiveLeaf = leaf;
if (newActiveviewEV) {
this.plugin.addModalContainerObserver();
this.plugin.addModalContainerObserver(newActiveviewEV);
this.plugin.lastActiveExcalidrawFilePath = newActiveviewEV.file?.path;
} else {
this.plugin.removeModalContainerObserver();
+85 -33
View File
@@ -20,7 +20,8 @@ import {
nanoid,
VIEW_TYPE_EXCALIDRAW,
} from "src/constants/constants";
import { Prompt, templatePromt } from "src/shared/Dialogs/Prompt";
import { templatePromt } from "src/shared/Dialogs/Prompt";
import { FileAndFolderSelectorModal } from "src/shared/Dialogs/FileAndFolderSelectorModal";
import {
changeThemeOfExcalidrawMD,
ExcalidrawData,
@@ -28,10 +29,11 @@ import {
} from "../../shared/ExcalidrawData";
import ExcalidrawView from "src/view/ExcalidrawView";
import { getTextMode } from "src/shared/TextMode";
import ExcalidrawPlugin from "src/core/main";
import type ExcalidrawPlugin from "src/core/main";
import {
checkAndCreateFolder,
createFileAndAwaitMetacacheUpdate,
createOrOverwriteFile,
download,
getIMGFilename,
getLink,
@@ -47,6 +49,7 @@ import {
import { errorlog, getExportTheme } from "src/utils/utils";
import { getImageCache } from "src/shared/ImageCache";
import { PaneTarget } from "src/types/utilTypes";
import { t } from "src/lang/helpers";
export class PluginFileManager {
private plugin: ExcalidrawPlugin;
@@ -76,6 +79,16 @@ export class PluginFileManager {
});
}
/**
* Returns whether a vault file is an Excalidraw drawing.
*
* Parsed frontmatter is authoritative when available. During a vault write,
* Obsidian can temporarily remove that frontmatter from the metadata cache;
* in that gap, retain the last confirmed classification from
* {@link excalidrawFiles}. The metadata `changed` event updates that set, so
* deliberately removing the Excalidraw frontmatter still declassifies the
* file once the replacement metadata is published.
*/
public isExcalidrawFile(f: TFile): boolean {
if (!f) {
return false;
@@ -83,11 +96,12 @@ export class PluginFileManager {
if (f.extension === "excalidraw") {
return true;
}
const fileCache = f ? this.plugin.app.metadataCache.getFileCache(f) : null;
return (
!!fileCache?.frontmatter &&
!!fileCache.frontmatter[FRONTMATTER_KEYS.plugin.name]
);
const frontmatter = this.plugin.app.metadataCache.getFileCache(f)?.frontmatter;
if (frontmatter) {
return !!frontmatter[FRONTMATTER_KEYS.plugin.name];
}
return this.excalidrawFiles.has(f);
}
//managing my own list of Excalidraw files because in the onDelete event handler
@@ -384,29 +398,29 @@ export class PluginFileManager {
public async exportLibrary() {
if (DEVICE.isMobile) {
const prompt = new Prompt(
this.app,
"Please provide a filename",
"my-library",
"filename, leave blank to cancel action",
const location = await new FileAndFolderSelectorModal(this.app, {
title: t("FILE_AND_FOLDER_SELECTOR_EXPORT_TITLE"),
folderLabel: t("FILE_AND_FOLDER_SELECTOR_FOLDER"),
fileNameLabel: t("FILE_AND_FOLDER_SELECTOR_FILENAME"),
submitButtonText: t("FILE_AND_FOLDER_SELECTOR_EXPORT"),
folderPath: normalizePath(this.settings.folder),
fileName: "my-library.excalidrawlib",
}).start();
if (!location) {
return;
}
const filename = location.fileName
.toLowerCase()
.endsWith(".excalidrawlib")
? location.fileName
: `${location.fileName}.excalidrawlib`;
const fname = getNewUniqueFilepath(
this.app.vault,
filename,
location.folderPath,
);
void prompt.openAndGetValue((filename: string) => {
void (async () => {
if (!filename) {
return;
}
filename = `${filename}.excalidrawlib`;
const folderpath = normalizePath(this.settings.folder);
await checkAndCreateFolder(folderpath); //create folder if it does not exist
const fname = getNewUniqueFilepath(
this.app.vault,
filename,
folderpath,
);
await this.app.vault.create(fname, this.settings.library);
new Notice(`Exported library to ${fname}`, 6000);
})();
});
await createOrOverwriteFile(this.app, fname, this.settings.library);
new Notice(`Exported library to ${fname}`, 6000);
return;
}
download(
@@ -534,6 +548,40 @@ export class PluginFileManager {
);
}
/**
* Extracts binary files embedded in a converted legacy scene and rewrites
* the Markdown drawing with durable vault attachment links.
*
* The target file must already exist because Obsidian determines its
* attachment folder relative to that file. This method resolves only after
* every embedded file has been persisted.
*/
public async persistLegacySceneFilesInMarkdown(
markdown: string,
file: TFile,
): Promise<string> {
const convertedData = new ExcalidrawData(this.plugin);
try {
const loaded = await convertedData.loadData(
markdown,
file,
getTextMode(markdown),
);
if (!loaded) {
throw new Error(`Failed to load converted drawing: ${file.path}`);
}
convertedData.disableCompression = true;
await convertedData.syncElements(convertedData.scene);
return (
FRONTMATTER +
(await convertedData.generateMDAsync(convertedData.deletedElements))
);
} finally {
convertedData.destroy();
}
}
// -------------------------------------------------------
// ------------------ Event Handlers ---------------------
// -------------------------------------------------------
@@ -619,7 +667,10 @@ export class PluginFileManager {
const excalidrawViews = getExcalidrawViews(this.app);
excalidrawViews.forEach((excalidrawView) => {
void (async () => {
if (excalidrawView.semaphores?.viewunload) {
if (
excalidrawView.semaphores?.viewunload ||
excalidrawView.semaphores?.windowMigrating
) {
return;
}
if (
@@ -715,12 +766,13 @@ export class PluginFileManager {
return;
}
//this will not work in the short period when Obsidian is starting up, however
//this will only effect a very few files, statistically unlikely to cause
//much/any real user impact.
//a proper queuing feels overkill for this.
//this will only affect very few files, statistically unlikely to cause
//much/any real user impact. Flush the shared queue so a recently scheduled
//backup is moved with the drawing instead of later recreating the old key.
if (!getImageCache().isReady()) {
return;
}
await getImageCache().flushPendingBAK(oldPath);
const backup = await getImageCache().getBAKFromCache(oldPath);
if (backup) {
await getImageCache().addBAKToCache(newPath, `${backup}`);
+199
View File
@@ -0,0 +1,199 @@
import type { Packages } from "src/types/types";
import { Notice, normalizePath, TFile } from "obsidian";
import {
CJK_STYLE_ID,
DEVICE,
FONTS_STYLE_ID,
} from "src/constants/constants";
import { t } from "src/lang/helpers";
import { getCJKDataURLs } from "src/utils/CJKLoader";
import { getFontDataURL } from "src/utils/utils";
import { getFontMetrics } from "src/utils/fontMetrics";
import type ExcalidrawPlugin from "src/core/main";
declare const mainDocument: Document;
declare const deliberateCreateElement: (
document: Document,
tagName: string,
) => HTMLStyleElement;
type RuntimePackageProvider = () => Packages;
/**
* Owns CJK and custom-font discovery, registration, document stylesheets, and
* readiness state while preserving the plugin's existing public font facade.
*/
export class FontManager {
private isLocalCJKFontAvailabe: boolean = undefined;
// Intentionally true to preserve the existing startup race behavior.
private fontsReady = true;
public constructor(
private readonly plugin: ExcalidrawPlugin,
private readonly getRuntimePackage: RuntimePackageProvider,
) {}
/** Whether font initialization permits the plugin readiness wait to finish. */
public get isReady(): boolean {
return this.fontsReady;
}
/** Returns the enabled CJK ranges when local CJK font assets are available. */
public getCJKFontSettings(): { c: boolean; j: boolean; k: boolean } {
const assetsFoler = this.plugin.settings.fontAssetsPath;
if (typeof this.isLocalCJKFontAvailabe === "undefined") {
this.isLocalCJKFontAvailabe = this.plugin.app.vault
.getFiles()
.some((file) => file.path.startsWith(assetsFoler));
}
if (!this.isLocalCJKFontAvailabe) {
return { c: false, j: false, k: false };
}
return {
c: this.plugin.settings.loadChineseFonts,
j: this.plugin.settings.loadJapaneseFonts,
k: this.plugin.settings.loadKoreanFonts,
};
}
/** Reads a configured CJK font asset from the vault. */
public async loadFontFromFile(
fontName: string,
): Promise<ArrayBuffer | undefined> {
const assetsFoler = this.plugin.settings.fontAssetsPath;
if (!this.isLocalCJKFontAvailabe) {
return;
}
const file = this.plugin.app.vault.getFileByPath(
normalizePath(`${assetsFoler}/${fontName}`),
);
if (!file || !(file instanceof TFile)) {
return;
}
return await this.plugin.app.vault.readBinary(file);
}
/**
* Loads configured CJK and custom fonts into every open Obsidian document
* and registers custom font metrics with the shared Excalidraw runtime.
*/
public async initializeFonts(): Promise<void> {
const cjkFontDataURLs = await getCJKDataURLs(this.plugin);
if (typeof cjkFontDataURLs === "boolean" && !cjkFontDataURLs) {
new Notice(
t("FONTS_LOAD_ERROR") + this.plugin.settings.fontAssetsPath,
6000,
);
}
if (typeof cjkFontDataURLs === "object") {
const fontDeclarations = cjkFontDataURLs.map(
(dataURL) =>
`@font-face { font-family: 'Xiaolai'; src: url("${dataURL}"); font-display: swap; font-weight: 400; }`,
);
for (const ownerDocument of this.getOpenObsidianDocuments()) {
await this.addFonts(fontDeclarations, ownerDocument, CJK_STYLE_ID);
}
new Notice(t("FONTS_LOADED"));
}
const font = await getFontDataURL(
this.plugin.app,
this.plugin.settings.experimantalFourthFont,
"",
"Local Font",
);
if (font.dataURL === "") {
this.plugin.fourthFontLoaded = true;
return;
}
const fourthFontDataURL = font.dataURL;
const file = this.plugin.app.metadataCache.getFirstLinkpathDest(
this.plugin.settings.experimantalFourthFont,
"",
);
let fontMetrics = file.extension.startsWith("woff") || !font.arrayBuffer
? undefined
: getFontMetrics(font.arrayBuffer);
if (!fontMetrics) {
fontMetrics = {
unitsPerEm: 1000,
ascender: 750,
descender: -250,
lineHeight: 1.2,
};
}
const { excalidrawLib } = this.getRuntimePackage();
if (fontMetrics) {
excalidrawLib.registerLocalFont(
{ metrics: fontMetrics },
fourthFontDataURL,
);
}
for (const ownerDocument of this.getOpenObsidianDocuments()) {
await this.addFonts(
[
`@font-face{font-family:'Local Font';src:url("${fourthFontDataURL}");font-display: swap;font-weight: 400;`,
],
ownerDocument,
);
}
if (!this.plugin.fourthFontLoaded) {
window.setTimeout(() => {
this.plugin.fourthFontLoaded = true;
}, 100);
}
this.fontsReady = true;
}
/** Replaces a plugin-owned font stylesheet and waits for the font to load. */
public async addFonts(
declarations: string[],
ownerDocument: Document = mainDocument,
styleId: string = FONTS_STYLE_ID,
): Promise<void> {
const newStylesheet = deliberateCreateElement(ownerDocument, "style");
newStylesheet.id = styleId;
newStylesheet.textContent = declarations.join("");
const oldStylesheet = ownerDocument.getElementById(styleId);
ownerDocument.head.appendChild(newStylesheet);
if (oldStylesheet) {
ownerDocument.head.removeChild(oldStylesheet);
}
await ownerDocument.fonts.load("20px Local Font");
}
/** Removes custom and CJK font stylesheets from all open documents. */
public removeFonts(): void {
this.getOpenObsidianDocuments().forEach((ownerDocument) => {
const oldCustomFontStylesheet =
ownerDocument.getElementById(FONTS_STYLE_ID);
if (oldCustomFontStylesheet) {
ownerDocument.head.removeChild(oldCustomFontStylesheet);
}
const oldCJKFontStylesheet = ownerDocument.getElementById(CJK_STYLE_ID);
if (oldCJKFontStylesheet) {
ownerDocument.head.removeChild(oldCJKFontStylesheet);
}
});
}
private getOpenObsidianDocuments(): Document[] {
const visitedDocuments = new Set<Document>();
this.plugin.app.workspace.iterateAllLeaves((leaf) => {
const ownerDocument = DEVICE.isMobile
? mainDocument
: leaf.view.containerEl.ownerDocument;
if (!ownerDocument || visitedDocuments.has(ownerDocument)) {
return;
}
visitedDocuments.add(ownerDocument);
});
return Array.from(visitedDocuments);
}
}
@@ -0,0 +1,92 @@
import type { App } from "obsidian";
import { DEVICE } from "src/constants/constants";
import type { ExcalidrawSettings } from "src/core/settingsDefaults";
import { isInstanceOfHTMLStyleElement } from "src/utils/typechecks";
declare const mainDocument: Document;
declare const deliberateCreateElement: (
document: Document,
tagName: string,
) => HTMLStyleElement;
const FOOTER_SAFE_AREA_STYLE_ID = "excalidraw-phone-footer-safe-area";
const FOOTER_SAFE_AREA_CSS = `
.excalidraw .App-bottom-bar {
padding-bottom: 50px;
}
`;
interface FooterSafeAreaHost {
app: App;
settings: ExcalidrawSettings;
}
/**
* Owns the optional phone and tablet footer-padding stylesheet across Obsidian
* documents, including cleanup when the plugin unloads.
*/
export class FooterSafeAreaManager {
public constructor(private readonly host: FooterSafeAreaHost) {}
/** Applies or removes footer padding according to the current device and settings. */
public updateFooterSafeAreaPadding(): void {
const documents = new Set<Document>([
mainDocument,
...this.getOpenObsidianDocuments(),
]);
const shouldEnable =
(DEVICE.isPhone && this.host.settings?.phoneFooterSafeAreaPadding) ||
(DEVICE.isTablet && this.host.settings?.tabletFooterSafeAreaPadding);
documents.forEach((ownerDocument) => {
const existingStylesheet = ownerDocument.getElementById(
FOOTER_SAFE_AREA_STYLE_ID,
);
if (!shouldEnable) {
if (existingStylesheet) {
ownerDocument.head.removeChild(existingStylesheet);
}
return;
}
if (isInstanceOfHTMLStyleElement(existingStylesheet)) {
existingStylesheet.textContent = FOOTER_SAFE_AREA_CSS;
return;
}
const stylesheet = deliberateCreateElement(ownerDocument, "style");
stylesheet.id = FOOTER_SAFE_AREA_STYLE_ID;
stylesheet.textContent = FOOTER_SAFE_AREA_CSS;
ownerDocument.head.appendChild(stylesheet);
});
}
/** Removes every footer-padding stylesheet owned by the plugin. */
public destroy(): void {
const documents = new Set<Document>([
mainDocument,
...this.getOpenObsidianDocuments(),
]);
documents.forEach((ownerDocument) => {
const existingStylesheet = ownerDocument.getElementById(
FOOTER_SAFE_AREA_STYLE_ID,
);
if (existingStylesheet) {
ownerDocument.head.removeChild(existingStylesheet);
}
});
}
private getOpenObsidianDocuments(): Document[] {
const visitedDocuments = new Set<Document>();
this.host.app.workspace.iterateAllLeaves((leaf) => {
const ownerDocument = DEVICE.isMobile
? mainDocument
: leaf.view.containerEl.ownerDocument;
if (!ownerDocument || visitedDocuments.has(ownerDocument)) {
return;
}
visitedDocuments.add(ownerDocument);
});
return Array.from(visitedDocuments);
}
}
+17 -11
View File
@@ -13,7 +13,7 @@ import {
} from "../../constants/constants";
import { EmbeddedFilesLoader } from "../../shared/EmbeddedFileLoader";
import { createPNG, createSVG } from "../../utils/excalidrawAutomateUtils";
import ExcalidrawPlugin from "../main";
import type ExcalidrawPlugin from "../main";
import { getIMGFilename } from "../../utils/fileUtils";
import {
getEmbeddedFilenameParts,
@@ -23,6 +23,7 @@ import {
getWithBackground,
hasExportTheme,
convertSVGStringToElement,
isImagePartRef,
isMaskFile,
} from "../../utils/utils";
import {
@@ -40,6 +41,7 @@ import { linkPrompt } from "../../shared/Dialogs/Prompt";
import {
isInstanceOfHTMLElement,
isInstanceOfHTMLImageElement,
isInstanceOfSVGSVGElement,
isInstanceOfSVGElement,
} from "../../utils/typechecks";
import { ExportSettings } from "src/types/exportUtilTypes";
@@ -149,25 +151,23 @@ const _getPNG = async ({
};
if (cacheReady) {
const src = await getImageCache().getImageFromCache(cacheKey);
//In case of PNG I cannot change the viewBox to select the area of the element
//being referenced. For PNG only the group reference works
const src = await getImageCache().getImageFromCache(cacheKey, {
expectedPayloadKind: "raster",
});
if (src && typeof src === "string") {
img.src = src;
return img;
}
}
const quickPNG = !(filenameParts.hasGroupref || filenameParts.hasFrameref)
const quickPNG = !isImagePartRef(filenameParts)
? await getQuickImagePreview(plugin, file.path, "png")
: undefined;
const png =
quickPNG ??
(await createPNG(
filenameParts.hasGroupref ||
filenameParts.hasFrameref ||
filenameParts.hasClippedFrameref
isImagePartRef(filenameParts)
? filenameParts.filepath + filenameParts.linkpartReference
: file.path,
scale,
@@ -189,6 +189,7 @@ const _getPNG = async ({
[],
plugin,
0,
getExportPadding(plugin, file),
));
if (!png) {
return null;
@@ -290,7 +291,10 @@ const _getSVGIMG = async ({
};
if (cacheReady) {
const src = await getImageCache().getImageFromCache(cacheKey);
const src = await getImageCache().getImageFromCache(cacheKey, {
expectedPayloadKind: "svg",
svgFormat: "data-url",
});
if (src && typeof src === "string") {
img.setAttribute("src", src);
return img;
@@ -382,11 +386,13 @@ const _getSVGNative = async ({
};
let maybeSVG;
if (cacheReady) {
maybeSVG = await getImageCache().getImageFromCache(cacheKey);
maybeSVG = await getImageCache().getImageFromCache(cacheKey, {
expectedPayloadKind: "svg",
});
}
const svg =
maybeSVG && maybeSVG instanceof SVGSVGElement
maybeSVG && isInstanceOfSVGSVGElement(maybeSVG)
? maybeSVG
: convertSVGStringToElement(
(
+4 -4
View File
@@ -43,6 +43,10 @@ export class MonkeyPatchManager {
T extends View,
>(this: Workspace, type: ViewConstructor<T>): T | null {
const result = old.call(this, type) as T | null;
const stackTrace = new Error().stack ?? "";
if (!MonkeyPatchManager.isCallerFromTemplaterPlugin(stackTrace)) {
return result;
}
const maybeEAView = this.getMostRecentLeaf()?.view;
if (
!maybeEAView ||
@@ -50,10 +54,6 @@ export class MonkeyPatchManager {
) {
return result;
}
const stackTrace = new Error().stack ?? "";
if (!MonkeyPatchManager.isCallerFromTemplaterPlugin(stackTrace)) {
return result;
}
const leafOrNode = (
maybeEAView as ExcalidrawView
).getActiveEmbeddable();
+60 -23
View File
@@ -1,5 +1,6 @@
import { t } from "src/lang/helpers";
import { DEBUGGING } from "src/utils/debugHelper";
import ExcalidrawPlugin from "src/core/main";
import type ExcalidrawPlugin from "src/core/main";
import { CustomMutationObserver } from "src/utils/debugHelper";
import { DEVICE } from "src/constants/constants";
import {
@@ -11,14 +12,30 @@ import {
isInstanceOfDocumentFragment,
isInstanceOfElement,
} from "src/utils/typechecks";
import type ExcalidrawView from "src/view/ExcalidrawView";
declare const mainDocument: Document;
const MODAL_CONTAINER_SELECTOR = ".modal-container";
/**
* Checks an observed DOM node without relying on cross-window constructors.
*
* Mutation records can contain nodes from an Obsidian popout realm whose
* `instanceof Element` identity is not reliable after window migration.
*/
const isObservedElement = (node: Node): node is Element =>
node.nodeType === 1 && typeof (node as Element).matches === "function";
export class ObserverManager {
private plugin: ExcalidrawPlugin;
private app: App;
private themeObserver: MutationObserver | CustomMutationObserver;
private fileExplorerObserver: MutationObserver | CustomMutationObserver;
private modalContainerObserver: MutationObserver | CustomMutationObserver;
private modalContainerObserver:
| MutationObserver
| CustomMutationObserver
| null = null;
private modalObservedView: ExcalidrawView | null = null;
private workspaceDrawerLeftObserver:
| MutationObserver
| CustomMutationObserver;
@@ -49,7 +66,7 @@ export class ObserverManager {
this.addWorkspaceDrawerObserver();
}
} catch (e) {
new Notice("Error adding ObserverManager", 6000);
new Notice(t("ERROR_ADDING_OBSERVER_MANAGER"), 6000);
console.error("Error adding ObserverManager", e);
}
this.plugin.logStartupEvent("ObserverManager added");
@@ -266,51 +283,70 @@ export class ObserverManager {
}
/**
* Monitors if the user clicks outside the Excalidraw view, and saves the drawing if it's dirty
* @returns
* Saves a dirty drawing when an Obsidian modal opens in its live document.
*
* @param view - The active or same-leaf replacement view to observe.
*/
public addModalContainerObserver() {
if (!this.plugin.activeExcalidrawView) {
public addModalContainerObserver(view = this.plugin.activeExcalidrawView) {
if (!view) {
return;
}
const activeViewDoc = view.containerEl.ownerDocument;
if (this.modalContainerObserver) {
if (
this.activeViewDoc === this.plugin.activeExcalidrawView.ownerDocument
this.activeViewDoc === activeViewDoc &&
this.modalObservedView === view
) {
return;
}
this.removeModalContainerObserver();
}
//The user clicks settings, or "open another vault", or the command palette
//The user clicks settings, or "open another vault", or the command palette.
//Other body portals, including inline suggestions, must not interrupt editing with a save.
const modalContainerObserverFn: MutationCallback = (
m: MutationRecord[],
mutations: MutationRecord[],
) => {
const view = this.plugin.activeExcalidrawView;
const observedView = this.modalObservedView;
const addedNodes = mutations.flatMap((mutation) =>
mutation.type === "childList"
? Array.from(mutation.addedNodes)
: [],
);
const modalOpened = addedNodes.some(
(node) =>
isObservedElement(node) &&
(node.matches(MODAL_CONTAINER_SELECTOR) ||
node.querySelector(MODAL_CONTAINER_SELECTOR) !== null),
);
if (
m.length !== 1 ||
m[0].type !== "childList" ||
m[0].addedNodes.length !== 1 ||
!view ||
view.semaphores?.viewunload ||
!view.isDirty()
!modalOpened ||
!observedView ||
observedView.semaphores?.viewunload ||
!observedView.isDirty() ||
!observedView.excalidrawAPI
) {
return;
}
const { errorMessage } = view.excalidrawAPI.getAppState();
const { errorMessage } = observedView.excalidrawAPI.getAppState();
if (!errorMessage) {
void this.plugin.activeExcalidrawView.save();
void observedView.save();
}
};
this.activeViewDoc = activeViewDoc;
this.modalObservedView = view;
// Keep the observer constructor and target in the same window realm so a
// migrated view never depends on its destroyed source window.
this.modalContainerObserver = DEBUGGING
? new CustomMutationObserver(
modalContainerObserverFn,
"modalContainerObserver",
)
: new MutationObserver(modalContainerObserverFn);
this.activeViewDoc = this.plugin.activeExcalidrawView.ownerDocument;
this.modalContainerObserver.observe(this.activeViewDoc.body, {
: new (activeViewDoc.defaultView?.MutationObserver ?? MutationObserver)(
modalContainerObserverFn,
);
this.modalContainerObserver.observe(activeViewDoc.body, {
childList: true,
});
}
@@ -320,8 +356,9 @@ export class ObserverManager {
return;
}
this.modalContainerObserver.disconnect();
this.activeViewDoc = null;
this.modalContainerObserver = null;
this.modalObservedView = null;
this.activeViewDoc = null;
}
private addWorkspaceDrawerObserver() {
+228 -137
View File
@@ -1,36 +1,77 @@
import { updateExcalidrawLib } from "src/constants/constants";
import { ExcalidrawLib } from "../../types/excalidrawLib";
import { Packages } from "../../types/types";
import { PackageLease, Packages } from "../../types/types";
import { Notice } from "obsidian";
import ExcalidrawPlugin from "src/core/main";
import type ExcalidrawPlugin from "src/core/main";
import { errorHandler } from "../../utils/ErrorHandler";
import React from "react";
import ReactDOM from "react-dom/client";
import * as ReactDOMLegacy from "react-dom";
import * as ReactDOMClient from "react-dom/client";
import * as ReactJSXRuntime from "react/jsx-runtime";
import * as ReactJSXDevRuntime from "react/jsx-dev-runtime";
import { createObsidianCommonHostAdapter } from "./obsidianCommonHostAdapter";
import { createObsidianExcalidrawHostAdapter } from "./obsidianExcalidrawHostAdapter";
declare let REACT_PACKAGES: string;
declare let react: typeof React;
declare let reactDOM: typeof ReactDOM;
declare let excalidrawLib: typeof ExcalidrawLib;
declare const unpackExcalidraw: () => string;
export class PackageManager {
private packageMap: Map<Window, Packages> = new Map<Window, Packages>();
private EXCALIDRAW_PACKAGE: string;
private plugin: ExcalidrawPlugin;
private fallbackPackage: Packages | null = null;
const reactDOM = Object.assign({}, ReactDOMLegacy, ReactDOMClient);
const reactJSXDevRuntime = Object.assign({}, ReactJSXDevRuntime, {
// React's production jsx-dev-runtime deliberately leaves jsxDEV undefined,
// while the Excalidraw artifact accepts either external runtime entrypoint.
jsxDEV: ReactJSXDevRuntime.jsxDEV ?? ReactJSXRuntime.jsx,
});
constructor(plugin: ExcalidrawPlugin) {
this.plugin = plugin;
const normalizeError = (error: unknown): Error =>
error instanceof Error
? error
: new Error(typeof error === "string" ? error : "Unknown error");
/**
* Owns the plugin's single private React/Excalidraw runtime.
*
* Each view receives the same package but retains an idempotent lease keyed by
* its actual window. The window key governs migration persistence and the
* temporary `ExcalidrawLib` compatibility alias only; rendering ownership is
* supplied independently through each Excalidraw instance's `ownerDocument`.
*/
export class PackageManager {
private runtimePackage: Packages | null = null;
private packageLeaseCountMap = new Map<Window, number>();
private commonHostDisposer: (() => void) | null = null;
private excalidrawHostDisposer: (() => void) | null = null;
private runtimeAliasWindows = new Set<Window>();
constructor(private readonly plugin: ExcalidrawPlugin) {
let excalidrawPackage = "";
try {
this.EXCALIDRAW_PACKAGE = unpackExcalidraw();
excalidrawPackage = unpackExcalidraw();
// Use safe evaluation for unpacking the Excalidraw package
excalidrawLib = errorHandler.safeEval(
`(function() {${this.EXCALIDRAW_PACKAGE};return ExcalidrawLib;})()`,
// Evaluate Excalidraw in the main window with the same private React
// instance used by the plugin bundle. The runtime is passed explicitly
// because window.React and window.ReactDOM are deliberately not set.
const loadExcalidraw = errorHandler.safeEval<
(
reactInstance: typeof React,
reactDOMInstance: typeof reactDOM,
jsxRuntime: unknown,
jsxDevRuntime: unknown,
) => typeof ExcalidrawLib
>(
`(function(React, ReactDOM, ReactJSXRuntime, ReactJSXDevRuntime) {
${excalidrawPackage};
return ExcalidrawLib;
})`,
"PackageManager constructor - excalidrawLib initialization",
window,
);
excalidrawLib = loadExcalidraw(
React,
reactDOM,
ReactJSXRuntime,
reactJSXDevRuntime,
);
if (!excalidrawLib) {
throw new Error("Failed to initialize excalidrawLib");
@@ -40,22 +81,29 @@ export class PackageManager {
updateExcalidrawLib();
// Create a package with the loaded libraries
const initialPackage = { react, reactDOM, excalidrawLib };
const initialPackage = { react: React, reactDOM, excalidrawLib };
// Validate the package before storing
if (this.validatePackage(initialPackage)) {
this.setPackage(window, initialPackage);
this.fallbackPackage = initialPackage; // Store a valid package as fallback
this.setRuntimePackage(initialPackage);
} else {
throw new Error("Invalid initial package");
}
} catch (e) {
errorHandler.handleError(e, "PackageManager constructor");
} catch (e: unknown) {
errorHandler.handleError(
normalizeError(e),
"PackageManager constructor",
);
new Notice(
"Error loading the Excalidraw package. Some features may not work correctly.",
10000,
);
console.error("Error loading the Excalidraw package", e);
} finally {
// Per-window evaluation has been removed. Release the decompressed
// Excalidraw source after the one runtime is initialized instead of
// retaining it for hypothetical future popouts.
excalidrawPackage = "";
}
plugin.logStartupEvent("Excalidraw package unpacked");
@@ -85,151 +133,194 @@ export class PackageManager {
}
/**
* Store a package for a specific window
* Registers plugin capabilities with one evaluated Excalidraw runtime.
*/
public setPackage(window: Window, pkg: Packages) {
if (this.validatePackage(pkg)) {
this.packageMap.set(window, pkg);
private configureObsidianCommonHost(pkg: Packages): void {
this.commonHostDisposer?.();
this.commonHostDisposer = null;
// Update fallback if we don't have one
if (!this.fallbackPackage) {
this.fallbackPackage = pkg;
const lib = pkg.excalidrawLib;
if (
!lib ||
typeof lib.configureObsidianCommonHost !== "function" ||
typeof lib.OBSIDIAN_COMMON_HOST_PROTOCOL_VERSION !== "number"
) {
throw new Error("Excalidraw package is missing the common host boundary");
}
const adapter = createObsidianCommonHostAdapter(
this.plugin,
lib.OBSIDIAN_COMMON_HOST_PROTOCOL_VERSION,
);
this.commonHostDisposer = lib.configureObsidianCommonHost(adapter);
}
/** Registers plugin-wide settings with one evaluated Excalidraw runtime. */
private configureObsidianExcalidrawHost(pkg: Packages): void {
this.excalidrawHostDisposer?.();
this.excalidrawHostDisposer = null;
const lib = pkg.excalidrawLib;
if (
!lib ||
typeof lib.configureObsidianExcalidrawHost !== "function" ||
typeof lib.OBSIDIAN_EXCALIDRAW_HOST_PROTOCOL_VERSION !== "number"
) {
throw new Error(
"Excalidraw package is missing the package host boundary",
);
}
const adapter = createObsidianExcalidrawHostAdapter(
this.plugin,
lib.OBSIDIAN_EXCALIDRAW_HOST_PROTOCOL_VERSION,
);
this.excalidrawHostDisposer =
lib.configureObsidianExcalidrawHost(adapter);
}
/** Disposes the plugin capabilities registered with the shared runtime. */
private disposeObsidianHosts(): void {
this.commonHostDisposer?.();
this.commonHostDisposer = null;
this.excalidrawHostDisposer?.();
this.excalidrawHostDisposer = null;
}
/** Stores and configures the plugin's single evaluated runtime package. */
private setRuntimePackage(pkg: Packages): void {
if (this.validatePackage(pkg)) {
try {
this.configureObsidianCommonHost(pkg);
this.configureObsidianExcalidrawHost(pkg);
} catch (error: unknown) {
this.disposeObsidianHosts();
throw normalizeError(error);
}
this.runtimePackage = pkg;
} else {
errorHandler.handleError(
"Attempted to set invalid package",
"PackageManager.setPackage",
"PackageManager.setRuntimePackage",
);
}
}
public getPackageMap() {
return this.packageMap;
/** Returns the one runtime used by every main-window and popout view. */
public getRuntimePackage(): Packages {
if (!this.runtimePackage || !this.validatePackage(this.runtimePackage)) {
throw new Error("Excalidraw runtime package is unavailable");
}
return this.runtimePackage;
}
/**
* Gets a package for a window, creating it if necessary
* with robust error handling
* Acquires the shared runtime while retaining the view's actual window.
*
* @remarks
* Window identity remains view-owned migration/persistence state. Popout
* leases additionally own the temporary `window.ExcalidrawLib` compatibility
* alias and remove it when the final view in that window releases its lease.
*/
public acquirePackage(win: Window): PackageLease {
const packages = this.getPackage(win);
const leaseCount = (this.packageLeaseCountMap.get(win) ?? 0) + 1;
this.packageLeaseCountMap.set(win, leaseCount);
let released = false;
return {
window: win,
packages,
release: () => {
if (released) {
return;
}
released = true;
this.releasePackageLease(win);
},
};
}
/** Releases one view-owned package lease without consulting mutable DOM. */
private releasePackageLease(win: Window): void {
const leaseCount = this.packageLeaseCountMap.get(win);
if (leaseCount === undefined) {
return;
}
const remainingLeases = Math.max(0, leaseCount - 1);
if (remainingLeases === 0) {
this.packageLeaseCountMap.delete(win);
if (win !== window) {
this.removeRuntimeAlias(win);
}
} else {
this.packageLeaseCountMap.set(win, remainingLeases);
}
}
/**
* Returns the shared runtime and exposes its compatibility API in `win`.
*
* @remarks
* The runtime is never evaluated in the supplied window. Rendering ownership
* is provided separately through Excalidraw's stable `ownerDocument` prop.
*/
public getPackage(win: Window): Packages {
try {
// Return existing package if available
if (this.packageMap.has(win)) {
const pkg = this.packageMap.get(win);
if (this.validatePackage(pkg)) {
return pkg;
}
// If package exists but is invalid, delete it so we can recreate it
this.packageMap.delete(win);
}
// Create new package
return errorHandler.wrapWithTryCatch(
() => {
// Use safe evaluation to load packages in the window context
const evalResult = errorHandler.safeEval<{
react: typeof React;
reactDOM: typeof ReactDOM;
excalidrawLib: typeof ExcalidrawLib;
}>(
`(function() {
${REACT_PACKAGES + this.EXCALIDRAW_PACKAGE};
return {react: React, reactDOM: ReactDOM, excalidrawLib: ExcalidrawLib};
})()`,
"PackageManager.getPackage - package evaluation",
win,
);
if (!evalResult || !this.validatePackage(evalResult)) {
throw new Error("Failed to create valid package");
}
const newPackage = {
react: evalResult.react,
reactDOM: evalResult.reactDOM,
excalidrawLib: evalResult.excalidrawLib,
};
this.packageMap.set(win, newPackage);
return newPackage;
},
"PackageManager.getPackage",
this.fallbackPackage,
);
} catch (error) {
errorHandler.handleError(error, "PackageManager.getPackage");
// Return fallback package if available to prevent data loss
if (this.fallbackPackage) {
return this.fallbackPackage;
}
// If no fallback, throw error to prevent undefined behavior
throw new Error("Failed to get package and no fallback available");
const pkg = this.getRuntimePackage();
if (win !== window) {
win.ExcalidrawLib = pkg.excalidrawLib;
this.runtimeAliasWindows.add(win);
}
return pkg;
}
/** Removes only the window-local alias; the shared runtime remains alive. */
private removeRuntimeAlias(win: Window): void {
const packageLib = this.runtimePackage?.excalidrawLib;
errorHandler.wrapWithTryCatch(() => {
if (packageLib && win.ExcalidrawLib === packageLib) {
delete win.ExcalidrawLib;
}
}, "PackageManager.removeRuntimeAlias");
this.runtimeAliasWindows.delete(win);
}
/**
* Compatibility facade retained for callers that explicitly clean a window.
* The plugin-wide runtime and host registrations live until `destroy()`.
*/
public deletePackage(win: Window) {
try {
const pkg = this.packageMap.get(win);
if (!pkg) {
return;
if (win !== window) {
this.removeRuntimeAlias(win);
}
const { react, reactDOM, excalidrawLib } = pkg;
if (win.ExcalidrawLib === excalidrawLib) {
// Safely clean up resources
errorHandler.wrapWithTryCatch(() => {
if (
excalidrawLib &&
typeof excalidrawLib.destroyObsidianUtils === "function"
) {
excalidrawLib.destroyObsidianUtils();
}
delete win.ExcalidrawLib;
}, "PackageManager.deletePackage - cleanup ExcalidrawLib");
}
if (win.React === react) {
errorHandler.wrapWithTryCatch(() => {
delete win.React;
}, "PackageManager.deletePackage - cleanup React");
}
if (win.ReactDOM === reactDOM) {
errorHandler.wrapWithTryCatch(() => {
delete win.ReactDOM;
}, "PackageManager.deletePackage - cleanup ReactDOM");
}
this.packageMap.delete(win);
} catch (error) {
errorHandler.handleError(error, "PackageManager.deletePackage");
} catch (error: unknown) {
errorHandler.handleError(
normalizeError(error),
"PackageManager.deletePackage",
);
}
}
public setExcalidrawPackage(pkg: string) {
this.EXCALIDRAW_PACKAGE = pkg;
}
public destroy() {
try {
REACT_PACKAGES = "";
Array.from(this.packageMap.entries()).forEach(([win, _]) => {
this.deletePackage(win);
Array.from(this.runtimeAliasWindows).forEach((win) => {
this.removeRuntimeAlias(win);
});
this.removeRuntimeAlias(window);
this.packageMap.clear();
this.EXCALIDRAW_PACKAGE = "";
this.fallbackPackage = null;
this.packageLeaseCountMap.clear();
this.runtimeAliasWindows.clear();
this.disposeObsidianHosts();
this.runtimePackage = null;
react = null;
reactDOM = null;
excalidrawLib = null;
} catch (error) {
errorHandler.handleError(error, "PackageManager.destroy");
} catch (error: unknown) {
errorHandler.handleError(
normalizeError(error),
"PackageManager.destroy",
);
}
}
}
+395
View File
@@ -0,0 +1,395 @@
import { Notice, type App, type PluginManifest } from "obsidian";
import { JSON_parse } from "src/constants/constants";
import {
DEFAULT_SETTINGS,
type ExcalidrawSettings,
} from "src/core/settingsDefaults";
import { PreviewImageType } from "src/types/utilTypes";
import {
decryptPersistedAPIKeys,
encryptPersistedAPIKeys,
} from "src/utils/settingsKeyObfuscation";
import { SerializedSettingsWriter } from "src/core/settings/SerializedSettingsWriter";
import { SettingsRecoveryStore } from "src/core/settings/SettingsRecoveryStore";
import {
SettingsRecoveryPrompt,
type SettingsRecoveryChoice,
type SettingsRecoveryPromptMode,
} from "src/shared/Dialogs/SettingsRecoveryPrompt";
import {
classifySettingsDataLoad,
isSettingsDataRecord,
type SettingsDataFileState,
} from "src/core/settings/settingsDataValidation";
import { t } from "src/lang/helpers";
type PersistedExcalidrawSettings = Partial<ExcalidrawSettings> &
Record<string, unknown>;
interface PluginSettingsHost {
app: App;
manifest: PluginManifest;
settings: ExcalidrawSettings;
loadData(): Promise<unknown>;
saveData(data: unknown): Promise<void>;
}
interface SettingsRecoveryStoreLike {
load(): Promise<PersistedExcalidrawSettings | null>;
save(settings: PersistedExcalidrawSettings): Promise<void>;
destroy(): void;
}
type SettingsRecoveryPromptHandler = (
mode: SettingsRecoveryPromptMode,
) => Promise<SettingsRecoveryChoice>;
/**
* Owns plugin settings persistence, default assembly, and compatibility
* migrations while leaving startup readiness and settings UI registration to
* the plugin lifecycle.
*/
export class PluginSettingsManager {
private readonly writer: SerializedSettingsWriter<PersistedExcalidrawSettings>;
private readonly recoveryStore: SettingsRecoveryStoreLike;
private hasCompletedInitialLoad = false;
private persistenceBlockedByInvalidData = false;
private missingRecoveryNoticeShown = false;
private awaitingStartupRecoveryChoice = false;
private readonly promptForRecoveryChoice: SettingsRecoveryPromptHandler;
public constructor(
private readonly host: PluginSettingsHost,
recoveryStore?: SettingsRecoveryStoreLike,
promptForRecoveryChoice?: SettingsRecoveryPromptHandler,
) {
this.recoveryStore =
recoveryStore ??
new SettingsRecoveryStore({
databaseName: `Excalidraw Settings Recovery ${host.app.appId}`,
});
this.promptForRecoveryChoice =
promptForRecoveryChoice ??
((mode) => new SettingsRecoveryPrompt(host.app, mode).start());
this.writer = new SerializedSettingsWriter({
saveData: async (data) => {
await this.saveRecoverySnapshot(data);
await this.host.saveData(data);
},
});
}
/**
* Loads persisted settings, applies defaults and migrations, and decrypts
* protected API-key fields.
*
* @remarks Unknown persisted properties are intentionally retained.
* @returns `false` when the disk payload was invalid. Runtime callers use
* this to suppress cache invalidation for a rejected synchronized payload.
*/
public async loadSettings(): Promise<boolean> {
const dataFileState = await this.getSettingsDataFileState();
let loadedSettings: unknown = null;
let loadFailed = false;
try {
loadedSettings = await this.host.loadData();
} catch {
loadFailed = true;
}
const classification = classifySettingsDataLoad({
value: loadedSettings,
fileState: dataFileState,
loadFailed,
isInitialLoad: !this.hasCompletedInitialLoad,
});
const hasInvalidSettings = classification === "invalid";
const isFirstInstallation = classification === "first-installation";
let persistedSettings: PersistedExcalidrawSettings;
let recoveredInvalidStartup = false;
let shouldPersistStartupChoice = false;
if (hasInvalidSettings) {
if (this.hasCompletedInitialLoad) {
this.persistenceBlockedByInvalidData = false;
this.missingRecoveryNoticeShown = false;
new Notice(t("SETTINGS_DATA_REPAIRED_FROM_MEMORY"), 12000);
console.error(
"Excalidraw rejected invalid synchronized settings data and restored the active settings",
);
await this.persistSnapshot(
encryptPersistedAPIKeys(
this.host.settings as PersistedExcalidrawSettings,
),
);
return false;
}
const recoveredSettings = await this.loadRecoverySnapshot();
if (recoveredSettings) {
persistedSettings = recoveredSettings;
recoveredInvalidStartup = true;
shouldPersistStartupChoice = true;
this.persistenceBlockedByInvalidData = false;
this.missingRecoveryNoticeShown = false;
} else {
this.host.settings = Object.assign({}, DEFAULT_SETTINGS);
const choice = await this.requestStartupRecoveryChoice(
"invalid-without-recovery",
);
persistedSettings = {};
if (choice === "reset-defaults") {
this.persistenceBlockedByInvalidData = false;
this.missingRecoveryNoticeShown = false;
shouldPersistStartupChoice = true;
} else {
this.blockPersistenceWhileWaitingForFile();
}
}
} else if (isFirstInstallation) {
const recoveredSettings = await this.loadRecoverySnapshot();
if (recoveredSettings) {
this.host.settings = Object.assign({}, DEFAULT_SETTINGS);
const choice = await this.requestStartupRecoveryChoice(
"missing-with-recovery",
);
persistedSettings =
choice === "reset-defaults" ? {} : recoveredSettings;
} else {
persistedSettings = {};
}
this.persistenceBlockedByInvalidData = false;
this.missingRecoveryNoticeShown = false;
shouldPersistStartupChoice = true;
} else {
this.persistenceBlockedByInvalidData = false;
this.missingRecoveryNoticeShown = false;
persistedSettings = isSettingsDataRecord(loadedSettings)
? loadedSettings
: {};
}
const decryptedSettings = decryptPersistedAPIKeys(persistedSettings);
let didSettingsMigration = false;
this.host.settings = Object.assign(
{},
DEFAULT_SETTINGS,
decryptedSettings,
);
if (typeof decryptedSettings.libraryStorageMode === "undefined") {
const legacyLibrary: unknown =
typeof decryptedSettings.library === "string" &&
decryptedSettings.library !== "" &&
decryptedSettings.library !== "deprecated"
? JSON_parse(decryptedSettings.library)
: decryptedSettings.library2;
const legacyLibraryRecord =
typeof legacyLibrary === "object" && legacyLibrary !== null
? (legacyLibrary as Record<string, unknown>)
: null;
const hasLegacyItems = Boolean(
(Array.isArray(legacyLibraryRecord?.library) &&
legacyLibraryRecord.library.length) ||
(Array.isArray(legacyLibraryRecord?.libraryItems) &&
legacyLibraryRecord.libraryItems.length),
);
this.host.settings.libraryStorageMode = hasLegacyItems
? "data-json"
: "vault";
this.host.settings.libraryMigrationStatus = hasLegacyItems
? "pending"
: "not-required";
didSettingsMigration = true;
}
const savedMarkdownImageSettings = decryptedSettings.markdownImageSettings;
if (!savedMarkdownImageSettings) {
this.host.settings.markdownImageSettings = {
defaults: {
...DEFAULT_SETTINGS.markdownImageSettings.defaults,
width: this.host.settings.mdSVGwidth,
fontFamily: this.host.settings.mdFont,
fontColor: this.host.settings.mdFontColor ?? "#000000",
border: {
enabled: false,
color: this.host.settings.mdBorderColor,
},
css: "",
transclusion: {
...DEFAULT_SETTINGS.markdownImageSettings.defaults.transclusion,
border: {
...DEFAULT_SETTINGS.markdownImageSettings.defaults.transclusion
.border,
},
},
},
};
didSettingsMigration = true;
} else {
this.host.settings.markdownImageSettings = {
defaults: {
...DEFAULT_SETTINGS.markdownImageSettings.defaults,
...savedMarkdownImageSettings.defaults,
border: {
...DEFAULT_SETTINGS.markdownImageSettings.defaults.border,
...savedMarkdownImageSettings.defaults?.border,
},
transclusion: {
...DEFAULT_SETTINGS.markdownImageSettings.defaults.transclusion,
...savedMarkdownImageSettings.defaults?.transclusion,
border: {
...DEFAULT_SETTINGS.markdownImageSettings.defaults.transclusion
.border,
...savedMarkdownImageSettings.defaults?.transclusion?.border,
},
},
},
};
}
const markdownImageDefaults = this.host.settings.markdownImageSettings
.defaults as unknown as Record<string, unknown>;
if ("theme" in markdownImageDefaults) {
delete markdownImageDefaults.theme;
didSettingsMigration = true;
}
const settingsRecord = this.host.settings as unknown as Record<
string,
unknown
>;
if (
typeof settingsRecord.iframelyAllowed === "boolean" &&
typeof this.host.settings.oEmbedAllowed !== "boolean"
) {
this.host.settings.oEmbedAllowed = settingsRecord.iframelyAllowed;
didSettingsMigration = true;
}
if ("iframelyAllowed" in settingsRecord) {
delete settingsRecord.iframelyAllowed;
didSettingsMigration = true;
}
if (!this.host.settings.previewImageType) {
// Migration introduced in 1.9.13.
if (typeof this.host.settings.displaySVGInPreview === "undefined") {
this.host.settings.previewImageType = PreviewImageType.SVGIMG;
} else {
this.host.settings.previewImageType = this.host.settings
.displaySVGInPreview
? PreviewImageType.SVGIMG
: PreviewImageType.PNG;
}
}
const encryptedPersistedSettings = encryptPersistedAPIKeys(
this.host.settings as PersistedExcalidrawSettings,
);
const shouldPersistEncryptedSettings =
JSON.stringify(encryptedPersistedSettings) !==
JSON.stringify(persistedSettings);
if (shouldPersistStartupChoice) {
await this.persistSnapshot(encryptedPersistedSettings);
if (recoveredInvalidStartup) {
new Notice(t("SETTINGS_DATA_RECOVERED"), 12000);
}
} else if (
!this.persistenceBlockedByInvalidData &&
(didSettingsMigration || shouldPersistEncryptedSettings)
) {
await this.persistSnapshot(encryptedPersistedSettings);
} else if (!this.persistenceBlockedByInvalidData) {
await this.saveRecoverySnapshot(encryptedPersistedSettings);
}
this.hasCompletedInitialLoad = true;
return !hasInvalidSettings;
}
/** Encrypts protected fields and persists the current settings object. */
public saveSettings(): Promise<void> {
if (this.persistenceBlockedByInvalidData) {
this.showMissingRecoveryNotice();
return Promise.resolve();
}
return this.persistSnapshot(
encryptPersistedAPIKeys(
this.host.settings as PersistedExcalidrawSettings,
),
);
}
/** Whether plugin startup is intentionally waiting for a recovery choice. */
public get isAwaitingStartupRecoveryChoice(): boolean {
return this.awaitingStartupRecoveryChoice;
}
private persistSnapshot(
settings: PersistedExcalidrawSettings,
): Promise<void> {
return this.writer.persist(settings);
}
/** Closes the device-local recovery database connection. */
public destroy(): void {
this.recoveryStore.destroy();
}
private async getSettingsDataFileState(): Promise<SettingsDataFileState> {
const pluginDirectory = this.host.manifest.dir;
if (!pluginDirectory) {
return "unknown";
}
try {
const stat = await this.host.app.vault.adapter.stat(
`${pluginDirectory}/data.json`,
);
if (!stat) {
return "missing";
}
return stat.size === 0 ? "empty" : "present";
} catch {
return "unknown";
}
}
private blockPersistenceWhileWaitingForFile(): void {
this.persistenceBlockedByInvalidData = true;
this.missingRecoveryNoticeShown = false;
}
private showMissingRecoveryNotice(): void {
if (this.missingRecoveryNoticeShown) {
return;
}
this.missingRecoveryNoticeShown = true;
console.error(
"Excalidraw settings data is empty or unreadable; waiting for a valid replacement file",
);
new Notice(t("SETTINGS_DATA_INVALID"), 12000);
}
private async requestStartupRecoveryChoice(
mode: SettingsRecoveryPromptMode,
): Promise<SettingsRecoveryChoice> {
this.awaitingStartupRecoveryChoice = true;
try {
return await this.promptForRecoveryChoice(mode);
} finally {
this.awaitingStartupRecoveryChoice = false;
}
}
private async loadRecoverySnapshot(): Promise<PersistedExcalidrawSettings | null> {
try {
const recoveredSettings = await this.recoveryStore.load();
return isSettingsDataRecord(recoveredSettings) ? recoveredSettings : null;
} catch (error) {
console.error("Could not load Excalidraw settings recovery", error);
return null;
}
}
private async saveRecoverySnapshot(
settings: PersistedExcalidrawSettings,
): Promise<void> {
try {
await this.recoveryStore.save(settings);
} catch (error) {
console.error("Could not update Excalidraw settings recovery", error);
}
}
}
+40
View File
@@ -0,0 +1,40 @@
import { log } from "src/utils/debugHelper";
/** Stores and formats plugin startup timing events without owning startup order. */
export class StartupTimer {
private readonly events: string[] = [];
private lastLogTimestamp: number;
public constructor(
initialTimestamp: number,
private readonly pluginVersion: string,
) {
this.lastLogTimestamp = initialTimestamp;
}
/**
* Starts a new timing baseline while retaining events recorded before the
* reset, matching the existing constructor-to-layout startup breakdown.
*/
public reset(timestamp: number): void {
this.lastLogTimestamp = timestamp;
}
/** Records one startup event with total and previous-event elapsed times. */
public logEvent(message: string, loadTimestamp: number): void {
const timestamp = Date.now();
this.events.push(
`${message}\nTotal: ${timestamp - loadTimestamp}ms Delta: ${timestamp - this.lastLogTimestamp}ms\n`,
);
this.lastLogTimestamp = timestamp;
}
/** Writes the complete startup timing breakdown to the debug log. */
public printBreakdown(): void {
log(
`Excalidraw ${this.pluginVersion} startup breakdown:\n${this.events.join(
"\n",
)}`,
);
}
}
+539
View File
@@ -0,0 +1,539 @@
import { Notice, normalizePath, TFolder } from "obsidian";
import type {
LibraryItem,
LibraryItems,
} from "@zsviczian/excalidraw/types/excalidraw/types";
import type ExcalidrawPlugin from "src/core/main";
import { restoreLibraryItems } from "src/constants/constants";
import { URLs } from "src/constants/safeUrls";
import { t } from "src/lang/helpers";
import { StencilLibraryMigrationPrompt } from "src/shared/Dialogs/StencilLibraryMigrationPrompt";
import type {
StencilLibraryData,
StencilLibraryFileData,
} from "src/types/stencilLibraryTypes";
import { getExcalidrawViews } from "src/utils/obsidianUtils";
const LIBRARY_EXTENSION = "excalidrawlib";
const MIGRATION_SNOOZE_MS = 24 * 60 * 60 * 1000;
const LIBRARY_RELOAD_DEBOUNCE_MS = 300;
const OWN_WRITE_EVENT_WINDOW_MS = 2000;
declare const PLUGIN_VERSION: string;
const getLibraryItems = (data: StencilLibraryData | null): LibraryItems =>
data?.libraryItems ?? data?.library ?? [];
const normalizeLibraryFileName = (fileName: string): string => {
const trimmed = fileName.trim().replace(/[\\/]/g, "-");
const withoutExtension = trimmed.replace(/\.excalidrawlib$/i, "");
return withoutExtension || "local-library";
};
/**
* Owns stencil-library persistence and keeps each item's source file stable.
* Vault writes are reconciled with the latest file contents to avoid clobbering
* files updated by sync after the library was loaded.
*/
export class StencilLibraryManager {
private itemSource = new Map<LibraryItem["id"], string>();
private currentItems: LibraryItems = [];
private loaded = false;
private loadRevision = 0;
private loadPromise: Promise<void> | null = null;
private migrationPrompt: Promise<void> | null = null;
private saveQueue: Promise<void> = Promise.resolve();
private reloadTimer: number | null = null;
private readonly ownWritePaths = new Set<string>();
private isUpdatingOpenViews = false;
constructor(private readonly plugin: ExcalidrawPlugin) {
const handleLibraryFileChange = (file: { path: string }) => {
if (
file.path.startsWith(`${this.getFolderPath()}/`) &&
file.path.toLowerCase().endsWith(`.${LIBRARY_EXTENSION}`)
) {
if (this.ownWritePaths.has(file.path)) {
return;
}
this.invalidate();
if (this.plugin.settings.libraryStorageMode === "vault") {
this.scheduleOpenViewReload();
}
}
};
plugin.registerEvent(
plugin.app.vault.on("create", handleLibraryFileChange),
);
plugin.registerEvent(
plugin.app.vault.on("modify", handleLibraryFileChange),
);
plugin.registerEvent(
plugin.app.vault.on("delete", handleLibraryFileChange),
);
plugin.registerEvent(
plugin.app.vault.on("rename", (file, oldPath) => {
handleLibraryFileChange(file);
handleLibraryFileChange({ path: oldPath });
}),
);
plugin.register(() => {
if (this.reloadTimer !== null) {
window.clearTimeout(this.reloadTimer);
}
});
}
public hasLegacyItems(): boolean {
return getLibraryItems(this.plugin.getLegacyStencilLibrary()).length > 0;
}
public invalidate(): void {
this.loadRevision++;
this.loaded = false;
this.itemSource.clear();
this.currentItems = [];
}
public async getLibrary(): Promise<LibraryItems> {
await this.ensureMigrationDecision();
if (this.plugin.settings.libraryStorageMode === "data-json") {
return restoreLibraryItems(
getLibraryItems(this.plugin.getLegacyStencilLibrary()),
"unpublished",
);
}
if (
this.hasLegacyItems() &&
(this.plugin.settings.libraryMigrationStatus === "completed" ||
this.plugin.settings.libraryMigrationStatus === "not-required")
) {
// A sync conflict can restore stale data.json items after migration.
// Merge them idempotently before clearing the legacy copy again.
await this.migrateLegacyLibrary();
}
if (!this.loaded) {
await this.ensureLoaded();
}
return this.currentItems;
}
public async setLibrary(items: LibraryItems): Promise<void> {
if (this.isUpdatingOpenViews) {
return;
}
if (this.plugin.settings.libraryStorageMode === "data-json") {
await this.plugin.setLegacyStencilLibrary(this.createFileData(items));
return;
}
this.saveQueue = this.saveQueue.then(() => this.persistChanges(items));
await this.saveQueue;
}
public async showMigrationPrompt(): Promise<void> {
if (this.migrationPrompt !== null) {
return this.migrationPrompt;
}
this.migrationPrompt = this.runMigrationPrompt().finally(() => {
this.migrationPrompt = null;
});
return this.migrationPrompt;
}
public async switchToLegacyStorage(): Promise<void> {
const items = await this.getVaultLibrary();
await this.plugin.setLegacyStencilLibrary(
this.createFileData(items),
false,
);
this.plugin.settings.libraryStorageMode = "data-json";
this.plugin.settings.libraryMigrationStatus = "opted-out";
this.plugin.settings.libraryMigrationSnoozeUntil = 0;
await this.plugin.saveSettings();
this.invalidate();
}
/** Reloads the merged vault library in every initialized Excalidraw view. */
public async reloadLibrariesInOpenViews(): Promise<void> {
if (this.plugin.settings.libraryStorageMode !== "vault") {
return;
}
await this.saveQueue;
this.invalidate();
await this.ensureLoaded();
this.isUpdatingOpenViews = true;
try {
for (const view of getExcalidrawViews(this.plugin.app, true)) {
await view.excalidrawAPI.updateLibrary({
libraryItems: this.currentItems,
merge: false,
});
}
} finally {
this.isUpdatingOpenViews = false;
}
}
private async ensureMigrationDecision(): Promise<void> {
const status = this.plugin.settings.libraryMigrationStatus;
const isSnoozed =
status === "later" &&
Date.now() < this.plugin.settings.libraryMigrationSnoozeUntil;
if (status !== "pending" && (status !== "later" || isSnoozed)) {
return;
}
await this.showMigrationPrompt();
}
private async runMigrationPrompt(): Promise<void> {
const result = await new StencilLibraryMigrationPrompt(this.plugin).start();
this.plugin.settings.libraryFolderPath = result.folderPath;
this.plugin.settings.libraryFileName = normalizeLibraryFileName(
result.fileName,
);
if (result.choice === "migrate") {
try {
await this.migrateLegacyLibrary();
new Notice(t("LIBRARY_MIGRATION_SUCCESS"));
} catch (error) {
console.error("Stencil library migration failed", error);
this.plugin.settings.libraryStorageMode = "data-json";
this.plugin.settings.libraryMigrationStatus = "later";
this.plugin.settings.libraryMigrationSnoozeUntil =
Date.now() + MIGRATION_SNOOZE_MS;
await this.plugin.saveSettings();
new Notice(t("LIBRARY_MIGRATION_FAILED"), 8000);
}
return;
}
this.plugin.settings.libraryStorageMode = "data-json";
this.plugin.settings.libraryMigrationStatus =
result.choice === "later" ? "later" : "opted-out";
this.plugin.settings.libraryMigrationSnoozeUntil =
result.choice === "later" ? Date.now() + MIGRATION_SNOOZE_MS : 0;
await this.plugin.saveSettings();
this.invalidate();
}
private async migrateLegacyLibrary(): Promise<void> {
const previousLibrary = this.plugin.settings.library;
const previousLibrary2 = this.plugin.settings.library2;
const previousStorageMode = this.plugin.settings.libraryStorageMode;
const previousMigrationStatus = this.plugin.settings.libraryMigrationStatus;
const previousMigrationSnoozeUntil =
this.plugin.settings.libraryMigrationSnoozeUntil;
const legacyItems = restoreLibraryItems(
getLibraryItems(this.plugin.getLegacyStencilLibrary()),
"unpublished",
);
const path = this.getLocalLibraryPath();
const existing = await this.readLibraryFile(path);
const existingItems = restoreLibraryItems(
getLibraryItems(existing),
"unpublished",
);
const merged = this.mergeById(existingItems, legacyItems);
await this.persistLibraryFile(path, this.createFileData(merged));
const verified = await this.readLibraryFile(path);
const verifiedIds = new Set(
restoreLibraryItems(getLibraryItems(verified), "unpublished").map(
(item) => item.id,
),
);
if (legacyItems.some((item) => !verifiedIds.has(item.id))) {
throw new Error("Not all legacy library items were written");
}
this.plugin.settings.libraryStorageMode = "vault";
this.plugin.settings.libraryMigrationStatus = "completed";
this.plugin.settings.libraryMigrationSnoozeUntil = 0;
await this.plugin.setLegacyStencilLibrary(this.createFileData([]), false);
try {
await this.plugin.saveSettings();
} catch (error) {
// The verified vault file remains as a safe recovery copy, while the
// in-memory settings are restored so a retry cannot clear data.json.
this.plugin.settings.library = previousLibrary;
this.plugin.settings.library2 = previousLibrary2;
this.plugin.settings.libraryStorageMode = previousStorageMode;
this.plugin.settings.libraryMigrationStatus = previousMigrationStatus;
this.plugin.settings.libraryMigrationSnoozeUntil =
previousMigrationSnoozeUntil;
throw error;
}
await this.reloadLibrariesInOpenViews();
}
private scheduleOpenViewReload(): void {
if (this.reloadTimer !== null) {
window.clearTimeout(this.reloadTimer);
}
this.reloadTimer = window.setTimeout(() => {
this.reloadTimer = null;
void this.reloadLibrariesInOpenViews().catch((error) =>
console.error("Could not reload stencil libraries", error),
);
}, LIBRARY_RELOAD_DEBOUNCE_MS);
}
private async getVaultLibrary(): Promise<LibraryItems> {
const previousMode = this.plugin.settings.libraryStorageMode;
this.plugin.settings.libraryStorageMode = "vault";
this.invalidate();
try {
return await this.getLibrary();
} finally {
this.plugin.settings.libraryStorageMode = previousMode;
}
}
/** Coalesces concurrent view initialization into one vault-library load. */
private async ensureLoaded(): Promise<void> {
while (!this.loaded) {
if (this.loadPromise === null) {
const revision = this.loadRevision;
this.loadPromise = this.loadFromVault().then(
({ itemSource, items }) => {
if (revision !== this.loadRevision) {
return;
}
this.itemSource = itemSource;
this.currentItems = items;
this.loaded = true;
},
);
}
const activeLoad: Promise<void> = this.loadPromise;
try {
await activeLoad;
} finally {
if (this.loadPromise === activeLoad) {
this.loadPromise = null;
}
}
}
}
/** Reads a coherent library snapshot without mutating the active cache. */
private async loadFromVault(): Promise<{
itemSource: Map<LibraryItem["id"], string>;
items: LibraryItems;
}> {
const itemSource = new Map<LibraryItem["id"], string>();
const folderPath = this.getFolderPath();
const localPath = this.getLocalLibraryPath();
const files = this.plugin.app.vault
.getFiles()
.filter(
(file) =>
file.parent?.path === folderPath &&
file.extension.toLowerCase() === LIBRARY_EXTENSION,
)
.sort((a, b) => {
if (a.path === localPath) return -1;
if (b.path === localPath) return 1;
return a.path.localeCompare(b.path);
});
const combined: LibraryItem[] = [];
for (const file of files) {
const data = await this.readLibraryFile(file.path);
if (!data) {
continue;
}
const isLocalFile = file.path === localPath;
const items = restoreLibraryItems(
getLibraryItems(data),
isLocalFile ? "unpublished" : "published",
);
for (const item of items) {
if (itemSource.has(item.id)) {
console.warn(
`Duplicate stencil library item id '${item.id}' in ${file.path}; keeping the first occurrence.`,
);
continue;
}
itemSource.set(item.id, file.path);
combined.push(
isLocalFile ? item : { ...item, status: "published" as const },
);
}
}
return { itemSource, items: combined };
}
private async persistChanges(nextItems: LibraryItems): Promise<void> {
if (!this.loaded) {
await this.ensureLoaded();
}
const previousById = new Map(
this.currentItems.map((item) => [item.id, item]),
);
const nextById = new Map(nextItems.map((item) => [item.id, item]));
const affectedPaths = new Set<string>();
const additions: LibraryItem[] = [];
for (const item of this.currentItems) {
const next = nextById.get(item.id);
if (!next || JSON.stringify(next, null, 2) !== JSON.stringify(item, null, 2)) {
affectedPaths.add(
this.itemSource.get(item.id) ?? this.getLocalLibraryPath(),
);
}
}
for (const item of nextItems) {
if (!previousById.has(item.id)) {
additions.push(item);
affectedPaths.add(this.getLocalLibraryPath());
}
}
for (const path of affectedPaths) {
const existingData =
(await this.readLibraryFile(path)) ?? this.createFileData([]);
const existingItems = restoreLibraryItems(
getLibraryItems(existingData),
path === this.getLocalLibraryPath() ? "unpublished" : "published",
);
const updated: LibraryItem[] = [];
for (const diskItem of existingItems) {
if (this.itemSource.get(diskItem.id) !== path) {
updated.push(diskItem);
continue;
}
const next = nextById.get(diskItem.id);
if (next) {
updated.push(this.withFileStatus(next, path));
}
}
if (path === this.getLocalLibraryPath()) {
for (const item of additions) {
if (!updated.some((candidate) => candidate.id === item.id)) {
updated.unshift(this.withFileStatus(item, path));
this.itemSource.set(item.id, path);
}
}
}
const nextData: StencilLibraryFileData = {
...existingData,
type: "excalidrawlib",
version: 2,
libraryItems: updated,
};
if (JSON.stringify(existingData, null, 2) !== JSON.stringify(nextData, null, 2)) {
await this.persistLibraryFile(path, nextData);
}
}
const nextItemSource = new Map<LibraryItem["id"], string>();
this.currentItems = nextItems.map((item) => {
const path = this.itemSource.get(item.id) ?? this.getLocalLibraryPath();
nextItemSource.set(item.id, path);
return this.withFileStatus(item, path);
});
this.itemSource = nextItemSource;
}
private withFileStatus(item: LibraryItem, path: string): LibraryItem {
return path === this.getLocalLibraryPath()
? item
: { ...item, status: "published" };
}
private mergeById(
preferred: LibraryItems,
additional: LibraryItems,
): LibraryItems {
const seen = new Set(preferred.map((item) => item.id));
return [...preferred, ...additional.filter((item) => !seen.has(item.id))];
}
private createFileData(items: LibraryItems): StencilLibraryFileData {
return {
type: "excalidrawlib",
version: 2,
source: `${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_RELEASES_TAG}/${PLUGIN_VERSION}`,
libraryItems: items,
};
}
private getFolderPath(): string {
return normalizePath(
this.plugin.settings.libraryFolderPath.trim() ||
`${this.plugin.settings.folder}/Libraries`,
);
}
private getLocalLibraryPath(): string {
return normalizePath(
`${this.getFolderPath()}/${normalizeLibraryFileName(
this.plugin.settings.libraryFileName,
)}.${LIBRARY_EXTENSION}`,
);
}
private async ensureFolder(): Promise<TFolder> {
const path = this.getFolderPath();
const folder = this.plugin.app.vault.getFolderByPath(path);
if (folder) {
return folder;
}
if (this.plugin.app.vault.getFileByPath(path)) {
throw new Error(`Library folder path is a file: ${path}`);
}
return this.plugin.app.vault.createFolder(path);
}
private async readLibraryFile(
path: string,
): Promise<StencilLibraryData | null> {
const file = this.plugin.app.vault.getFileByPath(path);
if (!file) {
return null;
}
try {
return JSON.parse(
await this.plugin.app.vault.read(file),
) as StencilLibraryData;
} catch (error) {
console.error(`Could not read stencil library ${path}`, error);
new Notice(t("LIBRARY_FILE_READ_ERROR").replace("{PATH}", path), 8000);
return null;
}
}
/** Writes a non-empty library or removes its file when no items remain. */
private async persistLibraryFile(
path: string,
data: StencilLibraryFileData,
): Promise<void> {
const existing = this.plugin.app.vault.getFileByPath(path);
if (data.libraryItems.length === 0 && !existing) {
return;
}
this.ownWritePaths.add(path);
try {
if (data.libraryItems.length === 0) {
await this.plugin.app.fileManager.trashFile(existing);
return;
}
await this.ensureFolder();
const content = JSON.stringify(data, null, 2);
if (existing) {
await this.plugin.app.vault.modify(existing, content);
return;
}
if (this.plugin.app.vault.getFolderByPath(path)) {
throw new Error(`Library file path is a folder: ${path}`);
}
await this.plugin.app.vault.create(path, content);
} finally {
window.setTimeout(
() => this.ownWritePaths.delete(path),
OWN_WRITE_EVENT_WINDOW_MS,
);
}
}
}
+27 -14
View File
@@ -1,9 +1,10 @@
import { WorkspaceWindow } from "obsidian";
import ExcalidrawPlugin from "src/core/main";
import type ExcalidrawPlugin from "src/core/main";
import { getAllWindowDocuments } from "../../utils/obsidianUtils";
import { setStyleText } from "src/utils/htmlUtils";
declare const mainDocument: Document;
declare const deliberateCreateElement: (doc: Document, tagName: string) => HTMLStyleElement;
export let REM_VALUE = 16;
const STYLE_VARIABLES = [
@@ -68,10 +69,20 @@ export class StylesManager {
}
private async onCSSChange() {
await this.harvestStyles();
getAllWindowDocuments(this.plugin.app).forEach((doc) => {
this.copyPropertiesToTheme(doc);
});
const harvest = async () => {
await this.harvestStyles();
getAllWindowDocuments(this.plugin.app).forEach((doc) => {
this.copyPropertiesToTheme(doc);
});
};
if (!this.plugin.app.workspace.layoutReady) {
this.plugin.app.workspace.onLayoutReady(async () => {
await harvest();
});
return;
}
await harvest();
}
private onWindowOpen(win: WorkspaceWindow) {
@@ -102,9 +113,8 @@ export class StylesManager {
}
const body = mainDocument.body;
const iframe: HTMLIFrameElement = mainDocument.createElement("iframe");
const iframe: HTMLIFrameElement = mainDocument.body.createEl("iframe");
iframe.hidden = true;
body.appendChild(iframe);
const iframeLoadedPromise = new Promise<void>((resolve) => {
iframe.addEventListener("load", () => resolve());
@@ -115,11 +125,12 @@ export class StylesManager {
iframeDoc.open();
iframeDoc.close(); // Closes the stream to clear out the default page skeleton
const newHead = iframeDoc.createElement("head");
const targetHead = iframeDoc.head;
// Obsidian's DOM helpers are not installed on elements from the iframe realm.
targetHead.replaceChildren();
Array.from(mainDocument.head.children).forEach((child) => {
newHead.appendChild(child.cloneNode(true));
targetHead.appendChild(child.cloneNode(true));
});
iframeDoc.documentElement.replaceChild(newHead, iframeDoc.head);
await iframeLoadedPromise;
@@ -142,8 +153,10 @@ export class StylesManager {
const cm = this.plugin.ea.getCM(
computedStyles.getPropertyValue("--background-primary"),
);
cm.alphaTo(0.9);
allVariables["--background-primary"] = cm.stringHEX();
if(cm) {
cm.alphaTo(0.9);
allVariables["--background-primary"] = cm.stringHEX();
}
return Object.entries(allVariables)
.map(([key, value]) => `${key}: ${value} !important;`)
.join(" ");
@@ -168,7 +181,7 @@ export class StylesManager {
`.${EXCALIDRAW_CONTAINER_CLASS} .theme-dark {\n${this.styleDark}\n}`,
);
} else {
const lightStyleTag = doc.createElement("style");
const lightStyleTag = deliberateCreateElement(doc, "style");
lightStyleTag.setAttribute("id", "excalidraw-embedded-light");
setStyleText(
lightStyleTag,
@@ -176,7 +189,7 @@ export class StylesManager {
);
doc.head.appendChild(lightStyleTag);
const darkStyleTag = doc.createElement("style");
const darkStyleTag = deliberateCreateElement(doc, "style");
darkStyleTag.setAttribute("id", "excalidraw-embedded-dark");
setStyleText(
darkStyleTag,
@@ -0,0 +1,186 @@
import type {
AppState,
BinaryFiles,
} from "@zsviczian/excalidraw/types/excalidraw/types";
import type { ExcalidrawElement } from "@zsviczian/excalidraw/types/element/src/types";
import type { ExcalidrawDataMigrationState } from "../../shared/ExcalidrawData";
import type { TextMode } from "../../shared/TextMode";
import type { ViewSaveMigrationState } from "../../view/managers/ViewSaveCoordinator";
const DEFAULT_HANDOFF_TTL_MS = 15_000;
/** Drawing-owned runtime state that may cross an Obsidian window migration. */
export interface ViewMigrationDrawingState {
elements: readonly ExcalidrawElement[];
appState: AppState;
files: BinaryFiles;
textMode: TextMode;
compatibilityMode: boolean;
excalidrawData: ExcalidrawDataMigrationState;
save: ViewSaveMigrationState;
}
/** Metadata used to register one transient migration handoff. */
export interface ViewMigrationHandoffRegistration {
leafId: string;
filePath: string;
fileMtime: number;
drawing: ViewMigrationDrawingState;
}
/** Identity and freshness checks required to consume a migration handoff. */
export interface ViewMigrationHandoffRequest {
token: string;
leafId: string;
filePath: string;
fileMtime: number;
}
interface ViewMigrationHandoffEntry extends ViewMigrationHandoffRegistration {
token: string;
expiresAt: number;
}
interface ViewMigrationHandoffScheduler {
now: () => number;
setTimeout: (callback: () => void, delay: number) => number;
clearTimeout: (timer: number) => void;
}
interface ViewMigrationHandoffManagerOptions {
ttlMs?: number;
scheduler?: ViewMigrationHandoffScheduler;
}
/**
* Owns bounded, one-shot drawing handoffs between recreated views.
*
* Entries contain drawing state only. They never retain an `ExcalidrawView`,
* React root, DOM node, `Window`, listener, or package lease. Consumption
* removes the entry before validation so stale or mismatched state cannot be
* retried, and a single expiry timer bounds abandoned payload lifetime.
*/
export class ViewMigrationHandoffManager {
private readonly ttlMs: number;
private readonly scheduler: ViewMigrationHandoffScheduler;
private readonly entries = new Map<string, ViewMigrationHandoffEntry>();
private readonly tokensByLeaf = new Map<string, string>();
private cleanupTimer: number | null = null;
private tokenSequence = 0;
public constructor(options: ViewMigrationHandoffManagerOptions = {}) {
this.ttlMs = options.ttlMs ?? DEFAULT_HANDOFF_TTL_MS;
if (!Number.isFinite(this.ttlMs) || this.ttlMs <= 0) {
throw new Error("View migration handoff TTL must be positive");
}
this.scheduler =
options.scheduler ??
{
now: () => Date.now(),
setTimeout: (callback, delay) => window.setTimeout(callback, delay),
clearTimeout: (timer) => window.clearTimeout(timer),
};
}
/** Registers a handoff, replacing any older payload for the same leaf. */
public register(registration: ViewMigrationHandoffRegistration): string {
this.pruneExpired();
const previousToken = this.tokensByLeaf.get(registration.leafId);
if (previousToken) {
this.deleteEntry(previousToken);
}
const now = this.scheduler.now();
const token = `view-migration-${now.toString(36)}-${(++this.tokenSequence).toString(36)}`;
this.entries.set(token, {
...registration,
token,
expiresAt: now + this.ttlMs,
});
this.tokensByLeaf.set(registration.leafId, token);
this.scheduleCleanup();
return token;
}
/**
* Consumes a matching handoff exactly once.
*
* A token mismatch, leaf/path mismatch, file modification, or TTL expiry
* returns `null` and discards the candidate so the caller must use its
* ordinary disk-backed load path.
*/
public consume(
request: ViewMigrationHandoffRequest,
): ViewMigrationDrawingState | null {
this.pruneExpired();
const entry = this.entries.get(request.token);
if (!entry) {
return null;
}
this.deleteEntry(request.token);
this.scheduleCleanup();
if (
entry.leafId !== request.leafId ||
entry.filePath !== request.filePath ||
entry.fileMtime !== request.fileMtime
) {
return null;
}
return entry.drawing;
}
/** Drops all retained drawing state and cancels expiry work. */
public destroy(): void {
if (this.cleanupTimer !== null) {
this.scheduler.clearTimeout(this.cleanupTimer);
this.cleanupTimer = null;
}
this.entries.clear();
this.tokensByLeaf.clear();
}
private deleteEntry(token: string): void {
const entry = this.entries.get(token);
if (!entry) {
return;
}
this.entries.delete(token);
if (this.tokensByLeaf.get(entry.leafId) === token) {
this.tokensByLeaf.delete(entry.leafId);
}
}
private pruneExpired(): void {
const now = this.scheduler.now();
for (const [token, entry] of this.entries) {
if (entry.expiresAt <= now) {
this.deleteEntry(token);
}
}
if (this.entries.size === 0 && this.cleanupTimer !== null) {
this.scheduler.clearTimeout(this.cleanupTimer);
this.cleanupTimer = null;
}
}
private scheduleCleanup(): void {
if (this.cleanupTimer !== null) {
this.scheduler.clearTimeout(this.cleanupTimer);
this.cleanupTimer = null;
}
if (this.entries.size === 0) {
return;
}
let nextExpiry = Number.POSITIVE_INFINITY;
for (const entry of this.entries.values()) {
nextExpiry = Math.min(nextExpiry, entry.expiresAt);
}
this.cleanupTimer = this.scheduler.setTimeout(() => {
this.cleanupTimer = null;
this.pruneExpired();
this.scheduleCleanup();
}, Math.max(0, nextExpiry - this.scheduler.now()));
}
}
@@ -0,0 +1,95 @@
const DEFAULT_HANDOFF_TTL_MS = 15_000;
export interface ViewMigrationPersistenceHandoff {
leafId: string;
filePath: string;
data: string;
}
interface ViewMigrationPersistenceHandoffEntry extends ViewMigrationPersistenceHandoff {
expiresAt: number;
}
/**
* Owns bounded serialized drawing handoffs from a destroyed popout view to
* the replacement view in Obsidian's main window.
*
* Entries contain drawing text and stable identifiers only. They never retain
* a view, DOM node, React runtime, package lease, or Window. Consumption is
* one-shot, and abandoned entries expire promptly.
*/
export class ViewMigrationPersistenceHandoffManager {
private readonly entries = new Map<
string,
ViewMigrationPersistenceHandoffEntry
>();
private cleanupTimer: number | null = null;
/** Registers or replaces the pending drawing text for one workspace leaf. */
public register(handoff: ViewMigrationPersistenceHandoff): void {
this.pruneExpired();
this.entries.set(handoff.leafId, {
...handoff,
expiresAt: Date.now() + DEFAULT_HANDOFF_TTL_MS,
});
this.scheduleCleanup();
}
/** Consumes matching drawing text exactly once. */
public consume(leafId: string, filePath: string): string | null {
this.pruneExpired();
const entry = this.entries.get(leafId);
if (!entry) {
return null;
}
this.entries.delete(leafId);
this.scheduleCleanup();
return entry.filePath === filePath ? entry.data : null;
}
/** Discards an abandoned handoff after a failed view replacement. */
public discard(leafId: string): void {
this.entries.delete(leafId);
this.scheduleCleanup();
}
/** Clears retained text and its main-window cleanup timer. */
public destroy(): void {
if (this.cleanupTimer !== null) {
window.clearTimeout(this.cleanupTimer);
this.cleanupTimer = null;
}
this.entries.clear();
}
private pruneExpired(): void {
const now = Date.now();
for (const [leafId, entry] of this.entries) {
if (entry.expiresAt <= now) {
this.entries.delete(leafId);
}
}
}
private scheduleCleanup(): void {
if (this.cleanupTimer !== null) {
window.clearTimeout(this.cleanupTimer);
this.cleanupTimer = null;
}
if (this.entries.size === 0) {
return;
}
let nextExpiry = Number.POSITIVE_INFINITY;
for (const entry of this.entries.values()) {
nextExpiry = Math.min(nextExpiry, entry.expiresAt);
}
this.cleanupTimer = window.setTimeout(
() => {
this.cleanupTimer = null;
this.pruneExpired();
this.scheduleCleanup();
},
Math.max(0, nextExpiry - Date.now()),
);
}
}
@@ -0,0 +1,41 @@
import type ExcalidrawPlugin from "src/core/main";
import { ExcalidrawLib } from "../../types/excalidrawLib";
const DEFAULT_AREA_LIMIT = 16_777_216;
const DEFAULT_WIDTH_HEIGHT_LIMIT = 32_767;
/**
* Creates the narrow, window-runtime host adapter consumed by the Excalidraw
* fork's common and element packages.
*
* @remarks
* Capability methods read current plugin state rather than capturing settings
* values. The package manager owns both this adapter and its disposer, so the
* adapter cannot outlive the corresponding evaluated Excalidraw runtime.
*/
export const createObsidianCommonHostAdapter = (
plugin: ExcalidrawPlugin,
protocolVersion: typeof ExcalidrawLib.OBSIDIAN_COMMON_HOST_PROTOCOL_VERSION,
): ExcalidrawLib.ObsidianCommonHostAdapter => ({
protocolVersion,
getDeviceInfo: () => plugin.getObsidianDevice(),
getDesktopUIMode: () => plugin.getPreferredUIMode(),
getPreferredUIMode: (formFactor) => {
if (formFactor === "phone") {
return plugin.settings.phoneUIMode;
}
if (formFactor === "tablet") {
return plugin.settings.tabletUIMode;
}
return plugin.settings.desktopUIMode;
},
getCanvasLimits: () => ({
areaLimit: plugin.excalidrawConfig?.areaLimit ?? DEFAULT_AREA_LIMIT,
widthHeightLimit:
plugin.excalidrawConfig?.widthHeightLimit ?? DEFAULT_WIDTH_HEIGHT_LIMIT,
}),
getHighlightColor: (sceneBackgroundColor, opacity) =>
plugin.getHighlightColor(sceneBackgroundColor, opacity),
});
@@ -0,0 +1,48 @@
import type ExcalidrawPlugin from "src/core/main";
import { ExcalidrawLib } from "../../types/excalidrawLib";
/**
* Creates the plugin-wide capability adapter consumed by the evaluated
* Excalidraw package runtime.
*
* @remarks
* Settings methods read current values rather than capturing a stale snapshot.
* The adapter exposes only semantic operations and never the plugin instance,
* settings object, or active-view state.
*/
export const createObsidianExcalidrawHostAdapter = (
plugin: ExcalidrawPlugin,
protocolVersion: typeof ExcalidrawLib.OBSIDIAN_EXCALIDRAW_HOST_PROTOCOL_VERSION,
): ExcalidrawLib.ObsidianExcalidrawHostAdapter => ({
protocolVersion,
isDoubleTapEraserEnabled: () => plugin.settings.penModeDoubleTapEraser,
isRightClickPanEnabled: () => plugin.settings.panWithRightMouseButton,
getZoomToFitMaxLevel: () => plugin.settings.zoomToFitMaxLevel,
isPenModeCrosshairVisible: () => plugin.settings.penModeCrosshairVisible,
isSingleFingerPanningEnabled: () =>
plugin.settings.penModeSingleFingerPanning,
isDoubleClickTextEditingDisabled: () =>
plugin.settings.disableDoubleClickTextEditing,
getZoomStep: () => plugin.settings.zoomStep,
getZoomMin: () => plugin.settings.zoomMin,
getZoomMax: () => plugin.settings.zoomMax,
isContextMenuDisabled: () => plugin.settings.disableContextMenu,
shouldSyncElementLinkWithText: () => plugin.settings.syncElementLinkWithText,
loadFontFromFile: (filename) => plugin.loadFontFromFile(filename),
getMermaid: () => plugin.getMermaid(),
runAction: (action) => plugin.runAction(action),
getLabel: (key) =>
plugin.getLabel(key as Parameters<ExcalidrawPlugin["getLabel"]>[0]),
attachInlineLinkSuggester: (
inputEl,
widthWrapper,
container,
suppressPlaceholder,
) =>
plugin.attachInlineLinkSuggester(
inputEl,
widthWrapper,
container ?? undefined,
suppressPlaceholder,
),
});
+4550 -3868
View File
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,149 @@
/**
* Obsidian 1.13 declarative adapter for canonical setting specifications.
*/
import type { SettingBindingRegistry } from "src/core/settings/SettingBindingRegistry";
import type { LegacySettingsAdapter } from "src/core/settings/LegacySettingsAdapter";
import type {
SettingBindingKey,
SettingSpec,
} from "src/core/settings/settingSpecs";
import type {
SettingDefinition,
} from "src/types/obsidianDeclarativeSettings";
import { annotateMarkdownDefinition } from "src/core/settings/declarativeSettingsMarkdown";
/** Converts canonical setting rows into Obsidian 1.13 definitions. */
export class DeclarativeSettingsAdapter {
private readonly bindings: SettingBindingRegistry;
private readonly legacyAdapter: LegacySettingsAdapter;
private registerBindings = true;
constructor(
bindings: SettingBindingRegistry,
legacyAdapter: LegacySettingsAdapter,
) {
this.bindings = bindings;
this.legacyAdapter = legacyAdapter;
}
/** Starts a definition build, optionally replacing the live control bindings. */
beginBuild(registerBindings: boolean = true): void {
this.registerBindings = registerBindings;
if (registerBindings) {
this.bindings.clear();
}
}
/** Converts one canonical row during the current definition build. */
toDefinition(spec: SettingSpec): SettingDefinition<SettingBindingKey> {
if (this.requiresCustomRender(spec)) {
return this.toRenderedDefinition(spec);
}
if (this.registerBindings) {
this.bindings.register(spec);
}
const base = {
name: this.toSearchText(spec.name),
desc: spec.desc,
aliases: spec.aliases,
searchable: spec.searchable,
visible: spec.visible,
};
const control = spec.control;
switch (control.type) {
case "toggle":
return {
...base,
control: {
type: "toggle",
key: control.key,
disabled: control.disabled,
},
};
case "text":
return {
...base,
control: {
type: "text",
key: control.key,
placeholder: control.placeholder,
disabled: control.disabled,
},
};
case "dropdown":
return {
...base,
control: {
type: "dropdown",
key: control.key,
options: Object.fromEntries(
control.options.map(({ value, label }) => [value, label]),
),
disabled: control.disabled,
},
};
case "number-dropdown":
return {
...base,
control: {
type: "dropdown",
key: control.key,
options: Object.fromEntries(
control.options.map(({ value, label }) => [
value.toString(),
label,
]),
),
disabled: control.disabled,
},
};
case "slider":
return {
...base,
control: {
type: "slider",
key: control.key,
min: control.min,
max: control.max,
step: control.step,
disabled: control.disabled,
},
};
}
}
private requiresCustomRender(spec: SettingSpec): boolean {
if (typeof spec.name !== "string") {
return true;
}
const control = spec.control;
return (
(control.type === "text" &&
Boolean(control.capture || control.sanitize || control.vaultPath)) ||
(control.type === "slider" && control.minWidth !== undefined)
);
}
private toRenderedDefinition(
spec: SettingSpec,
): SettingDefinition<SettingBindingKey> {
return annotateMarkdownDefinition(
{
name: this.toSearchText(spec.name),
desc:
spec.desc === undefined ? undefined : this.toSearchText(spec.desc),
aliases: spec.aliases,
searchable: spec.searchable,
visible: spec.visible,
render: (setting) => this.legacyAdapter.configure(setting, spec),
},
{ controlType: spec.control.type },
);
}
private toSearchText(value: string | DocumentFragment): string {
return typeof value === "string" ? value : (value.textContent ?? "");
}
}
+138
View File
@@ -0,0 +1,138 @@
/**
* Imperative renderer for canonical setting-row specifications.
*/
import { Setting, type TextComponent } from "obsidian";
import type { SettingBindingRegistry } from "src/core/settings/SettingBindingRegistry";
import type {
SettingSpec,
TextControl,
} from "src/core/settings/settingSpecs";
import { configureSliderWithText } from "src/utils/sliderUtils";
/** Legacy-only services used by custom text controls. */
export interface LegacySettingsAdapterHost {
addVaultPathSupport(
setting: Setting,
text: TextComponent,
kind: "file" | "folder",
options: NonNullable<TextControl["vaultPath"]>["options"],
): void;
}
/** Builds or configures imperative Obsidian setting rows from canonical specs. */
export class LegacySettingsAdapter {
constructor(
private readonly bindings: SettingBindingRegistry,
private readonly host: LegacySettingsAdapterHost,
) {}
/**
* Creates one legacy row. Slider return behavior remains `undefined` for
* compatibility with the former in-class interpreter.
*/
render(container: HTMLElement, spec: SettingSpec): Setting | undefined {
const visible =
typeof spec.visible === "function"
? spec.visible()
: (spec.visible ?? true);
if (!visible) {
return undefined;
}
const setting = new Setting(container);
this.configure(setting, spec);
return spec.control.type === "slider" ? undefined : setting;
}
/** Configures a row supplied by either the legacy or declarative host. */
configure(setting: Setting, spec: SettingSpec): void {
const control = spec.control;
const disabled =
typeof control.disabled === "function"
? control.disabled()
: (control.disabled ?? false);
if (control.type === "slider") {
configureSliderWithText(setting, {
name: spec.name,
desc: spec.desc,
value: this.bindings.getSpecValue(spec) as number,
min: control.min,
max: control.max,
step: control.step,
minWidth: control.minWidth,
onChange: (value) => this.bindings.setLegacySpecValue(spec, value),
});
setting.setDisabled(disabled);
return;
}
setting.setName(spec.name);
if (spec.desc) {
setting.setDesc(spec.desc);
}
switch (control.type) {
case "toggle":
setting.addToggle((toggle) =>
toggle
.setValue(this.bindings.getSpecValue(spec) as boolean)
.onChange((value) =>
this.bindings.setLegacySpecValue(spec, value),
),
);
break;
case "text":
setting.addText((text) => {
control.capture?.(text);
if (control.placeholder !== undefined) {
text.setPlaceholder(control.placeholder);
}
text
.setValue(this.bindings.getSpecValue(spec) as string)
.onChange((value) =>
this.bindings.setLegacySpecValue(spec, value, () => {
if (control.sanitize) {
text.setValue(this.bindings.getSpecValue(spec) as string);
}
}),
);
if (control.vaultPath) {
this.host.addVaultPathSupport(
setting,
text,
control.vaultPath.kind,
control.vaultPath.options,
);
}
});
break;
case "dropdown":
setting.addDropdown((dropdown) => {
for (const option of control.options) {
dropdown.addOption(option.value, option.label);
}
dropdown
.setValue(this.bindings.getSpecValue(spec) as string)
.onChange((value) =>
this.bindings.setLegacySpecValue(spec, value),
);
});
break;
case "number-dropdown":
setting.addDropdown((dropdown) => {
for (const option of control.options) {
dropdown.addOption(option.value.toString(), option.label);
}
dropdown
.setValue(this.bindings.getSpecValue(spec) as string)
.onChange((value) =>
this.bindings.setLegacySpecValue(spec, value),
);
});
}
// Setting#setDisabled only affects controls that already exist. Apply the
// initial predicate after configuring the row so dependent controls start
// in the same state in both legacy and declarative render paths.
setting.setDisabled(disabled);
}
}
@@ -0,0 +1,42 @@
/**
* Serialized stable-snapshot writer for plugin settings.
*/
/** Persistence operation required by the serialized settings writer. */
export interface SerializedSettingsWriterHost<Snapshot> {
saveData(data: Snapshot): Promise<void>;
}
/**
* Serializes complete settings writes so an older save cannot finish after a
* newer one. Each request captures an immutable JSON snapshot before waiting
* for an earlier write.
*/
export class SerializedSettingsWriter<
Snapshot extends Record<string, unknown>,
> {
private persistenceChain: Promise<void> = Promise.resolve();
public constructor(
private readonly host: SerializedSettingsWriterHost<Snapshot>,
) {}
/** Queues one stable snapshot and resolves when that snapshot is saved. */
public persist(settings: Snapshot): Promise<void> {
let snapshot: Snapshot;
try {
snapshot = JSON.parse(JSON.stringify(settings)) as Snapshot;
} catch (error) {
return Promise.reject(
error instanceof Error
? error
: new Error("Could not serialize settings snapshot"),
);
}
const persistence = this.persistenceChain
.catch((): void => undefined)
.then(() => this.host.saveData(snapshot));
this.persistenceChain = persistence;
return persistence;
}
}
+240
View File
@@ -0,0 +1,240 @@
/**
* Typed value and persistence bridge for canonical setting specifications.
*/
import type { ExcalidrawSettings } from "src/core/settingsDefaults";
import type {
SettingBindingKey,
SettingControlSpec,
SettingSpec,
} from "src/core/settings/settingSpecs";
/** Services required to persist a canonical setting mutation. */
export interface SettingBindingHost {
getSettings(): ExcalidrawSettings;
queueSettingsUpdate(requestReloadDrawings: boolean): Promise<void>;
}
/**
* Resolves declarative control keys and applies the same transformations,
* hooks, save queue, and pending actions as the legacy controls.
*/
export class SettingBindingRegistry {
private readonly bindings = new Map<SettingBindingKey, SettingSpec>();
private readonly host: SettingBindingHost;
constructor(host: SettingBindingHost) {
this.host = host;
}
/** Clears bindings before a fresh declarative definition build. */
clear(): void {
this.bindings.clear();
}
/** Registers one native declarative control binding for the current build. */
register(spec: SettingSpec): void {
const { key } = spec.control;
if (this.bindings.has(key)) {
throw new Error(`Duplicate declarative setting binding: ${key}`);
}
this.bindings.set(key, spec);
}
/** Reads a registered declarative control value. */
getControlValue(key: string): unknown {
return this.getSpecValue(this.getBinding(key));
}
/** Writes a registered declarative control value and awaits persistence. */
setControlValue(key: string, value: unknown): Promise<void> {
return this.setSpecValue(this.getBinding(key), value);
}
/** Reads the UI-facing value for either adapter. */
getSpecValue(spec: SettingSpec): boolean | string | number {
const settings = this.host.getSettings();
const control = spec.control;
switch (control.type) {
case "toggle": {
const storedValue = settings[control.key];
return control.negate ? !storedValue : storedValue;
}
case "number-dropdown":
return settings[control.key].toString();
case "slider":
return settings[control.key] * (control.scale ?? 1);
default:
return settings[control.key];
}
}
/** Applies a UI-facing value from either adapter. */
setSpecValue(
spec: SettingSpec,
value: unknown,
afterWrite?: () => void,
): Promise<void> {
return this.setSpecValueInternal(spec, value, afterWrite, true);
}
/**
* Applies a legacy UI value without extending the component callback until
* queued disk persistence completes.
*/
setLegacySpecValue(
spec: SettingSpec,
value: unknown,
afterWrite?: () => void,
): Promise<void> {
return this.setSpecValueInternal(spec, value, afterWrite, false);
}
private async setSpecValueInternal(
spec: SettingSpec,
value: unknown,
afterWrite: (() => void) | undefined,
awaitPersistence: boolean,
): Promise<void> {
const control = spec.control;
switch (control.type) {
case "toggle": {
const nextValue = this.requireBoolean(control, value);
await control.before?.(nextValue);
this.setSettingValue(control.key, control.negate ? !nextValue : nextValue);
afterWrite?.();
await control.after?.(nextValue);
await this.persistAndRunAfterUpdate(
control,
nextValue,
awaitPersistence,
);
return;
}
case "text": {
const nextValue = this.requireString(control, value);
await control.before?.(nextValue);
this.setSettingValue(
control.key,
control.sanitize?.(nextValue) ?? nextValue,
);
afterWrite?.();
await control.after?.(nextValue);
await this.persistAndRunAfterUpdate(
control,
nextValue,
awaitPersistence,
);
return;
}
case "dropdown": {
const nextValue = this.requireString(control, value);
await control.before?.(nextValue);
this.setSettingValue(control.key, nextValue);
afterWrite?.();
await control.after?.(nextValue);
await this.persistAndRunAfterUpdate(
control,
nextValue,
awaitPersistence,
);
return;
}
case "number-dropdown": {
const rawValue = this.requireString(control, value);
const nextValue =
control.parse === "int" ? parseInt(rawValue) : parseFloat(rawValue);
await control.before?.(nextValue);
this.setSettingValue(control.key, nextValue);
afterWrite?.();
await control.after?.(nextValue);
await this.persistAndRunAfterUpdate(
control,
nextValue,
awaitPersistence,
);
return;
}
case "slider": {
const displayValue = this.requireNumber(control, value);
await control.before?.(displayValue);
this.setSettingValue(
control.key,
displayValue / (control.scale ?? 1),
);
afterWrite?.();
await control.after?.(displayValue);
await this.persistAndRunAfterUpdate(
control,
displayValue,
awaitPersistence,
);
}
}
}
private getBinding(key: string): SettingSpec {
const binding = this.bindings.get(key as SettingBindingKey);
if (!binding) {
throw new Error(`Unknown declarative setting binding: ${key}`);
}
return binding;
}
private setSettingValue<K extends keyof ExcalidrawSettings>(
key: K,
value: ExcalidrawSettings[K],
): void {
this.host.getSettings()[key] = value;
}
private async persistAndRunAfterUpdate<Value>(
control: SettingControlSpec & {
afterUpdate?: (value: Value) => void | Promise<void>;
},
value: Value,
awaitPersistence: boolean,
): Promise<void> {
const persistence = this.host.queueSettingsUpdate(control.reload ?? false);
if (awaitPersistence) {
try {
await control.afterUpdate?.(value);
} finally {
await persistence;
}
return;
}
await control.afterUpdate?.(value);
void persistence.catch((): void => undefined);
}
private requireBoolean(control: SettingControlSpec, value: unknown): boolean {
if (typeof value !== "boolean") {
throw this.invalidValueError(control, "boolean");
}
return value;
}
private requireString(control: SettingControlSpec, value: unknown): string {
if (typeof value !== "string") {
throw this.invalidValueError(control, "string");
}
return value;
}
private requireNumber(control: SettingControlSpec, value: unknown): number {
if (typeof value !== "number") {
throw this.invalidValueError(control, "number");
}
return value;
}
private invalidValueError(
control: SettingControlSpec,
expectedType: string,
): TypeError {
return new TypeError(
`Invalid value for setting '${control.key}': expected ${expectedType}`,
);
}
}
@@ -0,0 +1,145 @@
/**
* Coalesces settings mutations so rapid controls do not enqueue one complete
* `data.json` write per input event.
*/
/** Persistence operations owned by the settings tab. */
export interface SettingsPersistenceQueueHost {
/** Persists the latest in-memory settings snapshot. */
persistSettings(): Promise<void>;
/** Applies side effects that must observe a successfully persisted snapshot. */
applyPendingActions(): Promise<void>;
/** Returns true while persistence would replace a control being edited. */
shouldDeferPersistence?(): boolean;
}
interface PersistenceWaiter {
revision: number;
resolve: () => void;
reject: (reason: unknown) => void;
}
/**
* Trailing-edge persistence queue for settings mutations.
*
* Rapid mutations are collapsed into one write. If another mutation arrives
* while that write is in flight, one follow-up write persists the newest
* snapshot before pending actions and callers are released.
*/
export class SettingsPersistenceQueue {
private requestedRevision = 0;
private completedRevision = 0;
private debounceTimer: number | null = null;
private activeRun: Promise<void> | null = null;
private waiters: PersistenceWaiter[] = [];
constructor(
private readonly host: SettingsPersistenceQueueHost,
private readonly debounceMilliseconds: number = 250,
) {}
/**
* Records a mutation and resolves after a persisted snapshot containing it
* has had its pending actions applied.
*/
enqueue(): Promise<void> {
const revision = ++this.requestedRevision;
const persistence = new Promise<void>((resolve, reject) => {
this.waiters.push({ revision, resolve, reject });
});
this.schedule();
return persistence;
}
/** Immediately starts any scheduled persistence and awaits completion. */
flush(): Promise<void> {
this.cancelTimer();
if (this.activeRun !== null) {
return this.activeRun;
}
if (this.completedRevision >= this.requestedRevision) {
return Promise.resolve();
}
return this.startRun();
}
private schedule(): void {
if (this.activeRun !== null) {
return;
}
this.cancelTimer();
this.debounceTimer = window.setTimeout(() => {
this.debounceTimer = null;
if (this.host.shouldDeferPersistence?.()) {
this.schedule();
return;
}
void this.startRun().catch((): void => undefined);
}, this.debounceMilliseconds);
}
private cancelTimer(): void {
if (this.debounceTimer === null) {
return;
}
window.clearTimeout(this.debounceTimer);
this.debounceTimer = null;
}
private startRun(): Promise<void> {
if (this.activeRun !== null) {
return this.activeRun;
}
const run = this.persistLatestRevision();
this.activeRun = run;
void run
.finally(() => {
if (this.activeRun === run) {
this.activeRun = null;
}
})
.catch((): void => undefined);
return run;
}
private async persistLatestRevision(): Promise<void> {
try {
while (this.completedRevision < this.requestedRevision) {
const revisionToPersist = this.requestedRevision;
await this.host.persistSettings();
if (revisionToPersist !== this.requestedRevision) {
continue;
}
await this.host.applyPendingActions();
if (revisionToPersist !== this.requestedRevision) {
continue;
}
this.completedRevision = revisionToPersist;
this.resolveWaitersThrough(revisionToPersist);
}
} catch (error) {
this.rejectWaiters(error);
throw error;
}
}
private resolveWaitersThrough(revision: number): void {
const remaining: PersistenceWaiter[] = [];
for (const waiter of this.waiters) {
if (waiter.revision <= revision) {
waiter.resolve();
} else {
remaining.push(waiter);
}
}
this.waiters = remaining;
}
private rejectWaiters(reason: unknown): void {
const waiters = this.waiters;
this.waiters = [];
for (const waiter of waiters) {
waiter.reject(reason);
}
}
}
+185
View File
@@ -0,0 +1,185 @@
/**
* Device-local, transactional storage for the last known good settings.
*
* The recovery copy deliberately lives outside the vault and Obsidian's
* localStorage. IndexedDB can hold large legacy settings records and replaces
* the single recovery record atomically if a write completes.
*/
const DATABASE_VERSION = 1;
const STORE_NAME = "settingsRecovery";
const RECORD_KEY = "lastKnownGood";
const RECORD_VERSION = 1;
interface SettingsRecoveryRecord<Snapshot> {
version: typeof RECORD_VERSION;
settings: Snapshot;
}
interface SettingsRecoveryStoreOptions {
databaseName: string;
indexedDBFactory?: IDBFactory | null;
}
const normalizeError = (error: unknown, message: string): Error =>
error instanceof Error ? error : new Error(message);
/**
* Stores one durable last-known-good settings snapshot for the current vault.
*/
export class SettingsRecoveryStore<Snapshot extends Record<string, unknown>> {
private database: IDBDatabase | null = null;
private databasePromise: Promise<IDBDatabase> | null = null;
private readonly indexedDBFactory: IDBFactory | null;
private destroyed = false;
public constructor(private readonly options: SettingsRecoveryStoreOptions) {
this.indexedDBFactory =
"indexedDBFactory" in options
? (options.indexedDBFactory ?? null)
: typeof indexedDB === "undefined"
? null
: indexedDB;
}
/** Returns the last complete settings snapshot, if one is available. */
public async load(): Promise<Snapshot | null> {
const database = await this.getDatabase();
return new Promise<Snapshot | null>((resolve, reject) => {
let request: IDBRequest<SettingsRecoveryRecord<Snapshot> | undefined>;
try {
const transaction = database.transaction(STORE_NAME, "readonly");
request = transaction
.objectStore(STORE_NAME)
.get(RECORD_KEY) as IDBRequest<
SettingsRecoveryRecord<Snapshot> | undefined
>;
request.onsuccess = () => {
const record = request.result;
resolve(
record?.version === RECORD_VERSION &&
typeof record.settings === "object" &&
record.settings !== null &&
!Array.isArray(record.settings)
? record.settings
: null,
);
};
request.onerror = () => {
reject(
request.error ?? new Error("Could not read settings recovery"),
);
};
} catch (error) {
reject(normalizeError(error, "Could not read settings recovery"));
}
});
}
/** Atomically replaces the last-known-good settings snapshot. */
public async save(settings: Snapshot): Promise<void> {
const database = await this.getDatabase();
return new Promise<void>((resolve, reject) => {
try {
const transaction = database.transaction(STORE_NAME, "readwrite");
transaction.objectStore(STORE_NAME).put(
{
version: RECORD_VERSION,
settings,
} satisfies SettingsRecoveryRecord<Snapshot>,
RECORD_KEY,
);
transaction.oncomplete = () => resolve();
transaction.onerror = () => {
reject(
transaction.error ?? new Error("Could not save settings recovery"),
);
};
transaction.onabort = () => {
reject(
transaction.error ?? new Error("Settings recovery write aborted"),
);
};
} catch (error) {
reject(normalizeError(error, "Could not save settings recovery"));
}
});
}
/** Closes the database connection owned by this plugin instance. */
public destroy(): void {
this.destroyed = true;
this.database?.close();
this.database = null;
this.databasePromise = null;
}
private async getDatabase(): Promise<IDBDatabase> {
if (this.destroyed) {
throw new Error("Settings recovery store has been destroyed");
}
if (this.database) {
return this.database;
}
const indexedDBFactory = this.indexedDBFactory;
if (!indexedDBFactory) {
throw new Error("IndexedDB is unavailable for settings recovery");
}
if (this.databasePromise === null) {
this.databasePromise = this.openDatabase(indexedDBFactory);
}
try {
return await this.databasePromise;
} catch (error) {
this.database?.close();
this.database = null;
this.databasePromise = null;
throw error;
}
}
private openDatabase(indexedDBFactory: IDBFactory): Promise<IDBDatabase> {
return new Promise<IDBDatabase>((resolve, reject) => {
let requestCompleted = false;
const request = indexedDBFactory.open(
this.options.databaseName,
DATABASE_VERSION,
);
request.onupgradeneeded = () => {
const database = request.result;
if (!database.objectStoreNames.contains(STORE_NAME)) {
database.createObjectStore(STORE_NAME);
}
};
request.onsuccess = () => {
const database = request.result;
if (requestCompleted || this.destroyed) {
database.close();
if (!requestCompleted) {
requestCompleted = true;
reject(new Error("Settings recovery store has been destroyed"));
}
return;
}
requestCompleted = true;
database.onversionchange = () => {
database.close();
if (this.database === database) {
this.database = null;
this.databasePromise = null;
}
};
this.database = database;
resolve(database);
};
request.onerror = () => {
requestCompleted = true;
reject(request.error ?? new Error("Could not open settings recovery"));
};
request.onblocked = () => {
requestCompleted = true;
reject(new Error("Settings recovery database upgrade was blocked"));
};
});
}
}
@@ -0,0 +1,138 @@
/**
* Markdown export for Obsidian's declarative settings tree.
*
* The exporter reads the declarations rather than the currently mounted page,
* so nested and conditionally rendered settings remain discoverable in one
* document.
*/
import { htmlToMarkdown } from "obsidian";
import type {
SettingDefinition,
SettingDefinitionItem,
} from "src/types/obsidianDeclarativeSettings";
declare const mainDocument: Document;
declare const deliberateCreateElement: (
document: Document,
tagName: string,
) => HTMLElement;
interface MarkdownDefinitionMetadata {
controlType?: string;
omit?: boolean;
}
const definitionMetadata = new WeakMap<object, MarkdownDefinitionMetadata>();
/** Adds export-only metadata without exposing custom fields to Obsidian. */
export function annotateMarkdownDefinition<T extends object>(
definition: T,
metadata: MarkdownDefinitionMetadata,
): T {
definitionMetadata.set(definition, metadata);
return definition;
}
function toMarkdown(value: string | DocumentFragment | undefined): string {
if (value === undefined) {
return "";
}
if (typeof value === "string") {
return htmlToMarkdown(value).trim();
}
const container = deliberateCreateElement(mainDocument, "div");
container.appendChild(value.cloneNode(true));
return htmlToMarkdown(container.innerHTML).trim();
}
function normalizeControlType(controlType: string): string {
switch (controlType) {
case "text":
return "text input";
case "number-dropdown":
return "dropdown";
case "textarea":
return "text area";
default:
return controlType;
}
}
function getControlType(definition: SettingDefinition): string | undefined {
const metadata = definitionMetadata.get(definition);
if (metadata?.controlType) {
return normalizeControlType(metadata.controlType);
}
if ("control" in definition && definition.control) {
return normalizeControlType(definition.control.type);
}
if ("render" in definition && definition.render) {
return "custom control";
}
return undefined;
}
function renderSetting(definition: SettingDefinition): string | null {
const metadata = definitionMetadata.get(definition);
if (metadata?.omit) {
return null;
}
const description = toMarkdown(definition.desc);
const controlType = getControlType(definition);
const typePrefix = controlType ? ` (${controlType})` : "";
return `- **${definition.name}:**${typePrefix}${description ? ` ${description}` : ""}`;
}
function renderItems(
items: readonly SettingDefinitionItem[],
headingLevel: number,
): string[] {
const output: string[] = [];
for (const item of items) {
if ("type" in item) {
output.push(`${"#".repeat(headingLevel)} ${item.name}`);
const description = toMarkdown(item.desc);
if (description) {
output.push(description);
}
if (item.items?.length) {
output.push(...renderItems(item.items, headingLevel + 1));
}
continue;
}
const setting = renderSetting(item);
if (setting) {
output.push(setting);
}
}
return output;
}
/** Converts a complete declarative settings tree into one Markdown document. */
export function declarativeSettingsToMarkdown(
definitions: readonly SettingDefinitionItem[],
): string {
const blocks = renderItems(definitions, 1);
if (blocks.length === 0) {
return "";
}
let markdown = "";
let previousBlock = "";
for (const block of blocks) {
const separator =
markdown.length === 0
? ""
: previousBlock.startsWith("- **") && block.startsWith("- **")
? "\n"
: "\n\n";
markdown += `${separator}${block}`;
previousBlock = block;
}
return `${markdown}\n`;
}
+126
View File
@@ -0,0 +1,126 @@
/**
* Canonical setting-row specifications shared by the legacy and declarative
* settings adapters.
*/
import type { TextComponent } from "obsidian";
import type { ExcalidrawSettings } from "src/core/settingsDefaults";
/** Keys of {@link ExcalidrawSettings} whose value type is boolean. */
export type BooleanSettingKey = {
[K in keyof ExcalidrawSettings]: ExcalidrawSettings[K] extends boolean
? K
: never;
}[keyof ExcalidrawSettings];
/** Keys whose value type is exactly `string`, excluding literal unions. */
export type StringSettingKey = {
[K in keyof ExcalidrawSettings]: string extends ExcalidrawSettings[K]
? ExcalidrawSettings[K] extends string
? K
: never
: never;
}[keyof ExcalidrawSettings];
/** Keys whose value is a string or a narrower string-literal union. */
export type StringLikeSettingKey = {
[K in keyof ExcalidrawSettings]: ExcalidrawSettings[K] extends string
? K
: never;
}[keyof ExcalidrawSettings];
/** Keys of {@link ExcalidrawSettings} whose value type is number. */
export type NumberSettingKey = {
[K in keyof ExcalidrawSettings]: ExcalidrawSettings[K] extends number
? K
: never;
}[keyof ExcalidrawSettings];
/** Every persisted key currently supported by a canonical row binding. */
export type SettingBindingKey =
| BooleanSettingKey
| StringLikeSettingKey
| NumberSettingKey;
type SettingControlBase<Value, Key extends SettingBindingKey> = {
key: Key;
before?: (value: Value) => void | Promise<void>;
after?: (value: Value) => void | Promise<void>;
afterUpdate?: (value: Value) => void | Promise<void>;
reload?: boolean;
disabled?: boolean | (() => boolean);
};
/** Canonical toggle control, including support for an inverted stored value. */
export type ToggleControl = SettingControlBase<boolean, BooleanSettingKey> & {
type: "toggle";
negate?: boolean;
};
/** Canonical text control and its legacy-only component integrations. */
export type TextControl = SettingControlBase<string, StringSettingKey> & {
type: "text";
placeholder?: string;
sanitize?: (value: string) => string;
vaultPath?: {
kind: "file" | "folder";
options?: {
optional?: boolean;
extensions?: readonly string[];
resolvePath?: (value: string) => string;
createFolder?: boolean;
validate?: boolean;
};
};
capture?: (text: TextComponent) => void;
};
/** Canonical string-valued dropdown control. */
export type DropdownControl = SettingControlBase<
string,
StringLikeSettingKey
> & {
type: "dropdown";
options: readonly { value: string; label: string }[];
};
/** Canonical numeric value represented by string-valued dropdown options. */
export type NumberDropdownControl = SettingControlBase<
number,
NumberSettingKey
> & {
type: "number-dropdown";
options: readonly { value: number; label: string }[];
parse?: "int" | "float";
};
/** Canonical numeric slider control. */
export type SliderControl = SettingControlBase<number, NumberSettingKey> & {
type: "slider";
min: number;
max: number;
step: number;
minWidth?: string;
scale?: number;
};
/** Controls currently understood by both settings adapters. */
export type SettingControlSpec =
| ToggleControl
| TextControl
| DropdownControl
| NumberDropdownControl
| SliderControl;
/**
* One canonical setting row. Search metadata is declarative-only; visibility
* and disabled predicates are interpreted by both adapters.
*/
export interface SettingSpec {
name: string | DocumentFragment;
desc?: string | DocumentFragment;
aliases?: string[];
searchable?: boolean | (() => boolean);
visible?: boolean | (() => boolean);
control: SettingControlSpec;
}
@@ -0,0 +1,44 @@
/** Classification helpers for safely loading plugin settings data. */
/** Observable state of the plugin's `data.json` file before loading it. */
export type SettingsDataFileState =
| "missing"
| "empty"
| "present"
| "unknown";
/** Result of validating one settings load attempt. */
export type SettingsDataLoadClassification =
| "valid"
| "first-installation"
| "invalid";
/** Returns true for the object shape accepted as persisted settings data. */
export const isSettingsDataRecord = (
value: unknown,
): value is Record<string, unknown> =>
typeof value === "object" && value !== null && !Array.isArray(value);
/**
* Distinguishes a genuine first installation from an empty, malformed, or
* failed settings load that must not replace already loaded settings.
*/
export function classifySettingsDataLoad(options: {
value: unknown;
fileState: SettingsDataFileState;
loadFailed: boolean;
isInitialLoad: boolean;
}): SettingsDataLoadClassification {
if (isSettingsDataRecord(options.value)) {
return "valid";
}
if (
options.isInitialLoad &&
!options.loadFailed &&
(options.value === null || typeof options.value === "undefined") &&
options.fileState === "missing"
) {
return "first-installation";
}
return "invalid";
}
+51
View File
@@ -0,0 +1,51 @@
import type { App } from "obsidian";
/** Returns whether the current Obsidian runtime exposes page navigation. */
export function canNavigateSettingsPages(app: App): boolean {
return (
typeof app.setting.openPagePath === "function" ||
(typeof app.setting.findTabById === "function" &&
typeof app.setting.navigateToPage === "function")
);
}
/**
* Navigates to a declarative settings page through Obsidian's unpublished
* settings API.
*
* The method is deliberately isolated behind structural and exception guards
* because it is not part of Obsidian's public compatibility contract.
*
* @returns `true` when Obsidian accepted the navigation request, otherwise
* `false` so callers can leave the current page intact.
*/
export function navigateToSettingsPage(
app: App,
tabId: string,
pagePath: readonly string[],
): boolean {
try {
if (typeof app.setting.openPagePath === "function") {
return app.setting.openPagePath(tabId, [...pagePath]) !== null;
}
if (
typeof app.setting.findTabById !== "function" ||
typeof app.setting.navigateToPage !== "function"
) {
return false;
}
const tab = app.setting.findTabById(tabId);
if (!tab) {
return false;
}
app.setting.navigateToPage(tab, [...pagePath]);
return true;
} catch (error) {
console.warn(
"Excalidraw: Obsidian settings page navigation is unavailable.",
error,
);
return false;
}
}
File diff suppressed because it is too large. Load diff
+243 -22
View File
@@ -22,6 +22,21 @@ export default {
SELECT_FILE_TO_INSERT: "Select a file to insert",
// main.ts
ERROR_INITIALIZING_EA: "Error initializing Excalidraw Automate",
SETTINGS_DATA_INVALID:
"Excalidraw is waiting for a valid replacement data.json. Setting changes will not be saved until that file is restored, or you restart Obsidian and choose Reset to defaults.",
SETTINGS_DATA_REPAIRED_FROM_MEMORY:
"An empty or unreadable Excalidraw settings file was received and rejected. The active settings were written back to repair data.json.",
SETTINGS_DATA_RECOVERED:
"Excalidraw data.json was empty or unreadable. The last known good settings were restored automatically.",
SETTINGS_RECOVERY_MISSING_TITLE: "Excalidraw settings file is missing",
SETTINGS_RECOVERY_MISSING_DESC:
"A last known good settings backup exists on this device. Restore that backup, or reset Excalidraw to factory defaults. Closing this message restores the backup.",
SETTINGS_RECOVERY_CORRUPT_TITLE: "Excalidraw settings file is corrupted",
SETTINGS_RECOVERY_CORRUPT_DESC:
"The settings file is empty or unreadable, and no recovery backup is available on this device. Reset Excalidraw to factory defaults, or leave the file unchanged while you restore a valid data.json from another source. Closing this message waits for a replacement file.",
SETTINGS_RECOVERY_RESTORE_BACKUP: "Restore backup",
SETTINGS_RECOVERY_RESET_DEFAULTS: "Reset to defaults",
SETTINGS_RECOVERY_WAIT_FOR_FILE: "Wait for restored file",
CONVERT_URL_TO_FILE: "Save image from URL to local file",
UNZIP_CURRENT_FILE: "Decompress current Excalidraw file",
PUBLISH_SVG_CHECK:
@@ -44,6 +59,41 @@ export default {
CONVERT_FILE_KEEP_EXT: "*.excalidraw => *.excalidraw.md",
CONVERT_FILE_REPLACE_EXT: "*.excalidraw => *.md (Logseq compatibility)",
DOWNLOAD_LIBRARY: "Export stencil library as an *.excalidrawlib file",
LIBRARY_MIGRATION_TITLE: "Move your Excalidraw library into the vault",
LIBRARY_MIGRATION_DESC:
"Excalidraw can store your library in a dedicated vault file instead of data.json. This keeps plugin settings smaller and makes saving more stable. Your existing items will be merged into the selected local library file; downloaded *.excalidrawlib files placed in the same folder will also be loaded. Choose Later to hide this message until tomorrow.",
LIBRARY_MIGRATION_SYNC_WARNING:
'To sync library files with Obsidian Sync, enable "Sync all other types" in Obsidian Sync settings.',
LIBRARY_MIGRATION_KEEP_DATA_JSON: "Keep using data.json",
LIBRARY_MIGRATION_LATER: "Later",
LIBRARY_MIGRATION_MIGRATE: "Move library",
LIBRARY_MIGRATION_SUCCESS: "Excalidraw library moved into the vault.",
LIBRARY_MIGRATION_FAILED:
"The library could not be moved. Your original data.json library was kept unchanged.",
LIBRARY_FILE_READ_ERROR: "Could not read Excalidraw library file: {PATH}",
LIBRARY_STORAGE_NAME: "Library storage",
LIBRARY_STORAGE_DESC:
"Vault files provide more stable saving because the stencil library is kept out of data.json.",
LIBRARY_STORAGE_VAULT: "Vault folder (recommended)",
LIBRARY_STORAGE_DATA_JSON: "Plugin data.json (legacy)",
LIBRARY_FOLDER_NAME: "Library folder",
LIBRARY_FOLDER_DESC:
'Folder for local-library.excalidrawlib and downloaded library files. Library files use the .excalidrawlib extension. To see them in Obsidian\'s file explorer, enable "Show all file types" in Obsidian settings.',
LIBRARY_FILE_NAME: "Local library file name",
LIBRARY_FILE_DESC:
"Name of the editable local library file. The .excalidrawlib extension is added automatically.",
LIBRARY_MIGRATE_NOW: "Move library now",
LIBRARY_MIGRATE_NOW_DESC:
"Move the existing data.json library into the configured vault file.",
LIBRARY_PATH_MISSING: "This path does not currently exist in the vault.",
CREATE_FOLDER: "Create folder",
CREATE_FOLDER_CONFIRM: "Do you want to create the folder <b>{PATH}</b>?",
CREATE_FOLDER_NEVER_MIND: "Never mind",
CREATE_FOLDER_YES: "Yes",
CREATE_FOLDER_SUCCESS: "Created folder: {PATH}",
CREATE_FOLDER_FAILED: "Could not create folder: {PATH}",
CREATE_FOLDER_PATH_IS_FILE:
"The folder cannot be created because a file already exists at: {PATH}",
OPEN_SIDEPANEL: "Open Excalidraw Sidepanel",
OPEN_EXISTING_NEW_PANE: "Open existing drawing - IN A NEW PANE",
OPEN_EXISTING_ACTIVE_PANE:
@@ -102,32 +152,26 @@ export default {
MARKDOWN_IMAGE_APPEARANCE: "Appearance",
MARKDOWN_IMAGE_WIDTH: "Width",
MARKDOWN_IMAGE_WIDTH_DESC: "Markdown flow width in canvas units",
MARKDOWN_IMAGE_BOTTOM_PADDING: "Bottom padding",
MARKDOWN_IMAGE_BOTTOM_PADDING_DESC:
"Extra space below the rendered Markdown, in pixels",
MARKDOWN_IMAGE_FONT: "Font",
MARKDOWN_IMAGE_FONT_COLOR: "Font color",
MARKDOWN_IMAGE_BORDER: "Border",
MARKDOWN_IMAGE_BORDER_COLOR: "Border color",
MARKDOWN_IMAGE_THEME: "Theme",
MARKDOWN_IMAGE_THEME_DESC:
"Controls theme-sensitive content such as code blocks, tables, links, and callouts.",
MARKDOWN_IMAGE_MATCH_CANVAS: "Match canvas",
MARKDOWN_IMAGE_LIGHT: "Light",
MARKDOWN_IMAGE_DARK: "Dark",
MARKDOWN_IMAGE_CSS: "CSS",
MARKDOWN_IMAGE_CSS_DESC: "CSS rules applied only to this Markdown image.",
MARKDOWN_IMAGE_CSS_DESC:
"CSS for this Markdown image only. Copy the SVG below and ask your preferred LLM for the CSS you need.",
MARKDOWN_IMAGE_CSS_IMPORTANT_HINT:
"If a rule has no effect, add !important to the declaration.",
MARKDOWN_IMAGE_CSS_DESKTOP_HELP:
"To inspect the generated markup, open Developer Console ({shortcut}) and run the command available from the copy button.",
MARKDOWN_IMAGE_CSS_MOBILE_HELP:
"On desktop, you can inspect the generated markup in Developer Console and run the command available from the copy button.",
MARKDOWN_IMAGE_CSS_EDITOR_ARIA: "CSS editor for this Markdown image",
MARKDOWN_IMAGE_TRANSCLUSION_CSS_EDITOR_ARIA:
"CSS editor for transcluded Markdown",
MARKDOWN_IMAGE_INSERT_CSS_BOILERPLATE:
"Insert a commented CSS boilerplate",
MARKDOWN_IMAGE_COPY_CSS_COMMAND:
"Copy the generated Markdown SVG console command",
MARKDOWN_IMAGE_CSS_COMMAND_COPIED: "Console command copied",
MARKDOWN_IMAGE_COPY_SVG: "Copy the current Markdown image SVG",
MARKDOWN_IMAGE_SVG_COPIED: "Markdown image SVG copied",
MARKDOWN_IMAGE_SVG_COPY_ERROR: "Could not copy the Markdown image SVG",
MARKDOWN_IMAGE_TRANSCLUSION_DIFFERENT_STYLE:
"Use a different style for transclusions",
MARKDOWN_IMAGE_TRANSCLUSION_DIFFERENT_STYLE_DESC:
@@ -141,6 +185,7 @@ export default {
MARKDOWN_IMAGE_SET_DEFAULT: "Set as default",
MARKDOWN_IMAGE_SAVE_DEFAULT_ARIA:
"Save current appearance settings as the default",
MARKDOWN_IMAGE_DEFAULT_SAVED: "Markdown image defaults saved",
MARKDOWN_IMAGE_RENDER_NOW: "Render now",
MARKDOWN_IMAGE_UPDATING: "Updating image…",
MARKDOWN_IMAGE_EXTERNAL_SOURCE: "External Markdown source",
@@ -153,12 +198,16 @@ export default {
MARKDOWN_IMAGE_USE_SOURCE: "Use source",
MARKDOWN_IMAGE_EXTRACT_LOCAL: "Extract local Markdown to a note",
MARKDOWN_IMAGE_EXTRACT: "Extract to note",
MARKDOWN_IMAGE_DUPLICATE_ERROR: "Could not duplicate the Markdown image",
MARKDOWN_IMAGE_SELECT_SOURCE: "Select a Markdown note, heading, or block",
MARKDOWN_IMAGE_CHANGE_SOURCE_ERROR:
"Could not change the Markdown image source",
MARKDOWN_IMAGE_LOCAL_COPY_ERROR: "Could not create a local Markdown copy",
MARKDOWN_IMAGE_EXTRACT_TITLE: "Extract Markdown image to note",
MARKDOWN_IMAGE_EXTRACT_PATH: "Path to the new Markdown note",
FILE_AND_FOLDER_SELECTOR_FOLDER: "Folder",
FILE_AND_FOLDER_SELECTOR_FILENAME: "File name",
FILE_AND_FOLDER_SELECTOR_EXPORT_TITLE: "Export to Vault",
FILE_AND_FOLDER_SELECTOR_EXPORT: "Export",
MARKDOWN_IMAGE_DEFAULT_NOTE: "Markdown image.md",
MARKDOWN_IMAGE_CREATE_NOTE_ERROR: "Could not create Markdown note",
MARKDOWN_IMAGE_UNKNOWN_ERROR: "Unknown error",
@@ -180,6 +229,10 @@ export default {
"A local Markdown image can contain only one level 1 heading when converted to an embeddable. It must be the first content and its name must be unique in the drawing.",
MARKDOWN_IMAGE_SECTION_NAME: "Name the back-of-note section",
MARKDOWN_IMAGE_SECTION_NAME_PLACEHOLDER: "Enter a unique section name",
MARKDOWN_IMAGE_DELETE_TEXT_PROMPT:
"Delete the Markdown text stored for this image? The image will be removed from the scene either way.",
MARKDOWN_IMAGE_KEEP_TEXT: "Keep Markdown text",
MARKDOWN_IMAGE_DELETE_TEXT: "Delete Markdown text",
INSERT_PDF: "Insert PDF file from vault",
INSERT_LAST_ACTIVE_PDF_PAGE_AS_IMAGE: "Insert last active PDF page as image",
UNIVERSAL_ADD_FILE: "Insert ANY file",
@@ -208,6 +261,10 @@ export default {
"OCR full drawing: Grab text from freedraw + images to clipboard and doc.props",
TASKBONE_NOT_ENABLED:
"Taskbone OCR is not enabled. Please go to plugins settings to enable it.",
OCR_ABORT_NO_ELEMENTS:
"Aborting OCR because there are no image or freedraw elements on the canvas.",
OCR_ALREADY_PROCESSED:
"The drawing has already been processed, you will find the result in the frontmatter in Markdown view mode. If you ran the command from the Obsidian panel in Excalidraw then you can ctrl(cmd)+click the command to force the rescanning.",
RERUN_OCR:
"OCR full drawing re-run: Grab text from freedraw + images to clipboard and doc.props",
RUN_OCR_ELEMENTS:
@@ -256,8 +313,6 @@ export default {
"Inverted Mode: Default arrow binding is now disabled. Use CTRL/CMD to temporarily enable binding when needed.",
ARROW_BINDING_NORMAL_MODE:
"Normal Mode: Arrow binding is now enabled. Use CTRL/CMD to temporarily disable binding when needed.",
EXPORT_FILENAME_PROMPT: "Please provide filename",
EXPORT_FILENAME_PROMPT_PLACEHOLDER: "filename, leave blank to cancel action",
WARNING_SERIOUS_ERROR:
"WARNING: Excalidraw ran into an unknown problem!\n\n" +
"There is a risk that your most recent changes cannot be saved.\n\n" +
@@ -344,6 +399,18 @@ export default {
SEARCH_SHOWHIDE_ARIA: "Show/Hide search bar",
SEARCH_NEXT: "Next",
SEARCH_PREVIOUS: "Previous",
SETTINGS_TOOLBAR_COPY: "Copy settings",
SETTINGS_TOOLBAR_NOTEBOOKLM: "NotebookLM",
SETTINGS_TOOLBAR_BUGS: "Bugs",
SETTINGS_TOOLBAR_WIKI: "Wiki",
SETTINGS_TOOLBAR_YOUTUBE: "YouTube",
SETTINGS_TOOLBAR_LEARN: "Learn",
SETTINGS_TOOLBAR_FOLLOW: "Twitter",
SETTINGS_TOOLBAR_READ: "Read Book",
SETTINGS_TOOLBAR_KOFI: "Ko-fi",
USE_DECLARATIVE_SETTINGS_NAME: "Use searchable settings",
USE_DECLARATIVE_SETTINGS_DESC:
"Use Obsidian's searchable, multi-page settings interface. Turn this off to use Excalidraw's legacy single-page settings. Requires restarting Obsidian.",
//settings.ts
FOLDER_PLACEHOLDER: "e.g.: Excalidraw",
@@ -378,8 +445,6 @@ export default {
"Disables the Excalidraw context menu. This can be useful on Mobile devices where the context menu pops up in unwanted moments.",
NOTEBOOKLM_LINK_ARIA:
"Ask NotebookLM for help about the plugin. This model is pre-loaded with all my video transcripts, release notes and other helpful content. Chat with NotebookLM to explore my 250+ videos and the Excalidraw documentation.",
NOTEBOOKLM_LINK_TEXT:
"Learn the Plugin. Access the NotebookLM knowledgebase.",
EXCALIDRAW_MASTERY: "Excalidraw Mastery",
EXCALIDRAW_MASTERY_PROMO_ARIA: "Open Excalidraw Mastery",
EXCALIDRAW_MASTERY_PROMO_HTML: `<p><b>Feeling lost in the toggles and menus?</b></p><p>Excalidraw is a Visual PKM powerhouse built for heavy-duty workflows like <b>Visual-First Daily Notes</b>, deep <b>PDF research</b>, <b>automation</b>, <b>AI integration</b>, and <b>Visual Zettelkasten</b>. But all this power comes with complexity.</p><p>Skip the trial and error. <a href="${URLs.COMMUNITY_SKETCH_YOUR_MIND_COM_EM}" target="_blank">👉 Join Excalidraw Mastery</a> to learn these exact setups step-by-step. Overcome tool friction and master your knowledge alongside a supportive community of visual thinkers!</p>`,
@@ -413,6 +478,15 @@ export default {
"<b><u>Toggle OFF:</u></b> Silent mode. You need to check for plugin updates in Community Plugins.",
BASIC_HEAD: "Basic",
BASIC_UPDATES_STARTUP_HEAD: "Updates and startup",
BASIC_UPDATES_STARTUP_DESC:
"Release notes, update checks and notifications, and the startup splash screen.",
BASIC_FILES_FOLDERS_HEAD: "Files and folders",
BASIC_FILES_FOLDERS_DESC:
"Default folders and paths for drawings, crops, annotations, templates, and Excalidraw Automate scripts.",
BASIC_STENCIL_LIBRARY_HEAD: "Stencil Library",
BASIC_STENCIL_LIBRARY_DESC:
"Choose where stencil library data is stored and configure its vault folder and local library file.",
BASIC_DESC: `In the "Basic" settings, you can configure options such as displaying release notes after updates, receiving plugin update notifications, setting the default location for new drawings, specifying the Excalidraw folder for embedding drawings into active documents, defining an Excalidraw template file, and designating an Excalidraw Automate script folder for managing automation scripts.`,
FOLDER_NAME: "Excalidraw folder (CAsE sEnsITive!)",
FOLDER_DESC:
@@ -612,6 +686,9 @@ export default {
AI_USAGE_SETTINGS_BUTTON_DESC:
"View AI token consumption for the current Obsidian session broken down by model. Usage resets on restart.",
SAVING_HEAD: "Saving",
SAVING_STORAGE_AUTOSAVE_HEAD: "Storage and autosave",
SAVING_STORAGE_AUTOSAVE_DESC:
"Control drawing JSON compression and choose desktop and mobile autosave intervals.",
SAVING_DESC:
"In the 'Saving' section of Excalidraw Settings, you can configure how your drawings are saved. This includes options for compressing Excalidraw JSON in Markdown, setting autosave intervals for both desktop and mobile, defining filename formats, and choosing whether to use the .excalidraw.md or .md file extension. ",
COMPRESS_NAME: "Compress Excalidraw JSON in Markdown",
@@ -645,6 +722,8 @@ export default {
"Excalidraw will not be able to save your work when terminating Obsidian directly (i.e. swiping it away). Also note, that when you switch apps on a Mobile device, sometimes Android and iOS closes " +
"Obsidian in the background to save system resources. In such a case Excalidraw will not be able to save the latest changes.",
FILENAME_HEAD: "Filename",
FILENAME_GROUP_DESC:
"Configure how new, embedded, cropped, and annotated drawing filenames are generated.",
FILENAME_DESC:
`<p>Click this link for the <a href="${URLs.MOMENTJS_COM_DOCS}">` +
"date and time format reference</a>.</p>",
@@ -672,6 +751,9 @@ export default {
DISPLAY_HEAD: "Excalidraw appearance and behavior",
DISPLAY_DESC:
"In the 'appearance and behavior' section of Excalidraw Settings, you can fine-tune how Excalidraw appears and behaves. This includes options for dynamic styling, left-handed mode, matching Excalidraw and Obsidian themes, default modes, and more.",
DISPLAY_EDITOR_PREVIEWS_HEAD: "Editing and previews",
DISPLAY_EDITOR_PREVIEWS_DESC:
"Configure canvas editing gestures and how Excalidraw files appear in reading mode and hover previews.",
OVERRIDE_OBSIDIAN_FONT_SIZE_NAME: "Limit Obsidian Font Size to Editor Text",
OVERRIDE_OBSIDIAN_FONT_SIZE_DESC:
"Obsidian's custom font size setting affects the entire interface, including Excalidraw and themes that depend on the default font size. " +
@@ -752,6 +834,8 @@ export default {
}'>Markdown Reading Mode</a> under 'Appearance and Behavior' further above.<br>` +
`⚠️ You must close and reopen the Excalidraw/markdown file for changes to take effect. ⚠️`,
MODES_HEAD: "UI Modes",
MODES_DESC:
"Choose device-specific Excalidraw interface layouts, title-bar controls, and left- or right-handed tray placement.",
DESKTOP_UI_MODE_NAME: "Preferred Desktop Mode",
DESKTOP_UI_MODE_DESC: "Select the default UI mode for desktop devices.",
TABLET_UI_MODE_NAME: "Preferred Tablet Mode",
@@ -764,12 +848,19 @@ export default {
MODE_PHONE: "Phone-mode",
REAPPLY_UI_MODE_BUTTON: "Reapply UI mode now",
HOTKEY_OVERRIDE_HEAD: "Hotkey overrides",
HOTKEY_OVERRIDE_GROUP_DESC:
"Manage Excalidraw key combinations that should take priority over conflicting Obsidian hotkeys.",
HOTKEY_OVERRIDE_CONTROL_NAME: "Manage hotkey overrides",
HOTKEY_OVERRIDE_DESC:
`Some of the Excalidraw hotkeys such as <code>${labelCTRL()}+Enter</code> to edit text or <code>${labelCTRL()}+K</code> to create an element link ` +
"conflict with Obsidian hotkey settings. The hotkey combinations you add below will override Obsidian's hotkey settings while using Excalidraw, thus " +
`you can add <code>${labelCTRL()}+G</code> if you want to default to Group Object in Excalidraw instead of opening Graph View.`,
THEME_HEAD: "Theme and styling",
THEME_DESC:
"Control interface styling, drawing and embed themes, opening mode, and mobile safe-area spacing.",
ZOOM_AND_PAN_HEAD: "Zoom and Pan",
ZOOM_AND_PAN_DESC:
"Configure mouse, touch, opening, resizing, and zoom-range behavior.",
PAN_WITH_RIGHT_MOUSE_BUTTON_NAME: "Right-click drag to pan",
PAN_WITH_RIGHT_MOUSE_BUTTON_DESC:
"Right-click and drag to pan the canvas (Miro-style). Press 'm' to open the context menu.",
@@ -802,7 +893,11 @@ export default {
ZOOM_MAX_DESC:
"Upper zoom limit. Default: 3000%. Usually no need to change; included for completeness.",
PEN_HEAD: "Pen",
PEN_DESC:
"Configure automatic pen mode, touch gestures, the eraser, and the freedraw crosshair.",
GRID_HEAD: "Grid",
GRID_DESC:
"Configure grid direction, automatic or custom color, and opacity.",
GRID_DYNAMIC_COLOR_NAME: "Dynamic grid color",
GRID_DYNAMIC_COLOR_DESC:
"<b><u>Toggle ON:</u></b>Change grid color to match the canvas color<br><b><u>Toggle OFF:</u></b>Use the color below as the grid color",
@@ -816,6 +911,8 @@ export default {
GRID_HORIZONTAL: "Render horizontal grid",
GRID_VERTICAL: "Render vertical grid",
LASER_HEAD: "Laser pointer",
LASER_DESC:
"Configure the laser pointer color and how quickly and how far its trail fades.",
LASER_COLOR: "Laser pointer color",
LASER_DECAY_TIME_NAME: "Laser pointer decay time",
LASER_DECAY_TIME_DESC:
@@ -835,6 +932,21 @@ export default {
"When Obsidian files change, the matching <code>[[link]]</code> in your drawings will also change. " +
"If you don't want text accidentally changing in your drawings use <code>[[links|with aliases]]</code>.",
DRAG_MODIFIER_NAME: "Link Click and Drag&Drop Modifier Keys",
DRAG_MODIFIER_GROUP_DESC:
"Configure link-opening gestures and platform-specific modifier combinations for clicks and drag-and-drop actions.",
LINK_OPENING_GESTURES_HEAD: "Link-opening gestures",
LINK_OPENING_GESTURES_DESC:
"Configure long-press delays and double-click link opening for embedded drawings and view mode.",
WEB_BROWSER_DRAG_ACTION_DESC:
"Choose modifier combinations for links, images, imports, and embeddables dragged from a web browser.",
LOCAL_FILE_DRAG_ACTION_DESC:
"Choose modifier combinations for links, images, imports, and embeddables dragged from the operating system.",
INTERNAL_DRAG_ACTION_DESC:
"Choose modifier combinations for links, images, full-size images, and embeddables dragged inside Obsidian.",
PANE_TARGET_DESC:
"Choose modifier combinations that determine where clicked links open.",
MODIFIER_KEY_USAGE_NAME: "Configuring modifier keys",
MODIFIER_KEY_COMBINATIONS: "Modifier combinations",
DRAG_MODIFIER_DESC:
`Modifier key behavior when clicking links and dragging and dropping elements. ` +
`Excalidraw will not validate your configuration... pay attention to avoid conflicting settings. ` +
@@ -932,6 +1044,22 @@ export default {
"Use the <code>http" +
"s://noembed" +
".com/embed?url=</code> to get title of page when dropping an HTTPS link into Excalidraw",
LINK_BEHAVIOR_HEAD: "Link behavior",
LINK_BEHAVIOR_DESC:
"Configure link synchronization, related links, hover previews, click handling, and web-page title lookup.",
LINK_USAGE_NAME: "Using links in Excalidraw",
LINK_OPENING_HEAD: "Pane and tab behavior",
LINK_OPENING_DESC:
"Choose whether opened links reuse, focus, or move between panes, tabs, and the main workspace.",
LINK_APPEARANCE_HEAD: "Link appearance",
LINK_APPEARANCE_DESC:
"Configure brackets, prefixes, icons, and opacity used when links are displayed.",
TODO_HEAD: "TODOs",
TODO_GROUP_DESC:
"Configure TODO parsing and the icons used for open and completed tasks.",
TRANSCLUSION_HEAD: "Text transclusions",
TRANSCLUSION_DESC:
"Configure character limits, wrapping, and quote cleanup for transcluded Markdown text.",
PDF_TO_IMAGE: "PDF to Image",
PDF_TO_IMAGE_SCALE_NAME: "PDF to Image conversion scale",
PDF_TO_IMAGE_SCALE_DESC:
@@ -941,7 +1069,12 @@ export default {
EMBED_TOEXCALIDRAW_DESC:
"In the Embed Files section of Excalidraw Settings, you can configure how various files are embedded into Excalidraw. This includes options for embedding interactive markdown files, PDFs, and markdown files as images.",
MD_HEAD: "Embed markdown into Excalidraw as image",
MD_GROUP_DESC:
"Set dimensions, font, colors, borders, and CSS for Markdown files rendered as images.",
MD_EMBED_CUSTOMDATA_HEAD_NAME: "Interactive Markdown Files",
MD_EMBED_CUSTOMDATA_GROUP_DESC:
"Configure editing and default appearance for future interactive Markdown embeds.",
MD_EMBED_DEFAULTS_CONTROL_NAME: "Interactive Markdown appearance defaults",
MD_EMBED_CUSTOMDATA_HEAD_DESC: `The below settings will only effect future embeds. Current embeds remain unchanged. The theme setting of embedded frames is under the "Excalidraw appearance and behavior" section.`,
MD_EMBED_SINGLECLICK_EDIT_NAME: "Single click to edit embedded markdown",
MD_EMBED_SINGLECLICK_EDIT_DESC:
@@ -985,12 +1118,17 @@ export default {
EMBED_HEAD: "Embedding Excalidraw into your Notes and Exporting",
EMBED_DESC: `In the "Embed & Export" settings, you can configure how images and Excalidraw drawings are embedded and exported within your documents. Key settings include choosing the image type for markdown preview (such as Native SVG or PNG), specifying the type of file to insert into the document (original Excalidraw, PNG, or SVG), and managing image caching for embedding in markdown. You can also control image sizing, whether to embed drawings using wiki links or markdown links, and adjust settings related to image themes, background colors, and Obsidian integration.
Additionally, there are settings for auto-export, which automatically generates SVG and/or PNG files to match the title of your Excalidraw drawings, keeping them in sync with file renames and deletions.`,
EMBED_PREVIEW_LINKS_HEAD: "Previews, links, and Canvas",
EMBED_PREVIEW_LINKS_DESC:
"Choose preview and inserted-file formats, source-link behavior, placeholders, and immersive Canvas embeds.",
EMBED_CANVAS: "Obsidian Canvas support",
EMBED_CANVAS_NAME: "Immersive embedding",
EMBED_CANVAS_DESC:
"Hide canvas node border and background when embedding an Excalidraw drawing to Canvas. " +
"Note that for a full transparent background for your image, you will still need to configure Excalidraw to export images with transparent background.",
EMBED_CACHING: "Image caching and rendering optimization",
EMBED_CACHING_DESC:
"Tune rendering concurrency and local image caches, purge cached images or backups, and optionally reuse exported previews.",
RENDERING_CONCURRENCY_NAME: "Image rendering concurrency",
RENDERING_CONCURRENCY_DESC:
"Number of parallel workers to use for image rendering. Increasing this number will speed up the rendering process, but may slow down the rest of the system. " +
@@ -1003,8 +1141,14 @@ export default {
"The practical impact is local disk or browser-storage usage inside Obsidian. This can matter on phones and on desktops with tighter browser storage quotas or limited free disk space.<br><br>" +
"Lower values reclaim local cache space sooner but may force more rerendering of PDFs and embedded drawings. Higher values keep repeat loads faster at the cost of more local cache storage.",
EXPORT_SUBHEAD: "Export Settings",
EXPORT_SUBHEAD_DESC:
"Configure PDF rendering and exported scene data, image dimensions, theme and background, PDF defaults, and automatic PNG/SVG copies.",
EMBED_SIZING: "Image sizing",
EMBED_SIZING_DESC:
"Set default embedded-image dimensions, PNG scale, and export padding.",
EMBED_THEME_BACKGROUND: "Image theme and background color",
EMBED_THEME_BACKGROUND_DESC:
"Choose exported-image background and theme behavior and whether previews follow Obsidian's theme.",
EMBED_IMAGE_CACHE_NAME: "Cache images for embedding in markdown",
EMBED_IMAGE_CACHE_DESC:
"Cache images for embedding in markdown. This will speed up the embedding process, but in case you compose images of several sub-component drawings, " +
@@ -1085,7 +1229,18 @@ export default {
"Embed Excalidraw scene in exported image. Can be overridden at a file level by adding the <code>excalidraw-export-embed-scene: true/false</code> frontmatter key. " +
"The setting only takes effect the next time you (re)open drawings.",
PDF_EXPORT_SETTINGS: "PDF Export Settings",
PDF_EXPORT_SETTINGS_DESC:
"Choose default PDF page size, orientation, tiling, margins, paper color, and alignment.",
PDF_EXPORT_DEFAULTS_CONTROL_NAME: "Default PDF export layout",
EXPORT_HEAD: "Auto-export Settings",
EXPORT_AUTOEXPORT_DESC:
"Keep exported files synchronized and automatically create SVG, PNG, light, and dark variants.",
SETTINGS_NAVIGATION_OPEN: "Open",
SETTINGS_BREADCRUMB_ARIA: "Settings path",
SETTINGS_RELATED_AUTOEXPORT_DESC:
"Enable automatic PNG or SVG copies to make those formats available in the inserted-file dropdown.",
SETTINGS_RELATED_EMBED_TYPE_DESC:
"Choose whether Excalidraw, PNG, or SVG is inserted when you embed a drawing in a document.",
EXPORT_SYNC_NAME:
"Keep the .SVG and/or .PNG filenames in sync with the drawing file",
EXPORT_SYNC_DESC:
@@ -1159,8 +1314,11 @@ export default {
CUSTOM_PEN_DESC:
"You will see these pens next to the Obsidian Menu on the canvas. You can customize the pens on the canvas by long-pressing the pen button.",
EXPERIMENTAL_HEAD: "Miscellaneous features",
EXPERIMENTAL_DESC: `These miscellaneous features in Excalidraw include options for setting default LaTeX formulas for new equations, enabling a Field Suggester for autocompletion, displaying type indicators for Excalidraw files, enabling immersive image embedding in live preview editing mode, and experimenting with Taskbone Optical Character Recognition for text extraction from images and drawings. Users can also enter a Taskbone API key for extended usage of the OCR service.`,
EXPERIMENTAL_DESC:
"Configure LaTeX defaults, file type indicators, live preview behavior, property suggestions, and the experimental Taskbone OCR integration.",
EA_HEAD: "Excalidraw Automate",
EA_GROUP_DESC:
"Configure Excalidraw Automate scripting, startup and autostart behavior, command links, and settings exposed by installed scripts.",
EA_DESC:
"ExcalidrawAutomate is a scripting and automation API for Excalidraw. Unfortunately, the documentation of the API is sparse. " +
`I recommend reading the <a href="${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_BLOB_MASTER_DOCS_API_EXCALIDRAWAUTOMATE_D_TS}">ExcalidrawAutomate.d.ts</a> file, ` +
@@ -1171,6 +1329,33 @@ export default {
FIELD_SUGGESTER_DESC:
"Field Suggester borrowed from Breadcrumbs and Templater plugins. The Field Suggester will show an autocomplete menu " +
"when you type <code>excalidraw-</code> or <code>ea.</code> with function description as hints on the individual items in the list.",
ALLOW_JS_FILES_NAME: "Load JavaScript files from the Scripts folder",
ALLOW_JS_FILES_DESC:
"When enabled, Excalidraw Automate monitors and runs <code>.js</code> files in the Scripts folder and accepts a <code>.js</code> startup script. " +
"By default, Obsidian Sync does not sync non-Markdown files, Obsidian does not open <code>.js</code> files for editing, and File Explorer hides them. Enable <b>Sync all other types</b> and <b>Show all file types</b> in Obsidian when needed. If matching <code>.md</code> and <code>.js</code> scripts exist, the Markdown file is used.",
STORE_SCRIPTS_AS_JS_NAME: "Store downloaded scripts as",
STORE_SCRIPTS_AS_JS_DESC:
"Choose the local file type used for new Script Library downloads and updates. This is independent of whether the remote source is <code>.md</code> or <code>.js</code>.",
SCRIPT_FILE_EXTENSION_MARKDOWN: "Markdown (.md)",
SCRIPT_FILE_EXTENSION_JAVASCRIPT: "JavaScript (.js)",
MIGRATE_SCRIPT_FILES_NAME: "Move existing script files",
MIGRATE_SCRIPTS_TO_JS_BUTTON: "Move existing scripts to .js",
MIGRATE_SCRIPTS_TO_MD_BUTTON: "Move existing scripts to .md",
MIGRATE_SCRIPT_FILES_STATUS:
"{eligible} script file(s) can be moved to {extension}. {skipped}",
MIGRATE_SCRIPT_FILES_CONFIRM:
"Back up your vault before continuing.<br><br><b>{count}</b> script file(s) will be renamed to <code>{extension}</code>. Pinned script paths will be updated. {startup} {skipped}",
MIGRATE_SCRIPT_FILES_STARTUP_INCLUDED:
"The configured startup script and its setting will also be updated.",
MIGRATE_SCRIPT_FILES_SKIPPED:
"{count} same-named .md/.js pair(s) will not be moved.",
MIGRATE_SCRIPT_FILES_SKIPPED_DETAILS:
"Skipped {count} script file(s) because the destination already exists:\n{files}",
MIGRATE_SCRIPT_FILES_NONE: "No eligible script files were found to move.",
MIGRATE_SCRIPT_FILES_COMPLETE:
"Moved {count} script file(s) to {extension}.",
MIGRATE_SCRIPT_FILES_FAILED:
"Could not move the script files. Completed renames were rolled back where possible.",
ENABLE_ONLOAD_SCRIPTS_NAME: "Enable onload scripts",
ENABLE_ONLOAD_SCRIPTS_CONFIRMATION:
"This file includes an <code>excalidraw-onload-script</code>. Do you want to enable onload scripts?",
@@ -1180,6 +1365,19 @@ export default {
"If enabled, Excalidraw will execute file-level <code>excalidraw-onload-script</code> code in all drawings you open from now on, until you disable this setting. " +
"This creates a risk if you download markdown files from unknown sources: a malicious actor can use <code>excalidraw-onload-script</code> " +
"to run any command in Obsidian and potentially transfer data to the internet. Only enable this if you trust the file and its source.",
AUTOSTART_SCRIPT_PROMPT:
"wants to run automatically every time you open an Excalidraw drawing. Do you want to allow this?",
AUTOSTART_SCRIPT_PROMPT_MANAGE_HINT:
'You can change this later from the Command Palette ("Autostart scripts") or in Settings → Excalidraw Automate → Autostart scripts.',
AUTOSTART_SCRIPT_ALLOW: "Autostart",
AUTOSTART_SCRIPT_DENY: "Manual start only",
AUTOSTART_SCRIPT_ASK_LATER: "Ask every time",
AUTOSTART_SCRIPTS_HEAD: "Autostart scripts",
AUTOSTART_SCRIPTS_DESC:
"Scripts appear here once they ask for permission to run automatically every time a new Excalidraw view opens (running the script once, manually, is what triggers the request). Change a script's setting at any time.",
AUTOSTART_SCRIPTS_EMPTY: "No scripts have requested autostart permission yet.",
AUTOSTART_SCRIPT_FAILED_WARNING:
"This script failed the last time it tried to autostart.",
ENABLE_COMMAND_LINKS_NAME: "Enable command links (cmd://)",
ENABLE_COMMAND_LINKS_CONFIRMATION:
"This link triggers an Obsidian command via <code>cmd://</code>. Do you want to enable command links?",
@@ -1190,9 +1388,10 @@ export default {
"This creates a risk if you open drawings from unknown sources: a malicious drawing can make a normal click trigger privileged commands. " +
"Only enable this if you trust the file and its source.",
STARTUP_SCRIPT_NAME: "Startup script",
STARTUP_SCRIPT_JS_DISABLED:
"JavaScript startup scripts are disabled. Enable JavaScript files in Excalidraw Automate settings first.",
STARTUP_SCRIPT_DESC:
"If set, excalidraw will execute the script at plugin startup. This is useful if you want to set any of the Excalidraw Automate hooks. The startup script is a markdown file " +
"that should contain the javascript code you want to execute when Excalidraw starts.",
"If set, Excalidraw will execute the script at plugin startup. This is useful for configuring Excalidraw Automate hooks. Extensionless paths use a Markdown file; <code>.js</code> files are accepted when JavaScript-file loading is enabled.",
STARTUP_SCRIPT_BUTTON_CREATE: "Create startup script",
STARTUP_SCRIPT_BUTTON_OPEN: "Open startup script",
FILETYPE_NAME: "Display type (✏️) for excalidraw.md files in File Explorer",
@@ -1236,6 +1435,8 @@ export default {
"For optimal performance, it is recommended to use a .woff2 file, as Excalidraw will encode only the necessary glyphs when exporting images to SVG. " +
"Other font formats will embed the entire font in the exported file, potentially resulting in significantly larger file sizes.",
OFFLINE_CJK_NAME: "Offline CJK font support",
OFFLINE_CJK_GROUP_DESC:
"Download and selectively preload Chinese, Japanese, and Korean fonts so Excalidraw can render them without an internet connection.",
OFFLINE_CJK_DESC: `<strong>Changes you make here will only take effect after restarting Obsidian.</strong><br>
Excalidraw.com offers handwritten CJK fonts. By default these fonts are not included in the plugin locally, but are served from the Internet.
If you prefer to keep Excalidraw fully local, allowing it to work without Internet access you can download the necessary <a href="${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_RAW_REFS_HEADS_MASTER_ASSETS_EXCALIDRAW_FONTS_ZIP}" target="_blank">font files from GitHub</a>.
@@ -1252,6 +1453,8 @@ export default {
SCRIPT_SETTINGS_DESC:
"Some of the Excalidraw Automate Scripts include settings. Settings are organized by script. Settings will only become visible in this list after you have executed the newly downloaded script once.",
TASKBONE_HEAD: "Taskbone Optical Character Recognition",
TASKBONE_GROUP_DESC:
"Configure the optional Taskbone online OCR service for extracting searchable text from drawings and images.",
TASKBONE_DESC:
"This is an experimental integration of optical character recognition into Excalidraw. Please note, that taskbone is an independent external service not provided by Excalidraw, nor the Excalidraw-Obsidian plugin project. " +
"The OCR service will grab legible text from freedraw lines and embedded pictures on your canvas and place the recognized text in the frontmatter of your drawing as well as onto clipboard. " +
@@ -1431,6 +1634,7 @@ export default {
PROMPT_BUTTON_NEVERMIND: "Nevermind",
PROMPT_BUTTON_OK: "OK",
PROMPT_BUTTON_CANCEL: "Cancel",
PROMPT_BUTTON_CLOSE: "Close",
PROMPT_BUTTON_INSERT_LINE: "Insert new line",
PROMPT_BUTTON_INSERT_SPACE: "Insert space",
PROMPT_BUTTON_INSERT_LINK: "Insert markdown link to file",
@@ -1457,6 +1661,7 @@ export default {
//InsertPDFModal.ts
IPM_PAGES_TO_IMPORT_NAME: "Pages to import",
IPM_PAGES_TO_IMPORT_DESC: "E.g.: 1,3-5,7,9-10",
IPM_SELECT_PAGES_TO_IMPORT: "Please select pages to import",
IPM_ADD_BORDER_BOX_NAME: "Add border box",
IPM_ADD_FRAME_NAME: "Add page to frame",
@@ -1793,4 +1998,20 @@ Thank you & Enjoy!
PEN_SETTINGS_CAP_END: "Cap End",
PEN_SETTINGS_SAVE: "Save Changes",
PEN_SETTINGS_CANCEL: "Cancel",
//ObserverManager.ts
ERROR_ADDING_OBSERVER_MANAGER: "Error adding ObserverManager",
//PublishOutOfDateFiles.ts
POODF_TITLE: "Out of date SVG files",
POODF_CHECK_RECURSIVE: "Check recursive",
POODF_OPEN_SELECTED: "Open selected",
//ImageCache.ts
IMAGE_CACHE_INITIALIZED:
"Excalidraw image cache is initialized - you may now retry opening your damaged drawing.",
//carveout.ts
NEW_DRAWING_TIMEOUT:
"File not found. New Excalidraw drawing is taking too long to create. Please try again.",
};
+252 -23
View File
@@ -19,6 +19,23 @@ export default {
// Sugester
SELECT_FILE_TO_INSERT: "Selecciona un archivo para insertar",
// main.ts
SETTINGS_DATA_INVALID:
"Excalidraw está esperando un archivo data.json válido. Los cambios no se guardarán hasta que se restaure el archivo o reinicies Obsidian y elijas Restablecer valores predeterminados.",
SETTINGS_DATA_REPAIRED_FROM_MEMORY:
"Se recibió y rechazó un archivo de configuración de Excalidraw vacío o ilegible. La configuración activa se volvió a guardar para reparar data.json.",
SETTINGS_DATA_RECOVERED:
"El archivo data.json de Excalidraw estaba vacío o no se podía leer. La última configuración válida se restauró automáticamente.",
SETTINGS_RECOVERY_MISSING_TITLE:
"Falta el archivo de configuración de Excalidraw",
SETTINGS_RECOVERY_MISSING_DESC:
"Existe una copia válida de la configuración en este dispositivo. Restaura la copia o restablece Excalidraw a los valores de fábrica. Al cerrar este mensaje se restaurará la copia.",
SETTINGS_RECOVERY_CORRUPT_TITLE:
"El archivo de configuración de Excalidraw está dañado",
SETTINGS_RECOVERY_CORRUPT_DESC:
"El archivo está vacío o no se puede leer y no hay una copia de recuperación en este dispositivo. Restablece Excalidraw a los valores de fábrica o deja el archivo sin cambios mientras restauras un data.json válido desde otra fuente. Al cerrar este mensaje se esperará un archivo de reemplazo.",
SETTINGS_RECOVERY_RESTORE_BACKUP: "Restaurar copia",
SETTINGS_RECOVERY_RESET_DEFAULTS: "Restablecer valores predeterminados",
SETTINGS_RECOVERY_WAIT_FOR_FILE: "Esperar archivo restaurado",
CONVERT_URL_TO_FILE: "Guardar imagen desde el URL en un archivo local",
UNZIP_CURRENT_FILE: "Descomprimir el archivo Excalidraw actual",
PUBLISH_SVG_CHECK:
@@ -44,6 +61,41 @@ export default {
CONVERT_FILE_REPLACE_EXT: "*.excalidraw => *.md (compatibilidad con Logseq)",
DOWNLOAD_LIBRARY:
"Exportar librería de plantillas como archivo *.excalidrawlib",
LIBRARY_MIGRATION_TITLE: "Mover la biblioteca de Excalidraw a la bóveda",
LIBRARY_MIGRATION_DESC:
"Excalidraw puede guardar la biblioteca en un archivo de la bóveda en lugar de data.json. Esto hace más estable el guardado. Los elementos existentes se combinarán con el archivo local seleccionado y también se cargarán los archivos *.excalidrawlib copiados en la misma carpeta. Elige «Más tarde» para ocultar este mensaje hasta mañana.",
LIBRARY_MIGRATION_SYNC_WARNING:
'Para sincronizar las bibliotecas con Obsidian Sync, activa "Sincronizar todos los demás tipos" en los ajustes de Sync.',
LIBRARY_MIGRATION_KEEP_DATA_JSON: "Seguir usando data.json",
LIBRARY_MIGRATION_LATER: "Más tarde",
LIBRARY_MIGRATION_MIGRATE: "Mover biblioteca",
LIBRARY_MIGRATION_SUCCESS: "La biblioteca de Excalidraw se movió a la bóveda.",
LIBRARY_MIGRATION_FAILED:
"No se pudo mover la biblioteca. La biblioteca original de data.json no se modificó.",
LIBRARY_FILE_READ_ERROR: "No se pudo leer la biblioteca: {PATH}",
LIBRARY_STORAGE_NAME: "Almacenamiento de la biblioteca",
LIBRARY_STORAGE_DESC:
"Los archivos de la bóveda ofrecen un guardado más estable al mantener la biblioteca fuera de data.json.",
LIBRARY_STORAGE_VAULT: "Carpeta de la bóveda (recomendado)",
LIBRARY_STORAGE_DATA_JSON: "data.json del complemento (heredado)",
LIBRARY_FOLDER_NAME: "Carpeta de bibliotecas",
LIBRARY_FOLDER_DESC:
"Carpeta para la biblioteca local y los archivos descargados. Los archivos de biblioteca usan la extensión .excalidrawlib. Para verlos en el explorador de archivos de Obsidian, activa «Mostrar todos los tipos de archivo» en los ajustes de Obsidian.",
LIBRARY_FILE_NAME: "Nombre del archivo de biblioteca local",
LIBRARY_FILE_DESC:
"Nombre de la biblioteca local editable. La extensión se añade automáticamente.",
LIBRARY_MIGRATE_NOW: "Mover la biblioteca ahora",
LIBRARY_MIGRATE_NOW_DESC:
"Mover la biblioteca existente de data.json al archivo configurado en la bóveda.",
LIBRARY_PATH_MISSING: "Esta ruta no existe actualmente en la bóveda.",
CREATE_FOLDER: "Crear carpeta",
CREATE_FOLDER_CONFIRM: "¿Quieres crear la carpeta <b>{PATH}</b>?",
CREATE_FOLDER_NEVER_MIND: "No importa",
CREATE_FOLDER_YES: "Sí",
CREATE_FOLDER_SUCCESS: "Carpeta creada: {PATH}",
CREATE_FOLDER_FAILED: "No se pudo crear la carpeta: {PATH}",
CREATE_FOLDER_PATH_IS_FILE:
"No se puede crear la carpeta porque ya existe un archivo en: {PATH}",
OPEN_EXISTING_NEW_PANE: "Abrir bosquejo existente - EN UN PANEL NUEVO",
OPEN_EXISTING_ACTIVE_PANE:
"Abrir bosquejo existente - EN EL PANEL ACTIVO ACTUAL",
@@ -103,32 +155,27 @@ export default {
MARKDOWN_IMAGE_APPEARANCE: "Apariencia",
MARKDOWN_IMAGE_WIDTH: "Ancho",
MARKDOWN_IMAGE_WIDTH_DESC: "Ancho del flujo Markdown en unidades del lienzo",
MARKDOWN_IMAGE_BOTTOM_PADDING: "Relleno inferior",
MARKDOWN_IMAGE_BOTTOM_PADDING_DESC:
"Espacio adicional debajo del Markdown renderizado, en píxeles",
MARKDOWN_IMAGE_FONT: "Fuente",
MARKDOWN_IMAGE_FONT_COLOR: "Color de fuente",
MARKDOWN_IMAGE_BORDER: "Borde",
MARKDOWN_IMAGE_BORDER_COLOR: "Color del borde",
MARKDOWN_IMAGE_THEME: "Tema",
MARKDOWN_IMAGE_THEME_DESC:
"Controla el contenido sensible al tema, como bloques de código, tablas, enlaces y llamadas.",
MARKDOWN_IMAGE_MATCH_CANVAS: "Coincidir con el lienzo",
MARKDOWN_IMAGE_LIGHT: "Claro",
MARKDOWN_IMAGE_DARK: "Oscuro",
MARKDOWN_IMAGE_CSS: "CSS",
MARKDOWN_IMAGE_CSS_DESC: "Reglas CSS aplicadas solo a esta imagen Markdown.",
MARKDOWN_IMAGE_CSS_DESC:
"CSS solo para esta imagen Markdown. Copia el SVG de abajo y pide a tu LLM preferido el CSS que necesitas.",
MARKDOWN_IMAGE_CSS_IMPORTANT_HINT:
"Si una regla no tiene efecto, añade !important a la declaración.",
MARKDOWN_IMAGE_CSS_DESKTOP_HELP:
"Para inspeccionar el marcado generado, abre la consola de desarrollo ({shortcut}) y ejecuta el comando disponible en el botón de copia.",
MARKDOWN_IMAGE_CSS_MOBILE_HELP:
"En un equipo de escritorio puedes inspeccionar el marcado generado en la consola de desarrollo y ejecutar el comando disponible en el botón de copia.",
MARKDOWN_IMAGE_CSS_EDITOR_ARIA: "Editor CSS para esta imagen Markdown",
MARKDOWN_IMAGE_TRANSCLUSION_CSS_EDITOR_ARIA:
"Editor CSS para Markdown transcluido",
MARKDOWN_IMAGE_INSERT_CSS_BOILERPLATE:
"Insertar una plantilla CSS comentada",
MARKDOWN_IMAGE_COPY_CSS_COMMAND:
"Copiar el comando de consola del SVG Markdown generado",
MARKDOWN_IMAGE_CSS_COMMAND_COPIED: "Comando de consola copiado",
MARKDOWN_IMAGE_COPY_SVG: "Copiar el SVG de la imagen Markdown actual",
MARKDOWN_IMAGE_SVG_COPIED: "SVG de la imagen Markdown copiado",
MARKDOWN_IMAGE_SVG_COPY_ERROR:
"No se pudo copiar el SVG de la imagen Markdown",
MARKDOWN_IMAGE_TRANSCLUSION_DIFFERENT_STYLE:
"Usar un estilo diferente para las transclusiones",
MARKDOWN_IMAGE_TRANSCLUSION_DIFFERENT_STYLE_DESC:
@@ -142,6 +189,7 @@ export default {
MARKDOWN_IMAGE_SET_DEFAULT: "Establecer como predeterminado",
MARKDOWN_IMAGE_SAVE_DEFAULT_ARIA:
"Guardar la configuración de apariencia actual como predeterminada",
MARKDOWN_IMAGE_DEFAULT_SAVED: "Valores predeterminados de imagen Markdown guardados",
MARKDOWN_IMAGE_RENDER_NOW: "Renderizar ahora",
MARKDOWN_IMAGE_UPDATING: "Actualizando imagen…",
MARKDOWN_IMAGE_EXTERNAL_SOURCE: "Fuente Markdown externa",
@@ -153,11 +201,15 @@ export default {
MARKDOWN_IMAGE_USE_SOURCE: "Usar fuente",
MARKDOWN_IMAGE_EXTRACT_LOCAL: "Extraer Markdown local a una nota",
MARKDOWN_IMAGE_EXTRACT: "Extraer a nota",
MARKDOWN_IMAGE_DUPLICATE_ERROR: "No se pudo duplicar la imagen Markdown",
MARKDOWN_IMAGE_SELECT_SOURCE: "Selecciona una nota, encabezado o bloque Markdown",
MARKDOWN_IMAGE_CHANGE_SOURCE_ERROR: "No se pudo cambiar la fuente de la imagen Markdown",
MARKDOWN_IMAGE_LOCAL_COPY_ERROR: "No se pudo crear una copia Markdown local",
MARKDOWN_IMAGE_EXTRACT_TITLE: "Extraer imagen Markdown a una nota",
MARKDOWN_IMAGE_EXTRACT_PATH: "Ruta de la nueva nota Markdown",
FILE_AND_FOLDER_SELECTOR_FOLDER: "Carpeta",
FILE_AND_FOLDER_SELECTOR_FILENAME: "Nombre del archivo",
FILE_AND_FOLDER_SELECTOR_EXPORT_TITLE: "Exportar a la bóveda",
FILE_AND_FOLDER_SELECTOR_EXPORT: "Exportar",
MARKDOWN_IMAGE_DEFAULT_NOTE: "Imagen Markdown.md",
MARKDOWN_IMAGE_CREATE_NOTE_ERROR: "No se pudo crear la nota Markdown",
MARKDOWN_IMAGE_UNKNOWN_ERROR: "Error desconocido",
@@ -178,6 +230,10 @@ export default {
MARKDOWN_IMAGE_SECTION_NAME: "Nombre de la sección al final de la nota",
MARKDOWN_IMAGE_SECTION_NAME_PLACEHOLDER:
"Introduce un nombre de sección único",
MARKDOWN_IMAGE_DELETE_TEXT_PROMPT:
"¿Eliminar el texto Markdown guardado para esta imagen? La imagen se eliminará de la escena en cualquier caso.",
MARKDOWN_IMAGE_KEEP_TEXT: "Conservar texto Markdown",
MARKDOWN_IMAGE_DELETE_TEXT: "Eliminar texto Markdown",
INSERT_PDF: "Insertar archivo PDF desde la bóveda",
INSERT_LAST_ACTIVE_PDF_PAGE_AS_IMAGE:
"Insertar última página PDF activa como imagen",
@@ -245,9 +301,6 @@ export default {
"Modo Invertido: La vinculación de flechas predeterminada está ahora deshabilitada. Usa CTRL/CMD para habilitar temporalmente la vinculación cuando sea necesario.",
ARROW_BINDING_NORMAL_MODE:
"Modo Normal: La vinculación de flechas está ahora habilitada. Usa CTRL/CMD para deshabilitar temporalmente la vinculación cuando sea necesario.",
EXPORT_FILENAME_PROMPT: "Por favor, ingresa el nombre de archivo",
EXPORT_FILENAME_PROMPT_PLACEHOLDER:
"nombre de archivo, dejar en blanco para cancelar la acción",
WARNING_SERIOUS_ERROR:
"ADVERTENCIA: ¡Excalidraw encontró un problema desconocido!\n\n" +
"Existe el riesgo de que tus cambios más recientes no se puedan guardar.\n\n" +
@@ -337,12 +390,22 @@ export default {
SEARCH_SHOWHIDE_ARIA: "Mostrar/Ocultar barra de búsqueda",
SEARCH_NEXT: "Siguiente",
SEARCH_PREVIOUS: "Anterior",
SETTINGS_TOOLBAR_COPY: "Copiar ajustes",
SETTINGS_TOOLBAR_NOTEBOOKLM: "NotebookLM",
SETTINGS_TOOLBAR_BUGS: "Errores",
SETTINGS_TOOLBAR_WIKI: "Wiki",
SETTINGS_TOOLBAR_YOUTUBE: "YouTube",
SETTINGS_TOOLBAR_LEARN: "Aprender",
SETTINGS_TOOLBAR_FOLLOW: "Twitter",
SETTINGS_TOOLBAR_READ: "Leer libro",
SETTINGS_TOOLBAR_KOFI: "Ko-fi",
USE_DECLARATIVE_SETTINGS_NAME: "Usar ajustes con búsqueda",
USE_DECLARATIVE_SETTINGS_DESC:
"Usa la interfaz de ajustes de Obsidian con búsqueda y varias páginas. Desactívala para usar los ajustes heredados de Excalidraw en una sola página. Requiere reiniciar Obsidian.",
//settings.ts
NOTEBOOKLM_LINK_ARIA:
"Pídele ayuda a NotebookLM sobre el complemento. Este modelo viene precargado con todas mis transcripciones de videos, notas de lanzamiento y otro contenido útil. Chatea con NotebookLM para explorar mis más de 250 videos y la documentación de Excalidraw.",
NOTEBOOKLM_LINK_TEXT:
"Aprende sobre el complemento. Accede a la base de conocimientos de NotebookLM.",
LINKS_BUGS_ARIA:
"Reporta errores y solicita nuevas funciones en la página de GitHub del complemento",
LINKS_BUGS: "Reportar Errores",
@@ -372,6 +435,15 @@ export default {
"<b><u>Desactivado:</u></b> Modo silencioso. Necesitarás verificar las actualizaciones del complemento en Complementos Comunitarios.",
BASIC_HEAD: "Básico",
BASIC_UPDATES_STARTUP_HEAD: "Actualizaciones e inicio",
BASIC_UPDATES_STARTUP_DESC:
"Notas de la versión, comprobaciones y avisos de actualizaciones, y la pantalla de inicio.",
BASIC_FILES_FOLDERS_HEAD: "Archivos y carpetas",
BASIC_FILES_FOLDERS_DESC:
"Carpetas y rutas predeterminadas para dibujos, recortes, anotaciones, plantillas y scripts de Excalidraw Automate.",
BASIC_STENCIL_LIBRARY_HEAD: "Biblioteca de elementos",
BASIC_STENCIL_LIBRARY_DESC:
"Elige dónde se guardan los datos de la biblioteca de elementos y configura su carpeta y archivo local.",
BASIC_DESC: `En la configuración "Básico", puedes configurar opciones como mostrar las notas de la versión después de las actualizaciones, recibir notificaciones de actualización del complemento, establecer la ubicación predeterminada para nuevos bosquejos, especificar la carpeta de Excalidraw para incrustar bosquejos en documentos activos, definir un archivo de plantilla de Excalidraw, y designar una carpeta de scripts de Excalidraw Automate para gestionar scripts de automatización.`,
FOLDER_NAME: "Carpeta de Excalidraw (¡Sensible a MAYÚSCULAS/minúsculas!)",
FOLDER_DESC:
@@ -585,6 +657,9 @@ export default {
AI_USAGE_SETTINGS_BUTTON_DESC:
"Ver el consumo de tokens de IA en la sesión actual de Obsidian desglosado por modelo. El uso se reinicia al reiniciar.",
SAVING_HEAD: "Guardar",
SAVING_STORAGE_AUTOSAVE_HEAD: "Almacenamiento y guardado automático",
SAVING_STORAGE_AUTOSAVE_DESC:
"Controla la compresión del JSON de los dibujos y los intervalos de guardado automático en escritorio y móvil.",
SAVING_DESC:
"En la sección 'Guardar' de la Configuración de Excalidraw, puedes configurar cómo se guardan tus bosquejos. Esto incluye opciones para comprimir el JSON de Excalidraw en Markdown, establecer intervalos de autoguardado para escritorio y móvil, definir formatos de nombre de archivo y elegir si usar la extensión de archivo .excalidraw.md o .md. ",
COMPRESS_NAME: "Comprimir JSON de Excalidraw en Markdown",
@@ -619,6 +694,8 @@ export default {
"Excalidraw no podrá guardar tu trabajo al cerrar Obsidian directamente (es decir, al deslizar la aplicación para cerrarla). También ten en cuenta que cuando cambias de aplicación en un dispositivo móvil, a veces Android e iOS cierran " +
"Obsidian en segundo plano para ahorrar recursos del sistema. En tal caso, Excalidraw no podrá guardar los últimos cambios.",
FILENAME_HEAD: "Nombre de archivo",
FILENAME_GROUP_DESC:
"Configura cómo se generan los nombres de dibujos nuevos, incrustados, recortados y anotados.",
FILENAME_DESC:
`<p>Haz click en este enlace para la <a href="${URLs.MOMENTJS_COM_DOCS}">` +
`referencia de formato de fecha y hora</a>.</p>`,
@@ -647,6 +724,9 @@ export default {
DISPLAY_HEAD: "Apariencia y Comportamiento de Excalidraw",
DISPLAY_DESC:
"En la sección 'Apariencia y Comportamiento' de la Configuración de Excalidraw, puedes ajustar cómo se ve y se comporta Excalidraw. Esto incluye opciones para estilos dinámicos, modo para zurdos, coincidencia de temas de Excalidraw y Obsidian, modos predeterminados y más.",
DISPLAY_EDITOR_PREVIEWS_HEAD: "Edición y vistas previas",
DISPLAY_EDITOR_PREVIEWS_DESC:
"Configura los gestos de edición del lienzo y cómo aparecen los archivos de Excalidraw en el modo de lectura y las vistas previas al pasar el cursor.",
OVERRIDE_OBSIDIAN_FONT_SIZE_NAME:
"Limitar tamaño de fuente de Obsidian al texto del editor",
OVERRIDE_OBSIDIAN_FONT_SIZE_DESC:
@@ -726,13 +806,22 @@ export default {
}'>Modo de Lectura de Markdown</a> en 'Apariencia y Comportamiento' más arriba.<br>` +
`⚠️ Debes cerrar y volver a abrir el archivo de Excalidraw/Markdown para que los cambios surtan efecto. ⚠️`,
MODES_HEAD: "Modos",
MODES_DESC:
"Elige diseños de interfaz específicos para cada dispositivo, controles de la barra de título y la posición de la bandeja para diestros o zurdos.",
HOTKEY_OVERRIDE_HEAD: "Anulaciones de atajos de teclado",
HOTKEY_OVERRIDE_GROUP_DESC:
"Administra las combinaciones de Excalidraw que deben tener prioridad sobre los atajos de Obsidian en conflicto.",
HOTKEY_OVERRIDE_CONTROL_NAME: "Administrar anulaciones de atajos",
HOTKEY_OVERRIDE_DESC:
`Algunos de los atajos de teclado de Excalidraw, como <code>${labelCTRL()}+Enter</code> para editar texto o <code>${labelCTRL()}+K</code> para crear un enlace de elemento ` +
"entran en conflicto con la configuración de atajos de teclado de Obsidian. Las combinaciones de atajos de teclado que agregues a continuación anularán la configuración de atajos de teclado de Obsidian mientras usas Excalidraw. Por lo tanto, " +
`puedes agregar <code>${labelCTRL()}+G</code> si quieres que el comportamiento predeterminado sea Agrupar Objeto en Excalidraw en lugar de abrir la Vista de Gráfico.`,
THEME_HEAD: "Tema y estilo",
THEME_DESC:
"Controla el estilo de la interfaz, los temas de dibujos e incrustaciones, el modo de apertura y el espacio seguro en móviles.",
ZOOM_AND_PAN_HEAD: "Zoom y panorámica",
ZOOM_AND_PAN_DESC:
"Configura el comportamiento del ratón, el tacto, la apertura, el cambio de tamaño y el intervalo de zoom.",
PAN_WITH_RIGHT_MOUSE_BUTTON_NAME:
"Desplazar el lienzo con el botón derecho del mouse (abrir menú con 'm')",
PAN_WITH_RIGHT_MOUSE_BUTTON_DESC:
@@ -766,7 +855,11 @@ export default {
ZOOM_MAX_DESC:
"Límite superior del zoom. Predeterminado: 3000%. Por lo general, no es necesario cambiarlo; se incluye para ser exhaustivos.",
PEN_HEAD: "Lápiz",
PEN_DESC:
"Configura el modo lápiz automático, los gestos táctiles, el borrador y la cruz de dibujo libre.",
GRID_HEAD: "Cuadrícula",
GRID_DESC:
"Configura la dirección de la cuadrícula, el color automático o personalizado y la opacidad.",
GRID_DYNAMIC_COLOR_NAME: "Color de cuadrícula dinámica",
GRID_DYNAMIC_COLOR_DESC:
"<b><u>Activado:</u></b> Cambia el color de la cuadrícula para que coincida con el color del lienzo<br><b><u>Desactivado:</u></bUsar el color de abajo como color de la cuadrícula",
@@ -781,6 +874,8 @@ export default {
GRID_HORIZONTAL: "Renderizar cuadrícula horizontal",
GRID_VERTICAL: "Renderizar cuadrícula vertical",
LASER_HEAD: "Puntero láser",
LASER_DESC:
"Configura el color del puntero láser y la rapidez y distancia con que se desvanece su rastro.",
LASER_COLOR: "Color del puntero láser",
LASER_DECAY_TIME_NAME: "Tiempo de desvanecimiento del puntero láser",
LASER_DECAY_TIME_DESC:
@@ -801,6 +896,21 @@ export default {
"Si no quieres que el texto cambie accidentalmente en tus bosquejos, usa <code>[[enlaces|con alias]]</code>.",
DRAG_MODIFIER_NAME:
"Teclas modificadoras para click de enlace y Arrastrar y Soltar(Drag&Drop)",
DRAG_MODIFIER_GROUP_DESC:
"Configura gestos para abrir enlaces y combinaciones de modificadores para clics y acciones de arrastrar y soltar.",
LINK_OPENING_GESTURES_HEAD: "Gestos para abrir enlaces",
LINK_OPENING_GESTURES_DESC:
"Configura retrasos de pulsación prolongada y la apertura con doble clic en dibujos incrustados y el modo de vista.",
WEB_BROWSER_DRAG_ACTION_DESC:
"Elige modificadores para enlaces, imágenes, importaciones e incrustaciones arrastradas desde un navegador web.",
LOCAL_FILE_DRAG_ACTION_DESC:
"Elige modificadores para enlaces, imágenes, importaciones e incrustaciones arrastradas desde el sistema operativo.",
INTERNAL_DRAG_ACTION_DESC:
"Elige modificadores para enlaces, imágenes, imágenes a tamaño completo e incrustaciones arrastradas dentro de Obsidian.",
PANE_TARGET_DESC:
"Elige combinaciones de modificadores que determinan dónde se abren los enlaces.",
MODIFIER_KEY_USAGE_NAME: "Configurar teclas modificadoras",
MODIFIER_KEY_COMBINATIONS: "Combinaciones de modificadores",
DRAG_MODIFIER_DESC:
`Comportamiento de la tecla modificadora al hacer click en enlaces y arrastrar y soltar elementos. ` +
`Excalidraw no validará tu configuración... presta atención para evitar configuraciones conflictivas. ` +
@@ -899,6 +1009,22 @@ export default {
"Usa <code>http" +
"s://noembed" +
".com/embed?url=</code> para obtener el título de la página al soltar un enlace HTTPS en Excalidraw.",
LINK_BEHAVIOR_HEAD: "Comportamiento de enlaces",
LINK_BEHAVIOR_DESC:
"Configura la sincronización, enlaces relacionados, vistas previas, clics y la búsqueda de títulos web.",
LINK_USAGE_NAME: "Usar enlaces en Excalidraw",
LINK_OPENING_HEAD: "Comportamiento de paneles y pestañas",
LINK_OPENING_DESC:
"Elige si los enlaces reutilizan, enfocan o cambian entre paneles, pestañas y el espacio de trabajo principal.",
LINK_APPEARANCE_HEAD: "Apariencia de enlaces",
LINK_APPEARANCE_DESC:
"Configura corchetes, prefijos, iconos y opacidad al mostrar enlaces.",
TODO_HEAD: "Tareas pendientes",
TODO_GROUP_DESC:
"Configura el análisis de tareas y los iconos para tareas abiertas y completadas.",
TRANSCLUSION_HEAD: "Transclusiones de texto",
TRANSCLUSION_DESC:
"Configura límites de caracteres, ajuste de línea y limpieza de citas para texto Markdown transcluido.",
PDF_TO_IMAGE: "PDF a Image",
PDF_TO_IMAGE_SCALE_NAME: "Escala de conversión de PDF a imagen",
PDF_TO_IMAGE_SCALE_DESC:
@@ -908,7 +1034,13 @@ export default {
EMBED_TOEXCALIDRAW_DESC:
"En la sección 'Incrustar archivos' de la Configuración de Excalidraw, puedes configurar cómo se incrustan varios tipos de archivos en Excalidraw. Esto incluye opciones para incrustar archivos Markdown interactivos, PDFs y archivos Markdown como imágenes.",
MD_HEAD: "Incrustar Markdown en Excalidraw como imagen",
MD_GROUP_DESC:
"Configura las dimensiones, la fuente, los colores, los bordes y el CSS de los archivos Markdown renderizados como imágenes.",
MD_EMBED_CUSTOMDATA_HEAD_NAME: "Archivos Markdown interactivos",
MD_EMBED_CUSTOMDATA_GROUP_DESC:
"Configura la edición y la apariencia predeterminada de futuras incrustaciones interactivas de Markdown.",
MD_EMBED_DEFAULTS_CONTROL_NAME:
"Valores predeterminados de apariencia de Markdown interactivo",
MD_EMBED_CUSTOMDATA_HEAD_DESC: `Las siguientes configuraciones solo afectarán a futuras incrustaciones. Las incrustaciones actuales no se modificarán. La configuración del tema de los marcos incrustados se encuentra en la sección "Apariencia y comportamiento de Excalidraw`,
MD_EMBED_SINGLECLICK_EDIT_NAME:
"Un solo click para editar Markdown incrustado",
@@ -954,19 +1086,30 @@ export default {
EMBED_HEAD: "Incrustar Excalidraw en tus notas y exportar",
EMBED_DESC: `En la configuración de "Incrustar y exportar", puedes configurar cómo se incrustan y exportan las imágenes y los bosquejos de Excalidraw en tus documentos. Las configuraciones clave incluyen elegir el tipo de imagen para la vista previa de Markdown (como SVG nativo o PNG), especificar el tipo de archivo a insertar en el documento (Excalidraw original, PNG o SVG) y gestionar el almacenamiento en caché de imágenes para incrustarlas en Markdown. También puedes controlar el tamaño de la imagen, si incrustar los bosquejos usando wikienlaces o enlaces Markdown y ajustar la configuración relacionada con los temas de imagen, colores de fondo y la integración de Obsidian.
Además, hay configuraciones para la autoexportación, que genera automáticamente archivos SVG y/o PNG que coinciden con el título de tus bosquejos de Excalidraw, manteniéndolos sincronizados con los cambios de nombre y eliminaciones de archivos.`,
EMBED_PREVIEW_LINKS_HEAD: "Vistas previas, enlaces y Canvas",
EMBED_PREVIEW_LINKS_DESC:
"Elige los formatos de vista previa y de archivo insertado, los enlaces de origen, los marcadores de posición y las incrustaciones inmersivas en Canvas.",
EMBED_CANVAS: "Soporte para Obsidian Canvas",
EMBED_CANVAS_NAME: "Incrustación inmersiva",
EMBED_CANVAS_DESC:
"Oculta el borde y el fondo del nodo del Canvas al incrustar un bosquejo de Excalidraw en un Canvas. " +
"Ten en cuenta que para un fondo completamente transparente en tu imagen, aún necesitarás configurar Excalidraw para que exporte las imágenes con fondo transparente.",
EMBED_CACHING: "Caché de imágenes y optimización de renderizado",
EMBED_CACHING_DESC:
"Ajusta la concurrencia de renderizado y las cachés locales, elimina imágenes o copias de seguridad almacenadas y reutiliza vistas previas exportadas.",
RENDERING_CONCURRENCY_NAME: "Concurrencia de renderizado de imágenes",
RENDERING_CONCURRENCY_DESC:
"Número de parallel workers(trabajadores paralelos) a usar para el renderizado de imágenes. Aumentar este número acelerará el proceso de renderizado, pero puede ralentizar el resto del sistema. " +
"El valor predeterminado es 3. Puedes aumentar este número si tienes un sistema potente.",
EXPORT_SUBHEAD: "Configuraciones de Exportación",
EXPORT_SUBHEAD_DESC:
"Configura el renderizado de PDF, los datos de escena exportados, las dimensiones, el tema y fondo, los valores predeterminados de PDF y las copias PNG/SVG automáticas.",
EMBED_SIZING: "Tamaño de imagen",
EMBED_SIZING_DESC:
"Define las dimensiones predeterminadas de las imágenes incrustadas, la escala PNG y el margen de exportación.",
EMBED_THEME_BACKGROUND: "Tema de la imagen y color de fondo",
EMBED_THEME_BACKGROUND_DESC:
"Elige el fondo y el tema de las imágenes exportadas y si las vistas previas siguen el tema de Obsidian.",
EMBED_IMAGE_CACHE_NAME:
"Guardar imágenes en caché para incrustar en Markdown",
EMBED_IMAGE_CACHE_DESC:
@@ -1052,7 +1195,19 @@ export default {
"Incrusta la escena de Excalidraw en la imagen exportada. Se puede anular a nivel de archivo añadiendo la clave frontmatter <code>excalidraw-export-embed-scene: true/false</code> . " +
"La configuración solo surtirá efecto la próxima vez que (re)abras los bosquejos.",
PDF_EXPORT_SETTINGS: "Configuración de exportación a PDF",
PDF_EXPORT_SETTINGS_DESC:
"Elige el tamaño de página, la orientación, la distribución, los márgenes, el color del papel y la alineación predeterminados del PDF.",
PDF_EXPORT_DEFAULTS_CONTROL_NAME:
"Diseño predeterminado de exportación a PDF",
EXPORT_HEAD: "Configuración de auto-exportación",
EXPORT_AUTOEXPORT_DESC:
"Mantén sincronizados los archivos exportados y crea automáticamente variantes SVG, PNG, claras y oscuras.",
SETTINGS_NAVIGATION_OPEN: "Abrir",
SETTINGS_BREADCRUMB_ARIA: "Ruta de configuración",
SETTINGS_RELATED_AUTOEXPORT_DESC:
"Activa las copias automáticas PNG o SVG para que esos formatos estén disponibles en el menú del tipo de archivo insertado.",
SETTINGS_RELATED_EMBED_TYPE_DESC:
"Elige si se inserta Excalidraw, PNG o SVG al incrustar un bosquejo en un documento.",
EXPORT_SYNC_NAME:
"Mantiene los nombres de archivo .SVG y/o .PNG sincronizados con el archivo del bosquejo",
EXPORT_SYNC_DESC:
@@ -1128,8 +1283,11 @@ export default {
CUSTOM_PEN_DESC:
"Verás estos lápices junto al Menú de Obsidian en el lienzo. Puedes personalizarlos manteniendo presionado el botón del lápiz en el lienzo.",
EXPERIMENTAL_HEAD: "Funcionalidades misceláneas",
EXPERIMENTAL_DESC: `Estas funcionalidades misceláneas en Excalidraw incluyen opciones para establecer fórmulas LaTeX predeterminadas para nuevas ecuaciones, habilitar un sugeridor de campos para autocompletar, mostrar indicadores de tipo para archivos de Excalidraw, habilitar la incrustación de imágenes inmersivas en el modo de edición de vista en vivo y experimentar con el Reconocimiento Óptico de Caracteres (OCR) de Taskbone para la extracción de texto de imágenes y bosquejos. Los usuarios también pueden ingresar una clave de API de Taskbone para un uso extendido del servicio de OCR.`,
EXPERIMENTAL_DESC:
"Configura los valores predeterminados de LaTeX, los indicadores de tipo de archivo, el comportamiento de la vista previa en vivo, las sugerencias de propiedades y la integración experimental de OCR con Taskbone.",
EA_HEAD: "Excalidraw Automate",
EA_GROUP_DESC:
"Configura los scripts de Excalidraw Automate, el comportamiento de inicio y autoarranque, los enlaces de comandos y los ajustes expuestos por los scripts instalados.",
EA_DESC:
"ExcalidrawAutomate es una API de scripting y automatización para Excalidraw. Desafortunadamente, la documentación de la API es escasa. " +
`Te recomiendo leer el archivo <a href="${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_BLOB_MASTER_DOCS_API_EXCALIDRAWAUTOMATE_D_TS}">ExcalidrawAutomate.d.ts</a>, ` +
@@ -1140,6 +1298,34 @@ export default {
FIELD_SUGGESTER_DESC:
"El sugeridor de campos, tomado de los complementos Breadcrumbs y Templater, mostrará un menú de autocompletar " +
"cuando escribas <code>excalidraw-</code> o <code>ea.</code> , con descripciones de las funciones como pistas para cada elemento en la lista.",
ALLOW_JS_FILES_NAME: "Cargar archivos JavaScript desde la carpeta Scripts",
ALLOW_JS_FILES_DESC:
"Cuando está activado, Excalidraw Automate supervisa y ejecuta archivos <code>.js</code> en la carpeta Scripts y acepta un script de inicio <code>.js</code>. " +
"De forma predeterminada, Obsidian Sync no sincroniza archivos que no sean Markdown, Obsidian no abre archivos <code>.js</code> para editarlos y el Explorador de archivos los oculta. Activa <b>Sincronizar todos los demás tipos</b> y <b>Mostrar todos los tipos de archivo</b> en Obsidian cuando sea necesario. Si existen scripts <code>.md</code> y <code>.js</code> con el mismo nombre, se utiliza el archivo Markdown.",
STORE_SCRIPTS_AS_JS_NAME: "Guardar los scripts descargados como",
STORE_SCRIPTS_AS_JS_DESC:
"Elige el tipo de archivo local para las nuevas descargas y actualizaciones de la Biblioteca de scripts. Es independiente de si la fuente remota es <code>.md</code> o <code>.js</code>.",
SCRIPT_FILE_EXTENSION_MARKDOWN: "Markdown (.md)",
SCRIPT_FILE_EXTENSION_JAVASCRIPT: "JavaScript (.js)",
MIGRATE_SCRIPT_FILES_NAME: "Mover archivos de script existentes",
MIGRATE_SCRIPTS_TO_JS_BUTTON: "Mover scripts existentes a .js",
MIGRATE_SCRIPTS_TO_MD_BUTTON: "Mover scripts existentes a .md",
MIGRATE_SCRIPT_FILES_STATUS:
"Se pueden mover {eligible} archivo(s) de script a {extension}. {skipped}",
MIGRATE_SCRIPT_FILES_CONFIRM:
"Haz una copia de seguridad de tu bóveda antes de continuar.<br><br>Se cambiará la extensión de <b>{count}</b> archivo(s) de script a <code>{extension}</code>. Se actualizarán las rutas de los scripts fijados. {startup} {skipped}",
MIGRATE_SCRIPT_FILES_STARTUP_INCLUDED:
"También se actualizarán el script de inicio configurado y su ajuste.",
MIGRATE_SCRIPT_FILES_SKIPPED:
"No se moverán {count} par(es) .md/.js con el mismo nombre.",
MIGRATE_SCRIPT_FILES_SKIPPED_DETAILS:
"Se omitieron {count} archivo(s) de script porque el destino ya existe:\n{files}",
MIGRATE_SCRIPT_FILES_NONE:
"No se encontraron archivos de script aptos para mover.",
MIGRATE_SCRIPT_FILES_COMPLETE:
"Se movieron {count} archivo(s) de script a {extension}.",
MIGRATE_SCRIPT_FILES_FAILED:
"No se pudieron mover los archivos de script. Los cambios completados se revirtieron cuando fue posible.",
ENABLE_ONLOAD_SCRIPTS_NAME: "Habilitar scripts de carga",
ENABLE_ONLOAD_SCRIPTS_CONFIRMATION:
"Este archivo incluye un <code>excalidraw-onload-script</code>. ¿Quieres habilitar los scripts de carga?",
@@ -1149,6 +1335,20 @@ export default {
"Si está habilitado, Excalidraw ejecutará el <code>excalidraw-onload-script</code> a nivel de archivo en todos los dibujos que abras a partir de ahora, hasta que desactives esta opción. " +
"Esto crea un riesgo si descargas archivos Markdown de fuentes desconocidas: un actor malicioso puede usar <code>excalidraw-onload-script</code> " +
"para ejecutar cualquier comando en Obsidian y potencialmente transferir datos a internet. Actívalo solo si confías en el archivo y en su origen.",
AUTOSTART_SCRIPT_PROMPT:
"quiere ejecutarse automáticamente cada vez que abras un dibujo de Excalidraw. ¿Deseas permitirlo?",
AUTOSTART_SCRIPT_PROMPT_MANAGE_HINT:
'Puedes cambiar esto más tarde desde la paleta de comandos ("Scripts de inicio automático") o en Ajustes → Excalidraw Automate → Scripts de inicio automático.',
AUTOSTART_SCRIPT_ALLOW: "Inicio automático",
AUTOSTART_SCRIPT_DENY: "Solo manual",
AUTOSTART_SCRIPT_ASK_LATER: "Preguntar cada vez",
AUTOSTART_SCRIPTS_HEAD: "Scripts de inicio automático",
AUTOSTART_SCRIPTS_DESC:
"Los scripts aparecen aquí una vez que solicitan permiso para ejecutarse automáticamente cada vez que se abre un nuevo dibujo de Excalidraw (ejecutar el script una vez manualmente es lo que activa la solicitud). Puedes cambiar el ajuste de un script en cualquier momento.",
AUTOSTART_SCRIPTS_EMPTY:
"Ningún script ha solicitado permiso de inicio automático todavía.",
AUTOSTART_SCRIPT_FAILED_WARNING:
"Este script falló la última vez que intentó iniciarse automáticamente.",
ENABLE_COMMAND_LINKS_NAME: "Habilitar enlaces de comandos (cmd://)",
ENABLE_COMMAND_LINKS_CONFIRMATION:
"Este enlace ejecuta un comando de Obsidian mediante <code>cmd://</code>. ¿Quieres habilitar los enlaces de comandos?",
@@ -1159,9 +1359,10 @@ export default {
"Esto crea un riesgo si abres dibujos de fuentes desconocidas: un dibujo malicioso puede hacer que un clic normal ejecute comandos privilegiados. " +
"Actívalo solo si confías en el archivo y en su origen.",
STARTUP_SCRIPT_NAME: "Script de inicio",
STARTUP_SCRIPT_JS_DISABLED:
"Los scripts de inicio JavaScript están desactivados. Primero habilita los archivos JavaScript en la configuración de Excalidraw Automate.",
STARTUP_SCRIPT_DESC:
"Si está configurado, Excalidraw ejecutará el script al iniciar el complemento. Esto es útil si quieres establecer cualquiera de los hooks de Excalidraw Automate. El script de inicio es un archivo Markdown " +
"que debe contener el código Javascript que quieres ejecutar cuando Excalidraw se inicie",
"Si está configurado, Excalidraw ejecutará el script al iniciar el complemento. Es útil para configurar hooks de Excalidraw Automate. Las rutas sin extensión utilizan un archivo Markdown; los archivos <code>.js</code> se aceptan cuando está habilitada la carga de archivos JavaScript.",
STARTUP_SCRIPT_BUTTON_CREATE: "Crear script de inicio",
STARTUP_SCRIPT_BUTTON_OPEN: "Abrir script de inicio",
FILETYPE_NAME:
@@ -1208,6 +1409,8 @@ export default {
"Otros formatos de fuente incrustarán la fuente completa en el archivo exportado, lo que podría resultar en tamaños de archivo significativamente mayores.",
OFFLINE_CJK_NAME:
"Soporte de fuentes CJK (chino, japonés y coreano) sin conexión",
OFFLINE_CJK_GROUP_DESC:
"Descarga y precarga de forma selectiva fuentes chinas, japonesas y coreanas para que Excalidraw pueda mostrarlas sin conexión a internet.",
OFFLINE_CJK_DESC: `<strong>Los cambios que hagas aquí solo se aplicarán después de reiniciar Obsidian.</strong><br>
Excalidraw.com ofrece fuentes CJK (chino, japonés, coreano) escritas a mano. Por defecto, estas fuentes no se incluyen en el complemento de forma local, sino que se obtienen de internet.
Si prefieres que Excalidraw funcione completamente sin conexión a internet, puedes descargar los <a href="${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_RAW_REFS_HEADS_MASTER_ASSETS_EXCALIDRAW_FONTS_ZIP}" target="_blank">archivos de fuentes necesarios desde GitHub</a>.
@@ -1226,6 +1429,8 @@ export default {
SCRIPT_SETTINGS_DESC:
"Algunos de los scripts de Excalidraw Automate incluyen configuraciones. Las configuraciones están organizadas por script. Solo se harán visibles en esta lista después de que hayas ejecutado el script recién descargado al menos una vez.",
TASKBONE_HEAD: "Reconocimiento Óptico de Caracteres de Taskbone",
TASKBONE_GROUP_DESC:
"Configura el servicio opcional de OCR en línea Taskbone para extraer texto que se pueda buscar de dibujos e imágenes.",
TASKBONE_DESC:
"Esta es una integración experimental del reconocimiento óptico de caracteres en Excalidraw. Ten en cuenta que Taskbone es un servicio externo independiente y no es proporcionado por Excalidraw ni por el proyecto del complemento Excalidraw-Obsidian. " +
"El servicio de OCR capturará texto legible de las líneas de dibujo a mano alzada y de las imágenes incrustadas en tu lienzo y colocará el texto reconocido en el frontmatter de tu bosquejo, así como en el portapapeles. " +
@@ -1393,6 +1598,7 @@ export default {
PROMPT_BUTTON_NEVERMIND: "No importa",
PROMPT_BUTTON_OK: "OK",
PROMPT_BUTTON_CANCEL: "Cancelar",
PROMPT_BUTTON_CLOSE: "Cerrar",
PROMPT_BUTTON_INSERT_LINE: "Insertar nueva línea",
PROMPT_BUTTON_INSERT_SPACE: "Insertar espacio",
PROMPT_BUTTON_INSERT_LINK: "Insertar enlace Markdown a un archivo",
@@ -1420,6 +1626,7 @@ export default {
//InsertPDFModal.ts
IPM_PAGES_TO_IMPORT_NAME: "Páginas para importar",
IPM_PAGES_TO_IMPORT_DESC: "P. ej.: 1,3-5,7,9-10",
IPM_SELECT_PAGES_TO_IMPORT: "Por favor, selecciona las páginas para importar",
IPM_ADD_BORDER_BOX_NAME: "Añadir recuadro de borde",
IPM_ADD_FRAME_NAME: "Añadir página a un marco(frame)",
@@ -1628,4 +1835,26 @@ Si quieres ver lo que ya es posible hoy, aquí tienes una presentación de las f
"Puede volver a habilitar esto en: Opciones → Excalidraw → Básico → Advertir sobre actualizaciones de complementos incompletos.",
VERSION_MISMATCH_REDOWNLOAD: "Volver a descargar complemento",
VERSION_MISMATCH_IGNORE: "Ignorar",
//Taskbone.ts
OCR_ABORT_NO_ELEMENTS:
"Cancelando el OCR porque no hay elementos de imagen o dibujo a mano alzada en el lienzo.",
OCR_ALREADY_PROCESSED:
"El dibujo ya ha sido procesado, encontrará el resultado en el frontmatter en modo de vista Markdown. Si ejecutó el comando desde el panel de Obsidian en Excalidraw, puede hacer ctrl(cmd)+clic en el comando para forzar el reescaneo.",
//ObserverManager.ts
ERROR_ADDING_OBSERVER_MANAGER: "Error al añadir ObserverManager",
//PublishOutOfDateFiles.ts
POODF_TITLE: "Archivos SVG desactualizados",
POODF_CHECK_RECURSIVE: "Comprobar de forma recursiva",
POODF_OPEN_SELECTED: "Abrir seleccionados",
//ImageCache.ts
IMAGE_CACHE_INITIALIZED:
"La caché de imágenes de Excalidraw se ha inicializado - ahora puede volver a intentar abrir su dibujo dañado.",
//carveout.ts
NEW_DRAWING_TIMEOUT:
"Archivo no encontrado. El nuevo dibujo de Excalidraw está tardando demasiado en crearse. Inténtelo de nuevo.",
};
+254 -21
View File
@@ -15,6 +15,21 @@ import {
// русский
export default {
// main.ts
SETTINGS_DATA_INVALID:
"Excalidraw ожидает корректный файл data.json. Изменения настроек не будут сохранены, пока файл не будет восстановлен или вы не перезапустите Obsidian и не выберете сброс настроек.",
SETTINGS_DATA_REPAIRED_FROM_MEMORY:
"Получен пустой или нечитаемый файл настроек Excalidraw, поэтому он был отклонён. Активные настройки записаны обратно для восстановления data.json.",
SETTINGS_DATA_RECOVERED:
"Файл Excalidraw data.json был пуст или недоступен для чтения. Последняя исправная версия настроек восстановлена автоматически.",
SETTINGS_RECOVERY_MISSING_TITLE: "Файл настроек Excalidraw отсутствует",
SETTINGS_RECOVERY_MISSING_DESC:
"На этом устройстве есть последняя исправная резервная копия настроек. Восстановите её или сбросьте Excalidraw к заводским настройкам. При закрытии этого сообщения будет восстановлена резервная копия.",
SETTINGS_RECOVERY_CORRUPT_TITLE: "Файл настроек Excalidraw повреждён",
SETTINGS_RECOVERY_CORRUPT_DESC:
"Файл пуст или недоступен для чтения, а резервная копия на этом устройстве отсутствует. Сбросьте Excalidraw к заводским настройкам или оставьте файл без изменений, пока восстанавливаете корректный data.json из другого источника. При закрытии этого сообщения Excalidraw будет ждать замену файла.",
SETTINGS_RECOVERY_RESTORE_BACKUP: "Восстановить копию",
SETTINGS_RECOVERY_RESET_DEFAULTS: "Сбросить настройки",
SETTINGS_RECOVERY_WAIT_FOR_FILE: "Ждать восстановленный файл",
CONVERT_URL_TO_FILE: "Сохранить изображение из URL в локальный файл",
UNZIP_CURRENT_FILE: "Распаковать текущий файл Excalidraw",
PUBLISH_SVG_CHECK:
@@ -39,6 +54,41 @@ export default {
CONVERT_FILE_KEEP_EXT: "*.excalidraw => *.excalidraw.md",
CONVERT_FILE_REPLACE_EXT: "*.excalidraw => *.md (совместимость с Logseq)",
DOWNLOAD_LIBRARY: "Экспорт библиотеки трафаретов в файл *.excalidrawlib",
LIBRARY_MIGRATION_TITLE: "Перенести библиотеку Excalidraw в хранилище",
LIBRARY_MIGRATION_DESC:
"Excalidraw может хранить библиотеку в отдельном файле хранилища вместо data.json. Это делает сохранение стабильнее. Существующие элементы будут объединены с выбранным локальным файлом; файлы *.excalidrawlib в той же папке также будут загружены. Выберите «Позже», чтобы скрыть это сообщение до завтра.",
LIBRARY_MIGRATION_SYNC_WARNING:
'Для синхронизации файлов библиотеки включите «Синхронизировать все остальные типы» в настройках Obsidian Sync.',
LIBRARY_MIGRATION_KEEP_DATA_JSON: "Оставить в data.json",
LIBRARY_MIGRATION_LATER: "Позже",
LIBRARY_MIGRATION_MIGRATE: "Перенести библиотеку",
LIBRARY_MIGRATION_SUCCESS: "Библиотека Excalidraw перенесена в хранилище.",
LIBRARY_MIGRATION_FAILED:
"Не удалось перенести библиотеку. Исходная библиотека data.json не изменена.",
LIBRARY_FILE_READ_ERROR: "Не удалось прочитать файл библиотеки: {PATH}",
LIBRARY_STORAGE_NAME: "Хранилище библиотеки",
LIBRARY_STORAGE_DESC:
"Файлы хранилища делают сохранение стабильнее, поскольку библиотека находится вне data.json.",
LIBRARY_STORAGE_VAULT: "Папка хранилища (рекомендуется)",
LIBRARY_STORAGE_DATA_JSON: "data.json плагина (устаревшее)",
LIBRARY_FOLDER_NAME: "Папка библиотеки",
LIBRARY_FOLDER_DESC:
"Папка для локальной библиотеки и загруженных файлов. Файлы библиотек имеют расширение .excalidrawlib. Чтобы видеть их в проводнике файлов Obsidian, включите «Показывать все типы файлов» в настройках Obsidian.",
LIBRARY_FILE_NAME: "Имя файла локальной библиотеки",
LIBRARY_FILE_DESC:
"Имя редактируемого файла локальной библиотеки. Расширение добавляется автоматически.",
LIBRARY_MIGRATE_NOW: "Перенести библиотеку сейчас",
LIBRARY_MIGRATE_NOW_DESC:
"Перенести существующую библиотеку data.json в настроенный файл хранилища.",
LIBRARY_PATH_MISSING: "Этот путь сейчас не существует в хранилище.",
CREATE_FOLDER: "Создать папку",
CREATE_FOLDER_CONFIRM: "Создать папку <b>{PATH}</b>?",
CREATE_FOLDER_NEVER_MIND: "Не надо",
CREATE_FOLDER_YES: "Да",
CREATE_FOLDER_SUCCESS: "Папка создана: {PATH}",
CREATE_FOLDER_FAILED: "Не удалось создать папку: {PATH}",
CREATE_FOLDER_PATH_IS_FILE:
"Невозможно создать папку: по этому пути уже существует файл: {PATH}",
OPEN_EXISTING_NEW_PANE: "Открыть существующий чертеж - В НОВОЙ ПАНЕЛИ",
OPEN_EXISTING_ACTIVE_PANE:
"Открыть существующий чертеж - В ТЕКУЩЕЙ АКТИВНОЙ ПАНЕЛИ",
@@ -94,33 +144,27 @@ export default {
MARKDOWN_IMAGE_APPEARANCE: "Оформление",
MARKDOWN_IMAGE_WIDTH: "Ширина",
MARKDOWN_IMAGE_WIDTH_DESC: "Ширина потока Markdown в единицах холста",
MARKDOWN_IMAGE_BOTTOM_PADDING: "Нижний отступ",
MARKDOWN_IMAGE_BOTTOM_PADDING_DESC:
"Дополнительное пространство под отрисованным Markdown в пикселях",
MARKDOWN_IMAGE_FONT: "Шрифт",
MARKDOWN_IMAGE_FONT_COLOR: "Цвет шрифта",
MARKDOWN_IMAGE_BORDER: "Рамка",
MARKDOWN_IMAGE_BORDER_COLOR: "Цвет рамки",
MARKDOWN_IMAGE_THEME: "Тема",
MARKDOWN_IMAGE_THEME_DESC:
"Управляет зависящим от темы содержимым: блоками кода, таблицами, ссылками и выносками.",
MARKDOWN_IMAGE_MATCH_CANVAS: "Как на холсте",
MARKDOWN_IMAGE_LIGHT: "Светлая",
MARKDOWN_IMAGE_DARK: "Тёмная",
MARKDOWN_IMAGE_CSS: "CSS",
MARKDOWN_IMAGE_CSS_DESC:
"Правила CSS применяются только к этому Markdown-изображению.",
"CSS только для этого Markdown-изображения. Скопируйте SVG ниже и попросите предпочитаемую LLM подобрать нужный CSS.",
MARKDOWN_IMAGE_CSS_IMPORTANT_HINT:
"Если правило не действует, добавьте !important к объявлению.",
MARKDOWN_IMAGE_CSS_DESKTOP_HELP:
"Чтобы проверить созданную разметку, откройте консоль разработчика ({shortcut}) и выполните команду, доступную по кнопке копирования.",
MARKDOWN_IMAGE_CSS_MOBILE_HELP:
"На компьютере созданную разметку можно проверить в консоли разработчика и выполнить команду, доступную по кнопке копирования.",
MARKDOWN_IMAGE_CSS_EDITOR_ARIA: "Редактор CSS для этого Markdown-изображения",
MARKDOWN_IMAGE_TRANSCLUSION_CSS_EDITOR_ARIA:
"Редактор CSS для встроенного Markdown",
MARKDOWN_IMAGE_INSERT_CSS_BOILERPLATE:
"Вставить шаблон CSS с комментариями",
MARKDOWN_IMAGE_COPY_CSS_COMMAND:
"Копировать консольную команду для созданного Markdown SVG",
MARKDOWN_IMAGE_CSS_COMMAND_COPIED: "Консольная команда скопирована",
MARKDOWN_IMAGE_COPY_SVG: "Копировать SVG текущего Markdown-изображения",
MARKDOWN_IMAGE_SVG_COPIED: "SVG Markdown-изображения скопирован",
MARKDOWN_IMAGE_SVG_COPY_ERROR:
"Не удалось скопировать SVG Markdown-изображения",
MARKDOWN_IMAGE_TRANSCLUSION_DIFFERENT_STYLE:
"Использовать отдельный стиль для встраиваний",
MARKDOWN_IMAGE_TRANSCLUSION_DIFFERENT_STYLE_DESC:
@@ -134,6 +178,7 @@ export default {
MARKDOWN_IMAGE_SET_DEFAULT: "Сделать по умолчанию",
MARKDOWN_IMAGE_SAVE_DEFAULT_ARIA:
"Сохранить текущие настройки оформления как настройки по умолчанию",
MARKDOWN_IMAGE_DEFAULT_SAVED: "Настройки Markdown-изображения сохранены",
MARKDOWN_IMAGE_RENDER_NOW: "Отобразить сейчас",
MARKDOWN_IMAGE_UPDATING: "Обновление изображения…",
MARKDOWN_IMAGE_EXTERNAL_SOURCE: "Внешний источник Markdown",
@@ -145,11 +190,15 @@ export default {
MARKDOWN_IMAGE_USE_SOURCE: "Использовать источник",
MARKDOWN_IMAGE_EXTRACT_LOCAL: "Извлечь локальный Markdown в заметку",
MARKDOWN_IMAGE_EXTRACT: "Извлечь в заметку",
MARKDOWN_IMAGE_DUPLICATE_ERROR: "Не удалось дублировать Markdown-изображение",
MARKDOWN_IMAGE_SELECT_SOURCE: "Выберите Markdown-заметку, заголовок или блок",
MARKDOWN_IMAGE_CHANGE_SOURCE_ERROR: "Не удалось изменить источник Markdown-изображения",
MARKDOWN_IMAGE_LOCAL_COPY_ERROR: "Не удалось создать локальную копию Markdown",
MARKDOWN_IMAGE_EXTRACT_TITLE: "Извлечь Markdown-изображение в заметку",
MARKDOWN_IMAGE_EXTRACT_PATH: "Путь к новой Markdown-заметке",
FILE_AND_FOLDER_SELECTOR_FOLDER: "Папка",
FILE_AND_FOLDER_SELECTOR_FILENAME: "Имя файла",
FILE_AND_FOLDER_SELECTOR_EXPORT_TITLE: "Экспорт в хранилище",
FILE_AND_FOLDER_SELECTOR_EXPORT: "Экспортировать",
MARKDOWN_IMAGE_DEFAULT_NOTE: "Markdown-изображение.md",
MARKDOWN_IMAGE_CREATE_NOTE_ERROR: "Не удалось создать Markdown-заметку",
MARKDOWN_IMAGE_UNKNOWN_ERROR: "Неизвестная ошибка",
@@ -173,6 +222,10 @@ export default {
MARKDOWN_IMAGE_SECTION_NAME: "Название раздела в конце заметки",
MARKDOWN_IMAGE_SECTION_NAME_PLACEHOLDER:
"Введите уникальное название раздела",
MARKDOWN_IMAGE_DELETE_TEXT_PROMPT:
"Удалить текст Markdown, сохранённый для этого изображения? Само изображение будет удалено со сцены в любом случае.",
MARKDOWN_IMAGE_KEEP_TEXT: "Сохранить текст Markdown",
MARKDOWN_IMAGE_DELETE_TEXT: "Удалить текст Markdown",
INSERT_PDF: "Вставить PDF-файл из хранилища",
UNIVERSAL_ADD_FILE: "Вставка ЛЮБОГО файла",
// Compatibility keys consumed by upstream Excalidraw via ExcalidrawPlugin.getLabel().
@@ -247,9 +300,6 @@ export default {
"Инвертированный режим: Привязка стрелок по умолчанию теперь отключена. Используйте CTRL/CMD, чтобы временно включить привязку, когда это необходимо.",
ARROW_BINDING_NORMAL_MODE:
"Обычный режим: Привязка стрелок теперь включена. Используйте CTRL/CMD, чтобы временно отключить привязку при необходимости.",
EXPORT_FILENAME_PROMPT: "Пожалуйста, укажите имя файла",
EXPORT_FILENAME_PROMPT_PLACEHOLDER:
"имя файла, оставьте пустым, чтобы отменить действие",
WARNING_SERIOUS_ERROR:
"ПРЕДУПРЕЖДЕНИЕ: Excalidraw столкнулся с неизвестной проблемой!\n\n" +
"Есть риск, что последние изменения не будут сохранены.\n\n" +
@@ -317,6 +367,18 @@ export default {
"Для повышения производительности рассмотрите возможность разделения больших рисунков на несколько файлов меньшего размера.",
//settings.ts
SETTINGS_TOOLBAR_COPY: "Копировать настройки",
SETTINGS_TOOLBAR_NOTEBOOKLM: "NotebookLM",
SETTINGS_TOOLBAR_BUGS: "Ошибки",
SETTINGS_TOOLBAR_WIKI: "Вики",
SETTINGS_TOOLBAR_YOUTUBE: "YouTube",
SETTINGS_TOOLBAR_LEARN: "Обучение",
SETTINGS_TOOLBAR_FOLLOW: "Twitter",
SETTINGS_TOOLBAR_READ: "Читать книгу",
SETTINGS_TOOLBAR_KOFI: "Ko-fi",
USE_DECLARATIVE_SETTINGS_NAME: "Использовать настройки с поиском",
USE_DECLARATIVE_SETTINGS_DESC:
"Использовать многостраничный интерфейс настроек Obsidian с поиском. Отключите, чтобы использовать прежнюю одностраничную страницу настроек Excalidraw. Требуется перезапуск Obsidian.",
RELEASE_NOTES_NAME: "Отображение информации о выпуске после обновления",
RELEASE_NOTES_DESC:
`<b><u>Переключатель ВКЛ:</u></b> Отображение информации о выпуске при каждом обновлении Excalidraw до новой версии.<br>` +
@@ -331,6 +393,15 @@ export default {
"<b><u>Переключатель ВЫКЛ:</u></b> Тихий режим. Вам необходимо проверить обновления плагинов в разделе Community Plugins.",
BASIC_HEAD: "Основные",
BASIC_UPDATES_STARTUP_HEAD: "Обновления и запуск",
BASIC_UPDATES_STARTUP_DESC:
"Примечания к выпуску, проверка и уведомления об обновлениях, а также заставка при запуске.",
BASIC_FILES_FOLDERS_HEAD: "Файлы и папки",
BASIC_FILES_FOLDERS_DESC:
"Папки и пути по умолчанию для рисунков, обрезок, аннотаций, шаблонов и скриптов Excalidraw Automate.",
BASIC_STENCIL_LIBRARY_HEAD: "Библиотека элементов",
BASIC_STENCIL_LIBRARY_DESC:
"Выберите место хранения библиотеки элементов и настройте её папку в хранилище и локальный файл.",
BASIC_DESC: `В настройках "Основные" можно настроить такие параметры, как отображение заметок о выпуске после обновлений, получение уведомлений об обновлении плагинов, установка местоположения по умолчанию для новых чертежей, указание папки Excalidraw для вставки чертежей в активные документы, определение файла шаблона Excalidraw и указание папки сценария Excalidraw Automate для управления сценариями автоматизации.`,
FOLDER_NAME: "Папка Excalidraw",
FOLDER_DESC:
@@ -529,6 +600,9 @@ export default {
AI_USAGE_SETTINGS_BUTTON_DESC:
"Просмотр потребления токенов ИИ в текущей сессии Obsidian с разбивкой по моделям. Данные сбрасываются при перезапуске.",
SAVING_HEAD: "Сохранение",
SAVING_STORAGE_AUTOSAVE_HEAD: "Хранение и автосохранение",
SAVING_STORAGE_AUTOSAVE_DESC:
"Настройте сжатие JSON рисунков и интервалы автосохранения на компьютере и мобильных устройствах.",
SAVING_DESC:
"В разделе 'Сохранение' раздела Настройки Excalidraw вы можете настроить способ сохранения ваших чертежей. Сюда входят опции сжатия Excalidraw JSON в Markdown, установки интервалов автосохранения для настольных и мобильных компьютеров, определения форматов имен файлов, а также выбора расширения файла .excalidraw.md или .md. ",
COMPRESS_NAME: "Сжатие Excalidraw JSON в формате Markdown",
@@ -564,6 +638,8 @@ export default {
"Excalidraw не сможет сохранить вашу работу при прямом завершении работы Obsidian (т.е. смахнув ее). Также обратите внимание, что при переключении приложений на мобильном устройстве, иногда Android и iOS закрываются " +
"Obsidian в фоновом режиме для экономии системных ресурсов. В этом случае Excalidraw не сможет сохранить последние изменения.",
FILENAME_HEAD: "Имя файла",
FILENAME_GROUP_DESC:
"Настройте создание имён новых, встроенных, обрезанных и аннотированных рисунков.",
FILENAME_DESC:
`<p>Нажмите на эту ссылку, чтобы получить <a href="${URLs.MOMENTJS_COM_DOCS}">` +
`справочник по формату даты и времени</a>.</p>`,
@@ -591,6 +667,9 @@ export default {
DISPLAY_HEAD: "Внешний вид и поведение Excalidraw",
DISPLAY_DESC:
"В разделе 'Внешний вид и поведение' раздела Настройки Excalidraw вы можете настроить внешний вид и поведение Excalidraw. Сюда входят опции динамической стилизации, режима для левой руки, соответствия тем Excalidraw и Obsidian, режимов по умолчанию и многое другое.",
DISPLAY_EDITOR_PREVIEWS_HEAD: "Редактирование и предпросмотр",
DISPLAY_EDITOR_PREVIEWS_DESC:
"Настройте жесты редактирования холста и отображение файлов Excalidraw в режиме чтения и предпросмотре при наведении.",
DYNAMICSTYLE_NAME: "Динамическая стилизация",
DYNAMICSTYLE_DESC:
"Изменение цветов пользовательского интерфейса Excalidraw в соответствии с цветом холста",
@@ -653,13 +732,23 @@ export default {
"<li>Если <b>заблокировать</b>, то в PDF будет отображаться разметка документа.</li></ul>" +
`См. другие связанные настройки для <a href='#${TAG_MDREADINGMODE}'>режима чтения разметки</a> в разделе 'Внешний вид и поведение' выше.<br>` +
"⚠️ Обратите внимание, что необходимо закрыть активный файл excalidraw/markdown и открыть его снова, чтобы изменения вступили в силу. ⚠️",
MODES_HEAD: "Режимы интерфейса",
MODES_DESC:
"Выберите интерфейс Excalidraw для каждого устройства, кнопки заголовка и расположение панели для правой или левой руки.",
HOTKEY_OVERRIDE_HEAD: "Переопределение горячих клавиш",
HOTKEY_OVERRIDE_GROUP_DESC:
"Управляйте сочетаниями Excalidraw, которые должны иметь приоритет над конфликтующими горячими клавишами Obsidian.",
HOTKEY_OVERRIDE_CONTROL_NAME: "Управление переопределениями клавиш",
HOTKEY_OVERRIDE_DESC:
`Некоторые горячие клавиши Excalidraw, такие как <code>${labelCTRL()}+Enter</code> для редактирования текста или <code>${labelCTRL()}+K</code> создания ссылки на элемент ` +
"конфликтуют с настройками горячих клавиш Obsidian. Комбинации горячих клавиш, которые вы добавите ниже, отменят настройки горячих клавиш Obsidian при использовании Excalidraw, таким образом " +
`Вы можете добавить <code>${labelCTRL()}+G</code>, если хотите по умолчанию перейти к Группе Объектов в Excalidraw вместо открытия Режима просмотра Графиков.`,
THEME_HEAD: "Тема и стиль",
THEME_DESC:
"Настройте стиль интерфейса, темы рисунков и вставок, режим открытия и безопасные отступы на мобильных устройствах.",
ZOOM_AND_PAN_HEAD: "Масштаб и панорамирование",
ZOOM_AND_PAN_DESC:
"Настройте поведение мыши, сенсорного ввода, открытия, изменения размера и диапазона масштаба.",
PAN_WITH_RIGHT_MOUSE_BUTTON_NAME:
"Перемещение холста правой кнопкой мыши (открыть меню с 'm')",
PAN_WITH_RIGHT_MOUSE_BUTTON_DESC:
@@ -684,7 +773,12 @@ export default {
"Увеличение до максимального уровня масштабирования",
ZOOM_TO_FIT_MAX_LEVEL_DESC:
"Установите максимальный уровень, до которого масштабирование будет увеличивать чертеж. Минимальное значение - 0,5 (50 %), максимальное - 10 (1000 %).",
PEN_HEAD: "Перо",
PEN_DESC:
"Настройте автоматический режим пера, сенсорные жесты, ластик и перекрестие свободного рисования.",
GRID_HEAD: "Сетка",
GRID_DESC:
"Настройте направление сетки, автоматический или пользовательский цвет и прозрачность.",
GRID_DYNAMIC_COLOR_NAME: "Динамический цвет сетки",
GRID_DYNAMIC_COLOR_DESC:
"<b><u>Переключатель ВКЛ:</u></b>Измените цвет сетки, чтобы он соответствовал цвету холста<br><b><u>Переключатель ВЫКЛ:</u></b>Используйте цвет, указанный ниже, в качестве цвета сетки",
@@ -694,6 +788,8 @@ export default {
"Прозрачность сетки также будет управлять прозрачностью поля привязки при привязке стрелки к элементу.<br>" +
"Установите прозрачность сетки. 0 - прозрачная, 100 - непрозрачная.",
LASER_HEAD: "Лазерный указатель",
LASER_DESC:
"Настройте цвет лазерного указателя, скорость и длину затухания его следа.",
LASER_COLOR: "Цвет лазерного указателя",
LASER_DECAY_TIME_NAME: "Время затухания лазерного указателя",
LASER_DECAY_TIME_DESC:
@@ -713,6 +809,21 @@ export default {
"Когда файлы Obsidian изменяются, соответствующие <code>[[link]]</code> в ваших чертежах также изменится. " +
"Если вы не хотите, чтобы текст случайно менялся в ваших чертежах, используйте <code>[[links|with aliases]]</code>.",
DRAG_MODIFIER_NAME: "Щелкните ссылку и перетащите клавиши-модификаторы",
DRAG_MODIFIER_GROUP_DESC:
"Настройте жесты открытия ссылок и платформенные сочетания модификаторов для щелчков и перетаскивания.",
LINK_OPENING_GESTURES_HEAD: "Жесты открытия ссылок",
LINK_OPENING_GESTURES_DESC:
"Настройте задержку долгого нажатия и открытие ссылок двойным щелчком во встроенных рисунках и режиме просмотра.",
WEB_BROWSER_DRAG_ACTION_DESC:
"Выберите модификаторы для ссылок, изображений, импорта и вставок, перетаскиваемых из веб-браузера.",
LOCAL_FILE_DRAG_ACTION_DESC:
"Выберите модификаторы для ссылок, изображений, импорта и вставок, перетаскиваемых из операционной системы.",
INTERNAL_DRAG_ACTION_DESC:
"Выберите модификаторы для ссылок, изображений, полноразмерных изображений и вставок внутри Obsidian.",
PANE_TARGET_DESC:
"Выберите сочетания модификаторов, определяющие место открытия ссылок.",
MODIFIER_KEY_USAGE_NAME: "Настройка клавиш-модификаторов",
MODIFIER_KEY_COMBINATIONS: "Сочетания модификаторов",
DRAG_MODIFIER_DESC:
`Поведение клавиши-модификатора при нажатии на ссылки и перетаскивании элементов. ` +
`Excalidraw не будет проверять вашу конфигурацию... обратите внимание, чтобы избежать конфликтов настроек. ` +
@@ -809,6 +920,22 @@ export default {
"Используйте <code>http" +
"s://noembed" +
".com/embed?url=</code> для получения заголовка страницы при переходе по HTTPS-ссылке в Excalidraw",
LINK_BEHAVIOR_HEAD: "Поведение ссылок",
LINK_BEHAVIOR_DESC:
"Настройте синхронизацию ссылок, связанные ссылки, предпросмотр, щелчки и получение заголовков веб-страниц.",
LINK_USAGE_NAME: "Использование ссылок в Excalidraw",
LINK_OPENING_HEAD: "Поведение панелей и вкладок",
LINK_OPENING_DESC:
"Выберите, будут ли ссылки повторно использовать, фокусировать или переключать панели, вкладки и главное рабочее пространство.",
LINK_APPEARANCE_HEAD: "Внешний вид ссылок",
LINK_APPEARANCE_DESC:
"Настройте скобки, префиксы, значки и прозрачность отображаемых ссылок.",
TODO_HEAD: "Задачи TODO",
TODO_GROUP_DESC:
"Настройте распознавание TODO и значки открытых и завершенных задач.",
TRANSCLUSION_HEAD: "Текстовые включения",
TRANSCLUSION_DESC:
"Настройте ограничения символов, перенос строк и очистку цитат для включенного текста Markdown.",
PDF_TO_IMAGE: "PDF в изображение",
PDF_TO_IMAGE_SCALE_NAME: "Шкала преобразования PDF в изображения",
PDF_TO_IMAGE_SCALE_DESC:
@@ -818,7 +945,13 @@ export default {
EMBED_TOEXCALIDRAW_DESC:
"В разделе Встраивание файлов раздела Настройки Excalidraw вы можете настроить, как различные файлы будут встраиваться в Excalidraw. Сюда входят опции для встраивания интерактивных файлов разметки (Markdown), PDF-файлов и файлов разметки (Markdown) в виде изображений.",
MD_HEAD: "Встраивать разметку в Excalidraw в виде изображения",
MD_GROUP_DESC:
"Настройте размеры, шрифт, цвета, границы и CSS для файлов Markdown, отображаемых как изображения.",
MD_EMBED_CUSTOMDATA_HEAD_NAME: "Интерактивные файлы Markdown",
MD_EMBED_CUSTOMDATA_GROUP_DESC:
"Настройте редактирование и внешний вид по умолчанию для будущих интерактивных вставок Markdown.",
MD_EMBED_DEFAULTS_CONTROL_NAME:
"Внешний вид интерактивного Markdown по умолчанию",
MD_EMBED_CUSTOMDATA_HEAD_DESC: `Приведенные ниже настройки будут влиять только на будущие вставки. Текущие вставки остаются неизменными. Настройки темы для встроенных фреймов находятся в разделе "Внешний вид и поведение Excalidraw".`,
MD_EMBED_SINGLECLICK_EDIT_NAME:
"Редактирование встроенной разметки (Markdown) одним щелчком мыши",
@@ -864,12 +997,17 @@ export default {
EMBED_HEAD: "Встраивание Excalidraw в заметки и экспорт",
EMBED_DESC: `В настройках "Вставка и экспорт" можно настроить вставку и экспорт изображений и рисунков Excalidraw в документы. Основные настройки включают выбор типа изображения для предварительного просмотра в формате разметки (например, Native SVG или PNG), указание типа файла для вставки в документ (оригинальный Excalidraw, PNG или SVG) и управление кэшированием изображений для вставки в разметку. Вы также можете управлять размерами изображений, вставлять рисунки с помощью ссылок на вики или ссылок на разметку, а также настраивать темы изображений, цвета фона и интеграцию с Obsidian.
Кроме того, есть настройки автоэкспорта, который автоматически генерирует файлы SVG и/или PNG, соответствующие названию ваших рисунков Excalidraw, сохраняя их синхронизацию при переименовании и удалении файлов.`,
EMBED_PREVIEW_LINKS_HEAD: "Предпросмотр, ссылки и Canvas",
EMBED_PREVIEW_LINKS_DESC:
"Выберите форматы предпросмотра и вставляемых файлов, поведение исходных ссылок, заполнители и иммерсивные вставки Canvas.",
EMBED_CANVAS: "Поддержка Obsidian Canvas",
EMBED_CANVAS_NAME: "Иммерсивное встраивание",
EMBED_CANVAS_DESC:
"Скрывайте границы и фон узлов холста при встраивании чертежа Excalidraw в холст. " +
"Обратите внимание, что для создания полностью прозрачного фона изображения вам все равно придется настроить Excalidraw на экспорт изображений с прозрачным фоном.",
EMBED_CACHING: "Кэширование изображений",
EMBED_CACHING_DESC:
"Настройте параллельный рендеринг и локальные кэши, очищайте изображения или резервные копии и повторно используйте экспортированные предпросмотры.",
IMAGE_CACHE_RETENTION_DAYS_NAME: "Срок хранения локального кэша изображений",
IMAGE_CACHE_RETENTION_DAYS_DESC:
"Определяет, сколько дней Excalidraw должен хранить локально закэшированные отрендеренные ресурсы, такие как вложенные изображения Excalidraw и страницы PDF, прежде чем неиспользуемые записи кэша будут удалены. " +
@@ -878,8 +1016,14 @@ export default {
"Практически это влияет только на локальное использование диска или браузерного хранилища внутри Obsidian. Это может быть особенно заметно на телефонах и на настольных системах с более жёсткими лимитами браузерного хранилища или ограниченным свободным местом на диске.<br><br>" +
"Меньшие значения быстрее освобождают локальное место, но могут приводить к более частому повторному рендерингу PDF и встроенных рисунков. Большие значения ускоряют повторные загрузки ценой большего локального кэша.",
EXPORT_SUBHEAD: "Настройки экспорта",
EXPORT_SUBHEAD_DESC:
"Настройте рендеринг PDF, данные экспортируемой сцены, размеры, тему и фон, параметры PDF по умолчанию и автоматические копии PNG/SVG.",
EMBED_SIZING: "Размер изображения",
EMBED_SIZING_DESC:
"Задайте размеры встроенных изображений по умолчанию, масштаб PNG и отступ экспорта.",
EMBED_THEME_BACKGROUND: "Тема изображения и цвет фона",
EMBED_THEME_BACKGROUND_DESC:
"Выберите фон и тему экспортируемых изображений, а также следование предпросмотра теме Obsidian.",
EMBED_IMAGE_CACHE_NAME: "Кэширование изображений для вставки в markdown",
EMBED_IMAGE_CACHE_DESC:
"Кэшируйте изображения для вставки в markdown. Это ускорит процесс встраивания, но в случае, если вы составите изображения из нескольких чертежей-субкомпонентов, " +
@@ -961,7 +1105,19 @@ export default {
EXPORT_EMBED_SCENE_DESC:
"Вставка сцены Excalidraw в экспортируемое изображение. Можно переопределить на уровне файла, добавив ключ frontmatter. <code>excalidraw-export-embed-scene: true/false</code>. " +
"Настройка вступит в силу только при следующем (повторном) открытии чертежей.",
PDF_EXPORT_SETTINGS: "Настройки экспорта PDF",
PDF_EXPORT_SETTINGS_DESC:
"Выберите размер страницы PDF, ориентацию, разбиение, поля, цвет бумаги и выравнивание по умолчанию.",
PDF_EXPORT_DEFAULTS_CONTROL_NAME: "Макет экспорта PDF по умолчанию",
EXPORT_HEAD: "Настройки автоэкспорта",
EXPORT_AUTOEXPORT_DESC:
"Синхронизируйте экспортированные файлы и автоматически создавайте варианты SVG, PNG, для светлой и тёмной темы.",
SETTINGS_NAVIGATION_OPEN: "Открыть",
SETTINGS_BREADCRUMB_ARIA: "Путь настроек",
SETTINGS_RELATED_AUTOEXPORT_DESC:
"Включите автоматические копии PNG или SVG, чтобы эти форматы стали доступны в списке типа вставляемого файла.",
SETTINGS_RELATED_EMBED_TYPE_DESC:
"Выберите, что вставлять в документ при встраивании рисунка: Excalidraw, PNG или SVG.",
EXPORT_SYNC_NAME:
"Поддерживайте синхронизацию имен файлов .SVG и/или .PNG с файлом чертежа",
EXPORT_SYNC_DESC:
@@ -1034,8 +1190,11 @@ export default {
CUSTOM_PEN_DESC:
"Вы увидите эти ручки рядом с меню Obsidian на холсте. Вы можете настроить ручки на холсте, долго нажимая на кнопку ручки.",
EXPERIMENTAL_HEAD: "Разные возможности",
EXPERIMENTAL_DESC: `Среди прочих возможностей Excalidraw - установка формул LaTeX по умолчанию для новых уравнений, включение Предложение полей (Suggester) для автозаполнения, отображение индикаторов типов файлов Excalidraw, включение иммерсивного встраивания изображений в режиме предварительного просмотра и эксперименты с оптическим распознаванием символов Taskbone для извлечения текста из изображений и чертежей. Пользователи также могут ввести API-ключ Taskbone для расширенного использования сервиса OCR.`,
EXPERIMENTAL_DESC:
"Настройте значения LaTeX по умолчанию, индикаторы типов файлов, режим живого предварительного просмотра, подсказки свойств и экспериментальную интеграцию OCR Taskbone.",
EA_HEAD: "Автоматизация Excalidraw",
EA_GROUP_DESC:
"Настройте сценарии Excalidraw Automate, запуск и автозапуск, командные ссылки и параметры, предоставляемые установленными сценариями.",
EA_DESC:
"Excalidraw Автоматизация - это скриптовый и автоматизированный API для Excalidraw. К сожалению, документация по API скудна. " +
`Рекомендую прочитать <a href="${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_BLOB_MASTER_DOCS_API_EXCALIDRAWAUTOMATE_D_TS}">ExcalidrawAutomate.d.ts</a> файл, ` +
@@ -1046,6 +1205,34 @@ export default {
FIELD_SUGGESTER_DESC:
"Предложение полей (Suggester) позаимствован у плагинов Breadcrumbs и Templater. Предложение полей (Suggester) полей будет показывать " +
"меню автозаполнения при вводе текста с описанием функций <code>excalidraw-</code> или <code>ea.</code> в качестве подсказок для отдельных элементов в списке.",
ALLOW_JS_FILES_NAME: "Загружать файлы JavaScript из папки скриптов",
ALLOW_JS_FILES_DESC:
"Если включено, Excalidraw Automate отслеживает и запускает файлы <code>.js</code> в папке скриптов и принимает скрипт запуска <code>.js</code>. " +
"По умолчанию Obsidian Sync не синхронизирует файлы, отличные от Markdown, Obsidian не открывает файлы <code>.js</code> для редактирования, а проводник файлов скрывает их. При необходимости включите <b>Синхронизировать все остальные типы</b> и <b>Показывать все типы файлов</b> в Obsidian. Если существуют одноимённые скрипты <code>.md</code> и <code>.js</code>, используется файл Markdown.",
STORE_SCRIPTS_AS_JS_NAME: "Хранить загруженные скрипты как",
STORE_SCRIPTS_AS_JS_DESC:
"Выберите локальный тип файла для новых загрузок и обновлений из библиотеки скриптов. Он не зависит от того, имеет ли удалённый источник расширение <code>.md</code> или <code>.js</code>.",
SCRIPT_FILE_EXTENSION_MARKDOWN: "Markdown (.md)",
SCRIPT_FILE_EXTENSION_JAVASCRIPT: "JavaScript (.js)",
MIGRATE_SCRIPT_FILES_NAME: "Переместить существующие файлы скриптов",
MIGRATE_SCRIPTS_TO_JS_BUTTON: "Переместить существующие скрипты в .js",
MIGRATE_SCRIPTS_TO_MD_BUTTON: "Переместить существующие скрипты в .md",
MIGRATE_SCRIPT_FILES_STATUS:
"Можно переместить файлов скриптов в {extension}: {eligible}. {skipped}",
MIGRATE_SCRIPT_FILES_CONFIRM:
"Перед продолжением создайте резервную копию хранилища.<br><br><b>{count}</b> файл(ов) скриптов будет переименовано в <code>{extension}</code>. Пути закреплённых скриптов будут обновлены. {startup} {skipped}",
MIGRATE_SCRIPT_FILES_STARTUP_INCLUDED:
"Настроенный скрипт запуска и его параметр также будут обновлены.",
MIGRATE_SCRIPT_FILES_SKIPPED:
"Одноимённых пар .md/.js, которые не будут перемещены: {count}.",
MIGRATE_SCRIPT_FILES_SKIPPED_DETAILS:
"Пропущено файлов скриптов, поскольку целевой файл уже существует: {count}.\n{files}",
MIGRATE_SCRIPT_FILES_NONE:
"Не найдено подходящих файлов скриптов для перемещения.",
MIGRATE_SCRIPT_FILES_COMPLETE:
"Перемещено файлов скриптов в {extension}: {count}.",
MIGRATE_SCRIPT_FILES_FAILED:
"Не удалось переместить файлы скриптов. Выполненные переименования по возможности отменены.",
ENABLE_ONLOAD_SCRIPTS_NAME: "Включить onload-скрипты",
ENABLE_ONLOAD_SCRIPTS_CONFIRMATION:
"Этот файл содержит <code>excalidraw-onload-script</code>. Включить onload-скрипты?",
@@ -1055,6 +1242,19 @@ export default {
"Если эта настройка включена, Excalidraw будет выполнять <code>excalidraw-onload-script</code> на уровне файла во всех рисунках, которые вы откроете далее, пока вы не отключите эту настройку. " +
"Это создаёт риск, если вы загружаете Markdown-файлы из неизвестных источников: злоумышленник может использовать <code>excalidraw-onload-script</code> " +
"для запуска любой команды в Obsidian и потенциальной передачи данных в интернет. Включайте это только если доверяете файлу и его источнику.",
AUTOSTART_SCRIPT_PROMPT:
"хочет запускаться автоматически каждый раз, когда вы открываете рисунок Excalidraw. Разрешить это?",
AUTOSTART_SCRIPT_PROMPT_MANAGE_HINT:
"Позже это можно изменить в командной палитре («Автозапуск скриптов») или в Настройках → Автоматизация Excalidraw → Автозапуск скриптов.",
AUTOSTART_SCRIPT_ALLOW: "Автозапуск",
AUTOSTART_SCRIPT_DENY: "Только вручную",
AUTOSTART_SCRIPT_ASK_LATER: "Спрашивать каждый раз",
AUTOSTART_SCRIPTS_HEAD: "Автозапуск скриптов",
AUTOSTART_SCRIPTS_DESC:
"Скрипты появляются здесь после того, как они запрашивают разрешение автоматически запускаться каждый раз при открытии нового рисунка Excalidraw (запрос инициируется однократным ручным запуском скрипта). Изменить настройку скрипта можно в любое время.",
AUTOSTART_SCRIPTS_EMPTY: "Ни один скрипт ещё не запрашивал разрешение на автозапуск.",
AUTOSTART_SCRIPT_FAILED_WARNING:
"Этот скрипт завершился ошибкой при последнем автозапуске.",
ENABLE_COMMAND_LINKS_NAME: "Включить ссылки-команды (cmd://)",
ENABLE_COMMAND_LINKS_CONFIRMATION:
"Эта ссылка запускает команду Obsidian через <code>cmd://</code>. Включить ссылки-команды?",
@@ -1065,9 +1265,10 @@ export default {
"Это создаёт риск при открытии рисунков из неизвестных источников: вредоносный рисунок может превратить обычный клик в запуск привилегированной команды. " +
"Включайте это только если доверяете файлу и его источнику.",
STARTUP_SCRIPT_NAME: "Сценарий запуска",
STARTUP_SCRIPT_JS_DISABLED:
"Сценарии запуска JavaScript отключены. Сначала включите файлы JavaScript в настройках Excalidraw Automate.",
STARTUP_SCRIPT_DESC:
"Если этот параметр установлен, excalidraw будет выполнять скрипт при запуске плагина. Это полезно, если вы хотите установить какой-либо из крючков Excalidraw Automate. " +
"Скрипт запуска - это файл в формате markdown, который должен содержать код javascript, который вы хотите выполнять при запуске Excalidraw.",
"Если задано, Excalidraw выполнит скрипт при запуске плагина. Это полезно для настройки крючков Excalidraw Automate. Пути без расширения используют файл Markdown; файлы <code>.js</code> принимаются, когда включена загрузка файлов JavaScript.",
STARTUP_SCRIPT_BUTTON_CREATE: "Создание сценария запуска",
STARTUP_SCRIPT_BUTTON_OPEN: "Открыть сценарий запуска",
FILETYPE_NAME:
@@ -1096,6 +1297,9 @@ export default {
"Включение этой функции упрощает использование свойств титульного листа Excalidraw, позволяя использовать множество мощных настроек. Если вы предпочитаете не загружать эти свойства автоматически, " +
"Вы можете отключить эту функцию, но при этом вам придется вручную удалить все ненужные свойства из предложения. " +
"Обратите внимание, что включение этой настройки требует перезапуска плагина, так как свойства загружаются при запуске.",
FONTS_HEAD: "Шрифты",
FONTS_DESC:
"Настройте локальные гарнитуры и загруженные шрифты CJK для Excalidraw.",
CUSTOM_FONT_HEAD: "Локальный шрифт",
ENABLE_FOURTH_FONT_NAME: "Включите опцию локального шрифта",
ENABLE_FOURTH_FONT_DESC:
@@ -1109,10 +1313,15 @@ export default {
"Если файл не выбран, Excalidraw по умолчанию использует шрифт Virgil. " +
"Для оптимальной производительности рекомендуется использовать файл .woff2, так как Excalidraw закодирует только необходимые глифы при экспорте изображений в SVG. " +
"Другие форматы шрифтов будут встраивать весь шрифт в экспортируемый файл, что может привести к значительному увеличению размера файла.",
OFFLINE_CJK_NAME: "Поддержка шрифтов CJK без подключения к Интернету",
OFFLINE_CJK_GROUP_DESC:
"Загрузите и выборочно предварительно загружайте китайские, японские и корейские шрифты, чтобы Excalidraw мог отображать их без подключения к Интернету.",
SCRIPT_SETTINGS_HEAD: "Настройки для установленных сценариев",
SCRIPT_SETTINGS_DESC:
"Некоторые сценарии Excalidraw Automate Scripts включают в себя настройки. Настройки упорядочены по сценариям. Настройки станут видны в этом списке только после того, как вы один раз выполните загруженный скрипт.",
TASKBONE_HEAD: "Taskbone Оптический распознаватель символов",
TASKBONE_GROUP_DESC:
"Настройте дополнительный онлайн-сервис OCR Taskbone для извлечения доступного для поиска текста из рисунков и изображений.",
TASKBONE_DESC:
"Это экспериментальная интеграция оптического распознавания символов в Excalidraw. Обратите внимание, что taskbone - это независимый внешний сервис, не предоставляемый ни Excalidraw, ни проектом плагинов Excalidraw-Obsidian. " +
"Сервис OCR выхватывает разборчивый текст из произвольных линий и встроенных изображений на вашем холсте и помещает распознанный текст на передний план вашего рисунка, а также в буфер обмена. " +
@@ -1231,6 +1440,7 @@ export default {
PROMPT_BUTTON_NEVERMIND: "Неважно",
PROMPT_BUTTON_OK: "OK",
PROMPT_BUTTON_CANCEL: "Отменить",
PROMPT_BUTTON_CLOSE: "Закрыть",
PROMPT_BUTTON_INSERT_LINE: "Вставить новую строку",
PROMPT_BUTTON_INSERT_SPACE: "Вставить пробел",
PROMPT_BUTTON_INSERT_LINK: "Вставить ссылку на файл в формате markdown",
@@ -1256,6 +1466,7 @@ export default {
//InsertPDFModal.ts
IPM_PAGES_TO_IMPORT_NAME: "Страницы для импорта",
IPM_PAGES_TO_IMPORT_DESC: "Например: 1,3-5,7,9-10",
IPM_SELECT_PAGES_TO_IMPORT: "Пожалуйста, выберите страницы для импорта",
IPM_ADD_BORDER_BOX_NAME: "Добавить рамку",
IPM_ADD_FRAME_NAME: "Добавить страницу в кадр",
@@ -1266,4 +1477,26 @@ export default {
IPM_GROUP_PAGES_DESC:
"Это позволит объединить все страницы в одну группу. Это рекомендуется делать, если вы блокируете страницы после импорта, потому что группу будет легче разблокировать позже, чем разблокировать каждую по отдельности.",
IPM_SELECT_PDF: "Пожалуйста, выберите файл PDF",
//Taskbone.ts
OCR_ABORT_NO_ELEMENTS:
"Отмена OCR, так как на холсте нет элементов изображения или рисования от руки.",
OCR_ALREADY_PROCESSED:
"Рисунок уже обработан, результат можно найти во frontmatter в режиме просмотра Markdown. Если вы запустили команду с панели Obsidian в Excalidraw, вы можете нажать ctrl(cmd)+клик по команде, чтобы принудительно повторить сканирование.",
//ObserverManager.ts
ERROR_ADDING_OBSERVER_MANAGER: "Ошибка при добавлении ObserverManager",
//PublishOutOfDateFiles.ts
POODF_TITLE: "Устаревшие файлы SVG",
POODF_CHECK_RECURSIVE: "Проверить рекурсивно",
POODF_OPEN_SELECTED: "Открыть выбранное",
//ImageCache.ts
IMAGE_CACHE_INITIALIZED:
"Кэш изображений Excalidraw инициализирован - теперь вы можете повторить попытку открытия повреждённого рисунка.",
//carveout.ts
NEW_DRAWING_TIMEOUT:
"Файл не найден. Создание нового рисунка Excalidraw занимает слишком много времени. Пожалуйста, попробуйте снова.",
};
+227 -20
View File
@@ -15,6 +15,21 @@ export default {
// Sugester
SELECT_FILE_TO_INSERT: "选择要嵌入到当前绘图中的文件",
// main.ts
SETTINGS_DATA_INVALID:
"Excalidraw 正在等待有效的替代 data.json。在恢复该文件,或重新启动 Obsidian 并选择重置为默认值之前,设置更改不会保存。",
SETTINGS_DATA_REPAIRED_FROM_MEMORY:
"收到的 Excalidraw 设置文件为空或无法读取,已拒绝该文件。当前设置已写回,以修复 data.json。",
SETTINGS_DATA_RECOVERED:
"Excalidraw 的 data.json 为空或无法读取。已自动恢复最近的有效设置。",
SETTINGS_RECOVERY_MISSING_TITLE: "Excalidraw 设置文件缺失",
SETTINGS_RECOVERY_MISSING_DESC:
"此设备上存在最近的有效设置备份。你可以恢复该备份,或将 Excalidraw 重置为出厂默认值。关闭此消息将恢复备份。",
SETTINGS_RECOVERY_CORRUPT_TITLE: "Excalidraw 设置文件已损坏",
SETTINGS_RECOVERY_CORRUPT_DESC:
"设置文件为空或无法读取,并且此设备上没有恢复备份。你可以将 Excalidraw 重置为出厂默认值,或保持文件不变,同时从其他来源恢复有效的 data.json。关闭此消息将等待替代文件。",
SETTINGS_RECOVERY_RESTORE_BACKUP: "恢复备份",
SETTINGS_RECOVERY_RESET_DEFAULTS: "重置为默认值",
SETTINGS_RECOVERY_WAIT_FOR_FILE: "等待恢复文件",
ERROR_INITIALIZING_EA: "初始化 Excalidraw Automate 时出错",
CONVERT_URL_TO_FILE: "从 URL 下载图片到本地",
UNZIP_CURRENT_FILE: "解压当前 Excalidraw 文件",
@@ -36,6 +51,36 @@ export default {
CONVERT_FILE_KEEP_EXT: "转换:*.excalidraw => *.excalidraw.md",
CONVERT_FILE_REPLACE_EXT: "转换:*.excalidraw => *.md (兼容 Logseq)",
DOWNLOAD_LIBRARY: "导出 stencil 库为 *.excalidrawlib 文件",
LIBRARY_MIGRATION_TITLE: "将 Excalidraw 素材库移入仓库",
LIBRARY_MIGRATION_DESC:
"Excalidraw 可将素材库保存为独立的仓库文件,而不是放在 data.json 中,从而提升保存稳定性。现有素材会与所选本地素材库文件合并;放入同一文件夹的 *.excalidrawlib 文件也会自动加载。选择“稍后”可将此消息隐藏到明天。",
LIBRARY_MIGRATION_SYNC_WARNING:
"若要通过 Obsidian Sync 同步素材库文件,请在同步设置中启用“同步所有其他文件类型”。",
LIBRARY_MIGRATION_KEEP_DATA_JSON: "继续使用 data.json",
LIBRARY_MIGRATION_LATER: "稍后",
LIBRARY_MIGRATION_MIGRATE: "移动素材库",
LIBRARY_MIGRATION_SUCCESS: "Excalidraw 素材库已移入仓库。",
LIBRARY_MIGRATION_FAILED: "无法移动素材库。原 data.json 素材库保持不变。",
LIBRARY_FILE_READ_ERROR: "无法读取 Excalidraw 素材库文件:{PATH}",
LIBRARY_STORAGE_NAME: "素材库存储位置",
LIBRARY_STORAGE_DESC: "将素材库移出 data.json 并使用仓库文件可提升保存稳定性。",
LIBRARY_STORAGE_VAULT: "仓库文件夹(推荐)",
LIBRARY_STORAGE_DATA_JSON: "插件 data.json(旧方式)",
LIBRARY_FOLDER_NAME: "素材库文件夹",
LIBRARY_FOLDER_DESC:
"用于存放本地素材库和下载的素材库文件。素材库文件使用 .excalidrawlib 扩展名。要在 Obsidian 文件列表中查看这些文件,请在 Obsidian 设置中启用“显示所有文件类型”。",
LIBRARY_FILE_NAME: "本地素材库文件名",
LIBRARY_FILE_DESC: "可编辑本地素材库的名称。扩展名会自动添加。",
LIBRARY_MIGRATE_NOW: "立即移动素材库",
LIBRARY_MIGRATE_NOW_DESC: "将 data.json 中的现有素材库移到设定的仓库文件。",
LIBRARY_PATH_MISSING: "此路径目前不存在于仓库中。",
CREATE_FOLDER: "创建文件夹",
CREATE_FOLDER_CONFIRM: "是否创建文件夹 <b>{PATH}</b>?",
CREATE_FOLDER_NEVER_MIND: "暂不创建",
CREATE_FOLDER_YES: "是",
CREATE_FOLDER_SUCCESS: "已创建文件夹:{PATH}",
CREATE_FOLDER_FAILED: "无法创建文件夹:{PATH}",
CREATE_FOLDER_PATH_IS_FILE: "无法创建文件夹,该路径已有文件:{PATH}",
OPEN_SIDEPANEL: "打开 Excalidraw 侧边面板",
OPEN_EXISTING_NEW_PANE: "打开已有的绘图 - 于新面板",
OPEN_EXISTING_ACTIVE_PANE: "打开已有的绘图 - 于当前面板",
@@ -87,30 +132,25 @@ export default {
MARKDOWN_IMAGE_APPEARANCE: "外观",
MARKDOWN_IMAGE_WIDTH: "宽度",
MARKDOWN_IMAGE_WIDTH_DESC: "以画布单位表示的 Markdown 排版宽度",
MARKDOWN_IMAGE_BOTTOM_PADDING: "底部内边距",
MARKDOWN_IMAGE_BOTTOM_PADDING_DESC:
"渲染后的 Markdown 下方额外空间(像素)",
MARKDOWN_IMAGE_FONT: "字体",
MARKDOWN_IMAGE_FONT_COLOR: "字体颜色",
MARKDOWN_IMAGE_BORDER: "边框",
MARKDOWN_IMAGE_BORDER_COLOR: "边框颜色",
MARKDOWN_IMAGE_THEME: "主题",
MARKDOWN_IMAGE_THEME_DESC:
"控制代码块、表格、链接和标注等随主题变化的内容。",
MARKDOWN_IMAGE_MATCH_CANVAS: "匹配画布",
MARKDOWN_IMAGE_LIGHT: "浅色",
MARKDOWN_IMAGE_DARK: "深色",
MARKDOWN_IMAGE_CSS: "CSS",
MARKDOWN_IMAGE_CSS_DESC: "仅应用于此 Markdown 图像的 CSS 规则。",
MARKDOWN_IMAGE_CSS_DESC:
"CSS 仅应用于此 Markdown 图像。复制下方的 SVG,让你选择的 LLM 生成所需的 CSS。",
MARKDOWN_IMAGE_CSS_IMPORTANT_HINT:
"如果规则没有效果,请在声明中添加 !important。",
MARKDOWN_IMAGE_CSS_DESKTOP_HELP:
"要检查生成的标记,请打开开发者控制台({shortcut}),然后运行复制按钮提供的命令。",
MARKDOWN_IMAGE_CSS_MOBILE_HELP:
"在桌面设备上,可在开发者控制台中检查生成的标记,并运行复制按钮提供的命令。",
MARKDOWN_IMAGE_CSS_EDITOR_ARIA: "此 Markdown 图像的 CSS 编辑器",
MARKDOWN_IMAGE_TRANSCLUSION_CSS_EDITOR_ARIA:
"嵌入 Markdown 的 CSS 编辑器",
MARKDOWN_IMAGE_INSERT_CSS_BOILERPLATE: "插入带注释的 CSS 模板",
MARKDOWN_IMAGE_COPY_CSS_COMMAND: "复制生成的 Markdown SVG 控制台命令",
MARKDOWN_IMAGE_CSS_COMMAND_COPIED: "控制台命令已复制",
MARKDOWN_IMAGE_COPY_SVG: "复制当前 Markdown 图像的 SVG",
MARKDOWN_IMAGE_SVG_COPIED: "已复制 Markdown 图像 SVG",
MARKDOWN_IMAGE_SVG_COPY_ERROR: "无法复制 Markdown 图像 SVG",
MARKDOWN_IMAGE_TRANSCLUSION_DIFFERENT_STYLE: "为嵌入内容使用不同样式",
MARKDOWN_IMAGE_TRANSCLUSION_DIFFERENT_STYLE_DESC:
"显示嵌入 Markdown 的独立外观设置。",
@@ -121,6 +161,7 @@ export default {
MARKDOWN_IMAGE_TRANSCLUSION_CSS_DESC: "仅应用于嵌入 Markdown 的 CSS 规则。",
MARKDOWN_IMAGE_SET_DEFAULT: "设为默认",
MARKDOWN_IMAGE_SAVE_DEFAULT_ARIA: "将当前外观设置保存为默认值",
MARKDOWN_IMAGE_DEFAULT_SAVED: "Markdown 图像默认设置已保存",
MARKDOWN_IMAGE_RENDER_NOW: "立即渲染",
MARKDOWN_IMAGE_UPDATING: "正在更新图像…",
MARKDOWN_IMAGE_EXTERNAL_SOURCE: "外部 Markdown 来源",
@@ -132,11 +173,15 @@ export default {
MARKDOWN_IMAGE_USE_SOURCE: "使用来源",
MARKDOWN_IMAGE_EXTRACT_LOCAL: "将本地 Markdown 提取到笔记",
MARKDOWN_IMAGE_EXTRACT: "提取到笔记",
MARKDOWN_IMAGE_DUPLICATE_ERROR: "无法复制 Markdown 图像",
MARKDOWN_IMAGE_SELECT_SOURCE: "请选择 Markdown 笔记、标题或块",
MARKDOWN_IMAGE_CHANGE_SOURCE_ERROR: "无法更改 Markdown 图像来源",
MARKDOWN_IMAGE_LOCAL_COPY_ERROR: "无法创建本地 Markdown 副本",
MARKDOWN_IMAGE_EXTRACT_TITLE: "将 Markdown 图像提取到笔记",
MARKDOWN_IMAGE_EXTRACT_PATH: "新 Markdown 笔记的路径",
FILE_AND_FOLDER_SELECTOR_FOLDER: "文件夹",
FILE_AND_FOLDER_SELECTOR_FILENAME: "文件名",
FILE_AND_FOLDER_SELECTOR_EXPORT_TITLE: "导出到仓库",
FILE_AND_FOLDER_SELECTOR_EXPORT: "导出",
MARKDOWN_IMAGE_DEFAULT_NOTE: "Markdown 图像.md",
MARKDOWN_IMAGE_CREATE_NOTE_ERROR: "无法创建 Markdown 笔记",
MARKDOWN_IMAGE_UNKNOWN_ERROR: "未知错误",
@@ -155,6 +200,10 @@ export default {
"本地 Markdown 图像转换为嵌入内容时只能包含一个一级标题。该标题必须是首个内容,且名称在绘图中必须唯一。",
MARKDOWN_IMAGE_SECTION_NAME: "命名笔记末尾的章节",
MARKDOWN_IMAGE_SECTION_NAME_PLACEHOLDER: "输入唯一的章节名称",
MARKDOWN_IMAGE_DELETE_TEXT_PROMPT:
"是否删除为此图像保存的 Markdown 文本?无论如何,该图像都会从场景中移除。",
MARKDOWN_IMAGE_KEEP_TEXT: "保留 Markdown 文本",
MARKDOWN_IMAGE_DELETE_TEXT: "删除 Markdown 文本",
INSERT_PDF: "以图像形式嵌入 PDF 到当前绘图中",
INSERT_LAST_ACTIVE_PDF_PAGE_AS_IMAGE: "以图像形式嵌入最后激活的 PDF 页面",
UNIVERSAL_ADD_FILE: "嵌入文件 / Insert ANY file",
@@ -181,6 +230,9 @@ export default {
ABOUT_EXCALIDRAW: "关于 Excalidraw",
RUN_OCR: "OCR 整个绘图:识别涂鸦和图片里的文本并复制到剪贴板和笔记属性中",
TASKBONE_NOT_ENABLED: "Taskbone OCR 未启用。请前往插件设置将其开启。",
OCR_ABORT_NO_ELEMENTS: "正在中止 OCR,因为画布上没有图像或手绘元素。",
OCR_ALREADY_PROCESSED:
"该绘图已经处理过,您可以在 Markdown 视图模式下的 frontmatter 中找到结果。如果您是从 Excalidraw 的 Obsidian 面板运行此命令,可以按住 ctrl(cmd) 并点击该命令以强制重新扫描。",
RERUN_OCR:
"重新 OCR 整个绘图:识别涂鸦和图片里的文本并复制到剪贴板和笔记属性中",
RUN_OCR_ELEMENTS: "OCR 选中的元素:识别涂鸦和图片里的文本并复制到剪贴板",
@@ -223,8 +275,6 @@ export default {
"反转模式:默认方向按键已禁用。需要时请使用 Ctrl/CMD 临时启用。",
ARROW_BINDING_NORMAL_MODE:
"正常模式:方向键已启用。需要时请使用 Ctrl/CMD 临时禁用。",
EXPORT_FILENAME_PROMPT: "请提供文件名",
EXPORT_FILENAME_PROMPT_PLACEHOLDER: "请输入文件名,留空以取消操作",
WARNING_SERIOUS_ERROR:
"警告:Excalidraw 遇到了未知的问题!\n\n" +
"您最近的更改可能无法保存。\n\n" +
@@ -305,6 +355,18 @@ export default {
SEARCH_SHOWHIDE_ARIA: "显示/隐藏搜索栏",
SEARCH_NEXT: "下一个",
SEARCH_PREVIOUS: "上一个",
SETTINGS_TOOLBAR_COPY: "复制设置",
SETTINGS_TOOLBAR_NOTEBOOKLM: "NotebookLM",
SETTINGS_TOOLBAR_BUGS: "问题",
SETTINGS_TOOLBAR_WIKI: "Wiki",
SETTINGS_TOOLBAR_YOUTUBE: "YouTube",
SETTINGS_TOOLBAR_LEARN: "学习",
SETTINGS_TOOLBAR_FOLLOW: "Twitter",
SETTINGS_TOOLBAR_READ: "阅读书籍",
SETTINGS_TOOLBAR_KOFI: "Ko-fi",
USE_DECLARATIVE_SETTINGS_NAME: "使用可搜索设置",
USE_DECLARATIVE_SETTINGS_DESC:
"使用 Obsidian 可搜索的多页面设置界面。关闭后将使用 Excalidraw 的旧版单页面设置。需要重启 Obsidian。",
//settings.ts
FOLDER_PLACEHOLDER: "e.g.: Excalidraw",
@@ -338,7 +400,6 @@ export default {
"禁用 Excalidraw 的上下文菜单。这在移动设备上很有用,因为上下文菜单有时会在不需要的时候弹出。",
NOTEBOOKLM_LINK_ARIA:
"向 NotebookLM 咨询有关插件的帮助。此模型已预加载了我所有的视频转录稿、发布说明和其他帮助内容。与 NotebookLM 聊天,浏览我的 250+ 视频和 Excalidraw 文件。",
NOTEBOOKLM_LINK_TEXT: "学习插件。访问 NotebookLM 知识库。",
EXCALIDRAW_MASTERY: "Excalidraw Mastery",
EXCALIDRAW_MASTERY_PROMO_ARIA: "打开 Excalidraw Mastery",
EXCALIDRAW_MASTERY_PROMO_HTML: `<p><b>在各种开关和菜单里找不着北?</b></p><p>Excalidraw 是一款为高强度工作流打造的 Visual PKM 强力工具,适合 <b>Visual-First Daily Notes</b>、深度 <b>PDF 研究</b>、<b>自动化</b>、<b>AI 集成</b> 和 <b>Visual Zettelkasten</b>。但强大能力也伴随着复杂度。</p><p>跳过反复试错。<a href="${URLs.COMMUNITY_SKETCH_YOUR_MIND_COM_EM}" target="_blank">👉 加入 Excalidraw Mastery</a>,一步一步学会这些具体配置。减少工具摩擦,与视觉思维社区伙伴一起掌握知识!</p>`,
@@ -369,6 +430,14 @@ export default {
"<b>关闭:</b>您需要手动检查插件更新(设置 - 第三方插件 - 检查更新)。",
BASIC_HEAD: "基本",
BASIC_UPDATES_STARTUP_HEAD: "更新与启动",
BASIC_UPDATES_STARTUP_DESC: "发行说明、更新检查与通知,以及启动欢迎画面。",
BASIC_FILES_FOLDERS_HEAD: "文件与文件夹",
BASIC_FILES_FOLDERS_DESC:
"设置绘图、裁剪、批注、模板和 Excalidraw Automate 脚本的默认文件夹与路径。",
BASIC_STENCIL_LIBRARY_HEAD: "素材库",
BASIC_STENCIL_LIBRARY_DESC:
"选择素材库数据的存储位置,并配置其仓库文件夹和本地素材库文件。",
BASIC_DESC: `包括:更新说明,更新通知,新绘图文件、模板文件、脚本文件的存储路径等。`,
FOLDER_NAME: "Excalidraw 文件夹(區分大小寫!)",
FOLDER_DESC: "新绘图的默认存储路径。若为空,将在仓库根目录中创建新绘图。",
@@ -549,6 +618,9 @@ export default {
AI_USAGE_SETTINGS_BUTTON_DESC:
"按模型查看当前 Obsidian 会话的 AI Token 消耗明细。重启后将重置。",
SAVING_HEAD: "保存",
SAVING_STORAGE_AUTOSAVE_HEAD: "存储与自动保存",
SAVING_STORAGE_AUTOSAVE_DESC:
"控制绘图 JSON 压缩,并选择桌面端和移动端的自动保存间隔。",
SAVING_DESC: "包括:压缩,自动保存的时间间隔,文件的命名格式和扩展名等。",
COMPRESS_NAME: "压缩 Excalidraw JSON",
COMPRESS_DESC:
@@ -581,6 +653,8 @@ export default {
"直接退出 Obsidian 应用(在应用切换器中划掉)不会触发自动保存。" +
"此外,当您切换到其他应用时,有时系统会自动清理 Obsidian 后台以释放资源。这种情况下,自动保存会失效。",
FILENAME_HEAD: "文件名",
FILENAME_GROUP_DESC:
"配置新建、嵌入、裁剪和批注绘图文件名的生成方式。",
FILENAME_DESC: `<p>点击阅读 <a href="${URLs.MOMENTJS_COM_DOCS}">日期和时间格式参考</a>。</p>`,
FILENAME_SAMPLE: "“新建绘图”系列命令创建的文件名如:",
FILENAME_EMBED_SAMPLE:
@@ -606,6 +680,9 @@ export default {
DISPLAY_HEAD: "界面 & 行为",
DISPLAY_DESC:
"包括:左手模式、动态样式、匹配 Excalidraw 和 Obsidian 主题、默认运行模式等。",
DISPLAY_EDITOR_PREVIEWS_HEAD: "编辑与预览",
DISPLAY_EDITOR_PREVIEWS_DESC:
"配置画布编辑手势,以及 Excalidraw 文件在阅读模式和悬停预览中的显示方式。",
OVERRIDE_OBSIDIAN_FONT_SIZE_NAME: "限制 Obsidian 字体大小为编辑器文本",
OVERRIDE_OBSIDIAN_FONT_SIZE_DESC:
"Obsidian 的自定义字体大小设置会影响整个界面,包括 Excalidraw 和依赖默认字体大小的主题。" +
@@ -680,6 +757,8 @@ export default {
`请参阅下方 <a href='#${TAG_PDFEXPORT}'>PDF 导出设置</a>。<br>` +
`⚠️ 关闭并重新打开 Excalidraw/Markdown 文件后生效。`,
MODES_HEAD: "UI 模式",
MODES_DESC:
"选择不同设备的 Excalidraw 界面布局、标题栏控件和左右手托盘位置。",
DESKTOP_UI_MODE_NAME: "桌面端偏好模式",
DESKTOP_UI_MODE_DESC: "桌面端设备默认 UI 模式。",
TABLET_UI_MODE_NAME: "平板端偏好模式",
@@ -692,12 +771,19 @@ export default {
MODE_PHONE: "Phone-mode",
REAPPLY_UI_MODE_BUTTON: "重新应用 UI 模式",
HOTKEY_OVERRIDE_HEAD: "热键覆盖",
HOTKEY_OVERRIDE_GROUP_DESC:
"管理应优先于冲突 Obsidian 热键的 Excalidraw 按键组合。",
HOTKEY_OVERRIDE_CONTROL_NAME: "管理热键覆盖",
HOTKEY_OVERRIDE_DESC:
`一些 Excalidraw 的热键,如 ${labelCTRL()}+Enter 用于编辑文本,或 ${labelCTRL()}+K 用于创建元素链接,` +
"与 Obsidian 的热键设置冲突。您在下面添加的热键组合将在使用 Excalidraw 时覆盖 Obsidian 的热键设置," +
`因此如果您希望在 Excalidraw 中默认“编组”,而不是“查看关系图谱”(核心插件 - 关系图谱),您可以添加 ${labelCTRL()}+G。`,
THEME_HEAD: "主题和样式",
THEME_DESC:
"控制界面样式、绘图和嵌入主题、打开模式以及移动设备安全区域间距。",
ZOOM_AND_PAN_HEAD: "缩放和平移",
ZOOM_AND_PAN_DESC:
"配置鼠标、触控、打开、调整大小和缩放范围行为。",
PAN_WITH_RIGHT_MOUSE_BUTTON_NAME: "右键拖动平移",
PAN_WITH_RIGHT_MOUSE_BUTTON_DESC:
"右键点击并拖动来平移绘图(和在线白板工具 Miro 类似)。按 'm' 键打开上下文菜单。",
@@ -730,7 +816,9 @@ export default {
ZOOM_MAX_DESC:
"绘图放大的极限。默认:3000%。通常无需修改,考虑完整性而提供。",
PEN_HEAD: "手写笔",
PEN_DESC: "配置自动手写笔模式、触控手势、橡皮擦和自由绘制十字线。",
GRID_HEAD: "网格",
GRID_DESC: "配置网格方向、自动或自定义颜色以及不透明度。",
GRID_DYNAMIC_COLOR_NAME: "动态网格颜色",
GRID_DYNAMIC_COLOR_DESC:
"<b>开启:</b>更改网格颜色以匹配绘图颜色。<br><b>关闭:</b>将以下颜色用作网格颜色。",
@@ -743,6 +831,7 @@ export default {
GRID_HORIZONTAL: "渲染水平网格",
GRID_VERTICAL: "渲染垂直网格",
LASER_HEAD: "激光笔工具(更多工具 > 激光笔)",
LASER_DESC: "配置激光笔颜色及其轨迹淡出的速度和长度。",
LASER_COLOR: "激光笔颜色",
LASER_DECAY_TIME_NAME: "激光笔消失时间",
LASER_DECAY_TIME_DESC: "单位是毫秒,默认 1000(即 1 秒)。",
@@ -761,6 +850,20 @@ export default {
"链接的源文件被重命名时,绘图中相应的 <code>[[内部链接]]</code> 也会同步更新。" +
"若您不愿绘图中的链接外观因此而变化,可使用 <code>[[内部链接|别名]]</code>。",
DRAG_MODIFIER_NAME: "修饰键",
DRAG_MODIFIER_GROUP_DESC:
"配置链接打开手势,以及点击和拖放操作的平台特定修饰键组合。",
LINK_OPENING_GESTURES_HEAD: "链接打开手势",
LINK_OPENING_GESTURES_DESC:
"配置嵌入绘图和查看模式中的长按延迟与双击打开链接。",
WEB_BROWSER_DRAG_ACTION_DESC:
"选择从网页浏览器拖入链接、图片、导入项和嵌入内容时的修饰键组合。",
LOCAL_FILE_DRAG_ACTION_DESC:
"选择从操作系统拖入链接、图片、导入项和嵌入内容时的修饰键组合。",
INTERNAL_DRAG_ACTION_DESC:
"选择在 Obsidian 内拖动链接、图片、全尺寸图片和嵌入内容时的修饰键组合。",
PANE_TARGET_DESC: "选择决定点击链接打开位置的修饰键组合。",
MODIFIER_KEY_USAGE_NAME: "配置修饰键",
MODIFIER_KEY_COMBINATIONS: "修饰键组合",
DRAG_MODIFIER_DESC:
`在您按住点击链接或拖动元素时,可以触发某些行为。您可以为这些行为添加修饰键。` +
`Excalidraw 不会检查您的设置是否合理,因此请谨慎设置,避免冲突。` +
@@ -856,6 +959,20 @@ export default {
"拖动链接到 Excalidraw 时,使用 <code>http" +
"s://noembed" +
".com/embed?url=</code> 来获取 HTTPS 页面标题。",
LINK_BEHAVIOR_HEAD: "链接行为",
LINK_BEHAVIOR_DESC:
"配置链接同步、相关链接、悬停预览、点击处理和网页标题查询。",
LINK_USAGE_NAME: "在 Excalidraw 中使用链接",
LINK_OPENING_HEAD: "窗格和标签页行为",
LINK_OPENING_DESC:
"选择链接是否复用、聚焦或切换窗格、标签页和主工作区。",
LINK_APPEARANCE_HEAD: "链接外观",
LINK_APPEARANCE_DESC: "配置链接显示时使用的括号、前缀、图标和不透明度。",
TODO_HEAD: "待办事项",
TODO_GROUP_DESC: "配置待办事项解析以及未完成和已完成任务使用的图标。",
TRANSCLUSION_HEAD: "文本嵌入",
TRANSCLUSION_DESC:
"配置嵌入 Markdown 文本的字符限制、换行和引用符号清理。",
PDF_TO_IMAGE: "以图像形式嵌入到绘图中的 PDF",
PDF_TO_IMAGE_SCALE_NAME: "分辨率",
PDF_TO_IMAGE_SCALE_DESC:
@@ -865,8 +982,13 @@ export default {
EMBED_TOEXCALIDRAW_DESC:
"包括:以图像形式嵌入到绘图中的 PDF、以交互或图像形式嵌入到绘图中的 Markdown 文档等。",
MD_HEAD: "以图像形式嵌入到绘图中的 Markdown 文档(MD-Embed)",
MD_GROUP_DESC:
"设置以图像呈现的 Markdown 文件的尺寸、字体、颜色、边框和 CSS。",
MD_EMBED_CUSTOMDATA_HEAD_NAME:
"以交互形式嵌入到绘图中的 Markdown 文档(MD-Embeddable)",
MD_EMBED_CUSTOMDATA_GROUP_DESC:
"配置未来交互式 Markdown 嵌入的编辑方式和默认外观。",
MD_EMBED_DEFAULTS_CONTROL_NAME: "交互式 Markdown 默认外观",
MD_EMBED_CUSTOMDATA_HEAD_DESC: `以下设置只会影响以后的嵌入。已存在的嵌入保持不变。嵌入框的主题设置位于“界面 & 行为”部分。`,
MD_EMBED_SINGLECLICK_EDIT_NAME: "单击编辑嵌入的 Markdown",
MD_EMBED_SINGLECLICK_EDIT_DESC:
@@ -906,12 +1028,17 @@ export default {
EMBED_HEAD: "嵌入到 Markdown 文档中的绘图",
EMBED_DESC: `包括:嵌入到 Markdown 文档中的绘图的预览图类型(SVG、PNG)、源文件类型(Excalidraw、SVG、PNG)、缓存、图像尺寸、图像主题,以及嵌入的语法等。
此外,还有自动导出 SVG 或 PNG 文件并保持与绘图文件状态同步的设置。`,
EMBED_PREVIEW_LINKS_HEAD: "预览、链接与 Canvas",
EMBED_PREVIEW_LINKS_DESC:
"选择预览和插入文件的格式、源链接行为、占位图像及沉浸式 Canvas 嵌入。",
EMBED_CANVAS: "Obsidian 白板支持",
EMBED_CANVAS_NAME: "沉浸式嵌入",
EMBED_CANVAS_DESC:
"当嵌入绘图到 Obsidian 白板中时,隐藏节点的边界和背景。" +
"注意:如果想要背景完全透明,您依然需要设置导出背景为透明(关闭“导出图片包含背景”)。",
EMBED_CACHING: "图像缓存和渲染优化",
EMBED_CACHING_DESC:
"调整并行渲染和本地图像缓存,清除缓存图像或备份,并可复用已导出的预览。",
RENDERING_CONCURRENCY_NAME: "图像渲染并发性",
RENDERING_CONCURRENCY_DESC:
"用于图像渲染的并行工作线程数。增加该值可以加快渲染速度,但可能会减慢系统其他部分的运行速度。" +
@@ -924,8 +1051,13 @@ export default {
"实际影响在于 Obsidian 内部的本地磁盘或浏览器存储占用。在手机以及浏览器存储配额较紧、剩余磁盘空间有限的桌面设备上需要留意。<br><br>" +
"较小的值会更快回收本地缓存空间,但可能导致 PDF 和嵌入绘图更频繁地重新渲染。较大的值会保留更久的缓存,以换取更快的加载速度。",
EXPORT_SUBHEAD: "导出",
EXPORT_SUBHEAD_DESC:
"配置 PDF 渲染、导出的场景数据、图像尺寸、主题与背景、PDF 默认值及自动 PNG/SVG 副本。",
EMBED_SIZING: "图像尺寸",
EMBED_SIZING_DESC: "设置嵌入图像的默认尺寸、PNG 缩放比例和导出边距。",
EMBED_THEME_BACKGROUND: "图像的主题和背景色",
EMBED_THEME_BACKGROUND_DESC:
"选择导出图像的背景和主题,以及预览是否跟随 Obsidian 主题。",
EMBED_IMAGE_CACHE_NAME: "为嵌入到 Markdown 文档中的绘图创建预览图缓存",
EMBED_IMAGE_CACHE_DESC:
"可提高下次嵌入的速度。" +
@@ -1005,7 +1137,18 @@ export default {
"在导出图片中嵌入 Excalidraw 场景。可以在其 frontmatter 中添加如 <code>excalidraw-export-embed-scene: true/false</code> 的键值对来覆盖该项。" +
"该项仅在您下次(重新)打开绘图时生效。",
PDF_EXPORT_SETTINGS: "PDF 导出设置",
PDF_EXPORT_SETTINGS_DESC:
"选择默认 PDF 页面大小、方向、分页、边距、纸张颜色和对齐方式。",
PDF_EXPORT_DEFAULTS_CONTROL_NAME: "默认 PDF 导出布局",
EXPORT_HEAD: "导出设置",
EXPORT_AUTOEXPORT_DESC:
"保持导出文件同步,并自动创建 SVG、PNG、浅色和深色版本。",
SETTINGS_NAVIGATION_OPEN: "打开",
SETTINGS_BREADCRUMB_ARIA: "设置路径",
SETTINGS_RELATED_AUTOEXPORT_DESC:
"启用自动 PNG 或 SVG 副本,使这些格式可在插入文件类型下拉列表中选择。",
SETTINGS_RELATED_EMBED_TYPE_DESC:
"选择在文档中嵌入绘图时插入 Excalidraw、PNG 还是 SVG。",
EXPORT_SYNC_NAME: "保持 SVG/PNG 文件名与绘图文件同步",
EXPORT_SYNC_DESC:
"打开后,当绘图文件被重命名时,插件将同步更新同文件夹下的同名 .SVG 和 .PNG 文件。" +
@@ -1078,8 +1221,11 @@ export default {
CUSTOM_PEN_DESC:
"在绘图上的 Obsidian 菜单按钮旁边切换自定义画笔。长按(双击)画笔按钮可以修改其样式。",
EXPERIMENTAL_HEAD: "杂项",
EXPERIMENTAL_DESC: `包括:默认的 LaTeX 公式,字段建议,绘图文件的类型标识符,OCR 等。`,
EXPERIMENTAL_DESC:
"配置 LaTeX 默认值、文件类型标识、实时预览行为、属性建议以及实验性的 Taskbone OCR 集成。",
EA_HEAD: "Excalidraw 自动化",
EA_GROUP_DESC:
"配置 Excalidraw Automate 脚本、启动和自动启动行为、命令链接,以及已安装脚本提供的设置。",
EA_DESC:
`ExcalidrawAutomate 是用于 Excalidraw 自动化脚本的 API,但是目前说明文档还不够完善,` +
`建议阅读 <a href="${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_BLOB_MASTER_DOCS_API_EXCALIDRAWAUTOMATE_D_TS}">ExcalidrawAutomate.d.ts</a> 文件源码,` +
@@ -1090,6 +1236,33 @@ export default {
FIELD_SUGGESTER_DESC:
"开启后,当您在编辑器中输入 <code>excalidraw-</code> 或者 <code>ea.</code> 时,会弹出一个带有函数说明的自动补全提示菜单。<br>" +
"该功能借鉴了 Breadcrumbs 和 Templater 插件。",
ALLOW_JS_FILES_NAME: "从 Scripts 文件夹加载 JavaScript 文件",
ALLOW_JS_FILES_DESC:
"启用后,Excalidraw Automate 会监视并运行 Scripts 文件夹中的 <code>.js</code> 文件,也允许使用 <code>.js</code> 启动脚本。" +
"默认情况下,Obsidian Sync 不同步非 Markdown 文件,Obsidian 不会打开 <code>.js</code> 文件进行编辑,文件列表也会隐藏它们。需要时请在 Obsidian 中启用<b>同步所有其他文件类型</b>和<b>显示所有文件类型</b>。如果存在同名的 <code>.md</code> 和 <code>.js</code> 脚本,将使用 Markdown 文件。",
STORE_SCRIPTS_AS_JS_NAME: "将下载的脚本存储为",
STORE_SCRIPTS_AS_JS_DESC:
"选择脚本库新下载和更新在本地使用的文件类型。无论远程源是 <code>.md</code> 还是 <code>.js</code>,都会使用此设置。",
SCRIPT_FILE_EXTENSION_MARKDOWN: "Markdown (.md)",
SCRIPT_FILE_EXTENSION_JAVASCRIPT: "JavaScript (.js)",
MIGRATE_SCRIPT_FILES_NAME: "迁移现有脚本文件",
MIGRATE_SCRIPTS_TO_JS_BUTTON: "将现有脚本迁移为 .js",
MIGRATE_SCRIPTS_TO_MD_BUTTON: "将现有脚本迁移为 .md",
MIGRATE_SCRIPT_FILES_STATUS:
"有 {eligible} 个脚本文件可迁移为 {extension}。{skipped}",
MIGRATE_SCRIPT_FILES_CONFIRM:
"继续前请备份仓库。<br><br><b>{count}</b> 个脚本文件将重命名为 <code>{extension}</code>,固定脚本的路径也会更新。{startup} {skipped}",
MIGRATE_SCRIPT_FILES_STARTUP_INCLUDED:
"已配置的启动脚本及其设置也会更新。",
MIGRATE_SCRIPT_FILES_SKIPPED:
"有 {count} 对同名 .md/.js 文件不会被迁移。",
MIGRATE_SCRIPT_FILES_SKIPPED_DETAILS:
"因目标文件已存在,已跳过 {count} 个脚本文件:\n{files}",
MIGRATE_SCRIPT_FILES_NONE: "没有找到可迁移的脚本文件。",
MIGRATE_SCRIPT_FILES_COMPLETE:
"已将 {count} 个脚本文件迁移为 {extension}。",
MIGRATE_SCRIPT_FILES_FAILED:
"无法迁移脚本文件。已尽可能回滚完成的重命名。",
ENABLE_ONLOAD_SCRIPTS_NAME: "加载期脚本(onload)",
ENABLE_ONLOAD_SCRIPTS_CONFIRMATION:
"此文件包含 <code>excalidraw-onload-script</code>。是否启用加载期脚本?",
@@ -1099,6 +1272,18 @@ export default {
"启用后,Excalidraw 会在你之后打开的所有绘图中执行文件级别的 <code>excalidraw-onload-script</code>,直到你关闭此设置。" +
"如果你从未知来源下载 Markdown 文件,这会带来风险:恶意行为者可以利用 <code>excalidraw-onload-script</code> " +
"在 Obsidian 中运行任意命令,并且有可能将数据传输到互联网。只有在你信任该文件及其来源时才启用此功能。",
AUTOSTART_SCRIPT_PROMPT:
"希望在你每次打开 Excalidraw 绘图时自动运行。是否允许?",
AUTOSTART_SCRIPT_PROMPT_MANAGE_HINT:
"你以后可以在命令面板(“自动启动脚本”)或设置 → Excalidraw 自动化 → 自动启动脚本中更改此设置。",
AUTOSTART_SCRIPT_ALLOW: "自动启动",
AUTOSTART_SCRIPT_DENY: "仅手动启动",
AUTOSTART_SCRIPT_ASK_LATER: "每次都询问",
AUTOSTART_SCRIPTS_HEAD: "自动启动脚本",
AUTOSTART_SCRIPTS_DESC:
"脚本在请求权限以便每次打开新的 Excalidraw 绘图时自动运行后会出现在这里(手动运行一次脚本即可触发该请求)。你可以随时更改脚本的设置。",
AUTOSTART_SCRIPTS_EMPTY: "尚无脚本请求自动启动权限。",
AUTOSTART_SCRIPT_FAILED_WARNING: "该脚本上次自动启动时失败了。",
ENABLE_COMMAND_LINKS_NAME: "启用命令链接(cmd://)",
ENABLE_COMMAND_LINKS_CONFIRMATION:
"此链接会通过 <code>cmd://</code> 触发 Obsidian 命令。是否启用命令链接?",
@@ -1109,9 +1294,10 @@ export default {
"如果你打开未知来源的绘图,这会带来风险:恶意绘图可以让一次普通点击触发高权限命令。" +
"只有在你信任该文件及其来源时才启用此功能。",
STARTUP_SCRIPT_NAME: "启动期脚本(startup)",
STARTUP_SCRIPT_JS_DISABLED:
"JavaScript 启动脚本已禁用。请先在 Excalidraw Automate 设置中启用 JavaScript 文件。",
STARTUP_SCRIPT_DESC:
"插件启动时将自动执行该脚本。可用于设置 Excalidraw 自动化钩子。" +
"该脚本是包含 javascript 代码的 Markdown 文件。",
"插件启动时将自动执行该脚本,可用于设置 Excalidraw Automate 钩子。没有扩展名的路径使用 Markdown 文件;启用 JavaScript 文件加载后可使用 <code>.js</code> 文件。",
STARTUP_SCRIPT_BUTTON_CREATE: "创建启动期脚本",
STARTUP_SCRIPT_BUTTON_OPEN: "打开启动期脚本",
FILETYPE_NAME: "在文件浏览器中为 excalidraw.md 文件添加类型标识符(如 ✏️)",
@@ -1152,6 +1338,8 @@ export default {
"为了获得最佳性能,建议使用 .woff2 文件,因为当导出 SVG 格式的图片时,Excalidraw 只会编码必要的字形。" +
`其他字体格式将在导出文件中嵌入整个字体,可能会导致文件大小显著增加。<b>译者注:</b>可在 <a href="${URLs.WANGCHUJIANG_COM_FREE_FONT}" target='_blank'>Free Font</a> 获取免费商用中文手写字体。`,
OFFLINE_CJK_NAME: "离线 CJK 字体支持",
OFFLINE_CJK_GROUP_DESC:
"下载并按需预加载中文、日文和韩文字体,使 Excalidraw 无需互联网连接也能显示这些字体。",
OFFLINE_CJK_DESC: `<strong>该项需要重启 Obsidian 才能生效。</strong><br>
Excalidraw.com 提供手写风格的 CJK 字体。默认情况下,这些字体不会包含在插件本地,而是从互联网获取。
如果您希望 Excalidraw 完全本地化,以便在没有互联网连接的情况下使用,可以从 <a href="${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_RAW_REFS_HEADS_MASTER_ASSETS_EXCALIDRAW_FONTS_ZIP}" target="_blank">GitHub 下载所需的字体文件</a>。
@@ -1168,6 +1356,8 @@ export default {
SCRIPT_SETTINGS_DESC:
"有些 Excalidraw 自动化脚本包含设置项,当执行这些脚本时,它们会在该列表下添加设置项。",
TASKBONE_HEAD: "Taskbone OCR(光学符号识别)",
TASKBONE_GROUP_DESC:
"配置可选的 Taskbone 在线 OCR 服务,从绘图和图像中提取可搜索文本。",
TASKBONE_DESC:
"这是一个将 OCR 融入 Excalidraw 的实验性功能。请注意,Taskbone 是一项独立的外部服务,而不是由 Excalidraw 或 obsidian-excalidraw-plugin 项目提供的。" +
"OCR 能够对绘图上用自由画笔工具写下的涂鸦或者嵌入的图像进行文本识别,并将识别出来的文本写入绘图文件的 frontmatter,同时复制到剪贴板。" +
@@ -1338,6 +1528,7 @@ export default {
PROMPT_BUTTON_NEVERMIND: "算了",
PROMPT_BUTTON_OK: "OK",
PROMPT_BUTTON_CANCEL: "取消",
PROMPT_BUTTON_CLOSE: "关闭",
PROMPT_BUTTON_INSERT_LINE: "插入一行",
PROMPT_BUTTON_INSERT_SPACE: "插入空格",
PROMPT_BUTTON_INSERT_LINK: "插入内部链接",
@@ -1363,6 +1554,7 @@ export default {
//InsertPDFModal.ts
IPM_PAGES_TO_IMPORT_NAME: "要导入的页面",
IPM_PAGES_TO_IMPORT_DESC: "例如:1,3-5,7,9-10",
IPM_SELECT_PAGES_TO_IMPORT: "请选择页面以进行导入",
IPM_ADD_BORDER_BOX_NAME: "添加带边框的盒子容器",
IPM_ADD_FRAME_NAME: "添加页面到画框",
@@ -1604,4 +1796,19 @@ Obsidian 的 Excalidraw 插件远不只是画图工具。由于它与 Obsidian
EXTRAS_GATEWAY_COMP_PLUGIN: "Excalidraw Extras 插件",
EXTRAS_GATEWAY_UPDATE_TITLE: "Excalidraw 需要新版本的 Extras 插件",
EXTRAS_GATEWAY_UPDATE_BTN: "打开社区插件",
//ObserverManager.ts
ERROR_ADDING_OBSERVER_MANAGER: "添加 ObserverManager 时出错",
//PublishOutOfDateFiles.ts
POODF_TITLE: "过期的 SVG 文件",
POODF_CHECK_RECURSIVE: "递归检查",
POODF_OPEN_SELECTED: "打开所选项",
//ImageCache.ts
IMAGE_CACHE_INITIALIZED:
"Excalidraw 图像缓存已初始化 - 您现在可以重试打开损坏的绘图。",
//carveout.ts
NEW_DRAWING_TIMEOUT: "未找到文件。新建 Excalidraw 绘图耗时过长。请重试。",
};
+227 -20
View File
@@ -15,6 +15,21 @@ export default {
// Sugester
SELECT_FILE_TO_INSERT: "選擇要嵌入到當前繪圖中的檔案",
// main.ts
SETTINGS_DATA_INVALID:
"Excalidraw 正在等待有效的替代 data.json。在復原該檔案,或重新啟動 Obsidian 並選擇重設為預設值之前,設定變更不會儲存。",
SETTINGS_DATA_REPAIRED_FROM_MEMORY:
"收到的 Excalidraw 設定檔為空或無法讀取,已拒絕該檔案。目前的設定已寫回,以修復 data.json。",
SETTINGS_DATA_RECOVERED:
"Excalidraw 的 data.json 為空或無法讀取。已自動復原最近的有效設定。",
SETTINGS_RECOVERY_MISSING_TITLE: "Excalidraw 設定檔遺失",
SETTINGS_RECOVERY_MISSING_DESC:
"此裝置上有最近的有效設定備份。你可以復原該備份,或將 Excalidraw 重設為出廠預設值。關閉此訊息將復原備份。",
SETTINGS_RECOVERY_CORRUPT_TITLE: "Excalidraw 設定檔已損壞",
SETTINGS_RECOVERY_CORRUPT_DESC:
"設定檔為空或無法讀取,且此裝置上沒有復原備份。你可以將 Excalidraw 重設為出廠預設值,或保持檔案不變,同時從其他來源復原有效的 data.json。關閉此訊息將等待替代檔案。",
SETTINGS_RECOVERY_RESTORE_BACKUP: "復原備份",
SETTINGS_RECOVERY_RESET_DEFAULTS: "重設為預設值",
SETTINGS_RECOVERY_WAIT_FOR_FILE: "等待復原檔案",
ERROR_INITIALIZING_EA: "初始化 Excalidraw Automate 時出錯",
CONVERT_URL_TO_FILE: "從 URL 下載圖片到本地",
UNZIP_CURRENT_FILE: "解壓當前 Excalidraw 檔案",
@@ -36,6 +51,36 @@ export default {
CONVERT_FILE_KEEP_EXT: "轉換:*.excalidraw => *.excalidraw.md",
CONVERT_FILE_REPLACE_EXT: "轉換:*.excalidraw => *.md (相容 Logseq)",
DOWNLOAD_LIBRARY: "匯出 stencil 庫為 *.excalidrawlib 檔案",
LIBRARY_MIGRATION_TITLE: "將 Excalidraw 素材庫移入儲存庫",
LIBRARY_MIGRATION_DESC:
"Excalidraw 可將素材庫儲存為獨立的儲存庫檔案,而不是放在 data.json 中,讓儲存更穩定。現有素材會與所選本機素材庫檔案合併;放入同一資料夾的 *.excalidrawlib 檔案也會載入。選擇「稍後」可將此訊息隱藏到明天。",
LIBRARY_MIGRATION_SYNC_WARNING:
"若要透過 Obsidian Sync 同步素材庫檔案,請在同步設定中啟用「同步所有其他檔案類型」。",
LIBRARY_MIGRATION_KEEP_DATA_JSON: "繼續使用 data.json",
LIBRARY_MIGRATION_LATER: "稍後",
LIBRARY_MIGRATION_MIGRATE: "移動素材庫",
LIBRARY_MIGRATION_SUCCESS: "Excalidraw 素材庫已移入儲存庫。",
LIBRARY_MIGRATION_FAILED: "無法移動素材庫。原 data.json 素材庫保持不變。",
LIBRARY_FILE_READ_ERROR: "無法讀取 Excalidraw 素材庫檔案:{PATH}",
LIBRARY_STORAGE_NAME: "素材庫儲存位置",
LIBRARY_STORAGE_DESC: "將素材庫移出 data.json 並使用儲存庫檔案可提升穩定性。",
LIBRARY_STORAGE_VAULT: "儲存庫資料夾(建議)",
LIBRARY_STORAGE_DATA_JSON: "外掛 data.json(舊方式)",
LIBRARY_FOLDER_NAME: "素材庫資料夾",
LIBRARY_FOLDER_DESC:
"用於存放本機素材庫和下載的素材庫檔案。素材庫檔案使用 .excalidrawlib 副檔名。要在 Obsidian 檔案列表中查看這些檔案,請在 Obsidian 設定中啟用「顯示所有檔案類型」。",
LIBRARY_FILE_NAME: "本機素材庫檔名",
LIBRARY_FILE_DESC: "可編輯本機素材庫的名稱。副檔名會自動加入。",
LIBRARY_MIGRATE_NOW: "立即移動素材庫",
LIBRARY_MIGRATE_NOW_DESC: "將 data.json 中的現有素材庫移到設定的儲存庫檔案。",
LIBRARY_PATH_MISSING: "此路徑目前不存在於儲存庫中。",
CREATE_FOLDER: "建立資料夾",
CREATE_FOLDER_CONFIRM: "是否建立資料夾 <b>{PATH}</b>?",
CREATE_FOLDER_NEVER_MIND: "暫不建立",
CREATE_FOLDER_YES: "是",
CREATE_FOLDER_SUCCESS: "已建立資料夾:{PATH}",
CREATE_FOLDER_FAILED: "無法建立資料夾:{PATH}",
CREATE_FOLDER_PATH_IS_FILE: "無法建立資料夾,該路徑已有檔案:{PATH}",
OPEN_SIDEPANEL: "開啟 Excalidraw 側邊面板",
OPEN_EXISTING_NEW_PANE: "開啟已有的繪圖 - 於新面板",
OPEN_EXISTING_ACTIVE_PANE: "開啟已有的繪圖 - 於當前面板",
@@ -87,30 +132,25 @@ export default {
MARKDOWN_IMAGE_APPEARANCE: "外觀",
MARKDOWN_IMAGE_WIDTH: "寬度",
MARKDOWN_IMAGE_WIDTH_DESC: "以畫布單位表示的 Markdown 排版寬度",
MARKDOWN_IMAGE_BOTTOM_PADDING: "底部內距",
MARKDOWN_IMAGE_BOTTOM_PADDING_DESC:
"算繪後的 Markdown 下方額外空間(像素)",
MARKDOWN_IMAGE_FONT: "字型",
MARKDOWN_IMAGE_FONT_COLOR: "字型顏色",
MARKDOWN_IMAGE_BORDER: "邊框",
MARKDOWN_IMAGE_BORDER_COLOR: "邊框顏色",
MARKDOWN_IMAGE_THEME: "主題",
MARKDOWN_IMAGE_THEME_DESC:
"控制程式碼區塊、表格、連結和標註等隨主題變化的內容。",
MARKDOWN_IMAGE_MATCH_CANVAS: "符合畫布",
MARKDOWN_IMAGE_LIGHT: "淺色",
MARKDOWN_IMAGE_DARK: "深色",
MARKDOWN_IMAGE_CSS: "CSS",
MARKDOWN_IMAGE_CSS_DESC: "僅套用於此 Markdown 圖像的 CSS 規則。",
MARKDOWN_IMAGE_CSS_DESC:
"CSS 僅套用於此 Markdown 圖像。複製下方的 SVG,讓你選擇的 LLM 產生所需的 CSS。",
MARKDOWN_IMAGE_CSS_IMPORTANT_HINT:
"如果規則沒有作用,請在宣告中加入 !important。",
MARKDOWN_IMAGE_CSS_DESKTOP_HELP:
"若要檢查產生的標記,請開啟開發者主控台({shortcut}),然後執行複製按鈕提供的命令。",
MARKDOWN_IMAGE_CSS_MOBILE_HELP:
"在桌面裝置上,可在開發者主控台中檢查產生的標記,並執行複製按鈕提供的命令。",
MARKDOWN_IMAGE_CSS_EDITOR_ARIA: "此 Markdown 圖像的 CSS 編輯器",
MARKDOWN_IMAGE_TRANSCLUSION_CSS_EDITOR_ARIA:
"嵌入 Markdown 的 CSS 編輯器",
MARKDOWN_IMAGE_INSERT_CSS_BOILERPLATE: "插入含註解的 CSS 範本",
MARKDOWN_IMAGE_COPY_CSS_COMMAND: "複製產生的 Markdown SVG 主控台命令",
MARKDOWN_IMAGE_CSS_COMMAND_COPIED: "主控台命令已複製",
MARKDOWN_IMAGE_COPY_SVG: "複製目前 Markdown 圖像的 SVG",
MARKDOWN_IMAGE_SVG_COPIED: "已複製 Markdown 圖像 SVG",
MARKDOWN_IMAGE_SVG_COPY_ERROR: "無法複製 Markdown 圖像 SVG",
MARKDOWN_IMAGE_TRANSCLUSION_DIFFERENT_STYLE: "為嵌入內容使用不同樣式",
MARKDOWN_IMAGE_TRANSCLUSION_DIFFERENT_STYLE_DESC:
"顯示嵌入 Markdown 的獨立外觀設定。",
@@ -121,6 +161,7 @@ export default {
MARKDOWN_IMAGE_TRANSCLUSION_CSS_DESC: "僅套用於嵌入 Markdown 的 CSS 規則。",
MARKDOWN_IMAGE_SET_DEFAULT: "設為預設",
MARKDOWN_IMAGE_SAVE_DEFAULT_ARIA: "將目前外觀設定儲存為預設值",
MARKDOWN_IMAGE_DEFAULT_SAVED: "Markdown 圖像預設設定已儲存",
MARKDOWN_IMAGE_RENDER_NOW: "立即渲染",
MARKDOWN_IMAGE_UPDATING: "正在更新圖像…",
MARKDOWN_IMAGE_EXTERNAL_SOURCE: "外部 Markdown 來源",
@@ -132,11 +173,15 @@ export default {
MARKDOWN_IMAGE_USE_SOURCE: "使用來源",
MARKDOWN_IMAGE_EXTRACT_LOCAL: "將本機 Markdown 擷取到筆記",
MARKDOWN_IMAGE_EXTRACT: "擷取到筆記",
MARKDOWN_IMAGE_DUPLICATE_ERROR: "無法複製 Markdown 圖像",
MARKDOWN_IMAGE_SELECT_SOURCE: "請選擇 Markdown 筆記、標題或區塊",
MARKDOWN_IMAGE_CHANGE_SOURCE_ERROR: "無法變更 Markdown 圖像來源",
MARKDOWN_IMAGE_LOCAL_COPY_ERROR: "無法建立本機 Markdown 副本",
MARKDOWN_IMAGE_EXTRACT_TITLE: "將 Markdown 圖像擷取到筆記",
MARKDOWN_IMAGE_EXTRACT_PATH: "新 Markdown 筆記的路徑",
FILE_AND_FOLDER_SELECTOR_FOLDER: "資料夾",
FILE_AND_FOLDER_SELECTOR_FILENAME: "檔案名稱",
FILE_AND_FOLDER_SELECTOR_EXPORT_TITLE: "匯出到儲存庫",
FILE_AND_FOLDER_SELECTOR_EXPORT: "匯出",
MARKDOWN_IMAGE_DEFAULT_NOTE: "Markdown 圖像.md",
MARKDOWN_IMAGE_CREATE_NOTE_ERROR: "無法建立 Markdown 筆記",
MARKDOWN_IMAGE_UNKNOWN_ERROR: "未知錯誤",
@@ -155,6 +200,10 @@ export default {
"本機 Markdown 圖像轉換為嵌入內容時只能包含一個一級標題。該標題必須是首個內容,且名稱在繪圖中必須唯一。",
MARKDOWN_IMAGE_SECTION_NAME: "命名筆記末尾的章節",
MARKDOWN_IMAGE_SECTION_NAME_PLACEHOLDER: "輸入唯一的章節名稱",
MARKDOWN_IMAGE_DELETE_TEXT_PROMPT:
"是否刪除為此圖像儲存的 Markdown 文字?無論如何,該圖像都會從場景中移除。",
MARKDOWN_IMAGE_KEEP_TEXT: "保留 Markdown 文字",
MARKDOWN_IMAGE_DELETE_TEXT: "刪除 Markdown 文字",
INSERT_PDF: "以影像形式嵌入 PDF 到當前繪圖中",
INSERT_LAST_ACTIVE_PDF_PAGE_AS_IMAGE: "以影像形式嵌入最後啟用的 PDF 頁面",
UNIVERSAL_ADD_FILE: "嵌入檔案 / Insert ANY file",
@@ -181,6 +230,9 @@ export default {
ABOUT_EXCALIDRAW: "關於 Excalidraw",
RUN_OCR: "OCR 整個繪圖:識別塗鴉和圖片裡的文字並複製到剪貼簿和筆記屬性中",
TASKBONE_NOT_ENABLED: "Taskbone OCR 未啟用。請前往外掛設定將其開啟。",
OCR_ABORT_NO_ELEMENTS: "正在中止 OCR,因為畫布上沒有圖像或手繪元素。",
OCR_ALREADY_PROCESSED:
"此繪圖已經處理過,您可以在 Markdown 檢視模式下的 frontmatter 中找到結果。如果您是從 Excalidraw 的 Obsidian 面板執行此命令,可以按住 ctrl(cmd) 並點擊該命令以強制重新掃描。",
RERUN_OCR:
"重新 OCR 整個繪圖:識別塗鴉和圖片裡的文字並複製到剪貼簿和筆記屬性中",
RUN_OCR_ELEMENTS: "OCR 選中的元素:識別塗鴉和圖片裡的文字並複製到剪貼簿",
@@ -223,8 +275,6 @@ export default {
"反轉模式:預設方向按鍵已停用。需要時請使用 Ctrl/CMD 臨時啟用。",
ARROW_BINDING_NORMAL_MODE:
"正常模式:方向鍵已啟用。需要時請使用 Ctrl/CMD 臨時停用。",
EXPORT_FILENAME_PROMPT: "請提供檔名",
EXPORT_FILENAME_PROMPT_PLACEHOLDER: "請輸入檔名,留空以取消操作",
WARNING_SERIOUS_ERROR:
"警告:Excalidraw 遇到了未知的問題!\n\n" +
"您最近的更改可能無法儲存。\n\n" +
@@ -305,6 +355,18 @@ export default {
SEARCH_SHOWHIDE_ARIA: "顯示/隱藏搜尋欄",
SEARCH_NEXT: "下一個",
SEARCH_PREVIOUS: "上一個",
SETTINGS_TOOLBAR_COPY: "複製設定",
SETTINGS_TOOLBAR_NOTEBOOKLM: "NotebookLM",
SETTINGS_TOOLBAR_BUGS: "問題",
SETTINGS_TOOLBAR_WIKI: "Wiki",
SETTINGS_TOOLBAR_YOUTUBE: "YouTube",
SETTINGS_TOOLBAR_LEARN: "學習",
SETTINGS_TOOLBAR_FOLLOW: "Twitter",
SETTINGS_TOOLBAR_READ: "閱讀書籍",
SETTINGS_TOOLBAR_KOFI: "Ko-fi",
USE_DECLARATIVE_SETTINGS_NAME: "使用可搜尋設定",
USE_DECLARATIVE_SETTINGS_DESC:
"使用 Obsidian 可搜尋的多頁面設定介面。關閉後將使用 Excalidraw 的舊版單頁面設定。需要重新啟動 Obsidian。",
//settings.ts
FOLDER_PLACEHOLDER: "e.g.: Excalidraw",
@@ -338,7 +400,6 @@ export default {
"停用 Excalidraw 的上下文選單。這在移動裝置上很有用,因為上下文選單有時會在不需要的時候彈出。",
NOTEBOOKLM_LINK_ARIA:
"向 NotebookLM 諮詢有關外掛的幫助。此模型已預載入了我所有的影片轉錄稿、釋出說明和其他幫助內容。與 NotebookLM 聊天,瀏覽我的 250+ 影片和 Excalidraw 檔案。",
NOTEBOOKLM_LINK_TEXT: "學習外掛。訪問 NotebookLM 知識庫。",
EXCALIDRAW_MASTERY: "Excalidraw Mastery",
EXCALIDRAW_MASTERY_PROMO_ARIA: "開啟 Excalidraw Mastery",
EXCALIDRAW_MASTERY_PROMO_HTML: `<p><b>在各種開關和選單裡找不著北?</b></p><p>Excalidraw 是一款為高強度工作流打造的 Visual PKM 強力工具,適合 <b>Visual-First Daily Notes</b>、深度 <b>PDF 研究</b>、<b>自動化</b>、<b>AI 整合</b> 和 <b>Visual Zettelkasten</b>。但強大能力也伴隨著複雜度。</p><p>跳過反覆試錯。<a href="${URLs.COMMUNITY_SKETCH_YOUR_MIND_COM_EM}" target="_blank">👉 加入 Excalidraw Mastery</a>,一步一步學會這些具體配置。減少工具摩擦,與視覺思維社群夥伴一起掌握知識!</p>`,
@@ -369,6 +430,14 @@ export default {
"<b>關閉:</b>您需要手動檢查外掛更新(設定 - 第三方外掛 - 檢查更新)。",
BASIC_HEAD: "基本",
BASIC_UPDATES_STARTUP_HEAD: "更新與啟動",
BASIC_UPDATES_STARTUP_DESC: "版本說明、更新檢查與通知,以及啟動歡迎畫面。",
BASIC_FILES_FOLDERS_HEAD: "檔案與資料夾",
BASIC_FILES_FOLDERS_DESC:
"設定繪圖、裁切、註解、範本和 Excalidraw Automate 指令碼的預設資料夾與路徑。",
BASIC_STENCIL_LIBRARY_HEAD: "素材庫",
BASIC_STENCIL_LIBRARY_DESC:
"選擇素材庫資料的儲存位置,並設定其儲存庫資料夾和本機素材庫檔案。",
BASIC_DESC: `包括:更新說明,更新通知,新繪圖檔案、模板檔案、指令碼檔案的儲存路徑等。`,
FOLDER_NAME: "Excalidraw 資料夾(區分大小寫!)",
FOLDER_DESC: "新繪圖的預設儲存路徑。若為空,將在倉庫根目錄中建立新繪圖。",
@@ -549,6 +618,9 @@ export default {
AI_USAGE_SETTINGS_BUTTON_DESC:
"按模型檢視當前 Obsidian 會話的 AI Token 消耗明細。重啟後將重置。",
SAVING_HEAD: "儲存",
SAVING_STORAGE_AUTOSAVE_HEAD: "儲存與自動儲存",
SAVING_STORAGE_AUTOSAVE_DESC:
"控制繪圖 JSON 壓縮,並選擇桌面版和行動版的自動儲存間隔。",
SAVING_DESC: "包括:壓縮,自動儲存的時間間隔,檔案的命名格式和副檔名等。",
COMPRESS_NAME: "壓縮 Excalidraw JSON",
COMPRESS_DESC:
@@ -581,6 +653,8 @@ export default {
"直接退出 Obsidian 應用(在應用切換器中劃掉)不會觸發自動儲存。" +
"此外,當您切換到其他應用時,有時系統會自動清理 Obsidian 後臺以釋放資源。這種情況下,自動儲存會失效。",
FILENAME_HEAD: "檔名",
FILENAME_GROUP_DESC:
"設定新建、嵌入、裁切和註解繪圖檔名的產生方式。",
FILENAME_DESC: `<p>點選閱讀 <a href="${URLs.MOMENTJS_COM_DOCS}">日期和時間格式參考</a>。</p>`,
FILENAME_SAMPLE: "“新建繪圖”系列命令建立的檔名如:",
FILENAME_EMBED_SAMPLE:
@@ -606,6 +680,9 @@ export default {
DISPLAY_HEAD: "介面 & 行為",
DISPLAY_DESC:
"包括:左手模式、動態樣式、匹配 Excalidraw 和 Obsidian 主題、預設執行模式等。",
DISPLAY_EDITOR_PREVIEWS_HEAD: "編輯與預覽",
DISPLAY_EDITOR_PREVIEWS_DESC:
"設定畫布編輯手勢,以及 Excalidraw 檔案在閱讀模式和懸停預覽中的顯示方式。",
OVERRIDE_OBSIDIAN_FONT_SIZE_NAME: "限制 Obsidian 字型大小為編輯器文字",
OVERRIDE_OBSIDIAN_FONT_SIZE_DESC:
"Obsidian 的自定義字型大小設定會影響整個介面,包括 Excalidraw 和依賴預設字型大小的主題。" +
@@ -680,6 +757,8 @@ export default {
`請參閱下方 <a href='#${TAG_PDFEXPORT}'>PDF 匯出設定</a>。<br>` +
`⚠️ 關閉並重新開啟 Excalidraw/Markdown 檔案後生效。`,
MODES_HEAD: "UI 模式",
MODES_DESC:
"選擇不同裝置的 Excalidraw 介面配置、標題列控制項和左右手托盤位置。",
DESKTOP_UI_MODE_NAME: "桌面端偏好模式",
DESKTOP_UI_MODE_DESC: "桌面端裝置預設 UI 模式。",
TABLET_UI_MODE_NAME: "平板端偏好模式",
@@ -692,12 +771,19 @@ export default {
MODE_PHONE: "Phone-mode",
REAPPLY_UI_MODE_BUTTON: "重新應用 UI 模式",
HOTKEY_OVERRIDE_HEAD: "熱鍵覆蓋",
HOTKEY_OVERRIDE_GROUP_DESC:
"管理應優先於衝突 Obsidian 熱鍵的 Excalidraw 按鍵組合。",
HOTKEY_OVERRIDE_CONTROL_NAME: "管理熱鍵覆蓋",
HOTKEY_OVERRIDE_DESC:
`一些 Excalidraw 的熱鍵,如 ${labelCTRL()}+Enter 用於編輯文字,或 ${labelCTRL()}+K 用於建立元素連結,` +
"與 Obsidian 的熱鍵設定衝突。您在下面新增的熱鍵組合將在使用 Excalidraw 時覆蓋 Obsidian 的熱鍵設定," +
`因此如果您希望在 Excalidraw 中預設“編組”,而不是“檢視關係圖譜”(核心外掛 - 關係圖譜),您可以新增 ${labelCTRL()}+G。`,
THEME_HEAD: "主題和樣式",
THEME_DESC:
"控制介面樣式、繪圖和嵌入主題、開啟模式以及行動裝置安全區域間距。",
ZOOM_AND_PAN_HEAD: "縮放和平移",
ZOOM_AND_PAN_DESC:
"設定滑鼠、觸控、開啟、調整大小和縮放範圍行為。",
PAN_WITH_RIGHT_MOUSE_BUTTON_NAME: "右鍵拖動平移",
PAN_WITH_RIGHT_MOUSE_BUTTON_DESC:
"右鍵點選並拖動來平移繪圖(和線上白板工具 Miro 類似)。按 'm' 鍵開啟上下文選單。",
@@ -730,7 +816,9 @@ export default {
ZOOM_MAX_DESC:
"繪圖放大的極限。預設:3000%。通常無需修改,考慮完整性而提供。",
PEN_HEAD: "手寫筆",
PEN_DESC: "設定自動手寫筆模式、觸控手勢、橡皮擦和自由繪製十字線。",
GRID_HEAD: "網格",
GRID_DESC: "設定網格方向、自動或自訂顏色以及不透明度。",
GRID_DYNAMIC_COLOR_NAME: "動態網格顏色",
GRID_DYNAMIC_COLOR_DESC:
"<b>開啟:</b>更改網格顏色以匹配繪圖顏色。<br><b>關閉:</b>將以下顏色用作網格顏色。",
@@ -743,6 +831,7 @@ export default {
GRID_HORIZONTAL: "渲染水平網格",
GRID_VERTICAL: "渲染垂直網格",
LASER_HEAD: "雷射筆工具(更多工具 > 雷射筆)",
LASER_DESC: "設定雷射筆顏色及其軌跡淡出的速度和長度。",
LASER_COLOR: "雷射筆顏色",
LASER_DECAY_TIME_NAME: "雷射筆消失時間",
LASER_DECAY_TIME_DESC: "單位是毫秒,預設 1000(即 1 秒)。",
@@ -761,6 +850,20 @@ export default {
"連結的原始檔被重新命名時,繪圖中相應的 <code>[[內部連結]]</code> 也會同步更新。" +
"若您不願繪圖中的連結外觀因此而變化,可使用 <code>[[內部連結|別名]]</code>。",
DRAG_MODIFIER_NAME: "修飾鍵",
DRAG_MODIFIER_GROUP_DESC:
"設定連結開啟手勢,以及點擊和拖放操作的平台特定修飾鍵組合。",
LINK_OPENING_GESTURES_HEAD: "連結開啟手勢",
LINK_OPENING_GESTURES_DESC:
"設定嵌入繪圖和檢視模式中的長按延遲與雙擊開啟連結。",
WEB_BROWSER_DRAG_ACTION_DESC:
"選擇從網頁瀏覽器拖入連結、圖片、匯入項目和嵌入內容時的修飾鍵組合。",
LOCAL_FILE_DRAG_ACTION_DESC:
"選擇從作業系統拖入連結、圖片、匯入項目和嵌入內容時的修飾鍵組合。",
INTERNAL_DRAG_ACTION_DESC:
"選擇在 Obsidian 內拖動連結、圖片、完整尺寸圖片和嵌入內容時的修飾鍵組合。",
PANE_TARGET_DESC: "選擇決定點擊連結開啟位置的修飾鍵組合。",
MODIFIER_KEY_USAGE_NAME: "設定修飾鍵",
MODIFIER_KEY_COMBINATIONS: "修飾鍵組合",
DRAG_MODIFIER_DESC:
`在您按住點選連結或拖動元素時,可以觸發某些行為。您可以為這些行為新增修飾鍵。` +
`Excalidraw 不會檢查您的設定是否合理,因此請謹慎設定,避免衝突。` +
@@ -856,6 +959,20 @@ export default {
"拖動連結到 Excalidraw 時,使用 <code>http" +
"s://noembed" +
".com/embed?url=</code> 來獲取 HTTPS 頁面標題。",
LINK_BEHAVIOR_HEAD: "連結行為",
LINK_BEHAVIOR_DESC:
"設定連結同步、相關連結、懸停預覽、點擊處理和網頁標題查詢。",
LINK_USAGE_NAME: "在 Excalidraw 中使用連結",
LINK_OPENING_HEAD: "窗格和分頁行為",
LINK_OPENING_DESC:
"選擇連結是否重複使用、聚焦或切換窗格、分頁和主要工作區。",
LINK_APPEARANCE_HEAD: "連結外觀",
LINK_APPEARANCE_DESC: "設定連結顯示時使用的括號、前綴、圖示和不透明度。",
TODO_HEAD: "待辦事項",
TODO_GROUP_DESC: "設定待辦事項解析以及未完成和已完成任務使用的圖示。",
TRANSCLUSION_HEAD: "文字嵌入",
TRANSCLUSION_DESC:
"設定嵌入 Markdown 文字的字元限制、換行和引用符號清理。",
PDF_TO_IMAGE: "以影像形式嵌入到繪圖中的 PDF",
PDF_TO_IMAGE_SCALE_NAME: "解析度",
PDF_TO_IMAGE_SCALE_DESC:
@@ -865,8 +982,13 @@ export default {
EMBED_TOEXCALIDRAW_DESC:
"包括:以影像形式嵌入到繪圖中的 PDF、以互動或影像形式嵌入到繪圖中的 Markdown 文件等。",
MD_HEAD: "以影像形式嵌入到繪圖中的 Markdown 文件(MD-Embed)",
MD_GROUP_DESC:
"設定以影像呈現的 Markdown 檔案之尺寸、字型、顏色、邊框和 CSS。",
MD_EMBED_CUSTOMDATA_HEAD_NAME:
"以互動形式嵌入到繪圖中的 Markdown 文件(MD-Embeddable)",
MD_EMBED_CUSTOMDATA_GROUP_DESC:
"設定未來互動式 Markdown 嵌入的編輯方式和預設外觀。",
MD_EMBED_DEFAULTS_CONTROL_NAME: "互動式 Markdown 預設外觀",
MD_EMBED_CUSTOMDATA_HEAD_DESC: `以下設定只會影響以後的嵌入。已存在的嵌入保持不變。嵌入框的主題設定位於“介面 & 行為”部分。`,
MD_EMBED_SINGLECLICK_EDIT_NAME: "單擊編輯嵌入的 Markdown",
MD_EMBED_SINGLECLICK_EDIT_DESC:
@@ -906,12 +1028,17 @@ export default {
EMBED_HEAD: "嵌入到 Markdown 文件中的繪圖",
EMBED_DESC: `包括:嵌入到 Markdown 文件中的繪圖的預覽圖型別(SVG、PNG)、原始檔型別(Excalidraw、SVG、PNG)、快取、影像尺寸、影像主題,以及嵌入的語法等。
此外,還有自動匯出 SVG 或 PNG 檔案並保持與繪圖檔案狀態同步的設定。`,
EMBED_PREVIEW_LINKS_HEAD: "預覽、連結與 Canvas",
EMBED_PREVIEW_LINKS_DESC:
"選擇預覽和插入檔案的格式、來源連結行為、預留影像及沉浸式 Canvas 嵌入。",
EMBED_CANVAS: "Obsidian 白板支援",
EMBED_CANVAS_NAME: "沉浸式嵌入",
EMBED_CANVAS_DESC:
"當嵌入繪圖到 Obsidian 白板中時,隱藏節點的邊界和背景。" +
"注意:如果想要背景完全透明,您依然需要設定匯出背景為透明(關閉“匯出圖片包含背景”)。",
EMBED_CACHING: "影像快取和渲染最佳化",
EMBED_CACHING_DESC:
"調整平行渲染和本機圖片快取、清除快取圖片或備份,並可重用已匯出的預覽。",
RENDERING_CONCURRENCY_NAME: "影像渲染併發性",
RENDERING_CONCURRENCY_DESC:
"用於影像渲染的並行工作執行緒數。增加該值可以加快渲染速度,但可能會減慢系統其他部分的執行速度。" +
@@ -924,8 +1051,13 @@ export default {
"實際影響在於 Obsidian 內部的本地磁碟或瀏覽器儲存佔用。在手機以及瀏覽器儲存配額較緊、剩餘磁碟空間有限的桌面裝置上需要留意。<br><br>" +
"較小的值會更快回收本地快取空間,但可能導致 PDF 和嵌入繪圖更頻繁地重新渲染。較大的值會保留更久的快取,以換取更快的載入速度。",
EXPORT_SUBHEAD: "匯出",
EXPORT_SUBHEAD_DESC:
"設定 PDF 渲染、匯出的場景資料、影像尺寸、主題與背景、PDF 預設值及自動 PNG/SVG 副本。",
EMBED_SIZING: "影像尺寸",
EMBED_SIZING_DESC: "設定嵌入影像的預設尺寸、PNG 縮放比例和匯出邊距。",
EMBED_THEME_BACKGROUND: "影像的主題和背景色",
EMBED_THEME_BACKGROUND_DESC:
"選擇匯出影像的背景和主題,以及預覽是否跟隨 Obsidian 主題。",
EMBED_IMAGE_CACHE_NAME: "為嵌入到 Markdown 文件中的繪圖建立預覽圖快取",
EMBED_IMAGE_CACHE_DESC:
"可提高下次嵌入的速度。" +
@@ -1005,7 +1137,18 @@ export default {
"在匯出圖片中嵌入 Excalidraw 場景。可以在其 frontmatter 中新增如 <code>excalidraw-export-embed-scene: true/false</code> 的鍵值對來覆蓋該項。" +
"該項僅在您下次(重新)開啟繪圖時生效。",
PDF_EXPORT_SETTINGS: "PDF 匯出設定",
PDF_EXPORT_SETTINGS_DESC:
"選擇預設 PDF 頁面大小、方向、分頁、邊距、紙張顏色和對齊方式。",
PDF_EXPORT_DEFAULTS_CONTROL_NAME: "預設 PDF 匯出配置",
EXPORT_HEAD: "匯出設定",
EXPORT_AUTOEXPORT_DESC:
"保持匯出檔案同步,並自動建立 SVG、PNG、淺色和深色版本。",
SETTINGS_NAVIGATION_OPEN: "開啟",
SETTINGS_BREADCRUMB_ARIA: "設定路徑",
SETTINGS_RELATED_AUTOEXPORT_DESC:
"啟用自動 PNG 或 SVG 副本,使這些格式可在插入檔案類型下拉清單中選擇。",
SETTINGS_RELATED_EMBED_TYPE_DESC:
"選擇在文件中嵌入繪圖時插入 Excalidraw、PNG 還是 SVG。",
EXPORT_SYNC_NAME: "保持 SVG/PNG 檔名與繪圖檔案同步",
EXPORT_SYNC_DESC:
"開啟後,當繪圖檔案被重新命名時,外掛將同步更新同文件夾下的同名 .SVG 和 .PNG 檔案。" +
@@ -1078,8 +1221,11 @@ export default {
CUSTOM_PEN_DESC:
"在繪圖上的 Obsidian 選單按鈕旁邊切換自定義畫筆。長按(雙擊)畫筆按鈕可以修改其樣式。",
EXPERIMENTAL_HEAD: "雜項",
EXPERIMENTAL_DESC: `包括:預設的 LaTeX 公式,欄位建議,繪圖檔案的型別識別符號,OCR 等。`,
EXPERIMENTAL_DESC:
"設定 LaTeX 預設值、檔案類型標記、即時預覽行為、屬性建議,以及實驗性的 Taskbone OCR 整合。",
EA_HEAD: "Excalidraw 自動化",
EA_GROUP_DESC:
"設定 Excalidraw Automate 指令碼、啟動與自動啟動行為、命令連結,以及已安裝指令碼提供的設定。",
EA_DESC:
`ExcalidrawAutomate 是用於 Excalidraw 自動化指令碼的 API,但是目前說明文件還不夠完善,` +
`建議閱讀 <a href="${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_BLOB_MASTER_DOCS_API_EXCALIDRAWAUTOMATE_D_TS}">ExcalidrawAutomate.d.ts</a> 檔案原始碼,` +
@@ -1090,6 +1236,33 @@ export default {
FIELD_SUGGESTER_DESC:
"開啟後,當您在編輯器中輸入 <code>excalidraw-</code> 或者 <code>ea.</code> 時,會彈出一個帶有函式說明的自動補全提示選單。<br>" +
"該功能借鑑了 Breadcrumbs 和 Templater 外掛。",
ALLOW_JS_FILES_NAME: "從 Scripts 資料夾載入 JavaScript 檔案",
ALLOW_JS_FILES_DESC:
"啟用後,Excalidraw Automate 會監視並執行 Scripts 資料夾中的 <code>.js</code> 檔案,也允許使用 <code>.js</code> 啟動指令碼。" +
"預設情況下,Obsidian Sync 不會同步非 Markdown 檔案,Obsidian 不會開啟 <code>.js</code> 檔案進行編輯,檔案總管也會隱藏它們。需要時請在 Obsidian 中啟用<b>同步所有其他檔案類型</b>和<b>顯示所有檔案類型</b>。如果存在同名的 <code>.md</code> 和 <code>.js</code> 指令碼,將使用 Markdown 檔案。",
STORE_SCRIPTS_AS_JS_NAME: "將下載的指令碼儲存為",
STORE_SCRIPTS_AS_JS_DESC:
"選擇指令碼庫新下載與更新在本機使用的檔案類型。無論遠端來源是 <code>.md</code> 或 <code>.js</code>,都會使用此設定。",
SCRIPT_FILE_EXTENSION_MARKDOWN: "Markdown (.md)",
SCRIPT_FILE_EXTENSION_JAVASCRIPT: "JavaScript (.js)",
MIGRATE_SCRIPT_FILES_NAME: "遷移現有指令碼檔案",
MIGRATE_SCRIPTS_TO_JS_BUTTON: "將現有指令碼遷移為 .js",
MIGRATE_SCRIPTS_TO_MD_BUTTON: "將現有指令碼遷移為 .md",
MIGRATE_SCRIPT_FILES_STATUS:
"有 {eligible} 個指令碼檔案可遷移為 {extension}。{skipped}",
MIGRATE_SCRIPT_FILES_CONFIRM:
"繼續前請先備份儲存庫。<br><br><b>{count}</b> 個指令碼檔案將重新命名為 <code>{extension}</code>,釘選指令碼的路徑也會更新。{startup} {skipped}",
MIGRATE_SCRIPT_FILES_STARTUP_INCLUDED:
"已設定的啟動指令碼及其設定也會更新。",
MIGRATE_SCRIPT_FILES_SKIPPED:
"有 {count} 對同名 .md/.js 檔案不會被遷移。",
MIGRATE_SCRIPT_FILES_SKIPPED_DETAILS:
"因目標檔案已存在,已略過 {count} 個指令碼檔案:\n{files}",
MIGRATE_SCRIPT_FILES_NONE: "找不到可遷移的指令碼檔案。",
MIGRATE_SCRIPT_FILES_COMPLETE:
"已將 {count} 個指令碼檔案遷移為 {extension}。",
MIGRATE_SCRIPT_FILES_FAILED:
"無法遷移指令碼檔案。已盡可能回復完成的重新命名。",
ENABLE_ONLOAD_SCRIPTS_NAME: "載入期指令碼(onload)",
ENABLE_ONLOAD_SCRIPTS_CONFIRMATION:
"此檔案包含 <code>excalidraw-onload-script</code>。是否啟用載入期指令碼?",
@@ -1099,6 +1272,18 @@ export default {
"啟用後,Excalidraw 會在你之後開啟的所有繪圖中執行檔案級別的 <code>excalidraw-onload-script</code>,直到你關閉此設定。" +
"如果你從未知來源下載 Markdown 檔案,這會帶來風險:惡意行為者可以利用 <code>excalidraw-onload-script</code> " +
"在 Obsidian 中執行任意命令,並且有可能將資料傳輸到網際網路。只有在你信任該檔案及其來源時才啟用此功能。",
AUTOSTART_SCRIPT_PROMPT:
"希望在你每次開啟 Excalidraw 繪圖時自動執行。是否允許?",
AUTOSTART_SCRIPT_PROMPT_MANAGE_HINT:
"你之後可以在命令選擇區(「自動啟動指令碼」)或設定 → Excalidraw 自動化 → 自動啟動指令碼中變更此設定。",
AUTOSTART_SCRIPT_ALLOW: "自動啟動",
AUTOSTART_SCRIPT_DENY: "僅手動啟動",
AUTOSTART_SCRIPT_ASK_LATER: "每次都詢問",
AUTOSTART_SCRIPTS_HEAD: "自動啟動指令碼",
AUTOSTART_SCRIPTS_DESC:
"指令碼在請求權限以便每次開啟新的 Excalidraw 繪圖時自動執行後會出現在這裡(手動執行一次指令碼即可觸發該請求)。你可以隨時變更指令碼的設定。",
AUTOSTART_SCRIPTS_EMPTY: "尚無指令碼請求自動啟動權限。",
AUTOSTART_SCRIPT_FAILED_WARNING: "該指令碼上次自動啟動時失敗了。",
ENABLE_COMMAND_LINKS_NAME: "啟用命令連結(cmd://)",
ENABLE_COMMAND_LINKS_CONFIRMATION:
"此連結會透過 <code>cmd://</code> 觸發 Obsidian 命令。是否啟用命令連結?",
@@ -1109,9 +1294,10 @@ export default {
"如果你開啟未知來源的繪圖,這會帶來風險:惡意繪圖可以讓一次普通點選觸發高許可權命令。" +
"只有在你信任該檔案及其來源時才啟用此功能。",
STARTUP_SCRIPT_NAME: "啟動期指令碼(startup)",
STARTUP_SCRIPT_JS_DISABLED:
"JavaScript 啟動指令碼已停用。請先在 Excalidraw Automate 設定中啟用 JavaScript 檔案。",
STARTUP_SCRIPT_DESC:
"外掛啟動時將自動執行該指令碼。可用於設定 Excalidraw 自動化鉤子。" +
"該指令碼是包含 javascript 程式碼的 Markdown 檔案。",
"外掛啟動時將自動執行該指令碼,可用於設定 Excalidraw Automate 鉤子。沒有副檔名的路徑使用 Markdown 檔案;啟用 JavaScript 檔案載入後可使用 <code>.js</code> 檔案。",
STARTUP_SCRIPT_BUTTON_CREATE: "建立啟動期指令碼",
STARTUP_SCRIPT_BUTTON_OPEN: "開啟啟動期指令碼",
FILETYPE_NAME: "在檔案瀏覽器中為 excalidraw.md 檔案新增型別識別符號(如 ✏️)",
@@ -1152,6 +1338,8 @@ export default {
"為了獲得最佳效能,建議使用 .woff2 檔案,因為當匯出 SVG 格式的圖片時,Excalidraw 只會編碼必要的字形。" +
`其他字型格式將在匯出檔案中嵌入整個字型,可能會導致檔案大小顯著增加。<b>譯者注:</b>可在 <a href="${URLs.WANGCHUJIANG_COM_FREE_FONT}" target='_blank'>Free Font</a> 獲取免費商用中文手寫字型。`,
OFFLINE_CJK_NAME: "離線 CJK 字型支援",
OFFLINE_CJK_GROUP_DESC:
"下載並按需預先載入中文、日文和韓文字型,讓 Excalidraw 在沒有網際網路連線時也能顯示這些字型。",
OFFLINE_CJK_DESC: `<strong>該項需要重啟 Obsidian 才能生效。</strong><br>
Excalidraw.com 提供手寫風格的 CJK 字型。預設情況下,這些字型不會包含在外掛本地,而是從網際網路獲取。
如果您希望 Excalidraw 完全本地化,以便在沒有網際網路連線的情況下使用,可以從 <a href="${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_RAW_REFS_HEADS_MASTER_ASSETS_EXCALIDRAW_FONTS_ZIP}" target="_blank">GitHub 下載所需的字型檔案</a>。
@@ -1168,6 +1356,8 @@ export default {
SCRIPT_SETTINGS_DESC:
"有些 Excalidraw 自動化指令碼包含設定項,當執行這些指令碼時,它們會在該列表下新增設定項。",
TASKBONE_HEAD: "Taskbone OCR(光學符號識別)",
TASKBONE_GROUP_DESC:
"設定選用的 Taskbone 線上 OCR 服務,從繪圖與影像中擷取可搜尋文字。",
TASKBONE_DESC:
"這是一個將 OCR 融入 Excalidraw 的實驗性功能。請注意,Taskbone 是一項獨立的外部服務,而不是由 Excalidraw 或 obsidian-excalidraw-plugin 專案提供的。" +
"OCR 能夠對繪圖上用自由畫筆工具寫下的塗鴉或者嵌入的影像進行文字識別,並將識別出來的文字寫入繪圖檔案的 frontmatter,同時複製到剪貼簿。" +
@@ -1338,6 +1528,7 @@ export default {
PROMPT_BUTTON_NEVERMIND: "算了",
PROMPT_BUTTON_OK: "OK",
PROMPT_BUTTON_CANCEL: "取消",
PROMPT_BUTTON_CLOSE: "關閉",
PROMPT_BUTTON_INSERT_LINE: "插入一行",
PROMPT_BUTTON_INSERT_SPACE: "插入空格",
PROMPT_BUTTON_INSERT_LINK: "插入內部連結",
@@ -1363,6 +1554,7 @@ export default {
//InsertPDFModal.ts
IPM_PAGES_TO_IMPORT_NAME: "要匯入的頁面",
IPM_PAGES_TO_IMPORT_DESC: "例如:1,3-5,7,9-10",
IPM_SELECT_PAGES_TO_IMPORT: "請選擇頁面以進行匯入",
IPM_ADD_BORDER_BOX_NAME: "新增帶邊框的盒子容器",
IPM_ADD_FRAME_NAME: "新增頁面到畫框",
@@ -1604,4 +1796,19 @@ Obsidian 的 Excalidraw 外掛遠不只是畫圖工具。由於它與 Obsidian
EXTRAS_GATEWAY_COMP_PLUGIN: "Excalidraw Extras 外掛",
EXTRAS_GATEWAY_UPDATE_TITLE: "Excalidraw 需要新版本的 Extras 外掛",
EXTRAS_GATEWAY_UPDATE_BTN: "開啟社群外掛",
//ObserverManager.ts
ERROR_ADDING_OBSERVER_MANAGER: "新增 ObserverManager 時發生錯誤",
//PublishOutOfDateFiles.ts
POODF_TITLE: "過期的 SVG 檔案",
POODF_CHECK_RECURSIVE: "遞迴檢查",
POODF_OPEN_SELECTED: "開啟所選項",
//ImageCache.ts
IMAGE_CACHE_INITIALIZED:
"Excalidraw 圖片快取已初始化 - 您現在可以重試開啟損壞的繪圖。",
//carveout.ts
NEW_DRAWING_TIMEOUT: "找不到檔案。建立新的 Excalidraw 繪圖耗時過長。請重試。",
};
+165
View File
@@ -0,0 +1,165 @@
type PendingBackup = {
data: string;
};
type BackupWriteState = {
timer: number | null;
inFlight: Promise<void> | null;
pending: PendingBackup | null;
};
type BackupPersistenceQueueOptions = {
ownerWindow: Window;
write: (filepath: string, data: string) => Promise<void>;
onError?: (error: unknown, stage: "write") => void;
};
/**
* Coalesces plugin-global drawing backups by vault path.
*
* @remarks
* Each path owns at most one IndexedDB write and one latest trailing payload.
* The timer belongs to the main application window because persistent plugin
* storage is shared by main and popout views.
*/
export class BackupPersistenceQueue {
private readonly ownerWindow: Window;
private readonly write: BackupPersistenceQueueOptions["write"];
private readonly onError?: BackupPersistenceQueueOptions["onError"];
private readonly writes = new Map<string, BackupWriteState>();
constructor(options: BackupPersistenceQueueOptions) {
this.ownerWindow = options.ownerWindow;
this.write = options.write;
this.onError = options.onError;
}
/**
* Schedules the latest payload for a path.
*
* @returns `true` when an older pending payload was replaced or the new
* payload was coalesced behind an active write.
*/
public schedule(filepath: string, data: string, delayMs: number): boolean {
let state = this.writes.get(filepath);
if (!state) {
state = { timer: null, inFlight: null, pending: null };
this.writes.set(filepath, state);
}
const coalesced = state.pending !== null || state.inFlight !== null;
state.pending = { data };
this.clearTimer(state);
if (state.inFlight === null) {
this.scheduleDrain(filepath, state, delayMs);
}
return coalesced;
}
/** Writes all currently pending data for one path without the normal delay. */
public async flush(filepath: string): Promise<void> {
const state = this.writes.get(filepath);
if (!state) {
return;
}
this.clearTimer(state);
while (this.writes.get(filepath) === state) {
this.clearTimer(state);
if (state.inFlight !== null) {
try {
await state.inFlight;
} catch {
// The owning drain reports the write failure and releases state.
}
continue;
}
if (state.pending === null) {
break;
}
await this.drain(filepath, state, 0);
}
}
/** Cancels queued data and waits for an already-active write to settle. */
public async cancel(filepath: string): Promise<void> {
const state = this.writes.get(filepath);
if (!state) {
return;
}
this.clearTimer(state);
state.pending = null;
this.writes.delete(filepath);
if (state.inFlight !== null) {
try {
await state.inFlight;
} catch {
// The owning drain reports the write failure; cancellation still wins.
}
}
}
/** Cancels every queued backup before the backup store is cleared. */
public async cancelAll(): Promise<void> {
await Promise.all(
Array.from(this.writes.keys(), (filepath) => this.cancel(filepath)),
);
}
/** Drops timers and references during plugin unload without starting writes. */
public destroy(): void {
this.writes.forEach((state) => this.clearTimer(state));
this.writes.clear();
}
private clearTimer(state: BackupWriteState): void {
if (state.timer !== null) {
this.ownerWindow.clearTimeout(state.timer);
state.timer = null;
}
}
private scheduleDrain(
filepath: string,
state: BackupWriteState,
delayMs: number,
): void {
state.timer = this.ownerWindow.setTimeout(() => {
state.timer = null;
void this.drain(filepath, state, delayMs);
}, delayMs);
}
private async drain(
filepath: string,
state: BackupWriteState,
trailingDelayMs: number,
): Promise<void> {
if (
this.writes.get(filepath) !== state ||
state.inFlight !== null ||
state.pending === null
) {
return;
}
const pending = state.pending;
state.pending = null;
const write = this.write(filepath, pending.data);
state.inFlight = write;
try {
await write;
} catch (error: unknown) {
this.onError?.(error, "write");
} finally {
if (this.writes.get(filepath) === state) {
state.inFlight = null;
if (state.pending !== null) {
this.scheduleDrain(filepath, state, trailingDelayMs);
} else {
this.writes.delete(filepath);
}
}
}
}
}
+3 -1
View File
@@ -8,6 +8,7 @@ import { svgToBase64 } from "../utils/utils";
import { ExportSettings } from "src/types/exportUtilTypes";
import { nanoid } from "src/constants/constants";
declare const deliberateCreateElement: (document: Document, tagName: string) => HTMLElement;
declare const mainDocument: Document;
/**
* Creates a masked image from an Excalidraw scene.
@@ -204,7 +205,8 @@ export class CropImage {
//https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2026
const svgData = svg.outerHTML;
//const svgData = new XMLSerializer().serializeToString(svg);
const canvas = mainDocument.createElement("canvas");
// canvas should never be attached to the DOM
const canvas = deliberateCreateElement(mainDocument, "canvas") as HTMLCanvasElement;
const context = canvas.getContext("2d");
if (!context) {
@@ -0,0 +1,105 @@
import { Modal, Setting } from "obsidian";
import ExcalidrawPlugin from "src/core/main";
import { t } from "src/lang/helpers";
import { fragWithHTML } from "src/utils/utils";
/**
* Lists every script that has ever called `ExcalidrawAutomate.
* registerAutostart()` (i.e. the user ran it at least once), each with an
* editable Autostart / Manual start only / Ask every time control (reusing
* the exact same labels as the permission prompt's buttons, so the two
* surfaces speak one consistent vocabulary), and a warning if the script's
* most recent autostart run failed (`settings.autostartScriptFailures`,
* purely informational - it never changes the script's setting on its
* own). A "Manual start only" (deny) decision is not a dead end: it can be
* switched straight back to Autostart or Ask every time from here, without
* needing to re-run the script to get prompted again.
*
* Rendered as a bordered table (header row + one row per script), reusing
* the AI provider table's existing `.excalidraw-ai-provider-table` CSS (see
* `renderAISettings()` in `settings.ts`) rather than adding near-duplicate
* rules to `styles.css`, and rather than a foldable `<details>` section,
* since this is a short, flat list rather than a large collapsible
* settings group. Rendered both inline in Settings (under the Startup
* script setting, in the ExcalidrawAutomate section) and inside
* `AutostartScriptsModal` for the Command Palette entry point, matching
* how `EmbeddalbeMDFileCustomDataSettingsComponent` is reused across
* contexts.
*/
export class AutostartScriptsSettingsComponent {
constructor(
private contentEl: HTMLElement,
private plugin: ExcalidrawPlugin,
) {}
render(): void {
this.contentEl.empty();
this.contentEl.addClass("excalidraw-ai-provider-table");
const autostartScripts = this.plugin.settings.autostartScripts;
const scriptNames = Object.keys(autostartScripts).sort();
const headerSetting = new Setting(this.contentEl)
.setName(t("AUTOSTART_SCRIPTS_HEAD"))
.setDesc(fragWithHTML(t("AUTOSTART_SCRIPTS_DESC")));
headerSetting.settingEl.addClass("excalidraw-ai-provider-table__header");
if (scriptNames.length === 0) {
const emptyRow = new Setting(this.contentEl).setDesc(
t("AUTOSTART_SCRIPTS_EMPTY"),
);
emptyRow.settingEl.addClass("excalidraw-ai-provider-table__row");
return;
}
scriptNames.forEach((scriptName) => {
const rowSetting = new Setting(this.contentEl)
.setName(scriptName)
.addDropdown((dropdown) =>
dropdown
.addOption("allow", t("AUTOSTART_SCRIPT_ALLOW"))
.addOption("deny", t("AUTOSTART_SCRIPT_DENY"))
.addOption("unknown", t("AUTOSTART_SCRIPT_ASK_LATER"))
.setValue(autostartScripts[scriptName])
.onChange(async (value) => {
autostartScripts[scriptName] = value as
| "allow"
| "deny"
| "unknown";
await this.plugin.saveSettings();
}),
);
rowSetting.settingEl.addClass("excalidraw-ai-provider-table__row");
if (this.plugin.settings.autostartScriptFailures[scriptName]) {
rowSetting.setDesc(
fragWithHTML(
`<span style="color: var(--text-error);">${t("AUTOSTART_SCRIPT_FAILED_WARNING")}</span>`,
),
);
}
});
}
}
export class AutostartScriptsModal extends Modal {
constructor(private plugin: ExcalidrawPlugin) {
super(plugin.app);
}
onOpen(): void {
this.titleEl.setText(t("AUTOSTART_SCRIPTS_HEAD"));
new AutostartScriptsSettingsComponent(
this.contentEl,
this.plugin,
).render();
new Setting(this.contentEl).addButton((button) =>
button.setButtonText(t("PROMPT_BUTTON_CLOSE")).onClick(() => this.close()),
);
}
onClose(): void {
this.contentEl.empty();
}
}
+4 -9
View File
@@ -99,13 +99,13 @@ export const showColorPicker = async (
}
return new Promise((resolve) => {
const overlay = activeDocument.createElement("div");
const overlay = activeDocument.body.createDiv();
overlay.classList.add("excalidraw-colorpicker-overlay");
const popup = activeDocument.createElement("div");
const popup = overlay.createDiv();
popup.classList.add("excalidraw-colorpicker-popup");
const grid = activeDocument.createElement("div");
const grid = popup.createDiv();
grid.classList.add("excalidraw-colorpicker-grid");
setStyle(grid, {
gridTemplateColumns: `repeat(${GRID_COLUMNS}, ${CELL_SIZE}px)`,
@@ -114,19 +114,14 @@ export const showColorPicker = async (
});
colors.forEach((color) => {
const swatch = activeDocument.createElement("button");
const swatch = grid.createEl("button");
swatch.type = "button";
swatch.ariaLabel = color;
swatch.classList.add("excalidraw-colorpicker-swatch");
setStyle(swatch, { backgroundColor: color });
swatch.addEventListener("click", () => cleanup(color));
grid.appendChild(swatch);
});
popup.appendChild(grid);
overlay.appendChild(popup);
activeDocument.body.appendChild(overlay);
positionPopup(popup, anchorElement);
const cleanup = attachOutsideHandlers(overlay, popup, resolve);
+46
View File
@@ -0,0 +1,46 @@
import { Notice, normalizePath } from "obsidian";
import type ExcalidrawPlugin from "src/core/main";
import { t } from "src/lang/helpers";
import { MultiOptionConfirmationPrompt } from "./Prompt";
/** Confirms and creates a missing vault folder without overwriting files. */
export const confirmAndCreateFolder = async (
plugin: ExcalidrawPlugin,
requestedPath: string,
): Promise<boolean> => {
const path = normalizePath(requestedPath.trim());
if (!path) {
return false;
}
if (plugin.app.vault.getFolderByPath(path)) {
return true;
}
if (plugin.app.vault.getFileByPath(path)) {
new Notice(t("CREATE_FOLDER_PATH_IS_FILE").replace("{PATH}", path), 6000);
return false;
}
const confirmed = await new MultiOptionConfirmationPrompt<boolean | null>(
plugin,
t("CREATE_FOLDER_CONFIRM").replace("{PATH}", path),
new Map<string, boolean | null>([
[t("CREATE_FOLDER_NEVER_MIND"), false],
[t("CREATE_FOLDER_YES"), true],
]),
t("CREATE_FOLDER_YES"),
).waitForClose;
if (confirmed !== true) {
return false;
}
try {
await plugin.app.vault.createFolder(path);
new Notice(t("CREATE_FOLDER_SUCCESS").replace("{PATH}", path));
return true;
} catch (error) {
console.error(`Could not create folder '${path}'`, error);
new Notice(t("CREATE_FOLDER_FAILED").replace("{PATH}", path), 6000);
return false;
}
};
@@ -53,6 +53,7 @@ export class EmbeddalbeMDFileCustomDataSettingsComponent {
.setValue(this.mdCustomData.filenameVisible)
.onChange((value) => {
this.mdCustomData.filenameVisible = value;
this.update();
}),
);
@@ -72,6 +73,7 @@ export class EmbeddalbeMDFileCustomDataSettingsComponent {
.setValue(this.mdCustomData.propertiesVisible ?? true)
.onChange((value) => {
this.mdCustomData.propertiesVisible = value;
this.update();
});
if (!this.isFullFile || isGlobalHidden) {
toggle.setDisabled(true);
@@ -91,6 +93,7 @@ export class EmbeddalbeMDFileCustomDataSettingsComponent {
.setValue(!!this.mdCustomData.lockedReadingMode)
.onChange((value) => {
this.mdCustomData.lockedReadingMode = value;
this.update();
}),
);
}
@@ -120,6 +123,7 @@ export class EmbeddalbeMDFileCustomDataSettingsComponent {
if (value) {
hideElement(bgSetting.settingEl);
if (this.mdCustomData.backgroundMatchCanvas) {
this.mdCustomData.backgroundMatchCanvas = false;
bgMatchCanvasToggle.setValue(false);
}
} else if (!this.mdCustomData.backgroundMatchCanvas) {
@@ -140,6 +144,7 @@ export class EmbeddalbeMDFileCustomDataSettingsComponent {
if (value) {
hideElement(bgSetting.settingEl);
if (this.mdCustomData.backgroundMatchElement) {
this.mdCustomData.backgroundMatchElement = false;
bgMatchElementToggle.setValue(false);
}
} else if (!this.mdCustomData.backgroundMatchElement) {
+2 -2
View File
@@ -3,7 +3,7 @@ import { Modal, Notice, Setting, TFile } from "obsidian";
import { getEA } from "src/core";
import { DEVICE } from "src/constants/constants";
import { ExcalidrawAutomate } from "src/shared/ExcalidrawAutomate";
import ExcalidrawView from "src/view/ExcalidrawView";
import type ExcalidrawView from "src/view/ExcalidrawView";
import ExcalidrawPlugin from "src/core/main";
import {
fragWithHTML,
@@ -81,7 +81,7 @@ export class ExportDialog extends Modal {
this.theme = getExportTheme(
this.plugin,
this.file,
this.api.getAppState().theme as string,
this.api.getAppState().theme,
);
this.boundingBox = this.ea.getBoundingBox(this.ea.getViewElements());
this.embedScene = shouldEmbedScene(this.plugin, this.file);
@@ -0,0 +1,107 @@
import { Modal, Setting, type App, type ButtonComponent } from "obsidian";
import { t } from "src/lang/helpers";
import { VaultPathSuggest } from "src/shared/Suggesters/VaultPathSuggest";
/** Folder and filename selected in a {@link FileAndFolderSelectorModal}. */
export type FileAndFolderSelection = {
folderPath: string;
fileName: string;
};
/** Labels and initial values for a {@link FileAndFolderSelectorModal}. */
export type FileAndFolderSelectorOptions = FileAndFolderSelection & {
title: string;
folderLabel: string;
fileNameLabel: string;
submitButtonText: string;
};
/** Prompts for a Vault folder and filename. */
export class FileAndFolderSelectorModal extends Modal {
private resolvePromise: (
selection: FileAndFolderSelection | null,
) => void;
private result: FileAndFolderSelection | null = null;
constructor(
app: App,
private readonly options: FileAndFolderSelectorOptions,
) {
super(app);
}
/** Opens the modal and resolves with the selection or null when cancelled. */
public start(): Promise<FileAndFolderSelection | null> {
const result = new Promise<FileAndFolderSelection | null>((resolve) => {
this.resolvePromise = resolve;
});
this.open();
return result;
}
public onOpen(): void {
this.titleEl.setText(this.options.title);
this.contentEl.addClass("excalidraw-file-and-folder-selector");
let folderPath = this.options.folderPath;
let fileName = this.options.fileName;
let submitButton: ButtonComponent | null = null;
const updateSubmitButton = (): void => {
submitButton?.setDisabled(fileName.trim().length === 0);
};
const folderSetting = new Setting(this.contentEl)
.setClass("excalidraw-file-and-folder-selector__field")
.setName(this.options.folderLabel)
.addText((text) => {
text.setValue(folderPath).onChange((value) => {
folderPath = value.trim();
});
new VaultPathSuggest(this.app, text.inputEl, "folder");
});
folderSetting.controlEl.addClass("excalidraw-folder-path-control");
let fileNameInput: HTMLInputElement | null = null;
new Setting(this.contentEl)
.setClass("excalidraw-file-and-folder-selector__field")
.setName(this.options.fileNameLabel)
.addText((text) => {
fileNameInput = text.inputEl;
text.setValue(fileName).onChange((value) => {
fileName = value;
updateSubmitButton();
});
});
new Setting(this.contentEl)
.addButton((button) =>
button
.setButtonText(t("PROMPT_BUTTON_CANCEL"))
.onClick(() => this.close()),
)
.addButton((button) => {
submitButton = button;
button
.setCta()
.setButtonText(this.options.submitButtonText)
.onClick(() => {
this.result = {
folderPath,
fileName: fileName.trim(),
};
this.close();
});
updateSubmitButton();
});
this.containerEl.ownerDocument.defaultView?.setTimeout(
() => fileNameInput?.focus(),
0,
);
}
public onClose(): void {
this.contentEl.empty();
this.resolvePromise?.(this.result);
}
}
+1 -1
View File
@@ -1,7 +1,7 @@
import { BaseComponent, Setting, Modifier } from "obsidian";
import { DEVICE } from "src/constants/constants";
import { t } from "src/lang/helpers";
import { ExcalidrawSettings } from "src/core/settings";
import type { ExcalidrawSettings } from "src/core/settingsDefaults";
import { modifierLabel } from "src/utils/modifierkeyHelper";
import { fragWithHTML } from "src/utils/utils";
import { setStyle } from "src/utils/styleUtils";
+6 -7
View File
@@ -2,7 +2,7 @@ import { FuzzySuggestModal, TFile } from "obsidian";
import ExcalidrawView from "../../view/ExcalidrawView";
import { t } from "../../lang/helpers";
import ExcalidrawPlugin from "../../core/main";
import { getEA } from "src/core";
import { UniversalInsertFileModal } from "./UniversalInsertFileModal";
export class InsertMDDialog extends FuzzySuggestModal<TFile> {
public plugin: ExcalidrawPlugin;
@@ -40,12 +40,11 @@ export class InsertMDDialog extends FuzzySuggestModal<TFile> {
}
onChooseItem(item: TFile): void {
const ea = getEA(this.view);
void (async () => {
await ea.addImage(0, 0, item);
await ea.addElementsToView(true, false, true);
ea.destroy();
})();
new UniversalInsertFileModal(this.plugin, this.view).open(
item,
this.view.currentPosition,
"image",
);
}
public start(view: ExcalidrawView) {
+3 -2
View File
@@ -13,6 +13,7 @@ import { getEA } from "src/core";
import { t } from "src/lang/helpers";
import { NamedExcalidrawFrameElement } from "src/types/excalidrawElementTypes";
import type { PdfJsDocumentProxy } from "src/types/pdfJsTypes";
import { log } from "src/utils/debugHelper";
import { setSanitizedHtml } from "src/utils/htmlUtils";
import { hideElement, setStyle, showElement } from "src/utils/styleUtils";
@@ -97,7 +98,7 @@ export class InsertPDFModal extends Modal {
height: viewport.height,
});
} catch (e) {
console.log(e);
log(e);
}
}
this.setImageSizeMessage();
@@ -287,7 +288,7 @@ export class InsertPDFModal extends Modal {
numPagesMessages();
new Setting(ce)
.setName(t("IPM_PAGES_TO_IMPORT_NAME"))
.setDesc("e.g.: 1,3-5,7,9-10")
.setDesc(t("IPM_PAGES_TO_IMPORT_DESC"))
.addText((text) => {
pageRangesTextComponent = text;
text.setValue("").onChange(async (value) => {
+88 -255
View File
@@ -17,18 +17,99 @@ I build this plugin as a labor of love. Curious about the philosophy behind it?
<div class="ex-coffee-div"><a href="${URLs.KO_FI_COM_ZSOLT}"><img src="${URLs.CDN_KO_FI_COM_CDN_KOFI3_PNG}" border="0" alt="Buy Me a Coffee at ko-fi.com" height=45></a></div>
`,
"2.26.0": `
"2.27.0": `
## New
- Added editable Markdown images. Their source can be stored locally as back-of-the-card markdown content in the drawing or linked to an external Markdown note, heading, or block. Edit content and appearance in the Excalidraw sidepanel or use the action menu on a selected Markdown image; Markdown images participate in normal canvas layering and image export. You can convert interactive embeddables into images and back in the embeddale/image menu in the top left of the selected element.
- On Obsidian 1.13 and newer, Excalidraw now uses Obsidian's searchable, multi-page settings. Settings are organized into clearer sections with breadcrumbs, compact help links, and clickable links between related options.
- Prefer the previous experience? Turn off **Use searchable settings** at the top of Excalidraw settings and restart Obsidian. Older Obsidian versions continue using the legacy single-page layout automatically.
- Settings exposed by installed Excalidraw Automate scripts have moved to **Excalidraw Automate → Settings for installed scripts** and update when a script adds or changes its settings.
- Excalidraw Automate can optionally load and monitor JavaScript (\`.js\`) files in the Scripts folder, use an explicit \`.js\` startup script, and store Script Library downloads as either Markdown or JavaScript. Existing scripts can be moved between the two formats while updating startup and pinned-script paths. [#2901](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2901)
- Markdown notes created from unresolved links in a drawing now follow Obsidian's **Default location for new notes** setting. [#2916](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2916)
## New from Excalidraw.com
- Improved bucket tool and eyedropper support. [#11849](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/11849)
- Lasso selection now respects box selection mode: contain or overlap. [#11862](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/11862)
- Customize color-picker top picks by dragging colors onto the strip; right-click the strip to reset it. [#11872](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/11872)
## Fixed
- Moving a dirty drawing out of a popout window now safely transfers and persists its latest edits from the replacement main-window view.
- Opening the command palette or another Obsidian modal reliably saves dirty drawings, while inline link suggestions no longer trigger a save that can end text editing.
- Converting a legacy ".excalidraw" drawing now persists its embedded images as vault attachments during conversion, before the source file can be removed. [#2898](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2898)
- Entering text editing no longer scans and sorts the entire vault for link suggestions; file-link candidates are loaded only after typing \`[[\`. [#2907](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2907)
- Settings changes are saved promptly without collapsing sections or interrupting fast typing. Writes are serialized, and Excalidraw keeps a device-local recovery copy so an empty or corrupted synchronized **data.json** cannot silently erase a large settings configuration.
- Interdependent settings now initialize and refresh consistently, including TODO icons, auto-export formats, Taskbone credentials, filename previews, and custom grid colors. Built-in font previews also use the correct typeface in secondary Obsidian windows.
- Applying a rendering-related setting no longer resets the live zoom and scroll position of an open drawing. New configurations use ☑ as the completed-TODO marker.
- Interactive Markdown embed defaults now save filename, properties, locked-reading-mode, and background-source changes reliably.
- The color palette uses the available height, keeps its native picker aligned, remembers customized top picks after reload, and updates popover theming immediately after a canvas background change.
- Text-to-diagram chat history is visible again, so saved chats can be restored or deleted.
- Stencil-library JSON is now tab-indented for cleaner Git diffs. [#2883](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2883)
## Maintenance
- This is one of the Plugin's largest internal maintenance releases. The settings system, persistence pipeline, plugin lifecycle, runtime packaging, and several major managers were reorganized into clearer, independently maintained components. The visible workflow remains familiar, but the foundation is substantially safer for future features and fixes.
- The embedded Excalidraw runtime now uses a modern ESM-source build and React 19 instead of the retired UMD pipeline. Offline use and popout windows remain supported; the Assistant UI font is bundled locally and Mermaid still loads on demand through Excalidraw Extras.
- Drawings with many cached embedded files load more efficiently by avoiding redundant cache rewrites, SVG reconstruction, image measurement, hashing, and normalization. Cached and direct images can appear before slower generated drawings, while drawing backups remain protected.
- Removed unused code and the obsolete Draw.io/Diagram integration, and retired the non-functional Create DrawIO file script.
## New in Excalidraw Automate
- \`setView(null)\` now explicitly clears \`ea.targetView\`. Use \`setView()\` or \`setView("auto")\` when you want EA to select a sensible default drawing.
- Scripts can register custom buttons in the selected-element context menu:
\`\`\`ts
registerElementActionProvider(getActions: (element: ExcalidrawElement) => readonly {id: string, title: string, icon: string, action: () => void}[]): (() => void) | null;
\`\`\`
- Scripts can request permission to run automatically whenever an Excalidraw view opens. Manage permissions with the **Autostart scripts** command or under Excalidraw Automate settings:
\`\`\`ts
registerAutostart(message?: string): Promise<"allow" | "deny" | "pending">;
\`\`\`
- Pass an optional message to explain what the script does during autostart. It appears between the permission question and the settings hint.
- Scripts can release listeners, timers, observers, and other external resources with EA-owned cleanup:
\`\`\`ts
registerCleanup(cleanup: () => void): () => void;
\`\`\`
- Scripts can distinguish \`manual\`, \`plugin-startup\`, \`view-autostart\`, \`sidepanel-restore\`, \`sidepanel-reload\`, and \`drawing-onload\` execution through \`utils.executionSource\`. Compilation caching is transparent and does not retain script runtime state.
`,
"2.26.4": `
## Fixed
- Markdown-image edits could be lost in some usage scenarios, 2.26.3 did not provide a broad enough fix. [#2865](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2865)
`,
"2.26.3": `
## Fixed
- Editing one Markdown image and immediately selecting another to edit could silently drop the first image's contents, both from memory and from the note on disk. Reported on the [Sketch Your Mind community](${URLs.COMMUNITY_SKETCH_YOUR_MIND_COM}/t/excalidraw-2-26-0/7791/2). 🙏
- Deleting the last local Markdown image via the Excalidraw properties panel's delete button no longer skips the prompt to keep or delete its Markdown content. Deletion detection now covers every trigger (keyboard, Cut, context menu, panel button, or scripts) uniformly.
## New from Excalidraw.com
- New tool: Bucket fill. See more tools menu, or press B to toggle the bucket fill tool. [#11799](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/11799)
`,
"2.26.2": `
${getYouTubeDiv("p9MBFxUoOXQ")}
## New
- Stencil libraries can now be stored as vault files instead of \`data.json\`, improving plugin settings stability. Existing users are offered a safe, merge-first migration. To sync libraries, enable **Sync all other types** in Obsidian Sync. To view library files, enable **Show all file types** in Obsidian settings.
- Added editable Markdown images.
- Store content locally (back-of-the-card) or link to a Markdown note, heading, or block.
- Edit content and appearance from the Excalidraw side panel.
- Supports canvas layering and image export.
- Dragging a Markdown note as an image lets you choose a heading (when available) and insert it as either an editable Markdown image or embeddable.
- Local Markdown image copies share the same source. Use **Duplicate selected image** to create an independent image and Markdown body. You can also convert between images and embeddables from the selected element's menu.
- Image-reference embeds now support an optional \`padding=N\` parameter, e.g.: \`![[drawing#^area=xyz,padding=10]]\` [#2850](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_PULL}/2850) 🙏[@Evgene-Kopylov](${URLs.GITHUB_COM}/Evgene-Kopylov)
- Added the Voronoi diagram script. 🙏[@FreeCutter](${URLs.GITHUB_COM}/FreeCutter) [#2845](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_PULL}/2845)
- Dragging a single external GIF with the **Import external file** action now lets you import it as either an image or an embeddable. [#2848](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2848)
- Folder and file path settings now provide vault suggestions, warn about missing paths, and can create missing folders after confirmation.
## New and fixed from Excalidraw.com
- New: flowchart (CTRL/CMD+arrow keys) now intelligently routes new shapes to avoid overlap of flowchart children [#11532](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/11532)
- New Draw To Shape feature: Draw a shape freehand, and Excalidraw will automatically convert it to a perfect shape. [#9313](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/9313)
- Fixed: Dragged arrow endpoint ignore grid and angle locks [#10972](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/10972)
- New: Double-click to toggle arrowhead [#11615](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/11615)
- New: Flowchart (CTRL/CMD+Arrow) now intelligently routes new shapes to avoid overlapping child nodes. [#11532](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/11532)
- New: Draw To Shape automatically converts freehand drawings into perfect shapes. [#9313](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/9313)
- Fixed: Dragged arrow endpoints now respect grid and angle locks. [#10972](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/10972)
- New: Double-click an arrow to toggle its arrowhead. [#11615](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/11615)
## Fixed
- Custom freedraw pens now remain selected after temporarily switching to the eraser or another tool, and are restored when returning to freedraw. [#2859](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2859)
- Added configurable bottom padding for Markdown images to prevent clipped final lines or borders.
- Markdown image font selectors now preview each font and refresh the vault font list whenever opened.
- Empty Markdown image font colors now normalize to black when the editor opens or the color field loses focus. CSS controls can also copy the generated SVG for inspection.
- Dragging an external video or other non-image file with the **Import external file** action now offers the same use, overwrite, or import options as images when a matching vault file already exists. [#2851](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_PULL}/2851) 🙏[@WolfExplode](${URLs.GITHUB_COM}/WolfExplode)
## Excalidraw Automate Breaking Change
- Excalidraw component API has discontinued \`api.scrollToContent(target?, opts?)\` and replaced it with \`api.setViewport(opts | null)\`. You'll need to update MindMap Builder and Comic Strip Director scripts. If you have your own scripts using this API function you'll need to update them accordingly. For more information read the Excalidraw [Change Log](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_CHANGELOG}#viewport-control--scrollzoom-locking)
- The Excalidraw API has replaced \`api.scrollToContent(target?, opts?)\` with \`api.setViewport(opts | null)\`. Update the MindMap Builder and Comic Strip Director scripts, along with any custom scripts using the old API. See the Excalidraw [Change Log](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_CHANGELOG}#viewport-control--scrollzoom-locking) for details.
`,
"2.25.3": `
Minor maintenance release with two important fixes.
@@ -420,253 +501,5 @@ async addImage(
anchor: boolean = true,
): Promise<string>;
\`\`\`
`,
"2.22.3": `
Feeling overwhelmed by Excalidraw's endless features?
It's not just a drawing tool. Inside Obsidian, it becomes a thinking tool.
To unlock linking, embedding, and referencing, you need a mindset shift.
**Join Excalidraw Mastery** to make that shift.
Courses, live Q&As, and deep dives to help you move into true 4D Visual PKM. 👉 https://community.sketch-your-mind.com/em
<div style="text-align:center;margin-top:10px;">
<a href="${URLs.COMMUNITY_SKETCH_YOUR_MIND_COM_EM}" target="_blank"><img src="${URLs.SKETCH_YOUR_MIND_COM_IMAGES_LOGO_EM_PNG}" style="width:50%"></a>
</div>
Excalidraw Mastery is part of the **Sketch Your Mind Community**—a space for visual thinkers.
Share your work. Ask questions. Learn from others. 👉 https://community.sketch-your-mind.com
Curious about the philosophy behind it?
${getYouTubeDiv("TnwRlaIdhSU")}
`,
"2.22.1": `
## New
- Added a command palette action to switch all currently open Excalidraw drawings to view mode.
- While this temporary mode is enabled, any Excalidraw drawing opened afterward will also open in view mode.
- This is useful when presenting multiple drawings and you want to avoid accidentally moving elements, and when you don't want the tools to be in the way.
- Added an optional phone-only layout setting to push Excalidraw's footer controls above the system navigation bar on some Android devices [#2688](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2688), [#2652](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2652), [#798](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/798)
- Look for ""Extra bottom padding for phone controls" in the plugin settings.
## Fixed
- invisible cursor color in color picker, mermaid chat, in text elements in dark mode [#2739](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2739)
- image sizing issue when embedding image type "SVG Image" to markdown
- copying a nested image fragment in Excalidraw and pasting to markdown lost the image block reference
- modifier keys conflicted with Excalidraw alt-select (lasso) behavior
`,
"2.22.0": `
## Fixed
- Fixed misaligned panel buttons in tray mode [#2718](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2718) 🙏[@heinrich26](${URLs.GITHUB_COM}/heinrich26)
- Improved loading of nested Excalidraw files within a scene, with some additional performance gains.
- Fixed an issue where the caret color did not match the text color [#11018](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_ISSUES}/11018)
## New from Excalidraw.com
- Added several text editing improvements, including a right-side handle on wrapped text for easier auto-resizing without opening the context menu [#10979](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/10979)
- Added support for Mermaid state diagrams [#11031](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/11031)
- There is a new Preferences menu above the Dark/Light mode switch in the main menu [#10760](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/10760)
- Added a new Preferences option to switch between Wrap and Overlap selection modes. Overlap mode behaves similarly to the lasso selection tool available under More Tools [#11053](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/11053)
## New
- Added support for embedding the [Sheet Plus](obsidian://show-plugin?id=sheet-plus) plugin as an active embeddable element in Excalidraw. At the moment, changing the canvas theme between dark and light mode does not automatically re-render embedded sheets. To apply the theme change, close and reopen the drawing. This will likely be improved in a future update.
`,
"2.21.3": `
## Fixed
- Caret color for link editor, text elemnts in dark mode, color picker input element.
- Link click behavior modifier keys setting in plugin settings now enforces CTRL/CMD for link clicks and improves on clarity of setting UI by adding a header row
- Link click conbinations that included ALT/OPT did not work because they trigger lasso selection in Excalidraw. This is now fixed, if you CTRL+ALT click a link it will navigate while retaining the lasso select feature when pressing ALT/OPT.
- Copying an image block embed (e.g. \`![[drawing#^frame=my_frame]]\`) from the excalidraw scene and pasting it to markdown no longer loses the frame reference
- Embed "SVG Image" to markdown should size correctly now when setting a percentage \`![[drawing|50%]]\` where 50% is relative to the width of the markdown note.
`,
"2.21.2": `
## Fixed
- The new ExcalidrawAutomate function \`parseText()\` broke if the text was a transcluded image or PDF document, causing downstream paste issues in MindMap Builder.
- Custom pen sloppiness not being saved to a template drawing [#2715](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_PULL}/2715) 🙏[@sreedharsreeram](${URLs.GITHUB_COM_SREEDHARSREERAM})
`,
"2.21.1": `
## Fixed
- Drawing and editor fails to initialize in a new window [#2713](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2713)
- Duplicate selected image with a different image ID command palette action did not duplicate cropped PDF images.
- Memory leak issue with PDF import as images.
## New
- Put caret at pointer position when clicking on selected text element [#10970](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/10970)
`,
"2.21.0": `
## New
- LaTeX editor is now floating [#2684](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_PULL}/2684) 🙏[@TravisLEBLANC1](${URLs.GITHUB_COM_TRAVISLEBLANC1}), [#2698](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_PULL}/2698) 🙏[@heinrich26](${URLs.GITHUB_COM}/heinrich26)
- Inline link suggester supports new triggers \`![[drawing#^frame=\` and \`![[drawing#^clippedframe=\`, thus it is easy to reference frames like pdf pages, slides or other parts of your scene marked using marker frames.
- Support for mermaid Entity Relationship Diagrams, and new ERD/cardinality arrowheads [#10940](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/10940)
- New Context Menu options to disable arrow binding and midpoint snapping [#10906](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/10906)
- Improved UI styling and icons are better aligned with Obsidian [#2703](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_PULL}/2703), [#2687](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_PULL}/2687), [#2697](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_PULL}/2697) 🙏[@heinrich26](${URLs.GITHUB_COM}/heinrich26)
## Fixed
- Sizing of embedded images in Markdown when image type is set to SVG [#2685](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2685)
- Fixed Enter, Up/Down arrows, and TAB keys stopped working in text elements after deleting the \`#\` character [#2704](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2704)
## MindMap Builder
- Fixed navigation (arrow keys) scoping and recognition
- Added new feature to paste images and single Excalidraw elements like container with text, text element, or image element directly as a map leaf (using the MindMap Builder default paste shortcut: ALT/OPT+V)
- Added new action to toggle a markdown link between markdown embeddable and link as text. Default shortcut is ALT/OPT+E.
## New in ExcalidrawAutomate
\`\`\`ts
/**
* Parses text using the target view's ExcalidrawData parser.
*
* This reuses ExcalidrawData parsing logic directly, including transclusion
* resolution, link bracket rendering, and link/url prefixes based on the
* target file's frontmatter.
*
* @param {string} text - Raw text to parse.
* @returns {Promise<string | undefined>} Parsed text, or undefined when input/view is unavailable.
*/
public async parseText (text: string): Promise<string | undefined>;
\`\`\`
`,
"2.20.6": `
${getYouTubeDiv("g-BiyQ7TJTM")}
## New
- Inline suggester now supports searching for tags in addition to files. Trigger with "#".
- In Mindmap Builder
- Added Up-Facing, Down-Facing, and Up-Down maps
- Added submaps. You can now promote any node to be a new mindmap root (a sub-map). Sub-maps can have different layout settings such as different growth strategies, different colors, etc.
- Added experimental MindMap Builder API, accessible via \`window.MindMapBuilderAPI\`. See [MindMap Builder API documentation](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_BLOB_MASTER_DOCS_EA_SCRIPT_DOCS_MINDMAPBUILDERAPI_MD}) for more. Essentially, the API allows mindmaps to be created using the Obsidian CLI.
## New from Excalidraw.com
- Allow clicking on links and embeds with laser tool [#10797](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/10797)
- Improved paste text to diagram with more options and support for more data [#10824](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/10824)
try copy/pasting this into Excalidraw:
\`\`\`
skill, junior, medior, senior
business_analysis, 2, 6, 9
business_writing, 3, 7, 9
stakeholder_mgmt, 1, 6, 10
\`\`\`
## New in ExcalidrawAutomate
- Added \`skipScriptRestore(scriptName?: string): boolean\` function to the API. This allows scripts to queue a one-time skip marker so sidepanel persisted restoration will not re-run the script. Intended for startup race conditions where a script is started from the Command Palette/hotkey before the sidepanel has opened. If scriptName is omitted, the function uses ea.activeScript.
## Fixed
- Significant performance improvement of MindMap Builder and all other scripts modifying elements in large scenes containing thousands of elements.
- Multiple arrow related updates and fixes from Excalidraw.com [#10832](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/10832) [#10831](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/10831) [#10816](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/10816)
- Hide MindMap Builder and other floating tools when creating a screenshot
`,
"2.20.5": `
## Fixed
- Obsidian Mobile: The floating navigation bar got stuck at the bottom after closing Excalidraw or switching to a markdown note. [#2673](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2673)
- "Toggle UI Mode" now includes a preference setting for Obsidian Phone as well. You can now set different default layouts for phone, tablet, and desktop. [#2670](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2670)
## New
- Added "Toggle Full Screen" button to toolbar right next to the "Obsidian menu", and the "Insert Any File" button.
`,
"2.20.4": `
## Fixed
- Fix NativeSVG embed mode into Markdown documents, ahead of the Obsidian 1.12.1 release. [#2665](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2665)
- Color picker once again supports 8-digit hex codes (Hex color string with an opacity). [#10772](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_ISSUES}/10772)
- Fixed regression that removed LaTeX scaling. [#2668](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_PULL}/2668) 🙏[@TravisLEBLANC1](${URLs.GITHUB_COM_TRAVISLEBLANC1})
- Corrected malformed frame embeds when using marker frames.
- Context menu options **“Do not invert image(s) in dark mode”** and **“Invert image(s) in dark mode”** now properly cascade when drawings are nested as images inside other drawings.
- Improved performance of the [MindMap Builder script](${URLs.VISUAL_THINKING_WORKSHOP_COM_MINDMAP}).
## New
- [Deconstruct Selected Elements script](${getYouTubeUrl("HRtaaD34Zzg")}) now includes a folder selection option, allowing you to choose the destination folder for the generated image.
- Arrow binding midpoints. When the projected point is close to center, snap it to the exact center. This way it's easier to create neat(er) simple arrow connections. [#10611](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/10611)
`,
"2.20.3": `
## Fixed
- Hover preview when hovering an element with a link in the scene was unreliable
- If a text element had a link in the text body, in some situations, the link became unresponsive to clicks. [#2660](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2660)
## New
- Added default keymap to latex editor [#2655](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_PULL}/2655) 🙏[superle3](${URLs.GITHUB_COM_SUPERLE3})
`,
"2.20.2": `
## New from Excalidraw.com
- Arrow focus indicator [#10613](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/10613)
## Fixed
- Experimental file type display now also works in Obsidian Mobile. (Reported on Discord)
- Text to Mermaid stores chat history locally (i.e. not synchronized between devices).
- Image positioning in crop editor [#2589](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2589), [#10726](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/10726)
## MindMap Builder
- Implemented better undo support (effective only for the very last MindMap Builder action). Additionally, CMD/CTRL+Z and CTRL+Y, CMD+SHIFT+Z now work when the MindMap input window is focused.
- Fixed: Double character input issue (IME Composition Error) when creating nodes [#2647](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2647)
- Fixed: More robust error handling when the MindMap is corrupted or invalid.
- Updated Excalidraw Writing Machine to support document generation from MindMaps. Writing Machine will honor the branch order. Requires update of the Writing Machine Script.
## New in ExcalidrawAutomate
- \`getBoundTextElement()\` now also accepts an \`ExcalidrawElement[]\` (2-element selection: container + text) in addition to a single element.
- \`addElementsToView()\` extended with \`captureUpdate\` parameter (default: "IMMEDIATELY"). When set to false, the addition of elements will not be recorded in the view's history.
\`\`\`ts
async addElementsToView(
repositionToCursor: boolean = false,
save: boolean = true,
newElementsOnTop: boolean = false,
shouldRestoreElements: boolean = false,
captureUpdate: CaptureUpdateActionType = CaptureUpdateAction.IMMEDIATELY,
): Promise<boolean>
\`\`\`
`,
"2.20.1": `
## Fixed
- Fixed Experimental file type display, available under miscellaneous settings. (Reported on Discord)
- Fixed image inversion in dark mode on iOS devices. [#2636](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2636)
- Fixed UI Mode switching on tablets was unreliable.
## New/Fixed in MindMap Builder
- **Connector Ontology**: Added support for labeling connection lines. A secondary input field (accessible via Shift+Tab) is now available in both docked and floating modes. Labels are preserved during copy/paste operations using inline Dataview syntax (e.g., link ontology:: node content).
- **Connector Styling**: Introduced configuration settings for branch thickness and scaling strategies, allowing a choice between Hierarchical (tapering width by depth) or Uniform connector widths.
- **Smart Resume**: The Focus and Zoom actions now target the most recently active node if no current selection is made. This automatically focuses the input field, allowing you to quickly resume mapping from where you left off.
- **Radial Fill Sweep**: Added a "Fill Sweep Angle" option for Radial layouts. When enabled, nodes are distributed evenly across the full configured arc range, even when there are only a few nodes. (Visible only when Growth Strategy is set to "Radial").
- **Radial Navigation**: Updated Level 1 node navigation in Radial maps to follow visual vertical alignment instead of rotational order. Up/Down keys now consistently move the selection visually up or down on both sides of the circle, matching the behavior of Right-Left layouts.
- **Fixed**:
- Sidepanel opens on activation of MindMap Builder even in floating mode. Requires update of both Excalidraw and the MindMap Builder script.
- **Node Reordering**: Overhauled the logic for moving nodes via CMD/CTRL+Arrow to resolve unpredictability; nodes now move consistently to the intended locations.
- **iOS Navigation**: Resolved an issue where using the Tab key to cycle focus between components in the floating input window did not work reliably on iOS.
- **Boundary Layering**: Fixed an issue where sub-branch boundaries were placed above text elements when pasting a map; they now correctly render on the layer below the text.
- **Layout Stability**: Fixed an issue where the viewport would shift unexpectedly when pasting multiple elements onto an existing node in large scenes.
> [!Tip]- Learn MindMap Builder
> Learn it fast with the low-cost [MindMap Builder course](${URLs.VISUAL_THINKING_WORKSHOP_COM_MINDMAP}). Register before **31 Jan** to join a live Q&A:
> - Sat Jan 31 @ 18:00 CET ([local time](${URLs.WWW_TIMEANDDATE_COM_WORLDCLOCK_FIXEDTIME_HTML}))
> - Sun Feb 1 @ 09:00 CET ([local time](${URLs.WWW_TIMEANDDATE_COM_WORLDCLOCK_FIXEDTIME_HTML_1}))
`,
"2.20.0": `
${getYouTubeDiv("5G9QF-u9w0Q")}
> [!Tip]- Learn MindMap Builder
> Learn it fast with the low-cost [MindMap Builder course](${URLs.VISUAL_THINKING_WORKSHOP_COM_MINDMAP}). Register before **31 Jan** to join a live Q&A:
> - Sat Jan 31 @ 18:00 CET ([local time](${URLs.WWW_TIMEANDDATE_COM_WORLDCLOCK_FIXEDTIME_HTML}))
> - Sun Feb 1 @ 09:00 CET ([local time](${URLs.WWW_TIMEANDDATE_COM_WORLDCLOCK_FIXEDTIME_HTML_1}))
## Scripts
- Moved [Shade Master](${getYouTubeUrl("ISuORbVKyhQ")}) to use the new Excalidraw Sidepanel API (just like MindMap Builder).
## New
- Dark theme from Excalidraw.com [#10578](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/10578) (including correct emoji rendering in dark mode 😍).
- New image context-menu option (right-click an image) to control whether that image inverts in dark mode
- Default behavior: SVG-based images (including LaTeX, Mermaid, and nested Excalidraw images) invert in dark mode; bitmap images (PNG/JPG) do not.
- New from Excalidraw.com: chat-style interface for Mermaid TextToDiagrams (requires an OpenAI API key configured in Excalidraw plugin settings). [#10530](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/10530)
- Breaking change: the legacy “force SVG” option for Mermaid diagrams is no longer supported. If a diagram can be rendered as Excalidraw, it will be; otherwise, an SVG will be used.
- Moved the Shade Master script to use the new Sidepanel (just like MindMap Builder).
## Fixed
- In full-screen mode on phones, a large area at the top of the screen was left unused. Also fixed an issue where the Obsidian Mobile navigation bar could overlap the Excalidraw toolbar.
- The link indicator in the top-right corner would remain visible even when an element was set to transparent [#2625](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2625)
- Importing PDFs with mixed page sizes could produce distorted pages [#2578](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2578)
- Some PDFs failed to load when importing PDFs as images (notably documents using JPEG2000-compressed images). Also improved handling of certain color profiles and cases where text rendered with missing/incorrect glyphs.
- A long-standing export issue: when exporting in a theme different from the current view (e.g., viewing in dark mode but exporting in light mode), nested Excalidraw images containing bitmap images could export with inverted colors.
`,
};
+115 -94
View File
@@ -8,17 +8,26 @@ import {
} from "src/utils/modifierkeyHelper";
import { setStyle } from "src/utils/styleUtils";
type ModifierKeyCategories = Partial<{
[modifierSetType in ModifierSetType]: string;
}>;
const CATEGORIES: ModifierKeyCategories = {
const CATEGORIES: Record<ModifierSetType, string> = {
WebBrowserDragAction: t("WEB_BROWSER_DRAG_ACTION"),
LocalFileDragAction: t("LOCAL_FILE_DRAG_ACTION"),
InternalDragAction: t("INTERNAL_DRAG_ACTION"),
LinkClickAction: t("PANE_TARGET"),
};
/** Modifier-key categories rendered by the settings component. */
export const MODIFIER_KEY_CATEGORIES = [
"WebBrowserDragAction",
"LocalFileDragAction",
"InternalDragAction",
"LinkClickAction",
] as const satisfies readonly ModifierSetType[];
/** Returns the localized heading for one modifier-key category. */
export const getModifierKeyCategoryName = (
modifierSetType: ModifierSetType,
): string => CATEGORIES[modifierSetType];
export class ModifierKeySettingsComponent {
private isMacOS: boolean;
@@ -28,12 +37,22 @@ export class ModifierKeySettingsComponent {
Mac: Record<string, ModifierKeySet>;
Win: Record<string, ModifierKeySet>;
},
private update?: () => void,
private update: () => void,
) {
this.isMacOS = DEVICE.isMacOS || DEVICE.isIOS;
}
render() {
render(): void {
MODIFIER_KEY_CATEGORIES.forEach((modifierSetType) =>
this.renderCategory(modifierSetType, true),
);
}
/** Renders one modifier-key category, optionally with its legacy fold. */
renderCategory(
modifierSetType: ModifierSetType,
includeSummary: boolean,
): void {
const platform = this.isMacOS ? "Mac" : "Win";
const modifierKeysConfig = this.modifierKeyConfig[platform];
const tooltipMessages = modifierKeyTooltipMessages() as Record<
@@ -41,102 +60,104 @@ export class ModifierKeySettingsComponent {
Record<string, string>
>;
Object.entries(CATEGORIES).forEach(([modifierSetType, label]) => {
const detailsEl = this.contentEl.createEl("details");
const detailsEl = includeSummary
? this.contentEl.createEl("details")
: this.contentEl;
if (includeSummary) {
detailsEl.createEl("summary", {
text: label,
text: getModifierKeyCategoryName(modifierSetType),
cls: "excalidraw-setting-h4",
});
}
const modifierKeys = modifierKeysConfig[modifierSetType];
detailsEl.createDiv({
text:
t("DEFAULT_ACTION_DESC") +
(tooltipMessages[modifierSetType]?.[modifierKeys.defaultAction] ??
""),
cls: "setting-item-description",
});
// Ensure all LinkClickAction rules have ctrl_cmd enabled
if (modifierSetType === "LinkClickAction") {
let dirty = false;
modifierKeys.rules.forEach((rule) => {
if (!rule.ctrl_cmd) {
rule.ctrl_cmd = true;
dirty = true;
}
});
if (dirty) {
this.update?.();
const modifierKeys = modifierKeysConfig[modifierSetType];
detailsEl.createDiv({
text:
t("DEFAULT_ACTION_DESC") +
(tooltipMessages[modifierSetType]?.[modifierKeys.defaultAction] ??
""),
cls: "setting-item-description",
});
// Ensure all LinkClickAction rules have ctrl_cmd enabled
if (modifierSetType === "LinkClickAction") {
let dirty = false;
modifierKeys.rules.forEach((rule) => {
if (!rule.ctrl_cmd) {
rule.ctrl_cmd = true;
dirty = true;
}
});
if (dirty) {
this.update();
}
}
// Column header row
const headerSetting = new Setting(detailsEl);
headerSetting.settingEl.addClass("modifier-key-header-row");
headerSetting.infoEl.remove();
[
"SHIFT",
this.isMacOS ? "CMD" : "CTRL",
this.isMacOS ? "OPT" : "ALT",
this.isMacOS ? "CTRL" : "META",
].forEach((key) => {
headerSetting.controlEl.createSpan({
text: key,
cls: "modifier-key-col-header",
});
// Column header row
const headerSetting = new Setting(detailsEl);
headerSetting.settingEl.addClass("modifier-key-header-row");
headerSetting.infoEl.remove();
[
"SHIFT",
this.isMacOS ? "CMD" : "CTRL",
this.isMacOS ? "OPT" : "ALT",
this.isMacOS ? "CTRL" : "META",
].forEach((key) => {
headerSetting.controlEl.createSpan({
text: key,
cls: "modifier-key-col-header",
});
});
modifierKeys.rules.forEach((rule) => {
const setting = new Setting(detailsEl).setName(
tooltipMessages[modifierSetType]?.[rule.result],
);
setting.addToggle((toggle) =>
toggle
.setValue(rule.shift)
.setTooltip("SHIFT")
.onChange((value) => {
rule.shift = value;
this.update();
}),
);
setting.addToggle((toggle) => {
const isLinkClick = modifierSetType === "LinkClickAction";
toggle
.setValue(isLinkClick ? true : rule.ctrl_cmd)
.setTooltip(this.isMacOS ? "CMD" : "CTRL")
.onChange((value) => {
rule.ctrl_cmd = value;
this.update();
});
if (isLinkClick || this.isMacOS) {
// CMD is always required for link-click actions (Excalidraw detects
// the click via CMD being held). On macOS, CMD is also reserved for
// non-link-click actions.
toggle.setDisabled(true);
setStyle(toggle.toggleEl, { opacity: "0.5" });
}
});
Object.entries(modifierKeys.rules).forEach(([_, rule]) => {
const setting = new Setting(detailsEl).setName(
tooltipMessages[modifierSetType]?.[rule.result],
);
setting.addToggle((toggle) =>
toggle
.setValue(rule.shift)
.setTooltip("SHIFT")
.onChange((value) => {
rule.shift = value;
this.update();
}),
);
setting.addToggle((toggle) => {
const isLinkClick = modifierSetType === "LinkClickAction";
toggle
.setValue(isLinkClick ? true : rule.ctrl_cmd)
.setTooltip(this.isMacOS ? "CMD" : "CTRL")
.onChange((value) => {
rule.ctrl_cmd = value;
this.update();
});
if (isLinkClick || this.isMacOS) {
// CMD is always required for link-click actions (Excalidraw detects
// the click via CMD being held). On macOS, CMD is also reserved for
// non-link-click actions.
toggle.setDisabled(true);
setStyle(toggle.toggleEl, { opacity: "0.5" });
}
});
setting.addToggle((toggle) =>
toggle
.setValue(rule.alt_opt)
.setTooltip(this.isMacOS ? "OPT" : "ALT")
.onChange((value) => {
rule.alt_opt = value;
this.update();
}),
);
setting.addToggle((toggle) =>
toggle
.setValue(rule.meta_ctrl)
.setTooltip(this.isMacOS ? "CTRL" : "META")
.onChange((value) => {
rule.meta_ctrl = value;
this.update();
}),
);
});
setting.addToggle((toggle) =>
toggle
.setValue(rule.alt_opt)
.setTooltip(this.isMacOS ? "OPT" : "ALT")
.onChange((value) => {
rule.alt_opt = value;
this.update();
}),
);
setting.addToggle((toggle) =>
toggle
.setValue(rule.meta_ctrl)
.setTooltip(this.isMacOS ? "CTRL" : "META")
.onChange((value) => {
rule.meta_ctrl = value;
this.update();
}),
);
});
}
}
+45 -10
View File
@@ -5,6 +5,7 @@ import {
FuzzyMatch,
FuzzySuggestModal,
Instruction,
normalizePath,
TFile,
Notice,
TextAreaComponent,
@@ -1096,6 +1097,7 @@ export class NewFileActions extends Modal {
private openNewFile: boolean;
private parentFile: TFile;
private sourceElement: ExcalidrawElement;
private followObsidianNewNoteLocation: boolean;
constructor({
plugin,
@@ -1105,6 +1107,7 @@ export class NewFileActions extends Modal {
openNewFile = true,
parentFile,
sourceElement,
followObsidianNewNoteLocation = false,
}: {
plugin: ExcalidrawPlugin;
path: string;
@@ -1113,6 +1116,7 @@ export class NewFileActions extends Modal {
openNewFile?: boolean;
parentFile?: TFile;
sourceElement?: ExcalidrawElement;
followObsidianNewNoteLocation?: boolean;
}) {
super(plugin.app);
this.plugin = plugin;
@@ -1122,6 +1126,7 @@ export class NewFileActions extends Modal {
this.openNewFile = openNewFile;
this.sourceElement = sourceElement;
this.parentFile = parentFile ?? view.file;
this.followObsidianNewNoteLocation = followObsidianNewNoteLocation;
this.waitForClose = new Promise<TFile | null>((resolve, reject) => {
this.resolvePromise = resolve;
this.rejectPromise = reject;
@@ -1183,15 +1188,42 @@ export class NewFileActions extends Modal {
return true;
};
const createFile = async (data: string): Promise<TFile> => {
if (!this.path.includes("/")) {
const re = new RegExp(`${escapeRegExp(this.parentFile.name)}$`, "g");
this.path = this.parentFile.path.replace(re, this.path);
const createFile = async (
data: string,
useObsidianNewNoteLocation: boolean,
): Promise<TFile> => {
let path = this.path;
if (!path.match(/\.md$/)) {
path = `${path}.md`;
}
if (!this.path.match(/\.md$/)) {
this.path = `${this.path}.md`;
if (!path.includes("/")) {
if (
useObsidianNewNoteLocation &&
this.followObsidianNewNoteLocation
) {
const newFileLocation = this.app.vault.getConfig("newFileLocation");
let targetFolder = this.parentFile.parent?.path ?? "";
if (newFileLocation === "root") {
targetFolder = "";
} else if (newFileLocation === "folder") {
const configuredFolder = this.app.vault.getConfig(
"newFileFolderPath",
);
targetFolder =
typeof configuredFolder === "string" ? configuredFolder : "";
}
path = normalizePath(
targetFolder ? `${targetFolder}/${path}` : path,
);
} else {
const re = new RegExp(
`${escapeRegExp(this.parentFile.name)}$`,
"g",
);
path = this.parentFile.path.replace(re, path);
}
}
return await createOrOverwriteFile(this.app, this.path, data);
return await createOrOverwriteFile(this.app, path, data);
};
if (this.sourceElement) {
@@ -1203,7 +1235,7 @@ export class NewFileActions extends Modal {
if (!checks) {
return;
}
const f = await createFile("");
const f = await createFile("", true);
if (f) {
const ea: ExcalidrawAutomate = getEA(this.view);
ea.copyViewElementsToEAforEditing([this.sourceElement]);
@@ -1231,7 +1263,7 @@ export class NewFileActions extends Modal {
if (!checks) {
return;
}
const f = await createFile("");
const f = await createFile("", true);
this.openFile(f);
this.close();
};
@@ -1244,7 +1276,10 @@ export class NewFileActions extends Modal {
if (!checks) {
return;
}
const f = await createFile(await this.plugin.getBlankDrawing());
const f = await createFile(
await this.plugin.getBlankDrawing(),
false,
);
await sleep(200); //wait for metadata cache to update, so file opens as excalidraw
this.openFile(f);
this.close();
+7 -5
View File
@@ -1,5 +1,7 @@
import { Modal, Setting, TFile, TAbstractFile } from "obsidian";
import { t } from "src/lang/helpers";
import ExcalidrawPlugin from "src/core/main";
import { log } from "src/utils/debugHelper";
import { getIMGFilename } from "src/utils/fileUtils";
import { setElementDisplay } from "src/utils/htmlUtils";
import { addYouTubeThumbnail } from "src/utils/utils";
@@ -27,7 +29,7 @@ const haveLinkedFilesChanged = (
if (!file || !(file instanceof TFile)) {
continue;
}
console.log(path, {
log(path, {
mtimeLinked: file.stat.mtime,
mtimeSource: mtime,
path: file.path,
@@ -109,7 +111,7 @@ export class PublishOutOfDateFilesDialog extends Modal {
onOpen() {
this.containerEl.classList.add("excalidraw-release");
this.titleEl.setText(`Out of Date SVG Files`);
this.titleEl.setText(t("POODF_TITLE"));
void this.createForm(false);
}
@@ -143,7 +145,7 @@ export class PublishOutOfDateFilesDialog extends Modal {
};
if (!recursive) {
const bRecursive = div.createEl("button", {
text: "Check Recursive",
text: t("POODF_CHECK_RECURSIVE"),
cls: "excalidraw-prompt-button",
});
bRecursive.onclick = () => {
@@ -177,7 +179,7 @@ export class PublishOutOfDateFilesDialog extends Modal {
};
if (!recursive) {
const bRecursive = div.createEl("button", {
text: "Check Recursive",
text: t("POODF_CHECK_RECURSIVE"),
cls: "excalidraw-prompt-button",
});
bRecursive.onclick = () => {
@@ -186,7 +188,7 @@ export class PublishOutOfDateFilesDialog extends Modal {
};
}
const bOpen = div.createEl("button", {
text: "Open Selected",
text: t("POODF_OPEN_SELECTED"),
cls: "excalidraw-prompt-button",
});
bOpen.onclick = () => {
+1 -1
View File
@@ -1,6 +1,6 @@
import { App, Component, MarkdownRenderer, Modal } from "obsidian";
import { isVersionNewerThanOther } from "src/utils/utils";
import ExcalidrawPlugin from "../../core/main";
import type ExcalidrawPlugin from "../../core/main";
import { RELEASE_NOTES } from "./Messages";
import { t } from "src/lang/helpers";
import { setStyle } from "src/utils/styleUtils";
+1 -4
View File
@@ -6,8 +6,6 @@ import { ContentSearcher } from "../components/ContentSearcher";
import { URLs } from "src/constants/safeUrls";
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;
@@ -24,8 +22,7 @@ export class ScriptInstallPrompt extends Modal {
this.renderComponent = new Component();
this.renderComponent.load();
this.contentEl.classList.add("excalidraw-scriptengine-install");
this.contentDiv = mainDocument.createElement("div");
this.contentEl.appendChild(this.contentDiv);
this.contentDiv = this.contentEl.createDiv();
new ContentSearcher(this.contentDiv);
@@ -0,0 +1,85 @@
import { type App, Modal, Setting } from "obsidian";
import { t } from "src/lang/helpers";
export type SettingsRecoveryChoice =
| "restore-recovery"
| "reset-defaults"
| "wait-for-file";
export type SettingsRecoveryPromptMode =
| "missing-with-recovery"
| "invalid-without-recovery";
/** Resolves ambiguous startup settings loss without silently choosing for the user. */
export class SettingsRecoveryPrompt extends Modal {
private resolvePromise: (choice: SettingsRecoveryChoice) => void;
private choice: SettingsRecoveryChoice;
public constructor(
app: App,
private readonly mode: SettingsRecoveryPromptMode,
) {
super(app);
this.choice =
mode === "missing-with-recovery"
? "restore-recovery"
: "wait-for-file";
}
/** Opens the prompt and resolves after the user chooses or closes it. */
public start(): Promise<SettingsRecoveryChoice> {
const result = new Promise<SettingsRecoveryChoice>((resolve) => {
this.resolvePromise = resolve;
});
this.open();
return result;
}
public onOpen(): void {
const hasRecovery = this.mode === "missing-with-recovery";
this.titleEl.setText(
t(
hasRecovery
? "SETTINGS_RECOVERY_MISSING_TITLE"
: "SETTINGS_RECOVERY_CORRUPT_TITLE",
),
);
this.contentEl.createEl("p", {
text: t(
hasRecovery
? "SETTINGS_RECOVERY_MISSING_DESC"
: "SETTINGS_RECOVERY_CORRUPT_DESC",
),
});
const buttons = new Setting(this.contentEl);
buttons.addButton((button) =>
button
.setButtonText(t("SETTINGS_RECOVERY_RESET_DEFAULTS"))
.onClick(() => {
this.choice = "reset-defaults";
this.close();
}),
);
buttons.addButton((button) =>
button
.setCta()
.setButtonText(
t(
hasRecovery
? "SETTINGS_RECOVERY_RESTORE_BACKUP"
: "SETTINGS_RECOVERY_WAIT_FOR_FILE",
),
)
.onClick(() => {
this.choice = hasRecovery ? "restore-recovery" : "wait-for-file";
this.close();
}),
);
}
public onClose(): void {
this.contentEl.empty();
this.resolvePromise?.(this.choice);
}
}
@@ -0,0 +1,125 @@
import { Modal, normalizePath, Setting, TextComponent } from "obsidian";
import type ExcalidrawPlugin from "src/core/main";
import { t } from "src/lang/helpers";
import { VaultPathSuggest } from "src/shared/Suggesters/VaultPathSuggest";
import type { StencilLibraryMigrationChoice } from "src/types/stencilLibraryTypes";
import { setElementHidden } from "src/utils/htmlUtils";
import { confirmAndCreateFolder } from "./CreateFolderPrompt";
export type StencilLibraryMigrationResult = {
choice: StencilLibraryMigrationChoice;
folderPath: string;
fileName: string;
};
/** Explains and configures the one-time stencil-library storage migration. */
export class StencilLibraryMigrationPrompt extends Modal {
private resolvePromise: (result: StencilLibraryMigrationResult) => void;
private result: StencilLibraryMigrationResult;
constructor(private readonly plugin: ExcalidrawPlugin) {
super(plugin.app);
this.result = {
choice: "later",
folderPath: plugin.settings.libraryFolderPath,
fileName: plugin.settings.libraryFileName,
};
}
public start(): Promise<StencilLibraryMigrationResult> {
const result = new Promise<StencilLibraryMigrationResult>((resolve) => {
this.resolvePromise = resolve;
});
this.open();
return result;
}
onOpen(): void {
this.titleEl.setText(t("LIBRARY_MIGRATION_TITLE"));
this.contentEl.createEl("p", { text: t("LIBRARY_MIGRATION_DESC") });
this.contentEl.createEl("p", {
cls: "mod-warning",
text: t("LIBRARY_MIGRATION_SYNC_WARNING"),
});
let folderText: TextComponent | null = null;
let createFolderButtonEl: HTMLButtonElement | null = null;
const folderSetting = new Setting(this.contentEl)
.setName(t("LIBRARY_FOLDER_NAME"))
.setDesc(t("LIBRARY_FOLDER_DESC"));
const updateCreateFolderButton = (): void => {
const path = folderText?.getValue().trim() ?? "";
const folderExists = path
? Boolean(this.app.vault.getFolderByPath(normalizePath(path)))
: false;
if (createFolderButtonEl) {
setElementHidden(createFolderButtonEl, !path || folderExists);
}
};
folderSetting
.addText((text: TextComponent) => {
folderText = text;
text.setValue(this.result.folderPath).onChange((value) => {
this.result.folderPath = value;
updateCreateFolderButton();
});
new VaultPathSuggest(this.app, text.inputEl, "folder");
text.inputEl.addEventListener("input", updateCreateFolderButton);
window.setTimeout(updateCreateFolderButton, 0);
})
.addButton((button) => {
createFolderButtonEl = button.buttonEl;
setElementHidden(button.buttonEl, true);
button.setButtonText(t("CREATE_FOLDER")).onClick(async () => {
await confirmAndCreateFolder(this.plugin, this.result.folderPath);
updateCreateFolderButton();
});
});
folderSetting.controlEl.addClass("excalidraw-folder-path-control");
const createFolderRow = folderSetting.controlEl.createDiv({
cls: "excalidraw-folder-create-row",
});
createFolderRow.appendChild(createFolderButtonEl);
new Setting(this.contentEl)
.setName(t("LIBRARY_FILE_NAME"))
.setDesc(t("LIBRARY_FILE_DESC"))
.addText((text) =>
text.setValue(this.result.fileName).onChange((value) => {
this.result.fileName = value;
}),
);
const buttons = new Setting(this.contentEl);
buttons.addButton((button) =>
button
.setButtonText(t("LIBRARY_MIGRATION_KEEP_DATA_JSON"))
.onClick(() => {
this.result.choice = "keep-data-json";
this.close();
}),
);
buttons.addButton((button) =>
button.setButtonText(t("LIBRARY_MIGRATION_LATER")).onClick(() => {
this.result.choice = "later";
this.close();
}),
);
buttons.addButton((button) =>
button
.setCta()
.setButtonText(t("LIBRARY_MIGRATION_MIGRATE"))
.onClick(() => {
this.result.choice = "migrate";
this.close();
}),
);
}
onClose(): void {
// Closing via the title-bar button or Escape intentionally keeps the
// default "later" choice and applies the same one-day snooze.
this.contentEl.empty();
this.resolvePromise?.(this.result);
}
}
+53 -7
View File
@@ -287,7 +287,7 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
},
{
field: "createViewSVG",
code: "async createViewSVG({withBackground?: boolean, theme?: 'light' | 'dark', frameRendering?: FrameRenderingOptions, padding?: number, selectedOnly?: boolean, skipInliningFonts?: boolean, embedScene?: boolean}): Promise<SVGSVGElement>",
code: "async createViewSVG({withBackground?: boolean, theme?: 'light' | 'dark', frameRendering?: FrameRenderingOptions, padding?: number, selectedOnly?: boolean, skipInliningFonts?: boolean, embedScene?: boolean, elementsOverride?: readonly ExcalidrawElement[]}): Promise<SVGSVGElement>",
desc:
"Creates an SVG representation of the current view with specified options.\n" +
"\n" +
@@ -299,6 +299,7 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
"@param {boolean} [options.selectedOnly=false] - Whether to include only the selected elements in the SVG.\n" +
"@param {boolean} [options.skipInliningFonts=false] - Whether to skip inlining fonts in the SVG.\n" +
"@param {boolean} [options.embedScene=false] - Whether to embed the scene in the SVG.\n" +
"@param {readonly ExcalidrawElement[]} [options.elementsOverride] - Complete replacement for the exported elements. It is not merged with the current scene or treated as a patch by ID. Include every element that should appear in the SVG.\n" +
"@returns {Promise<SVGSVGElement>} A promise that resolves to the SVG element.\n" +
"\n" +
"@typedef {Object} FrameRenderingOptions\n" +
@@ -315,6 +316,7 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
" selectedOnly: false,\n" +
" skipInliningFonts: false,\n" +
" embedScene: false,\n" +
" // elementsOverride: ea.getElements(), // Must contain the complete export set.\n" +
"});",
},
{
@@ -506,24 +508,25 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
},
{
field: "targetView",
code: "targetView: ExcalidrawView;",
desc: "The Obsidian view currently edited",
code: "targetView: ExcalidrawView | null;",
desc: "The targeted Obsidian Excalidraw view, or null when EA is unbound",
after: "",
},
{
field: "setView",
code: 'setView(view?: ExcalidrawView | "auto" | "first" | "active" | null, show: boolean = false): ExcalidrawView;',
code: 'setView(view?: ExcalidrawView | "auto" | "first" | "active" | null, show: boolean = false): ExcalidrawView | null;',
desc:
"Sets the target view for EA. All the view operations and the access to Excalidraw API will be performed on this view. " +
"Typically you will use setView() (to pick a sensible default) or setView(excalidrawView) (to explicitly target a specific view).\n" +
"Typically you will use setView() (to pick a sensible default), setView(excalidrawView) (to explicitly target a specific view), or setView(null) (to explicitly clear targetView).\n" +
'"auto" is equivalent to calling setView() and can read nicer when you want to show the view (e.g. setView("auto", true)).\n' +
'"active" and "first" are deprecated and are kept for backward compatibility.\n' +
'If view is null or undefined (or "auto"), EA will pick a sensible default: first the currently active Excalidraw view (if any), otherwise the last active Excalidraw view (if it is still available), otherwise the "first" Excalidraw view in the workspace.\n' +
'If view is undefined (or "auto"), EA will pick a sensible default: first the currently active Excalidraw view (if any), otherwise the last active Excalidraw view (if it is still available), otherwise the "first" Excalidraw view in the workspace.\n' +
"If view is explicitly null, EA clears targetView. This is useful when a sidepanel becomes unbound because focus moved to a Markdown view or no drawing is eligible.\n" +
"If show is true, the view will be brought to front and focused.\n" +
'If "first" is provided, the target will be the first Excalidraw view returned by Obsidian\'s workspace leaf collection (i.e., the first item in getExcalidrawViews()). ' +
"This ordering is managed by Obsidian and does not necessarily match what a user would consider the “first” view; from a user's perspective it may appear random.\n" +
'If "active" is provided, the currently active Excalidraw view in the workspace will be used. If that is not available, then the last active Excalidraw view will be used.\n' +
"The function returns the ExcalidrawView that was set as targetView.",
"The function returns the ExcalidrawView that was set as targetView, or null when cleared or no view was found.",
after: '("auto",true);',
},
{
@@ -996,6 +999,40 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
"In case the script wants to replace the sidepanel tab it created earlier, call closeSidepanelTab() first, then createSidepanelTab() again.",
after: "",
},
{
field: "registerCleanup",
code: "registerCleanup(cleanup: () => void): () => void;",
desc:
"Registers synchronous cleanup owned by this ExcalidrawAutomate instance. " +
"Use it for external Obsidian or DOM listeners, observers, timers, and subscriptions. " +
"The callback runs when this EA is destroyed; the returned function unregisters it without running it. " +
"The exact lifetime depends on the lifecycle that created the EA.",
after: "(() => releaseExternalResource());",
},
{
field: "registerElementActionProvider",
code:
"registerElementActionProvider(getActions: (element: ExcalidrawElement) => readonly {id: string, title: string, icon: string, action: () => void}[]): (() => void) | null;",
desc:
"Registers custom action buttons in the selected-element context menu (the small toolbar shown above a single selected element). " +
"getActions is called with the selected element whenever the selection, element type, fileId, or customData changes; return an empty array to show nothing. " +
"The menu is temporarily hidden while the selected frame title is being edited. " +
"Registration is cleared automatically when the view closes, and cleared for this script specifically if the script's file is deleted while the view is still open. " +
"Calling this again for the same script in the same view (e.g. running the script again while it is already registered) does not create a duplicate - it is a no-op that returns null. " +
"Returns a cleanup function to unregister manually, or null if there is no active target view or this script is already registered in it.",
after: '((element) => element.type === "rectangle" ? [{id: "my-action", title: "My Action", icon: "star", action: () => console.log(element.id)}] : []);',
},
{
field: "registerAutostart",
code: 'registerAutostart(message?: string): Promise<"allow" | "deny" | "pending">;',
desc:
"Requests permission for this script to be automatically re-run every time a new Excalidraw view is opened. " +
"The optional message is shown as a separate second paragraph after the permission question and before the hint explaining where the permission can be changed. Use it to clarify what the script registers or performs during autostart. " +
"The first time a given script calls this, the user is prompted to Allow, Deny, or decide later; the decision persists and is not asked again unless the user changes it (via the \"Autostart scripts\" command or settings section) or previously picked \"Ask me later\". " +
"A fresh Allow also immediately re-runs the script in every other currently-open Excalidraw view, so it attaches everywhere right away instead of only the next time each view is opened. " +
'Returns "allow", "deny", or "pending" (no active script, or the user has not yet decided). Typically called near the top of a script, guarding whatever the script wants to re-register on autostart, e.g. registerElementActionProvider(). Use utils.executionSource === "view-autostart" when only the view-autostart execution should stop after registration.',
after: '("Autostart registers this script’s drawing tools; it does not run its main action.");',
},
{
field: "getSidepanelLeaf",
code: "getSidepanelLeaf(): WorkspaceLeaf | null;",
@@ -1391,6 +1428,15 @@ export const EXCALIDRAW_SCRIPTENGINE_INFO: SuggesterInfo[] = [
desc: "The TFile of the currently running script",
after: "",
},
{
field: "executionSource",
code: 'executionSource: "manual" | "plugin-startup" | "view-autostart" | "sidepanel-restore" | "sidepanel-reload" | "drawing-onload"',
desc:
"Identifies why the script engine invoked the current script. " +
'Use "view-autostart" for registration-only setup, while "manual" covers the script button, command palette, and hotkey. ' +
"This value describes the trigger, not compilation-cache reuse or retained runtime state.",
after: "",
},
];
export const FRONTMATTER_KEYS_INFO: SuggesterInfo[] = [
+3 -2
View File
@@ -1,10 +1,11 @@
import { Setting, DropdownComponent, App } from "obsidian";
import type { StylesPanelMode } from "@zsviczian/excalidraw/types/common/src/editorInterface";
import { t } from "src/lang/helpers";
import { ExcalidrawSettings } from "src/core/settings";
import type { ExcalidrawSettings } from "src/core/settingsDefaults";
import { fragWithHTML, setLeftHandedMode, setUIMode } from "src/utils/utils";
import { DEVICE } from "src/constants/constants";
export type UIMode = "full" | "compact" | "tray" | "mobile";
export type UIMode = StylesPanelMode;
//setDesktopUIMode(this.app, this.plugin.settings);
+80 -66
View File
@@ -1,6 +1,6 @@
import { ButtonComponent, DropdownComponent, TFile } from "obsidian";
import ExcalidrawView from "../../view/ExcalidrawView";
import ExcalidrawPlugin from "../../core/main";
import type ExcalidrawPlugin from "../../core/main";
import { Modal, Setting, TextComponent } from "obsidian";
import { FileSuggestionModal } from "../Suggesters/FileSuggestionModal";
import {
@@ -9,7 +9,6 @@ import {
viewportCoordsToSceneCoords,
MAX_IMAGE_SIZE,
ANIMATED_IMAGE_TYPES,
MD_EX_SECTIONS,
} from "src/constants/constants";
import {
insertEmbeddableToView,
@@ -17,14 +16,21 @@ import {
} from "src/utils/excalidrawViewUtils";
import { getEA } from "src/core";
import { InsertPDFModal } from "./InsertPDFModal";
import { ExcalidrawAutomate } from "src/shared/ExcalidrawAutomate";
import { cleanSectionHeading } from "src/utils/pathUtils";
import { t } from "src/lang/helpers";
import { hideElement, setStyle, showElement } from "src/utils/styleUtils";
import {
getMarkdownHeadingSubpaths,
type MarkdownHeadingSubpath,
} from "src/shared/Suggesters/markdownSubpathSuggester";
import { insertMarkdownImage } from "src/shared/MarkdownImage";
import { EmbeddedFile } from "src/shared/EmbeddedFileLoader";
export type UniversalInsertFileAction = "image" | "embeddable";
export class UniversalInsertFileModal extends Modal {
private center: { x: number; y: number } = { x: 0, y: 0 };
private file: TFile;
private preferredAction: UniversalInsertFileAction | null = null;
constructor(
private plugin: ExcalidrawPlugin,
@@ -72,9 +78,14 @@ export class UniversalInsertFileModal extends Modal {
private onKeyDown: (evt: KeyboardEvent) => void;
open(file?: TFile, center?: { x: number; y: number }) {
open(
file?: TFile,
center?: { x: number; y: number },
preferredAction?: UniversalInsertFileAction,
) {
this.file = file;
this.center = center ?? this.center;
this.preferredAction = preferredAction ?? null;
super.open();
}
@@ -95,6 +106,7 @@ export class UniversalInsertFileModal extends Modal {
let actionPDF: ButtonComponent;
let anchorTo100: boolean = false;
let file = this.file;
let fileSections: MarkdownHeadingSubpath[] = [];
const updateForm = async () => {
const ea = this.plugin.ea;
@@ -110,38 +122,26 @@ export class UniversalInsertFileModal extends Modal {
const isPDF = file && file.extension === "pdf";
const isExcalidraw = file && ea.isExcalidrawFile(file);
const sections =
file && file.extension === "md"
? (
await this.plugin.app.metadataCache.blockCache.getForFile(
{ isCancelled: () => false },
file,
)
).blocks
.filter(
(b: { display: string; node?: { type: string } }) =>
b.display && b.node?.type === "heading",
)
.filter(
(b: { display: string; node?: { type: string } }) =>
!isExcalidraw || !MD_EX_SECTIONS.includes(b.display),
)
: null;
fileSections =
file?.extension === "md"
? await getMarkdownHeadingSubpaths(
this.app,
file,
Boolean(isExcalidraw),
)
: [];
if (isMarkdown || (isExcalidraw && sections?.length > 0)) {
while (sectionPicker.selectEl.options.length > 0) {
sectionPicker.selectEl.remove(0);
}
if (isMarkdown || (isExcalidraw && fileSections.length > 0)) {
showElement(sectionPickerSetting.settingEl);
showElement(sectionPicker.selectEl);
while (sectionPicker.selectEl.options.length > 0) {
sectionPicker.selectEl.remove(0);
if (!isSelf) {
sectionPicker.addOption("", t("SHOW_ENTIRE_FILE"));
}
if (!isExcalidraw) {
sectionPicker.addOption("", "");
}
sections.forEach((b: { display: string; node?: { type: string } }) => {
sectionPicker.addOption(
`#${cleanSectionHeading(b.display)}`,
b.display,
);
fileSections.forEach((section) => {
sectionPicker.addOption(section.subpath, section.display);
});
} else {
hideElement(sectionPickerSetting.settingEl);
@@ -154,7 +154,10 @@ export class UniversalInsertFileModal extends Modal {
hideElement(sizeToggleSetting.settingEl);
}
if (!isSelf && (isImage || file?.extension === "md")) {
if (
(!isSelf && (isImage || file?.extension === "md")) ||
(isSelf && isExcalidraw && fileSections.length > 0)
) {
showElement(actionImage.buttonEl);
} else {
hideElement(actionImage.buttonEl);
@@ -163,7 +166,7 @@ export class UniversalInsertFileModal extends Modal {
if (
isIFrame ||
isAnimatedImage ||
(isExcalidraw && sections?.length > 0)
(isExcalidraw && (!isSelf || fileSections.length > 0))
) {
showElement(actionIFrame.buttonEl);
} else {
@@ -177,20 +180,11 @@ export class UniversalInsertFileModal extends Modal {
}
};
const sections = (
await this.plugin.app.metadataCache.blockCache.getForFile(
{ isCancelled: () => false },
this.view.file,
)
).blocks
.filter(
(b: { display: string; node?: { type: string } }) =>
b.display && b.node?.type === "heading",
)
.filter(
(b: { display: string; node?: { type: string } }) =>
!MD_EX_SECTIONS.includes(b.display),
);
const currentFileSections = await getMarkdownHeadingSubpaths(
this.app,
this.view.file,
true,
);
const search = new TextComponent(ce);
setStyle(search.inputEl, { width: "100%" });
@@ -199,7 +193,9 @@ export class UniversalInsertFileModal extends Modal {
search,
this.app.vault
.getFiles()
.filter((f: TFile) => sections?.length > 0 || f !== this.view.file),
.filter(
(f: TFile) => currentFileSections.length > 0 || f !== this.view.file,
),
this.plugin,
);
search.onChange(() => {
@@ -225,13 +221,16 @@ export class UniversalInsertFileModal extends Modal {
new Setting(ce)
.addButton((button) => {
if (this.preferredAction === "embeddable") {
button.setCta();
}
button.setButtonText(t("UIFM_BTN_EMBEDDABLE")).onClick(async () => {
const path = this.app.metadataCache.fileToLinktext(
file,
this.view.file.path,
file.extension === "md",
);
const ea: ExcalidrawAutomate = getEA(this.view);
const ea = getEA(this.view);
ea.selectElementsInView([
await insertEmbeddableToView(
ea,
@@ -255,24 +254,39 @@ export class UniversalInsertFileModal extends Modal {
actionPDF = button;
})
.addButton((button) => {
if (this.preferredAction === "image") {
button.setCta();
}
button.setButtonText(t("UIFM_BTN_IMAGE")).onClick(async () => {
const ea: ExcalidrawAutomate = getEA(this.view);
const isMarkdown =
file && file.extension === "md" && !ea.isExcalidrawFile(file);
ea.selectElementsInView([
await insertImageToView(
ea,
this.center,
//this.view.currentPosition,
isMarkdown &&
sectionPicker.selectEl.value &&
sectionPicker.selectEl.value !== ""
? `${file.path}${sectionPicker.selectEl.value}`
file &&
file.extension === "md" &&
!this.plugin.isExcalidrawFile(file);
const section = sectionPicker.selectEl.value;
if (isMarkdown || (file?.extension === "md" && section)) {
await insertMarkdownImage(
this.view,
section
? new EmbeddedFile(
this.plugin,
this.view.file.path,
`${file.path}${section}`,
)
: file,
ea.isExcalidrawFile(file) ? !anchorTo100 : undefined,
),
]);
ea.destroy();
this.center,
);
} else {
const ea = getEA(this.view);
ea.selectElementsInView([
await insertImageToView(
ea,
this.center,
file,
ea.isExcalidrawFile(file) ? !anchorTo100 : undefined,
),
]);
ea.destroy();
}
this.close();
});
actionImage = button;
@@ -4,8 +4,6 @@ import { NamedExcalidrawFrameElement } from "src/types/excalidrawElementTypes";
import { ScriptEngine } from "../Scripts";
import ExcalidrawView from "src/view/ExcalidrawView";
declare const mainDocument: Document;
/**
*
* @param view - ExcalidrawView instance
@@ -170,12 +168,11 @@ export async function copyLinkToSelectedElementToClipboard(
(container: HTMLElement) => {
const wrapper =
container.createDiv?.("excalidraw-prompt-checkboxes") ?? container;
const ownerDoc = wrapper.ownerDocument ?? mainDocument;
const anchorRow = ownerDoc.createElement("label");
const anchorRow = wrapper.createEl("label");
anchorRow.addClass("excalidraw-copylinkprompt-label");
const anchorCb = ownerDoc.createElement("input");
const anchorCb = anchorRow.createEl("input");
anchorCb.type = "checkbox";
anchorCb.checked = anchorTo100;
anchorCb.setAttribute("aria-label", t("UIFM_ANCHOR_DESC"));
@@ -183,18 +180,14 @@ export async function copyLinkToSelectedElementToClipboard(
anchorTo100 = anchorCb.checked;
});
const anchorText = ownerDoc.createElement("span");
const anchorText = anchorRow.createSpan();
anchorText.textContent = t("UIFM_ANCHOR");
anchorRow.appendChild(anchorCb);
anchorRow.appendChild(anchorText);
wrapper.appendChild(anchorRow);
if (frameNameIsValid) {
const frameRow = ownerDoc.createElement("label");
const frameRow = wrapper.createEl("label");
frameRow.addClass("excalidraw-copylinkprompt-label");
const frameCb = ownerDoc.createElement("input");
const frameCb = frameRow.createEl("input");
frameCb.type = "checkbox";
frameCb.checked = copyFrameLinkByName;
frameCb.setAttribute("aria-label", t("FRAME_WITH_NAME"));
@@ -202,12 +195,8 @@ export async function copyLinkToSelectedElementToClipboard(
copyFrameLinkByName = frameCb.checked;
});
const frameText = ownerDoc.createElement("span");
const frameText = frameRow.createSpan();
frameText.textContent = t("FRAME_WITH_NAME");
frameRow.appendChild(frameCb);
frameRow.appendChild(frameText);
wrapper.appendChild(frameRow);
}
},
);
+285
View File
@@ -0,0 +1,285 @@
/**
* Owns the four per-drawing embedded-data registries on `ExcalidrawData`:
* embedded files, LaTeX equations, local Markdown images, and Mermaid
* diagrams. Each registry mirrors its entries into a matching plugin-wide
* "master" map (`ExcalidrawPlugin.filesMaster`/`equationsMaster`/
* `markdownImagesMaster`/`mermaidsMaster`) so intra-vault copy/paste can
* restore a fileId's data in a drawing that never natively loaded it.
* Extracted intact from `ExcalidrawData.ts`; `ExcalidrawData` keeps every
* method below as a public delegate for compatibility with its existing
* callers.
*/
import type { FileId } from "@zsviczian/excalidraw/types/element/src/types";
import type { MarkdownImageData } from "src/types/markdownImageTypes";
import type { EmbeddedFile } from "./EmbeddedFileLoader";
import type { ExcalidrawData, EquationItem, MermaidItem } from "./ExcalidrawData";
export class EmbeddedDataRegistries {
/**
* `embeddedFileCtor` is constructor-injected (rather than imported as a
* value) so this module stays type-only with respect to
* `EmbeddedFileLoader.ts`, matching the existing pattern used to avoid
* adding new circular-import edges around the `ExcalidrawData` cluster
* (see `ViewLinkNavigationManager`/`ViewExcalidrawExtensionRenderer`).
*/
constructor(
private host: ExcalidrawData,
private embeddedFileCtor: typeof EmbeddedFile,
) {}
//--------------
//Files
//--------------
public setFile(fileId: FileId, data: EmbeddedFile) {
//always store absolute path because in case of paste, relative path may not resolve ok
if (!data) {
return;
}
this.host.files.set(fileId, data);
if (data.isHyperLink || data.isLocalLink) {
this.host.plugin.filesMaster.set(fileId, {
isHyperLink: data.isHyperLink,
isLocalLink: data.isLocalLink,
path: data.hyperlink,
blockrefData: null,
hasSVGwithBitmap: data.isSVGwithBitmap,
});
return;
}
if (!data.file) {
return;
}
const parts = data.linkParts.original.split("#");
this.host.plugin.filesMaster.set(fileId, {
isHyperLink: false,
isLocalLink: false,
path: data.file.path + (data.shouldScale() ? "" : "|100%"),
blockrefData: parts.length === 1 ? null : parts[1],
hasSVGwithBitmap: data.isSVGwithBitmap,
colorMapJSON: data.colorMap ? JSON.stringify(data.colorMap) : null,
});
}
public getFiles(): EmbeddedFile[] {
return Array.from(this.host.files.values());
}
public getFile(fileId: FileId): EmbeddedFile {
let embeddedFile = this.host.files.get(fileId);
if (embeddedFile) {
return embeddedFile;
}
const masterFile = this.host.plugin.filesMaster.get(fileId);
if (!masterFile) {
return embeddedFile;
}
embeddedFile = new this.embeddedFileCtor(
this.host.plugin,
this.host.file.path,
masterFile.blockrefData
? `${masterFile.path}#${masterFile.blockrefData}`
: masterFile.path,
masterFile.colorMapJSON,
);
this.host.files.set(fileId, embeddedFile);
return embeddedFile;
}
public getFileEntries() {
return this.host.files.entries();
}
public deleteFile(fileId: FileId) {
this.host.files.delete(fileId);
//deliberately not deleting from plugin.filesMaster
//could be present in other drawings as well
}
//Image copy/paste support
public hasFile(fileId: FileId): boolean {
if (this.host.files.has(fileId)) {
return true;
}
if (this.host.plugin.filesMaster.has(fileId)) {
const masterFile = this.host.plugin.filesMaster.get(fileId);
if (masterFile.isHyperLink || masterFile.isLocalLink) {
this.host.files.set(
fileId,
new this.embeddedFileCtor(
this.host.plugin,
this.host.file.path,
masterFile.path,
),
);
return true;
}
const path = masterFile.path.split("|")[0].split("#")[0];
if (!this.host.app.vault.getAbstractFileByPath(path)) {
this.host.plugin.filesMaster.delete(fileId);
return true;
} // the file no longer exists
const fixScale = masterFile.path.endsWith("100%");
const embeddedFile = new this.embeddedFileCtor(
this.host.plugin,
this.host.file.path,
(masterFile.blockrefData
? `${path}#${masterFile.blockrefData}`
: path) + (fixScale ? "|100%" : ""),
masterFile.colorMapJSON,
);
this.host.files.set(fileId, embeddedFile);
return true;
}
return false;
}
//--------------
//Equations
//--------------
public setEquation(
fileId: FileId,
data: { latex: string; isLoaded: boolean },
) {
this.host.equations.set(fileId, {
latex: data.latex,
isLoaded: data.isLoaded,
});
this.host.plugin.equationsMaster.set(fileId, data.latex);
}
public getEquation(fileId: FileId): EquationItem {
const result = this.host.equations.get(fileId);
if (result) {
return result;
}
const latex = this.host.plugin.equationsMaster.get(fileId);
if (!latex) {
return result;
}
this.host.equations.set(fileId, { latex, isLoaded: false });
return { latex, isLoaded: false };
}
public getEquationEntries() {
return this.host.equations?.entries();
}
public deleteEquation(fileId: FileId) {
this.host.equations.delete(fileId);
//deliberately not deleting from plugin.equationsMaster
//could be present in other drawings as well
}
//Image copy/paste support
public hasEquation(fileId: FileId): boolean {
if (this.host.equations.has(fileId)) {
return true;
}
if (this.host.plugin.equationsMaster.has(fileId)) {
this.host.equations.set(fileId, {
latex: this.host.plugin.equationsMaster.get(fileId),
isLoaded: false,
});
return true;
}
return false;
}
//--------------
//Local Markdown images
//--------------
/** Stores a local Markdown-image source and makes it available for intra-vault copy/paste. */
public setMarkdownImage(fileId: FileId, data: MarkdownImageData): void {
if (!data) {
return;
}
const value = { markdown: data.markdown ?? "" };
this.host.markdownImages.set(fileId, value);
this.host.plugin.markdownImagesMaster.set(fileId, value);
}
/** Returns local Markdown, restoring it from the intra-vault copy master. */
public getMarkdownImage(fileId: FileId): MarkdownImageData | undefined {
const local = this.host.markdownImages.get(fileId);
if (local) {
return local;
}
const master = this.host.plugin.markdownImagesMaster.get(fileId);
if (master) {
const value = { ...master };
this.host.markdownImages.set(fileId, value);
return value;
}
return undefined;
}
/** Returns whether local Markdown exists, restoring intra-vault clipboard data. */
public hasMarkdownImage(fileId: FileId): boolean {
return Boolean(this.getMarkdownImage(fileId));
}
/** Removes a local source, optionally discarding its clipboard master entry. */
public deleteMarkdownImage(fileId: FileId, clearMaster = false): void {
this.host.markdownImages.delete(fileId);
if (clearMaster) {
this.host.plugin.markdownImagesMaster.delete(fileId);
}
// Normally retain the master entry for copies already on the clipboard.
}
//--------------
//Mermaids
//--------------
public setMermaid(
fileId: FileId,
data: { mermaid: string; isLoaded: boolean },
) {
this.host.mermaids.set(fileId, {
mermaid: data.mermaid,
isLoaded: data.isLoaded,
});
this.host.plugin.mermaidsMaster.set(fileId, data.mermaid);
}
public getMermaid(fileId: FileId): MermaidItem {
const result = this.host.mermaids.get(fileId);
if (result) {
return result;
}
const mermaid = this.host.plugin.mermaidsMaster.get(fileId);
if (!mermaid) {
return result;
}
this.host.mermaids.set(fileId, { mermaid, isLoaded: false });
return { mermaid, isLoaded: false };
}
public getMermaidEntries() {
return this.host.mermaids.entries();
}
public deleteMermaid(fileId: FileId) {
this.host.mermaids.delete(fileId);
//deliberately not deleting from plugin.mermaidsMaster
//could be present in other drawings as well
}
//Image copy/paste support
public hasMermaid(fileId: FileId): boolean {
if (this.host.mermaids.has(fileId)) {
return true;
}
if (this.host.plugin.mermaidsMaster.has(fileId)) {
this.host.mermaids.set(fileId, {
mermaid: this.host.plugin.mermaidsMaster.get(fileId),
isLoaded: false,
});
return true;
}
return false;
}
}
File diff suppressed because it is too large. Load diff
Loaded 100 of 188 files, more files were not shown because too many files have changed in this diff. Show more