Compare commits

..
239 Commits
Author SHA1 Message Date
zsviczian 9853b6b0fc 2.19.1 2026-01-15 19:30:30 +01:00
zsviczian bfc4e4561a Merge pull request #2604 from TravisLEBLANC1/latex-scaling
latex scaling on update
2026-01-15 19:15:43 +01:00
zsviczian c557d1c0e8 workspace-drawer observer for Obsidian Mobile 2026-01-15 18:16:43 +01:00
zsviczian e912ab698b InlineLinkSuggester to support headings and block references 2026-01-15 17:39:43 +01:00
TravisLeblanc1 20e305931b copy last modified latex's scaling
When creating a new latex, we copy the last
modified latex'scaling
2026-01-15 10:09:56 +01:00
TravisLeblanc1 33be7275b1 add scaleX/scaleY to ea.addLaTex 2026-01-15 10:09:15 +01:00
TravisLeblanc1 4e9baf72ec rename "widthscale" for "scaleX" 2026-01-12 15:45:41 +01:00
zsviczian a0e251af36 Merge pull request #2602 from rlan/feat/zh-tw/4ac8dcc
Update zh-tw.ts at 4ac8dcc
2026-01-12 07:41:30 +01:00
TravisLeblanc1 375c29171c latex scaling on update
add current latex scaling in customData.latexscale
before updating it
2026-01-11 12:05:18 +01:00
Rick Lan 0a5a7660fc Update zh-tw.ts 2026-01-10 10:43:20 -08:00
zsviczian 4ac8dcc4de addImage supports PDF++ image links 2026-01-07 21:35:16 +01:00
zsviczian aa6f07e652 Revert "migrating to restoreElements to follow recent Excalidraw changes"
This reverts commit 1efb8f3049.
2026-01-07 20:54:07 +01:00
zsviczian 0acacc8f9f renderLinksToText 2026-01-06 08:29:25 +00:00
zsviczian 1efb8f3049 migrating to restoreElements to follow recent Excalidraw changes 2026-01-06 08:12:37 +01:00
zsviczian 7d99259cdc button disable behavior 2026-01-05 16:57:33 +00:00
zsviczian a97d90653f working on grouping 2026-01-05 14:34:56 +00:00
zsviczian 06debd4106 group-ungroup 2026-01-05 13:07:40 +00:00
zsviczian 62ae0b8230 box node moved next to toggle 2026-01-05 11:37:25 +00:00
zsviczian 0e2044ba72 Merge pull request #2592 from playermiller109/2026-01-05
Update zh-cn.ts to 9319b39
2026-01-05 12:09:09 +01:00
playermiller109 0db8ab9cda Update zh-cn.ts to 9319b39 2026-01-05 11:23:36 +08:00
zsviczian 9319b39c96 only remove group ids for elements connected to the map 2026-01-04 19:00:20 +01:00
zsviczian 75cbc47bc5 Merge pull request #2591 from zsviczian/sidepanels
feat: Side panels, ColorPicker, Link Autocomplete, Mindmap Builder Improvements
2026-01-04 16:13:30 +01:00
zsviczian 66e31110e2 updated collaboration frame release date 2026-01-04 16:11:23 +01:00
zsviczian a0ec16cdf1 fixed mindmap builder after merge 2026-01-04 16:09:15 +01:00
zsviczian a5105688e4 Merge branch 'master' into sidepanels 2026-01-04 16:01:15 +01:00
zsviczian 60fe7a413f 2.19.0 2026-01-04 15:52:42 +01:00
zsviczian ee3da19290 image width to constant 2026-01-04 07:58:54 +01:00
zsviczian 4a71042fea added image support, fixed dock, undock 2026-01-03 22:44:32 +01:00
zsviczian fc51cf9a15 fixed enter navigation 2026-01-03 21:35:45 +01:00
zsviczian 1b5a6ae18a Fixed double enter, added support to add images as nodes 2026-01-03 21:21:49 +01:00
zsviczian fee74f4edd save settings when dock/undock 2026-01-03 20:44:31 +01:00
zsviczian bfcab155ca updated mindmap builder documentation 2026-01-03 17:25:51 +01:00
zsviczian 56934e0279 sidepanel.reveal, Mindmap Builder fixes, inlinesuggester fixes 2026-01-03 17:16:15 +01:00
zsviczian d89ef4caeb updated shade master with the new color picker 2026-01-02 07:21:43 +01:00
zsviczian f939db2cba 2.19.0-beta-6, see sidepanels branch for changes 2026-01-01 21:53:22 +01:00
zsviczian 04e9723048 2.19.0-beta-6, 0.18.0-65
ColorPicker, updated Pen Settings, Scribble Helper and Mindmap Builder, reintroduced insertLinkAction for mobiles and tablets,
2026-01-01 21:52:41 +01:00
zsviczian 5e68f29f7c implemented colorpicker 2026-01-01 18:45:59 +01:00
zsviczian b82ab59126 fixed suggester suggestions to be more relevant, root node of mindmap will be inverted color of current background color, If inputEl has a selection link suggester will not be displayed 2026-01-01 12:26:48 +01:00
zsviczian 894906cebb fixed inlineLinkSuggester ranking 2026-01-01 10:40:59 +01:00
zsviczian b0828011e2 2.19.0-beta-5, see sidepanels branch for the actual changes 2026-01-01 10:04:05 +01:00
zsviczian ef70901263 2.19.0-beta-5 2026-01-01 10:03:31 +01:00
zsviczian b934c429bc Added edit Node to Mindmap Builder. ea.addElementsToView now honors setting.syncElementLinkWithText 2026-01-01 00:04:13 +01:00
zsviczian 57b00f7c69 2.19.0-beta-4, see sidepanels branch for details 2025-12-31 19:05:25 +01:00
zsviczian 1e245f1136 removed INSERT_LINK from context menu 2025-12-31 19:04:17 +01:00
zsviczian a5632866b0 2.19.0-beta-4, 0.18.0-64 2025-12-31 18:57:55 +01:00
zsviczian a96f0d0889 removed insertLinkAction, implemented syncElementLinkWithText in ExcalidrawData 2025-12-31 18:26:16 +01:00
zsviczian 5cbaf5b203 syncElementLinkWithText 2025-12-31 10:42:23 +01:00
zsviczian 3cd05b0be2 Implemented attachInlineLinkSuggester for Excalidraw component, 0.18.0-63 2025-12-31 09:25:42 +01:00
zsviczian 70a6c0167d fix suggester pointer events, implement minwidth, obsidianUtils attachInlineLinkSuggester call 2025-12-30 22:07:27 +01:00
zsviczian 7150aaf795 improved spacing when subbranches are large 2025-12-30 19:10:47 +01:00
zsviczian ad3874889e Fixed add order 2025-12-29 22:37:35 +01:00
zsviczian 15d15b35e7 fix sibling navigation order 2025-12-29 22:32:11 +01:00
zsviczian 7680396b99 hotkey configuration 2025-12-29 22:08:36 +01:00
zsviczian 3f582d87fe moved shortcuts to HOKEYS. Tweaked random colors. 2025-12-29 20:48:41 +01:00
zsviczian b37ed015e3 updated llm docs 2025-12-28 16:04:10 +01:00
zsviczian 22cf76b1f9 updated mindmap builder and link suggester sorting 2025-12-28 15:43:57 +01:00
zsviczian 588dfc5dc2 2.19.0-beta-3 (see sidepanels branch for actual changes) 2025-12-28 14:59:35 +01:00
zsviczian e1f36d910b 2.19.0-beta-3 2025-12-28 14:58:24 +01:00
zsviczian cbec7f4d9f inlineSuggester 2025-12-28 11:38:44 +01:00
zsviczian 6585a75b6e InlineLinkSuggester v0 2025-12-28 07:41:00 +01:00
zsviczian d3b8d07d9c updated training file 2025-12-28 06:52:55 +01:00
zsviczian 9cda26faad active-leaf-change listner 2025-12-27 22:51:50 +01:00
zsviczian cc18cf9166 2.19.0-beta-2: see sidepanels branch for the actual implementation 2025-12-27 22:19:00 +01:00
zsviczian 8ce71c262b 2.19.0-beta-2 2025-12-27 22:17:55 +01:00
zsviczian 0116125a10 keyboard event management, intelligent undock, dock 2025-12-27 20:19:50 +01:00
zsviczian f214633db8 more robust keydown handlers... 2025-12-27 10:04:38 +01:00
zsviczian bd191f0d2d added scope.register to override obsidian hotkeys while using mindmap builder 2025-12-27 09:41:18 +01:00
zsviczian afa8fbff80 zoom 2025-12-27 09:09:26 +01:00
zsviczian 5236a73a1e 2.19.0-beta-1 2025-12-27 00:04:45 +01:00
zsviczian 45d95856ca 2.19.0-beta-1 2025-12-27 00:03:48 +01:00
zsviczian 4e050f76e1 center and zoom root node after creation 2025-12-26 23:37:25 +01:00
zsviczian aee74ca6d9 implemented ExcalidrawViewClosed call in 2025-12-26 22:46:07 +01:00
zsviczian c6459b6a87 onWindowMigrated initial implementation 2025-12-26 21:50:32 +01:00
zsviczian 0eb4b2a1f5 floatingmodal fix, getSidepanelLeaf, sidepanel startup, MindmapBuilder sidepanel 2025-12-26 20:27:49 +01:00
zsviczian 23b793d21f Added getHostEA and checkForActiveSidepanelTabForScript 2025-12-26 13:12:15 +01:00
zsviczian 77dd95f089 added checkForActiveSidepanelTab 2025-12-26 10:39:23 +01:00
zsviczian faa900a352 ownerWindow? 2025-12-26 10:33:52 +01:00
zsviczian 2ceebab04f refactor UI Modal 2025-12-26 10:15:47 +01:00
zsviczian 0b0232aa62 removed sidepaneltaboptions, removed unnecessary / ambigous functions from ExcalidrawAutomate 2025-12-26 09:35:54 +01:00
zsviczian 497125d7cc lint 2025-12-26 08:13:45 +01:00
zsviczian 4e8baed49f remove end of line spaces 2025-12-26 07:55:40 +01:00
zsviczian 3f93be3b45 typo, unused const 2025-12-26 07:47:34 +01:00
zsviczian bb17694219 refactor, bug fixes 2025-12-26 07:22:34 +01:00
zsviczian 51ffcdf3de Added LLM documentation, type definitions, etc. 2025-12-25 22:07:33 +01:00
zsviczian 12bc2a1680 added box/unbox to toolbar 2025-12-25 19:01:03 +01:00
zsviczian 4c8ed3fe57 replace tabs with dropdown 2025-12-25 14:14:07 +01:00
zsviczian bbb3a63106 setDisabled 2025-12-25 13:36:00 +01:00
zsviczian b801a1e4d2 silent restore, persist panel ea 2025-12-25 13:19:53 +01:00
zsviczian 96bf5d4880 Implemented onFocus 2025-12-25 12:36:31 +01:00
zsviczian 0962eadcf9 sidepanelTab mimics Modal functions 2025-12-25 11:38:23 +01:00
zsviczian 4d57bf6fb5 hostEA stored, title persisted 2025-12-25 11:19:23 +01:00
zsviczian da8937499b deleted resolveSidepanelTab 2025-12-25 09:58:28 +01:00
zsviczian 4818d23f8b feat(sidepanel): add first draft solution for sidepanels 2025-12-25 09:51:44 +01:00
zsviczian a1561de832 ea.setView improvements 2025-12-24 09:23:46 +01:00
zsviczian 1900cfcf84 modified training files 2025-12-23 14:51:41 +01:00
zsviczian aa47d1375b updated mindmap builder 2025-12-23 14:46:50 +01:00
zsviczian 61ae34968a added ALT+C,X,V to cut,copy,paste 2025-12-23 14:46:11 +01:00
zsviczian 296ac84f08 2.18.3, 0.18.0-63 2025-12-23 12:36:40 +01:00
zsviczian bcd63ad7fe fix isSolidArrow overwritten in centerText, and fix grouping of non-autolayed out element 2025-12-22 22:15:32 +01:00
zsviczian 1fec09c367 smaller minimized view 2025-12-22 17:48:27 +01:00
zsviczian 4cd5dde3d6 option to center text, added force rearrange button 2025-12-22 15:29:02 +01:00
zsviczian 36ee7f6e52 canvas pointer listener 2025-12-22 14:46:39 +01:00
zsviczian 32f76d4ea4 add branch pinning, added connector arrow handling 2025-12-22 12:39:24 +01:00
zsviczian 53aed86777 publishing linear calendar generator 2025-12-22 07:48:44 +01:00
zsviczian 573587bd88 publish linear calenar 2025-12-22 07:40:06 +01:00
zsviczian 558d0105a5 Merge pull request #2584 from superle3/fix/latex_suite_display_math
fix: use displaymath in latex mock parser
2025-12-22 07:06:59 +01:00
superle3 76910a3352 fix: use displaymath in latex mock parser
For latex suite, the mocked opening math node should be math-begin-math-block to indicate that its displaymath and newlines can be entered and thus snippets with newlines are used instead of those without.
2025-12-22 00:04:08 +01:00
zsviczian e2c9e2b256 removed - node.width/2 from 2025-12-21 22:43:53 +01:00
zsviczian 9630db68a4 2.18.3-beta-1, 0.18.0-63 2025-12-21 22:29:33 +01:00
zsviczian 7541fa22b4 Merge pull request #2583 from TravisLEBLANC1/latex-suite-integration
Latex suite integration
2025-12-21 21:25:19 +01:00
zsviczian c5cf6d630f fixed rollup.config, and caret-color 2025-12-21 20:22:56 +00:00
Travis LEBLANC 2f296c7a46 Merge branch 'zsviczian:master' into latex-suite-integration 2025-12-21 19:59:17 +01:00
zsviczian 095ff057cd Merge pull request #2549 from zsviczian/dependabot/npm_and_yarn/MathjaxToSVG/nanoid-5.0.9
Bump nanoid from 4.0.2 to 5.0.9 in /MathjaxToSVG
2025-12-21 12:54:06 +01:00
zsviczian b38956cb51 changed markdown embed customize link to lucide.dev icon 2025-12-21 12:52:34 +01:00
zsviczian 03392db757 0.18.0-63, prompt.ts update 2025-12-21 12:35:58 +01:00
zsviczian 2bd252fcff Merge branch 'master' into latex-suite-integration 2025-12-21 11:20:19 +01:00
zsviczian 12b52e42f2 adding fallback if latex suit is not avaiable 2025-12-21 11:17:05 +01:00
zsviczian 76675591fe minor fixes 2025-12-21 10:57:14 +01:00
zsviczian 966f6b53ea added documentation 2025-12-21 10:10:17 +01:00
TravisLeblanc1 efbca80f74 adding grammar in comments 2025-12-21 09:11:27 +01:00
zsviczian ee8ac2f7ad compact mode for mindmap builder 2025-12-20 23:38:34 +01:00
zsviczian 0ac7ccde66 mindmap builder v1 2025-12-20 22:32:04 +01:00
zsviczian b5bd27f115 mindmap builder copy/paste 2025-12-20 22:27:47 +01:00
zsviczian 600b2d9621 disable autolayout 2025-12-20 21:53:35 +01:00
TravisLeblanc1 c709562925 solving field error and remove Prec 2025-12-20 20:51:19 +01:00
zsviczian c3cfe0b0ed Arrow update, mindmap builder 2025-12-20 20:39:09 +01:00
TravisLeblanc1 686ff92f4d adding extensions if latexsuite not active 2025-12-20 20:29:25 +01:00
TravisLeblanc1 37f3937bd6 adding Ctrl+Enter to submit 2025-12-20 20:15:30 +01:00
TravisLeblanc1 16c61c44ce add history extension 2025-12-20 15:57:52 +01:00
TravisLeblanc1 2f968a7bbc improve math-only parser 2025-12-20 14:52:41 +01:00
zsviczian 475492beda remove youtube links from LLM training data 2025-12-19 21:38:03 +01:00
zsviczian ab11258d0d updated doc, added space to youtube links to prevent aistudio gemini 3 automatically reading those youtube videos 2025-12-19 21:30:05 +01:00
TravisLeblanc1 1ab682e726 adding latex-suite support 2025-12-19 12:24:02 +01:00
zsviczian cb370645b7 2.18.2, 0.18.0-62 2025-12-19 07:10:59 +01:00
zsviczian c80420772e Merge pull request #2577 from playermiller109/2025-12-17
Update zh-cn.ts to 2e52744
2025-12-19 05:41:43 +01:00
zsviczian 5fd76e07ba fix copy group link 2025-12-18 22:29:38 +01:00
playermiller109 fda8d5ce77 Update zh-cn.ts to 2e52744 2025-12-17 08:46:56 +08:00
zsviczian 2e52744743 2.18.1, 0.18.0-61 2025-12-16 20:55:14 +01:00
zsviczian a634d24f6b Merge pull request #2576 from TravisLEBLANC1/back_of_note_fix
Bug fix: incorrectly-replaced back-of-note
2025-12-16 20:38:05 +01:00
zsviczian ebc0ecbfc4 Merge pull request #2575 from parkero/popover-size
Fix popover image sizing to match embeds more closely
2025-12-16 20:31:00 +01:00
zsviczian 9622e137ba Merge pull request #2565 from TravisLEBLANC1/addLaTex_fix
Bug fix: ExcalidrawAutomate addLaTex guard condition
2025-12-16 20:25:35 +01:00
zsviczian b3bf3b5a60 added cancel handling 2025-12-16 20:25:20 +01:00
zsviczian cc1ae730d1 moved copyLinkToSelectedElementToClipboard to its own file, implemented framename and anchor checkboxes 2025-12-16 20:12:05 +01:00
zsviczian 9841941431 updated frameName regexp, added new settings for copy frame link, added strings to en.ts 2025-12-16 19:30:39 +01:00
zsviczian f179b6720b fixed hover preview, unnecessary settings save 2025-12-16 19:16:28 +01:00
TravisLeblanc1 b44d2a4a9a fix uncaught promise with latex 2025-12-11 23:12:01 +01:00
TravisLeblanc1 6a82011bdb fix incorrectly-replaced back-of-note 2025-12-08 14:13:13 +01:00
parkero c835943fc5 Fix popover image sizing
They were not responding to the default width parameter in the settings.
Also prior to this if you added a default height, but removed the
default width, they would render at 0 width.
2025-12-07 21:05:49 -07:00
TravisLeblanc1 a4f0676686 addLaTex guard condition 2025-12-06 00:05:10 +01:00
zsviczian e69487c456 added refocus current slide button to the navigation panel 2025-12-04 18:14:04 +01:00
zsviczian e7a067d53a 2.18.0 2025-12-02 21:46:17 +01:00
zsviczian fe8ece275a ModalEl styling when onscreen keyboard is detected
https://discord.com/channels/1026825302900494357/1445155859100602368/1445355939355033611
2025-12-02 14:34:17 +01:00
zsviczian a5f2da74ba Update ExcalidrawView.ts
Extend wait times for scheduledBatchDelays - keyboard out event
2025-12-02 13:59:08 +01:00
zsviczian ce602b8268 2.18.0-beta-6, 0.18.0-60 (on-screen keyboard detection improved) 2025-12-01 21:52:56 +01:00
zsviczian 7bb718da81 Merge pull request #2556 from rlan/feat/zh-tw/44588ab
Update zh-tw.ts to 44588ab
2025-12-01 18:15:58 +01:00
Rick Lan cceb2cae82 Merge branch 'master' into feat/zh-tw/44588ab 2025-12-01 09:10:07 -08:00
Rick Lan f5f0134509 Update zh-tw.ts to 44588ab 2025-12-01 08:28:58 -08:00
zsviczian 44588ab4b8 improve getHighlightColor 2025-12-01 06:14:00 +01:00
zsviczian 989e7969dc renderScriptButtons, referenced view in toolspanel with weak reference 2025-11-30 21:05:46 +01:00
zsviczian f5c7820315 Merge pull request #2554 from rlan/feat/zh-tw/ba5d1aa
Update zh-tw.ts to ba5d1aa
2025-11-30 20:52:03 +01:00
zsviczian c416c21985 Merge pull request #2553 from playermiller109/2025-11-30
Update zh-cn.ts to ba5d1aa
2025-11-30 20:51:50 +01:00
zsviczian e5f6466542 improved ExcalidrawView onClose cleanup and timer removal 2025-11-30 16:44:13 +01:00
zsviczian 95ba981445 fix markdownPostProcessor blob leak 2025-11-30 16:34:56 +01:00
zsviczian 31cc45ff6d fixed prompt.ts event listner release 2025-11-30 16:31:54 +01:00
zsviczian 62f51511ed fixed suggestionmodal event listners release 2025-11-30 16:28:43 +01:00
zsviczian 5c628e08f4 fix remove debunceActiveLeafChangeHandlerTimer; cleanup observerManager; clear timers in ExcalidrawView onunload 2025-11-30 16:14:17 +01:00
zsviczian 0e11150055 fixed embeddedFileLoader memory stuck interval issue 2025-11-30 16:04:05 +01:00
zsviczian 37b4cdd44a fix memory leak with updateEmbeddableLeafRef and ImageCache obsidianURL 2025-11-30 15:55:05 +01:00
zsviczian a2a33bc463 fixed memory issues with updateEmbeddableRef, highlight color cache, embeddable onKeyDown event handler 2025-11-30 15:41:01 +01:00
Rick Lan 00531325ea Update zh-tw.ts to ba5d1aa 2025-11-29 22:34:11 -08:00
zsviczian a7d4d59619 updated getHighlightColor (only use background, not stroke) 2025-11-30 07:05:02 +01:00
playermiller109 b05e26d138 Unify the translation of 'opacity'
In the design field, '不透明度' is widely recognized.
As for general users, while '透明度' and '不透明度' are often interchangeable in daily use,
recent AI-powered tools reliably translate it as '不透明度'.
Unifying it as '不透明度' should be clear to both general users and future maintainers.
2025-11-30 13:01:24 +08:00
playermiller109 ce3cda7a1d Update zh-cn.ts to ba5d1aa 2025-11-30 10:17:18 +08:00
zsviczian ba5d1aa6d6 2.18.0-beta-4, 0.18.0-58 2025-11-29 14:42:21 +01:00
zsviczian 686f462716 Merge pull request #2550 from playermiller109/2025-11-27
Update zh-cn.ts to 168b1d1
2025-11-29 09:56:44 +01:00
playermiller109 21dec11170 Update zh-cn.ts to 168b1d1 2025-11-27 08:39:50 +08:00
zsviczian 168b1d1871 2.18.0-beta-3, 0.18.0-56 2025-11-26 21:22:11 +01:00
zsviczian 8df45aed14 2.18.0-beta-2, 0.18.0-55 (export-internal-links) 2025-11-26 21:11:57 +01:00
zsviczian 2e9b5ce593 2.18.0-beta-1 2025-11-25 21:10:38 +01:00
dependabot[bot] c332608bb5 Bump nanoid from 4.0.2 to 5.0.9 in /MathjaxToSVG
Bumps [nanoid](https://github.com/ai/nanoid) from 4.0.2 to 5.0.9.
- [Release notes](https://github.com/ai/nanoid/releases)
- [Changelog](https://github.com/ai/nanoid/blob/main/CHANGELOG.md)
- [Commits](https://github.com/ai/nanoid/compare/4.0.2...5.0.9)

---
updated-dependencies:
- dependency-name: nanoid
  dependency-version: 5.0.9
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-11-22 15:43:48 +00:00
zsviczian ed9fe5f3d4 2.17.2, 0.18.0-53 2025-11-22 16:42:47 +01:00
zsviczian 57afd6f134 Merge pull request #2540 from threeq/hotfix/openai
fix(openai): 添加对自定义OpenAI URL的支持
2025-11-22 08:05:12 +01:00
zsviczian 63e0c1368f Merge pull request #2543 from dddrop/master
Add configurable max tokens setting for OpenAI API
2025-11-22 07:58:45 +01:00
zsviczian 3b2f7d2c98 fixed toggle context menu on phones 2025-11-22 07:58:23 +01:00
dddrop 684d19eebd feat(i18n): add max tokens translations for zh-cn, zh-tw, es, and ru
- Add AI_OPENAI_DEFAULT_MAX_TOKENS_NAME and AI_OPENAI_DEFAULT_MAX_TOKENS_DESC translations
- Support for Chinese (Simplified), Chinese (Traditional), Spanish, and Russian languages
2025-11-18 17:04:21 +09:00
dddrop d65e967e4b feat(ai): add configurable max tokens setting for OpenAI API
- Add openAIDefaultTextModelMaxTokens setting to allow users to configure max_tokens parameter
- Add UI setting control with validation for max tokens input
- Update AIUtils to use configurable max_tokens instead of hardcoded value
- Support omitting max_tokens field when set to 0 (for models like GPT-5 that don't support this parameter)
2025-11-18 17:02:28 +09:00
three3q 59fe5abfa8 fix(openai): 添加对自定义OpenAI URL的支持
允许通过配置指定OpenAI API的URL地址,增强API调用的灵活性
2025-11-16 14:27:48 +08:00
zsviczian 919913044d Fixed hover preview 2025-11-15 14:02:11 +01:00
zsviczian 306e6db564 Merge pull request #2533 from rlan/feat/zh-tww/c1ea206
Update zh-tw.ts to c1ea206
2025-11-11 20:39:14 +01:00
zsviczian c32d0cb350 fix floatingmodal close 2025-11-11 12:44:30 +01:00
Rick Lan a43e527602 Update zh-tw.ts to c1ea206 2025-11-10 18:20:24 -08:00
zsviczian 2e48ee8484 2.17.1, 0.18.0-52 2025-11-09 23:01:59 +01:00
zsviczian d568003915 updated docs 2025-11-08 11:35:41 +01:00
zsviczian 247685b13f 2.17.0 2025-11-07 22:09:59 +01:00
zsviczian 73c20e0d9d Add tool-icon pen mode rule 2025-11-07 11:43:17 +01:00
zsviczian 222ff139d8 Merge pull request #2531 from playermiller109/2025-11-07
Update zh-cn.ts to ae72262
2025-11-07 11:42:23 +01:00
playermiller109 0e0774d973 Update zh-cn.ts to ae72262 2025-11-07 11:47:04 +08:00
zsviczian ae722623e5 2.17.0-beta-8, 0.18.0-50 2025-11-06 20:07:34 +01:00
zsviczian 65ab00a932 Merge pull request #2530 from playermiller109/2025-11-06
Update zh-cn.ts to b2f051e
2025-11-06 07:33:06 +01:00
playermiller109 418063e9b6 Update zh-cn.ts to b2f051e 2025-11-06 10:58:27 +08:00
zsviczian b2f051e088 2.17.0-beta-7, 0.18.0-49 2025-11-05 21:51:53 +01:00
zsviczian c884db0840 Merge pull request #2529 from playermiller109/2025-11-05
Update zh-cn.ts to 97da7c6
2025-11-05 11:24:19 +01:00
playermiller109 e4d1b509f7 Update zh-cn.ts to 97da7c6 2025-11-05 10:21:48 +08:00
zsviczian 97da7c680f 2.17.0-beta-6, 0.18.0-48 (merged EditorInterface refactor) 2025-11-04 23:45:31 +01:00
zsviczian 5696a33e60 Merge pull request #2527 from KTibow/master
fix bug (no isparsed) in compat mode and restructure to make sure it can't happen again
2025-11-04 23:41:58 +01:00
zsviczian b68e8c0b20 desktopUI changes 2025-11-04 23:40:53 +01:00
zsviczian 3a43571f3e Merge pull request #2528 from duianto/typo
Fix typo excalidarw
2025-11-04 23:39:03 +01:00
zsviczian 65c3a11fba 2.17.0-beta-5 (slightly polluted with new device handling in Excalidraw (what will be 0.18.0-48...) 2025-11-04 22:00:51 +01:00
duianto 010fd5c624 Fix typo excalidarw 2025-11-04 15:59:02 +01:00
KTibow 8ddf03cdd3 fix bug (no isparsed) in compat mode and restructure to make sure it
can't happen again
2025-11-03 18:22:20 -08:00
zsviczian a5fd91a33c updated docs 2025-11-03 19:33:29 +01:00
zsviczian d8de0db423 Updated docs with custom pens 2025-11-03 18:05:23 +01:00
zsviczian b5d9fa4625 2.17.0-beta-4, 0.18.0-46 2025-11-02 21:43:15 +01:00
zsviczian fcc0f94974 attempt to fix mobile keyboard popup 2025-11-02 21:38:30 +01:00
zsviczian 6b7d8c8b69 2.17.0-beta-3, 0.18.0-45 2025-11-01 13:58:22 +01:00
zsviczian 259e6277ed Added ExcalidrawLib to the training file 2025-11-01 13:51:06 +01:00
zsviczian 88405af417 Merge branch 'master' of https://github.com/zsviczian/obsidian-excalidraw-plugin 2025-11-01 13:30:51 +01:00
zsviczian 8fecb75f97 removed taryModeEnabled from AppState 2025-11-01 13:30:49 +01:00
zsviczian bd1b13b58c Merge pull request #2524 from playermiller109/master
Update zh-cn.ts to 8379f93
2025-11-01 13:13:03 +01:00
playermiller109 d8cac4eacd Update zh-cn.ts to 8379f93 2025-10-28 19:28:06 +08:00
zsviczian 8379f9315e disable Context menu, 0.18.0-44 2025-10-28 06:27:28 +01:00
zsviczian 123fa12122 updated AI training prompt 2025-10-25 17:27:02 +02:00
zsviczian 46a41feaf3 2.17.0-beta-2, 0.18.0-43 2025-10-24 22:41:04 +02:00
zsviczian a043ee131f updated training files 2025-10-24 13:44:59 +02:00
zsviczian 7e9f1f6350 Auto generate training file 2025-10-24 13:14:07 +02:00
zsviczian ffc209d4b0 carved out types 2025-10-24 12:31:28 +02:00
zsviczian c1ea206d9d updated invert colors script 2025-10-23 16:44:26 +02:00
zsviczian 4587d36997 2.17.0-beta-1; 0.18.0-42 2025-10-23 07:53:39 +02:00
zsviczian 4f4035b8ef Merge pull request #2519 from rlan/feat/zh-tw/27d30c6
Update zh-tw.ts to 27d30c6
2025-10-23 07:45:57 +02:00
Rick Lan de5da38474 Update zh-tw.ts to 27d30c6 2025-10-22 22:23:46 -07:00
zsviczian 27d30c609e fix #2514
Updated documentation link for support requests.
2025-10-22 12:46:54 +02:00
zsviczian 9aaaf77daf updated slideshow script to support marker frames during printout 2025-10-17 09:07:50 +02:00
zsviczian ba0fac6f74 Palette loader date issues 2025-10-15 07:48:14 +02:00
zsviczian 802e0f2dcd Update directory-info.json with new file metadata
Updated the directory-info.json file to reflect changes in file metadata.
2025-10-09 16:10:09 +02:00
zsviczian 7bcb14b72f Merge pull request #2506 from Joakim31/master
Update es.ts to 8b198a57
2025-10-09 15:19:19 +02:00
Joakim31 21ddc4b90f Update es.ts to 8b198a57 2025-10-07 22:33:42 -05:00
zsviczian 8035e489ca 2.16.1 removing iframes 2025-10-04 22:37:01 +02:00
zsviczian bf8ae6f8bb updated script files 2025-10-04 22:03:11 +02:00
zsviczian 8b557a8461 remove iframes from index-new 2025-10-04 21:50:20 +02:00
110 changed files with 69877 additions and 1878 deletions

No files matched your search

+1 -1
View File
@@ -11,7 +11,7 @@ body:
Before submitting a support request, please:
1. **[Consult NotebookLM with your question](https://notebooklm.google.com/notebook/42d76a2f-c11d-4002-9286-1683c43d0ab0)**
2. **Review the [documentation](https://github.com/zsviczian/obsidian-excalidraw-plugin/wiki)** – your question may already be answered.
2. **Review the [documentation](https://excalidraw-obsidian.online/wiki/welcome)** – your question may already be answered.
3. **[Search issues](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues) (including closed ones)** to see if your question has already been addressed.
4. **[Watch the Feature Walkthrough Video](https://youtu.be/P_Q6avJGoWI)**: As it infact answers 90% of the typical questions I receive
+1
View File
@@ -14,6 +14,7 @@ data.json
lib
dist
tmp
deploy.ps1
#VSCode
.vscode
+5 -5
View File
@@ -9,7 +9,7 @@
"version": "1.0.0",
"dependencies": {
"mathjax-full": "^3.2.2",
"nanoid": "^4.0.2"
"nanoid": "^5.0.9"
},
"devDependencies": {
"@rollup/plugin-commonjs": "^26.0.1",
@@ -749,9 +749,9 @@
}
},
"node_modules/nanoid": {
"version": "4.0.2",
"resolved": "https://registry.npmjs.org/nanoid/-/nanoid-4.0.2.tgz",
"integrity": "sha512-7ZtY5KTCNheRGfEFxnedV5zFiORN1+Y1N6zvPTnHQd8ENUvfaDBeuJDZb2bN/oXwXxu3qkTXDzy57W5vAmDTBw==",
"version": "5.0.9",
"resolved": "https://registry.npmjs.org/nanoid/-/nanoid-5.0.9.tgz",
"integrity": "sha512-Aooyr6MXU6HpvvWXKoVoXwKMs/KyVakWwg7xQfv5/S/RIgJMy0Ifa45H9qqYy7pTCszrHzP21Uk4PZq2HpEM8Q==",
"funding": [
{
"type": "github",
@@ -763,7 +763,7 @@
"nanoid": "bin/nanoid.js"
},
"engines": {
"node": "^14 || ^16 || >=18"
"node": "^18 || >=20"
}
},
"node_modules/obsidian": {
+1 -1
View File
@@ -8,7 +8,7 @@
},
"dependencies": {
"mathjax-full": "^3.2.2",
"nanoid": "^4.0.2"
"nanoid": "^5.0.9"
},
"devDependencies": {
"@rollup/plugin-commonjs": "^26.0.1",
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,727 @@
/*
#exclude
```js*/
// -----------------------------
// -----------------------------
// Icon Library / Bases Search
// -----------------------------
// -----------------------------
const IMAGE_LIBRARY_FOLDER = ea.obsidian.normalizePath("Assets/nosync");
const IMAGE_LIBRARY_FILENAME = "Image Library.base"
const ICONTYPES = [
{name: "Icon", pattern: "icon"},
{name: "Stickfigure", pattern: "stickfigure"},
{name: "Logo", pattern: "logo"}
];
const IMAGE_LIBRARY_PATH = ea.obsidian.normalizePath(IMAGE_LIBRARY_FOLDER + "/" + IMAGE_LIBRARY_FILENAME);
async function initializeImageLibrary() {
await ea.checkAndCreateFolder(IMAGE_LIBRARY_FOLDER);
const syncPlugin = app.internalPlugins.plugins["sync"]?.instance;
if(syncPlugin && !syncPlugin.ignoreFolders.includes(IMAGE_LIBRARY_FOLDER)) {
syncPlugin.setIgnoreFolders(syncPlugin.ignoreFolders.concat(IMAGE_LIBRARY_FOLDER));
}
const imgLibFile = app.vault.getFileByPath(IMAGE_LIBRARY_PATH);
if(!imgLibFile) {
//The bases file is very sensitive to spaces, indents, and formatting
//take care when modifying this
const baseTemplate = `formulas:\n` +
` Icon: image(file.path)\n` +
` keywords: file.name.split(" - ")[1]\n` +
` icon-path: link(if(file.ext == "md", "Assets/" + file.name.split(" - ")[0] + "s/" + file.name + ".svg", file.path))\n` +
`views:\n` +
` - type: cards\n` +
` name: View\n` +
` filters:\n` +
` and:\n` +
` - /^(icon|stickfigure|logo) \\- /i.matches(file.name.lower())\n` +
` - '!file.path.startsWith("Assets/")'\n` +
` - /./i.matches(formula.keywords)\n` +
` order:\n` +
` - formula.keywords\n` +
` sort:\n` +
` - property: formula.keywords\n` +
` direction: ASC\n` +
` cardSize: 130\n` +
` imageFit: contain\n` +
` image: formula.icon-path\n` +
` imageAspectRatio: 0.8\n`;
await app.vault.create(IMAGE_LIBRARY_PATH, baseTemplate);
}
}
initializeImageLibrary();
async function revealIconLibrary() {
const file = app.vault.getFileByPath(IMAGE_LIBRARY_PATH);
if(!file) return;
let leaf;
app.workspace.iterateAllLeaves(l=>{
if(leaf) return;
if(l.view?.getViewType() === "bases" && l.view.getState().file === file.path) leaf = l;
});
if(leaf) {
app.workspace.revealLeaf(leaf);
return file;
}
leaf = app.workspace.getRightLeaf();
await leaf.openFile(file);
app.workspace.revealLeaf(leaf);
return file;
}
if(ea.verifyMinimumPluginVersion("2.13.2")) {
ea.plugin.addCommand({
id: "base-filter-keywords",
name: "Icon Library",
icon: "images",
callback: async () => {
// Check if the active file is a .base file
const file = await revealIconLibrary();
if(!file) return false;
let baseContent = await app.vault.read(file);
// Check if the file has the specific patterns for filtering
if (!baseContent.includes(".matches(formula.keywords)")) return;
// Create a modal using Obsidian's Modal class
const Modal = ea.FloatingModal;
const modal = new Modal(app);
const { contentEl } = modal;
contentEl.createEl("style", {
text: `
input[type="checkbox"]:focus-visible {
outline: 2px solid ${app.getAccentColor()} !important;
outline-offset: 2px !important;
}
`
});
// Set title
contentEl.createEl("h3", {
text: "Icon Library"
});
// ---------------------
// Create keyword filter
// ---------------------
const inputContainer = contentEl.createDiv();
inputContainer.style.margin = "20px 0";
const input = contentEl.createEl("input", {
type: "text",
placeholder: "Enter filter term (leave empty for wildcard, you may use regular expression)",
});
input.style.width = "100%";
input.style.padding = "8px";
// Extract current keyword filter
const keywordFilterRegex = /(- +)\/(.*?)\/i?\.matches\(formula\.keywords\)/;
const keywordMatch = baseContent.match(keywordFilterRegex);
if (keywordMatch && keywordMatch[2] && keywordMatch[2] !== ".") {
input.value = keywordMatch[2];
}
// Set focus on the input
setTimeout(() => input.focus(), 50);
// ------------------
// Create toggle switches for file type filters
// ------------------
const toggleContainer = contentEl.createDiv();
toggleContainer.style.margin = "20px 0";
toggleContainer.style.display = "flex";
toggleContainer.style.gap = "15px";
toggleContainer.style.flexWrap = "wrap";
// Get current filter pattern to determine initial toggle states
const fileNameFilterRegex = /\/\^(.*?) \\- \/i?\.matches\(file\.name\.lower\(\)\)/;
const match = baseContent.match(fileNameFilterRegex);
let currentFilters = [];
if (match && match[1]) {
currentFilters = match[1].replace(/[\(\)]/g, '').split('|');
}
// Create toggle function
const createToggle = (label, value) => {
const toggleWrapper = toggleContainer.createDiv();
toggleWrapper.style.display = "flex";
toggleWrapper.style.alignItems = "center";
const checkbox = toggleWrapper.createEl("input", {
type: "checkbox",
attr: { id: `toggle-${value}` }
});
checkbox.checked = currentFilters.includes(value);
const labelEl = toggleWrapper.createEl("label", {
text: label,
attr: { for: `toggle-${value}` }
});
labelEl.style.marginLeft = "5px";
return checkbox;
};
// Create toggles dynamically based on ICONTYPES array
const typeToggles = {};
ICONTYPES.forEach(iconType => {
typeToggles[iconType.pattern] = createToggle(iconType.name, iconType.pattern);
});
// Function to apply the filter
const applyFilter = async () => {
// Get selected file types
const selectedTypes = [];
ICONTYPES.forEach(iconType => {
if (typeToggles[iconType.pattern].checked) selectedTypes.push(iconType.pattern);
});
// Build file type filter pattern
const fileTypePattern = selectedTypes.length > 0
? `/^(${selectedTypes.join('|')}) \\- /i`
: `/^() \\- /i`; // Empty pattern if none selected
// Get keyword filter
const keywordTerm = input.value.trim() || ".";
// Update both filter patterns in the base file
let updatedContent = baseContent;
// Update file name filter
updatedContent = updatedContent.replace(
/\/\^.*? \\\- \/i?\.matches\(file\.name\.lower\(\)\)/,
`${fileTypePattern}.matches(file.name.lower())`
);
// Update keyword filter
updatedContent = updatedContent.replace(
/(- +)\/.*\/i?\.matches\(formula\.keywords\)/g,
`$1/${keywordTerm}/i.matches(formula.keywords)`
);
// Save the updated file
if (updatedContent !== baseContent) {
await app.vault.modify(file, updatedContent);
baseContent = updatedContent; // Update base content to prevent duplicate updates
}
};
// -------------------
// Add event listeners for input changes to apply filter immediately
// -------------------
contentEl.querySelectorAll("input").forEach(el => {
el.addEventListener("input", applyFilter);
});
// Handle Enter key in the input field
contentEl.querySelectorAll("input").forEach(el => {
el.addEventListener("keydown", (e) => {
if (e.key === "Enter") {
e.preventDefault();
modal.close();
}
});
});
modal.open();
},
});
} else {
new Notice("Icon Library not initialized. Please update to the latest Excalidraw Plugin version", 0);
}
// -----------------
// -----------------
// Throttle Sync
// -----------------
// -----------------
const sync = app.internalPlugins.plugins["sync"]?.instance
function throttleSync() {
function setPause(newState) {
if (newState && sync.getStatus() !== "synced") {
setTimeout(() => setPause(true), 10000) //20 seconds
return;
}
sync.setPause(newState);
//console.log(`${moment().format("HH:mm:ss")} - ${sync.getStatus()}`);
if (newState) {
//unpause after 2 minutes
setTimeout(() => setPause(false), 120000) //2 minutes
} else {
//pause after 20 seconds of sync
setTimeout(() => setPause(true), 20000) //20 seconds
}
}
if (sync) {
if (ea.DEVICE.isDesktop) {
setPause(false);
console.log("Sync throttle started");
} else {
sync.setPause(false);
}
}
}
if (sync) {
sync.setPause(false);
}
//throttleSync();
// ----------------------
// ----------------------
// Move settings button
// ----------------------
// ----------------------
try {
if (ea.DEVICE.isDesktop) {
const actions = document.querySelector(".workspace-drawer-vault-actions");
actions.style.display = "none";
const setting = actions.children[1];
const header = document.querySelector(".workspace-tab-header-container");
const toggle = document.querySelector(".sidebar-toggle-button.mod-left");
header.appendChild(setting);
if (header === toggle.parentElement) header.insertBefore(setting, toggle);
}
} catch (e) {
console.log("Excalidraw Startup Move Settings Button", e);
}
// --------------
// --------------
// Debug logger
// --------------
// --------------
window.logger = (label, values) => {
if (!window.log) window.log = [];
window.log.push({
label,
timestamp: performance.now(),
stack: new Error().stack,
values,
});
return false;
}
window.printLog = () => {
console.log(window.log.map(l => {
return `${moment(l.timestamp).format("HH:mm:ss.SSS")} ${
l.label}\n${l.stack.split("\n").slice(3).map(x=>x.trim()).join("\n")
}\n------------------------`;
}).join("\n"))
}
if (window.electron) {
const alignElectronSpellcheckWithObsidianSettings = () => {
const session = window.electron.remote.getCurrentWebContents().session;
session.setSpellCheckerEnabled(app.vault.config.spellcheck);
if (app.vault.config.spellcheck) {
session.setSpellCheckerLanguages(navigator.languages);
}
};
const body = document.body;
const observer = new MutationObserver((mutationsList, observer) => {
for (let mutation of mutationsList) {
if (mutation.type === 'childList') {
mutation.removedNodes.forEach(node => {
if (node.classList && node.classList.contains('modal-container')) {
alignElectronSpellcheckWithObsidianSettings();
}
});
}
}
});
const config = {
childList: true
};
observer.observe(body, config);
alignElectronSpellcheckWithObsidianSettings();
}
// ------------------------
// ------------------------
// Excalidraw Event Hooks
// ------------------------
// ------------------------
/**
* If set, this callback is triggered when the user closes an Excalidraw view.
* onViewUnloadHook: (view: ExcalidrawView) => void = null;
*/
//ea.onViewUnloadHook = (view) => {};
/**
* If set, this callback is triggered, when the user changes the view mode.
* You can use this callback in case you want to do something additional when the user switches to view mode and back.
* onViewModeChangeHook: (isViewModeEnabled:boolean, view: ExcalidrawView, ea: ExcalidrawAutomate) => void = null;
*/
//ea.onViewModeChangeHook = (isViewModeEnabled, view, ea) => {};
/**
* If set, this callback is triggered, when the user hovers a link in the scene.
* You can use this callback in case you want to do something additional when the onLinkHover event occurs.
* This callback must return a boolean value.
* In case you want to prevent the excalidraw onLinkHover action you must return false, it will stop the native excalidraw onLinkHover management flow.
* onLinkHoverHook: (
* element: NonDeletedExcalidrawElement,
* linkText: string,
* view: ExcalidrawView,
* ea: ExcalidrawAutomate
* ) => boolean = null;
*/
//ea.onLinkHoverHook = (element, linkText, view, ea) => {};
/**
* If set, this callback is triggered, when the user clicks a link in the scene.
* You can use this callback in case you want to do something additional when the onLinkClick event occurs.
* This callback must return a boolean value.
* In case you want to prevent the excalidraw onLinkClick action you must return false, it will stop the native excalidraw onLinkClick management flow.
* onLinkClickHook:(
* element: ExcalidrawElement,
* linkText: string,
* event: MouseEvent,
* view: ExcalidrawView,
* ea: ExcalidrawAutomate
* ) => boolean = null;
*/
//ea.onLinkClickHook = (element,linkText,event, view, ea) => {};
/**
* If set, this callback is triggered, when Excalidraw receives an onDrop event.
* You can use this callback in case you want to do something additional when the onDrop event occurs.
* This callback must return a boolean value.
* In case you want to prevent the excalidraw onDrop action you must return false, it will stop the native excalidraw onDrop management flow.
* onDropHook: (data: {
* ea: ExcalidrawAutomate;
* event: React.DragEvent<HTMLDivElement>;
* draggable: any; //Obsidian draggable object
* type: "file" | "text" | "unknown";
* payload: {
* files: TFile[]; //TFile[] array of dropped files
* text: string; //string
* };
* excalidrawFile: TFile; //the file receiving the drop event
* view: ExcalidrawView; //the excalidraw view receiving the drop
* pointerPosition: { x: number; y: number }; //the pointer position on canvas at the time of drop
* }) => boolean = null;
*/
ea.onDropHook = (data) => {
const {view,draggable} = data;
if(!draggable) return;
const {file, type} = draggable;
if(!file || type !== "link") return;
const {extension} = file;
if(!(
data.ea.isExcalidrawFile(file) ||
["jpeg", "jpg", "png", "gif", "svg", "webp", "bmp", "ico", "jtif", "tif", "jfif", "avif"].contains(extension)
)) return;
const ea = data.ea.getAPI(view);
const idBefore = new Set(ea.getViewElements().map(el=>el.id));
setTimeout(()=>{
const newElements = ea.getViewElements().filter(el=>!idBefore.has(el.id));
if(newElements.length !== 1 || newElements[0].type !== "image") return;
const f = ea.getViewFileForImageElement(newElements[0]);
if(f !== file) return;
ea.copyViewElementsToEAforEditing(newElements);
ea.getElements().forEach(el=>{
const l = Math.max(el.width, el.height);
el.width = Math.round(el.width * 180/l);
el.height = Math.round(el.height * 180/l);
});
ea.addElementsToView();
},100);
}
/**
* If set, this callback is triggered, when Excalidraw receives an onPaste event.
* You can use this callback in case you want to do something additional when the
* onPaste event occurs.
* This callback must return a boolean value.
* In case you want to prevent the excalidraw onPaste action you must return false,
* it will stop the native excalidraw onPaste management flow.
* onPasteHook: (data: {
* ea: ExcalidrawAutomate;
* payload: ClipboardData;
* event: ClipboardEvent;
* excalidrawFile: TFile; //the file receiving the paste event
* view: ExcalidrawView; //the excalidraw view receiving the paste
* pointerPosition: { x: number; y: number }; //the pointer position on canvas
* }) => boolean = null;
*/
ea.onPasteHook = (data) => {
const {ea,payload} = data;
if (payload?.elements) {
payload.elements.filter(el => el.locked).forEach(el => {
el.locked = false;
});
/* data.payload.elements
.filter(el=>el.type==="text" && !el.hasOwnProperty("rawText"))
.forEach(el=>el.rawText = el.originalText);*/
}
/*
const getFileFromObsidianURL = (data) => {
if(!data) return null;
if(!data.startsWith("obsidian://")) return null;
try {
const url = new URL(data);
const fileParam = url.searchParams.get("file");
if(!fileParam) return null;
return decodeURIComponent(fileParam);
} catch {
return null;
}
}
if(payload.text) {
link = getFileFromObsidianURL(payload.text);
await ea.addImage(0,0,link);
await ea.addElementsToView(true,true,true);
return false;
}
*/
};
/**
* if set, this callback is triggered, when an Excalidraw file is opened
* You can use this callback in case you want to do something additional when the file is opened.
* This will run before the file level script defined in the `excalidraw-onload-script` frontmatter.
* onFileOpenHook: (data: {
* ea: ExcalidrawAutomate;
* excalidrawFile: TFile; //the file being loaded
* view: ExcalidrawView;
* }) => Promise<void>;
*/
//ea.onFileOpenHook = (data) => {};
/**
* if set, this callback is triggered, when an Excalidraw file is created
* see also: https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/1124
* onFileCreateHook: (data: {
* ea: ExcalidrawAutomate;
* excalidrawFile: TFile; //the file being created
* view: ExcalidrawView;
* }) => Promise<void>;
*/
/*ea.onFileCreateHook = (data) => {
app.fileManager.promptForFileRename(data.excalidrawFile);
};*/
/**
* If set, this callback is triggered when a image is being saved in Excalidraw.
* You can use this callback to customize the naming and path of pasted images to avoid
* default names like "Pasted image 123147170.png" being saved in the attachments folder,
* and instead use more meaningful names based on the Excalidraw file or other criteria,
* plus save the image in a different folder.
*
* If the function returns null or undefined, the normal Excalidraw operation will continue
* with the excalidraw generated name and default path.
* If a filepath is returned, that will be used. Include the full Vault filepath and filename
* with the file extension.
* The currentImageName is the name of the image generated by excalidraw or provided during paste.
*
* @param data - An object containing the following properties:
* @property {string} [currentImageName] - Default name for the image.
* @property {string} drawingFilePath - The file path of the Excalidraw file where the image is being used.
*
* @returns {string} - The new filepath for the image including full vault path and extension.
*
* Example usage:
* ```
* onImageFilePathHook: (data) => {
* const { currentImageName, drawingFilePath } = data;
* const ext = currentImageName.split('.').pop();
* // Generate a new filepath based on the drawing file name and other criteria
* return `${drawingFileName} - ${currentImageName || 'image'}.${ext}`;
* }
* ```
* onImageFilePathHook: (data: {
* currentImageName: string; // Excalidraw generated name of the image, or the name received from the file system.
* drawingFilePath: string; // The full filepath of the Excalidraw file where the image is being used.
* }) => string = null;
*/
// ea.onImageFilePathHook = (data) => { console.log(data); };
/**
* If set, this callback is triggered when the Excalidraw image is being exported to
* .svg, .png, or .excalidraw.
* You can use this callback to customize the naming and path of the images. This allows
* you to place images into an assets folder.
*
* If the function returns null or undefined, the normal Excalidraw operation will continue
* with the currentImageName and in the same folder as the Excalidraw file
* If a filepath is returned, that will be used. Include the full Vault filepath and filename
* with the file extension.
* !!!! If an image already exists on the path, that will be overwritten. When returning
* your own image path, you must take care of unique filenames (if that is a requirement) !!!!
* The current image name is the name generated by Excalidraw:
* - my-drawing.png
* - my-drawing.svg
* - my-drawing.excalidraw
* - my-drawing.dark.svg
* - my-drawing.light.svg
* - my-drawing.dark.png
* - my-drawing.light.png
*
* @param data - An object containing the following properties:
* @property {string} exportFilepath - Default export filepath for the image.
* @property {string} excalidrawFile - TFile: The Excalidraw file being exported.
* @property {ExcalidrawAutomate} ea - The ExcalidrawAutomate instance associated with the hook.
* @property {string} [oldExcalidrawPath] - If action === "move" The old path of the Excalidraw file, else undefined
* @property {string} action - The action being performed: "export", "move", or "delete". move and delete reference the change to the Excalidraw file.
*
* @returns {string} - The new filepath for the image including full vault path and extension.
*
* action === "move" || action === "delete" is only possible if "keep in sync" is enabled
* in plugin export settings
*
* Example usage:
* ```
* onImageFilePathHook: (data) => {
* const { currentImageName, drawingFilePath, frontmatter } = data;
* // Generate a new filepath based on the drawing file name and other criteria
* const ext = currentImageName.split('.').pop();
* if(frontmatter && frontmatter["my-custom-field"]) {
* }
* return `${drawingFileName} - ${currentImageName || 'image'}.${ext}`;
* }
* ```
*/
ea.onImageExportPathHook = (data) => {
//debugger; //remove comment to debug using Developer Console
let {
excalidrawFile,
exportFilepath,
exportExtension,
oldExcalidrawPath,
action
} = data;
const frontmatter = app.metadataCache.getFileCache(excalidrawFile)?.frontmatter;
//console.log(data, frontmatter);
const excalidrawFilename = action === "move" ?
ea.splitFolderAndFilename(excalidrawFile.name).filename :
excalidrawFile.name
if (excalidrawFilename.match(/^icon - /i)) {
const {
folderpath,
filename,
basename,
extension
} = ea.splitFolderAndFilename(exportFilepath);
exportFilepath = "Assets/icons/" + filename;
return exportFilepath;
}
if (excalidrawFilename.match(/^stickfigure - /i)) {
const {
folderpath,
filename,
basename,
extension
} = ea.splitFolderAndFilename(exportFilepath);
exportFilepath = "Assets/stickfigures/" + filename;
return exportFilepath;
}
if (excalidrawFilename.match(/^logo - /i)) {
const {
folderpath,
filename,
basename,
extension
} = ea.splitFolderAndFilename(exportFilepath);
exportFilepath = "Assets/logos/" + filename;
return exportFilepath;
}
// !!!! frontmatter will be undefined when action === "delete"
// this means if you base your logic on frontmatter properties, then
// plugin settings keep files in sync will break for those files when
// deleting the Excalidraw file. The images will not be deleted, or worst
// your logic might result in deleting other files. This hook gives you
// powerful control, but the hook function logic requires careful testing
// on your part.
//if(frontmatter && frontmatter["is-asset"]) { //custom frontmatter property
// exportFilepath = ea.obsidian.normalizePath("assets/" + exportFilepath);
// return exportFilepath;
//}
return exportFilepath;
};
/**
* Excalidraw supports auto-export of Excalidraw files to .png, .svg, and .excalidraw formats.
*
* Auto-export of Excalidraw files can be controlled at multiple levels.
* 1) In plugin settings where you can set up default auto-export applicable to all your Excalidraw files.
* 2) However, if you do not want to auto-export every file, you can also control auto-export
* at the file level using the 'excalidraw-autoexport' frontmatter property.
* 3) This hook gives you an additional layer of control over the auto-export process.
*
* This hook is triggered when an Excalidraw file is being saved.
*
* interface AutoexportConfig {
* png: boolean; // Whether to auto-export to PNG
* svg: boolean; // Whether to auto-export to SVG
* excalidraw: boolean; // Whether to auto-export to Excalidraw format
* theme: "light" | "dark" | "both"; // The theme to use for the export
* }
*
* @param {Object} data - The data for the hook.
* @param {AutoexportConfig} data.autoexportConfig - The current autoexport configuration.
* @param {TFile} data.excalidrawFile - The Excalidraw file being auto-exported.
* @returns {AutoexportConfig | null} - Return a modified AutoexportConfig to override the export behavior, or null to use the default.
*/
ea.onTriggerAutoexportHook = (data) => {
let {
autoexportConfig,
excalidrawFile
} = data;
//const frontmatter = app.metadataCache.getFileCache(excalidrawFile)?.frontmatter;
//console.log(data, frontmatter);
//logic based on filepath and frontmatter
if (excalidrawFile.name.match(/^(?:icon|stickfigure|logo) - /i)) {
autoexportConfig.theme = "light";
autoexportConfig.svg = true;
autoexportConfig.png = false;
autoexportConfig.excalidraw = false;
return autoexportConfig;
}
return autoexportConfig;
};
/**
* If set, this callback is triggered whenever the active canvas color changes
* onCanvasColorChangeHook: (
* ea: ExcalidrawAutomate,
* view: ExcalidrawView, //the excalidraw view
* color: string,
* ) => void = null;
*/
//ea.onCanvasColorChangeHook = (ea, view, color) => {};
/**
* If set, this callback is triggered whenever a drawing is exported to SVG.
* The string returned will replace the link in the exported SVG.
* The hook is only executed if the link is to a file internal to Obsidian
* see: https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/1605
* onUpdateElementLinkForExportHook: (data: {
* originalLink: string,
* obsidianLink: string,
* linkedFile: TFile | null,
* hostFile: TFile,
* }) => string = null;
*/
//ea.onUpdateElementLinkForExportHook = (data) => {
// const decodedObsidianURI = decodeURIComponent(data.obsidianLink);
//};
+3 -1
View File
@@ -577,9 +577,11 @@ export declare class ExcalidrawAutomate {
* @param {number} topX - The x-coordinate of the top-left corner.
* @param {number} topY - The y-coordinate of the top-left corner.
* @param {string} tex - The LaTeX equation string.
* @param {number} [scaleX=1] - The x-scaling factor (post mathjax creation)
* @param {number} [scaleY=1] - The y-scaling factor (post mathjax creation)
* @returns {Promise<string>} Promise resolving to the ID of the added LaTeX image element.
*/
addLaTex(topX: number, topY: number, tex: string): Promise<string>;
addLaTex(topX: number, topY: number, tex: string, scaleX?: number, scaleY?: number): Promise<string>;
/**
* Returns the base64 dataURL of the LaTeX equation rendered as an SVG.
* @param {string} tex - The LaTeX equation string.
+2 -2
View File
@@ -3011,7 +3011,7 @@ Fix:
- Transcluded text will now exclude ^block-references at end of lines
- Phantom duplicates of the drawing appear when "zoom to fit" results in a zoom value below 10% and there are many objects on the canvas [#850](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/850)
- CTRL+Wheel will increase/decrease zoom in steps of 5% matching the behavior of the "+" & "-" zoom buttons.
- Latest updates from Excalidarw.com
- Latest updates from Excalidraw.com
- Freedraw flip not scaling correctly [#5752](https://github.com/excalidraw/excalidraw/pull/5752)
- Multiple elements resizing regressions [#5586](https://github.com/excalidraw/excalidraw/pull/5586)
@@ -4339,7 +4339,7 @@ Fixed:
# 1.5.8
- minor fix to ExcalidarwAutomate addText to handle non-container bound text wrapping correctly.
- minor fix to ExcalidrawAutomate addText to handle non-container bound text wrapping correctly.
# 1.5.7
+3 -1
View File
@@ -577,9 +577,11 @@ export declare class ExcalidrawAutomate {
* @param {number} topX - The x-coordinate of the top-left corner.
* @param {number} topY - The y-coordinate of the top-left corner.
* @param {string} tex - The LaTeX equation string.
* @param {number} [scaleX=1] - The x-scaling factor (post mathjax creation)
* @param {number} [scaleY=1] - The y-scaling factor (post mathjax creation)
* @returns {Promise<string>} Promise resolving to the ID of the added LaTeX image element.
*/
addLaTex(topX: number, topY: number, tex: string): Promise<string>;
addLaTex(topX: number, topY: number, tex: string, scaleX?: number, scaleY?: number): Promise<string>;
/**
* Returns the base64 dataURL of the LaTeX equation rendered as an SVG.
* @param {string} tex - The LaTeX equation string.
+2 -2
View File
@@ -3011,7 +3011,7 @@ Fix:
- Transcluded text will now exclude ^block-references at end of lines
- Phantom duplicates of the drawing appear when "zoom to fit" results in a zoom value below 10% and there are many objects on the canvas [#850](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/850)
- CTRL+Wheel will increase/decrease zoom in steps of 5% matching the behavior of the "+" & "-" zoom buttons.
- Latest updates from Excalidarw.com
- Latest updates from Excalidraw.com
- Freedraw flip not scaling correctly [#5752](https://github.com/excalidraw/excalidraw/pull/5752)
- Multiple elements resizing regressions [#5586](https://github.com/excalidraw/excalidraw/pull/5586)
@@ -4339,7 +4339,7 @@ Fixed:
# 1.5.8
- minor fix to ExcalidarwAutomate addText to handle non-container bound text wrapping correctly.
- minor fix to ExcalidrawAutomate addText to handle non-container bound text wrapping correctly.
# 1.5.7
+3 -2
View File
@@ -7,7 +7,8 @@ If you are enjoying the Excalidraw plugin then please support my work and enthus
Jump ahead to the [[#List of available scripts]]
# Introducing Excalidraw Automate Script Engine
<iframe width="560" height="315" src="https://www.youtube.com/embed/hePJcObHIso" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
<a href="https://www.youtube.com/watch?v=hePJcObHIso" target="_blank"><img src ="https://i.ytimg.com/vi/hePJcObHIso/maxresdefault.jpg" style="width:560px;"></a>
Script Engine scripts are installed in the `Downloaded` subfolder of the `Excalidraw Automate script folder` specified in plugin settings.
@@ -243,7 +244,7 @@ https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/OCR%20-%20Optical%20Character%20Recognition.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/OCR%20-%20Optical%20Character%20Recognition.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">REQUIRES EXCALIDRAW 1.5.15<br>The script will 1) send the selected image file to [taskbone.com](https://taskbone.com) to extract the text from the image, and 2) will add the text to your drawing as a text element.<br><mark>⚠ Note that you will need to manually paste your token into the script after the first run! ⚠</mark><br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-ocr.jpg'><br><iframe width="560" height="315" src="https://www.youtube.com/embed/W2NMzR8s4eE" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></td></tr></table>
<table><tr valign='top'><td class="label">Author</td><td class="data"><a href='https://github.com/zsviczian'>@zsviczian</a></td></tr><tr valign='top'><td class="label">Source</td><td class="data"><a href='https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/ea-scripts/OCR%20-%20Optical%20Character%20Recognition.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">REQUIRES EXCALIDRAW 1.5.15<br>The script will 1) send the selected image file to [taskbone.com](https://taskbone.com) to extract the text from the image, and 2) will add the text to your drawing as a text element.<br><mark>⚠ Note that you will need to manually paste your token into the script after the first run! ⚠</mark><br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-ocr.jpg'><br><a href="https://www.youtube.com/watch?v=W2NMzR8s4eE" target="_blank"><img src ="https://i.ytimg.com/vi/W2NMzR8s4eE/maxresdefault.jpg" style="width:560px;"></a></td></tr></table>
## Organic Line
```excalidraw-script-install
@@ -3,9 +3,9 @@
Select some elements in the scene. The script will take these elements and move them into a new Excalidraw file, and open that file. The selected elements will also be replaced in your original drawing with the embedded Excalidraw file (the one that was just created). You will be prompted for the file name of the new deconstructed image. The script is useful if you want to break a larger drawing into smaller reusable parts that you want to reference in multiple drawings.
<iframe width="560" height="315" src="https://www.youtube.com/embed/HRtaaD34Zzg" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
<a href="https://www.youtube.com/watch?v=HRtaaD34Zzg" target="_blank"><img src ="https://i.ytimg.com/vi/HRtaaD34Zzg/maxresdefault.jpg" style="width:560px;"></a>
<iframe width="560" height="315" src="https://www.youtube.com/embed/mvMQcz401yo" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
<a href="https://www.youtube.com/watch?v=mvMQcz401yo" target="_blank"><img src ="https://i.ytimg.com/vi/mvMQcz401yo/maxresdefault.jpg" style="width:560px;"></a>
```javascript
*/
+3 -1
View File
@@ -1,5 +1,7 @@
/*
<iframe width="560" height="315" src="https://www.youtube.com/embed/A1vrSGBbWgo" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
<a href="https://www.youtube.com/watch?v=A1vrSGBbWgo" target="_blank"><img src ="https://i.ytimg.com/vi/A1vrSGBbWgo/maxresdefault.jpg" style="width:560px;"></a>
![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-draw-a-ui.jpg)
```js*/
+1 -1
View File
@@ -5,7 +5,7 @@ const room = Array.from(window.crypto.getRandomValues(new Uint8Array(10))).map((
const key = (await window.crypto.subtle.exportKey("jwk",await window.crypto.subtle.generateKey({name:"AES-GCM",length:128},true,["encrypt", "decrypt"]))).k;
const link = `https://excalidraw.com/#room=${room},${key}`;
ea.addIFrame(0,0,800,600,link);
ea.addEmbeddable(0,0,800,600,link);
ea.addElementsToView(true,true);
window.navigator.clipboard.writeText(link);
+2 -1
View File
@@ -1,5 +1,6 @@
/*
<iframe width="560" height="315" src="https://www.youtube.com/embed/A1vrSGBbWgo" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
<a href="https://www.youtube.com/watch?v=A1vrSGBbWgo" target="_blank"><img src ="https://i.ytimg.com/vi/A1vrSGBbWgo/maxresdefault.jpg" style="width:560px;"></a>
![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-draw-a-ui.jpg)
```js*/
+1 -2
View File
@@ -6,8 +6,7 @@ The script performs two different functions depending on the elements selected i
![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/golden-ratio.jpg)
<iframe width="560" height="315" src="https://www.youtube.com/embed/2SHn_ruax-s" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
<a href="https://www.youtube.com/watch?v=2SHn_ruax-s" target="_blank"><img src ="https://i.ytimg.com/vi/2SHn_ruax-s/maxresdefault.jpg" style="width:560px;"></a>
Gravitational point of spiral: $$\left[x,y\right]=\left[ x + \frac{{\text{width} \cdot \phi^2}}{{\phi^2 + 1}}\;, \; y + \frac{{\text{height} \cdot \phi^2}}{{\phi^2 + 1}} \right]$$
Dimensions of inner rectangles in case of Double Spiral: $$[width, height] = \left[\frac{width\cdot(\phi^2+1)}{2\phi^2}\;, \;\frac{height\cdot(\phi^2+1)}{2\phi^2}\right]$$
+100 -44
View File
@@ -1,65 +1,121 @@
/*
![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-invert-colors.jpg)
The script inverts the colors on the canvas including the color palette in Element Properties.
```javascript
*/
const defaultColorPalette = { // https://github.com/zsviczian/obsidian-excalidraw-plugin/releases/tag/1.6.8
elementStroke:["#000000","#343a40","#495057","#c92a2a","#a61e4d","#862e9c","#5f3dc4","#364fc7","#1864ab","#0b7285","#087f5b","#2b8a3e","#5c940d","#e67700","#d9480f"],
elementBackground:["transparent","#ced4da","#868e96","#fa5252","#e64980","#be4bdb","#7950f2","#4c6ef5","#228be6","#15aabf","#12b886","#40c057","#82c91e","#fab005","#fd7e14"],
canvasBackground:["#ffffff","#f8f9fa","#f1f3f5","#fff5f5","#fff0f6","#f8f0fc","#f3f0ff","#edf2ff","#e7f5ff","#e3fafc","#e6fcf5","#ebfbee","#f4fce3","#fff9db","#fff4e6"]
This script inverts all the colors in the current Excalidraw drawing. It applies the inversion to:
1. The stroke and background colors of every element on the canvas.
2. The main canvas background color.
3. All colors within the user's custom color palette, handling all possible configurations (simple arrays, nested arrays, and objects).
4. The currently selected stroke and background colors in the UI.
A default color palette is defined to use as a fallback if the current drawing's palette is missing or empty. // This is based on the standard Excalidraw palette from version [1.6.8.](https://github.com/zsviczian/obsidian-excalidraw-plugin/releases/tag/1.6.8)
You'll find a detailed description of the color palette data structure on the [Excalidraw-Obsidian Wiki](https://excalidraw-obsidian.online/wiki/color-palette)
```js*/
const defaultColorPalette = {
elementStroke: ["#000000", "#343a40", "#495057", "#c92a2a", "#a61e4d", "#862e9c", "#5f3dc4", "#364fc7", "#1864ab", "#0b7285", "#087f5b", "#2b8a3e", "#5c940d", "#e67700", "#d9480f"],
elementBackground: ["transparent", "#ced4da", "#868e96", "#fa5252", "#e64980", "#be4bdb", "#7950f2", "#4c6ef5", "#228be6", "#15aabf", "#12b886", "#40c057", "#82c91e", "#fab005", "#fd7e14"],
canvasBackground: ["#ffffff", "#f8f9fa", "#f1f3f5", "#fff5f5", "#fff0f6", "#f8f0fc", "#f3f0ff", "#edf2ff", "#e7f5ff", "#e3fafc", "#e6fcf5", "#ebfbee", "#f4fce3", "#fff9db", "#fff4e6"]
};
// Get the Excalidraw API and the current application state.
const api = ea.getExcalidrawAPI();
const st = api.getAppState();
// Retrieve the current color palette, falling back to the default if necessary.
let colorPalette = st.colorPalette ?? defaultColorPalette;
if (Object.entries(colorPalette).length === 0) colorPalette = defaultColorPalette;
if(!colorPalette.elementStroke || Object.entries(colorPalette.elementStroke).length === 0) colorPalette.elementStroke = defaultColorPalette.elementStroke;
if(!colorPalette.elementBackground || Object.entries(colorPalette.elementBackground).length === 0) colorPalette.elementBackground = defaultColorPalette.elementBackground;
if(!colorPalette.canvasBackground || Object.entries(colorPalette.canvasBackground).length === 0) colorPalette.canvasBackground = defaultColorPalette.canvasBackground;
if (!colorPalette || Object.keys(colorPalette).length === 0) {
colorPalette = defaultColorPalette;
}
// Ensure each key in the palette has a default value if it's missing.
if (!colorPalette.elementStroke || colorPalette.elementStroke.length === 0) {
colorPalette.elementStroke = defaultColorPalette.elementStroke;
}
if (!colorPalette.elementBackground || colorPalette.elementBackground.length === 0) {
colorPalette.elementBackground = defaultColorPalette.elementBackground;
}
if (!colorPalette.canvasBackground || colorPalette.canvasBackground.length === 0) {
colorPalette.canvasBackground = defaultColorPalette.canvasBackground;
}
/**
* Inverts a single color string by reversing its lightness value.
* This function uses the ColorMaster utility provided by Excalidraw Automate.
* It correctly handles various color formats (HEX, RGB, HSL) and preserves transparency.
* @param {string} color - The color to be inverted (e.g., "#FF0000").
* @returns {string} The inverted color string.
*/
const invertColor = (color) => {
if(color.toLowerCase()==="transparent") return color;
const cm = ea.getCM(color);
const lightness = cm.lightness;
cm.lightnessTo(Math.abs(lightness-100));
switch (cm.format) {
case "hsl": return cm.stringHSL();
case "rgb": return cm.stringRGB();
case "hsv": return cm.stringHSV();
default: return cm.stringHEX({alpha: false});
}
}
function invertColorsRecursively(obj) {
if (typeof obj === 'string') {
return invertColor(obj);
} else if (Array.isArray(obj)) {
return obj.map(item => invertColorsRecursively(item));
} else if (typeof obj === 'object' && obj !== null) {
const result = {};
Object.keys(obj).forEach(key => result[key] = invertColorsRecursively(obj[key]));
return result;
} else {
return obj;
const cm = ea.getCM(color);
const opts = cm.alpha !== 1 ? { alpha: true } : { alpha: false };
const lightness = cm.lightness;
cm.lightnessTo(Math.abs(lightness - 100)); // Invert lightness on a 0-100 scale.
switch (cm.format) {
case "hsl": return cm.stringHSL(opts);
case "rgb": return cm.stringRGB(opts);
case "hsv": return cm.stringHSV(opts);
default: return cm.stringHEX(opts);
}
}
colorPalette = invertColorsRecursively(colorPalette);
};
/**
* Recursively traverses a color palette data structure and inverts every color string found.
* This robustly handles all valid `colorPalette` configurations, including nested arrays
* (`string[][]`), simple arrays (`string[]`), and objects (`topPicks`).
* @param {any} palette - A color string, an array of colors, an array of arrays, or an object palette.
* @returns {any} A new palette structure with all colors inverted.
*/
const invertPaletteStructure = (palette) => {
if (typeof palette === 'string') {
// Base case: If the item is a color string, invert it.
return invertColor(palette);
}
if (Array.isArray(palette)) {
// If it's an array, recursively call this function for each item.
return palette.map(item => invertPaletteStructure(item));
}
if (typeof palette === 'object' && palette !== null) {
// If it's an object, create a new object and recursively process its values.
const newPalette = {};
for (const key in palette) {
if (Object.prototype.hasOwnProperty.call(palette, key)) {
newPalette[key] = invertPaletteStructure(palette[key]);
}
}
return newPalette;
}
// Return any other data types (like numbers or null) unchanged.
return palette;
};
// Generate the new, fully inverted color palette.
const invertedColorPalette = invertPaletteStructure(colorPalette);
// Load all elements from the current view into the Excalidraw Automate workbench for editing.
ea.copyViewElementsToEAforEditing(ea.getViewElements());
ea.getElements().forEach(el=>{
el.strokeColor = invertColor(el.strokeColor);
el.backgroundColor = invertColor(el.backgroundColor);
// Iterate over all elements and invert their stroke and background colors.
ea.getElements().forEach(el => {
if (el.strokeColor) {
el.strokeColor = invertColor(el.strokeColor);
}
if (el.backgroundColor) {
el.backgroundColor = invertColor(el.backgroundColor);
}
});
// Finally, update the Excalidraw scene with the inverted elements and application state.
ea.viewUpdateScene({
appState:{
colorPalette,
viewBackgroundColor: invertColor(st.viewBackgroundColor),
currentItemStrokeColor: invertColor(st.currentItemStrokeColor),
currentItemBackgroundColor: invertColor(st.currentItemBackgroundColor)
appState: {
colorPalette: invertedColorPalette,
viewBackgroundColor: invertColor(st.viewBackgroundColor),
currentItemStrokeColor: invertColor(st.currentItemStrokeColor),
currentItemBackgroundColor: invertColor(st.currentItemBackgroundColor)
},
elements: ea.getElements()
elements: ea.getElements(),
storeAction: "capture" // Ensures the change is saved and added to the undo/redo history.
});
+209
View File
@@ -0,0 +1,209 @@
/*
This script generates a linear (horizontal) calendar for a specified year, with days flowing left to right and months as rows.
![300](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-Linear-Calendar-Generator.jpg)
## Features
- Horizontal timeline layout with days of the week as columns
- Month names displayed on both left and right sides
- Weekend days (Saturday & Sunday) highlighted
- Day-of-week headers at top and bottom
## Customizable Colors
You can personalize the calendar's appearance by defining your own colors:
1. Create two rectangles in your design.
2. Select both rectangles before running the script:
• The **fill and stroke colors of the first rectangle** will be applied to weekdays.
• The **fill and stroke colors of the second rectangle** will be used for weekends.
If no rectangles are selected, the default color schema will be used (white and light blue-gray for weekends).
```javascript
*/
// -------------------------------------
// Constants initiation
// -------------------------------------
const CELL_WIDTH = 176; // Width of each day cell
const CELL_HEIGHT = 288; // Height of each day cell
const START_X = 0; // X start position
const START_Y = 0; // Y start position
const ROW_SPACING = 32; // Space between month rows
const MONTH_LABEL_WIDTH = 240; // Space for month labels on sides
// Colors
let COLOR_WEEKEND = "#e8eaed";
let COLOR_WEEKDAY = "#ffffff";
let COLOR_TEXT = "#000000";
let COLOR_WEEKEND_TEXT = "#000000";
let COLOR_HEADER_TEXT = "#000000";
const COLOR_STROKE = "#d0d4db";
let STROKE_WIDTH = 1;
let FILLSTYLE = "solid";
const ROUGHNESS = 0; // 0 = Architect, 1 = Artist, 2 = Cartoonist
const FONT_FAMILY = 3; // 1 = Virgil, 2 = Helvetica, 3 = Cascadia (code), 4 = Little One
// Font sizes
const FONT_SIZE_DAY = 56;
const FONT_SIZE_HEADER = 48;
const FONT_SIZE_MONTH = 64;
const FONT_SIZE_YEAR = 112;
// Day constants
const SATURDAY = 6;
const SUNDAY = 0;
const JANUARY = 0;
const FIRST_DAY_OF_THE_MONTH = 1;
// Day names (short)
const DAY_NAMES = ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"];
// Month names (short)
const MONTH_NAMES = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
// Number of day columns needed (max 37 to cover all possible month alignments: 6 days offset + 31 days)
const NUM_COLUMNS = 37;
// -------------------------------------
// Ask for requested Year
let requestedYear = parseFloat(new Date().getFullYear());
requestedYear = parseFloat(await utils.inputPrompt("Year?", requestedYear, requestedYear));
if (isNaN(requestedYear)) {
new Notice("Invalid number");
return;
}
// -------------------------------------
// Use selected elements for calendar style
// -------------------------------------
let elements = ea.getViewSelectedElements();
if (elements.length >= 1) {
COLOR_WEEKDAY = elements[0].backgroundColor;
FILLSTYLE = elements[0].fillStyle;
STROKE_WIDTH = elements[0].strokeWidth;
}
if (elements.length >= 2) {
COLOR_WEEKEND = elements[1].backgroundColor;
}
// -------------------------------------
// Helper function to get days in a month
// -------------------------------------
function getDaysInMonth(year, month) {
return new Date(year, month + 1, 0).getDate();
}
// -------------------------------------
// Helper function to get the day of week for first day of month
// -------------------------------------
function getFirstDayOfMonth(year, month) {
return new Date(year, month, 1).getDay();
}
// -------------------------------------
// Draw day-of-week headers
// -------------------------------------
function drawDayHeaders(yPosition) {
ea.style.fontSize = FONT_SIZE_HEADER;
ea.style.strokeColor = COLOR_TEXT;
ea.style.fontFamily = FONT_FAMILY;
for (let col = 0; col < NUM_COLUMNS; col++) {
const dayIndex = col % 7;
const x = START_X + MONTH_LABEL_WIDTH + (col * CELL_WIDTH);
// Center the text in the cell (approximate width of 2 chars)
const textX = x + (CELL_WIDTH / 2) - (FONT_SIZE_HEADER * 0.6);
ea.addText(textX, yPosition, DAY_NAMES[dayIndex]);
}
}
// -------------------------------------
// Draw month row
// -------------------------------------
function drawMonthRow(year, month, rowIndex) {
const daysInMonth = getDaysInMonth(year, month);
const firstDayOfWeek = getFirstDayOfMonth(year, month);
const y = START_Y + 160 + (rowIndex * (CELL_HEIGHT + ROW_SPACING));
// Draw month label on the left
ea.style.fontSize = FONT_SIZE_MONTH;
ea.style.strokeColor = COLOR_TEXT;
ea.style.fontFamily = FONT_FAMILY;
const monthLabelY = y + (CELL_HEIGHT / 2) - (FONT_SIZE_MONTH / 2);
ea.addText(START_X, monthLabelY, MONTH_NAMES[month]);
// Draw day cells
for (let day = 1; day <= daysInMonth; day++) {
const date = new Date(year, month, day);
const dayOfWeek = date.getDay();
const col = firstDayOfWeek + day - 1; // Column position based on day of week alignment
const x = START_X + MONTH_LABEL_WIDTH + (col * CELL_WIDTH);
const isWeekend = dayOfWeek === SATURDAY || dayOfWeek === SUNDAY;
// Set cell style
ea.style.backgroundColor = isWeekend ? COLOR_WEEKEND : COLOR_WEEKDAY;
ea.style.strokeColor = COLOR_STROKE;
ea.style.strokeWidth = STROKE_WIDTH;
ea.style.fillStyle = FILLSTYLE;
ea.style.roughness = ROUGHNESS;
// Draw cell rectangle
ea.addRect(x, y, CELL_WIDTH, CELL_HEIGHT);
// Draw day number
ea.style.fontSize = FONT_SIZE_DAY;
ea.style.strokeColor = COLOR_TEXT;
ea.style.fontFamily = FONT_FAMILY;
// Position the day number at top center of the cell
const dayStr = String(day).padStart(2, "0");
const charWidth = FONT_SIZE_DAY * 0.6; // Approximate character width
const textWidth = dayStr.length * charWidth;
const textX = x + (CELL_WIDTH - textWidth) / 2;
const textY = y + 32; // 32px padding from top
ea.addText(textX, textY, dayStr);
}
// Draw month label on the right
ea.style.fontSize = FONT_SIZE_MONTH;
ea.style.strokeColor = COLOR_TEXT;
const rightLabelX = START_X + MONTH_LABEL_WIDTH + (NUM_COLUMNS * CELL_WIDTH) + 60;
ea.addText(rightLabelX, monthLabelY, MONTH_NAMES[month]);
}
// -------------------------------------
// Main calendar generation
// -------------------------------------
// Draw year title (centered above calendar)
ea.style.fontSize = FONT_SIZE_YEAR;
ea.style.strokeColor = COLOR_TEXT;
ea.style.fontFamily = FONT_FAMILY;
const yearX = START_X + MONTH_LABEL_WIDTH + ((NUM_COLUMNS * CELL_WIDTH) / 2) - 120;
ea.addText(yearX, START_Y - 200, String(requestedYear));
// Draw top day-of-week headers
drawDayHeaders(START_Y);
// Draw all 12 months
for (let month = 0; month < 12; month++) {
drawMonthRow(requestedYear, month, month);
}
// Draw bottom day-of-week headers
const bottomHeaderY = START_Y + 160 + (12 * (CELL_HEIGHT + ROW_SPACING)) + 40;
drawDayHeaders(bottomHeaderY);
await ea.addElementsToView(false, false, true);
+24
View File
@@ -0,0 +1,24 @@
<svg version="1.1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 50.097575068473816 56.100231877975375" width="50.097575068473816" height="56.100231877975375" class="excalidraw-svg">
<!-- Linear calendar icon (same size/viewBox as original) -->
<g stroke="#1e1e1e" stroke-width="4" stroke-linecap="round" stroke-linejoin="round" fill="none">
<!-- Binding rings -->
<path d="M16 3 L16 12" />
<path d="M34.5 3 L34.5 12" />
<!-- Outer calendar body -->
<rect x="4" y="9" width="42.097575068473816" height="44.100231877975375" rx="5" ry="5" />
<!-- Header separator -->
<path d="M4 19 L46.097575068473816 19" />
<!-- A single highlighted date block -->
<rect x="10" y="23" width="8" height="8" rx="1.5" ry="1.5" />
<!-- Linear agenda lines -->
<path d="M22 27 L42 27" />
<path d="M10 35 L42 35" />
<path d="M10 43 L42 43" />
<path d="M10 51 L30 51" />
</g>
</svg>

After

Width:  |  Height:  |  Size: 929 B

File diff suppressed because it is too large. Load diff
+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="skip"><path d="m11 19-1.106-.552a2 2 0 0 0-1.788 0l-3.659 1.83A1 1 0 0 1 3 19.381V6.618a1 1 0 0 1 .553-.894l4.553-2.277a2 2 0 0 1 1.788 0l4.212 2.106a2 2 0 0 0 1.788 0l3.659-1.83A1 1 0 0 1 21 4.619V12"/><path d="M15 5.764V12"/><path d="M18 15v6"/><path d="M21 18h-6"/><path d="M9 3.236v15"/></svg>

After

Width:  |  Height:  |  Size: 485 B

+1 -2
View File
@@ -1,8 +1,7 @@
/*
Copies the text from the selected PDF page on the Excalidraw canvas to the clipboard.
<iframe width="560" height="315" src="https://www.youtube.com/embed/Kwt_8WdOUT4" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
Link:: https://youtu.be/Kwt_8WdOUT4
<a href="https://www.youtube.com/watch?v=Kwt_8WdOUT4" target="_blank"><img src ="https://i.ytimg.com/vi/Kwt_8WdOUT4/maxresdefault.jpg" style="width:560px;"></a>
```js*/
+2 -5
View File
@@ -1,11 +1,8 @@
/*
<a href="https://www.youtube.com/watch?v=epYNx2FSf2w" target="_blank"><img src ="https://i.ytimg.com/vi/epYNx2FSf2w/maxresdefault.jpg" style="width:560px;"></a>
<iframe width="560" height="315" src="https://www.youtube.com/embed/epYNx2FSf2w" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
Link:: https://youtu.be/epYNx2FSf2w
<iframe width="560" height="315" src="https://www.youtube.com/embed/diBT5iaoAYo" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
Link:: https://youtu.be/diBT5iaoAYo
<a href="https://www.youtube.com/watch?v=diBT5iaoAYo" target="_blank"><img src ="https://i.ytimg.com/vi/diBT5iaoAYo/maxresdefault.jpg" style="width:560px;"></a>
Design your palette at http://paletton.com/
Once you are happy with your colors, click Tables/Export in the bottom right of the screen:
+34 -23
View File
@@ -47,6 +47,7 @@ async function run() {
// Initialize state
let uiHidden = true;
let currentIcon = "eye";
let layerUIWrapper = ea.targetView.contentEl.querySelector(".excalidraw.excalidraw-container > .layer-ui__wrapper");
const toolbar = ea.targetView.contentEl.querySelector(".excalidraw > .Island");
let toolbarActive = toolbar?.style.display === "block";
let prevHiddenState = false;
@@ -55,30 +56,40 @@ async function run() {
const toggleUIVisibility = (hidden) => {
if(hidden === prevHiddenState) return hidden;
prevHiddenState = hidden;
try{
const topBar = ea.targetView.containerEl.querySelector(".App-top-bar");
const bottomBar = ea.targetView.containerEl.querySelector(".App-bottom-bar");
const sidebarToggle = ea.targetView.containerEl.querySelector(".sidebar-toggle");
const plugins = ea.targetView.containerEl.querySelector(".plugins-container");
if(hidden) {
if (toolbarActive && (toolbar?.style.display === "none")) {
toolbarActive = false;
if (!!layerUIWrapper) {
try {
if(hidden) {
layerUIWrapper.style.display = "none";
} else {
layerUIWrapper.style.display = "block";
}
} catch {};
} else {
try{
const topBar = ea.targetView.containerEl.querySelector(".App-top-bar");
const bottomBar = ea.targetView.containerEl.querySelector(".App-bottom-bar");
const sidebarToggle = ea.targetView.containerEl.querySelector(".sidebar-toggle");
const plugins = ea.targetView.containerEl.querySelector(".plugins-container");
if(hidden) {
if (toolbarActive && (toolbar?.style.display === "none")) {
toolbarActive = false;
}
if (toolbarActive = toolbar?.style.display === "block") {
toolbarActive = true;
};
}
if (toolbarActive = toolbar?.style.display === "block") {
toolbarActive = true;
};
}
const display = hidden ? "none" : "";
if (topBar) topBar.style.display = display;
if (bottomBar) bottomBar.style.display = display;
if (sidebarToggle) sidebarToggle.style.display = display;
if (plugins) plugins.style.display = display;
if (toolbarActive) toolbar.style.display = hidden ? "none" : "block";
modal.modalEl.style.opacity = hidden ? "0.4" : "0.8";
} catch {};
const display = hidden ? "none" : "";
if (topBar) topBar.style.display = display;
if (bottomBar) bottomBar.style.display = display;
if (sidebarToggle) sidebarToggle.style.display = display;
if (plugins) plugins.style.display = display;
if (toolbarActive) toolbar.style.display = hidden ? "none" : "block";
modal.modalEl.style.opacity = hidden ? "0.4" : "0.8";
} catch {};
};
return hidden;
};
+15 -46
View File
@@ -3,11 +3,11 @@
Scribble Helper can improve handwriting and add links. It lets you create and edit text elements, including wrapped text and sticky notes, by double-tapping on the canvas. When you run the script, it creates an event handler that will activate the editor when you double-tap. If you select a text element on the canvas before running the script, it will open the editor for that element. If you use a pen, you can set it up to only activate Scribble Helper when you double-tap with the pen. The event handler is removed when you run the script a second time or switch to a different tab.
<iframe width="560" height="315" src="https://www.youtube.com/embed/BvYkOaly-QM" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
<a href="https://www.youtube.com/watch?v=BvYkOaly-QM" target="_blank"><img src ="https://i.ytimg.com/vi/BvYkOaly-QM/maxresdefault.jpg" style="width:560px;"></a>
```javascript
```js
*/
if(!ea.verifyMinimumPluginVersion || !ea.verifyMinimumPluginVersion("2.11.0")) {
if(!ea.verifyMinimumPluginVersion || !ea.verifyMinimumPluginVersion("2.19.0")) {
new Notice("This script requires a newer version of Excalidraw. Please install the latest version.");
return;
}
@@ -58,39 +58,10 @@ if(typeof win.ExcalidrawScribbleHelper.action === "undefined") {
// Helper Functions
//---------------------------------------
// Color Palette for stroke color setting
// https://github.com/zsviczian/obsidian-excalidraw-plugin/releases/tag/1.6.8
const defaultStrokeColors = [
"#000000", "#343a40", "#495057", "#c92a2a", "#a61e4d",
"#862e9c", "#5f3dc4", "#364fc7", "#1864ab", "#0b7285",
"#087f5b", "#2b8a3e", "#5c940d", "#e67700", "#d9480f"
];
function loadColorPalette() {
const st = api.getAppState();
const strokeColors = new Set();
let strokeColorPalette = st.colorPalette?.elementStroke ?? defaultStrokeColors;
if(Object.entries(strokeColorPalette).length === 0) {
strokeColorPalette = defaultStrokeColors;
}
ea.getViewElements().forEach(el => {
if(el.strokeColor.toLowerCase()==="transparent") return;
strokeColors.add(el.strokeColor);
});
strokeColorPalette.forEach(color => {
strokeColors.add(color)
});
strokeColors.add(st.currentItemStrokeColor ?? ea.style.strokeColor);
return strokeColors;
}
// Event handler management
function addEventHandler(handler) {
if(win.ExcalidrawScribbleHelper.eventHandler) {
win.removeEventListner("pointerdown", handler);
win.removeEventListener("pointerdown", handler);
}
win.addEventListener("pointerdown",handler);
win.ExcalidrawScribbleHelper.eventHandler = handler;
@@ -147,19 +118,17 @@ function customControls (container) {
const viewBackground = api.getAppState().viewBackgroundColor;
const el1 = new ea.obsidian.Setting(container)
.setName(`Text color`)
.addDropdown(dropdown => {
Array.from(loadColorPalette()).forEach(color => {
const options = dropdown.addOption(color, color).selectEl.options;
options[options.length-1].setAttribute("style",`color: ${color
}; background: ${viewBackground};`);
});
dropdown
.setValue(ea.style.strokeColor)
.onChange(value => {
ea.style.strokeColor = value;
el1.nameEl.style.color = value;
})
})
.addButton(button => button
.setIcon("swatch-book")
.onClick(async () => {
const selected = await ea.showColorPicker(button.buttonEl, "elementStroke");
if(selected) {
ea.style.strokeColor = selected;
el1.nameEl.style.color = selected;
}
})
);
el1.nameEl.style.color = ea.style.strokeColor;
el1.nameEl.style.background = viewBackground;
el1.nameEl.style.fontWeight = "bold";
+50 -59
View File
@@ -23,10 +23,13 @@ const HELP_TEXT = `
- Additionally if the same color is used as fill and stroke the color can only be mapped once
- This is an experimental script - contributions welcome on GitHub via PRs
![](https://www.youtube.com/embed/ISuORbVKyhQ)
😍 If you find this script helpful, please [buy me a coffee ☕](https://ko-fi.com/zsolt).
<a href="https://www.youtube.com/watch?v=ISuORbVKyhQ" target="_blank"><img src ="https://i.ytimg.com/vi/ISuORbVKyhQ/maxresdefault.jpg" style="max-width:560px; width:100%"></a>
`;
if(!ea.verifyMinimumPluginVersion || !ea.verifyMinimumPluginVersion("2.7.2")) {
if(!ea.verifyMinimumPluginVersion || !ea.verifyMinimumPluginVersion("2.19.0")) {
new Notice("This script requires a newer version of Excalidraw. Please install the latest version.");
return;
}
@@ -323,7 +326,7 @@ function slider(contentEl, action, min, max, step, invert) {
function showModal() {
let debounceColorPicker = true;
const modal = new ea.obsidian.Modal(app);
const modal = new ea.FloatingModal(app);
let dirty = false;
modal.onOpen = async () => {
@@ -491,6 +494,50 @@ function showModal() {
.setValue(ea.getCM(info.mappedTo).stringHEX({alpha: false}).toLowerCase());
colorPicker.colorPickerEl.style.maxWidth = "2.5rem";
// Add palette picker button
const paletteButton = new ea.obsidian.Setting(row.controlEl)
.addButton(button => button
.setIcon("swatch-book")
.setTooltip("Pick from Palette")
.onClick(async () => {
const selected = await ea.showColorPicker(button.buttonEl, "elementStroke");
if (selected) {
try {
const cm = ea.getCM(selected);
if (cm) {
const format = settings[FORMAT].value;
// Preserve alpha from original color
const currentInfo = currentColors.get(svgElement.id).colors.get(color);
const originalAlpha = ea.getCM(currentInfo.mappedTo).alpha;
cm.alphaTo(originalAlpha);
const alpha = originalAlpha < 1 ? true : false;
const newColor = format === "RGB"
? cm.stringRGB({alpha , precision }).toLowerCase()
: format === "HEX"
? cm.stringHEX({alpha}).toLowerCase()
: cm.stringHSL({alpha, precision }).toLowerCase();
// Update text input
textInput.setValue(newColor);
// Update Color Picker visual
colorPicker.setValue(cm.stringHEX({alpha: false}).toLowerCase());
// Update SVG mapping
currentInfo.mappedTo = newColor;
run("Update SVG color");
}
} catch (e) {
console.error("Invalid color value:", e);
}
}
}));
paletteButton.settingEl.style.padding = "0";
paletteButton.settingEl.style.border = "0";
paletteButton.infoEl.style.display = "none";
// Store references to the components
colorInputs.set(color, {
@@ -561,8 +608,6 @@ function showModal() {
.setButtonText("Close")
.setCta(true)
.onClick(() => modal.close()));
makeModalDraggable(modalEl);
const maxHeight = Math.round(height * 0.6);
const maxWidth = Math.round(width * 0.9);
@@ -583,60 +628,6 @@ function showModal() {
modal.open();
}
/**
* Add draggable functionality to the modal element.
* @param {HTMLElement} modalEl - The modal element to make draggable.
*/
function makeModalDraggable(modalEl) {
let isDragging = false;
let startX, startY, initialX, initialY;
const header = modalEl.querySelector('.modal-titlebar') || modalEl; // Default to modalEl if no titlebar
header.style.cursor = 'move';
const onPointerDown = (e) => {
// Ensure the event target isn't an interactive element like slider, button, or input
if (e.target.tagName === 'INPUT' || e.target.tagName === 'BUTTON') return;
isDragging = true;
startX = e.clientX;
startY = e.clientY;
const rect = modalEl.getBoundingClientRect();
initialX = rect.left;
initialY = rect.top;
modalEl.style.position = 'absolute';
modalEl.style.margin = '0';
modalEl.style.left = `${initialX}px`;
modalEl.style.top = `${initialY}px`;
};
const onPointerMove = (e) => {
if (!isDragging) return;
const dx = e.clientX - startX;
const dy = e.clientY - startY;
modalEl.style.left = `${initialX + dx}px`;
modalEl.style.top = `${initialY + dy}px`;
};
const onPointerUp = () => {
isDragging = false;
};
header.addEventListener('pointerdown', onPointerDown);
document.addEventListener('pointermove', onPointerMove);
document.addEventListener('pointerup', onPointerUp);
// Clean up event listeners on modal close
modalEl.addEventListener('remove', () => {
header.removeEventListener('pointerdown', onPointerDown);
document.removeEventListener('pointermove', onPointerMove);
document.removeEventListener('pointerup', onPointerUp);
});
}
function executeChange(isDecrease, step, action) {
const modifyStroke = settings[STROKE].value;
const modifyBackground = settings[BACKGROUND].value;
+39 -3
View File
@@ -48,6 +48,7 @@ const EDIT_ZOOMOUT = 0.7; //70% of original slide zoom, set to a value between 1
const FADE_LEVEL = 0.1; //opacity of the slideshow controls after fade delay (value between 0 and 1)
const PRINT_SLIDE_WIDTH = 1920;
const PRINT_SLIDE_HEIGHT = 1080;
const MAX_ZOOM = 30; //3000%
//using outerHTML because the SVG object returned by Obsidin is in the main workspace window
//but excalidraw might be open in a popout window which has a different document object
const SVG_COG = ea.obsidian.getIcon("lucide-settings").outerHTML;
@@ -60,6 +61,7 @@ const SVG_MINIMIZE = ea.obsidian.getIcon("lucide-minimize").outerHTML;
const SVG_LASER_ON = ea.obsidian.getIcon("lucide-hand").outerHTML;
const SVG_LASER_OFF = ea.obsidian.getIcon("lucide-wand").outerHTML;
const SVG_PRINTER = ea.obsidian.getIcon("lucide-printer").outerHTML;
const SVG_REFOCUS = ea.obsidian.getIcon("lucide-scan-eye").outerHTML;
//-------------------------------
//utility & convenience functions
@@ -278,7 +280,7 @@ const getNavigationRect = ({ x1, y1, x2, y2, printDimensions }) => {
const { width, height } = printDimensions ? printDimensions : excalidrawAPI.getAppState();
const ratioX = width / Math.abs(x1 - x2);
const ratioY = height / Math.abs(y1 - y2);
let ratio = Math.min(Math.max(ratioX, ratioY), 30);
let ratio = Math.min(Math.max(ratioX, ratioY), MAX_ZOOM);
const scaledWidth = Math.abs(x1 - x2) * ratio;
const scaledHeight = Math.abs(y1 - y2) * ratio;
@@ -499,9 +501,22 @@ const createPresentationNavigationPanel = () => {
}
});
el.createEl("button",{
attr: {
title: "Re-focus current slide (shortcut: HOME)"
}
}, button => {
button.innerHTML = SVG_REFOCUS;
button.onclick = () => {
debugger;
slide--;
navigate("fwd");
}
});
el.createEl("button",{
attr: {
title: "Toggle fullscreen. If you hold ALT/OPT when starting the presentation it will not go fullscreen."
title: "Toggle fullscreen. If you hold ALT/OPT when starting the presentation it will not go fullscreen. (shortcut: f)"
},
}, button => {
toggleFullscreenButton = button;
@@ -590,7 +605,7 @@ const keydownListener = (e) => {
navigate("fwd");
break;
case "Home":
slide = -1;
slide--;
navigate("fwd");
break;
case "e":
@@ -600,6 +615,9 @@ const keydownListener = (e) => {
exitPresentation(true);
})()
break;
case "f":
toggleFullscreen();
break;
}
}
@@ -793,6 +811,22 @@ const translateToZero = ({ top, left, bottom, right }, padding) => {
};
}
const getElementPlaceholdersForMarkerFrames = () => {
const viewMarkerFrames = ea.getViewElements().filter(el=>el.type === "frame" && el.frameRole === "marker");
if(viewMarkerFrames.length === 0) return;
ea.clear();
ea.style.opacity = 0;
ea.style.roughness = 0;
ea.style.fillStyle = "solid";
ea.style.backgroundColor = "black"
ea.style.strokeWidth = 0.01;
for (const frame of viewMarkerFrames) {
ea.addRect(frame.x, frame.y, frame.width, frame.height);
}
return ea.getViewElements().concat(ea.getElements());
}
const printToPDF = async (e) => {
const slideWidth = e.shiftKey ? excalidrawAPI.getAppState().width : PRINT_SLIDE_WIDTH;
const slideHeight = e.shiftKey ? excalidrawAPI.getAppState().height : PRINT_SLIDE_HEIGHT;
@@ -803,6 +837,7 @@ const printToPDF = async (e) => {
const padding = shouldClipFrames ? 0 : Math.round(Math.max(slideWidth,slideHeight)/2)+10;
const st = ea.getExcalidrawAPI().getAppState();
setSingleNotice("Generating image. This can take a longer time depending on the size of the image and speed of your device");
const elementsOverride = getElementPlaceholdersForMarkerFrames();
const svg = await ea.createViewSVG({
withBackground: true,
theme: st.theme,
@@ -811,6 +846,7 @@ const printToPDF = async (e) => {
selectedOnly: false,
skipInliningFonts: false,
embedScene: false,
elementsOverride,
});
const pages = [];
for(i=0;i<slides.length;i++) {
+1 -1
View File
@@ -1 +1 @@
[{"fname":"Mindmap connector.md","mtime":1658686599427},{"fname":"Mindmap connector.svg","mtime":1658686599427},{"fname":"Add Connector Point.md","mtime":1735420748564},{"fname":"Add Connector Point.svg","mtime":1645944722000},{"fname":"Add Link to Existing File and Open.md","mtime":1647807918345},{"fname":"Add Link to Existing File and Open.svg","mtime":1645964261000},{"fname":"Add Link to New Page and Open.md","mtime":1654168862138},{"fname":"Add Link to New Page and Open.svg","mtime":1645960639000},{"fname":"Add Next Step in Process.md","mtime":1688304760357},{"fname":"Add Next Step in Process.svg","mtime":1645960639000},{"fname":"Box Each Selected Groups.md","mtime":1645305706000},{"fname":"Box Each Selected Groups.svg","mtime":1645967510000},{"fname":"Box Selected Elements.md","mtime":1645305706000},{"fname":"Box Selected Elements.svg","mtime":1645960639000},{"fname":"Change shape of selected elements.md","mtime":1652701169236},{"fname":"Change shape of selected elements.svg","mtime":1645960775000},{"fname":"Connect elements.md","mtime":1645305706000},{"fname":"Connect elements.svg","mtime":1645960639000},{"fname":"Convert freedraw to line.md","mtime":1645305706000},{"fname":"Convert freedraw to line.svg","mtime":1645960639000},{"fname":"Convert selected text elements to sticky notes.md","mtime":1670169501383},{"fname":"Convert selected text elements to sticky notes.svg","mtime":1645960639000},{"fname":"Convert text to link with folder and alias.md","mtime":1641639819000},{"fname":"Convert text to link with folder and alias.svg","mtime":1645960639000},{"fname":"Copy Selected Element Styles to Global.md","mtime":1642232088000},{"fname":"Copy Selected Element Styles to Global.svg","mtime":1645960639000},{"fname":"Create new markdown file and embed into active drawing.md","mtime":1640866935000},{"fname":"Create new markdown file and embed into active drawing.svg","mtime":1645960639000},{"fname":"Darken background color.md","mtime":1663059051059},{"fname":"Darken background color.svg","mtime":1645960639000},{"fname":"Elbow connectors.md","mtime":1671126911490},{"fname":"Elbow connectors.svg","mtime":1645960639000},{"fname":"Expand rectangles horizontally keep text centered.md","mtime":1646563692000},{"fname":"Expand rectangles horizontally keep text centered.svg","mtime":1645967510000},{"fname":"Expand rectangles horizontally.md","mtime":1644950235000},{"fname":"Expand rectangles horizontally.svg","mtime":1645967510000},{"fname":"Expand rectangles vertically keep text centered.md","mtime":1646563692000},{"fname":"Expand rectangles vertically keep text centered.svg","mtime":1645967510000},{"fname":"Expand rectangles vertically.md","mtime":1658686599427},{"fname":"Expand rectangles vertically.svg","mtime":1645967510000},{"fname":"Fixed horizontal distance between centers.md","mtime":1646743234000},{"fname":"Fixed horizontal distance between centers.svg","mtime":1645960639000},{"fname":"Fixed inner distance.md","mtime":1646743234000},{"fname":"Fixed inner distance.svg","mtime":1645960639000},{"fname":"Fixed spacing.md","mtime":1646743234000},{"fname":"Fixed spacing.svg","mtime":1645967510000},{"fname":"Fixed vertical distance between centers.md","mtime":1646743234000},{"fname":"Fixed vertical distance between centers.svg","mtime":1645967510000},{"fname":"Fixed vertical distance.md","mtime":1646743234000},{"fname":"Fixed vertical distance.svg","mtime":1645967510000},{"fname":"Lighten background color.md","mtime":1663059051059},{"fname":"Lighten background color.svg","mtime":1645959546000},{"fname":"Modify background color opacity.md","mtime":1644924415000},{"fname":"Modify background color opacity.svg","mtime":1645944722000},{"fname":"Normalize Selected Arrows.md","mtime":1670403743278},{"fname":"Normalize Selected Arrows.svg","mtime":1645960639000},{"fname":"Organic Line.md","mtime":1672920172531},{"fname":"Organic Line.svg","mtime":1645964261000},{"fname":"Organic Line Legacy.md","mtime":1690607372668},{"fname":"Organic Line Legacy.svg","mtime":1690607372668},{"fname":"README.md","mtime":1645175700000},{"fname":"Repeat Elements.md","mtime":1663059051059},{"fname":"Repeat Elements.svg","mtime":1645960639000},{"fname":"Reverse arrows.md","mtime":1645305706000},{"fname":"Reverse arrows.svg","mtime":1645960639000},{"fname":"Scribble Helper.md","mtime":1747585400113},{"fname":"Scribble Helper.svg","mtime":1645944722000},{"fname":"Select Elements of Type.md","mtime":1643464321000},{"fname":"Select Elements of Type.svg","mtime":1645960639000},{"fname":"Set Dimensions.md","mtime":1645305706000},{"fname":"Set Dimensions.svg","mtime":1645944722000},{"fname":"Set Font Family.md","mtime":1645305706000},{"fname":"Set Font Family.svg","mtime":1645944722000},{"fname":"Set Grid.md","mtime":1693725826368},{"fname":"Set Grid.svg","mtime":1645960639000},{"fname":"Set Link Alias.md","mtime":1645305706000},{"fname":"Set Link Alias.svg","mtime":1645960639000},{"fname":"Set Stroke Width of Selected Elements.md","mtime":1748189277Line truncated
[{"fname":"Mindmap connector.md","mtime":1658686599427},{"fname":"Mindmap connector.svg","mtime":1658686599427},{"fname":"Add Connector Point.md","mtime":1735420748564},{"fname":"Add Connector Point.svg","mtime":1645944722000},{"fname":"Add Link to Existing File and Open.md","mtime":1647807918345},{"fname":"Add Link to Existing File and Open.svg","mtime":1645964261000},{"fname":"Add Link to New Page and Open.md","mtime":1654168862138},{"fname":"Add Link to New Page and Open.svg","mtime":1645960639000},{"fname":"Add Next Step in Process.md","mtime":1688304760357},{"fname":"Add Next Step in Process.svg","mtime":1645960639000},{"fname":"Box Each Selected Groups.md","mtime":1645305706000},{"fname":"Box Each Selected Groups.svg","mtime":1645967510000},{"fname":"Box Selected Elements.md","mtime":1645305706000},{"fname":"Box Selected Elements.svg","mtime":1645960639000},{"fname":"Change shape of selected elements.md","mtime":1652701169236},{"fname":"Change shape of selected elements.svg","mtime":1645960775000},{"fname":"Connect elements.md","mtime":1645305706000},{"fname":"Connect elements.svg","mtime":1645960639000},{"fname":"Convert freedraw to line.md","mtime":1645305706000},{"fname":"Convert freedraw to line.svg","mtime":1645960639000},{"fname":"Convert selected text elements to sticky notes.md","mtime":1670169501383},{"fname":"Convert selected text elements to sticky notes.svg","mtime":1645960639000},{"fname":"Convert text to link with folder and alias.md","mtime":1641639819000},{"fname":"Convert text to link with folder and alias.svg","mtime":1645960639000},{"fname":"Copy Selected Element Styles to Global.md","mtime":1642232088000},{"fname":"Copy Selected Element Styles to Global.svg","mtime":1645960639000},{"fname":"Create new markdown file and embed into active drawing.md","mtime":1640866935000},{"fname":"Create new markdown file and embed into active drawing.svg","mtime":1645960639000},{"fname":"Darken background color.md","mtime":1663059051059},{"fname":"Darken background color.svg","mtime":1645960639000},{"fname":"Elbow connectors.md","mtime":1671126911490},{"fname":"Elbow connectors.svg","mtime":1645960639000},{"fname":"Expand rectangles horizontally keep text centered.md","mtime":1646563692000},{"fname":"Expand rectangles horizontally keep text centered.svg","mtime":1645967510000},{"fname":"Expand rectangles horizontally.md","mtime":1644950235000},{"fname":"Expand rectangles horizontally.svg","mtime":1645967510000},{"fname":"Expand rectangles vertically keep text centered.md","mtime":1646563692000},{"fname":"Expand rectangles vertically keep text centered.svg","mtime":1645967510000},{"fname":"Expand rectangles vertically.md","mtime":1658686599427},{"fname":"Expand rectangles vertically.svg","mtime":1645967510000},{"fname":"Fixed horizontal distance between centers.md","mtime":1646743234000},{"fname":"Fixed horizontal distance between centers.svg","mtime":1645960639000},{"fname":"Fixed inner distance.md","mtime":1646743234000},{"fname":"Fixed inner distance.svg","mtime":1645960639000},{"fname":"Fixed spacing.md","mtime":1646743234000},{"fname":"Fixed spacing.svg","mtime":1645967510000},{"fname":"Fixed vertical distance between centers.md","mtime":1646743234000},{"fname":"Fixed vertical distance between centers.svg","mtime":1645967510000},{"fname":"Fixed vertical distance.md","mtime":1646743234000},{"fname":"Fixed vertical distance.svg","mtime":1645967510000},{"fname":"Lighten background color.md","mtime":1663059051059},{"fname":"Lighten background color.svg","mtime":1645959546000},{"fname":"Modify background color opacity.md","mtime":1644924415000},{"fname":"Modify background color opacity.svg","mtime":1645944722000},{"fname":"Normalize Selected Arrows.md","mtime":1670403743278},{"fname":"Normalize Selected Arrows.svg","mtime":1645960639000},{"fname":"Organic Line.md","mtime":1672920172531},{"fname":"Organic Line.svg","mtime":1645964261000},{"fname":"Organic Line Legacy.md","mtime":1690607372668},{"fname":"Organic Line Legacy.svg","mtime":1690607372668},{"fname":"README.md","mtime":1645175700000},{"fname":"Repeat Elements.md","mtime":1663059051059},{"fname":"Repeat Elements.svg","mtime":1645960639000},{"fname":"Reverse arrows.md","mtime":1645305706000},{"fname":"Reverse arrows.svg","mtime":1645960639000},{"fname":"Scribble Helper.md","mtime":1767536720161},{"fname":"Scribble Helper.svg","mtime":1645944722000},{"fname":"Select Elements of Type.md","mtime":1643464321000},{"fname":"Select Elements of Type.svg","mtime":1645960639000},{"fname":"Set Dimensions.md","mtime":1645305706000},{"fname":"Set Dimensions.svg","mtime":1645944722000},{"fname":"Set Font Family.md","mtime":1645305706000},{"fname":"Set Font Family.svg","mtime":1645944722000},{"fname":"Set Grid.md","mtime":1693725826368},{"fname":"Set Grid.svg","mtime":1645960639000},{"fname":"Set Link Alias.md","mtime":1645305706000},{"fname":"Set Link Alias.svg","mtime":1645960639000},{"fname":"Set Stroke Width of Selected Elements.md","mtime":1748189277Line truncated
+29 -14
View File
@@ -7,7 +7,7 @@ If you are enjoying the Excalidraw plugin then please support my work and enthus
Jump ahead to the [[#List of available scripts]]
# Introducing Excalidraw Automate Script Engine
<iframe width="560" height="315" src="https://www.youtube.com/embed/hePJcObHIso" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
<a href="https://www.youtube.com/watch?v=hePJcObHIso" target="_blank"><img src ="https://i.ytimg.com/vi/hePJcObHIso/maxresdefault.jpg" style="width:560px;"></a>
Script Engine scripts are installed in the `Downloaded` subfolder of the `Excalidraw Automate script folder` specified in plugin settings.
@@ -55,6 +55,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/Excalidraw%20Writing%20Machine.svg"/></div>|[[#Excalidraw Writing Machine]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Convert%20freedraw%20to%20line.svg"/></div>|[[#Convert freedraw to line]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Crop%20Vintage%20Mask.svg"/></div>|[[#Crop Vintage Mask]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Mindmap%20Builder.svg"/></div>|[[#Mindmap Builder]]|
## Layout and Organization
**Keywords**: Design, Placement, Arrangement, Structure, Formatting, Alignment
@@ -76,6 +77,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/Fixed%20vertical%20distance.svg"/></div>|[[#Fixed vertical distance]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Golden%20Ratio.svg"/></div>|[[#Golden Ratio]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Grid%20Selected%20Images.svg"/></div>|[[#Grid selected images]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-mindmap-builder.png"/></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/Zoom%20to%20Fit%20Selected%20Elements.svg"/></div>|[[#Zoom to Fit Selected Elements]]|
@@ -181,6 +183,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/Convert%20freedraw%20to%20line.svg"/></div>|[[#Convert freedraw to line]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Deconstruct%20selected%20elements%20into%20new%20drawing.svg"/></div>|[[#Deconstruct selected elements into new drawing]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Full-Year%20Calendar%20Generator.svg"/></div>|[[#Full-Year Calendar Generator]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Linear%20Calendar%20Generator.svg"/></div>|[[#Linear Calendar Generator]]|
## Masking and cropping
**Keywords**: Crop, Mask, Transform images
@@ -289,7 +292,7 @@ https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/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><iframe width="400" height="225" src="https://www.youtube.com/embed/DJcosmN-q2s" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></td></tr></table>
<table><tr valign='top'><td class="label">Author</td><td class="data"><a href='https://github.com/zsviczian'>@zsviczian</a></td></tr><tr valign='top'><td class="label">Source</td><td class="data"><a href='https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/ea-scripts/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
@@ -321,7 +324,7 @@ https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Deconstruct%20selected%20elements%20into%20new%20drawing.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/Deconstruct%20selected%20elements%20into%20new%20drawing.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">Select some elements in the scene. The script will take these elements and move them into a new Excalidraw file, and open that file. The selected elements will also be replaced in your original drawing with the embedded Excalidraw file (the one that was just created). You will be prompted for the file name of the new deconstructed image. The script is useful if you want to break a larger drawing into smaller reusable parts that you want to reference in multiple drawings.<br><iframe width="400" height="225" src="https://www.youtube.com/embed/HRtaaD34Zzg" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe><br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-deconstruct.jpg'></td></tr></table>
<table><tr valign='top'><td class="label">Author</td><td class="data"><a href='https://github.com/zsviczian'>@zsviczian</a></td></tr><tr valign='top'><td class="label">Source</td><td class="data"><a href='https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/ea-scripts/Deconstruct%20selected%20elements%20into%20new%20drawing.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">Select some elements in the scene. The script will take these elements and move them into a new Excalidraw file, and open that file. The selected elements will also be replaced in your original drawing with the embedded Excalidraw file (the one that was just created). You will be prompted for the file name of the new deconstructed image. The script is useful if you want to break a larger drawing into smaller reusable parts that you want to reference in multiple drawings.<br><a href="https://www.youtube.com/watch?v=HRtaaD34Zzg" target="_blank"><img src ="https://i.ytimg.com/vi/HRtaaD34Zzg/maxresdefault.jpg" style="width:400px;"></a><br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-deconstruct.jpg'></td></tr></table>
## Elbow connectors
```excalidraw-script-install
@@ -339,7 +342,7 @@ https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Excalidraw%20Collaboration%20Frame.md
```
<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/Excalidraw%20Collaboration%20Frame.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">Creates a new Excalidraw.com collaboration room and places the link to the room on the clipboard.<iframe width="400" height="225" src="https://www.youtube.com/embed/7isRfeAhEH4" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></td></tr></table>
<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/Excalidraw%20Collaboration%20Frame.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">Creates a new Excalidraw.com collaboration room and places the link to the room on the clipboard.<a href="https://www.youtube.com/watch?v=7isRfeAhEH4" target="_blank"><img src ="https://i.ytimg.com/vi/7isRfeAhEH4/maxresdefault.jpg" style="width:400px;"></a></td></tr></table>
## Expand rectangles horizontally keep text centered
```excalidraw-script-install
@@ -407,7 +410,7 @@ 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/Golden%20Ratio.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">The script performs two different functions depending on the elements selected in the view.<br>
1) In case you select text elements, the script will cycle through a set of font scales. First the 2 larger fonts following the Fibonacci sequence (fontsize * φ; fonsize * φ^2), then the 2 smaller fonts (fontsize / φ; fontsize / φ^2), finally the original size, followed again by the 2 larger fonts. If you wait 2 seconds, the sequence clears and starts from which ever font size you are on. So if you want the 3rd larges font, then toggle twice, wait 2 sec, then toggle again.<br>
2) In case you select a single rectangle, the script will open the "Golden Grid", "Golden Spiral" window, where you can set up the type of grid or spiral you want to insert into the document.<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/golden-ratio.jpg'><br><iframe width="400" height="225" src="https://www.youtube.com/embed/2SHn_ruax-s" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></td></tr></table>
2) In case you select a single rectangle, the script will open the "Golden Grid", "Golden Spiral" window, where you can set up the type of grid or spiral you want to insert into the document.<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/golden-ratio.jpg'><br><a href="https://www.youtube.com/watch?v=2SHn_ruax-s" target="_blank"><img src ="https://i.ytimg.com/vi/2SHn_ruax-s/maxresdefault.jpg" style="width:400px;"></a></td></tr></table>
## Grid selected images
```excalidraw-script-install
@@ -419,13 +422,13 @@ https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/ExcaliAI.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/ExcaliAI.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">Various AI features based on GPT Vision.<br><iframe width="400" height="225" src="https://www.youtube.com/embed/A1vrSGBbWgo" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-draw-a-ui.jpg'></td></tr></table>
<table><tr valign='top'><td class="label">Author</td><td class="data"><a href='https://github.com/zsviczian'>@zsviczian</a></td></tr><tr valign='top'><td class="label">Source</td><td class="data"><a href='https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/ea-scripts/ExcaliAI.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">Various AI features based on GPT Vision.<br><a href="https://www.youtube.com/watch?v=A1vrSGBbWgo" target="_blank"><img src ="https://i.ytimg.com/vi/A1vrSGBbWgo/maxresdefault.jpg" style="width:400px;"></a><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-draw-a-ui.jpg'></td></tr></table>
## Excalidraw Writing Machine
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Excalidraw%20Writing%20Machine.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/Excalidraw%20Writing%20Machine.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">Creates a hierarchical Markdown document out of a visual layout of an article that can be fed to Templater and converted into an article using AI for Templater.<br>Watch this video to understand how the script is intended to work:<br><iframe width="400" height="225" src="https://www.youtube.com/embed/zvRpCOZAUSs" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe><br>You can download the sample Obsidian Templater file from <a href="https://gist.github.com/zsviczian/bf49d4b2d401f5749aaf8c2fa8a513d9">here</a>. You can download the demo PDF document showcased in the video from <a href="https://zsviczian.github.io/DemoArticle-AtomicHabits.pdf">here</a>.</td></tr></table>
<table><tr valign='top'><td class="label">Author</td><td class="data"><a href='https://github.com/zsviczian'>@zsviczian</a></td></tr><tr valign='top'><td class="label">Source</td><td class="data"><a href='https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/ea-scripts/Excalidraw%20Writing%20Machine.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">Creates a hierarchical Markdown document out of a visual layout of an article that can be fed to Templater and converted into an article using AI for Templater.<br>Watch this video to understand how the script is intended to work:<br><a href="https://www.youtube.com/watch?v=zvRpCOZAUSs" target="_blank"><img src ="https://i.ytimg.com/vi/zvRpCOZAUSs/maxresdefault.jpg" style="width:400px;"></a><br>You can download the sample Obsidian Templater file from <a href="https://gist.github.com/zsviczian/bf49d4b2d401f5749aaf8c2fa8a513d9">here</a>. You can download the demo PDF document showcased in the video from <a href="https://zsviczian.github.io/DemoArticle-AtomicHabits.pdf">here</a>.</td></tr></table>
## Full-Year Calendar Generator
```excalidraw-script-install
@@ -437,7 +440,7 @@ https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/GPT-Draw-a-UI.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/GPT-Draw-a-UI.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">This script was discontinued in favor of ExcaliAI. Draw a UI and let GPT create the code for you.<br><iframe width="400" height="225" src="https://www.youtube.com/embed/y3kHl_6Ll4w" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-draw-a-ui.jpg'></td></tr></table>
<table><tr valign='top'><td class="label">Author</td><td class="data"><a href='https://github.com/zsviczian'>@zsviczian</a></td></tr><tr valign='top'><td class="label">Source</td><td class="data"><a href='https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/ea-scripts/GPT-Draw-a-UI.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">This script was discontinued in favor of ExcaliAI. Draw a UI and let GPT create the code for you.<br><a href="https://www.youtube.com/watch?v=y3kHl_6Ll4w" target="_blank"><img src ="https://i.ytimg.com/vi/y3kHl_6Ll4w/maxresdefault.jpg" style="width:400px;"></a><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-draw-a-ui.jpg'></td></tr></table>
## Image Occlusion
```excalidraw-script-install
@@ -457,6 +460,18 @@ 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/Lighten%20background%20color.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">This script lightens the background color of the selected element by 2% at a time. You can use this script several times until you are satisfied. It is recommended to set a shortcut key for this script so that you can quickly try to DARKEN and LIGHTEN the color effect.In contrast to the `Modify background color opacity` script, the advantage is that the background color of the element is not affected by the canvas color, and the color value does not appear in a strange rgba() form.<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/darken-lighten-background-color.png'></td></tr></table>
## Linear Calendar Generator
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Linear%20Calendar%20Generator.md
```
<table><tr valign='top'><td class="label">Author</td><td class="data"><a href='https://github.com/iwanhoogendoorn'>@iwanhoogendoorn</a></td></tr><tr valign='top'><td class="label">Source</td><td class="data"><a href='https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/ea-scripts/Linear%20Calendar%20Generator.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">Generates a complete calendar for a specified year.<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-Linear-Calendar-Generator.jpg'></td></tr></table>
## Mindmap Builder
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Mindmap%20Builder.md
```
<table><tr valign='top'><td class="label">Author</td><td class="data"><a href='https://github.com/zsviczian'>@zsviczian</a></td></tr><tr valign='top'><td class="label">Source</td><td class="data"><a href='https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/ea-scripts/Mindmap%20Builder.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">Rapid mind mapping workflow driven by keyboard shortcuts: add sibling/child nodes, auto-layout and branch styling, quick navigation, optional recursive grouping, and Markdown copy/paste import/export for bullet-list sync.<br><a href="https://www.youtube.com/watch?v=qY66yoobaX4" target="_blank"><img src ="https://i.ytimg.com/vi/qY66yoobaX4/maxresdefault.jpg" style="width:400px;"></a><br><a href='https://youtu.be/qY66yoobaX4' target='_blank'>Link to video on YouTube</a><br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-mindmap-builder.png'></td></tr></table>
## Mindmap connector
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Mindmap%20connector.md
@@ -505,13 +520,13 @@ https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea
```
<table><tr valign='top'><td class="label">Author</td><td class="data"><a href='https://github.com/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/Palm%20Guard.md'>File on GitHub</a></td></tr>
<tr valign='top'><td class="label">Description</td><td class="data">Mobile & desktop palm‑rejection and distraction‑free drawing mode: optionally enters fullscreen, hides ALL Excalidraw UI chrome (top toolbar, side / bottom bars, plugin panels) for a clean / zen / immersive / kiosk / focus mode canvas. Provides a tiny draggable micro toolbar (toggle visibility + exit) so you gain maximum drawing area while preventing accidental palm taps. Uses the hotkey you assign in Obsidian’s Hotkey settings for this script to instantly show / hide controls (if no hotkey is set, use the on‑screen toggle). Ideal for stylus sketching, presentations, screen recording, split‑view space saving, or anyone searching for: palm rejection, hide toolbar, hide UI controls, clean mode, distraction free Excalidraw.<br><iframe width="400" height="225" src="https://www.youtube.com/embed/A_udjVjgWN0" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe><br><a href='https://youtu.be/A_udjVjgWN0' target='_blank'>Link to video on YouTube</a></td></tr></table>
<tr valign='top'><td class="label">Description</td><td class="data">Mobile & desktop palm‑rejection and distraction‑free drawing mode: optionally enters fullscreen, hides ALL Excalidraw UI chrome (top toolbar, side / bottom bars, plugin panels) for a clean / zen / immersive / kiosk / focus mode canvas. Provides a tiny draggable micro toolbar (toggle visibility + exit) so you gain maximum drawing area while preventing accidental palm taps. Uses the hotkey you assign in Obsidian’s Hotkey settings for this script to instantly show / hide controls (if no hotkey is set, use the on‑screen toggle). Ideal for stylus sketching, presentations, screen recording, split‑view space saving, or anyone searching for: palm rejection, hide toolbar, hide UI controls, clean mode, distraction free Excalidraw.<br><a href="https://www.youtube.com/watch?v=A_udjVjgWN0" target="_blank"><img src ="https://i.ytimg.com/vi/A_udjVjgWN0/maxresdefault.jpg" style="width:400px;"></a><br><a href='https://youtu.be/A_udjVjgWN0' target='_blank'>Link to video on YouTube</a></td></tr></table>
## PDF Page Text to Clipboard
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/PDF%20Page%20Text%20to%20Clipboard.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/PDF%20Page%20Text%20to%20Clipboard.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">Copies the text from the selected PDF page on the Excalidraw canvas to the clipboard.<br><iframe width="400" height="225" src="https://www.youtube.com/embed/Kwt_8WdOUT4" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe><br><a href='https://youtu.be/Kwt_8WdOUT4' target='_blank'>Link to video on YouTube</a></td></tr></table>
<table><tr valign='top'><td class="label">Author</td><td class="data"><a href='https://github.com/zsviczian'>@zsviczian</a></td></tr><tr valign='top'><td class="label">Source</td><td class="data"><a href='https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/ea-scripts/PDF%20Page%20Text%20to%20Clipboard.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">Copies the text from the selected PDF page on the Excalidraw canvas to the clipboard.<br><a href="https://www.youtube.com/watch?v=Kwt_8WdOUT4" target="_blank"><img src ="https://i.ytimg.com/vi/Kwt_8WdOUT4/maxresdefault.jpg" style="width:400px;"></a><br><a href='https://youtu.be/Kwt_8WdOUT4' target='_blank'>Link to video on YouTube</a></td></tr></table>
## Relative Font Size Cycle
```excalidraw-script-install
@@ -547,7 +562,7 @@ https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Scribble%20Helper.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/Scribble%20Helper.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">iOS scribble helper for better handwriting experience with text elements. If no elements are selected then the creates a text element at pointer position and you can use the edit box to modify the text with scribble. If a text element is selected then opens the input prompt where you can modify this text with scribble.<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-scribble-helper.jpg'><br><iframe width="560" height="315" src="https://www.youtube.com/embed/BvYkOaly-QM" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></td></tr></table>
<table><tr valign='top'><td class="label">Author</td><td class="data"><a href='https://github.com/zsviczian'>@zsviczian</a></td></tr><tr valign='top'><td class="label">Source</td><td class="data"><a href='https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/ea-scripts/Scribble%20Helper.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">iOS scribble helper for better handwriting experience with text elements. If no elements are selected then the creates a text element at pointer position and you can use the edit box to modify the text with scribble. If a text element is selected then opens the input prompt where you can modify this text with scribble.<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-scribble-helper.jpg'><br><a href="https://www.youtube.com/watch?v=BvYkOaly-QM" target="_blank"><img src ="https://i.ytimg.com/vi/BvYkOaly-QM/maxresdefault.jpg" style="width:560px;"></a></td></tr></table>
## Select Elements of Type
```excalidraw-script-install
@@ -615,14 +630,14 @@ https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Shade%20Master.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/Shade%20Master.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">You can modify the colors of SVG images, embedded files, and Excalidraw elements in a drawing by changing Hue, Saturation, Lightness and Transparency; and if only a single SVG or nested Excalidraw drawing is selected, then you can remap image colors.<br><iframe width="560" height="315" src="https://www.youtube.com/embed/ISuORbVKyhQ" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></td></tr></table>
<table><tr valign='top'><td class="label">Author</td><td class="data"><a href='https://github.com/zsviczian'>@zsviczian</a></td></tr><tr valign='top'><td class="label">Source</td><td class="data"><a href='https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/ea-scripts/Shade%20Master.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">You can modify the colors of SVG images, embedded files, and Excalidraw elements in a drawing by changing Hue, Saturation, Lightness and Transparency; and if only a single SVG or nested Excalidraw drawing is selected, then you can remap image colors.<br><a href="https://www.youtube.com/watch?v=ISuORbVKyhQ" target="_blank"><img src ="https://i.ytimg.com/vi/ISuORbVKyhQ/maxresdefault.jpg" style="width:560px;"></a></td></tr></table>
## Slideshow
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Slideshow.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/Slideshow.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">The script will convert your drawing into a slideshow presentation.<br><iframe width="560" height="315" src="https://www.youtube.com/embed/JwgtCrIVeEU" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></td></tr></table>
<table><tr valign='top'><td class="label">Author</td><td class="data"><a href='https://github.com/zsviczian'>@zsviczian</a></td></tr><tr valign='top'><td class="label">Source</td><td class="data"><a href='https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/ea-scripts/Slideshow.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">The script will convert your drawing into a slideshow presentation.<br><a href="https://www.youtube.com/watch?v=JwgtCrIVeEU" target="_blank"><img src ="https://i.ytimg.com/vi/JwgtCrIVeEU/maxresdefault.jpg" style="width:560px;"></a></td></tr></table>
## Split Ellipse
```excalidraw-script-install
@@ -676,7 +691,7 @@ https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Printable%20Layout%20Wizard.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/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><iframe width="400" height="225" src="https://www.youtube.com/embed/29EWeglRm7s" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe><br><a href='https://youtu.be/29EWeglRm7s' target='_blank'>Link to video on YouTube</a><br><iframe width="400" height="225" src="https://www.youtube.com/embed/DqDnzCOoYMc" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe><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>
<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>
## Zoom to Fit Selected Elements
Binary file not shown.

After

Width:  |  Height:  |  Size: 344 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 76 KiB

+2 -2
View File
@@ -1,9 +1,9 @@
{
"id": "obsidian-excalidraw-plugin",
"name": "Excalidraw",
"version": "2.16.0",
"version": "2.19.1",
"minAppVersion": "1.5.7",
"description": "An Obsidian plugin to edit and view Excalidraw drawings",
"description": "Sketch Your Mind. An Obsidian plugin to edit and view Excalidraw drawings. Enter the world of 4D Visual PKM.",
"author": "Zsolt Viczian",
"authorUrl": "https://excalidraw-obsidian.online",
"isDesktopOnly": false
+3 -3
View File
@@ -1,12 +1,12 @@
{
"id": "obsidian-excalidraw-plugin",
"name": "Excalidraw",
"version": "2.16.0",
"version": "2.19.1",
"minAppVersion": "1.5.7",
"description": "An Obsidian plugin to edit and view Excalidraw drawings",
"description": "Sketch Your Mind. An Obsidian plugin to edit and view Excalidraw drawings. Enter the world of 4D Visual PKM.",
"author": "Zsolt Viczian",
"authorUrl": "https://excalidraw-obsidian.online",
"fundingUrl": "https://ko-fi.com/zsolt",
"helpUrl": "https://github.com/zsviczian/obsidian-excalidraw-plugin#readme",
"isDesktopOnly": false
}
}
+6165 -170
View File
File diff suppressed because it is too large. Load diff
+3 -3
View File
@@ -17,14 +17,14 @@
"build:all": "npm run build:mathjax && npm run build",
"dev:mathjax": "cd MathjaxToSVG && npm run dev",
"dev:all": "npm run dev:mathjax && npm run dev",
"doc": "node scripts/generate-script-library.js"
"doc": "npm run lib && node scripts/generate-script-library.js"
},
"keywords": [],
"author": "",
"license": "MIT",
"dependencies": {
"@popperjs/core": "^2.11.8",
"@zsviczian/excalidraw": "0.18.0-41",
"@zsviczian/excalidraw": "0.18.0-67",
"chroma-js": "^3.1.2",
"clsx": "^2.0.0",
"@zsviczian/colormaster": "^1.2.2",
@@ -74,7 +74,7 @@
"eslint-config-prettier": "^9.0.0",
"eslint-plugin-prettier": "^5.0.0",
"lz-string": "^1.5.0",
"obsidian": "^1.7.2",
"obsidian": "^1.10.0",
"prettier": "^3.0.1",
"rollup": "^2.70.1",
"rollup-plugin-copy": "^3.5.0",
+4 -2
View File
@@ -188,8 +188,10 @@ const BUILD_CONFIG = {
},
}),
postprocess([
[/React=require\("react"\),state=require\("@codemirror\/state"\),view=require\("@codemirror\/view"\)/,
`state=require("@codemirror/state"),view=require("@codemirror/view")` + packageString],
[
/(var[^;]*?),\s*React\s*=\s*require\(["']react["']\)([^;]*;)/,
(_, g1, g2) => `${g1}${g2}${packageString}`
],
]),
] : [
postprocess([ [/var React = require\('react'\);/, packageString] ]),
+567 -11
View File
@@ -1,16 +1,221 @@
/* eslint-disable no-console */
// to run: npm run doc
const fs = require('fs');
const path = require('path');
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 DIST_DIR = path.join(ROOT, 'dist');
const OUTPUT_FILE = path.join(DIST_DIR, 'Excalidraw Script Library.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 INTRO = `# Excalidraw Script Library
const AI_TRAINING_INTRO = `**ExcalidrawAutomate full library for LLM training**
This file is an automatically generated knowledge base intended for Retrieval Augmented Generation (RAG) and other AI-assisted workflows (e.g. NotebookLM or local embeddings tools).
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.
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.
#### **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.
* 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**
* **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 avalable on 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.
#### **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.
#### **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":{}}
\`\`\`
`;
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.
@@ -18,9 +223,9 @@ Its purpose:
- 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. Intro (this section)
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)
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()}
@@ -28,6 +233,36 @@ 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",
];
/**
* Returns true if content contains at least one line starting with ```
* and has an odd number of fences (unbalanced).
@@ -37,6 +272,259 @@ function needsClosingFence(content) {
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;
}
/**
* Build additional type defs used only in AI_TRAINING_OUT (e.g. obsidian.d.ts).
*/
function buildAdditionalTypeDefsMarkdown() {
const entries = ADDITIONAL_TYPE_DEFS_FOR_AI_TRAINING.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] Additional type def 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;
}
function main() {
console.log('[script-library] Generating Excalidraw Script Library...');
if (!fs.existsSync(EA_SCRIPTS_DIR)) {
@@ -47,11 +535,11 @@ function main() {
console.error('index-new.md not found:', INDEX_NEW);
process.exit(1);
}
if (!fs.existsSync(DIST_DIR)) {
fs.mkdirSync(DIST_DIR, { recursive: true });
if (!fs.existsSync(OUT_DIR)) {
fs.mkdirSync(OUT_DIR, { recursive: true });
}
let output = INTRO;
let output = SCRIPT_INTRO;
console.log('[script-library] Adding index-new.md');
const indexNewContent = fs.readFileSync(INDEX_NEW, 'utf8');
@@ -90,8 +578,76 @@ function main() {
}
}
fs.writeFileSync(OUTPUT_FILE, output, 'utf8');
console.log('[script-library] Wrote:', OUTPUT_FILE);
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 additionalTypeDefs = buildAdditionalTypeDefsMarkdown();
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' +
additionalTypeDefs +
'\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.');
}
+1 -1
View File
@@ -879,7 +879,7 @@ export const penIcon = (pen: PenStyle) => {
}
export const stringToSVG = (svg: string) => {
if(svg.match('class="skip"')) {
if(svg.match(/class=("|')[^"']*(lucide|skip)[^"']*("|')/)) {
return <div dangerouslySetInnerHTML={{__html: svg}}></div>
}
svg = svg
+4 -3
View File
@@ -86,7 +86,6 @@ export const obsidianToExcalidrawMap: { [key: string]: string } = {
export let {
sceneCoordsToViewportCoords,
viewportCoordsToSceneCoords,
determineFocusDistance,
intersectElementWithLine,
getCommonBoundingBox,
getMaximumGroups,
@@ -107,6 +106,7 @@ export let {
loadSceneFonts,
loadMermaid,
syncInvalidIndices,
getDefaultColorPalette,
} = excalidrawLib;
export function updateExcalidrawLib() {
@@ -120,7 +120,6 @@ export function updateExcalidrawLib() {
const requiredFunctions = [
'sceneCoordsToViewportCoords',
'viewportCoordsToSceneCoords',
'determineFocusDistance',
'intersectElementWithLine',
'getCommonBoundingBox',
'measureText',
@@ -138,7 +137,6 @@ export function updateExcalidrawLib() {
({
sceneCoordsToViewportCoords,
viewportCoordsToSceneCoords,
determineFocusDistance,
intersectElementWithLine,
getCommonBoundingBox,
getMaximumGroups,
@@ -159,6 +157,7 @@ export function updateExcalidrawLib() {
loadSceneFonts,
loadMermaid,
syncInvalidIndices,
getDefaultColorPalette,
} = excalidrawLib);
} catch (error) {
errorHandler.handleError(error, "updateExcalidrawLib", true);
@@ -249,6 +248,7 @@ export const FRONTMATTER_KEYS:{[key:string]: {name: string, type: string, depric
"export-padding": {name: "excalidraw-export-padding", type: "number"},
"export-pngscale": {name: "excalidraw-export-pngscale", type: "number"},
"export-embed-scene": {name: "excalidraw-export-embed-scene", type: "checkbox"},
"export-internal-links": {name: "excalidraw-export-internal-links", type: "checkbox"},
"link-prefix": {name: "excalidraw-link-prefix", type: "text"},
"url-prefix": {name: "excalidraw-url-prefix", type: "text"},
"link-brackets": {name: "excalidraw-link-brackets", type: "checkbox"},
@@ -301,6 +301,7 @@ export const CaptureUpdateAction = {
export const EMBEDDABLE_THEME_FRONTMATTER_VALUES = ["light", "dark", "auto", "dafault"];
export const VIEW_TYPE_EXCALIDRAW = "excalidraw";
export const VIEW_TYPE_SIDEPANEL = "excalidraw-sidepanel";
export const VIEW_TYPE_EXCALIDRAW_LOADING = "excalidraw-loading";
export const ICON_NAME = "excalidraw-icon";
export const MAX_COLORS = 5;
+56 -7
View File
@@ -17,6 +17,7 @@ import {
} from "obsidian";
import {
VIEW_TYPE_EXCALIDRAW,
VIEW_TYPE_SIDEPANEL,
EXCALIDRAW_ICON,
ICON_NAME,
SCRIPTENGINE_ICON,
@@ -66,7 +67,7 @@ import { ScriptEngine } from "../shared/Scripts";
import { hoverEvent, initializeMarkdownPostProcessor, markdownPostProcessor, legacyExcalidrawPopoverObserver } from "./managers/MarkdownPostProcessor";
import { FieldSuggester } from "../shared/Suggesters/FieldSuggester";
import { ReleaseNotes } from "../shared/Dialogs/ReleaseNotes";
import { Packages } from "../types/types";
import { DeviceType, Packages } from "../types/types";
import { PreviewImageType } from "../types/utilTypes";
import { emulateCTRLClickForLinks, linkClickModifierType, PaneTarget } from "../utils/modifierkeyHelper";
import { imageCache } from "../shared/ImageCache";
@@ -86,10 +87,15 @@ import { PluginFileManager } from "./managers/FileManager";
import { ObserverManager } from "./managers/ObserverManager";
import { PackageManager } from "./managers/PackageManager";
import ExcalidrawView from "../view/ExcalidrawView";
import { ExcalidrawSidepanelView } from "../view/sidepanel/Sidepanel";
import { CommandManager } from "./managers/CommandManager";
import { EventManager } from "./managers/EventManager";
import { UniversalInsertFileModal } from "src/shared/Dialogs/UniversalInsertFileModal";
import en from "src/lang/locale/en";
import { get } from "http";
import { getHighlightColor } from "src/utils/dynamicStyling";
import { InlineLinkSuggester } from "src/shared/Suggesters/InlineLinkSuggester";
import { KeyBlocker } from "src/types/excalidrawAutomateTypes";
declare const PLUGIN_VERSION:string;
declare const INITIAL_TIMESTAMP: number;
@@ -116,6 +122,7 @@ export default class ExcalidrawPlugin extends Plugin {
public settings: ExcalidrawSettings;
public activeExcalidrawView: ExcalidrawView = null;
public lastActiveExcalidrawFilePath: string = null;
public lastActiveExcalidrawLeafID: string = null;
public hover: { linkText: string; sourcePath: string } = {
linkText: null,
sourcePath: null,
@@ -279,6 +286,10 @@ export default class ExcalidrawPlugin extends Plugin {
}
},
);
this.registerView(
VIEW_TYPE_SIDEPANEL,
(leaf: WorkspaceLeaf) => new ExcalidrawSidepanelView(leaf, this),
);
//Compatibility mode with .excalidraw files
this.registerExtensions(["excalidraw"], VIEW_TYPE_EXCALIDRAW);
@@ -415,7 +426,7 @@ export default class ExcalidrawPlugin extends Plugin {
try {
this.isReady = true;
await switchToExcalidraw(this.app);
this.switchToExcalidarwAfterLoad();
this.switchToExcalidrawAfterLoad();
} catch (e) {
new Notice("Error switching views to Excalidraw", 6000);
console.error("Error switching views to Excalidraw", e);
@@ -558,7 +569,7 @@ export default class ExcalidrawPlugin extends Plugin {
let fontMetrics = f.extension.startsWith("woff") ? undefined : await getFontMetrics(fourthFontDataURL, "Local Font");
if (!fontMetrics) {
console.log("Font Metrics not found, using default");
//console.log("Font Metrics not found, using default");
fontMetrics = {
unitsPerEm: 1000,
ascender: 750,
@@ -620,8 +631,8 @@ export default class ExcalidrawPlugin extends Plugin {
/**
* Must be called after the workspace is ready
*/
private switchToExcalidarwAfterLoad() {
(process.env.NODE_ENV === 'development') && DEBUGGING && debug(this.switchToExcalidarwAfterLoad, `ExcalidrawPlugin.switchToExcalidarwAfterLoad`);
private switchToExcalidrawAfterLoad() {
(process.env.NODE_ENV === 'development') && DEBUGGING && debug(this.switchToExcalidrawAfterLoad, `ExcalidrawPlugin.switchToExcalidrawAfterLoad`);
let leaf: WorkspaceLeaf;
for (leaf of this.app.workspace.getLeavesOfType("markdown")) {
if ( leaf.view instanceof MarkdownView && this.isExcalidrawFile(leaf.view.file)) {
@@ -1153,6 +1164,7 @@ export default class ExcalidrawPlugin extends Plugin {
}
onunload() {
ExcalidrawSidepanelView.onPluginUnload(this);
const excalidrawViews = getExcalidrawViews(this.app);
excalidrawViews.forEach(({leaf}) => {
this.setMarkdownView(leaf);
@@ -1254,6 +1266,10 @@ export default class ExcalidrawPlugin extends Plugin {
await this.saveData(this.settings);
}
public async openSidepanel(reveal: boolean = true): Promise<ExcalidrawSidepanelView | null> {
return ExcalidrawSidepanelView.getOrCreate(this, reveal);
}
public getStencilLibrary(): {} {
(process.env.NODE_ENV === 'development') && DEBUGGING && debug(this.getStencilLibrary,`ExcalidrawPlugin.getStencilLibrary`);
if (
@@ -1265,10 +1281,14 @@ export default class ExcalidrawPlugin extends Plugin {
return JSON_parse(this.settings.library);
}
public setStencilLibrary(library: {}) {
public async setStencilLibrary(library: {}) {
(process.env.NODE_ENV === 'development') && DEBUGGING && debug(this.setStencilLibrary,`ExcalidrawPlugin.setStencilLibrary`, library);
this.settings.library = "deprecated";
if(JSON.stringify(this.settings.library2) === JSON.stringify(library)) {
return;
}
this.settings.library2 = library;
await this.saveSettings();
}
public triggerEmbedUpdates(filepath?: string) {
@@ -1482,4 +1502,33 @@ export default class ExcalidrawPlugin extends Plugin {
public getLabel(key: keyof typeof en): string {
return t(key);
}
}
public getObsidianDevice(): DeviceType {
return DEVICE;
}
public getHighlightColor(sceneBgColor: string, opacity: number = 1): string {
return getHighlightColor(this.ea, sceneBgColor, opacity);
}
/**
* Attaches an inline link suggester to the specified input element.
* @param inputEl The HTML input element to attach the suggester to.
* @param widthWrapper Optional HTML element to wrap the width of suggester element.
* @param containerEl Optional container element used as collision boundary.
* @param surpessPlaceholder Whether to suppress the placeholder text. Defaults to true.
* @returns A KeyBlocker instance for managing keyboard input.
*/
public attachInlineLinkSuggester(
inputEl: HTMLInputElement,
widthWrapper?: HTMLElement,
containerEl?: HTMLDivElement,
surpessPlaceholder: boolean = true
): KeyBlocker {
const getSourcePath = () => {
this.ea.setView();
return this.ea.targetView?.file?.path;
};
return new InlineLinkSuggester(this.app, this, inputEl, getSourcePath, widthWrapper, surpessPlaceholder, containerEl);
}
}
+33 -6
View File
@@ -70,6 +70,7 @@ import { carveOutImage, carveOutPDF, createImageCropperFile } from "../../utils/
import { showFrameSettings } from "../../shared/Dialogs/FrameSettings";
import { insertImageToView } from "../../utils/excalidrawViewUtils";
import ExcalidrawPlugin from "src/core/main";
import { UIModeSettings } from "src/shared/Dialogs/UIModeSettings";
declare const PLUGIN_VERSION:string;
@@ -399,6 +400,14 @@ export class CommandManager {
callback: ()=>this.plugin.exportLibrary(),
});
this.addCommand({
id: "excalidraw-open-sidepanel",
name: t("OPEN_SIDEPANEL"),
callback: () => {
void this.plugin.openSidepanel();
},
});
this.addCommand({
id: "excalidraw-open",
name: t("OPEN_EXISTING_NEW_PANE"),
@@ -987,12 +996,11 @@ export class CommandManager {
name: t("TOGGLE_LEFTHANDED_MODE"),
checkCallback: (checking: boolean) => {
if (checking) {
if(DEVICE.isMobile) return false;
if(this.app.workspace.getActiveViewOfType(ExcalidrawView)) {
const view = this.app.workspace.getActiveViewOfType(ExcalidrawView);
const api = view?.excalidrawAPI;
if(!api) return false;
const st = api.getAppState();
if(!st.trayModeEnabled) return false;
const api = view?.excalidrawAPI as ExcalidrawImperativeAPI;
if(!api.isTrayModeEnabled()) return false;
return true;
}
return false;
@@ -1012,6 +1020,24 @@ export class CommandManager {
},
});
this.addCommand({
id: "toggle-enable-context-menu",
name: t("TOGGLE_ENABLE_CONTEXT_MENU"),
checkCallback: (checking: boolean) => {
if (checking) {
if(this.app.workspace.getActiveViewOfType(ExcalidrawView)) {
const view = this.app.workspace.getActiveViewOfType(ExcalidrawView);
const api = view?.excalidrawAPI as ExcalidrawImperativeAPI;
return true;
}
return false;
}
const view = this.app.workspace.getActiveViewOfType(ExcalidrawView);
view.toggleEnableContextMenu();
return true;
},
});
this.addCommand({
id: "flip-image",
name: t("FLIP_IMAGE"),
@@ -1642,7 +1668,7 @@ export class CommandManager {
this.addCommand({
id: "tray-mode",
name: t("TRAY_MODE"),
name: t("UI_MODE"),
checkCallback: (checking: boolean) => {
if (checking) {
const view = this.app.workspace.getActiveViewOfType(ExcalidrawView);
@@ -1657,7 +1683,8 @@ export class CommandManager {
}
const view = this.app.workspace.getActiveViewOfType(ExcalidrawView);
if (view && view.excalidrawAPI) {
view.toggleTrayMode();
const uiModeSettings = new UIModeSettings(this.plugin);
uiModeSettings.open();
return true;
}
return false;
+15 -2
View File
@@ -53,6 +53,10 @@ export class EventManager {
window.clearTimeout(this.leafChangeTimeout);
this.leafChangeTimeout = null;
}
if(this.debunceActiveLeafChangeHandlerTimer) {
window.clearTimeout(this.debunceActiveLeafChangeHandlerTimer);
this.debunceActiveLeafChangeHandlerTimer = null;
}
this.removeEventLisnters.forEach((removeEventListener) =>
removeEventListener(),
);
@@ -189,6 +193,15 @@ export class EventManager {
this.plugin.lastPDFLeafID = leaf.id;
}
if (leaf.view && leaf.view.getViewType() === VIEW_TYPE_EXCALIDRAW) {
this.plugin.lastActiveExcalidrawLeafID = leaf.id;
} else {
const lastLeaf = this.app.workspace.getLeafById(this.plugin.lastActiveExcalidrawLeafID);
if(!lastLeaf || !(lastLeaf.view instanceof ExcalidrawView)) {
this.plugin.lastActiveExcalidrawLeafID = null;
}
}
if(this.leafChangeTimeout) {
window.clearTimeout(this.leafChangeTimeout);
}
@@ -242,7 +255,7 @@ export class EventManager {
if (previouslyActiveEV && previouslyActiveEV !== newActiveviewEV) {
if (previouslyActiveEV.leaf !== leaf) {
//if loading new view to same leaf then don't save. Excalidarw view will take care of saving anyway.
//if loading new view to same leaf then don't save. Excalidraw view will take care of saving anyway.
//avoid double saving
if(previouslyActiveEV?.isDirty() && !previouslyActiveEV.semaphores?.viewunload) {
await previouslyActiveEV.save(true); //this will update transclusions in the drawing
@@ -364,4 +377,4 @@ export class EventManager {
})
);
}
}
}
+3 -3
View File
@@ -562,9 +562,9 @@ export class PluginFileManager {
return;
}
const isExcalidarwFile = this.getExcalidrawFiles().has(file);
const isExcalidrawFile = this.getExcalidrawFiles().has(file);
this.updateFileCache(file, undefined, true);
if (!isExcalidarwFile) {
if (!isExcalidrawFile) {
return;
}
@@ -614,4 +614,4 @@ export class PluginFileManager {
}
};
}
}
+31 -4
View File
@@ -9,7 +9,6 @@ import {
import { DEVICE, RERENDER_EVENT } from "../../constants/constants";
import { EmbeddedFilesLoader } from "../../shared/EmbeddedFileLoader";
import { createPNG, createSVG } from "../../utils/excalidrawAutomateUtils";
import { ExportSettings } from "../../view/ExcalidrawView";
import ExcalidrawPlugin from "../main";
import {getIMGFilename,} from "../../utils/fileUtils";
import {
@@ -30,6 +29,7 @@ import { CustomMutationObserver, debug, DEBUGGING } from "../../utils/debugHelpe
import { getExcalidrawFileForwardLinks } from "../../utils/excalidrawViewUtils";
import { linkPrompt } from "../../shared/Dialogs/Prompt";
import { isHTMLElement } from "../../utils/typechecks";
import { ExportSettings } from "src/types/exportUtilTypes";
interface imgElementAttributes {
file?: TFile;
@@ -136,8 +136,17 @@ const _getPNG = async ({imgAttributes,filenameParts,theme,cacheReady,img,file,ex
if (!png) {
return null;
}
img.src = URL.createObjectURL(png);
cacheReady && imageCache.addImageToCache(cacheKey, img.src, png);
const blobUrl = URL.createObjectURL(png);
img.src = blobUrl;
// Revoke the ObjectURL after the image loads or fails to prevent memory leaks
if (!cacheReady) {
const cleanup = () => URL.revokeObjectURL(blobUrl);
img.addEventListener('load', cleanup, { once: true });
img.addEventListener('error', cleanup, { once: true });
}
cacheReady && imageCache.addImageToCache(cacheKey, blobUrl, png);
return img;
}
@@ -382,6 +391,14 @@ const addSVGToImgSrc = (img: HTMLImageElement, svg: SVGSVGElement, cacheReady: b
const blob = new Blob([svgString], { type: 'image/svg+xml' });
const blobUrl = URL.createObjectURL(blob);
img.setAttribute("src", blobUrl);
// Revoke the ObjectURL after the image loads or fails to prevent memory leaks
if (!cacheReady) {
const cleanup = () => URL.revokeObjectURL(blobUrl);
img.addEventListener('load', cleanup, { once: true });
img.addEventListener('error', cleanup, { once: true });
}
cacheReady && imageCache.addImageToCache(cacheKey, blobUrl, blob);
return img;
}
@@ -812,7 +829,10 @@ const tmpObsidianWYSIWYG = async (
}
if(warningEl) {
const dataHeading = warningEl.getAttr("data-heading");
const ref = dataHeading.match(/.+(\^(?:group=|area=|frame=|clippedframe=)[A-Za-z0-9_-]{8,21})/)?.[1];
const ref = dataHeading.match(/.+(\^(?:group=|area=|frame=|clippedframe=)[A-Za-z0-9_-]{8,21})/)?.[1]
// I am unsure if this works with all Obsidian translations,
// thus I kept the first with the fix ID length and have the frame name as fallback
?? dataHeading.match(/.+(\^(?:group=|area=|frame=|clippedframe=)[\p{L}\p{N}_ -]+)/u)?.[1];
if(ref) {
attr.fname = file.path + "#" +ref;
areaPreview = true;
@@ -836,6 +856,13 @@ const tmpObsidianWYSIWYG = async (
imgDiv.firstChild.style.maxHeight = "100%";
imgDiv.firstChild.style.maxWidth = null;
}
// Resolve the cyclic size dependency by applying a CSS width and/or height
if(!onCanvas && isHoverPopover && imgDiv.firstChild instanceof HTMLImageElement) {
internalEmbedDiv.style.setProperty("--popover-width", attr.fwidth + "px");
internalEmbedDiv.style.setProperty("--popover-height", attr.fheight + "px");
internalEmbedDiv.style.width = "var(--popover-width)";
internalEmbedDiv.style.height = "var(--popover-height)";
}
internalEmbedDiv.appendChild(imgDiv.firstChild);
return;
}
+60 -40
View File
@@ -29,6 +29,9 @@ export class ObserverManager {
if(this.settings.matchThemeTrigger) this.addThemeObserver();
this.experimentalFileTypeDisplayToggle(this.settings.experimentalFileType);
this.addModalContainerObserver();
if (this.app.isMobile) {
this.addWorkspaceDrawerObserver();
}
} catch (e) {
new Notice("Error adding ObserverManager", 6000);
console.error("Error adding ObserverManager", e);
@@ -41,19 +44,20 @@ export class ObserverManager {
this.removeModalContainerObserver();
if (this.workspaceDrawerLeftObserver) {
this.workspaceDrawerLeftObserver.disconnect();
this.workspaceDrawerLeftObserver = null;
}
if (this.workspaceDrawerRightObserver) {
this.workspaceDrawerRightObserver.disconnect();
this.workspaceDrawerRightObserver = null;
}
if (this.fileExplorerObserver) {
this.fileExplorerObserver.disconnect();
this.fileExplorerObserver = null;
}
if (this.workspaceDrawerRightObserver) {
this.workspaceDrawerRightObserver.disconnect();
}
if (this.workspaceDrawerLeftObserver) {
this.workspaceDrawerLeftObserver.disconnect();
}
this.plugin = null;
this.app = null;
this.activeViewDoc = null;
}
public addThemeObserver() {
@@ -218,44 +222,60 @@ export class ObserverManager {
private addWorkspaceDrawerObserver() {
//when the user activates the sliding drawers on Obsidian Mobile
const leftWorkspaceDrawer = document.querySelector(
".workspace-drawer.mod-left",
);
const rightWorkspaceDrawer = document.querySelector(
".workspace-drawer.mod-right",
);
if (leftWorkspaceDrawer || rightWorkspaceDrawer) {
const action = async (m: MutationRecord[]) => {
if (
m[0].oldValue !== "display: none;" ||
!this.plugin.activeExcalidrawView ||
!this.plugin.activeExcalidrawView?.isDirty()
) {
return;
if (this.workspaceDrawerLeftObserver || this.workspaceDrawerRightObserver) return;
const leftWorkspaceDrawer = document.querySelector<HTMLElement>(".workspace .workspace-drawer.mod-left");
const rightWorkspaceDrawer = document.querySelector<HTMLElement>(".workspace .workspace-drawer.mod-right");
if (!leftWorkspaceDrawer && !rightWorkspaceDrawer) return;
const parseDisplay = (value?: string | null): string => {
if (!value) return "";
const match = value.match(/display:\s*([^;]+);?/i);
return match ? match[1].trim() : "";
};
const action: MutationCallback = (mutations) => {
const activeView = this.plugin.activeExcalidrawView;
if (!activeView || activeView.semaphores?.viewunload) return;
for (const mutation of mutations) {
if (mutation.type !== "attributes" || mutation.attributeName !== "style") continue;
const target = mutation.target as HTMLElement;
const newDisplay = target.style.display;
const oldDisplay = parseDisplay(mutation.oldValue as string);
// Drawer finished closing: refresh to fix pointer offset after CSS transitions
if (newDisplay === "none" && oldDisplay !== "none") {
activeView.refresh();
continue;
}
this.plugin.activeExcalidrawView.save();
};
const options = {
attributeOldValue: true,
attributeFilter: ["style"],
};
if (leftWorkspaceDrawer) {
this.workspaceDrawerLeftObserver = DEBUGGING
? new CustomMutationObserver(action, "slidingDrawerLeftObserver")
: new MutationObserver(action);
this.workspaceDrawerLeftObserver.observe(leftWorkspaceDrawer, options);
// Drawer just opened after being hidden: keep the previous autosave safeguard
if (oldDisplay === "none" && newDisplay !== "none" && activeView.isDirty()) {
activeView.save();
}
}
};
if (rightWorkspaceDrawer) {
this.workspaceDrawerRightObserver = DEBUGGING
? new CustomMutationObserver(action, "slidingDrawerRightObserver")
: new MutationObserver(action);
this.workspaceDrawerRightObserver.observe(
rightWorkspaceDrawer,
options,
);
}
const options = {
attributes: true,
attributeOldValue: true,
attributeFilter: ["style"],
};
if (leftWorkspaceDrawer) {
this.workspaceDrawerLeftObserver = DEBUGGING
? new CustomMutationObserver(action, "slidingDrawerLeftObserver")
: new MutationObserver(action);
this.workspaceDrawerLeftObserver.observe(leftWorkspaceDrawer, options);
}
if (rightWorkspaceDrawer) {
this.workspaceDrawerRightObserver = DEBUGGING
? new CustomMutationObserver(action, "slidingDrawerRightObserver")
: new MutationObserver(action);
this.workspaceDrawerRightObserver.observe(rightWorkspaceDrawer, options);
}
}
}
+96 -72
View File
@@ -24,10 +24,8 @@ import {
} from "src/utils/fileUtils";
import { PENS } from "src/utils/pens";
import {
addIframe,
addYouTubeThumbnail,
fragWithHTML,
setLeftHandedMode,
setTrayMode,
} from "src/utils/utils";
import { imageCache } from "src/shared/ImageCache";
import { MultiOptionConfirmationPrompt } from "src/shared/Dialogs/Prompt";
@@ -46,8 +44,12 @@ import { getExcalidrawViews } from "src/utils/obsidianUtils";
import { createSliderWithText } from "src/utils/sliderUtils";
import { PDFExportSettingsComponent, PDFExportSettings } from "src/shared/Dialogs/PDFExportSettingsComponent";
import { ContentSearcher } from "src/shared/components/ContentSearcher";
import { UIMode, UIModeSettingsComponent } from "src/shared/Dialogs/UIModeSettingComponent";
import { ScriptSettingValue } from "src/types/excalidrawAutomateTypes";
export interface ExcalidrawSettings {
copyLinkToElemenetAnchorTo100: boolean;
copyFrameLinkByName: boolean;
disableDoubleClickTextEditing: boolean;
folder: string;
cropFolder: string;
@@ -88,6 +90,8 @@ export interface ExcalidrawSettings {
overrideObsidianFontSize: boolean;
dynamicStyling: DynamicStyle;
isLeftHanded: boolean;
desktopUIMode: UIMode;
tabletUIMode: UIMode;
iframeMatchExcalidrawTheme: boolean;
matchTheme: boolean;
matchThemeAlways: boolean;
@@ -114,6 +118,7 @@ export interface ExcalidrawSettings {
focusOnFileTab: boolean;
openInMainWorkspace: boolean;
showLinkBrackets: boolean;
syncElementLinkWithText: boolean;
linkPrefix: string;
urlPrefix: string;
parseTODO: boolean;
@@ -168,17 +173,9 @@ export interface ExcalidrawSettings {
mdCSS: string;
scriptEngineSettings: {
[key:string]: {
[key:string]: {
value?:string,
hidden?: boolean,
description?: string,
valueset?: string[],
height?: number,
}
[key:string]: ScriptSettingValue;
}
};
defaultTrayMode: boolean;
compactModeOnTablets: boolean;
previousRelease: string;
showReleaseNotes: boolean;
compareManifestToPluginVersion: boolean;
@@ -189,6 +186,7 @@ export interface ExcalidrawSettings {
taskboneEnabled: boolean;
taskboneAPIkey: string;
pinnedScripts: string[];
sidepanelTabs: string[];
customPens: PenStyle[];
numberOfCustomPens: number;
pdfScale: number;
@@ -214,6 +212,7 @@ export interface ExcalidrawSettings {
aiEnabled: boolean,
openAIAPIToken: string,
openAIDefaultTextModel: string,
openAIDefaultTextModelMaxTokens: number,
openAIDefaultVisionModel: string,
openAIDefaultImageGenerationModel: string,
openAIURL: string,
@@ -234,11 +233,14 @@ export interface ExcalidrawSettings {
modifierKeyOverrides: {modifiers: Modifier[], key: string}[];
showSplashscreen: boolean;
pdfSettings: PDFExportSettings;
disableContextMenu: boolean;
}
declare const PLUGIN_VERSION:string;
export const DEFAULT_SETTINGS: ExcalidrawSettings = {
copyLinkToElemenetAnchorTo100: false,
copyFrameLinkByName: false,
disableDoubleClickTextEditing: false,
folder: "Excalidraw",
cropFolder: "",
@@ -279,6 +281,8 @@ export const DEFAULT_SETTINGS: ExcalidrawSettings = {
overrideObsidianFontSize: false,
dynamicStyling: "colorful",
isLeftHanded: false,
desktopUIMode: "tray",
tabletUIMode: "compact",
iframeMatchExcalidrawTheme: true,
matchTheme: false,
matchThemeAlways: false,
@@ -311,7 +315,8 @@ export const DEFAULT_SETTINGS: ExcalidrawSettings = {
showSecondOrderLinks: true,
focusOnFileTab: true,
openInMainWorkspace: true,
showLinkBrackets: true,
showLinkBrackets: false,
syncElementLinkWithText: false,
allowCtrlClick: true,
forceWrap: false,
pageTransclusionCharLimit: 200,
@@ -363,8 +368,6 @@ export const DEFAULT_SETTINGS: ExcalidrawSettings = {
mdBorderColor: "Black",
mdCSS: "",
scriptEngineSettings: {},
defaultTrayMode: true,
compactModeOnTablets: true,
previousRelease: "0.0.0",
showReleaseNotes: true,
compareManifestToPluginVersion: true,
@@ -375,6 +378,7 @@ export const DEFAULT_SETTINGS: ExcalidrawSettings = {
taskboneEnabled: false,
taskboneAPIkey: "",
pinnedScripts: [],
sidepanelTabs: [],
customPens: [
{...PENS["default"]},
{...PENS["highlighter"]},
@@ -426,6 +430,7 @@ export const DEFAULT_SETTINGS: ExcalidrawSettings = {
aiEnabled: true,
openAIAPIToken: "",
openAIDefaultTextModel: "gpt-3.5-turbo-1106",
openAIDefaultTextModelMaxTokens: 4096,
openAIDefaultVisionModel: "gpt-4o",
openAIDefaultImageGenerationModel: "dall-e-3",
openAIURL: "https://api.openai.com/v1/chat/completions",
@@ -534,6 +539,7 @@ export const DEFAULT_SETTINGS: ExcalidrawSettings = {
alignment: "center",
margin: "normal",
},
disableContextMenu: false,
};
export class ExcalidrawSettingTab extends PluginSettingTab {
@@ -827,7 +833,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
this.applySettingsUpdate();
}),
);
addIframe(detailsEl, "jgUpYznHP9A",216);
addYouTubeThumbnail(detailsEl, "jgUpYznHP9A",216);
new Setting(detailsEl)
.setName(t("SCRIPT_FOLDER_NAME"))
@@ -1157,6 +1163,35 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
}),
);
new Setting(detailsEl)
.setName(t("AI_OPENAI_DEFAULT_MAX_TOKENS_NAME"))
.setDesc(fragWithHTML(t("AI_OPENAI_DEFAULT_MAX_TOKENS_DESC")))
.addText((text) =>
text
.setPlaceholder("e.g.: 4096")
.setValue(this.plugin.settings.openAIDefaultTextModelMaxTokens.toString())
.onChange(async (value) => {
const intVal = parseInt(value);
if (isNaN(intVal) && value !== "") {
text.setValue(this.plugin.settings.openAIDefaultTextModelMaxTokens.toString());
return;
}
if (value === "") {
this.plugin.settings.openAIDefaultTextModelMaxTokens = 4096;
text.setValue("4096");
this.applySettingsUpdate();
return;
}
if (intVal < 0) {
text.setValue(this.plugin.settings.openAIDefaultTextModelMaxTokens.toString());
return;
}
this.plugin.settings.openAIDefaultTextModelMaxTokens = intVal;
text.setValue(intVal.toString());
this.applySettingsUpdate();
}),
);
new Setting(detailsEl)
.setName(t("AI_OPENAI_DEFAULT_VISION_MODEL_NAME"))
.setDesc(fragWithHTML(t("AI_OPENAI_DEFAULT_VISION_MODEL_DESC")))
@@ -1218,6 +1253,18 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
this.applySettingsUpdate();
}),
);
new Setting(detailsEl)
.setName(t("DISABLE_CONTEXT_MENU_NAME"))
.setDesc(t("DISABLE_CONTEXT_MENU_DESC"))
.addToggle((toggle) =>
toggle
.setValue(!this.plugin.settings.disableContextMenu)
.onChange(async (value) => {
this.plugin.settings.disableContextMenu = !value;
this.applySettingsUpdate();
}),
);
const readingModeEl = new Setting(detailsEl)
.setName(t("SHOW_DRAWING_OR_MD_IN_READING_MODE_NAME"))
@@ -1250,49 +1297,13 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
cls: "excalidraw-setting-h3",
});
new Setting(detailsEl)
.setName(t("TRAY_MODE_NAME"))
.setDesc(fragWithHTML(t("ARIA_LABEL_TRAY_MODE")))
.addToggle((toggle) =>
toggle
.setValue(this.plugin.settings.defaultTrayMode)
.onChange((value) => {
this.plugin.settings.defaultTrayMode = value;
setTrayMode(this.app, this.plugin.settings);
this.applySettingsUpdate();
})
);
new Setting(detailsEl)
.setName(t("COMPACT_MODE_NAME"))
.setDesc(fragWithHTML(t("COMPACT_MODE_DESC")))
.addToggle((toggle) =>
toggle
.setValue(this.plugin.settings.compactModeOnTablets)
.onChange((value) => {
this.plugin.settings.compactModeOnTablets = value;
setTrayMode(this.app, this.plugin.settings);
this.applySettingsUpdate();
}),
);
new Setting(detailsEl)
.setName(t("LEFTHANDED_MODE_NAME"))
.setDesc(fragWithHTML(t("LEFTHANDED_MODE_DESC")))
.addToggle((toggle) =>
toggle
.setValue(this.plugin.settings.isLeftHanded)
.onChange(async (value) => {
this.plugin.settings.isLeftHanded = value;
//not clear why I need to do this. If I don't double apply the stylesheet changes
//then the style won't be applied in the popout windows
setLeftHandedMode(value);
setTimeout(()=>setLeftHandedMode(value));
this.applySettingsUpdate();
}),
);
addIframe(detailsEl, "H8Njp7ZXYag",999);
new UIModeSettingsComponent(
detailsEl,
this.plugin.settings,
this.app,
()=>this.applySettingsUpdate(),
).render();
addYouTubeThumbnail(detailsEl, "H8Njp7ZXYag",999);
detailsEl = displayDetailsEl.createEl("details");
detailsEl.createEl("summary", {
@@ -1339,7 +1350,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
this.applySettingsUpdate();
}),
);
addIframe(detailsEl, "fypDth_-8q0");
addYouTubeThumbnail(detailsEl, "fypDth_-8q0");
new Setting(detailsEl)
.setName(t("IFRAME_MATCH_THEME_NAME"))
@@ -1352,7 +1363,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
this.applySettingsUpdate(true);
}),
);
addIframe(detailsEl, "ICpoyMv6KSs");
addYouTubeThumbnail(detailsEl, "ICpoyMv6KSs");
new Setting(detailsEl)
.setName(t("MATCH_THEME_NAME"))
@@ -1443,7 +1454,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
this.applySettingsUpdate();
}),
);
addIframe(detailsEl, "rBarRfcSxNo",107);
addYouTubeThumbnail(detailsEl, "rBarRfcSxNo",107);
new Setting(detailsEl)
.setName(t("DEFAULT_WHEELZOOM_NAME"))
@@ -1806,6 +1817,18 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
(el) => (el.innerHTML = t("LINKS_DESC")),
);
new Setting(detailsEl)
.setName(t("ELEMENT_LINK_SYNC_NAME"))
.setDesc(fragWithHTML(t("ELEMENT_LINK_SYNC_DESC")))
.addToggle((toggle) =>
toggle
.setValue(this.plugin.settings.syncElementLinkWithText)
.onChange(async (value) => {
this.plugin.settings.syncElementLinkWithText = value;
this.applySettingsUpdate();
}),
);
new Setting(detailsEl)
.setName(t("SECOND_ORDER_LINKS_NAME"))
.setDesc(fragWithHTML(t("SECOND_ORDER_LINKS_DESC")))
@@ -1866,6 +1889,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
}),
);
new Setting(detailsEl)
.setName(t("LINK_PREFIX_NAME"))
.setDesc(fragWithHTML(t("LINK_PREFIX_DESC")))
@@ -2103,8 +2127,8 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
this.applySettingsUpdate();
})
);
addIframe(detailsEl, "yZQoJg2RCKI");
addIframe(detailsEl, "opLd1SqaH_I",8);
addYouTubeThumbnail(detailsEl, "yZQoJg2RCKI");
addYouTubeThumbnail(detailsEl, "opLd1SqaH_I",8);
let dropdown: DropdownComponent;
let embedComment: Setting;
@@ -2263,7 +2287,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
text: t("EXPORT_SUBHEAD"),
cls: "excalidraw-setting-h3",
});
addIframe(detailsEl, "wTtaXmRJ7wg",171);
addYouTubeThumbnail(detailsEl, "wTtaXmRJ7wg",171);
const pdfExportEl = new Setting(detailsEl)
.setName(t("SHOW_DRAWING_OR_MD_IN_EXPORTPDF_NAME"))
@@ -2508,7 +2532,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
cls: "excalidraw-setting-h3",
});
addIframe(detailsEl, "nB4cOfn0xAs");
addYouTubeThumbnail(detailsEl, "nB4cOfn0xAs");
new Setting(detailsEl)
.setName(t("PDF_TO_IMAGE_SCALE_NAME"))
.setDesc(fragWithHTML(t("PDF_TO_IMAGE_SCALE_DESC")))
@@ -2554,7 +2578,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
new EmbeddalbeMDFileCustomDataSettingsComponent(
detailsEl,
this.plugin.settings.embeddableMarkdownDefaults,
this.applySettingsUpdate,
(val?:boolean) => this.applySettingsUpdate(val),
).render();
detailsEl = embedFilesDetailsEl.createEl("details");
@@ -2719,7 +2743,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
text: t("CUSTOM_PEN_HEAD"),
cls: "excalidraw-setting-h3",
});
addIframe(detailsEl, "OjNhjaH2KjI",69);
addYouTubeThumbnail(detailsEl, "OjNhjaH2KjI",69);
new Setting(detailsEl)
.setName(t("CUSTOM_PEN_NAME"))
.setDesc(t("CUSTOM_PEN_DESC"))
@@ -2761,7 +2785,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
text: t("CUSTOM_FONT_HEAD"),
cls: "excalidraw-setting-h3",
});
addIframe(detailsEl, "eKFmrSQhFA4");
addYouTubeThumbnail(detailsEl, "eKFmrSQhFA4");
new Setting(detailsEl)
.setName(t("ENABLE_FOURTH_FONT_NAME"))
.setDesc(fragWithHTML(t("ENABLE_FOURTH_FONT_DESC")))
@@ -2867,7 +2891,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
cls: "excalidraw-setting-h1",
});
addIframe(detailsEl, "r08wk-58DPk");
addYouTubeThumbnail(detailsEl, "r08wk-58DPk");
new Setting(detailsEl)
.setName(t("LATEX_DEFAULT_NAME"))
.setDesc(fragWithHTML(t("LATEX_DEFAULT_DESC")))
@@ -2965,7 +2989,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
detailsEl.createDiv( { text: t("TASKBONE_DESC"), cls: "setting-item-description" });
let taskboneAPIKeyText: TextComponent;
addIframe(detailsEl, "7gu4ETx7zro");
addYouTubeThumbnail(detailsEl, "7gu4ETx7zro");
new Setting(detailsEl)
.setName(t("TASKBONE_ENABLE_NAME"))
.setDesc(fragWithHTML(t("TASKBONE_ENABLE_DESC")))
@@ -3344,7 +3368,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
cls: "excalidraw-setting-h1",
});
addIframe(detailsEl, "H8Njp7ZXYag",52);
addYouTubeThumbnail(detailsEl, "H8Njp7ZXYag",52);
Object.keys(this.plugin.settings.scriptEngineSettings)
.filter((s) => scripts.contains(s))
.forEach((scriptName: string) => {
+42 -10
View File
@@ -37,6 +37,7 @@ 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",
OPEN_SIDEPANEL: "Open Excalidraw Sidepanel",
OPEN_EXISTING_NEW_PANE: "Open existing drawing - IN A NEW PANE",
OPEN_EXISTING_ACTIVE_PANE:
"Open existing drawing - IN THE CURRENT ACTIVE PANE",
@@ -63,6 +64,7 @@ export default {
MARKER_FRAME_TITLE_SHOW: "Show Marker Frame Titles",
MARKER_FRAME_TITLE_HIDE: "Hide Marker Frame Titles",
COPY_ELEMENT_LINK: "Copy [[link]] for selected element(s)",
FRAME_WITH_NAME: "Copy frame link by name",
COPY_DRAWING_LINK: "Copy ![[embed link]] for this drawing",
INSERT_LINK_TO_ELEMENT:
`Copy [[link]] for selected element to clipboard. ${labelCTRL()}+CLICK to copy 'group=' link. ${labelSHIFT()}+CLICK to copy an 'area=' link.`,
@@ -98,7 +100,7 @@ export default {
RUN_OCR: "OCR full drawing: Grab text from freedraw + images to clipboard and doc.props",
RERUN_OCR: "OCR full drawing re-run: Grab text from freedraw + images to clipboard and doc.props",
RUN_OCR_ELEMENTS: "OCR selected elements: Grab text from freedraw + images to clipboard",
TRAY_MODE: "Toggle property-panel tray-mode",
UI_MODE: "Toggle UI-mode",
SEARCH: "Search for text in drawing",
CROP_PAGE: "Crop and mask selected page",
CROP_IMAGE: "Crop and mask image",
@@ -110,11 +112,13 @@ export default {
TEMPORARY_ENABLE_AUTOSAVE: "Enable autosave",
FONTS_LOADED: "Excalidraw: CJK Fonts loaded",
FONTS_LOAD_ERROR: "Excalidraw: Could not find CJK Fonts in the assets folder\n",
TOGGLE_ENABLE_CONTEXT_MENU: "Toggle enable context menu (helpful on Mobile devices)",
//Prompt.ts
SELECT_LINK_TO_OPEN: "Select a link to open",
//ExcalidrawView.ts
ABOUT_LIBRARIES: "How to load libraries",
ERROR_CANT_READ_FILEPATH: "Error, can't read file path. Importing file instead",
NO_SEARCH_RESULT: "Didn't find a matching element in the drawing",
FORCE_SAVE_ABORTED: "Force Save aborted because saving is in progress",
@@ -137,9 +141,8 @@ export default {
"1) Please select your drawing using CTRL/CMD+A and make a copy with CTRL/CMD+C.\n" +
"2) Then create an empty drawing in a new pane by CTRL/CMD+clicking the Excalidraw ribbon button,\n" +
"3) and paste your work to the new document with CTRL/CMD+V.",
ARIA_LABEL_TRAY_MODE: "Tray-mode offers an alternative, more spacious canvas",
TRAY_TRAY_MODE: "Toggle tray-mode",
TOGGLE_COMPACT_MODE: "Toggle compact-mode",
ARIA_LABEL_TRAY_MODE: "You can choose from 3 different desktop and tablet UI modes: Full, Compact, and Tray. On Phones only the Phone mode is available.",
TRAY_TRAY_MODE: "Toggle UI-mode",
TRAY_SCRIPT_LIBRARY: "Script Library",
TRAY_SCRIPT_LIBRARY_ARIA: "Explore the Excalidraw Script Library",
TRAY_EXPORT: "Export Image...",
@@ -152,6 +155,7 @@ export default {
OPEN_AS_MD: "Open as Markdown",
EXPORT_IMAGE: `Export Image`,
OPEN_LINK: "Open selected text as link\n(SHIFT+CLICK to open in a new pane)",
EXCALIDRAW_SIDEPANEL: "Excalidraw Sidepanel",
EXPORT_EXCALIDRAW: "Export to an .Excalidraw file",
LINK_BUTTON_CLICK_NO_TEXT:
"Select an element that contains an internal or external link.\n",
@@ -215,6 +219,8 @@ export default {
//settings.ts
DISABLE_CONTEXT_MENU_NAME: "Disable Excalidraw context menu",
DISABLE_CONTEXT_MENU_DESC: "Disables the Excalidraw context menu. This can be useful on Mobile devices where the context menu pops up in unwanted moments.",
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.",
LINKS_BUGS_ARIA: "Report bugs and raise feature requsts on the plugin's GitHub page",
@@ -310,6 +316,9 @@ export default {
"The default AI model to use when generating text. This is a freetext field, so you can enter any valid OpenAI model name. " +
"Find out more about the available models on the <a href='https://platform.openai.com/docs/models'>OpenAI website</a>.",
AI_OPENAI_DEFAULT_MODEL_PLACEHOLDER: "Enter your default AI model here. e.g.: gpt-3.5-turbo-1106",
AI_OPENAI_DEFAULT_MAX_TOKENS_NAME: "Max tokens",
AI_OPENAI_DEFAULT_MAX_TOKENS_DESC:
"Maximum number of tokens to generate in the API response. Set to 0 to omit the max_tokens field (useful for models that don't support this parameter, such as GPT-5).",
AI_OPENAI_DEFAULT_IMAGE_MODEL_NAME: "Default Image Generation AI model",
AI_OPENAI_DEFAULT_IMAGE_MODEL_DESC:
"The default AI model to use when generating images. Image editing and variations are only supported by dall-e-2 at this time by OpenAI, " +
@@ -450,10 +459,20 @@ export default {
"Note: This setting does not affect the PDF export feature within Excalidraw itself.<br>" +
"See the other related setting for <a href='#"+TAG_MDREADINGMODE+"'>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: "Modes",
MODES_HEAD: "UI Modes",
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",
TABLET_UI_MODE_DESC: "Select the default UI mode for tablet devices.",
MODE_FULL: "Desktop-mode",
MODE_COMPACT: "Compact-mode",
MODE_TRAY: "Tray-mode",
TRAY_MODE_NAME: "Enable tray-mode",
COMPACT_MODE_NAME: "Compact-mode on Tablets",
COMPACT_MODE_DESC: "Overrides tray-mode on tablets, allowing the native Excalidraw compact-mode to be used instead.",
PREFER_COMPACT_MODE_DESKTOP_NAME: "Prefer compact-mode on Desktop",
PREFER_COMPACT_MODE_DESKTOP_DESC: "When toggling tray-mode on a desktop, if this option is enabled, Excalidraw will toggle between compact-mode and tray-mode. " +
"If this setting is off, it will toggle betweeen full-mode and tray-mode.",
COMPACT_MODE_NAME: "Prefer compact-mode on Tablets",
COMPACT_MODE_DESC: "This setting allows you to have a different default mode on tablets, then on desktops. You can default to compact mode on tablets, and to tray-mode on desktops with the help of this setting.",
HOTKEY_OVERRIDE_HEAD: "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 " +
@@ -493,8 +512,7 @@ export default {
"<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",
GRID_COLOR_NAME: "Grid color",
GRID_OPACITY_NAME: "Grid opacity",
GRID_OPACITY_DESC: "Grid opacity will also control the opacity of the binding box when binding an arrow to an element.<br>" +
"Set the opacity of the grid. 0 is transparent, 100 is opaque.",
GRID_OPACITY_DESC: "Sets the opacity of the grid. 0 is transparent, 100 is opaque.",
GRID_DIRECTION_NAME: "Grid direction",
GRID_DIRECTION_DESC: "The first toggle shows/hides the horizontal grid, the second toggle shows/hides the vertical grid.",
GRID_HORIZONTAL: "Render horizontal grid",
@@ -525,7 +543,8 @@ export default {
LONG_PRESS_MOBILE_NAME: "Long press to open mobile",
LONG_PRESS_MOBILE_DESC: "Long press delay in milliseconds to open an Excalidraw Drawing embedded in a Markdown file. ",
DOUBLE_CLICK_LINK_OPEN_VIEW_MODE: "Allow double-click to open links in view mode",
ELEMENT_LINK_SYNC_NAME: "Sync text-element link with text",
ELEMENT_LINK_SYNC_DESC: "When enabled, Excalidraw matches pre-2.19.0 behavior: the first link in the text body is always copied to the element link field. SVG/PNG exports only keep links when the element link field holds a single link (not links inside the text body). Turn this ON if you rely on text-body links and want the element link to always mirror the first one. Turn it OFF if you manage the element link separately: for metadata like tags, inline link ontologies, or multiple links, e.g., dataview-style notes like '(reminds me of:: [[link]]) #noteToSelf'.",
FOCUS_ON_EXISTING_TAB_NAME: "Focus on Existing Tab",
FOCUS_ON_EXISTING_TAB_DESC: "When opening a link, Excalidraw will focus on the existing tab if the file is already open. " +
"Enabling this setting overrides 'Reuse Adjacent Pane' when the file is already open except for the 'Open the back-of-the-note of the selected excalidraw image' command palette action.",
@@ -548,6 +567,12 @@ export default {
"In PREVIEW mode, when parsing Text Elements, place brackets around links. " +
"You can override this setting for a specific drawing by adding <code>"
}${FRONTMATTER_KEYS["link-brackets"].name}: true/false</code> to the file's frontmatter.`,
/*LINK_DETECTION_NAME: "Do not auto-create element link from text",
LINK_DETECTION_DESC: "By default, Excalidraw will automatically create an element link when you type or paste a valid " +
"[[Obsidian link]] or a (web link) into a Text Element. This link overrides whatever element link you may have set previously. " +
"Even if you delete the element link, if the text element contains a valid link, Excalidraw will recreate the element link. " +
"If you turn this setting on, Excalidraw will not auto-create element links from text. You can still manually set element links " +
`Links in the text will still be navigable when you ${labelCTRL()} + CLICK the element.`,*/
LINK_PREFIX_NAME: "Link prefix",
LINK_PREFIX_DESC: `${
"In PREVIEW mode, if the Text Element contains a link, precede the text with these characters. " +
@@ -1118,6 +1143,7 @@ export default {
EXPORTDIALOG_BACKGROUND: "Background",
EXPORTDIALOG_BACKGROUND_TRANSPARENT: "Transparent",
EXPORTDIALOG_BACKGROUND_USE_COLOR: "Use scene color",
EXPORTDIALOG_INCLUDE_INTERNAL_LINKS: "Export internal links to SVG/PDF?",
// Selection
EXPORTDIALOG_SELECTED_ELEMENTS: "Export",
EXPORTDIALOG_SELECTED_ALL: "Entire scene",
@@ -1230,4 +1256,10 @@ export default {
VERSION_MISMATCH_DISABLE_DESC: "You can re-enable this under: Settings → Excalidraw → Basic → Warn about incomplete plugin updates.",
VERSION_MISMATCH_REDOWNLOAD: "Re-download plugin",
VERSION_MISMATCH_IGNORE: "Ignore",
//InlineLinkSuggester.ts
INLINE_HINT: "Type [[ to search and insert a link",
//SuggestionModal.ts
SUGGESTION_NOMATCH: "No matches found",
};
+23
View File
@@ -139,6 +139,7 @@ export default {
"3) y pega tu trabajo en el nuevo documento con CTRL/CMD+V.",
ARIA_LABEL_TRAY_MODE: "El modo bandeja ofrece un lienzo alternativo y más espacioso",
TRAY_TRAY_MODE: "Activar/desactivar modo bandeja",
TOGGLE_COMPACT_MODE: "Alternar modo compacto",
TRAY_SCRIPT_LIBRARY: "Biblioteca de scripts",
TRAY_SCRIPT_LIBRARY_ARIA: "Explorar la biblioteca de scripts de Excalidraw",
TRAY_EXPORT: "Exportar imagen...",
@@ -234,6 +235,8 @@ export default {
RELEASE_NOTES_DESC:
"<b><u>Activado:</u></b> Muestra las notas de la versión cada vez que actualices Excalidraw a una versión más reciente.<br>" +
"<b><u>Desactivado:</u></b> Modo silencioso. Aún puedes leer las notas de la versión en <a href='https://github.com/zsviczian/obsidian-excalidraw-plugin/releases'>GitHub</a>.",
WARN_ON_MANIFEST_MISMATCH_NAME: "Advertir sobre actualizaciones de complementos incompletos",
WARN_ON_MANIFEST_MISMATCH_DESC: "Comprueba que el ejecutable de Excalidraw instalado coincida con la versión mostrada en la lista de complementos de Obsidian. Si no coinciden (a menudo después de una sincronización parcial), verás una advertencia y podrás actualizar. Desactívalo para dejar de comprobar.",
NEWVERSION_NOTIFICATION_NAME: "Notificación de Actualización del Complemento",
NEWVERSION_NOTIFICATION_DESC:
"<b><u>Activado:</u></b> Muestra una notificación cuando hay una nueva versión del complemento disponible.<br>" +
@@ -307,6 +310,9 @@ export default {
"El modelo de IA predeterminado para usar al generar texto. Este es un campo de texto libre, así que puedes ingresar cualquier nombre de modelo de OpenAI válido. " +
"Encuentra más información sobre los modelos disponibles en el sitio web de OpenAI: <a href='https://platform.openai.com/docs/models'></a>.",
AI_OPENAI_DEFAULT_MODEL_PLACEHOLDER: "Ingresa aquí tu modelo de IA predeterminado. Ej.: gpt-3.5-turbo-1106",
AI_OPENAI_DEFAULT_MAX_TOKENS_NAME: "Tokens máximos",
AI_OPENAI_DEFAULT_MAX_TOKENS_DESC:
"Número máximo de tokens a generar en la respuesta de la API. Establece en 0 para omitir el campo max_tokens (útil para modelos que no admiten este parámetro, como GPT-5).",
AI_OPENAI_DEFAULT_IMAGE_MODEL_NAME: "Modelo de IA predeterminado para generación de imágenes",
AI_OPENAI_DEFAULT_IMAGE_MODEL_DESC:
"El modelo de IA predeterminado para usar al generar imágenes. La edición y variaciones de imágenes solo son compatibles con Dall-E 2 en este momento por parte de OpenAI, " +
@@ -447,6 +453,10 @@ FILENAME_HEAD: "Nombre de archivo",
"Nota: Esta configuración no afecta la función de exportación a PDF dentro del propio Excalidraw.<br>" +
"Consulta la otra configuración relacionada para el <a href='#"+TAG_MDREADINGMODE+"'>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",
TRAY_MODE_NAME: "Habilitar modo de bandeja (tray-mode)",
COMPACT_MODE_NAME: "Modo compacto en tablets",
COMPACT_MODE_DESC: "Anula el modo de bandeja en tablets, permitiendo que se use en su lugar el modo compacto nativo de Excalidraw.",
HOTKEY_OVERRIDE_HEAD: "Anulaciones de atajos de teclado",
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, " +
@@ -1210,4 +1220,17 @@ FILENAME_HEAD: "Nombre de archivo",
//EmbeddableActionsMenu.tsx
BOOKMARK_PAGE: "Guardar posición actual en el documento",
CAPTURE_PAGE: "Capturar la página actual como imagen",
//VersionMismatch.ts
//ADVERTENCIA: No cambie las cadenas {VAL_RECORDED} y {VAL_ACTUAL}, ¡son reemplazadas por los valores de versión reales en tiempo de ejecución!
VERSION_MISMATCH_NOTICE: `La versión registrada por Obsidian es <b>{VAL_RECORDED}</b>, pero el código de Excalidraw instalado es <b>{VAL_ACTUAL}</b>.`,
VERSION_MISMATCH_HEADING: "Desajuste de versión de Excalidraw",
VERSION_MISMATCH_CAUSE: "Esto suele ocurrir después de una sincronización parcial (ej. Obsidian Sync Standard) donde archivos grandes (main.js > 5MB) no se sincronizaron, por lo que solo se actualizó <code>manifest.json</code> .",
VERSION_MISMATCH_OPTIONS: "Opciones:<br><b>1.</b> Vuelva a descargar el complemento (recomendado).<br><b>2.</b> Ignorar por ahora.",
VERSION_MISMATCH_NOTE: "Nota: Actualizar la información de la versión manualmente puede afectar a las herramientas que leen manifest.json directamente (ej. Plugin Update Tracker, BRAT) hasta una reinstalación completa.",
VERSION_MISMATCH_DISABLE_NAME: "Desactivar futuras advertencias de desajuste",
VERSION_MISMATCH_DISABLE_DESC: "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",
};
+3
View File
@@ -215,6 +215,9 @@ export default {
"Модель ИИ по умолчанию, используемая при генерации текста. Это поле свободного текста, поэтому вы можете ввести любое действительное имя модели OpenAI. " +
"Узнайте больше о доступных моделях на <a href='https://platform.openai.com/docs/models'>OpenAI сайте</a>.",
AI_OPENAI_DEFAULT_MODEL_PLACEHOLDER: "Введите здесь модель искусственного интеллекта по умолчанию, например: gpt-3.5-turbo-1106.",
AI_OPENAI_DEFAULT_MAX_TOKENS_NAME: "Максимальное количество токенов",
AI_OPENAI_DEFAULT_MAX_TOKENS_DESC:
"Максимальное количество токенов для генерации в ответе API. Установите значение 0, чтобы пропустить поле max_tokens (полезно для моделей, которые не поддерживают этот параметр, таких как GPT-5).",
AI_OPENAI_DEFAULT_IMAGE_MODEL_NAME: "Модель ИИ для генерации изображений по умолчанию",
AI_OPENAI_DEFAULT_IMAGE_MODEL_DESC:
"Модель ИИ по умолчанию, используемая при генерации изображений. Редактирование и изменение изображений поддерживается OpenAI только в dall-e-2, " +
+56 -24
View File
@@ -37,6 +37,7 @@ export default {
CONVERT_FILE_KEEP_EXT: "转换:*.excalidraw => *.excalidraw.md",
CONVERT_FILE_REPLACE_EXT: "转换:*.excalidraw => *.md (兼容 Logseq)",
DOWNLOAD_LIBRARY: "导出 stencil 库为 *.excalidrawlib 文件",
OPEN_SIDEPANEL: "打开 Excalidraw 侧边面板",
OPEN_EXISTING_NEW_PANE: "打开已有的绘图 - 于新面板",
OPEN_EXISTING_ACTIVE_PANE:
"打开已有的绘图 - 于当前面板",
@@ -63,6 +64,7 @@ export default {
MARKER_FRAME_TITLE_SHOW: "显示标记画框名称",
MARKER_FRAME_TITLE_HIDE: "隐藏标记画框名称",
COPY_ELEMENT_LINK: "复制所选元素的 [[file#^id]] 链接",
FRAME_WITH_NAME: "按名称复制画框链接",
COPY_DRAWING_LINK: "复制绘图的 ![[drawing]] 链接",
INSERT_LINK_TO_ELEMENT:
`单击=复制所选元素的 [[file#^id]] 链接\n${labelCTRL()}=复制元素所在分组为 [[file#^group=id]] 链接\n${labelSHIFT()}=复制所选元素所在区域为 [[file#^area=id]] 链接`,
@@ -86,7 +88,7 @@ export default {
INSERT_MD: "以图像形式嵌入 Markdown 文档到当前绘图中",
INSERT_PDF: "以图像形式嵌入 PDF 到当前绘图中",
INSERT_LAST_ACTIVE_PDF_PAGE_AS_IMAGE: "以图像形式嵌入最后激活的 PDF 页面",
UNIVERSAL_ADD_FILE: "以交互或图像形式嵌入文件",
UNIVERSAL_ADD_FILE: "嵌入文件 (Insert ANY file)",
INSERT_CARD: "插入“背景笔记”卡片",
CONVERT_CARD_TO_FILE: "将“背景笔记”卡片保存到文件",
ERROR_TRY_AGAIN: "请重试。",
@@ -98,7 +100,7 @@ export default {
RUN_OCR: "OCR 整个绘图:识别涂鸦和图片里的文本并复制到剪贴板和笔记属性中",
RERUN_OCR: "重新 OCR 整个绘图:识别涂鸦和图片里的文本并复制到剪贴板和笔记属性中",
RUN_OCR_ELEMENTS: "OCR 选中的元素:识别涂鸦和图片里的文本并复制到剪贴板",
TRAY_MODE: "绘图工具属性页:面板模式 ⟺ 托盘模式",
UI_MODE: "切换 UI 模式",
SEARCH: "搜索文本",
CROP_PAGE: "裁剪所选页面并添加蒙版",
CROP_IMAGE: "裁剪图片并添加蒙版",
@@ -110,11 +112,13 @@ export default {
TEMPORARY_ENABLE_AUTOSAVE: "启用自动保存功能",
FONTS_LOADED: "Excalidraw: CJK 字体已加载",
FONTS_LOAD_ERROR: "Excalidraw: 在资源文件夹下找不到 CJK 字体\n",
TOGGLE_ENABLE_CONTEXT_MENU: "切换是否启用上下文菜单(在移动设备上很有用)",
//Prompt.ts
SELECT_LINK_TO_OPEN: "选择要打开的链接",
//ExcalidrawView.ts
ABOUT_LIBRARIES: "如何加载素材库",
ERROR_CANT_READ_FILEPATH: "错误,无法读取文件路径。正在改为导入文件",
NO_SEARCH_RESULT: "在绘图中未找到匹配的元素",
FORCE_SAVE_ABORTED: "自动保存被中止,因为文件正在保存中",
@@ -137,9 +141,8 @@ export default {
"1) 使用 Ctrl/CMD+A 选择您的绘图,然后使用 Ctrl/CMD+C 进行复制。\n" +
"2) 然后在新窗格中,通过 Ctrl/CMD 点击 Excalidraw 功能区按钮创建一个空白绘图。\n" +
"3) 最后,使用 Ctrl/CMD+V 将您的作品粘贴到新文件中。",
ARIA_LABEL_TRAY_MODE: "托盘模式提供更宽敞的绘图空间",
TRAY_TRAY_MODE: "切换托盘模式",
TOGGLE_COMPACT_MODE: "切换紧凑模式",
ARIA_LABEL_TRAY_MODE: "切换 3 种 UI 模式:完整模式(桌面端)、紧凑模式、托盘模式。手机端只有手机端模式。",
TRAY_TRAY_MODE: "切换 UI 模式",
TRAY_SCRIPT_LIBRARY: "脚本库",
TRAY_SCRIPT_LIBRARY_ARIA: "浏览 Excalidraw 脚本库",
TRAY_EXPORT: "导出绘图…",
@@ -152,6 +155,7 @@ export default {
OPEN_AS_MD: "打开为 Markdown",
EXPORT_IMAGE: `导出为图片`,
OPEN_LINK: "打开所选元素里的链接 \n(按住 Shift 在新面板打开)",
EXCALIDRAW_SIDEPANEL: "Excalidraw 侧边面板",
EXPORT_EXCALIDRAW: "导出为 .excalidraw 文件(旧版绘图文件格式)",
LINK_BUTTON_CLICK_NO_TEXT:
"请选择一个包含内部或外部链接的元素。\n",
@@ -169,7 +173,7 @@ export default {
COMPATIBILITY_MODE:
"*.excalidraw 是兼容旧版的绘图文件格式。需要转换为新格式才能解锁本插件的全部功能。",
CONVERT_FILE: "转换为新格式",
BACKUP_AVAILABLE: "加载绘图文件时出错,可能是由于 Obsidian 在上次保存时意外退出了(手机上更容易发生这种意外)。<br><br><b>好消息:</b>这台设备上存在备份。您是否想要恢复本设备上的备份?<br><br>(我建议您先尝试在最近使用过的其他设备上打开该绘图,以检查是否有更新的备份。)",
BACKUP_AVAILABLE: "加载绘图文件时出错,可能是由于 Obsidian 在上次保存时意外退出了(移动设备上更容易发生这种意外)。<br><br><b>好消息:</b>这台设备上存在备份。您是否想要恢复本设备上的备份?<br><br>(我建议您先尝试在最近使用过的其他设备上打开该绘图,以检查是否有更新的备份。)",
BACKUP_RESTORED: "已恢复备份",
BACKUP_SAVE_AS_FILE: "此绘图为空。但有一个非空的备份可用。您想将其恢复为新文件并在新标签页中打开吗?",
BACKUP_SAVE: "恢复",
@@ -215,6 +219,8 @@ export default {
//settings.ts
DISABLE_CONTEXT_MENU_NAME: "禁用 Excalidraw 上下文菜单",
DISABLE_CONTEXT_MENU_DESC: "禁用 Excalidraw 的上下文菜单。这在移动设备上很有用,因为上下文菜单有时会在不需要的时候弹出。",
NOTEBOOKLM_LINK_ARIA: "向 NotebookLM 咨询有关插件的帮助。此模型已预加载了我所有的视频转录稿、发布说明和其他帮助内容。与 NotebookLM 聊天,浏览我的 250+ 视频和 Excalidraw 文件。",
NOTEBOOKLM_LINK_TEXT: "学习插件。访问 NotebookLM 知识库。",
LINKS_BUGS_ARIA: "在插件的 GitHub 页面报告错误和提交功能请求",
@@ -228,8 +234,8 @@ export default {
LINKS_VTW: "加入研讨会",
LINKS_BOOK_ARIA: "阅读我的视觉思维著作《Sketch Your Mind》",
LINKS_BOOK: "阅读书籍",
LINKS_WIKI: "插件 Wiki",
LINKS_WIKI_ARIA: "浏览 Excalidraw 插件 Wiki",
LINKS_WIKI: "插件维基",
LINKS_WIKI_ARIA: "浏览 Excalidraw 插件维基",
RELEASE_NOTES_NAME: "显示更新说明",
RELEASE_NOTES_DESC:
@@ -310,6 +316,9 @@ export default {
"使用哪个 AI 模型来生成文本。请填写有效的 OpenAI 模型名称。" +
"您可访问 <a href='https://platform.openai.com/docs/models'>OpenAI 网站</a> 了解更多模型信息。",
AI_OPENAI_DEFAULT_MODEL_PLACEHOLDER: "gpt-3.5-turbo-1106",
AI_OPENAI_DEFAULT_MAX_TOKENS_NAME: "最大 token 数",
AI_OPENAI_DEFAULT_MAX_TOKENS_DESC:
"API 响应中生成的最大 token 数。设置为 0 以忽略 max_tokens 字段(适用于不支持该参数的模型,如 GPT-5)。",
AI_OPENAI_DEFAULT_IMAGE_MODEL_NAME: "默认的图片 AI 模型",
AI_OPENAI_DEFAULT_IMAGE_MODEL_DESC:
"使用哪个 AI 模型来生成图片。图生图会强制使用 dall-e-2 模型," +
@@ -450,10 +459,20 @@ export default {
"注意:该项不会影响 Excalidraw 本身的 PDF 导出功能。<br>" +
"请参阅下方 <a href='#"+TAG_PDFEXPORT+"'>PDF 导出设置</a>。<br>" +
"⚠️ 关闭并重新打开 Excalidraw/Markdown 文件后生效。",
MODES_HEAD: "模式",
MODES_HEAD: "UI 模式",
DESKTOP_UI_MODE_NAME: "桌面端偏好模式",
DESKTOP_UI_MODE_DESC: "桌面端设备默认 UI 模式。",
TABLET_UI_MODE_NAME: "平板端偏好模式",
TABLET_UI_MODE_DESC: "平板端设备默认 UI 模式。",
MODE_FULL: "Desktop-mode",
MODE_COMPACT: "Compact-mode",
MODE_TRAY: "Tray-mode",
TRAY_MODE_NAME: "启用托盘模式",
COMPACT_MODE_NAME: "平板上的紧凑模式",
COMPACT_MODE_DESC: "覆盖平板上的托盘模式,使用原生的 Excalidraw 紧凑模式。",
PREFER_COMPACT_MODE_DESKTOP_NAME: "在桌面端偏好紧凑模式",
PREFER_COMPACT_MODE_DESKTOP_DESC: "切换托盘模式时,开启该项,Excalidraw 将在紧凑模式与托盘模式之间切换。" +
"关闭该项,则在完整模式与托盘模式之间切换。",
COMPACT_MODE_NAME: "在平板端偏好紧凑模式",
COMPACT_MODE_DESC: "该项允许平板端和桌面端设置不同的默认模式。你可以在平板端默认使用紧凑模式,而在桌面端默认使用托盘模式。",
HOTKEY_OVERRIDE_HEAD: "热键覆盖",
HOTKEY_OVERRIDE_DESC: `一些 Excalidraw 的热键,如 ${labelCTRL()}+Enter 用于编辑文本,或 ${labelCTRL()}+K 用于创建元素链接,` +
"与 Obsidian 的热键设置冲突。您在下面添加的热键组合将在使用 Excalidraw 时覆盖 Obsidian 的热键设置," +
@@ -492,9 +511,8 @@ export default {
GRID_DYNAMIC_COLOR_DESC:
"<b>开启:</b>更改网格颜色以匹配绘图颜色。<br><b>关闭:</b>将以下颜色用作网格颜色。",
GRID_COLOR_NAME: "网格颜色",
GRID_OPACITY_NAME: "网格透明度",
GRID_OPACITY_DESC: "设置网格的透明度。还将控制将箭头绑定到元素时绑定框的透明度。" +
"0 全透明 ⟺ 100 不透明。",
GRID_OPACITY_NAME: "网格不透明度",
GRID_OPACITY_DESC: "设置网格的不透明度。0 全透明 ⟺ 100 不透明。",
GRID_DIRECTION_NAME: "网格方向",
GRID_DIRECTION_DESC: "第一个开关显示/隐藏水平网格,第二个开关显示/隐藏垂直网格。",
GRID_HORIZONTAL: "渲染水平网格",
@@ -525,7 +543,8 @@ export default {
LONG_PRESS_MOBILE_NAME: "长按打开(移动端)",
LONG_PRESS_MOBILE_DESC: "长按打开在 Markdown 文档中嵌入的 Excalidraw 绘图。单位:毫秒。",
DOUBLE_CLICK_LINK_OPEN_VIEW_MODE: "在查看模式下允许双击打开链接",
ELEMENT_LINK_SYNC_NAME: "文本元素同步正文链接",
ELEMENT_LINK_SYNC_DESC: "若开启,Excalidraw 将匹配 2.19.0 之前的行为:始终将正文第一个链接复制到元素链接字段。导出 SVG/PNG 仅在元素链接字段包含单个链接(不包括正文内的链接)时保留链接。开启:若你依赖正文链接并希望元素链接始终镜像第一个链接。关闭:若你独立管理元素链接,用于标签、行内链接本体等元数据、或多个链接,如 Dataview 风格的笔记 '(reminds me of:: [[link]]) #noteToSelf'。",
FOCUS_ON_EXISTING_TAB_NAME: "聚焦于当前标签页",
FOCUS_ON_EXISTING_TAB_DESC: "当打开一个链接时,如果该文件已经打开,Excalidraw 将会聚焦到现有的标签页上。" +
"启用该项时,如果文件已打开,将覆盖“在相邻面板中打开”,但“打开所选绘图的背景笔记”命令面板操作除外。",
@@ -548,6 +567,12 @@ export default {
"文本元素处于 PREVIEW 模式时,在内部链接的两侧显示中括号。<br>" +
"可为某个绘图单独设置该项,方法是在其 frontmatter 中添加如 <code>"
}${FRONTMATTER_KEYS["link-brackets"].name}: true/false</code> 的键值对。`,
/*LINK_DETECTION_NAME: "Do not auto-create element link from text",
LINK_DETECTION_DESC: "By default, Excalidraw will automatically create an element link when you type or paste a valid " +
"[[Obsidian link]] or a (web link) into a Text Element. This link overrides whatever element link you may have set previously. " +
"Even if you delete the element link, if the text element contains a valid link, Excalidraw will recreate the element link. " +
"If you turn this setting on, Excalidraw will not auto-create element links from text. You can still manually set element links " +
`Links in the text will still be navigable when you ${labelCTRL()} + CLICK the element.`,*/
LINK_PREFIX_NAME: "内部链接的前缀",
LINK_PREFIX_DESC: `${
"文本元素处于 PREVIEW 模式时,如果其中包含链接,则添加此前缀。<br>" +
@@ -569,9 +594,9 @@ export default {
`<b>开启:</b>在 Excalidraw <u>查看模式(View)</u>下,鼠标悬停在 <code>[[内部链接]]</code> 上即可预览;` +
"而在<u>普通模式(Normal)</u>下,鼠标悬停在内部链接右上角的蓝色标识上即可预览。<br>" +
`<b>关闭:</b>鼠标悬停在 <code>[[内部链接]]</code> 上,并且按住 ${labelCTRL()} 才能预览。`,
LINKOPACITY_NAME: "链接标识的透明度",
LINKOPACITY_NAME: "链接标识的不透明度",
LINKOPACITY_DESC:
"含有链接的元素,其右上角的链接标识的透明度。0 全透明 ⟺ 100 不透明。",
"含有链接的元素,其右上角的链接标识的不透明度。0 全透明 ⟺ 100 不透明。",
LINK_CTRL_CLICK_NAME:
`按住 ${labelCTRL()} 并点击含有 [[链接]] 或 [别名](链接) 的文本来打开链接`,
LINK_CTRL_CLICK_DESC:
@@ -766,7 +791,7 @@ export default {
PRESERVE_TEXT_AFTER_DRAWING_NAME: "兼容 Zotero 和脚注(footnotes)",
PRESERVE_TEXT_AFTER_DRAWING_DESC: "保留 Excalidraw Markdown 中 <code>## Drawing</code> 部分之后的文本内容。保存非常大的绘图时,这可能会造成微小的性能影响。",
DEBUGMODE_NAME: "开启 debug 信息",
DEBUGMODE_DESC: "我建议在启用/禁用该项后重新启动 Obsidian。这将在控制台中启用调试消息。这对于排查问题很有帮助。" +
DEBUGMODE_DESC: "我建议在启用/禁用该项后重新启动 Obsidian。这将在控制台中启用调试消息,有助于排查问题。" +
"如果您在使用插件时遇到问题,请启用该项,重现问题,并在 <a href='https://github.com/zsviczian/obsidian-excalidraw-plugin/issues'>GitHub</a> 上提出的问题中包含控制台日志。",
SLIDING_PANES_NAME: "支持 Sliding Panes 插件",
SLIDING_PANES_DESC:
@@ -907,9 +932,9 @@ export default {
SELECT_FILE_TO_LINK: "选择要以链接形式插入到当前绘图中的文件",
SELECT_COMMAND_PLACEHOLDER: "选择要插入到当前绘图中的命令",
SELECT_DRAWING: "选择要以图像形式嵌入到当前绘图中的图片或绘图文件",
TYPE_FILENAME: "键入要选择的绘图名称",
TYPE_FILENAME: "输入要选择的绘图名称",
SELECT_FILE_OR_TYPE_NEW:
"选择已有绘图,或者键入新绘图文件的名称,然后按回车。",
"选择已有绘图,或者输入新绘图文件的名称,然后按回车。",
SELECT_TO_EMBED: "选择要嵌入到当前 Markdown 文档中的绘图",
SELECT_MD: "选择要以图像形式嵌入到当前绘图中的 Markdown 文档",
SELECT_PDF: "选择要以图像形式嵌入到当前绘图中的 PDF",
@@ -1001,15 +1026,15 @@ export default {
ES_FILENAME_VISIBLE: "显示页内标题",
ES_BACKGROUND_HEAD: "背景色",
ES_BACKGROUND_DESC_INFO: "点击此处查看更多颜色信息",
ES_BACKGROUND_DESC_DETAIL: "背景色仅影响预览模式的 MD-Embeddable。在编辑模式,它会根据场景(通过笔记属性设置)或插件设置,遵循 Obsidian 的深色/浅色主题。背景色有两层:元素背景色(下层颜色)和上层颜色。选择“匹配元素”表示两层都遵循元素背景色。选择“匹配绘图”或特定背景色不会改变元素背景色。设置透明度(如 50%)会将绘图或选定的颜色与元素背景色混合。要移除元素背景色,可以在 Excalidraw 的元素属性编辑器中将元素背景色设置为透明,这样只有上层颜色生效。",
ES_BACKGROUND_DESC_DETAIL: "背景色仅影响预览模式的 MD-Embeddable。在编辑模式,它会根据场景(通过笔记属性设置)或插件设置,遵循 Obsidian 的深色/浅色主题。背景色有两层:元素背景色(下层颜色)和上层颜色。选择“匹配元素”表示两层都遵循元素背景色。选择“匹配绘图”或特定背景色不会改变元素背景色。设置不透明度(如 50%)会将绘图或选定的颜色与元素背景色混合。要移除元素背景色,可以在 Excalidraw 的元素属性编辑器中将元素背景色设置为透明,这样只有上层颜色生效。",
ES_BACKGROUND_MATCH_ELEMENT: "匹配元素背景色",
ES_BACKGROUND_MATCH_CANVAS: "匹配绘图背景色",
ES_BACKGROUND_COLOR: "背景色",
ES_BORDER_HEAD: "边框颜色",
ES_BORDER_COLOR: "边框颜色",
ES_BORDER_MATCH_ELEMENT: "匹配元素边框颜色",
ES_BACKGROUND_OPACITY: "背景透明度",
ES_BORDER_OPACITY: "边框透明度",
ES_BACKGROUND_OPACITY: "背景不透明度",
ES_BORDER_OPACITY: "边框不透明度",
ES_EMBEDDABLE_SETTINGS: "MD-Embeddable 设置",
ES_USE_OBSIDIAN_DEFAULTS: "使用 Obsidian 默认设置",
ES_ZOOM_100_RELATIVE_DESC: "使元素的缩放等级等于当前绘图的缩放等级",
@@ -1118,6 +1143,7 @@ export default {
EXPORTDIALOG_BACKGROUND: "背景",
EXPORTDIALOG_BACKGROUND_TRANSPARENT: "透明",
EXPORTDIALOG_BACKGROUND_USE_COLOR: "使用场景颜色",
EXPORTDIALOG_INCLUDE_INTERNAL_LINKS: "导出内部链接为 SVG/PDF?",
// Selection
EXPORTDIALOG_SELECTED_ELEMENTS: "导出",
EXPORTDIALOG_SELECTED_ALL: "整个场景",
@@ -1192,7 +1218,7 @@ export default {
UIFM_TITLE: "从仓库中嵌入文件",
UIFM_SECTION_HEAD: "选择章节标题",
UIFM_ANCHOR: "锚定为原始大小的 100%",
UIFM_ANCHOR_DESC: "这是一个专业功能,请在了解其作用的情况下再使用。启用后,即使你在 Excalidraw 中调整了导入图像的大小,下次打开绘图时,该图像仍会恢复为原始大小的 100%。这在将一个独立的 Excalidraw 点子嵌入到另一份笔记中,并希望保持文字和图标的相对尺寸时非常有用。",
UIFM_ANCHOR_DESC: "这是一个专业功能,请在了解其作用的情况下再使用。启用后,即使你在 Excalidraw 中调整了导入图像的大小,下次打开绘图时,该图像仍会恢复为原始大小的 100%。当你将一个独立的 Excalidraw 点子嵌入到另一份笔记中,并希望保持文字和图标的相对尺寸时,这会很有用。",
UIFM_BTN_EMBEDDABLE: "以交互形式",
UIFM_BTN_PDF: "PDF 页面",
UIFM_BTN_IMAGE: "以图像形式",
@@ -1230,4 +1256,10 @@ export default {
VERSION_MISMATCH_DISABLE_DESC: "可在以下位置重新启用:设置 → Excalidraw → 基本 → 警告插件更新不完整",
VERSION_MISMATCH_REDOWNLOAD: "重新下载插件",
VERSION_MISMATCH_IGNORE: "忽略",
//InlineLinkSuggester.ts
INLINE_HINT: "输入 [[ 以搜索并插入链接",
//SuggestionModal.ts
SUGGESTION_NOMATCH: "未找到匹配结果",
};
+60 -22
View File
@@ -37,12 +37,13 @@ export default {
CONVERT_FILE_KEEP_EXT: "轉換:*.excalidraw => *.excalidraw.md",
CONVERT_FILE_REPLACE_EXT: "轉換:*.excalidraw => *.md (相容 Logseq)",
DOWNLOAD_LIBRARY: "匯出 stencil 庫為 *.excalidrawlib 檔案",
OPEN_SIDEPANEL: "開啟 Excalidraw 側邊面板",
OPEN_EXISTING_NEW_PANE: "開啟已有的繪圖 - 於新面板",
OPEN_EXISTING_ACTIVE_PANE:
"開啟已有的繪圖 - 於當前面板",
TRANSCLUDE: "嵌入繪圖 ![[drawing]] 到當前 Markdown 文件中",
TRANSCLUDE_MOST_RECENT: "嵌入最近編輯過的繪圖 ![[drawing]] 到當前 Markdown 文件中",
TOGGLE_LEFTHANDED_MODE: "切換為左手模式",
TOGGLE_LEFTHANDED_MODE: "切換左手模式",
TOGGLE_SPLASHSCREEN: "在新繪圖中顯示啟動畫面",
FLIP_IMAGE: "在彈出視窗中開啟所選繪圖的背景筆記",
NEW_IN_NEW_PANE: "新建繪圖 - 於新面板",
@@ -63,6 +64,7 @@ export default {
MARKER_FRAME_TITLE_SHOW: "顯示標記畫框名稱",
MARKER_FRAME_TITLE_HIDE: "隱藏標記畫框名稱",
COPY_ELEMENT_LINK: "複製所選元素的 [[file#^id]] 連結",
FRAME_WITH_NAME: "按名稱複製畫框連結",
COPY_DRAWING_LINK: "複製繪圖的 ![[drawing]] 連結",
INSERT_LINK_TO_ELEMENT:
`單擊=複製所選元素的 [[file#^id]] 連結\n${labelCTRL()}=複製元素所在分組為 [[file#^group=id]] 連結\n${labelSHIFT()}=複製所選元素所在區域為 [[file#^area=id]] 連結`,
@@ -86,7 +88,7 @@ export default {
INSERT_MD: "以影像形式嵌入 Markdown 文件到當前繪圖中",
INSERT_PDF: "以影像形式嵌入 PDF 到當前繪圖中",
INSERT_LAST_ACTIVE_PDF_PAGE_AS_IMAGE: "以影像形式嵌入最後啟用的 PDF 頁面",
UNIVERSAL_ADD_FILE: "以互動或影像形式嵌入檔案",
UNIVERSAL_ADD_FILE: "嵌入檔案 (Insert ANY file)",
INSERT_CARD: "插入“背景筆記”卡片",
CONVERT_CARD_TO_FILE: "將“背景筆記”卡片儲存到檔案",
ERROR_TRY_AGAIN: "請重試。",
@@ -98,7 +100,7 @@ export default {
RUN_OCR: "OCR 整個繪圖:識別塗鴉和圖片裡的文字並複製到剪貼簿和筆記屬性中",
RERUN_OCR: "重新 OCR 整個繪圖:識別塗鴉和圖片裡的文字並複製到剪貼簿和筆記屬性中",
RUN_OCR_ELEMENTS: "OCR 選中的元素:識別塗鴉和圖片裡的文字並複製到剪貼簿",
TRAY_MODE: "繪圖工具屬性頁:面板模式 ⟺ 托盤模式",
UI_MODE: "切換 UI 模式",
SEARCH: "搜尋文字",
CROP_PAGE: "裁剪所選頁面並新增蒙版",
CROP_IMAGE: "裁剪圖片並新增蒙版",
@@ -110,11 +112,13 @@ export default {
TEMPORARY_ENABLE_AUTOSAVE: "啟用自動儲存功能",
FONTS_LOADED: "Excalidraw: CJK 字型已載入",
FONTS_LOAD_ERROR: "Excalidraw: 在資原始檔夾下找不到 CJK 字型\n",
TOGGLE_ENABLE_CONTEXT_MENU: "切換是否啟用上下文選單(在移動裝置上很有用)",
//Prompt.ts
SELECT_LINK_TO_OPEN: "選擇要開啟的連結",
//ExcalidrawView.ts
ABOUT_LIBRARIES: "如何載入素材庫",
ERROR_CANT_READ_FILEPATH: "錯誤,無法讀取檔案路徑。正在改為匯入檔案",
NO_SEARCH_RESULT: "在繪圖中未找到匹配的元素",
FORCE_SAVE_ABORTED: "自動儲存被中止,因為檔案正在儲存中",
@@ -137,8 +141,8 @@ export default {
"1) 使用 Ctrl/CMD+A 選擇您的繪圖,然後使用 Ctrl/CMD+C 進行復制。\n" +
"2) 然後在新窗格中,透過 Ctrl/CMD 點選 Excalidraw 功能區按鈕建立一個空白繪圖。\n" +
"3) 最後,使用 Ctrl/CMD+V 將您的作品貼上到新檔案中。",
ARIA_LABEL_TRAY_MODE: "托盤模式提供更寬敞的繪圖空間",
TRAY_TRAY_MODE: "切換托盤模式",
ARIA_LABEL_TRAY_MODE: "切換 3 種 UI 模式:完整模式(桌面端)、緊湊模式、托盤模式。手機端只有手機端模式。",
TRAY_TRAY_MODE: "切換 UI 模式",
TRAY_SCRIPT_LIBRARY: "指令碼庫",
TRAY_SCRIPT_LIBRARY_ARIA: "瀏覽 Excalidraw 指令碼庫",
TRAY_EXPORT: "匯出繪圖…",
@@ -151,6 +155,7 @@ export default {
OPEN_AS_MD: "開啟為 Markdown",
EXPORT_IMAGE: `匯出為圖片`,
OPEN_LINK: "開啟所選元素裡的連結 \n(按住 Shift 在新面板開啟)",
EXCALIDRAW_SIDEPANEL: "Excalidraw 側邊面板",
EXPORT_EXCALIDRAW: "匯出為 .excalidraw 檔案(舊版繪圖檔案格式)",
LINK_BUTTON_CLICK_NO_TEXT:
"請選擇一個包含內部或外部連結的元素。\n",
@@ -168,7 +173,7 @@ export default {
COMPATIBILITY_MODE:
"*.excalidraw 是相容舊版的繪圖檔案格式。需要轉換為新格式才能解鎖本外掛的全部功能。",
CONVERT_FILE: "轉換為新格式",
BACKUP_AVAILABLE: "載入繪圖檔案時出錯,可能是由於 Obsidian 在上次儲存時意外退出了(手機上更容易發生這種意外)。<br><br><b>好訊息:</b>這臺裝置上存在備份。您是否想要恢復本裝置上的備份?<br><br>(我建議您先嚐試在最近使用過的其他裝置上開啟該繪圖,以檢查是否有更新的備份。)",
BACKUP_AVAILABLE: "載入繪圖檔案時出錯,可能是由於 Obsidian 在上次儲存時意外退出了(移動裝置上更容易發生這種意外)。<br><br><b>好訊息:</b>這臺裝置上存在備份。您是否想要恢復本裝置上的備份?<br><br>(我建議您先嚐試在最近使用過的其他裝置上開啟該繪圖,以檢查是否有更新的備份。)",
BACKUP_RESTORED: "已恢復備份",
BACKUP_SAVE_AS_FILE: "此繪圖為空。但有一個非空的備份可用。您想將其恢復為新檔案並在新標籤頁中開啟嗎?",
BACKUP_SAVE: "恢復",
@@ -214,6 +219,8 @@ export default {
//settings.ts
DISABLE_CONTEXT_MENU_NAME: "停用 Excalidraw 上下文選單",
DISABLE_CONTEXT_MENU_DESC: "停用 Excalidraw 的上下文選單。這在移動裝置上很有用,因為上下文選單有時會在不需要的時候彈出。",
NOTEBOOKLM_LINK_ARIA: "向 NotebookLM 諮詢有關外掛的幫助。此模型已預載入了我所有的影片轉錄稿、釋出說明和其他幫助內容。與 NotebookLM 聊天,瀏覽我的 250+ 影片和 Excalidraw 檔案。",
NOTEBOOKLM_LINK_TEXT: "學習外掛。訪問 NotebookLM 知識庫。",
LINKS_BUGS_ARIA: "在外掛的 GitHub 頁面報告錯誤和提交功能請求",
@@ -227,8 +234,8 @@ export default {
LINKS_VTW: "加入研討會",
LINKS_BOOK_ARIA: "閱讀我的視覺思維著作《Sketch Your Mind》",
LINKS_BOOK: "閱讀書籍",
LINKS_WIKI: "外掛 Wiki",
LINKS_WIKI_ARIA: "瀏覽 Excalidraw 外掛 Wiki",
LINKS_WIKI: "外掛維基",
LINKS_WIKI_ARIA: "瀏覽 Excalidraw 外掛維基",
RELEASE_NOTES_NAME: "顯示更新說明",
RELEASE_NOTES_DESC:
@@ -309,6 +316,9 @@ export default {
"使用哪個 AI 模型來生成文字。請填寫有效的 OpenAI 模型名稱。" +
"您可訪問 <a href='https://platform.openai.com/docs/models'>OpenAI 網站</a> 瞭解更多模型資訊。",
AI_OPENAI_DEFAULT_MODEL_PLACEHOLDER: "gpt-3.5-turbo-1106",
AI_OPENAI_DEFAULT_MAX_TOKENS_NAME: "最大 token 數",
AI_OPENAI_DEFAULT_MAX_TOKENS_DESC:
"API 生成的最大 token 數。設定為 0 以忽略 max_tokens 欄位(適用於不支援該引數的模型,如 GPT-5)。",
AI_OPENAI_DEFAULT_IMAGE_MODEL_NAME: "預設的圖片 AI 模型",
AI_OPENAI_DEFAULT_IMAGE_MODEL_DESC:
"使用哪個 AI 模型來生成圖片。圖生圖會強制使用 dall-e-2 模型," +
@@ -449,6 +459,20 @@ export default {
"注意:該項不會影響 Excalidraw 本身的 PDF 匯出功能。<br>" +
"請參閱下方 <a href='#"+TAG_PDFEXPORT+"'>PDF 匯出設定</a>。<br>" +
"⚠️ 關閉並重新開啟 Excalidraw/Markdown 檔案後生效。",
MODES_HEAD: "UI 模式",
DESKTOP_UI_MODE_NAME: "桌面端偏好模式",
DESKTOP_UI_MODE_DESC: "桌面端裝置預設 UI 模式。",
TABLET_UI_MODE_NAME: "平板端偏好模式",
TABLET_UI_MODE_DESC: "平板端裝置預設 UI 模式。",
MODE_FULL: "Desktop-mode",
MODE_COMPACT: "Compact-mode",
MODE_TRAY: "Tray-mode",
TRAY_MODE_NAME: "啟用托盤模式",
PREFER_COMPACT_MODE_DESKTOP_NAME: "在桌面端偏好緊湊模式",
PREFER_COMPACT_MODE_DESKTOP_DESC: "切換托盤模式時,開啟該項,Excalidraw 將在緊湊模式與托盤模式之間切換。" +
"關閉該項,則在完整模式與托盤模式之間切換。",
COMPACT_MODE_NAME: "在平板端偏好緊湊模式",
COMPACT_MODE_DESC: "該項允許平板端和桌面端設定不同的預設模式。你可以在平板端預設使用緊湊模式,而在桌面端預設使用托盤模式。",
HOTKEY_OVERRIDE_HEAD: "熱鍵覆蓋",
HOTKEY_OVERRIDE_DESC: `一些 Excalidraw 的熱鍵,如 ${labelCTRL()}+Enter 用於編輯文字,或 ${labelCTRL()}+K 用於建立元素連結,` +
"與 Obsidian 的熱鍵設定衝突。您在下面新增的熱鍵組合將在使用 Excalidraw 時覆蓋 Obsidian 的熱鍵設定," +
@@ -487,9 +511,8 @@ export default {
GRID_DYNAMIC_COLOR_DESC:
"<b>開啟:</b>更改網格顏色以匹配繪圖顏色。<br><b>關閉:</b>將以下顏色用作網格顏色。",
GRID_COLOR_NAME: "網格顏色",
GRID_OPACITY_NAME: "網格透明度",
GRID_OPACITY_DESC: "設定網格的透明度。還將控制將箭頭繫結到元素時繫結框的透明度。" +
"0 全透明 ⟺ 100 不透明。",
GRID_OPACITY_NAME: "網格不透明度",
GRID_OPACITY_DESC: "設定網格的不透明度。0 全透明 ⟺ 100 不透明。",
GRID_DIRECTION_NAME: "網格方向",
GRID_DIRECTION_DESC: "第一個開關顯示/隱藏水平網格,第二個開關顯示/隱藏垂直網格。",
GRID_HORIZONTAL: "渲染水平網格",
@@ -520,7 +543,8 @@ export default {
LONG_PRESS_MOBILE_NAME: "長按開啟(移動端)",
LONG_PRESS_MOBILE_DESC: "長按開啟在 Markdown 文件中嵌入的 Excalidraw 繪圖。單位:毫秒。",
DOUBLE_CLICK_LINK_OPEN_VIEW_MODE: "在檢視模式下允許雙擊開啟連結",
ELEMENT_LINK_SYNC_NAME: "文字元素同步正文連結",
ELEMENT_LINK_SYNC_DESC: "若開啟,Excalidraw 將匹配 2.19.0 之前的行為:始終將正文第一個連結複製到元素連結欄位。匯出 SVG/PNG 僅在元素連結欄位包含單個連結(不包括正文內的連結)時保留連結。開啟:若你依賴正文連結並希望元素連結始終映象第一個連結。關閉:若你獨立管理元素連結,用於標籤、行內連結本體等元資料、或多個連結,如 Dataview 風格的筆記 '(reminds me of:: [[link]]) #noteToSelf'。",
FOCUS_ON_EXISTING_TAB_NAME: "聚焦於當前標籤頁",
FOCUS_ON_EXISTING_TAB_DESC: "當開啟一個連結時,如果該檔案已經開啟,Excalidraw 將會聚焦到現有的標籤頁上。" +
"啟用該項時,如果檔案已開啟,將覆蓋“在相鄰面板中開啟”,但“開啟所選繪圖的背景筆記”命令面板操作除外。",
@@ -543,6 +567,12 @@ export default {
"文字元素處於 PREVIEW 模式時,在內部連結的兩側顯示中括號。<br>" +
"可為某個繪圖單獨設定該項,方法是在其 frontmatter 中新增如 <code>"
}${FRONTMATTER_KEYS["link-brackets"].name}: true/false</code> 的鍵值對。`,
/*LINK_DETECTION_NAME: "Do not auto-create element link from text",
LINK_DETECTION_DESC: "By default, Excalidraw will automatically create an element link when you type or paste a valid " +
"[[Obsidian link]] or a (web link) into a Text Element. This link overrides whatever element link you may have set previously. " +
"Even if you delete the element link, if the text element contains a valid link, Excalidraw will recreate the element link. " +
"If you turn this setting on, Excalidraw will not auto-create element links from text. You can still manually set element links " +
`Links in the text will still be navigable when you ${labelCTRL()} + CLICK the element.`,*/
LINK_PREFIX_NAME: "內部連結的字首",
LINK_PREFIX_DESC: `${
"文字元素處於 PREVIEW 模式時,如果其中包含連結,則新增此字首。<br>" +
@@ -564,9 +594,9 @@ export default {
`<b>開啟:</b>在 Excalidraw <u>檢視模式(View)</u>下,滑鼠懸停在 <code>[[內部連結]]</code> 上即可預覽;` +
"而在<u>普通模式(Normal)</u>下,滑鼠懸停在內部連結右上角的藍色標識上即可預覽。<br>" +
`<b>關閉:</b>滑鼠懸停在 <code>[[內部連結]]</code> 上,並且按住 ${labelCTRL()} 才能預覽。`,
LINKOPACITY_NAME: "連結標識的透明度",
LINKOPACITY_NAME: "連結標識的不透明度",
LINKOPACITY_DESC:
"含有連結的元素,其右上角的連結標識的透明度。0 全透明 ⟺ 100 不透明。",
"含有連結的元素,其右上角的連結標識的不透明度。0 全透明 ⟺ 100 不透明。",
LINK_CTRL_CLICK_NAME:
`按住 ${labelCTRL()} 並點選含有 [[連結]] 或 [別名](連結) 的文字來開啟連結`,
LINK_CTRL_CLICK_DESC:
@@ -671,7 +701,7 @@ export default {
EMBED_REUSE_EXPORTED_IMAGE_DESC:
"該項與下方“匯出”部分“匯出設定”中的 <a href='#"+TAG_AUTOEXPORT+"'>自動匯出 SVG/PNG 副本</a> 選項配合使用。如果嵌入到 Markdown 文件中的繪圖檔案存在同名的 SVG/PNG 副本,則將其作為預覽圖,而不再重新生成。<br>" +
"該項能夠提高 Markdown 文件的開啟速度,尤其是當嵌入到 Markdown 文件中的繪圖檔案中含有大量圖片或 MD-Embed 時。" +
"但是,該項也可能導致預覽圖無法立即響應繪圖檔案或者 Obsidian 主題的修改。<br>" +
"但是,該項也可能導致預覽圖無法即時反應繪圖檔案或者 Obsidian 主題的修改。<br>" +
"該項僅作用於嵌入到 Markdown 文件中的繪圖。" +
"該項無法提升繪圖檔案的開啟速度。詳見 <a href='https://github.com/zsviczian/obsidian-excalidraw-plugin/releases/tag/1.6.23' target='_blank'>此說明</a>。",
/*EMBED_PREVIEW_SVG_NAME: "生成 SVG 格式的預覽圖",
@@ -761,7 +791,7 @@ export default {
PRESERVE_TEXT_AFTER_DRAWING_NAME: "相容 Zotero 和腳註(footnotes)",
PRESERVE_TEXT_AFTER_DRAWING_DESC: "保留 Excalidraw Markdown 中 <code>## Drawing</code> 部分之後的文字內容。儲存非常大的繪圖時,這可能會造成微小的效能影響。",
DEBUGMODE_NAME: "開啟 debug 資訊",
DEBUGMODE_DESC: "我建議在啟用/停用該項後重新啟動 Obsidian。這將在控制檯中啟用除錯訊息。這對於排查問題很有幫助。" +
DEBUGMODE_DESC: "我建議在啟用/停用該項後重新啟動 Obsidian。這將在控制檯中啟用除錯訊息,有助於排查問題。" +
"如果您在使用外掛時遇到問題,請啟用該項,重現問題,並在 <a href='https://github.com/zsviczian/obsidian-excalidraw-plugin/issues'>GitHub</a> 上提出的問題中包含控制檯日誌。",
SLIDING_PANES_NAME: "支援 Sliding Panes 外掛",
SLIDING_PANES_DESC:
@@ -902,9 +932,9 @@ export default {
SELECT_FILE_TO_LINK: "選擇要以連結形式插入到當前繪圖中的檔案",
SELECT_COMMAND_PLACEHOLDER: "選擇要插入到當前繪圖中的命令",
SELECT_DRAWING: "選擇要以影像形式嵌入到當前繪圖中的圖片或繪圖檔案",
TYPE_FILENAME: "鍵入要選擇的繪圖名稱",
TYPE_FILENAME: "輸入要選擇的繪圖名稱",
SELECT_FILE_OR_TYPE_NEW:
"選擇已有繪圖,或者鍵入新繪圖檔案的名稱,然後按回車。",
"選擇已有繪圖,或者輸入新繪圖檔案的名稱,然後按回車。",
SELECT_TO_EMBED: "選擇要嵌入到當前 Markdown 文件中的繪圖",
SELECT_MD: "選擇要以影像形式嵌入到當前繪圖中的 Markdown 文件",
SELECT_PDF: "選擇要以影像形式嵌入到當前繪圖中的 PDF",
@@ -996,15 +1026,15 @@ export default {
ES_FILENAME_VISIBLE: "顯示頁內標題",
ES_BACKGROUND_HEAD: "背景色",
ES_BACKGROUND_DESC_INFO: "點選此處檢視更多顏色資訊",
ES_BACKGROUND_DESC_DETAIL: "背景色僅影響預覽模式的 MD-Embeddable。在編輯模式,它會根據場景(透過筆記屬性設定)或外掛設定,遵循 Obsidian 的深色/淺色主題。背景色有兩層:元素背景色(下層顏色)和上層顏色。選擇“匹配元素”表示兩層都遵循元素背景色。選擇“匹配繪圖”或特定背景色不會改變元素背景色。設定透明度(如 50%)會將繪圖或選定的顏色與元素背景色混合。要移除元素背景色,可以在 Excalidraw 的元素屬性編輯器中將元素背景色設定為透明,這樣只有上層顏色生效。",
ES_BACKGROUND_DESC_DETAIL: "背景色僅影響預覽模式的 MD-Embeddable。在編輯模式,它會根據場景(透過筆記屬性設定)或外掛設定,遵循 Obsidian 的深色/淺色主題。背景色有兩層:元素背景色(下層顏色)和上層顏色。選擇“匹配元素”表示兩層都遵循元素背景色。選擇“匹配繪圖”或特定背景色不會改變元素背景色。設定不透明度(如 50%)會將繪圖或選定的顏色與元素背景色混合。要移除元素背景色,可以在 Excalidraw 的元素屬性編輯器中將元素背景色設定為透明,這樣只有上層顏色生效。",
ES_BACKGROUND_MATCH_ELEMENT: "匹配元素背景色",
ES_BACKGROUND_MATCH_CANVAS: "匹配繪圖背景色",
ES_BACKGROUND_COLOR: "背景色",
ES_BORDER_HEAD: "邊框顏色",
ES_BORDER_COLOR: "邊框顏色",
ES_BORDER_MATCH_ELEMENT: "匹配元素邊框顏色",
ES_BACKGROUND_OPACITY: "背景透明度",
ES_BORDER_OPACITY: "邊框透明度",
ES_BACKGROUND_OPACITY: "背景不透明度",
ES_BORDER_OPACITY: "邊框不透明度",
ES_EMBEDDABLE_SETTINGS: "MD-Embeddable 設定",
ES_USE_OBSIDIAN_DEFAULTS: "使用 Obsidian 預設設定",
ES_ZOOM_100_RELATIVE_DESC: "使元素的縮放等級等於當前繪圖的縮放等級",
@@ -1113,6 +1143,7 @@ export default {
EXPORTDIALOG_BACKGROUND: "背景",
EXPORTDIALOG_BACKGROUND_TRANSPARENT: "透明",
EXPORTDIALOG_BACKGROUND_USE_COLOR: "使用場景顏色",
EXPORTDIALOG_INCLUDE_INTERNAL_LINKS: "匯出內部連結為 SVG/PDF?",
// Selection
EXPORTDIALOG_SELECTED_ELEMENTS: "匯出",
EXPORTDIALOG_SELECTED_ALL: "整個場景",
@@ -1187,7 +1218,7 @@ export default {
UIFM_TITLE: "從倉庫中嵌入檔案",
UIFM_SECTION_HEAD: "選擇章節標題",
UIFM_ANCHOR: "錨定為原始大小的 100%",
UIFM_ANCHOR_DESC: "這是一個專業功能,請在瞭解其作用的情況下再使用。啟用後,即使你在 Excalidraw 中調整了匯入影像的大小,下次開啟繪圖時,該影像仍會恢復為原始大小的 100%。這在將一個獨立的 Excalidraw 點子嵌入到另一份筆記中,並希望保持文字和圖示的相對尺寸時非常有用。",
UIFM_ANCHOR_DESC: "這是一個專業功能,請在瞭解其作用的情況下再使用。啟用後,即使你在 Excalidraw 中調整了匯入影像的大小,下次開啟繪圖時,該影像仍會恢復為原始大小的 100%。當你將一個獨立的 Excalidraw 點子嵌入到另一份筆記中,並希望保持文字和圖示的相對尺寸時,這會很有用。",
UIFM_BTN_EMBEDDABLE: "以互動形式",
UIFM_BTN_PDF: "PDF 頁面",
UIFM_BTN_IMAGE: "以影像形式",
@@ -1216,6 +1247,7 @@ export default {
//VersionMismatch.ts
//WARNING: Do not change the {VAL_RECORDED} and {VAL_ACTUAL} strings, they are replaced by the actual version values at runtime!
VERSION_MISMATCH_NOTICE: `Obsidian 顯示的版本是 <b>{VAL_RECORDED}</b>,但已安裝的 Excalidraw 程式碼顯示的版本是 <b>{VAL_ACTUAL}</b>。`,
VERSION_MISMATCH_HEADING: "Excalidraw 版本不匹配",
VERSION_MISMATCH_CAUSE: "通常源於同步不完整,大檔案未能同步(如使用 Obsidian Sync Standard,main.js > 5MB),只更新了 <code>manifest.json</code>。",
VERSION_MISMATCH_OPTIONS: "選項:<br><b>1.</b> 重新下載外掛(推薦)。<br><b>2.</b> 暫時忽略。",
@@ -1224,4 +1256,10 @@ export default {
VERSION_MISMATCH_DISABLE_DESC: "可在以下位置重新啟用:設定 → Excalidraw → 基本 → 警告外掛更新不完整",
VERSION_MISMATCH_REDOWNLOAD: "重新下載外掛",
VERSION_MISMATCH_IGNORE: "忽略",
//InlineLinkSuggester.ts
INLINE_HINT: "輸入 [[ 以搜尋並插入連結",
//SuggestionModal.ts
SUGGESTION_NOMATCH: "未找到匹配結果",
};
+1 -1
View File
@@ -6,9 +6,9 @@ import { Notice } from "obsidian";
import { getEA } from "src/core";
import { ExcalidrawAutomate } from "src/shared/ExcalidrawAutomate";
import { cloneElement } from "src/utils/excalidrawAutomateUtils";
import { ExportSettings } from "src/view/ExcalidrawView";
import { nanoid } from "src/constants/constants";
import { svgToBase64 } from "../utils/utils";
import { ExportSettings } from "src/types/exportUtilTypes";
/**
* Creates a masked image from an Excalidraw scene.
+127
View File
@@ -0,0 +1,127 @@
import ExcalidrawView from "src/view/ExcalidrawView";
import { getViewColorPalette } from "src/utils/excalidrawViewUtils";
type PaletteName = "canvasBackground"|"elementBackground"|"elementStroke";
const GRID_COLUMNS = 5;
const CELL_SIZE = 32;
const CELL_GAP = 8;
const POPUP_PADDING = 12;
const MAX_HEIGHT = 260;
const getColors = (palette: PaletteName, view?: ExcalidrawView, includeSceneColors: boolean = false): string[] => {
const raw = getViewColorPalette(palette, view, includeSceneColors) ?? [];
const flattened: string[] = [];
raw.forEach((entry: any) => {
if (Array.isArray(entry)) {
entry.forEach((color) => {
if (typeof color === "string" && color) {
flattened.push(color);
}
});
} else if (typeof entry === "string" && entry) {
flattened.push(entry);
}
});
return flattened;
};
const positionPopup = (popup: HTMLElement, anchor: HTMLElement) => {
const rect = anchor.getBoundingClientRect();
const { innerWidth, innerHeight } = window;
const popupWidth = popup.offsetWidth || (GRID_COLUMNS * (CELL_SIZE + CELL_GAP)) + POPUP_PADDING * 2;
const popupHeight = popup.offsetHeight || MAX_HEIGHT + POPUP_PADDING * 2;
let left = rect.left;
let top = rect.bottom + 8;
if (left + popupWidth > innerWidth - 8) {
left = Math.max(8, innerWidth - popupWidth - 8);
}
if (top + popupHeight > innerHeight - 8) {
top = Math.max(8, rect.top - popupHeight - 8);
}
popup.style.left = `${left}px`;
popup.style.top = `${top}px`;
};
const attachOutsideHandlers = (
overlay: HTMLElement,
popup: HTMLElement,
resolve: (color: string | null) => void,
) => {
const stopPropagation = (evt: Event) => evt.stopPropagation();
let cleanup: (color: string | null) => void;
const onKeyDown = (evt: KeyboardEvent) => {
if (evt.key === "Escape") {
evt.stopPropagation();
cleanup(null);
}
};
const onOverlayClick = () => cleanup(null);
cleanup = (color: string | null) => {
document.removeEventListener("keydown", onKeyDown, true);
overlay.removeEventListener("click", onOverlayClick);
popup.removeEventListener("click", stopPropagation);
overlay.remove();
resolve(color);
};
document.addEventListener("keydown", onKeyDown, true);
overlay.addEventListener("click", onOverlayClick);
popup.addEventListener("click", stopPropagation);
return cleanup;
};
export const showColorPicker = async (
palette: PaletteName,
anchorElement: HTMLElement,
view?: ExcalidrawView,
includeSceneColors: boolean = false,
): Promise<string | null> => {
const colors = getColors(palette, view, includeSceneColors);
if (!colors.length) {
return null;
}
return new Promise((resolve) => {
const overlay = document.createElement("div");
overlay.classList.add("excalidraw-colorpicker-overlay");
const popup = document.createElement("div");
popup.classList.add("excalidraw-colorpicker-popup");
const grid = document.createElement("div");
grid.classList.add("excalidraw-colorpicker-grid");
grid.style.gridTemplateColumns = `repeat(${GRID_COLUMNS}, ${CELL_SIZE}px)`;
grid.style.gap = `${CELL_GAP}px`;
grid.style.maxHeight = `${MAX_HEIGHT}px`;
colors.forEach((color) => {
const swatch = document.createElement("button");
swatch.type = "button";
swatch.ariaLabel = color;
swatch.classList.add("excalidraw-colorpicker-swatch");
swatch.style.backgroundColor = color;
swatch.addEventListener("click", () => cleanup(color));
grid.appendChild(swatch);
});
popup.appendChild(grid);
overlay.appendChild(popup);
document.body.appendChild(overlay);
positionPopup(popup, anchorElement);
const cleanup = attachOutsideHandlers(overlay, popup, resolve);
});
};
+10 -2
View File
@@ -37,6 +37,7 @@ export class EmbeddableSettings extends Modal {
private isLocalURI: boolean;
private mdCustomData: EmbeddableMDCustomProps;
private onKeyDown: (ev: KeyboardEvent) => void;
private listenerHost: Document | null = null;
constructor(
private plugin: ExcalidrawPlugin,
@@ -72,7 +73,10 @@ export class EmbeddableSettings extends Modal {
}
onClose() {
this.containerEl.removeEventListener("keydown",this.onKeyDown);
if(this.listenerHost && this.onKeyDown) {
this.listenerHost.removeEventListener("keydown",this.onKeyDown);
this.listenerHost = null;
}
this.plugin = null;
this.view = null;
this.file = null;
@@ -166,7 +170,11 @@ export class EmbeddableSettings extends Modal {
}
this.onKeyDown = onKeyDown;
this.containerEl.ownerDocument.addEventListener("keydown",onKeyDown);
const ownerDoc = this.containerEl.ownerDocument;
if(ownerDoc) {
this.listenerHost = ownerDoc;
ownerDoc.addEventListener("keydown",onKeyDown);
}
}
private async applySettings() {
+16 -3
View File
@@ -5,8 +5,9 @@ import { DEVICE } from "src/constants/constants";
import { ExcalidrawAutomate } from "src/shared/ExcalidrawAutomate";
import ExcalidrawView from "src/view/ExcalidrawView";
import ExcalidrawPlugin from "src/core/main";
import { fragWithHTML, getExportPadding, getExportTheme, getPNGScale, getWithBackground, shouldEmbedScene } from "src/utils/utils";
import { PageOrientation, PageSize, PDFPageAlignment, PDFPageMarginString, exportSVGToClipboard, exportPNG, exportPNGToClipboard } from "src/utils/exportUtils";
import { fragWithHTML, getExportInternalLinks, getExportPadding, getExportTheme, getPNGScale, getWithBackground, shouldEmbedScene } from "src/utils/utils";
import { exportSVGToClipboard, exportPNG, exportPNGToClipboard } from "src/utils/exportUtils";
import { PageOrientation, PageSize, PDFPageAlignment, PDFPageMarginString } from "src/types/exportUtilTypes";
import { t } from "src/lang/helpers";
import { PDFExportSettings, PDFExportSettingsComponent } from "./PDFExportSettingsComponent";
import { captureScreenshot } from "src/utils/screenshot";
@@ -21,6 +22,7 @@ export class ExportDialog extends Modal {
public scale: number;
public theme: string;
public transparent: boolean;
public exportInternalLinks: boolean = true;
public saveSettings: boolean;
public dirty: boolean = false;
private selectedOnlySetting: Setting;
@@ -63,6 +65,7 @@ export class ExportDialog extends Modal {
this.exportSelectedOnly = false;
this.saveToVault = true;
this.transparent = !getWithBackground(this.plugin, this.file);
this.exportInternalLinks = getExportInternalLinks(this.plugin, this.file);
this.pageSize = plugin.settings.pdfSettings.pageSize;
this.pageOrientation = plugin.settings.pdfSettings.pageOrientation;
@@ -301,7 +304,17 @@ export class ExportDialog extends Modal {
.onChange(value => {
this.transparent = value === "transparent";
})
)
);
new Setting(this.contentContainer)
.setName(t("EXPORTDIALOG_INCLUDE_INTERNAL_LINKS"))
.addToggle(toggle =>
toggle
.setValue(this.exportInternalLinks)
.onChange(value => {
this.exportInternalLinks = value;
})
);
}
this.selectedOnlySetting = new Setting(this.contentContainer)
+94 -20
View File
@@ -1,5 +1,68 @@
import { App, Modal } from "obsidian";
function getClientPoint(e: PointerEvent | TouchEvent) {
if (e.type.startsWith("touch")) {
const t = (e as TouchEvent).touches[0] ?? (e as TouchEvent).changedTouches[0];
return t ? { x: t.clientX, y: t.clientY } : null;
}
const p = e as PointerEvent;
return { x: p.clientX, y: p.clientY };
}
function pointInRect(pt: { x: number; y: number }, r: DOMRect, padding = 1): boolean {
return (
pt.x >= r.left - padding &&
pt.x <= r.right + padding &&
pt.y >= r.top - padding &&
pt.y <= r.bottom + padding
);
}
function isPointOnText(e: PointerEvent | TouchEvent, doc: Document): boolean {
const pt = getClientPoint(e);
if (!pt) return false;
let offsetNode: Node | null = null;
let offset: number | null = null;
// Chromium/Firefox-ish
const caretPos = (doc as any).caretPositionFromPoint?.(pt.x, pt.y);
if (caretPos?.offsetNode) {
offsetNode = caretPos.offsetNode;
offset = typeof caretPos.offset === "number" ? caretPos.offset : null;
} else {
// Safari/WebKit
const caretRange = (doc as any).caretRangeFromPoint?.(pt.x, pt.y);
if (caretRange?.startContainer) {
offsetNode = caretRange.startContainer;
offset = typeof caretRange.startOffset === "number" ? caretRange.startOffset : null;
}
}
if (!offsetNode || offsetNode.nodeType !== Node.TEXT_NODE || offset == null) return false;
if (!offsetNode.textContent?.trim()) return false;
const textNode = offsetNode as Text;
const len = textNode.data.length;
const at = Math.max(0, Math.min(offset, len));
const range = doc.createRange();
if (at < len) {
range.setStart(textNode, at);
range.setEnd(textNode, at + 1);
} else if (at > 0) {
range.setStart(textNode, at - 1);
range.setEnd(textNode, at);
} else {
return false;
}
const rects = Array.from(range.getClientRects());
if (rects.length === 0) return false;
return rects.some((r) => pointInRect(pt, r, 1));
}
export class FloatingModal extends Modal {
private dragging = false;
private offsetX = 0;
@@ -12,10 +75,11 @@ export class FloatingModal extends Modal {
private previousActive: HTMLElement | null = null; // stores element focused before opening
private escListener: (e: KeyboardEvent) => void;
private modalKeydownStopHandler: (e: KeyboardEvent) => void; // store handler so we can remove it
private ownerWindow: Window = window;
private ownerDocument: Document = document;
constructor(app: App) {
super(app);
// Initialize event handlers with proper binding
this.pointerDownHandler = this.handlePointerDown.bind(this);
this.pointerMoveHandler = this.handlePointerMove.bind(this);
@@ -34,7 +98,9 @@ export class FloatingModal extends Modal {
target instanceof HTMLTextAreaElement ||
target instanceof HTMLSelectElement ||
target instanceof HTMLButtonElement ||
target.closest(".clickable-icon")
isPointOnText(e, this.ownerDocument) ||
target.closest(".clickable-icon") ||
target.closest(".modal-close-button") // ensure close button never starts drag
) {
return;
}
@@ -51,13 +117,14 @@ export class FloatingModal extends Modal {
const { modalEl } = this;
this.offsetX = touch.clientX - modalEl.getBoundingClientRect().left;
this.offsetY = touch.clientY - modalEl.getBoundingClientRect().top;
modalEl.style.height = "fit-content";
// Add touch-specific event listeners
document.addEventListener("touchmove", this.pointerMoveHandler as (e: TouchEvent) => void, {
this.ownerDocument.addEventListener("touchmove", this.pointerMoveHandler as (e: TouchEvent) => void, {
passive: false,
});
document.addEventListener("touchend", this.pointerUpHandler);
document.addEventListener("touchcancel", this.pointerUpHandler);
this.ownerDocument.addEventListener("touchend", this.pointerUpHandler);
this.ownerDocument.addEventListener("touchcancel", this.pointerUpHandler);
} else {
// Handle pointer events
this.dragging = true;
@@ -67,8 +134,8 @@ export class FloatingModal extends Modal {
this.offsetY = pointerEvent.clientY - modalEl.getBoundingClientRect().top;
// Add pointer-specific event listeners
document.addEventListener("pointermove", this.pointerMoveHandler as (e: PointerEvent) => void);
document.addEventListener("pointerup", this.pointerUpHandler);
this.ownerDocument.addEventListener("pointermove", this.pointerMoveHandler as (e: PointerEvent) => void);
this.ownerDocument.addEventListener("pointerup", this.pointerUpHandler);
// Capture the pointer to ensure we get events even when outside the target
target.setPointerCapture(pointerEvent.pointerId);
}
@@ -106,16 +173,15 @@ export class FloatingModal extends Modal {
private handlePointerUp(): void {
this.dragging = false;
// Remove all event listeners
document.removeEventListener("pointermove", this.pointerMoveHandler as (e: PointerEvent) => void);
document.removeEventListener("pointerup", this.pointerUpHandler);
document.removeEventListener("touchmove", this.pointerMoveHandler as (e: TouchEvent) => void);
document.removeEventListener("touchend", this.pointerUpHandler);
document.removeEventListener("touchcancel", this.pointerUpHandler);
this.ownerDocument.removeEventListener("pointermove", this.pointerMoveHandler as (e: PointerEvent) => void);
this.ownerDocument.removeEventListener("pointerup", this.pointerUpHandler);
this.ownerDocument.removeEventListener("touchmove", this.pointerMoveHandler as (e: TouchEvent) => void);
this.ownerDocument.removeEventListener("touchend", this.pointerUpHandler);
this.ownerDocument.removeEventListener("touchcancel", this.pointerUpHandler);
}
private handleEscKey(e: KeyboardEvent) {
if (e.key === "Escape") {
// Optionally stop propagation if you do not want other handlers firing
e.stopPropagation();
this.close();
}
@@ -123,9 +189,11 @@ export class FloatingModal extends Modal {
open(): void {
super.open();
this.ownerDocument = this.modalEl.ownerDocument ?? document;
this.ownerWindow = this.ownerDocument.defaultView ?? window;
// NEW: capture previously focused element & release Obsidian modal key trapping
if (this.disableKeyCapture) {
this.previousActive = document.activeElement as HTMLElement | null;
this.previousActive = this.ownerDocument.activeElement as HTMLElement | null;
try {
// @ts-ignore pop modal's key scope so keys are not intercepted
this.app.keymap.popScope(this.scope);
@@ -150,13 +218,13 @@ export class FloatingModal extends Modal {
// Center the modal initially
const rect = modalEl.getBoundingClientRect();
const centerX = window.innerWidth / 2 - rect.width / 2;
const centerY = window.innerHeight / 2 - rect.height / 2;
const centerX = this.ownerWindow.innerWidth / 2 - rect.width / 2;
const centerY = this.ownerWindow.innerHeight / 2 - rect.height / 2;
modalEl.style.left = `${centerX}px`;
modalEl.style.top = `${centerY}px`;
modalEl.style.transform = "none";
const modalStyle = window.getComputedStyle(modalEl);
const modalStyle = this.ownerWindow.getComputedStyle(modalEl);
modalEl.style.borderBottomLeftRadius = modalStyle.borderTopLeftRadius;
modalEl.style.borderBottomRightRadius = modalStyle.borderTopRightRadius;
@@ -177,14 +245,20 @@ export class FloatingModal extends Modal {
modalEl.addEventListener("keydown", this.modalKeydownStopHandler, { capture: true });
}
// Add ESC listener (capture to run before underlying workspace)
document.addEventListener("keydown", this.escListener, { capture: true });
this.ownerDocument.addEventListener("keydown", this.escListener, { capture: true });
// NEW: re-enable pointer events on the close button so it is tappable on mobile
const closeBtn = containerEl.querySelector(".modal-close-button");
if (closeBtn) {
(closeBtn as HTMLElement).style.pointerEvents = "auto";
}
}
});
}
close(): void {
// Optional: restore previous focus if body ended up focused
if (this.disableKeyCapture && this.previousActive?.isConnected && document.activeElement === document.body) {
if (this.disableKeyCapture && this.previousActive?.isConnected && this.ownerDocument.activeElement === this.ownerDocument.body) {
try { this.previousActive.focus({ preventScroll: true }); } catch {}
}
const { modalEl } = this;
@@ -197,7 +271,7 @@ export class FloatingModal extends Modal {
}
// Remove any remaining document event listeners
this.handlePointerUp();
document.removeEventListener("keydown", this.escListener, { capture: true });
this.ownerDocument.removeEventListener("keydown", this.escListener, { capture: true });
super.close();
}
+7 -64
View File
@@ -1,9 +1,9 @@
import { FuzzyMatch, FuzzySuggestModal, setIcon } from "obsidian";
import { AUDIO_TYPES, CODE_TYPES, ICON_NAME, IMAGE_TYPES, REG_LINKINDEX_INVALIDCHARS, VIDEO_TYPES } from "../../constants/constants";
import { FuzzyMatch, FuzzySuggestModal } from "obsidian";
import { t } from "../../lang/helpers";
import ExcalidrawPlugin from "src/core/main";
import { getLink } from "src/utils/fileUtils";
import { LinkSuggestion } from "src/types/types";
import { getLinkSuggestionsFiltered, getSortedLinkMatches, renderLinkSuggestion } from "src/shared/Suggesters/LinkSuggesterUtils";
export class InsertLinkDialog extends FuzzySuggestModal<LinkSuggestion> {
@@ -32,13 +32,7 @@ export class InsertLinkDialog extends FuzzySuggestModal<LinkSuggestion> {
getItems(): LinkSuggestion[] {
//https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/422
return (
this.app.metadataCache
//@ts-ignore
.getLinkSuggestions()
//@ts-ignore
.filter((x) => !x.path.match(REG_LINKINDEX_INVALIDCHARS))
);
return getLinkSuggestionsFiltered(this.app);
}
getItemText(item: LinkSuggestion): string {
@@ -59,62 +53,11 @@ export class InsertLinkDialog extends FuzzySuggestModal<LinkSuggestion> {
}
renderSuggestion(result: FuzzyMatch<LinkSuggestion>, itemEl: HTMLElement) {
const { item, match: matches } = result || {};
itemEl.addClass("mod-complex");
const contentEl = itemEl.createDiv("suggestion-content");
const auxEl = itemEl.createDiv("suggestion-aux");
const titleEl = contentEl.createDiv("suggestion-title");
const noteEl = contentEl.createDiv("suggestion-note");
renderLinkSuggestion(this.plugin, result, itemEl, this.emptyStateText);
}
if (!item) {
titleEl.setText(this.emptyStateText);
itemEl.addClass("is-selected");
return;
}
const path = item.file?.path ?? item.path;
const pathLength = path.length - (item.file?.name.length ?? 0);
const matchElements = matches.matches.map((m) => {
return createSpan("suggestion-highlight");
});
const itemText = this.getItemText(item);
for (let i = pathLength; i < itemText.length; i++) {
const match = matches.matches.find((m) => m[0] === i);
if (match) {
const element = matchElements[matches.matches.indexOf(match)];
titleEl.appendChild(element);
element.appendText(itemText.substring(match[0], match[1]));
i += match[1] - match[0] - 1;
continue;
}
titleEl.appendText(itemText[i]);
}
noteEl.setText(path);
if(!item.file) {
setIcon(auxEl, "ghost");
} else if(this.plugin.isExcalidrawFile(item.file)) {
setIcon(auxEl, ICON_NAME);
} else if (item.file.extension === "md") {
setIcon(auxEl, "square-pen");
} else if (IMAGE_TYPES.includes(item.file.extension)) {
setIcon(auxEl, "image");
} else if (VIDEO_TYPES.includes(item.file.extension)) {
setIcon(auxEl, "monitor-play");
} else if (AUDIO_TYPES.includes(item.file.extension)) {
setIcon(auxEl, "file-audio");
} else if (CODE_TYPES.includes(item.file.extension)) {
setIcon(auxEl, "file-code");
} else if (item.file.extension === "canvas") {
setIcon(auxEl, "layout-dashboard");
} else if (item.file.extension === "pdf") {
setIcon(auxEl, "book-open-text");
} else {
auxEl.setText(item.file.extension);
}
getSuggestions(query: string): FuzzyMatch<LinkSuggestion>[] {
return getSortedLinkMatches(query, this.getItems());
}
onClose(): void {
+226 -358
View File
@@ -5,9 +5,9 @@ If you'd like to learn more, please subscribe to my YouTube channel: [Visual PKM
Thank you & Enjoy!
<div class="excalidraw-videoWrapper"><div>
<iframe src="https://www.youtube.com/embed/P_Q6avJGoWI" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div></div>
<div class="excalidraw-videoWrapper">
<a href="https://www.youtube.com/watch?v=P_Q6avJGoWI" target="_blank"><img src ="https://i.ytimg.com/vi/P_Q6avJGoWI/maxresdefault.jpg" style="width:100%;"></a>
</div>
`;
export const RELEASE_NOTES: { [k: string]: string } = {
@@ -17,10 +17,227 @@ I build this plugin in my free time, as a labor of love. Curious about the philo
<div class="ex-coffee-div"><a href="https://ko-fi.com/zsolt"><img src="https://storage.ko-fi.com/cdn/kofi6.png?v=6" border="0" alt="Buy Me a Coffee at ko-fi.com" height=45></a></div>
`,
"2.19.1":`
## Fixed
- Excalidraw pointer offset issue on Obsidian Mobile 1.11.4 [#2607](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2607)
## New
- Inline autocomplete link suggester now supports Heading sections and block references.
- Escaped "\\\\[" will now be rendered as "[" in text elements.
- Scaling the LaTeX element when the formula is updated. [#2604](https://github.com/zsviczian/obsidian-excalidraw-plugin/pull/2604) 🙏[@TravisLEBLANC1](https://github.com/TravisLEBLANC1)
## New in ExcalidrawAutomate
- Added PDF++ image link support to the \`addImage()\` function.
`,
"2.19.0":`
<div class="excalidraw-videoWrapper">
<a href="https://www.youtube.com/watch?v=qY66yoobaX4" target="_blank"><img src ="https://i.ytimg.com/vi/qY66yoobaX4/maxresdefault.jpg" style="width:100%;"></a>
</div>
## New
- 🚀🎉🍾 Added **inline link autocomplete** to text element editing and element link editing. Simply start typing "[[" as you would in a normal markdown document.
- ‼️ removed add link button element-link editor on desktop
- ‼️ removed add link from context menu on desktop
- ‼️ added new setting under "Links, transclusion and TODOs" **Sync text-element link with text**
- The default behavior is OFF, because it feels more natural to manage the element link separately.
- When enabled (ON), Excalidraw matches pre-2.19.0 behavior: the first link in the text body is always copied to the element link field. SVG/PNG exports only keep links when the element link field holds a single link (not links inside the text body). Turn this ON if you rely on text-body links and want the element link to always mirror the first one. Turn it OFF if you manage the element link separately: for metadata like tags, inline link ontologies, or multiple links, e.g., dataview-style notes like '(reminds me of:: [[link]]) #noteToSelf'.
- LaTeX formula is saved to \`element.customData.latex\`. This can be helpful for various automation use cases.
- Implemented Color Picker in Custom Pen Settings to pick from the current view's color palette.
- Updated the **Scribble Helper** script with the new Color Picker to select the text color.
- Updated the **Shade Maser** script with the new Color Picker to select the shading color.
- **Mindmap Builder**
- Uses new sidepanel, persistent across different drawings and autostarts with Obsidian.
- You can now configure hotkeys
- Allows editing node text in place
- You can define your own color palette for branches
- Improved auto-layout algorithm to work better with larger subtrees
- Includes inline link suggester
- Image and Embeddable nodes
## Fixed
- Floating modal used by Excalidraw scripts did not work correctly in Obisidian popout windows.
- In onPaste if \`imageElement.customData.latex\` is present, it will treat the pasted images as a LaTeX formula, even if copied from Excalidraw.com or another Obsidian Vault.
## New & fixed in ExcalidrawAutomate
- \`ea.toClipboard()\` will now include the DataURL for included images from \`ea.imagesDict\`
- Implemented Excalidraw Sidepanel API for ExcalidrawAutomate. Scripts can now create custom Obsidian sidepanel tabs in the Excalidraw Sidepanel.
- New Command Palette action: "Open Excalidraw Sidepanel" will toggle the sidepanel visibility.
- The demo script making full use of the new sidepanel API is [Mindmap Builder](https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/ea-scripts/Mindmap%20Builder.md).
- [ExcalidrawAutomate full library for LLM training.md](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/refs/heads/master/docs/AITrainingData/ExcalidrawAutomate%20full%20library%20for%20LLM%20training.md) includes all necessary training information to use sidepanels.
- Added palette popover helper \`showColorPicker()\` (also used in Pen Settings and Mindmap Builder) to pick from the current view's canvas/element palettes.
- Added inline link suggester helper \`attachInlineLinkSuggester()\` returning a KeyBlocker interface so host scripts can suppress their own keydown handlers while the suggester is active.
New functions in ExcalidrawAutomate. See also [SidepanelTab](https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/src/types/sidepanelTabTypes.ts) type definition.
\`\`\`ts
sidepanelTab: ExcalidrawSidepanelTab | null;
checkForActiveSidepanelTabForScript(scriptName?: string): ExcalidrawSidepanelTab | null;
createSidepanelTab(title: string, persist?: boolean, reveal?: boolean): Promise<ExcalidrawSidepanelTab | null>;
getSidepanelLeaf(): WorkspaceLeaf | null;
toggleSidepanelView(): void;
persistSidepanelTab(): ExcalidrawSidepanelTab | null;
attachInlineLinkSuggester(inputEl: HTMLInputElement, widthWrapper?: HTMLElement): KeyBlocker;
getViewColorPalette(palette: "canvasBackground"|"elementBackground"|"elementStroke"): (string[] | string)[];
showColorPicker(anchorElement: HTMLElement, palette: "canvasBackground"|"elementBackground"|"elementStroke", includeSceneColors: boolean = true): Promise<string | null>;
\`\`\`
- **setView() improvements**
- Calling \`setView()\` now picks a sensible target automatically:
- It prefers the **currently active Excalidraw view**.
- If no active Excalidraw view is found (e.g., the user is focused on a different tab like the File Explorer/sidebar), it will fall back to the **last active Excalidraw view (as long as it is still available)** — typically the drawing the user came from.
- **New selector**: \`"auto"\` (equivalent to calling \`setView()\`).
- Useful when you also want to reveal/focus the view: \`setView("auto", true)\`.
- **Deprecated selectors**: \`"active"\` and \`"first"\` are deprecated and kept only for backward compatibility.
- Recommended usage is either \`setView()\`, \`setView("auto")\`, or \`setView(excalidrawView)\` (explicitly target a specific view).
\`\`\`ts
setView(view?: ExcalidrawView | "auto" | "first" | "active" | null, show: boolean = false)
\`\`\`
`,
"2.18.3":`
<div class="excalidraw-videoWrapper">
<a href="https://www.youtube.com/watch?v=dZguonMP2KU" target="_blank"><img src ="https://i.ytimg.com/vi/dZguonMP2KU/maxresdefault.jpg" style="width:100%;"></a>
</div>
## New
- Added Mindmap Builder script to the store.
- LaTeX Suit Integration by [@TravisLEBLANC1](https://github.com/TravisLEBLANC1)
- Added Linear Calendar Generator script to the store. 🙏 [@iwanhoogendoorn](https://github.com/iwanhoogendoorn)
## Fixed
- YouTube video embeds working on iOS [#2569](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2569)
- Stroke color setting for Embeddedables (markdown notes, websites) is missing after 2.17.0 update [#2580](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2580)
- Context menu paste pastes in image twice [#10542](https://github.com/excalidraw/excalidraw/issues/10542)
## New in ExcalidrawAutomate
- Added 3 new helper functions for working with Script Engine settings (safe during initialization when \`scriptEngineSettings[activeScript]\` is \`undefined\` / \`null\`):
- \`setScriptSettingValue(key: string, value: ScriptSettingValue): void\`
- \`getScriptSettingValue(key: string, defaultValue: ScriptSettingValue): ScriptSettingValue\`
- \`saveScriptSettings(): Promise<void>\`
- Updated \`addArrow()\` to support the new Excalidraw binding options:
- \`startBindMode?: "inside" | "orbit"\`
- \`endBindMode?: "inside" | "orbit"\`
- \`startFixedPoint?: [number, number]\`
- \`endFixedPoint?: [number, number]\`
- \`elbowed?: boolean\`
\`\`\`ts
/**
* Returns an object describing the bound text element.
* If a text element is provided:
* - returns { eaElement } if the element is in ea.elementsDict
* - else (if searchInView is true) returns { sceneElement } if found in the targetView scene
* If a container element is provided, searches for the bound text element:
* - returns { eaElement } if found in ea.elementsDict
* - else (if searchInView is true) returns { sceneElement } if found in the targetView scene
* If not found, returns {}.
* Does not add the text element to elementsDict.
* @param element
* @param searchInView - If true, searches in the targetView elements if not found in elementsDict.
* @returns Object containing either eaElement or sceneElement or empty if not found.
*/
getBoundTextElement(element: ExcalidrawElement, searchInView: boolean = false): {
eaElement?: Mutable<ExcalidrawTextElement>,
sceneElement?: ExcalidrawTextElement
};
\`\`\`
`,
"2.18.2":`
## Fixed
- Stroke palette menu for embedded notes is gone after 2.17 update [#2580](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2580)
- Cannot link to group [#2579](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2579)
`,
"2.18.1":`
## New
- Improved the **Copy [[link]] for selected elements** context-menu action:
- Added an optional checkbox to append the \`|100%\` anchor to the copied link.
- Added an option to copy by **frame name** (instead of frame ID) when the frame is named.
## Fixed
- Prevented unnecessary \`data.json\` saves each time a drawing is opened. [#2562](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2562)
- Fixed angle snapping when a line passes over an object.
- Fixed hover preview when referencing a frame by name in an image reference.
- Fixed “Back of note” card insertion breaking LaTeX equations in existing cards. [#2296](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2296) 🙏[@TravisLEBLANC1](https://github.com/TravisLEBLANC1)
- Adjusted hover-preview sizing to more closely match embeds. [#2525](https://github.com/zsviczian/obsidian-excalidraw-plugin/pull/2575) 🙏[parkero](https://github.com/parkero)
`,
"2.18.0":`
## New from Excalidraw.com
- 🔥🔥🔥 New arrow behavior allows binding arrows to the inside of shapes and image! 🙏[mtolmacs](https://github.com/mtolmacs), [dwelle](https://github.com/dwelle) [#9670](https://github.com/excalidraw/excalidraw/pull/9670)
## New
- New option in the Export Dialog to **include/exclude internal links** when exporting to SVG or PDF.
- Useful when sharing an SVG or PDF with others.
- Internal links are links that point to files in your Obsidian vault.
- By default, internal links are included in exports.
- Use the new document property: \`export-internal-links: false\` to disable exporting internal links on a per-drawing basis.
## Fixed
- Memory leak issues
- Potential fix to Backspace and CTRL+V stopping working in text elements after extended use of Excalidraw.
- Improved detection of on-screen keyboard on mobile devices. (issue reported on [Discord](https://discord.com/channels/1026825302900494357/1444652800360316959))
- Insert any file, insert LaTeX and some other dialogs got hidden behind the on-screen keyboard on mobile devices. Dialogs appear at the top of the screen now on mobile devices.
## New in ExcalidrawAutomate
- **createSVG()** now exposes convertMarkdownLinksToObsidianURLs and includeInternalLinks parameters.
\`\`\`ts
async createSVG(
templatePath?: string,
embedFont: boolean = false,
exportSettings?: ExportSettings,
loader?: EmbeddedFilesLoader,
theme?: string,
padding?: number,
convertMarkdownLinksToObsidianURLs: boolean = false,
includeInternalLinks: boolean = true,
): Promise<SVGSVGElement>
\`\`\`
`,
"2.17.2":`
## Fixed
- Lasso selection tool is back in the more tools menu in tray-mode and desktop mode.
- "Toggle enable context menu" command palette action is available on mobile devices.
- FloatingModal window top-right close button did not work on mobile devices.
- Hover preview flashed for larger PDF hover previews, in some cases would not even show.
- Fixed: opanAI API URL in settings will be honored when creating code from diagram [#2540](https://github.com/zsviczian/obsidian-excalidraw-plugin/pull/2540) 🙏[@threeq](https://github.com/threeq)
- Fixed export to PDF. Rounded images cropped from the left and the top were transformed incorrectly. [#2544](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2544)
## New
- Added configurable max tokens setting for OpenAI API [#2543](https://github.com/zsviczian/obsidian-excalidraw-plugin/pull/2543) 🙏[@dddrop](https://github.com/dddrop)
`,
"2.17.1":`
## Fixed
- Excalibrain stopped working after the 2.17.0 update. Fixed. [#2532](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2532)
- Pinned scripts are not hidden in view mode when in phone UI mode.
`,
"2.17.0":`
## New
- Phone UI from Excalidraw.com [#9996](https://github.com/excalidraw/excalidraw/pull/9996)
- Custom pen settings now allow pen width to be set at 0.1 increments from 0.1 to 8.0
- Updated the "Palm Guard" script to support the change UI configurations.
- Restructured UI-Mode settings in plugin settings. You can now set the preference for UI mode for desktop and tablets.
The old "prefer tray-mode" toggle has been removed. "Toggle Tray-Mode" changes to "Toggle UI-Mode".
- New command palette action: "Toggle enable context menu". This setting is helpful on Mobile devices, where the context menu may interfere with touch interactions. The setting is saved with the drawing, thus you can add it to your templates (then press CTRL+S to force save) if you want the context menu to be disabled by default.
## Fixed
- side panel does not attach correctly when library is pinned [#2510](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2510)
- Fixed print area when using marker frames and printing Slideshow to PDF
- The "Invert Colors" script and ExcalidrawAutomate bugs that resulted in broken colors and Excalidraw crashes in some cases after color inversion.
- Fixed duplicated PDF elements after copy-pasting from scene to scene.
- Resolved the large gap at the top on iOS devices. As it turns out, Apple adds additional padding automatically to avoid collision with the notch.
- Fixed the positioning of the "Canvas and Shape Properties" window.
- Attempt to fix the mobile keyboard pop-up, distorting the view.
- Added finalize multipoint-line button to compact layout
`,
"2.16.1":`
## Fixed
- Based on a request from [Kevin](https://github.com/Kovah) referencing GDPR, I removed YouTube iframes from settings, scripts, etc., and replaced them with thumbnail images + links to YouTube. [#2234](https://github.com/zsviczian/obsidian-excalidraw-plugin/discussions/2234)`,
"2.16.0":`
<div class="excalidraw-videoWrapper"><div>
<iframe src="https://www.youtube.com/embed/51EgDgtiZgQ" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div></div>
<div class="excalidraw-videoWrapper">
<a href="https://www.youtube.com/watch?v=51EgDgtiZgQ" target="_blank"><img src ="https://i.ytimg.com/vi/51EgDgtiZgQ/maxresdefault.jpg" style="width:100%;"></a>
</div>
## New from Excalidraw.com
- New library search feature [#9903](https://github.com/excalidraw/excalidraw/pull/9903)
@@ -96,9 +313,9 @@ public getViewCenterPosition(): {x:number, y:number};
\`\`\`
`,
"2.15.0":`
<div class="excalidraw-videoWrapper"><div>
<iframe src="https://www.youtube.com/embed/DqDnzCOoYMc" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div></div>
<div class="excalidraw-videoWrapper">
<a href="https://www.youtube.com/watch?v=DqDnzCOoYMc" target="_blank"><img src ="https://i.ytimg.com/vi/DqDnzCOoYMc/maxresdefault.jpg" style="width:100%;"></a>
</div>
## New
- Introducing **Marker Frames**. These are special frames that can be used to mark slides, pages areas for PDF printouts, image references, etc.
@@ -133,353 +350,4 @@ public getViewCenterPosition(): {x:number, y:number};
):ExcalidrawElement[]
\`\`\`
`,
"2.14.3":`
<div class="excalidraw-videoWrapper"><div>
<iframe src="https://www.youtube.com/embed/29EWeglRm7s" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div></div>
Updated the Printable Layout Wizard script with the option to exclude empty pages.
## Fixed
- If a frame is locked, elements created over the frame or dragged over the frame should not be auto-added to the frame. [#9850](https://github.com/excalidraw/excalidraw/issues/9850)
## Fixed in ExcalidrawAutomate
- Not all AppState properties were being correctly copied to the template when creating a new drawing with ea.create() [#2440](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2440)
`,
"2.14.2":`
## Fixed
- Converting Markdown to Excalidraw ("Back of note"/"Convert markdown to ExcaliDrawing") no longer appends T00:00:00.000Z to an existing date frontmatter field and handles merging of lists such as tags intelligently [#2414](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2414)
- Multi‑point line creation on touchscreens (tap–tap–tap) produced a horizontal line after using a pen. Fixed. [#9840](https://github.com/excalidraw/excalidraw/pull/9840#issuecomment-3165319266)
## New
- Zoom settings (Settings → Excalidraw → Appearance and Behavior → Zoom) [#2434](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2434):
- Zoom increment (default 5%) to fine‑tune mouse wheel / gesture precision.
- Minimum zoom (default 10%) controls how far you can zoom out (below 10% may be unstable—use with caution).
- Maximum zoom (default 3000%) defines the upper zoom limit.
- Palm Guard script (in script store): Mobile-friendly drawing mode for stylus users. Enters fullscreen, hides UI, shows a draggable minimal toolbar (toggle + exit) to prevent accidental palm taps; single tap to exit. Inspired by [#2409](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2409)
<div class="excalidraw-videoWrapper"><div>
<iframe src="https://www.youtube.com/embed/A_udjVjgWN0" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div></div>
## ExcalidrawAutomate
- Improved \`FloatingModal\` behavior. Floating Modal now does not trap keyboard events, the header element does not block "X" button in the top right corner, all four corners are rounded on Mobile Devices.
`,
"2.14.1":`
## Fixed
- Excalidraw broke Obsidian's UI in Arabic, Persian, and Hebrew due to LTR, RTL conflict. [#2423](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2423)
- Styling issues impacting native Obsidian search/replace dialogs. [#2420](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2420)
- Now using native Obsidian attachment location function. 🙏 [mnaoumov](https://github.com/mnaoumov) [#2421](https://github.com/zsviczian/obsidian-excalidraw-plugin/pull/2421), potentially fixes [#179](https://github.com/RainCat1998/obsidian-custom-attachment-location/issues/179) of the Obsidian Custom Attachment Location plugin issue.
## New
- New frontmatter option \`excalidraw-embed-md\`. When set to \`true\`, embedding the drawing into a markdown note will render the "back of the note" (its markdown content) instead of rendering it as an image.
- If you want to always display the drawing as an image, even when \`excalidraw-embed-md\` is enabled, use the special embed syntax: \`![[drawing#^as-image]]\`. Here, \`as-image\` is a phantom block reference that forces image rendering.
- Added Spanish translation by [@Joakim31](https://github.com/Joakim31) [#2425](https://github.com/zsviczian/obsidian-excalidraw-plugin/pull/2425)
- Incremental minor updates from the main [Excalidraw project](https://github.com/excalidraw/excalidraw).
`,
"2.14.0":`
## A Big "Small" Update
- Added search to Excalidraw Settings, plus added a link to access the public NotebookLM workbook pre-loaded with everything about the plugin
- New Taiwan-idiomatic Traditional Chinese translation by [@rlan](https://github.com/rlan) [#2413](https://github.com/zsviczian/obsidian-excalidraw-plugin/pull/2413)
`,
"2.13.2":`
## New
- Excalidraw now properly supports drag and drop of obsidian links from Bases.
- ExcalidrawAutomate exposes a new class: \`FloatingModal\`. This is a modified version of the Obsidian.Modal class that allows the modal to be dragged around the screen and that does not dim the background. You can use it to create custom dialogs that behave like Obsidian modals but with more flexibility.
`,
"2.13.1":`
## New
- Support for Obsidian bases as embeddables in Excalidraw.
- **Note:** The feature is only available to Insiders who have Obsidian 1.9.4 or later installed.
- If your base includes multiple views you can pin the desired view similar to filtering to a section (click top left # button; \`[[my.base|my view]]\`).
## Fixed
- Cannot type in embedded web forms. In certain cases, typing within these embeds would trigger Excalidraw hotkeys instead of interacting with the embedded content. [#2403](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2403)
`,
"2.13.0":`
<div class="excalidraw-videoWrapper"><div>
<iframe src="https://www.youtube.com/embed/QzhyQb4JF3Q" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div></div>
## New
- **Flexible Auto-Export Location:** Take control of where your auto-exported .png, .svg, and .excalidraw files are saved. Addressing a long-standing request, you can now define custom output paths using the new **Excalidraw Hooks**.
- Implement the \`onImageExportPathHook\` callback in your ExcalidrawAutomate startup script to control the *destination path*.
- Get the skeleton script via plugin settings or download it [here](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/refs/heads/master/src/constants/assets/startupScript.md).
- **Control Auto-Export Trigger:** Use the \`onTriggerAutoexportHook\` in your startup script to decide *if* and *how* auto-export runs for a file, based on its properties or frontmatter, *before* the export path is determined.
- **Improved "Open Excalidraw drawing":** The Command Palette command now searches the *entire Vault* for the matching Excalidraw file when used on an embedded .svg or .png, useful when exports are in different folders.
- **Placeholder Files for New Embeds:** When embedding a new drawing as PNG/SVG via the Command Palette, empty placeholder files are now created immediately based on your auto-export setting. This ensures Obsidian correctly updates links if you rename the file soon after creation (when "Keep filenames in sync" is on).
- **Paste Obsidian URLs into Excalidraw:** Pasting an Obsidian URL for an image or file into Excalidraw now inserts the associated image directly into the drawing.
- **\`onImageFilePathHook\` Drag & Drop Support:** The \`onImageFilePathHook\` (for controlling location/filename of *embedded* files) is now triggered when dragging and dropping files into Excalidraw from outside Obsidian, matching the existing behavior for pasting.
## New in ExcalidrawAutomate
\`\`\`ts
splitFolderAndFilename(filepath: string) : {
folderpath: string;
filename: string;
basename: string;
extension: string;
}
\`\`\`
`,
"2.12.4":`
## Fixed
- ExaliBrain did not render after the 2.12.3 update. [#2384](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2384)
`,
"2.12.3":`
## Minor fixes
- Includes all recent updates and fixes from excalidraw.com
- Fixed issue with line editor snapping out of edit mode
- Fixed long-standing issue with wireframe to code calling a deprecated OpenAI endpoint
- "Load Excalidraw Properties into Obsidian Suggester" setting now defaults to false for new installations. [#2380](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2380)
- Taskbone OCR result does not get saved to frontmatter in some cases [#1123](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/1123)
## New
- If the cropped file or annotated file prefix is set to empty, there will now be no prefix added to the file name. Additionally, now you can also set a suffix to the file name. [#2370](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2370)
`,
"2.12.2": `
## Fixed
- BUG: Excalidraw theme changes to Light from Dark when clicking line element node [#2360](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2360)
`,
"2.12.1": `
## New
- "Text to Path" text input window is now draggable.
## Fixed
- Minor fixes to the Polygon line feature introduced in 2.12.0. [#9580](https://github.com/excalidraw/excalidraw/pull/9580)
- Fix new Improved Unlock UI, where if a lock element was over an unlocked element, the unlocked element was not selectable. [#9582](https://github.com/excalidraw/excalidraw/pull/9582)
- Fixed ghost point issue when moving a shape after dragging a point in the line editor [#9530](https://github.com/excalidraw/excalidraw/pull/9530)
## New in ExcalidrawAutomate
${String.fromCharCode(96,96,96)}js
untils.inputPrompt({
header: string,
placeholder?: string,
value?: string,
buttons?: { caption: string; tooltip?:string; action: Function }[],
lines?: number,
displayEditorButtons?: boolean,
customComponents?: (container: HTMLElement) => void,
blockPointerInputOutsideModal?: boolean,
controlsOnTop?: boolean,
draggable?: boolean,
});
${String.fromCharCode(96,96,96)}
`,
"2.12.0": `
<div class="excalidraw-videoWrapper"><div>
<iframe src="https://www.youtube.com/embed/-fldh3cE2gs" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div></div>
## Fixed
- Dynamic styling was not working when frames were present in the scene.
- Minor fix to the screenshot feature. This also resolves the long-standing issue where window control buttons (close, minimize, maximize) appeared in full-screen mode.
- Fixed an issue where ALT/OPT + dragging an embeddable object sometimes failed, resulting in an empty object instead of dragging the element.
## New
- **Line Polygons**: Draw a closed line shape, and it will automatically snap into a polygon. [#9477](https://github.com/excalidraw/excalidraw/pull/9477)
- Updated the Split Ellipse and Boolean Operations scripts to support this feature.
- When entering line editor mode (CTRL/CMD + click), the lock point is now marked for easier editing. You can break the polygon using the polygon action in the elements panel.
- **Popout Override**: The "Open the back-of-the-note for the selected image in a popout window" action now overrides the "Focus on Existing Tab" setting and always opens a new popout.
- **Text Arch Enhancements**: The Text Arch script now supports fitting text to a wider range of paths and shapes. Text can also be edited and refitted to different paths.
- **Improved Unlock UI**: Single-clicking a locked element now shows an unlock button. [#9546](https://github.com/excalidraw/excalidraw/pull/9546)
- **Script Update Alerts**: On startup, Excalidraw will notify you if any installed scripts have available updates.
`,
"2.11.1": `
## Fixed:
- The new "Screenshot" option in the Export Image dialog was not working properly. [#2339](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2339)
## New from Excalidraw.com
- Quarter snap points for diamonds [#9387](https://github.com/excalidraw/excalidraw/pull/9387)
- Precise highlights for bindings [#9472](https://github.com/excalidraw/excalidraw/pull/9472)
`,
"2.11.0": `
## New
- New "Screenshot" option in the Export Image dialog. This allows you to take a screenshot of the current view, including embedded web pages, youtube videos, and markdown documents. Screenshot is only possible in PNG.
- Expose parameter in plugin settings to disable AI functionality [#2325](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2325)
- Enable (disable) double-click text editing option in Excalidraw appearance and behavior (based on request on Discord)
- Added two new PDF export sizes: "Match image", "HD Screen".
- Switch between basic shapes. Quickly change the shape of the selected element by pressing TAB [#9270](https://github.com/excalidraw/excalidraw/pull/9270)
- Updated the Scribble Helper Script. Now controls are at the top so your palm does accidently trigger them. I added a new button to insert special characters. Scribble helper now makes use of the new text element wrapping in Excalidraw.
## Fixed in the plugin
- Scaling multiple embeddables at once did not work. [#2276](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2276)
- When creating multiple back-of-the-note the second card is not created correctly if autosave has not yet happened.
- Drawing reloads while editing the back-of-the-note card in certain cases causes editing to be interrupted.
- Moved Excalidraw filetype indicator ✏️ to after filename where other filetype tags are displayed. You can turn the filetype indicator on/off in plugin settings under Miscellaneous.
## Fixed by Excalidraw.com
- Alt-duplicate now preserves the original element. Previously, using Alt to duplicate would swap the original with the new element, leading to unexpected behavior and several downstream issues. [#9403](https://github.com/excalidraw/excalidraw/pull/9403)
- When dragging the arrow endpoint, update the binding only on the dragged side [#9367](https://github.com/excalidraw/excalidraw/pull/9367)
- Laser pointer trail disappearing on pointerup [#9413](https://github.com/excalidraw/excalidraw/pull/9413) [#9427](https://github.com/excalidraw/excalidraw/pull/9427)
`,
"2.10.1": `
## Fixed by Excalidraw.com
- Eraser performance improvement regression. Erasing locked elements. [#9400](https://github.com/excalidraw/excalidraw/pull/9400)
## New
- Grid Customization Options in plugin settings (appearance and behavior/grid): You can now selectively show or hide vertical and horizontal grid lines independently. This allows you to create alternative grid styles, such as horizontal-only lined grids instead of the traditional checkered pattern.
## Fixed in ExcalidrawAutomate
- ${String.fromCharCode(96)}ea.createSVG${String.fromCharCode(96)} throws error [#2321](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2321)
---
## ❤️ Enjoying the plugin?
Support my work by checking out my new book, now available for pre-order:
[Sketch Your Mind: Nurture a Playful and Creative Brain](https://sketch-your-mind.com) is about visual Personal Knowledge Management. It explores the thinking behind Excalidraw and how it helps you structure and evolve ideas visually. It’s the book I wish I had when I began my own PKM journey.
<div class="ex-coffee-div"><a href="https://sketch-your-mind.com"><img src="https://raw.githubusercontent.com/zsviczian/sketch-your-mind/refs/heads/main/images/cover-mini.jpg" border="0" alt="Pre-order Sketch Your Mind" height="100%"></a></div>
`,
"2.10.0": `
## New from Excalidraw.com
- Lasso select [#9169](https://github.com/excalidraw/excalidraw/pull/9169)
- Add container to multiple text elements [#9348](https://github.com/excalidraw/excalidraw/pull/9348)
## Fixed from Excalidraw.com
- Rounded diamond edge elbow arrow U route [#9349](https://github.com/excalidraw/excalidraw/pull/9349)
- Improved eraser performance [#9352](https://github.com/excalidraw/excalidraw/pull/9352)
- Keep arrow label horizontal [#9364](https://github.com/excalidraw/excalidraw/pull/9364)
## Fixed in ExcalidrawAutomate
- ${String.fromCharCode(96)}ea.addText${String.fromCharCode(96)} did not honor the width parameter.
`,
"2.9.2":`
- More minor fix. Toolbars are not responsive when dynamic styling is turned off. [#2287](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2287)
`,
"2.9.1":`
- Minor emergency fix. Reverting: [#9203](https://github.com/excalidraw/excalidraw/pull/9203)
`,
"2.9.0":`
## New
- QoL improvement: The context menu requires a longer press and hold for it to be displayed on mobile devices. When you want to precision adjust an element it happens that you linger on the point for just a little longer and the context menu appears unwantedly.
- Elbow arrow improvements [#9236](https://github.com/excalidraw/excalidraw/pull/9236), [#8593](https://github.com/excalidraw/excalidraw/pull/8593), [#9197](https://github.com/excalidraw/excalidraw/pull/9197), [#9191](https://github.com/excalidraw/excalidraw/pull/9191), [#9236](https://github.com/excalidraw/excalidraw/pull/9236)
## Fixed Obsidian 1.8.9 regressions
- Custom references (like #^group) broken in Live Preview in Obsidian 1.8.9 due to translation update [#2279](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2279)
- Excalidraw tabs only show on a second click on Obsidian Mobile
## Refactoring
- The Excalidraw component moved to React 19. Obsidian for now remains on React 18. This refactoring ensures that Excalidraw continues to work in Obsidian and Obsidian will receive future Excalidraw updates. [#9182](https://github.com/excalidraw/excalidraw/pull/9182)
`,
"2.8.3":`
## Fixed
- Chinese translation not available since 2.8.0. [#2247](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2247)
- Since the most recent Samsung Android update, adding images from the gallery returns an Unsupported Image Type error. [#2245](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2245)
- Duplicating/removing frame while children selected [#9079](https://github.com/excalidraw/excalidraw/pull/9079)
`,
"2.8.2":`
## New
- Moved "Create new drawing" option up in the context menu [#2243](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2243)
## Fixed
- In rare cases drawing content gets overwritten with another drawing [#2152](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2152)
- "Wrap selection in frame" sets dark mode to light mode [#2240](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2240)
- Multiple bug fixes from Excalidraw.com
- Elbow arrows within boxes [#9077](https://github.com/excalidraw/excalidraw/issues/9077)
- Elbow arrow orthogonality [#9073](https://github.com/excalidraw/excalidraw/pull/9073)
- Improve library sidebar performance [#9060](https://github.com/excalidraw/excalidraw/pull/9060)
- Opacity slider now displays numerical value [#9009](https://github.com/excalidraw/excalidraw/pull/9009)
- Resize a frame and its children together when box selecting the frame and its children together [#9031](https://github.com/excalidraw/excalidraw/pull/9031)
- Excalidraw screen flickering in dark mode [#9057](https://github.com/excalidraw/excalidraw/pull/9057)
`,
"2.8.1":`
## Fixed
- Unable to open Excalidraw files after the 2.8.0 update. [#2235](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2235)
`,
"2.8.0":`
<div class="excalidraw-videoWrapper"><div>
<iframe src="https://www.youtube.com/embed/tWi5xTUTz7E" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div></div>
## New
- Updated "Export Image" dialog
- 🚀 PDF Export option including tiling of images over multiple pages. Only available on desktop :(
- SVG to clipboard
- More granular setting for padding and scale
- Slideshow script can now print slides to PDF (update script from script store)
- Set local graph to show the links in the embeddable when it is activated/deactivated [#2200](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2200)
## Fixed
- Fixed several LaTeX issues. 🙏 @Sintuz [#1631](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/1631), [#2195](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2195), [#1842](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/1842)
- Fixed support for *.jfif and *.avif images [#2212](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2212)
- PDF++ selection is not correctly showing after embedded into a drawing (for some specific files) [#2213](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2213)
- iOS 18 can't upload image and library [#2182](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2182)
- Image block references are broken in hover previews [#2218](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2218)
- ⚠️ Note there is a known issue in Obsidian 1.8.2 ⚠️ affecting preview windows in Excalidraw. I received confirmation that this will be fixed in 1.8.3. For now, if hover previews are important to you, you can downgrade to Obsidian 1.8.1 [#2228](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2225)
- Mobile elements panel and context menu are not scrollable [#2216](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2216)
- "Local Font" menu disappears when opening a drawing in an Obsidian popout-window [#2205](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2205)
## Updates from Excalidraw.com
- Pressing delete on a frame will only delete the children [#9011](https://github.com/excalidraw/excalidraw/pull/9011)
- New crowfoot arrowheads and a new arrowhead picker [#8942](https://github.com/excalidraw/excalidraw/pull/8942)
- Fixed some of the arrow binding issues [#9010](https://github.com/excalidraw/excalidraw/pull/9010), [#2209](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2209)
- New context menu action: "Wrap selection in frame" [#9005](https://github.com/excalidraw/excalidraw/pull/9005)
- Elbow arrow segment fixing and positioning [#8952](https://github.com/excalidraw/excalidraw/pull/8952)
- When drag creating a new frame, do not add a partial group to it. When wrapping a selected partial group in a frame however, do add it to the wrapping frame. But such that it should be separated from the previous containing group. [#9014](https://github.com/excalidraw/excalidraw/pull/9014)
## New in ExcalidrawAutomate
- New hook: ${String.fromCharCode(96)}onImageFileNameHook${String.fromCharCode(96)}. When set, this callback is triggered when a image is being saved in Excalidraw.
- PDF export functions, paving the way for slideshow to export slides to PDF
${String.fromCharCode(96,96,96)}ts
/**
* Returns the dimensions of a standard page size in pixels.
*/
function getPagePDFDimensions(
pageSize: PageSize,
orientation: PageOrientation
): PageDimensions;
/**
* Creates a PDF from the provided SVG elements with specified scaling and page properties.
*/
function createPDF(props: {
SVG: SVGSVGElement[];
scale?: PDFExportScale;
pageProps?: PDFPageProperties;
filename: string;
}): Promise<void>;
/**
* Creates an SVG representation of the current view.
*/
function createViewSVG(props : {
withBackground?: boolean;
theme?: "light" | "dark";
frameRendering?: FrameRenderingOptions;
padding?: number;
selectedOnly?: boolean;
skipInliningFonts?: boolean;
embedScene?: boolean;
}): Promise<SVGSVGElement>;
/**
* If set, this callback is triggered when a image is being saved in Excalidraw.
* You can use this callback to customize the naming and path of pasted images to avoid
* default names like "Pasted image 123147170.png" being saved in the attachments folder,
* and instead use more meaningful names based on the Excalidraw file or other criteria,
* plus save the image in a different folder.
*
* If the function returns null or undefined, the normal Excalidraw operation will continue
* with the excalidraw generated name and default path.
* If a filepath is returned, that will be used. Include the full Vault filepath and filename
* with the file extension.
* The currentImageName is the name of the image generated by excalidraw or provided during paste.
*/
function onImageFilePathHook: (data: {
currentImageName: string;
drawingFilePath: string;
}) => string = null;
${String.fromCharCode(96,96,96)}
`,
};
@@ -1,5 +1,5 @@
import { Setting } from "obsidian";
import { PageOrientation, PageSize, PDFPageAlignment, PDFPageMarginString, STANDARD_PAGE_SIZES } from "src/utils/exportUtils";
import { PageOrientation, PageSize, PDFPageAlignment, PDFPageMarginString, STANDARD_PAGE_SIZES } from "src/types/exportUtilTypes";
import { t } from "src/lang/helpers";
export interface PDFExportSettings {
+44 -11
View File
@@ -9,6 +9,7 @@ import { getExcalidrawViews } from "src/utils/obsidianUtils";
import { PENS } from "src/utils/pens";
import { fragWithHTML } from "src/utils/utils";
import { __values } from "tslib";
import { showColorPicker } from "./ColorPicker";
const EASINGFUNCTIONS: Record<string,string> = {
linear: "linear",
@@ -55,7 +56,6 @@ export class PenSettingsModal extends Modal {
) {
super(plugin.app);
this.api = view.excalidrawAPI;
}
onOpen(): void {
@@ -66,8 +66,8 @@ export class PenSettingsModal extends Modal {
async onClose() {
if(this.dirty) {
await this.plugin.saveSettings();
getExcalidrawViews(this.app).forEach(excalidrawView=>excalidrawView.updatePinnedCustomPens());
this.plugin.saveSettings();
const pen = this.plugin.settings.customPens[this.pen]
const api = this.view.excalidrawAPI;
setPen(pen,api);
@@ -157,6 +157,7 @@ export class PenSettingsModal extends Modal {
let scSetting: Setting;
let sccpComponent: ColorComponent;
let sctComponent: TextComponent;
let strokeUseCurrentToggle: ToggleComponent;
let strokeSetting: Setting;
let [sHex, sOpacity] = hexColor(ps.strokeColor);
let sChangeBounce:boolean = false;
@@ -164,7 +165,8 @@ export class PenSettingsModal extends Modal {
strokeSetting = new Setting(ce)
.setName(fragWithHTML(!Boolean(ps.strokeColor) ? "Stroke color: <b>Current</b>" : "Stroke color: <b>Preset color</b>"))
.setDesc(fragWithHTML("Use <b>current</b> stroke color of the canvas, or set a specific <b>preset color</b> for the pen"))
.addToggle(toggle =>
.addToggle(toggle => {
strokeUseCurrentToggle = toggle;
toggle
.setValue(!Boolean(ps.strokeColor))
.onChange(value=> {
@@ -181,8 +183,8 @@ export class PenSettingsModal extends Modal {
}
ps.strokeColor = sctComponent.getValue();
}
})
)
});
})
scSetting = new Setting(ce)
.setName("Select stroke color")
@@ -225,8 +227,22 @@ export class PenSettingsModal extends Modal {
ps.strokeColor = value + sOpacity;
sctComponent.setValue(value + sOpacity);
})
}
}
)
.addButton(button => {
button
.setIcon("swatch-book")
.onClick(async () => {
const selected = await showColorPicker("elementStroke", button.buttonEl, this.view, true);
if(!selected) {return;}
strokeUseCurrentToggle?.setValue(false);
sChangeBounce = true;
[sHex, sOpacity] = hexColor(selected);
ps.strokeColor = selected;
sctComponent.setValue(selected);
if(sHex) {sccpComponent.setValue(sHex);}
});
})
scSetting.settingEl.style.display = !Boolean(ps.strokeColor) ? "none" : "";
@@ -236,13 +252,15 @@ export class PenSettingsModal extends Modal {
let bgcpComponent: ColorComponent;
let bgctComponent: TextComponent;
let bgtComponent: ToggleComponent;
let bgUseCurrentToggle: ToggleComponent;
let fsSetting: Setting;
let [bgHex, bgOpacity] = hexColor(ps.backgroundColor);
bgSetting = new Setting(ce)
.setName(fragWithHTML(!Boolean(ps.backgroundColor) ? "Background color: <b>Current</b>" : "Background color: <b>Preset color</b>"))
.setDesc(fragWithHTML("Toggle to use the <b>current background color</b> of the canvas; or a <b>preset color</b>"))
.addToggle(toggle =>
.addToggle(toggle => {
bgUseCurrentToggle = toggle;
toggle
.setValue(!Boolean(ps.backgroundColor))
.onChange(value=> {
@@ -260,8 +278,8 @@ export class PenSettingsModal extends Modal {
}
bgtComponent.setValue(false);
}
})
)
});
})
bgctSetting = new Setting(ce)
@@ -325,6 +343,21 @@ export class PenSettingsModal extends Modal {
bgctComponent.setValue(value+bgOpacity)
})
})
.addButton(button => {
button
.setIcon("swatch-book")
.onClick(async () => {
const selected = await showColorPicker("elementBackground", button.buttonEl, this.view, true);
if(!selected) {return;}
bgUseCurrentToggle?.setValue(false);
bgtComponent?.setValue(false);
bgChangeBounce = true;
[bgHex, bgOpacity] = hexColor(selected);
ps.backgroundColor = selected;
bgctComponent.setValue(selected);
if(bgHex) {bgcpComponent.setValue(bgHex);}
});
})
bgcSetting.settingEl.style.display = (!Boolean(ps.backgroundColor) || ps.backgroundColor==="transparent") ? "none" : "";
@@ -369,7 +402,7 @@ export class PenSettingsModal extends Modal {
.setName(fragWithHTML(`Stroke Width <b>${ps.strokeWidth === 0 ? "Not Set" : ps.strokeWidth}</b>`))
.addSlider(slider =>
slider
.setLimits(0,5,0.5)
.setLimits(0.1,8,0.1)
.setValue(ps.strokeWidth)
.onChange(value => {
this.dirty = true;
@@ -421,7 +454,7 @@ export class PenSettingsModal extends Modal {
.setDesc("If the stroke has an outline, this will mean the stroke color is the outline color, and the background color is the pen stroke's fill color. If the pen does not have an outline then the pen color is the stroke color. The Fill Style setting applies to the fill style of the enclosed shape, not of the line itself. The line can only have solid fill.")
.addSlider(slider =>
slider
.setLimits(0,8,0.5)
.setLimits(0,8,0.1)
.setValue(ps.penOptions.outlineWidth)
.onChange(value => {
this.dirty = true;
+233 -51
View File
@@ -8,6 +8,7 @@ import {
TFile,
Notice,
TextAreaComponent,
getIcon,
} from "obsidian";
import ExcalidrawView from "../../view/ExcalidrawView";
import ExcalidrawPlugin from "../../core/main";
@@ -23,6 +24,11 @@ import { REGEX_LINK, REGEX_TAGS } from "../ExcalidrawData";
import { ScriptEngine } from "../Scripts";
import { openExternalLink, openTagSearch, parseObsidianLink } from "src/utils/excalidrawViewUtils";
import { ButtonDefinition } from "src/types/promptTypes";
import { EditorView, keymap } from "@codemirror/view";
import { history } from "@codemirror/commands";
import { parser } from "./math-only";
import { LRLanguage } from "@codemirror/language";
import { editorLivePreviewField } from "obsidian";
export class Prompt extends Modal {
private promptEl: HTMLInputElement;
@@ -79,6 +85,149 @@ export class Prompt extends Modal {
}
}
export class LaTexPrompt extends Modal {
public waitForClose : Promise<string>;
private promptEl: HTMLInputElement;
private resolvePromise: (input: string) => void;
private rejectPromise: (reason?: any) => void;
private editorView : EditorView;
private latexsSuitePlugin : any;
protected constructor(
app: App,
private prompt_text: string,
private default_value?: string,
) {
super(app);
this.titleEl.setText(this.prompt_text);
this.contentEl.addClass("excalidraw-LatexPrompt");
this.latexsSuitePlugin = app.plugins.plugins["obsidian-latex-suite"];
const mainContentContainer: HTMLDivElement = this.contentEl.createDiv();
this.display(default_value, mainContentContainer);
this.waitForClose = new Promise<string>((resolve, reject) => {
this.resolvePromise = resolve;
this.rejectPromise = reject;
});
this.editorView.focus();
}
public static Prompt(app: App,
prompt_text?: string,
default_value?: string,
): Promise<string>{
const latexprompt = new LaTexPrompt(app, prompt_text, default_value);
return latexprompt.waitForClose;
}
private display(value : string, container : HTMLDivElement) {
if (this.latexsSuitePlugin) {
// the language put eveything in a "math" node
// surrounded by "math-begin" and "math-end"
// so that latex-suite always thinks we are in mathmode
const language = LRLanguage.define({parser:parser});
const extensions = [
language,
keymap.of([{
key:"Mod-Enter",
run : () => {this.submitCallback(); return true;}
}]),
history(),
editorLivePreviewField.init(() => false),
... this.latexsSuitePlugin.editorExtensions
];
this.editorView = new EditorView({
doc: value,
parent : container,
extensions : extensions,
});
} else {
const extensions = [
keymap.of([{
key:"Mod-Enter",
run : () => {this.submitCallback(); return true;}
}]),
history(),
];
this.editorView = new EditorView({
doc: value,
extensions : extensions,
parent : container,
});
}
const buttonBarContainer: HTMLDivElement = container.createDiv();
buttonBarContainer.addClass(`excalidraw-prompt-buttonbar-bottom`);
const actionButtonContainer: HTMLDivElement = buttonBarContainer.createDiv();
this.createButton(
actionButtonContainer,
"",
this.submitCallback.bind(this),
t("PROMPT_BUTTON_OK") ?? "",
undefined,
"check"
).setCta().buttonEl.style.marginRight = "0";
this.createButton(
actionButtonContainer,
"",
this.cancelCallback.bind(this),
t("PROMPT_BUTTON_CANCEL"),
undefined,
"x"
);
this.open();
}
private createButton(container: HTMLElement,
text: string,
callback: (evt: MouseEvent) => any,
tooltip: string = "",
margin: string = "5px",
iconId?:string,
){
const btn = new ButtonComponent(container);
btn.buttonEl.style.padding = "0.5em";
btn.buttonEl.style.marginLeft = margin;
btn.setTooltip(tooltip);
if (iconId) {
btn.setIcon(iconId);
} else {
btn.setButtonText(text);
}
btn.onClick(callback);
return btn;
}
private submitCallback(){
const res = this.editorView.state.doc.toString();
if (res.trim().length == 0) {
this.rejectPromise("empty latex");
} else {
this.resolvePromise(res);
}
this.close();
}
private cancelCallback(){
this.rejectPromise("Canceled input");
this.close();
}
onOpen(): void {
super.onOpen();
this.editorView.focus();
}
onClose(): void {
this.contentEl.empty();
this.editorView.destroy();
}
}
export class GenericInputPrompt extends Modal {
public waitForClose: Promise<string>;
private view: ExcalidrawView;
@@ -101,6 +250,26 @@ export class GenericInputPrompt extends Modal {
private draggable: boolean = false;
private cleanupDragListeners: (() => void) | null = null;
// Add event handler instance properties
private handleKeyDown = (evt: KeyboardEvent) => {
if ((evt.key === "Enter" && this.lines === 1) || (isWinCTRLorMacCMD(evt) && evt.key === "Enter")) {
evt.preventDefault();
this.submit();
}
if (this.displayEditorButtons && evt.key === "k" && isWinCTRLorMacCMD(evt)) {
evt.preventDefault();
this.linkBtnClickCallback();
}
};
private handleCheckCaret = () => {
//timer is implemented because on iPad with pencil the button click generates an event on the textarea
this.selectionUpdateTimer = this.view.ownerWindow.setTimeout(() => {
this.selectionStart = this.inputComponent.inputEl.selectionStart;
this.selectionEnd = this.inputComponent.inputEl.selectionEnd;
}, 30);
};
public static Prompt(
view: ExcalidrawView,
plugin: ExcalidrawPlugin,
@@ -141,7 +310,7 @@ export class GenericInputPrompt extends Modal {
private header: string,
placeholder?: string,
value?: string,
buttons?: { caption: string; action: Function }[],
buttons?: ButtonDefinition[],
lines?: number,
displayEditorButtons?: boolean,
customComponents?: (container: HTMLElement) => void,
@@ -226,25 +395,15 @@ export class GenericInputPrompt extends Modal {
.setValue(value ?? "")
.onChange((value) => (this.input = value));
let i = 0;
const checkcaret = () => {
//timer is implemented because on iPad with pencil the button click generates an event on the textarea
this.selectionUpdateTimer = this.view.ownerWindow.setTimeout(() => {
this.selectionStart = this.inputComponent.inputEl.selectionStart;
this.selectionEnd = this.inputComponent.inputEl.selectionEnd;
}, 30);
}
textComponent.inputEl.addEventListener("keydown", this.keyDownCallback.bind(this));
textComponent.inputEl.addEventListener('keyup', checkcaret.bind(this)); // Every character written
textComponent.inputEl.addEventListener('pointerup', checkcaret.bind(this)); // Click down
textComponent.inputEl.addEventListener('touchend', checkcaret.bind(this)); // Click down
textComponent.inputEl.addEventListener('input', checkcaret.bind(this)); // Other input events
textComponent.inputEl.addEventListener('paste', checkcaret.bind(this)); // Clipboard actions
textComponent.inputEl.addEventListener('cut', checkcaret.bind(this));
textComponent.inputEl.addEventListener('select', checkcaret.bind(this)); // Some browsers support this event
textComponent.inputEl.addEventListener('selectionchange', checkcaret.bind(this));// Some browsers support this event
textComponent.inputEl.addEventListener("keydown", this.handleKeyDown);
textComponent.inputEl.addEventListener('keyup', this.handleCheckCaret);
textComponent.inputEl.addEventListener('pointerup', this.handleCheckCaret);
textComponent.inputEl.addEventListener('touchend', this.handleCheckCaret);
textComponent.inputEl.addEventListener('input', this.handleCheckCaret);
textComponent.inputEl.addEventListener('paste', this.handleCheckCaret);
textComponent.inputEl.addEventListener('cut', this.handleCheckCaret);
textComponent.inputEl.addEventListener('select', this.handleCheckCaret);
textComponent.inputEl.addEventListener('selectionchange', this.handleCheckCaret);
return textComponent;
}
@@ -255,12 +414,20 @@ export class GenericInputPrompt extends Modal {
callback: (evt: MouseEvent) => any,
tooltip: string = "",
margin: string = "5px",
iconId?:string,
) {
const btn = new ButtonComponent(container);
btn.buttonEl.style.padding = "0.5em";
btn.buttonEl.style.marginLeft = margin;
btn.setTooltip(tooltip);
btn.setButtonText(text).onClick(callback);
if (iconId) {
btn.setIcon(iconId);
} else {
btn.setButtonText(text);
}
btn.onClick(callback);
return btn;
}
@@ -276,13 +443,17 @@ export class GenericInputPrompt extends Modal {
const btn = new ButtonComponent(actionButtonContainer);
btn.buttonEl.style.marginLeft="5px";
if(button.tooltip) btn.setTooltip(button.tooltip);
btn.setButtonText(button.caption).onClick((evt: MouseEvent) => {
const res = button.action(this.input);
if (res) {
this.input = res;
}
this.submit();
});
button.iconId
? btn.setIcon(button.iconId)
: btn.setButtonText(button.caption);
button.tooltip && btn.setTooltip(button.tooltip);
btn.onClick((evt: MouseEvent) => {
const res = button.action(this.input);
if (res) {
this.input = res;
}
this.submit();
});
b = b ?? btn;
}
if (b) {
@@ -292,20 +463,32 @@ export class GenericInputPrompt extends Modal {
} else {
this.createButton(
actionButtonContainer,
"✅",
"",
this.submitClickCallback.bind(this),
t("PROMPT_BUTTON_OK") ?? "",
"5px",
"check",
).setCta().buttonEl.style.marginRight = "0";
}
this.createButton(actionButtonContainer, "❌", this.cancelClickCallback.bind(this), t("PROMPT_BUTTON_CANCEL"));
this.createButton(
actionButtonContainer,
"",
this.cancelClickCallback.bind(this),
t("PROMPT_BUTTON_CANCEL"),
"5px",
"x",
);
if(this.displayEditorButtons) {
this.createButton(editorButtonContainer, "⏎", ()=>this.insertStringBtnClickCallback("\n"), t("PROMPT_BUTTON_INSERT_LINE"), "0");
this.createButton(editorButtonContainer, "⌫", this.delBtnClickCallback.bind(this), "Delete");
this.createButton(editorButtonContainer, "⎵", ()=>this.insertStringBtnClickCallback(" "), t("PROMPT_BUTTON_INSERT_SPACE"));
this.createButton(editorButtonContainer, "§", this.specialCharsBtnClickCallback.bind(this), t("PROMPT_BUTTON_SPECIAL_CHARS"));
this.createButton(editorButtonContainer, "", ()=>this.insertStringBtnClickCallback("\n"), t("PROMPT_BUTTON_INSERT_LINE"), "0", "corner-down-left");
this.createButton(editorButtonContainer, "", this.delBtnClickCallback.bind(this), "Delete", "5px", "delete");
this.createButton(editorButtonContainer, "", ()=>this.insertStringBtnClickCallback(" "), t("PROMPT_BUTTON_INSERT_SPACE"), "5px", "space");
this.createButton(editorButtonContainer, "", this.specialCharsBtnClickCallback.bind(this), t("PROMPT_BUTTON_SPECIAL_CHARS"), "5px", "at-sign");
if(this.view) {
this.createButton(editorButtonContainer, "🔗", this.linkBtnClickCallback.bind(this), t("PROMPT_BUTTON_INSERT_LINK"));
this.createButton(editorButtonContainer, "", this.linkBtnClickCallback.bind(this), t("PROMPT_BUTTON_INSERT_LINK"), "5px", "link");
}
this.createButton(editorButtonContainer, "🔠", this.uppercaseBtnClickCallback.bind(this), t("PROMPT_BUTTON_UPPERCASE"));
this.createButton(editorButtonContainer, "", this.uppercaseBtnClickCallback.bind(this), t("PROMPT_BUTTON_UPPERCASE"), "5px", "arrow-big-up");
}
}
@@ -372,17 +555,6 @@ export class GenericInputPrompt extends Modal {
this.cancel();
}
private keyDownCallback = (evt: KeyboardEvent) => {
if ((evt.key === "Enter" && this.lines === 1) || (isWinCTRLorMacCMD(evt) && evt.key === "Enter")) {
evt.preventDefault();
this.submit();
}
if (this.displayEditorButtons && evt.key === "k" && isWinCTRLorMacCMD(evt)) {
evt.preventDefault();
this.linkBtnClickCallback();
}
};
private submit() {
this.didSubmit = true;
this.close();
@@ -401,10 +573,18 @@ export class GenericInputPrompt extends Modal {
}
private removeInputListener() {
this.inputComponent?.inputEl?.removeEventListener(
"keydown",
this.keyDownCallback,
);
if (!this.inputComponent?.inputEl) return;
const inputEl = this.inputComponent.inputEl;
inputEl.removeEventListener("keydown", this.handleKeyDown);
inputEl.removeEventListener('keyup', this.handleCheckCaret);
inputEl.removeEventListener('pointerup', this.handleCheckCaret);
inputEl.removeEventListener('touchend', this.handleCheckCaret);
inputEl.removeEventListener('input', this.handleCheckCaret);
inputEl.removeEventListener('paste', this.handleCheckCaret);
inputEl.removeEventListener('cut', this.handleCheckCaret);
inputEl.removeEventListener('select', this.handleCheckCaret);
inputEl.removeEventListener('selectionchange', this.handleCheckCaret);
}
private specialCharsBtnClickCallback = (evt: MouseEvent) => {
@@ -477,6 +657,8 @@ export class GenericInputPrompt extends Modal {
onOpen() {
super.onOpen();
this.modalEl.classList.add("excalidraw-modal");
this.containerEl.classList.add("excalidraw-modal");
this.inputComponent.inputEl.focus();
this.inputComponent.inputEl.select();
+2 -2
View File
@@ -1,7 +1,7 @@
import { Modal, Setting, TFile } from "obsidian";
import ExcalidrawPlugin from "src/core/main";
import { getIMGFilename } from "src/utils/fileUtils";
import { addIframe } from "src/utils/utils";
import { addYouTubeThumbnail } from "src/utils/utils";
const haveLinkedFilesChanged = (depth: number, mtime: number, path: string, sourceList: Set<string>, plugin: ExcalidrawPlugin):boolean => {
if(depth++ > 5) return false;
@@ -67,7 +67,7 @@ export class PublishOutOfDateFilesDialog extends Modal {
text: "Video about Obsidian Publish support",
});
detailsEl.createEl("br");
addIframe(detailsEl, "JC1E-jeiWhI");
addYouTubeThumbnail(detailsEl, "JC1E-jeiWhI");
const p = this.contentEl.createEl("p",{text: "Collecting data..."});
const statusEl = this.contentEl.createEl("p", {text: "Status: "});
const files = await listOfOutOfSyncImgExports(this.plugin, recursive, statusEl);
+148 -11
View File
@@ -202,6 +202,22 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
desc: "Get single element from ExcalidrawAutomate elementsDict",
after: "",
},
{
field: "getBoundTextElement",
code:
"getBoundTextElement(element: ExcalidrawElement, searchInView?: boolean): { eaElement?: Mutable<ExcalidrawTextElement>; sceneElement?: ExcalidrawTextElement; };",
desc:
"Returns an object describing the bound text element.\n" +
"If a text element is provided:\n" +
" - returns { eaElement } if the element is in ea.elementsDict\n" +
" - else (if searchInView is true) returns { sceneElement } if found in the targetView scene\n" +
"If a container element is provided, searches for the bound text element:\n" +
" - returns { eaElement } if found in ea.elementsDict\n" +
" - else (if searchInView is true) returns { sceneElement } if found in the targetView scene\n" +
"If not found, returns {}.\n" +
"Does not add the text element to elementsDict.",
after: "",
},
{
field: "create",
code: 'async create(params?: {filename?: string, foldername?: string, templatePath?: string, onNewPane?: boolean, silent?: boolean, frontmatterKeys?: {},}): Promise<string>;',
@@ -221,12 +237,13 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
' "excalidraw-linkbutton-opacity"?: number;\n' +
' "excalidraw-autoexport"?: boolean;\n' +
' "excalidraw-mask"?: boolean;\n' +
' "excalidraw-export-internal-links"?: boolean;\n' +
' "cssclasses"?: string;\n}',
after: "",
},
{
field: "createSVG",
code: "async createSVG(templatePath?: string, embedFont?: boolean, exportSettings?: ExportSettings, loader?: EmbeddedFilesLoader, theme?: string,): Promise<SVGSVGElement>;",
code: "async createSVG(templatePath?: string, embedFont?: boolean, exportSettings?: ExportSettings, loader?: EmbeddedFilesLoader, theme?: string, padding?: number, convertMarkdownLinksToObsidianURLs: boolean = false, includeInternalLinks: boolean = true,): Promise<SVGSVGElement>;",
desc: "Use ExcalidrawAutomate.getExportSettings(boolean,boolean) to create an ExportSettings object.\nUse ExcalidrawAutomate.getEmbeddedFilesLoader(boolean?) to create an EmbeddedFilesLoader object.",
after: "",
},
@@ -387,8 +404,14 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
},
{
field: "addArrow",
code: "addArrow(points: [[x: number, y: number]], formatting?: { startArrowHead?: string; endArrowHead?: string; startObjectId?: string; endObjectId?: string;}, id?:string): string;",
desc: `valid values for startArrowHead and endArrowHead are: "arrow"|"bar"|"circle"|"circle_outline"|"triangle"|"triangle_outline"|"diamond"|"diamond_outline"|null`,
code:
'addArrow(points: [x: number, y: number][], formatting?: { startArrowHead?: string; endArrowHead?: string; startObjectId?: string; endObjectId?: string; startBindMode?: string; endBindMode?: string; startFixedPoint?: [number, number]; endFixedPoint?: [number, number]; elbowed?: boolean}, id?: string): string;',
desc:
"Adds an arrow element.\n" +
'Arrowheads: "arrow"|"bar"|"circle"|"circle_outline"|"triangle"|"triangle_outline"|"diamond"|"diamond_outline"|null.\n' +
'Bindings: "inside" | "outside" Sets startObjectId/endObjectId to bind the arrow ends to shapes. Bind mode: "orbit" (default) or "inside".\n' +
"Fixed point: [xRatio,yRatio] in 0..1 (percentage of bound element width/height) to bind to a specific point on the element. In case of orbit mode, the orbit will happen around this immaginary point.\n" +
"Elbowed: true will create an elbowed arrow.",
after: "",
},
{
@@ -405,8 +428,15 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
{
field: "addEmbeddable",
code: "addEmbeddable(topX: number, topY: number, width: number, height: number, url?: string, file?: TFile, embeddableCustomData?: EmbeddableMDCustomProps): string;",
desc: "Adds an iframe/webview (depending on content and platform) to the drawing. If url is not null then the iframe/webview will be loaded from the url. The url maybe a markdown link to an note in the Vault or a weblink. " +
"If url is null then the iframe/webview will be loaded from the file. Both the url and the file may not be null.<br>" + EMBEDDABLE_MDCUSTOMPROPS,
desc: "Adds an embeddable component (technically an iframe or webview depending on content and platform) to the drawing. If url is not null then the embeddable will be loaded from the url. The url maybe a markdown link to an note in the Vault or a weblink. " +
"If url is null then the embeddable will be loaded from the file. Both the url and the file may not be null.<br>" + EMBEDDABLE_MDCUSTOMPROPS,
after: "",
},
{
field: "addIFrame",
code: "addIFrame(topX: number, topY: number, width: number, height: number, url?: string, file?: TFile, html?: string): string;",
desc: "If the url or file attribute is provided then the iframe will insert an embeddable component (technically calling ea.addEmbeddable() in the background with the same parameters). The function is depricated in that case use addEmbeddable instead. \n" +
"If the html attribute is provided, then the function will create an 'iframe' element with the provided html content.",
after: "",
},
{
@@ -420,7 +450,7 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
},
{
field: "addLaTex",
code: "async addLaTex(topX: number, topY: number, tex: string): Promise<string>;",
code: "async addLaTex(topX: number, topY: number, tex: string, scaleX: number = 1, scaleY: number = 1): Promise<string>;",
desc: "This is an async function, you need to avait the results. Adds a LaTex element to the drawing. The tex string is the LaTex code. The function returns the id of the created element.",
after: "",
},
@@ -468,9 +498,18 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
},
{
field: "setView",
code: 'setView(view: ExcalidrawView | "first" | "active"): ExcalidrawView;',
desc: null,
after: "",
code: 'setView(view?: ExcalidrawView | "auto" | "first" | "active" | null, show: boolean = false): ExcalidrawView;',
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" +
'"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 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.",
after: '("auto",true);',
},
{
field: "getExcalidrawAPI",
@@ -678,6 +717,37 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
desc: `Sets script settings.\nSee for more details: ${hyperlink("https://zsviczian.github.io/obsidian-excalidraw-plugin/ExcalidrawScriptsEngine.html","Script Engine Help")}`,
after: "",
},
{
field: "setScriptSettingValue",
code: "setScriptSettingValue(key: string, value: ScriptSettingValue): void;",
desc:
`Sets a single Script Engine setting value for the active script (in-memory).\n` +
`Use saveScriptSettings() to persist changes.\n` +
`Handles initialization when scriptEngineSettings[activeScript] is undefined/null.\n` +
`See for more details: ${hyperlink("https://zsviczian.github.io/obsidian-excalidraw-plugin/ExcalidrawScriptsEngine.html","Script Engine Help")}\n\n` +
`type ScriptSettingValue = { value?: string; hidden?: boolean; description?: string; valueset?: string[]; height?: number; };`,
after: `("myKey", { value: "" });`,
},
{
field: "getScriptSettingValue",
code: "getScriptSettingValue(key: string, defaultValue: ScriptSettingValue): ScriptSettingValue;",
desc:
`Gets a single Script Engine setting value for the active script.\n` +
`Returns defaultValue if the key does not exist (or if activeScript is not set).\n` +
`Handles initialization when scriptEngineSettings[activeScript] is undefined/null.\n` +
`See for more details: ${hyperlink("https://zsviczian.github.io/obsidian-excalidraw-plugin/ExcalidrawScriptsEngine.html","Script Engine Help")}\n\n` +
`type ScriptSettingValue = { value?: string; hidden?: boolean; description?: string; valueset?: string[]; height?: number; };`,
after: `("myKey", { value: "" });`,
},
{
field: "saveScriptSettings",
code: "async saveScriptSettings(): Promise<void>;",
desc:
`Persists Script Engine settings to disk (plugin settings).\n` +
`Useful after calling setScriptSettingValue().\n` +
`See for more details: ${hyperlink("https://zsviczian.github.io/obsidian-excalidraw-plugin/ExcalidrawScriptsEngine.html","Script Engine Help")}`,
after: "()",
},
{
field: "openFileInNewOrAdjacentLeaf",
code: "openFileInNewOrAdjacentLeaf(file: TFile): WorkspaceLeaf;",
@@ -775,6 +845,25 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
"colorNameToHex to convert the color name to a HEX color.",
after: "",
},
{
field: "getViewColorPalette",
code: "getViewColorPalette(palette: \"canvasBackground\"|\"elementBackground\"|\"elementStroke\"): (string[] | string)[];",
desc: "Returns the current view's palette for canvas background, element background, or element stroke colors. Falls back to the default palette when no view is loaded or the palette is unavailable.",
after: "(\"elementStroke\");",
},
{
field: "showColorPicker",
code: "async showColorPicker(anchorElement: HTMLElement, palette: \"canvasBackground\"|\"elementBackground\"|\"elementStroke\", includeSceneColors: boolean = true): Promise<string | null>;",
desc: "Opens a palette popover anchored to the provided element and resolves with the selected color; returns null when dismissed.\n\n" +
"Example Usage:\n" +
'const selected = await ea.showColorPicker(button.buttonEl, "elementStroke");\n' +
"if(selected) {" +
'console.log("User selected color: " + selected);' +
"} else {" +
'console.log("User cancelled color selection");' +
"}",
after: "(buttonEl, \"elementStroke\");",
},
{
field: "obsidian",
code: "obsidian",
@@ -838,6 +927,47 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
desc: "@returns the center position of the current view in Excalidraw coordinates",
after: "",
},
{
field: "checkForActiveSidepanelTabForScript",
code: "checkForActiveSidepanelTabForScript(scriptName?: string): ExcalidrawSidepanelTab | null;",
desc: "Returns the active sidepanel tab for the given script, or null if none exists. " +
"If scriptName is omitted the function checks ea.activeScript. " +
"At most one sidepanel tab may be open per script. " +
"The returned ExcalidrawSidepanelTab may be hosted by a different ExcalidrawAutomate instance — compare sidepanelTab.getHostEA() === ea to determine ownership. " +
"Useful to detect or reuse an existing tab instead of creating a new one.",
after: '("MyScript");'
},
{
field: "createSidepanelTab",
code: "async createSidepanelTab(title: string, persist: boolean = false, reveal: boolean = true,): Promise<ExcalidrawSidepanelTab | null>;",
desc: "Creates this EA instance's sidepanel tab; use the returned ExcalidrawSidepanelTab (setContent/setTitle, onOpen/onClose/onFocus, contentEl) to build the UI and lifecycle hooks.\n"+
"In case the script wants to replace the sidepanel tab it created earlier, call closeSidepanelTab() first, then createSidepanelTab() again.",
after: "",
},
{
field: "getSidepanelLeaf",
code: "getSidepanelLeaf(): WorkspaceLeaf | null;",
desc: "Returns the WorkspaceLeaf hosting the Excalidraw sidepanel view, or null if the sidepanel is not present.",
after: "();"
},
{
field: "toggleSidepanelView",
code: "toggleSidepanelView(): void;",
desc: "Toggles the Excalidraw sidepanel visibility when the sidepanel is hosted in the left or right workspace split. If the sidepanel is not attached to a left/right sidebar, no action is taken.",
after: "();"
},
{
field: "persistSidepanelTab",
code: "persistSidepanelTab(): ExcalidrawSidepanelTab | null;",
desc: "Pins the active script's sidepanel tab so it persists across Obsidian restarts and returns it.",
after: "",
},
{
field: "attachInlineLinkSuggester",
code: "attachInlineLinkSuggester(inputEl: HTMLInputElement, widthWrapper?: HTMLElement): KeyBlocker;",
desc: "Attaches an inline [[link]] suggester to an input. Optionally align width to a wrapper element. Returns a KeyBlocker so host scripts can skip their own keydown handlers while the suggester is active via isBlockingKeys(); call close() on the returned suggester to detach.",
after: "",
},
{
field: "getleaf",
code: "getLeaf(origo: WorkspaceLeaf, targetPane?: PaneTarget): WorkspaceLeaf;",
@@ -950,7 +1080,7 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
export const EXCALIDRAW_SCRIPTENGINE_INFO: SuggesterInfo[] = [
{
field: "inputPrompt",
code: "inputPrompt: (opts: {header: string, placeholder?: string, value?: string, buttons?: {caption:string, tooltip?:string, action:Function}[], lines?: number, displayEditorButtons?: boolean, customComponents?: (container: HTMLElement) => void, blockPointerInputOutsideModal?: boolean, controlsOnTop?: boolean});",
code: "inputPrompt: (opts: {header: string, placeholder?: string, value?: string, buttons?: {caption:string, tooltip?:string, iconId?: string, action:Function}[], lines?: number, displayEditorButtons?: boolean, customComponents?: (container: HTMLElement) => void, blockPointerInputOutsideModal?: boolean, controlsOnTop?: boolean});",
desc:
"Opens a prompt that asks for an input.\nReturns a string with the input.\nYou need to await the result of inputPrompt.\n" +
"Editor buttons are text editing buttons like delete, enter, allcaps - these are only displayed if lines is greater than 1 \n" +
@@ -958,6 +1088,7 @@ export const EXCALIDRAW_SCRIPTENGINE_INFO: SuggesterInfo[] = [
"blockPointerInputOutsideModal will block pointer input outside the modal. This is useful if you want to prevent the user accidently closing the modal or interacting with the excalidraw canvas while the prompt is open.\n" +
"controlsOnTop when set to true will move all the buttons to the top of the modal, leaving the text area at the bottom. This feature was developed for Scribble Helper script to avoid your palm pressing buttons while scribbling.\n"+
"buttons.action(input: string) => string\nThe button action function will receive the actual input string. If action returns null, input will be unchanged. If action returns a string, input will receive that value when the promise is resolved. " +
"iconId is the lucide.dev icon name. If iconId is provided caption will be ignored, simply submit \"\" as caption in that case. \n" +
"example:\n<code>let fileType = '';\nconst filename = await utils.inputPrompt (\n 'Filename',\n '',\n '',\n, [\n {\n caption: 'Markdown',\n action: ()=>{fileType='md';return;}\n },\n {\n caption: 'Excalidraw',\n action: ()=>{fileType='ex';return;}\n }\n ]\n);</code>",
after: `({\n header: "",\n placeholder: undefined, //string\n value: undefined, //string\n buttons: [{ //optional, may leave undefined\n caption: "", //string\n tooltip: undefined, //string\n action: (input)=>{} //Function\n }],\n lines: undefined, //number\n displayEditorButtons: undefined, //boolean\n customComponents: undefined, //(container: HTMLElement) => void\n blockPointerInputOutsideModal: undefined, //boolean\n controlsOnTop: undefined, //boolean\n draggable: undefined, //boolean\n});`,
},
@@ -979,7 +1110,7 @@ export const FRONTMATTER_KEYS_INFO: SuggesterInfo[] = [
{
field: "plugin",
code: null,
desc: "Denotes an excalidraw file. If key is not present, the file will not be recognized as an Excalidarw file. Valid values are 'parsed' and 'raw'",
desc: "Denotes an excalidraw file. If key is not present, the file will not be recognized as an Excalidraw file. Valid values are 'parsed' and 'raw'",
after: ": parsed",
},
{
@@ -1073,6 +1204,12 @@ export const FRONTMATTER_KEYS_INFO: SuggesterInfo[] = [
desc: "If this key is present it will override the default excalidraw embed and export setting.",
after: ": false",
},
{
field: "export-internal-links",
code: null,
desc: "Default value (if not set) is true, if set to false internal links will not be exported to SVG images and PDFs.",
after: ": false",
},
{
field: "open-md",
code: null,
@@ -0,0 +1,86 @@
import { Setting, DropdownComponent, App } from "obsidian";
import { t } from "src/lang/helpers";
import { ExcalidrawSettings } from "src/core/settings";
import { fragWithHTML, setLeftHandedMode, setUIMode } from "src/utils/utils";
import { DEVICE } from "src/constants/constants";
export type UIMode = "full" | "compact" | "tray" | "phone";
//setTrayMode(this.app, this.plugin.settings);
//setDesktopUIMode(this.app, this.plugin.settings);
export class UIModeSettingsComponent {
private containerEl: HTMLElement;
private settings: ExcalidrawSettings;
private app: App;
private onChange: () => void;
constructor(
containerEl: HTMLElement,
settings: ExcalidrawSettings,
app: App,
onChange: () => void,
) {
this.containerEl = containerEl;
this.settings = settings;
this.app = app;
this.onChange = onChange;
}
render(): void {
const { containerEl } = this;
new Setting(containerEl)
.setName(t("DESKTOP_UI_MODE_NAME"))
.setDesc(t("DESKTOP_UI_MODE_DESC"))
.addDropdown((dropdown: DropdownComponent) =>
dropdown
.addOption("full", t("MODE_FULL"))
.addOption("compact", t("MODE_COMPACT"))
.addOption("tray", t("MODE_TRAY"))
.setValue(this.settings.desktopUIMode)
.onChange((value: UIMode) => {
this.settings.desktopUIMode = value;
if (DEVICE.isDesktop) {
setUIMode(this.app, this.settings);
}
this.onChange();
}),
);
new Setting(containerEl)
.setName(t("TABLET_UI_MODE_NAME"))
.setDesc(t("TABLET_UI_MODE_DESC"))
.addDropdown((dropdown: DropdownComponent) =>
dropdown
.addOption("compact", t("MODE_COMPACT"))
.addOption("tray", t("MODE_TRAY"))
.setValue(this.settings.tabletUIMode)
.onChange((value: UIMode) => {
this.settings.tabletUIMode = value;
if (DEVICE.isTablet) {
setUIMode(this.app, this.settings);
}
this.onChange();
}),
);
new Setting(containerEl)
.setName(t("LEFTHANDED_MODE_NAME"))
.setDesc(fragWithHTML(t("LEFTHANDED_MODE_DESC")))
.addToggle((toggle) =>
toggle
.setValue(this.settings.isLeftHanded)
.onChange(async (value) => {
this.settings.isLeftHanded = value;
//not clear why I need to do this. If I don't double apply the stylesheet changes
//then the style won't be applied in the popout windows
setLeftHandedMode(value);
setTimeout(()=>setLeftHandedMode(value));
this.onChange();
}),
);
}
}
+41
View File
@@ -0,0 +1,41 @@
import ExcalidrawPlugin from "src/core/main";
import { t } from "src/lang/helpers";
import { UIModeSettingsComponent } from "./UIModeSettingComponent";
import { FloatingModal } from "./FloatingModal";
import { Modal } from "obsidian";
export class UIModeSettings extends Modal {
private isDirty = false;
constructor(
private plugin: ExcalidrawPlugin,
) {
super(plugin.app);
}
onOpen(): void {
this.containerEl.classList.add("excalidraw-release");
this.createForm();
}
async onClose() {
if (this.isDirty) {
await this.plugin.saveSettings();
}
this.plugin = null;
}
async createForm() {
this.contentEl.createEl("h1",{text: t("MODES_HEAD")});
new UIModeSettingsComponent(
this.contentEl,
this.plugin.settings,
this.app,
()=>this.applySettingsUpdate(),
).render();
}
private async applySettingsUpdate() {
this.isDirty = true;
};
}
@@ -61,7 +61,10 @@ export class UniversalInsertFileModal extends Modal {
}
onOpen(): void {
const modalEl = this.modalEl;
modalEl.classList.add("excalidraw-modal");
this.containerEl.classList.add("excalidraw-release");
this.containerEl.classList.add("excalidraw-modal");
this.titleEl.setText(t("UIFM_TITLE"));
this.createForm();
}
@@ -0,0 +1,240 @@
import { ExcalidrawTextElement } from "@zsviczian/excalidraw/types/element/src/types";
import { Notice } from "obsidian";
import { t } from "src/lang/helpers";
import { ScriptEngine } from "../Scripts";
import ExcalidrawView from "src/view/ExcalidrawView";
/**
*
* @param view - ExcalidrawView instance
* @param prefix - defines the default button.
* @returns
*/
export async function copyLinkToSelectedElementToClipboard(view: ExcalidrawView, prefix: string) {
const elements = view.getViewSelectedElements();
if (elements.length < 1) {
new Notice(t("INSERT_LINK_TO_ELEMENT_ERROR"));
return;
}
let elementId: string = undefined;
if (elements.length === 2) {
const textEl = elements.filter((el) => el.type === "text");
if (textEl.length === 1 && (textEl[0] as ExcalidrawTextElement).containerId) {
const container = elements.filter(
(el) => el.boundElements && el.boundElements.some((be) => be.type === "text"),
);
if (container.length === 1) {
elementId = textEl[0].id;
}
}
}
if (!elementId) {
elementId =
elements.length === 1
? elements[0].id
: view.plugin.ea.getLargestElement(elements).id;
}
const frames = elements.filter((el) => el.type === "frame");
const hasFrame = frames.length === 1;
const hasMarkerFrame = hasFrame && (frames[0] as any).frameRole === "marker";
const hasGroup = elements.some((el) => el.groupIds && el.groupIds.length > 0);
// Feature 1: UIFM_ANCHOR checkbox (persisted)
let anchorTo100 = Boolean(view.plugin.settings.copyLinkToElemenetAnchorTo100);
// Feature 2: frame link by name (persisted)
let copyFrameLinkByName = Boolean(view.plugin.settings.copyFrameLinkByName);
const frameNameRaw = hasFrame ? (frames[0] as any)?.name : undefined;
const frameName = typeof frameNameRaw === "string" ? frameNameRaw.trim() : "";
const frameNameIsValid =
hasFrame && frameName.length > 0 && /[\p{L}\p{N}_ -]+/u.test(frameName);
const getFrameTarget = () =>
frameNameIsValid && copyFrameLinkByName ? frameName : frames[0].id;
let cancelled = true;
const button = {
area: {
caption: "Area",
action: () => {
cancelled = false;
prefix = "area=";
return;
}
},
link: {
caption: "Link",
action: () => {
cancelled = false;
prefix = "";
return;
} },
group: {
caption: "Group",
action: () => {
cancelled = false;
prefix = "group=";
return;
}
},
frame: {
caption: "Frame",
action: () => {
cancelled = false;
prefix = "frame=";
elementId = getFrameTarget();
return;
},
},
clippedframe: {
caption: "Clipped Frame",
action: () => {
cancelled = false;
prefix = "clippedframe=";
elementId = getFrameTarget();
return;
},
},
};
let buttons = [];
switch (prefix) {
case "area=":
buttons = [
button.area,
button.link,
...(hasGroup ? [button.group] : []),
...(hasFrame && !hasMarkerFrame ? [button.clippedframe] : []),
...(hasFrame ? [button.frame] : []),
];
break;
case "group=":
buttons = [
...(hasGroup ? [button.group] : []),
button.link,
button.area,
...(hasFrame && !hasMarkerFrame ? [button.clippedframe] : []),
...(hasFrame ? [button.frame] : []),
];
break;
case "frame=":
buttons = [
...(hasFrame && !hasMarkerFrame ? [button.clippedframe] : []),
...(hasFrame ? [button.frame] : []),
...(hasGroup ? [button.group] : []),
button.link,
button.area,
];
break;
case "clippedframe=":
buttons = [
...(hasFrame && !hasMarkerFrame ? [button.clippedframe] : []),
...(hasFrame ? [button.frame] : []),
...(hasGroup ? [button.group] : []),
button.link,
button.area,
];
break;
default:
buttons = [
button.link,
button.area,
button.group,
...(hasFrame && !hasMarkerFrame ? [button.clippedframe] : []),
...(hasFrame ? [button.frame] : []),
];
}
let alias: string;
try {
alias = await ScriptEngine.inputPrompt(
view,
view.plugin,
view.app,
"Set link alias",
"Leave empty if you do not want to set an alias",
"",
buttons,
undefined,
undefined,
(container: HTMLElement) => {
const wrapper = container.createDiv?.("excalidraw-prompt-checkboxes") ?? container;
const ownerDoc = wrapper.ownerDocument ?? document;
const anchorRow = ownerDoc.createElement("label");
anchorRow.style.display = "flex";
anchorRow.style.alignItems = "center";
anchorRow.style.gap = "8px";
anchorRow.style.marginTop = "8px";
const anchorCb = ownerDoc.createElement("input");
anchorCb.type = "checkbox";
anchorCb.checked = anchorTo100;
anchorCb.setAttribute("aria-label", t("UIFM_ANCHOR_DESC"));
anchorCb.addEventListener("change", () => {
anchorTo100 = anchorCb.checked;
});
const anchorText = ownerDoc.createElement("span");
anchorText.textContent = t("UIFM_ANCHOR");
anchorRow.appendChild(anchorCb);
anchorRow.appendChild(anchorText);
wrapper.appendChild(anchorRow);
if (frameNameIsValid) {
const frameRow = ownerDoc.createElement("label");
frameRow.style.display = "flex";
frameRow.style.alignItems = "center";
frameRow.style.gap = "8px";
frameRow.style.marginTop = "8px";
const frameCb = ownerDoc.createElement("input");
frameCb.type = "checkbox";
frameCb.checked = copyFrameLinkByName;
frameCb.setAttribute("aria-label", t("FRAME_WITH_NAME"));
frameCb.addEventListener("change", () => {
copyFrameLinkByName = frameCb.checked;
});
const frameText = ownerDoc.createElement("span");
frameText.textContent = t("FRAME_WITH_NAME");
frameRow.appendChild(frameCb);
frameRow.appendChild(frameText);
wrapper.appendChild(frameRow);
}
},
);
} finally {
const changed =
view.plugin.settings.copyLinkToElemenetAnchorTo100 !== anchorTo100 ||
view.plugin.settings.copyFrameLinkByName !== copyFrameLinkByName;
if (changed) {
await view.plugin.loadSettings();
view.plugin.settings.copyLinkToElemenetAnchorTo100 = anchorTo100;
view.plugin.settings.copyFrameLinkByName = copyFrameLinkByName;
await view.plugin.saveSettings();
}
}
if (cancelled) {
return;
}
if ((alias === "" || alias == null) && anchorTo100) {
alias = "100%";
}
navigator.clipboard.writeText(
`${prefix.length > 0 ? "!" : ""}[[${view.file.path}#^${prefix}${elementId}${alias ? `|${alias}` : ``}]]`,
);
new Notice(t("INSERT_LINK_TO_ELEMENT_READY"));
}
+31
View File
@@ -0,0 +1,31 @@
// This file was generated by lezer-generator. You probably shouldn't edit it.
/*
Obsidian uses a slightly modified version of the hypermd parser for math blocks
found at https://github.com/laobubu/HyperMD/blob/071ce236605bb7693efa6d4b829c39413a3d37fb/src/mode/hypermd.ts#L329-L336
where spaces are replaced with `_` and the mathlevel of 1|2 is replaced with `math-block` for display math and nothing for inline math
create from the following grammar (where we remove the upper-cases):
@top Document { Formatting_formatting-math_formatting-math-begin_keyword_math_math-block Math Formatting_formatting-math_formatting-math-end_keyword_math_math- }
Formatting_formatting-math_formatting-math-begin_keyword_math_math-block { "" }
Math { any* }
Formatting_formatting-math_formatting-math-end_keyword_math_math- { "" }
@tokens {
any { _ }
}
*/
import {LRParser} from "@lezer/lr"
export const parser = LRParser.deserialize({
version: 14,
states: "zOOOO?MrOOQOPOOOOOO'#Ca'#CaOYOPO'#C_OOOO?MtOOOOO-E6_-E6_QOOOOO",
stateData: "b~OVQOURP~OVQOURX~O",
goto: "fUPPVY]`RPORSPRUSQRPRTR",
nodeNames: "⚠ Document formatting_formatting-math_formatting-math-begin_keyword_math_math-block math formatting_formatting-math_formatting-math-end_keyword_math_math-",
maxTerm: 7,
skippedNodes: [0],
repeatNodeCount: 1,
tokenData: "i~RRO;'S[;'S;=`a;=`O[~aOV~~fPV~;=`<%l[",
tokenizers: [0],
topRules: {"Document":[0,1]},
tokenPrec: 0
})
+10 -51
View File
@@ -2,7 +2,7 @@
//https://img.youtube.com/vi/uZz5MgzWXiM/maxresdefault.jpg
import { ExcalidrawElement, FileId } from "@zsviczian/excalidraw/types/element/src/types";
import { BinaryFileData, DataURL } from "@zsviczian/excalidraw/types/excalidraw/types";
import { DataURL } from "@zsviczian/excalidraw/types/excalidraw/types";
import { App, MarkdownRenderer, Notice, TFile } from "obsidian";
import {
DEFAULT_MD_EMBED_CSS,
@@ -15,7 +15,6 @@ import {
} from "../constants/constants";
import { createSVG } from "src/utils/excalidrawAutomateUtils";
import { ExcalidrawData, getTransclusion } from "./ExcalidrawData";
import { ExportSettings } from "../view/ExcalidrawView";
import { t } from "../lang/helpers";
import { tex2dataURL } from "./LaTeX";
import ExcalidrawPlugin from "../core/main";
@@ -39,11 +38,12 @@ import {
promiseTry,
PromisePool,
} from "../utils/utils";
import { ValueOf } from "../types/types";
import { getMermaidImageElements, getMermaidText, shouldRenderMermaid } from "../utils/mermaidUtils";
import { mermaidToExcalidraw } from "src/constants/constants";
import { ImageKey, imageCache } from "./ImageCache";
import { FILENAMEPARTS, PreviewImageType } from "../types/utilTypes";
import { ColorMap, ImgData, PDFPageViewProps, Size, MimeType, FileData } from "src/types/embeddedFileLoaderTypes";
import { ExportSettings } from "src/types/exportUtilTypes";
//An ugly workaround for the following situation.
//File A is a markdown file that has an embedded Excalidraw file B
@@ -54,54 +54,7 @@ import { FILENAMEPARTS, PreviewImageType } from "../types/utilTypes";
//and getObsidianImage is aborted if the file is already in the Watchdog stack
const markdownRendererRecursionWatcthdog = new Set<TFile>();
export const IMAGE_MIME_TYPES = {
svg: "image/svg+xml",
png: "image/png",
jpg: "image/jpeg",
jpeg: "image/jpeg",
gif: "image/gif",
webp: "image/webp",
bmp: "image/bmp",
ico: "image/x-icon",
avif: "image/avif",
jfif: "image/jfif",
} as const;
type ImgData = {
mimeType: MimeType;
fileId: FileId;
dataURL: DataURL;
created: number;
hasSVGwithBitmap: boolean;
size: Size;
pdfPageViewProps?: PDFPageViewProps;
};
export declare type MimeType = ValueOf<typeof IMAGE_MIME_TYPES> | "application/octet-stream";
export type FileData = BinaryFileData & {
size: Size;
hasSVGwithBitmap: boolean;
shouldScale: boolean; //true if image should maintain its area, false if image should display at 100% its size
pdfPageViewProps?: PDFPageViewProps;
};
export type PDFPageViewProps = {
left: number;
bottom: number;
right: number;
top: number;
rotate?: number; //may be undefined in legacy files
}
export type Size = {
height: number;
width: number;
};
export interface ColorMap {
[color: string]: string;
};
/**
* Function takes an SVG and replaces all fill and stroke colors with the ones in the colorMap
@@ -789,6 +742,10 @@ export class EmbeddedFilesLoader {
}
const addFilesTimer = setInterval(() => {
if (this.terminate) {
clearInterval(addFilesTimer);
return;
}
if(files[batch].length === 0) {
return;
}
@@ -804,7 +761,9 @@ export class EmbeddedFilesLoader {
const iterator = loadIterator.bind(this)();
const concurency = this.plugin.settings.renderingConcurrency;
await new PromisePool(iterator, concurency).all();
if (!this.terminate) {
await new PromisePool(iterator, concurency).all();
}
clearInterval(addFilesTimer);
+490 -94
View File
@@ -13,10 +13,10 @@ import {
ExcalidrawFrameElement,
ExcalidrawTextContainer,
} from "@zsviczian/excalidraw/types/element/src/types";
import { ColorMap, MimeType } from "./EmbeddedFileLoader";
import { ColorMap, MimeType } from "../types/embeddedFileLoaderTypes";
import { Editor, Notice, OpenViewState, RequestUrlResponse, TFile, TFolder, WorkspaceLeaf } from "obsidian";
import * as obsidian_module from "obsidian";
import ExcalidrawView, { ExportSettings, TextMode } from "src/view/ExcalidrawView";
import ExcalidrawView, { TextMode } from "src/view/ExcalidrawView";
import { ExcalidrawData, getMarkdownDrawingSection } from "./ExcalidrawData";
import {
FRONTMATTER,
@@ -25,7 +25,6 @@ import {
COLOR_NAMES,
fileid,
GITHUB_RELEASES,
determineFocusDistance,
getCommonBoundingBox,
getLineHeight,
getMaximumGroups,
@@ -33,6 +32,7 @@ import {
DEVICE,
mermaidToExcalidraw,
refreshTextDimensions,
getFontFamilyString,
} from "src/constants/constants";
import { blobToBase64, checkAndCreateFolder, getDrawingFilename, getExcalidrawEmbeddedFilesFiletree, getListOfTemplateFiles, getNewUniqueFilepath, splitFolderAndFilename } from "src/utils/fileUtils";
import {
@@ -44,6 +44,7 @@ import {
addAppendUpdateCustomData,
getSVG,
} from "src/utils/utils";
import { InlineLinkSuggester } from "./Suggesters/InlineLinkSuggester";
import { getAttachmentsFolderAndFilePath, getExcalidrawViews, getLeaf, getNewOrAdjacentLeaf, isObsidianThemeDark, mergeMarkdownFiles, openLeaf } from "src/utils/obsidianUtils";
import { AppState, BinaryFileData, DataURL, ExcalidrawImperativeAPI, SceneData } from "@zsviczian/excalidraw/types/excalidraw/types";
import { EmbeddedFile, EmbeddedFilesLoader } from "./EmbeddedFileLoader";
@@ -73,24 +74,30 @@ import { Mutable } from "@zsviczian/excalidraw/types/common/src/utility-types";
import PolyBool from "polybooljs";
import { EmbeddableMDCustomProps } from "./Dialogs/EmbeddableSettings";
import {
AIRequest,
postOpenAI as _postOpenAI,
extractCodeBlocks as _extractCodeBlocks,
} from "../utils/AIUtils";
import { EXCALIDRAW_AUTOMATE_INFO, EXCALIDRAW_SCRIPTENGINE_INFO } from "./Dialogs/SuggesterInfo";
import { addBackOfTheNoteCard } from "../utils/excalidrawViewUtils";
import { showColorPicker } from "./Dialogs/ColorPicker";
import { addBackOfTheNoteCard, getViewColorPalette, sceneRemoveInternalLinks } from "../utils/excalidrawViewUtils";
import { log } from "../utils/debugHelper";
import { ExcalidrawLib } from "../types/excalidrawLib";
import { GlobalPoint } from "@zsviczian/excalidraw/types/math/src/types";
import { AddImageOptions, ImageInfo, SVGColorInfo } from "src/types/excalidrawAutomateTypes";
import { _measureText, cloneElement, createPNG, createSVG, errorMessage, filterColorMap, getEmbeddedFileForImageElment, getFontFamily, getLineBox, getTemplate, isColorStringTransparent, isSVGColorInfo, mergeColorMapIntoSVGColorInfo, normalizeLinePoints, repositionElementsToCursor, svgColorInfoToColorMap, updateOrAddSVGColorInfo, verifyMinimumPluginVersion } from "src/utils/excalidrawAutomateUtils";
import { exportToPDF, getMarginValue, getPageDimensions, PageDimensions, PageOrientation, PageSize, PDFExportScale, PDFPageProperties } from "src/utils/exportUtils";
import { AddImageOptions, ImageInfo, KeyBlocker, ScriptSettingValue, SVGColorInfo } from "src/types/excalidrawAutomateTypes";
import { _measureText, cloneElement, createPNG, createSVG, ensureActiveScriptSettingsObject, errorMessage, filterColorMap, getEmbeddedFileForImageElment, getLastActiveExcalidrawView, getLineBox, getTemplate, isColorStringTransparent, isSVGColorInfo, mergeColorMapIntoSVGColorInfo, normalizeBindMode, normalizeFixedPoint, normalizeLinePoints, repositionElementsToCursor, svgColorInfoToColorMap, updateOrAddSVGColorInfo, verifyMinimumPluginVersion } from "src/utils/excalidrawAutomateUtils";
import { exportToPDF, getMarginValue, getPageDimensions } from "src/utils/exportUtils";
import { PageDimensions, PageOrientation, PageSize, PDFExportScale, PDFPageProperties, ExportSettings} from "src/types/exportUtilTypes";
import { FrameRenderingOptions } from "src/types/utilTypes";
import { CaptureUpdateAction } from "src/constants/constants";
import { AutoexportConfig } from "src/types/excalidrawViewTypes";
import { FloatingModal } from "./Dialogs/FloatingModal";
import { ExcalidrawSidepanelView } from "src/view/sidepanel/Sidepanel";
import { ExcalidrawSidepanelTab } from "src/view/sidepanel/SidepanelTab";
import { patchMobileView } from "src/utils/customEmbeddableUtils";
import { ObsidianCanvasNode } from "src/view/managers/CanvasNodeFactory";
import { AIRequest } from "src/types/AIUtilTypes";
import { getAspectRatio } from "src/utils/YoutTubeUtils";
import { getPDFCropRect } from "src/utils/PDFUtils";
extendPlugins([
HarmonyPlugin,
@@ -147,7 +154,8 @@ const GAP = 4;
* you may access this object via the variable `ea`. e.g. ea.addImage(); This ea object is already set to the targetView.
* Through ea.obsidian all of the Obsidian API is available to the script. Thus you can create modal views, open files, etc.
* You can access Obsidian type definitions here: https://github.com/obsidianmd/obsidian-api/blob/master/obsidian.d.ts
* In addition to the ea object, the script also receives the `utils` object. utils includes to utility functions: suggester and inputPrompt
* In addition to the ea instance, the script also receives the `utils` object. utils includes to utility functions: suggester and inputPrompt.
* You may access these via the variable `utils`. e.g. utils.suggester(...);
* - inputPrompt(inputPrompt: (
* header: string,
* placeholder?: string,
@@ -541,6 +549,7 @@ export class ExcalidrawAutomate {
gridSize: number;
};
colorPalette: {};
sidepanelTab: ExcalidrawSidepanelTab | null = null;
constructor(plugin: ExcalidrawPlugin, view?: ExcalidrawView) {
this.plugin = plugin;
@@ -548,6 +557,119 @@ export class ExcalidrawAutomate {
this.targetView = view;
}
/**
* Return the active sidepanel tab for a script, if one exists.
* If scriptName is omitted the function checks ea.activeScript.
* At most one sidepanel tab may be open per script. If a tab exists this
* returns the corresponding ExcalidrawSidepanelTab; otherwise it returns
* undefined.
* The returned tab may be hosted by a different ExcalidrawAutomate instance.
* To determine whether the tab belongs to the current ea instance compare:
* sidepanelTab.getHostEA() === ea.
* In this case the script may wish to reuse the existing tab rather than create a new one.
* @param scriptName - Optional script name to query. Defaults to ea.activeScript.
* @returns The ExcalidrawSidepanelTab for the script, or undefined if none exists.
*/
public checkForActiveSidepanelTabForScript(scriptName?: string): ExcalidrawSidepanelTab | null {
scriptName = scriptName ?? this.activeScript;
if (!scriptName) {
return null;
}
const spView = ExcalidrawSidepanelView.getExisting(false);
if (!spView) {
return null;
}
return spView.getTabByScript(scriptName);
}
/**
* Creates a new sidepanel tab associated with this ExcalidrawAutomate instance.
* If a sidepanel tab already exists for this instance, it will be closed first.
* @param title - The title of the sidepanel tab.
* @param options
* @returns
*/
public async createSidepanelTab(
title: string,
persist: boolean = false,
reveal: boolean = true,
): Promise<ExcalidrawSidepanelTab | null> {
if (this.sidepanelTab) {
this.sidepanelTab.close();
}
const scriptName = this.activeScript ?? nanoid(); //random name if no active script
const spView = await ExcalidrawSidepanelView.getOrCreate(this.plugin, reveal);
if (!spView) {
errorMessage("Unable to open sidepanel", "createSidepanelTab()");
return null;
}
const tab = await spView.createTab({ title, scriptName, hostEA: this });
this.sidepanelTab = tab;
if (persist && this.activeScript) {
this.persistSidepanelTab();
}
return tab;
}
/**
* Returns the WorkspaceLeaf hosting the Excalidraw sidepanel view.
* @returns {WorkspaceLeaf | null} The sidepanel leaf or null if not found.
*/
public getSidepanelLeaf(): WorkspaceLeaf | null {
return ExcalidrawSidepanelView.getExisting(false)?.leaf ?? null;
}
/**
* Toggles the visibility of the Excalidraw sidepanel view.
* If the sidepanel is not in a leaf attached to the left or right split, no action is taken.
*/
public toggleSidepanelView(): void {
const leaf = this.getSidepanelLeaf();
if (leaf) {
const root = leaf.getRoot();
if (root === this.plugin.app.workspace.leftSplit) {
this.plugin.app.workspace.leftSplit.toggle();
return;
}
if (root === this.plugin.app.workspace.rightSplit) {
this.plugin.app.workspace.rightSplit.toggle();
return;
}
}
}
/**
* Pins the active script's sidepanel tab to be persistent across Obsidian restarts.
* @param options
* @returns {Promise<ExcalidrawSidepanelTab | null>} The persisted sidepanel tab or null on error.
*/
public persistSidepanelTab(): ExcalidrawSidepanelTab | null {
if (!this.activeScript && !this.sidepanelTab) {
errorMessage("No active script and sidepanel tab to persist", "persistSidepanelTab()");
return null;
}
const spView = ExcalidrawSidepanelView.getExisting();
if (!spView) {
return;
}
spView.markTabPersistent(this.sidepanelTab);
return this.sidepanelTab;
}
/**
* Attaches an inline link suggester to the provided input element. The suggester reacts to
* "[[" typing, offers vault link choices (including aliases and unresolved links), and inserts
* the selected link using relative linktext when the active Excalidraw view is known.
* @param {HTMLInputElement} inputEl - The input element to enhance.
* @param {HTMLElement} [widthWrapper] - Optional element to determine suggester width.
* @returns {KeyBlocker} The suggester instance; call close() to detach; call .isBlockingKeys() to check if suggester dropdown is open.
*/
public attachInlineLinkSuggester(inputEl: HTMLInputElement, widthWrapper?: HTMLElement): KeyBlocker {
const getSourcePath = () => this.targetView?.file?.path;
return new InlineLinkSuggester(this.plugin.app, this.plugin, inputEl, getSourcePath, widthWrapper);
}
/**
* Returns the last recorded pointer position on the Excalidraw canvas.
* @returns {{x:number, y:number}} The last recorded pointer position.
@@ -652,20 +774,8 @@ export class ExcalidrawAutomate {
* @returns {string} The font family string.
*/
setFontFamily(val: number):string {
switch (val) {
case 1:
this.style.fontFamily = 4;
return getFontFamily(4);
case 2:
this.style.fontFamily = 2;
return getFontFamily(2);
case 3:
this.style.fontFamily = 3;
return getFontFamily(3);
default:
this.style.fontFamily = 1;
return getFontFamily(1);
}
this.style.fontFamily = val;
return getFontFamilyString({fontFamily:val})
};
/**
@@ -713,10 +823,29 @@ export class ExcalidrawAutomate {
: null;
let elements = template ? template.elements : [];
elements = elements.concat(this.getElements());
const files: Record<FileId, {mimeType: MimeType; id: FileId; dataURL: DataURL; created: number}> = {
...(template?.files ?? {}),
};
Object.keys(this.imagesDict).forEach((key: FileId) => {
const item = this.imagesDict[key];
if (!item?.dataURL || !item?.mimeType) {
return;
}
files[key] = {
mimeType: item.mimeType,
id: key,
dataURL: item.dataURL,
created: item.created ?? Date.now(),
};
});
navigator.clipboard.writeText(
JSON.stringify({
type: "excalidraw/clipboard",
elements,
files,
}),
);
};
@@ -764,6 +893,59 @@ export class ExcalidrawAutomate {
return this.elementsDict[id];
};
/**
* Returns an object describing the bound text element.
* If a text element is provided:
* - returns { eaElement } if the element is in ea.elementsDict
* - else (if searchInView is true) returns { sceneElement } if found in the targetView scene
* If a container element is provided, searches for the bound text element:
* - returns { eaElement } if found in ea.elementsDict
* - else (if searchInView is true) returns { sceneElement } if found in the targetView scene
* If not found, returns {}.
* Does not add the text element to elementsDict.
* @param element
* @param searchInView - If true, searches in the targetView elements if not found in elementsDict.
* @returns Object containing either eaElement or sceneElement or empty if not found.
*/
getBoundTextElement(element: ExcalidrawElement, searchInView: boolean = false): {
eaElement?: Mutable<ExcalidrawTextElement>,
sceneElement?: ExcalidrawTextElement
} {
if (!element) {
return {};
}
if(element.type === "text") {
if(element.id in this.elementsDict) {
return {eaElement: element as Mutable<ExcalidrawTextElement>};
}
if (searchInView && this.targetView && this.targetView._loaded) {
const viewElements = this.getViewElements();
const ve = viewElements.find((e) => e.id === element.id);
if(ve) {
return {
sceneElement: ve as ExcalidrawTextElement
};
}
}
return {};
}
const boundElement = element.boundElements?.find((be) => be.type === "text");
if (!boundElement) {
return {};
}
let textElement = this.elementsDict[boundElement.id] as Mutable<ExcalidrawTextElement>;
if (textElement) {
return {eaElement: textElement};
}
if (!textElement && searchInView && this.targetView && this.targetView._loaded) {
const viewElements = this.getViewElements();
const ve = viewElements.find((e) => e.id === boundElement.id);
return {sceneElement: ve as ExcalidrawTextElement};
}
return {};
}
/**
* Creates a drawing and saves it to the specified filename.
* @param {Object} [params] - Parameters for creating the drawing.
@@ -798,6 +980,7 @@ export class ExcalidrawAutomate {
"excalidraw-autoexport"?: boolean;
"excalidraw-mask"?: boolean;
"excalidraw-open-md"?: boolean;
"excalidraw-export-internal-links"?: boolean;
"cssclasses"?: string;
};
plaintext?: string; //text to insert above the `# Text Elements` section
@@ -1098,6 +1281,11 @@ export class ExcalidrawAutomate {
if(elementsOverride) {
scene.elements = elementsOverride;
}
if(!view.getViewExportIncludeInternalLinks()) {
scene.elements = sceneRemoveInternalLinks(scene);
}
const exportSettings: ExportSettings = {
withBackground: view.getViewExportWithBackground(withBackground),
withTheme: true,
@@ -1140,6 +1328,8 @@ export class ExcalidrawAutomate {
loader?: EmbeddedFilesLoader,
theme?: string,
padding?: number,
convertMarkdownLinksToObsidianURLs: boolean = false,
includeInternalLinks: boolean = true,
): Promise<SVGSVGElement> {
if (!theme) {
theme = this.plugin.settings.previewMatchObsidianTheme
@@ -1177,7 +1367,9 @@ export class ExcalidrawAutomate {
this.plugin,
0,
padding,
this.imagesDict
this.imagesDict,
convertMarkdownLinksToObsidianURLs,
includeInternalLinks,
);
};
@@ -1271,6 +1463,36 @@ export class ExcalidrawAutomate {
return wrapTextAtCharLength(text, lineLen, this.plugin.settings.forceWrap);
};
/** ROUNDNESS as defined in the Excalidraw packages/common/src/constants.ts
* Radius represented as 25% of element's largest side (width/height).
* Used for LEGACY and PROPORTIONAL_RADIUS algorithms, or when the element is
* below the cutoff size.
* export const DEFAULT_PROPORTIONAL_RADIUS = 0.25;
*
* Fixed radius for the ADAPTIVE_RADIUS algorithm. In pixels.
* export const DEFAULT_ADAPTIVE_RADIUS = 32;
*
* roundness type (algorithm)
* export const ROUNDNESS = {
* Used for legacy rounding (rectangles), which currently works the same
* as PROPORTIONAL_RADIUS, but we need to differentiate for UI purposes and
* forwards-compat.
* LEGACY: 1,
*
* Used for linear elements & diamonds
* PROPORTIONAL_RADIUS: 2,
*
* Current default algorithm for rectangles, using fixed pixel radius.
* It's working similarly to a regular border-radius, but attemps to make
* radius visually similar across differnt element sizes, especially
* very large and very small elements.
*
* NOTE right now we don't allow configuration and use a constant radius
* (see DEFAULT_ADAPTIVE_RADIUS constant)
* ADAPTIVE_RADIUS: 3,
* } as const;
*/
/**
* Utility function. Returns an element object using style settings and provided parameters.
* @param {string} id - The element ID.
@@ -1323,12 +1545,13 @@ export class ExcalidrawAutomate {
link,
locked: false,
frameId: null as string,
hasTextLink: eltype === "text" && link ? true : false,
...scale ? {scale} : {},
};
}
/**
* Deprecated. Use addEmbeddable() instead.
* Use addEmbeddable() instead, unless you specifically need to pass HTML content and create a custom iframe.
* Retained for backward compatibility.
* @param {number} topX - The x-coordinate of the top-left corner.
* @param {number} topY - The y-coordinate of the top-left corner.
@@ -1336,19 +1559,41 @@ export class ExcalidrawAutomate {
* @param {number} height - The height of the iframe.
* @param {string} [url] - The URL of the iframe.
* @param {TFile} [file] - The file associated with the iframe.
* @param {string} [html] - The HTML content for the iframe.
* @returns {string} The ID of the added iframe element.
*/
addIFrame(topX: number, topY: number, width: number, height: number, url?: string, file?: TFile): string {
addIFrame(topX: number, topY: number, width: number, height: number, url?: string, file?: TFile, html?: string): string {
if(html) {
const id = nanoid();
this.elementsDict[id] = this.boxedElement(
id,
"iframe",
topX,
topY,
width,
height,
null,
[1,1],
);
this.elementsDict[id].customData = {
generationData: { status: "done", html },
};
return id;
}
return this.addEmbeddable(topX, topY, width, height, url, file);
}
/**
* Adds an embeddable element to the ExcalidrawAutomate instance.
* In case of urls, if the width and or height is set to 0 ExcalidrawAutomate will attempt to determine the dimensions based on the aspect ratio of the content.
* If both width and height are set to 0 the default size for youtube and vimeo embeddables (560x315) will be used. YouTube shorts will have a default size of 315x560.
* If only the width or height is set to 0 the other dimension will be calculated based on the aspect ratio of the content.
* If the calculated width is less than 560 or the calculated height is less than 315 the element will be scaled down proportionally, setting element.scale accordingly.
* @param {number} topX - The x-coordinate of the top-left corner.
* @param {number} topY - The y-coordinate of the top-left corner.
* @param {number} width - The width of the embeddable element.
* @param {number} height - The height of the embeddable element.
* @param {string} [url] - The URL of the embeddable element.
* @param {string} [url] - The URL of the embeddable element. The URL may be a dataURL as well (however such elements are not supported by Excalidraw.com).
* @param {TFile} [file] - The file associated with the embeddable element.
* @param {EmbeddableMDCustomProps} [embeddableCustomData] - Custom properties for the embeddable element.
* @returns {string} The ID of the added embeddable element.
@@ -1372,6 +1617,30 @@ export class ExcalidrawAutomate {
return null;
}
let scale: [number, number] = [1,1];
if (url) {
let { w, h } = getAspectRatio(url);
if (h > w) {
//swap width and height for portrait oriented content
[w, h] = [h, w];
}
if (width === 0 && height === 0) {
width = 560;
height = 560 * (h / w);
} else if (height === 0) {
height = width * (h / w);
if (width < 560) {
scale = [width / 560, width / 560];
}
} else if (width === 0) {
width = height * (w / h);
if (height < 315) {
scale = [height / 315, height / 315];
}
}
}
const id = nanoid();
this.elementsDict[id] = this.boxedElement(
id,
@@ -1387,7 +1656,7 @@ export class ExcalidrawAutomate {
false, //file.extension === "md", //changed this to false because embedable link navigation in ExcaliBrain
)
}]]` : "",
[1,1],
scale,
);
this.elementsDict[id].customData = {mdProps: embeddableCustomData ?? this.plugin.settings.embeddableMarkdownDefaults};
return id;
@@ -1755,6 +2024,17 @@ export class ExcalidrawAutomate {
* @param {"arrow"|"bar"|"circle"|"circle_outline"|"triangle"|"triangle_outline"|"diamond"|"diamond_outline"|null} [formatting.endArrowHead] - The end arrowhead type.
* @param {string} [formatting.startObjectId] - The ID of the start object.
* @param {string} [formatting.endObjectId] - The ID of the end object.
* BindMode Determines whether the arrow remains outside the shape or is allowed to
* go all the way inside the shape up to the exact fixed point.
* @param {"inside" | "orbit"} [formatting.startBindMode] - The binding mode for the start object.
* @param {"inside" | "orbit"} [formatting.endBindMode] - The binding mode for the end object.
* FixedPoint represents the fixed point binding information in form of a vertical and
* horizontal ratio (i.e. a percentage value in the 0.0-1.0 range). This ratio
* gives the user selected fixed point by multiplying the bound element width
* with fixedPoint[0] and the bound element height with fixedPoint[1] to get the
* bound element-local point coordinate.
* @param {[number, number]} [formatting.startFixedPoint] - The fixed point for the start object.
* @param {[number, number]} [formatting.endFixedPoint] - The fixed point for the end object.
* @param {string} [id] - The ID of the arrow element.
* @returns {string} The ID of the added arrow element.
*/
@@ -1765,40 +2045,40 @@ export class ExcalidrawAutomate {
endArrowHead?: "arrow"|"bar"|"circle"|"circle_outline"|"triangle"|"triangle_outline"|"diamond"|"diamond_outline"|null;
startObjectId?: string;
endObjectId?: string;
startBindMode?: "inside" | "orbit";
endBindMode?: "inside" | "orbit";
startFixedPoint?: [number, number];
endFixedPoint?: [number, number];
elbowed?: boolean;
},
id?: string,
): string {
const startFixedPoint = normalizeFixedPoint(formatting?.startFixedPoint);
const endFixedPoint = normalizeFixedPoint(formatting?.endFixedPoint);
const startMode = normalizeBindMode(formatting?.startBindMode);
const endMode = normalizeBindMode(formatting?.endBindMode);
const box = getLineBox(points);
const elbowed = formatting?.elbowed ?? false;
const startElement = formatting?.startObjectId
? this.getElement(formatting.startObjectId) as Mutable<ExcalidrawBindableElement>
: null;
const endElement = formatting?.endObjectId
? this.getElement(formatting.endObjectId) as Mutable<ExcalidrawBindableElement>
: null;
id = id ?? nanoid();
const startPoint = points[0] as GlobalPoint;
const endPoint = points[points.length - 1] as GlobalPoint;
const elementsMap = arrayToMap(this.getElements());
this.elementsDict[id] = {
points: normalizeLinePoints(points),
elbowed,
lastCommittedPoint: null,
startBinding: {
elementId: formatting?.startObjectId,
focus: formatting?.startObjectId
? determineFocusDistance(
this.getElement(formatting?.startObjectId) as ExcalidrawBindableElement,
elementsMap,
endPoint,
startPoint,
)
: 0.1,
gap: GAP,
mode: startMode,
fixedPoint: startFixedPoint,
},
endBinding: {
elementId: formatting?.endObjectId,
focus: formatting?.endObjectId
? determineFocusDistance(
this.getElement(formatting?.endObjectId) as ExcalidrawBindableElement,
elementsMap,
startPoint,
endPoint,
)
: 0.1,
gap: GAP,
mode: endMode,
fixedPoint: endFixedPoint,
},
//https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/388
startArrowhead:
@@ -1811,20 +2091,20 @@ export class ExcalidrawAutomate {
: this.style.endArrowHead,
...this.boxedElement(id, "arrow", points[0][0], points[0][1], box.w, box.h),
};
if (formatting?.startObjectId) {
if (!this.elementsDict[formatting.startObjectId].boundElements) {
this.elementsDict[formatting.startObjectId].boundElements = [];
if (startElement) {
if (!startElement.boundElements) {
startElement.boundElements = [];
}
this.elementsDict[formatting.startObjectId].boundElements.push({
(startElement.boundElements as Mutable<ExcalidrawElement["boundElements"]>).push({
type: "arrow",
id,
});
}
if (formatting?.endObjectId) {
if (!this.elementsDict[formatting.endObjectId].boundElements) {
this.elementsDict[formatting.endObjectId].boundElements = [];
if (endElement) {
if (!endElement.boundElements) {
endElement.boundElements = [];
}
this.elementsDict[formatting.endObjectId].boundElements.push({
(endElement.boundElements as Mutable<ExcalidrawElement["boundElements"]>).push({
type: "arrow",
id,
});
@@ -1909,33 +2189,39 @@ export class ExcalidrawAutomate {
colorMap = topXOrOpts.colorMap;
}
const pdfLinkRegex = /^[^#]*#page=\d*(&\w*=[^&]+){0,}&rect=\d*,\d*,\d*,\d*/;
const originalLink = typeof imageFile === "string" ? imageFile : null;
const imageFileForLoader = originalLink && pdfLinkRegex.test(originalLink)
? originalLink.split("&rect=")[0]
: imageFile;
const id = nanoid();
const loader = new EmbeddedFilesLoader(
this.plugin,
this.canvas.theme === "dark",
);
const image = (typeof imageFile === "string")
? await loader.getObsidianImage(new EmbeddedFile(this.plugin, "", imageFile),0)
: await loader.getObsidianImage(imageFile,0);
const image = (typeof imageFileForLoader === "string")
? await loader.getObsidianImage(new EmbeddedFile(this.plugin, "", imageFileForLoader),0)
: await loader.getObsidianImage(imageFileForLoader,0);
if (!image) {
return null;
}
const fileId = typeof imageFile === "string"
const fileId = typeof imageFileForLoader === "string"
? image.fileId
: imageFile.extension === "md" || imageFile.extension.toLowerCase() === "pdf" ? fileid() as FileId : image.fileId;
: imageFileForLoader.extension === "md" || imageFileForLoader.extension.toLowerCase() === "pdf" ? fileid() as FileId : image.fileId;
this.imagesDict[fileId] = {
mimeType: image.mimeType,
id: fileId,
dataURL: image.dataURL,
created: image.created,
isHyperLink: typeof imageFile === "string",
hyperlink: typeof imageFile === "string"
? imageFile
isHyperLink: typeof imageFileForLoader === "string",
hyperlink: typeof imageFileForLoader === "string"
? imageFileForLoader
: null,
file: typeof imageFile === "string"
file: typeof imageFileForLoader === "string"
? null
: imageFile.path + (scale || !anchor ? "":"|100%"),
: imageFileForLoader.path + (scale || !anchor ? "":"|100%"),
hasSVGwithBitmap: image.hasSVGwithBitmap,
latex: null,
size: { //must have the natural size here (e.g. for PDF cropping)
@@ -1963,6 +2249,22 @@ export class ExcalidrawAutomate {
newEl.fileId = fileId;
newEl.scale = [1, 1];
newEl.crop = null;
if(originalLink && pdfLinkRegex.test(originalLink)) {
const fd = this.imagesDict[fileId];
newEl.crop = getPDFCropRect({
scale: this.plugin.settings.pdfScale,
link: originalLink,
naturalHeight: fd.size.height,
naturalWidth: fd.size.width,
pdfPageViewProps: fd.pdfPageViewProps,
});
addAppendUpdateCustomData(newEl, {pdfPageViewProps: fd.pdfPageViewProps});
if(newEl.crop) {
newEl.width = newEl.crop.width/this.plugin.settings.pdfScale;
newEl.height = newEl.crop.height/this.plugin.settings.pdfScale;
}
newEl.link = `[[${originalLink}]]`;
}
if(!scale && anchor) {
newEl.customData = {isAnchored: true}
};
@@ -1974,9 +2276,14 @@ export class ExcalidrawAutomate {
* @param {number} topX - The x-coordinate of the top-left corner.
* @param {number} topY - The y-coordinate of the top-left corner.
* @param {string} tex - The LaTeX equation string.
* @param {number} [scaleX=1] - The x-scaling factor (post mathjax creation)
* @param {number} [scaleY=1] - The y-scaling factor (post mathjax creation)
* @returns {Promise<string>} Promise resolving to the ID of the added LaTeX image element.
*/
async addLaTex(topX: number, topY: number, tex: string): Promise<string> {
async addLaTex(topX: number, topY: number, tex: string, scaleX: number = 1, scaleY: number = 1): Promise<string> {
if (!tex || !scaleX || !scaleY){
return null;
}
const id = nanoid();
const image = await tex2dataURL(tex, 4, this.plugin);
if (!image) {
@@ -1996,11 +2303,12 @@ export class ExcalidrawAutomate {
"image",
topX,
topY,
image.size.width,
image.size.height,
image.size.width * Math.abs(scaleX),
image.size.height * Math.abs(scaleY),
);
this.elementsDict[id].fileId = image.fileId;
this.elementsDict[id].scale = [1, 1];
this.addAppendUpdateCustomData(id, {latex: tex});
this.elementsDict[id].scale = [Math.sign(scaleX), Math.sign(scaleY)];
return id;
};
@@ -2190,6 +2498,7 @@ export class ExcalidrawAutomate {
* Clears elementsDict and imagesDict, and resets all style values to default.
*/
reset():void {
this.sidepanelTab?.close();
this.clear();
this.activeScript = null;
this.style = {
@@ -2224,35 +2533,72 @@ export class ExcalidrawAutomate {
isExcalidrawFile(f: TFile): boolean {
return this.plugin.isExcalidrawFile(f);
};
targetView: ExcalidrawView = null; //the view currently edited
/**
* Sets the target view for EA. All the view operations and the access to Excalidraw API will be performed on this view.
* If view is null or undefined, the function will first try setView("active"), then setView("first").
* @param {ExcalidrawView | "first" | "active"} [view] - The view to set as target.
* @returns {ExcalidrawView} The target view.
* Sets the target view for EA. All view operations and all access to the Excalidraw API
* will be performed on this view.
*
* Typical usage:
* - `setView()` to pick a sensible default automatically
* - `setView(excalidrawView)` to explicitly target a specific view
*
* Selectors:
* - If `view` is `null` or `undefined` (or `"auto"`), EA will pick a sensible default:
* 1) the currently active Excalidraw view (if any),
* 2) otherwise the last active Excalidraw view (if it is still available),
* 3) otherwise the `"first"` Excalidraw view in the workspace.
* - If `show` is `true`, the view will be revealed (brought to front) and focused.
*
* Deprecated selectors (kept for backward compatibility):
* - If `"active"` is provided, the currently active Excalidraw view will be used. If no
* active Excalidraw view is available, the last active Excalidraw view will be used.
* - 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 the current
* `getExcalidrawViews()` result). **This ordering is managed by Obsidian and does not
* necessarily match what a user would consider the “first”/“leftmost”/“topmost” view;
* from a user's perspective it may appear effectively random.**
*
* @param {ExcalidrawView | "auto" | "first" | "active" | null | undefined} [view] - The view (or selector) to set as target.
* @param {boolean} [show=false] - Whether to reveal/focus the target view.
* @returns {ExcalidrawView} The ExcalidrawView that was set as `targetView` (or `null` if none found).
*/
setView(view?: ExcalidrawView | "first" | "active"): ExcalidrawView {
if(!view) {
const v = this.plugin.app.workspace.getActiveViewOfType(ExcalidrawView);
if (v instanceof ExcalidrawView) {
this.targetView = v;
}
else {
this.targetView = getExcalidrawViews(this.plugin.app)[0];
}
}
if (view == "active") {
const v = this.plugin.app.workspace.getActiveViewOfType(ExcalidrawView);
if (!(v instanceof ExcalidrawView)) {
setView(view?: ExcalidrawView | "auto" | "first" | "active" | null, show: boolean = false): ExcalidrawView {
const app = this.plugin.app;
const workspace = app.workspace;
const setView = () => {
if(!view || view === "auto") {
view = workspace.getActiveViewOfType(ExcalidrawView);
if (view instanceof ExcalidrawView) {
this.targetView = view;
return;
}
view = getLastActiveExcalidrawView(this.plugin);
this.targetView = view ?? getExcalidrawViews(this.plugin.app)[0];
return;
}
this.targetView = v;
if (view == "active") {
view = workspace.getActiveViewOfType(ExcalidrawView);
if (view instanceof ExcalidrawView) {
this.targetView = view;
return;
}
this.targetView = getLastActiveExcalidrawView(this.plugin);
return;
}
if (view == "first") {
this.targetView = getExcalidrawViews(this.plugin.app)[0];
return;
}
if (view instanceof ExcalidrawView) {
this.targetView = view;
}
}
if (view == "first") {
this.targetView = getExcalidrawViews(this.plugin.app)[0];
}
if (view instanceof ExcalidrawView) {
this.targetView = view;
setView();
if(show && this.targetView) {
this.plugin.app.workspace.revealLeaf(
this.targetView.leaf,
);
}
return this.targetView;
};
@@ -3276,6 +3622,23 @@ export class ExcalidrawAutomate {
await this.plugin.saveSettings();
};
public setScriptSettingValue(key: string, value: ScriptSettingValue): void {
const settings = ensureActiveScriptSettingsObject(this);
if (!settings) return;
settings[key] = value;
}
public getScriptSettingValue(key: string, defaultValue: ScriptSettingValue): ScriptSettingValue {
const settings = ensureActiveScriptSettingsObject(this);
if (!settings) return defaultValue;
return settings[key] ?? defaultValue;
}
public async saveScriptSettings(): Promise<void> {
ensureActiveScriptSettingsObject(this);
await this.plugin.saveSettings();
}
/**
* Opens a file in a new workspace leaf or reuses an existing adjacent leaf depending on Excalidraw Plugin Settings.
* @param {TFile} file - The file to open.
@@ -3453,6 +3816,7 @@ export class ExcalidrawAutomate {
/**
* Moves the specified element to a specific position in the z-index.
* * Operates directly on the Excalidraw Scene in targetView, not through ExcalidrawAutomate elements.
* @param {number} elementId - The ID of the element to move.
* @param {number} newZIndex - The new z-index position for the element.
*/
@@ -3567,6 +3931,37 @@ export class ExcalidrawAutomate {
return cm;
}
/**
* Get color palette for scene. If no palette is found, returns default Excalidraw color palette.
* @param {("canvasBackground"|"elementBackground"|"elementStroke")} palette - The palette type.
* @returns {([string, string, string, string, string][] | string[])} The color palette.
*/
getViewColorPalette(palette: "canvasBackground"|"elementBackground"|"elementStroke"): (string[] | string)[] {
return getViewColorPalette(palette, this.targetView);
}
/**
* Opens a palette popover anchored to the provided element and resolves with the selected color.
* @param {HTMLElement} anchorElement - The element to anchor the popover to.
* @param {"canvasBackground"|"elementBackground"|"elementStroke"} palette - Which palette to show.
* @param {boolean} [includeSceneColors=true] - Whether to include scene stroke/background colors in the palette.
* @returns {Promise<string|null>} Selected color or null if cancelled.
* example usage:
* const selected = await ea.showColorPicker(button.buttonEl, "elementStroke");
* if(selected) {
* console.log("User selected color: " + selected);
* } else {
* console.log("User cancelled color selection");
* }
*/
public async showColorPicker(
anchorElement: HTMLElement,
palette: "canvasBackground"|"elementBackground"|"elementStroke",
includeSceneColors: boolean = true,
): Promise<string | null> {
return showColorPicker(palette, anchorElement, this.targetView, includeSceneColors);
}
/**
* Gets the PolyBool class from https://github.com/velipso/polybooljs.
* @returns {PolyBool} The PolyBool class.
@@ -3596,6 +3991,7 @@ export class ExcalidrawAutomate {
* Destroys the ExcalidrawAutomate instance, clearing all references and data.
*/
destroy(): void {
this.sidepanelTab?.close();
this.targetView = null;
this.plugin = null;
this.elementsDict = {};
+11 -5
View File
@@ -46,7 +46,8 @@ import {
FileId,
} from "@zsviczian/excalidraw/types/element/src/types";
import { BinaryFiles, DataURL, SceneData } from "@zsviczian/excalidraw/types/excalidraw/types";
import { EmbeddedFile, MimeType } from "./EmbeddedFileLoader";
import { EmbeddedFile } from "./EmbeddedFileLoader";
import { MimeType } from "src/types/embeddedFileLoaderTypes";
import { MultiOptionConfirmationPrompt } from "./Dialogs/Prompt";
import { getMermaidImageElements, getMermaidText, shouldRenderMermaid } from "../utils/mermaidUtils";
import { DEBUGGING, debug } from "../utils/debugHelper";
@@ -939,7 +940,7 @@ export class ExcalidrawData {
raw: text,
parsed: parseRes.parsed,
});
if (parseRes.link) {
if (parseRes.link && this.plugin.settings.syncElementLinkWithText) {
textEl.link = parseRes.link;
}
//this will set the rawText field of text elements imported from files before 1.3.14, and from other instances of Excalidraw
@@ -1129,7 +1130,6 @@ export class ExcalidrawData {
return (
el.type !== "text" &&
el.link &&
//el.link.startsWith("[[") &&
!this.elementLinks.has(el.id)
);
});
@@ -1211,7 +1211,6 @@ export class ExcalidrawData {
el.type !== "text" &&
el.id === key &&
el.link, //&&
//el.link.startsWith("[["),
);
if (el.length === 0) {
this.elementLinks.delete(key); //if no longer in the scene, delete the text element
@@ -1349,6 +1348,7 @@ export class ExcalidrawData {
position = parts.value.index + parts.value[0].length;
}
outString += text.substring(position, text.length);
outString = this.unescapeSquareBrackets(outString);
if (linkIcon) {
outString = this.linkPrefix + outString;
}
@@ -1369,6 +1369,10 @@ export class ExcalidrawData {
: text;
}
private unescapeSquareBrackets(text: string): string {
return text?.replaceAll(/\\\[/g, "[") ?? text;
}
/**
* Does a quick parse of the raw text. Returns the parsed string if raw text does not include a transclusion.
* Return null if raw text includes a transclusion.
@@ -1426,6 +1430,7 @@ export class ExcalidrawData {
position = parts.value.index + parts.value[0].length;
}
outString += text.substring(position, text.length);
outString = this.unescapeSquareBrackets(outString);
if (linkIcon) {
outString = this.linkPrefix + outString;
}
@@ -1441,6 +1446,7 @@ export class ExcalidrawData {
*/
disableCompression: boolean = false;
generateMDBase(deletedElements: ExcalidrawElement[] = []) {
const syncTextLinks = this.plugin.settings.syncElementLinkWithText;
let outString = this.textElementCommentedOut ? "%%\n" : "";
outString += `# Excalidraw Data\n\n## Text Elements\n`;
if (this.plugin.settings.addDummyTextElement) {
@@ -1451,7 +1457,7 @@ export class ExcalidrawData {
//https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/566
const element = this.scene.elements.filter((el:any)=>el.id===key);
let elementString = this.textElements.get(key).raw;
if(element && element.length===1 && element[0].link && element[0].rawText === element[0].originalText) {
if(element && element.length===1 && element[0].link && (!syncTextLinks || element[0].rawText === element[0].originalText)) {
//if(element[0].link.match(/^\[\[[^\]]*]]$/g)) { //apply this only to markdown links
textElementLinks.set(key, element[0].link);
//elementString = `%%***>>>text element-link:${element[0].link}<<<***%%` + elementString;
+11
View File
@@ -55,6 +55,7 @@ class ImageCache {
this.db = null;
this.plugin = null;
this.app = null;
this.obsidanURLCache.forEach((url) => URL.revokeObjectURL(url));
this.obsidanURLCache.clear();
this.obsidanURLCache = null;
}
@@ -179,6 +180,10 @@ class ImageCache {
const fileExists = files.some((f: TFile) => f.path === filepath);
const file = fileExists ? files.find((f: TFile) => f.path === filepath) : null;
if (isLegacyKey || !file || (file && (file.stat.mtime > cursor.value.mtime)) || (!cursor.value.blob && !cursor.value.svg)) {
if(this.obsidanURLCache.has(key)) {
URL.revokeObjectURL(this.obsidanURLCache.get(key));
this.obsidanURLCache.delete(key);
}
deletePromises.push(
new Promise<void>((innerResolve, innerReject) => {
const deleteRequest = store.delete(cursor.primaryKey);
@@ -368,6 +373,9 @@ class ImageCache {
const key = getKey(key_);
store.put(data, key);
if(!Boolean(svg)) {
if(this.obsidanURLCache.has(key) && this.obsidanURLCache.get(key) !== obsidianURL) {
URL.revokeObjectURL(this.obsidanURLCache.get(key));
}
this.obsidanURLCache.set(key, obsidianURL);
}
}
@@ -406,6 +414,9 @@ class ImageCache {
return; // Database not initialized yet
}
this.obsidanURLCache.forEach((url) => URL.revokeObjectURL(url));
this.obsidanURLCache.clear();
return this.clear(this.cacheStoreName, "Image cache was cleared");
}
+1 -1
View File
@@ -1,7 +1,7 @@
// LaTeX.ts
import { DataURL } from "@zsviczian/excalidraw/types/excalidraw/types";
import ExcalidrawView from "../view/ExcalidrawView";
import { FileData, MimeType } from "./EmbeddedFileLoader";
import { FileData, MimeType } from "src/types/embeddedFileLoaderTypes";
import { FileId } from "@zsviczian/excalidraw/types/element/src/types";
import ExcalidrawPlugin from "src/core/main";
+2 -1
View File
@@ -1,13 +1,14 @@
import { ExcalidrawAutomate } from "../ExcalidrawAutomate";
import {Notice, requestUrl} from "obsidian"
import ExcalidrawPlugin from "../../core/main"
import ExcalidrawView, { ExportSettings } from "../../view/ExcalidrawView"
import FrontmatterEditor from "src/shared/Frontmatter";
import { ExcalidrawElement } from "@zsviczian/excalidraw/types/element/src/types";
import { EmbeddedFilesLoader } from "../EmbeddedFileLoader";
import { blobToBase64 } from "src/utils/fileUtils";
import { getEA } from "src/core";
import { log } from "src/utils/debugHelper";
import { ExportSettings } from "src/types/exportUtilTypes";
import ExcalidrawView from "src/view/ExcalidrawView";
const TASKBONE_URL = "https://api.taskbone.com/"; //"https://excalidraw-preview.onrender.com/";
const TASKBONE_OCR_FN = "execute?id=60f394af-85f6-40bc-9613-5d26dc283cbb";
+19 -8
View File
@@ -14,7 +14,7 @@ import { splitFolderAndFilename } from "../utils/fileUtils";
import { getEA } from "src/core";
import { ExcalidrawAutomate } from "../shared/ExcalidrawAutomate";
import { WeakArray } from "./WeakArray";
import { getExcalidrawViews } from "../utils/obsidianUtils";
import { getExcalidrawViews, stripYamlFrontmatter } from "../utils/obsidianUtils";
import { ButtonDefinition, InputPromptOptions } from "src/types/promptTypes";
export type ScriptIconMap = {
@@ -42,7 +42,12 @@ export class ScriptEngine {
this.eaInstances.forEach((ea) => {
if (ea.targetView === view) {
eas.add(ea);
ea.destroy();
if(ea.sidepanelTab) {
ea.targetView = null;
ea.sidepanelTab.onExcalidrawViewClosed();
} else {
ea.destroy();
}
}
});
this.eaInstances.removeObjects(eas);
@@ -180,6 +185,13 @@ export class ScriptEngine {
return basename;
}
public getScriptFileByName(scriptName: string): TFile | null {
return (
this.getListofScripts()?.find((file) => this.getScriptName(file) === scriptName) ??
null
);
}
async addScriptIconToMap(scriptPath: string, name: string) {
const svgFilePath = getIMGFilename(scriptPath, "svg");
const file = this.app.vault.getAbstractFileByPath(svgFilePath);
@@ -211,9 +223,8 @@ export class ScriptEngine {
const view = this.app.workspace.getActiveViewOfType(ExcalidrawView);
if (view) {
(async()=>{
const script = await this.app.vault.read(f);
const script = stripYamlFrontmatter(await this.app.vault.read(f));
if(script) {
//remove YAML frontmatter if present
this.executeScript(view, script, scriptName,f);
}
})()
@@ -250,17 +261,17 @@ export class ScriptEngine {
delete this.app.commands.commands[commandId];
}
async executeScript(view: ExcalidrawView, script: string, title: string, file: TFile) {
if (!view || !script || !title) {
async executeScript(view: ExcalidrawView = undefined, script: string, title: string, file: TFile) {
if (!script || !title) {
return;
}
//addresses the situation when after paste text element IDs are not updated to 8 characters
//linked to onPaste save issue with the false parameter
if(view.getScene().elements.some(el=>!el.isDeleted && el.type === "text" && el.id.length > 8)) {
if(view && view.getScene().elements.some(el=>!el.isDeleted && el.type === "text" && el.id.length > 8)) {
await view.save(false, true);
}
script = script.replace(/^---.*?---\n/gs, "");
script = stripYamlFrontmatter(script);
const ea = getEA(view);
this.eaInstances.push(ea);
ea.activeScript = title;
+12 -1
View File
@@ -17,6 +17,8 @@ export class FileSuggestionModal extends SuggestionModal<LinkSuggestion> {
cache: CachedMetadata;
filesAndAliases: LinkSuggestion[];
file: TFile;
private handleGetFile: () => void;
constructor(app: App, input: TextComponent, items: TFile[], private plugin: ExcalidrawPlugin) {
const filesAndAliases = [];
for (const file of items) {
@@ -36,7 +38,11 @@ export class FileSuggestionModal extends SuggestionModal<LinkSuggestion> {
this.text = input;
this.suggestEl.style.maxWidth = "100%";
this.suggestEl.style.width = `${input.inputEl.clientWidth}px`;
this.inputEl.addEventListener("input", () => this.getFile());
// Pre-bind the handler
this.handleGetFile = this.getFile.bind(this);
this.inputEl.addEventListener("input", this.handleGetFile);
this.setPlaceholder(t("SELECT_FILE_TO_INSERT"));
this.emptyStateText = t("NO_MATCH");
}
@@ -139,4 +145,9 @@ export class FileSuggestionModal extends SuggestionModal<LinkSuggestion> {
getItems() {
return this.filesAndAliases;
}
close(): void {
this.inputEl.removeEventListener("input", this.handleGetFile);
super.close();
}
}
@@ -12,12 +12,16 @@ export class FolderSuggestionModal extends SuggestionModal<TFolder> {
cache: CachedMetadata;
folders: TFolder[];
folder: TFolder;
private handleGetFolder: () => void;
constructor(app: App, input: TextComponent, items: TFolder[]) {
super(app, input.inputEl, items);
this.folders = [...items];
this.text = input;
this.inputEl.addEventListener("input", () => this.getFolder());
// Pre-bind the handler
this.handleGetFolder = this.getFolder.bind(this);
this.inputEl.addEventListener("input", this.handleGetFolder);
}
getFolder() {
const v = this.inputEl.value;
@@ -32,6 +36,10 @@ export class FolderSuggestionModal extends SuggestionModal<TFolder> {
this.onInputChanged();
}
close(): void {
this.inputEl.removeEventListener("input", this.handleGetFolder);
super.close();
}
getItemText(item: TFolder) {
return item.path;
}
@@ -0,0 +1,478 @@
import { App, FuzzyMatch, TFile } from "obsidian";
import { SuggestionModal } from "./SuggestionModal";
import { LinkSuggestion } from "src/types/types";
import ExcalidrawPlugin from "src/core/main";
import {
getLinkSuggestionsFiltered,
getSortedLinkMatches,
renderHeadingSuggestionRow,
renderLinkSuggestion,
renderParagraphSuggestionRow,
fuzzyMatchTextItems,
fuzzyMatchParagraphsWithId,
} from "src/shared/Suggesters/LinkSuggesterUtils";
import { KeyBlocker } from "src/types/excalidrawAutomateTypes";
import { t } from "src/lang/helpers";
import { nanoid } from "src/constants/constants";
import { sleep } from "src/utils/utils";
type HeadingSuggestion = {
kind: "heading";
heading: string;
level: number;
anchor: string;
file: TFile;
};
type ParagraphSuggestion = {
kind: "paragraph";
text: string;
id?: string;
file: TFile;
node: any;
};
type InlineSuggestion = LinkSuggestion | HeadingSuggestion | ParagraphSuggestion;
/**
* Inline link suggester that attaches to a specific input element.
*/
export class InlineLinkSuggester extends SuggestionModal<InlineSuggestion> implements KeyBlocker {
private readonly getSourcePath: () => string | undefined;
private readonly plugin: ExcalidrawPlugin;
private readonly widthHost: HTMLElement;
private readonly hasCustomWidthHost: boolean;
private block = false;
private activeOpen = -1;
private activeClose = -1;
private caretPos = 0;
private activeAlias: string | null = null;
private activeSearchTerm = "";
private activeFile: TFile | null = null;
private mode: "file" | "heading" | "block" | null = null;
private headingItems: HeadingSuggestion[] = [];
private paragraphItems: ParagraphSuggestion[] = [];
constructor(
app: App,
plugin: ExcalidrawPlugin,
inputEl: HTMLInputElement | HTMLTextAreaElement,
getSourcePath: () => string | undefined,
widthWrapper?: HTMLElement,
surpessPlaceholder: boolean = false,
collisionBoundary?: HTMLElement,
) {
const items = getLinkSuggestionsFiltered(app);
super(app, inputEl, items, collisionBoundary);
this.plugin = plugin;
this.getSourcePath = getSourcePath;
this.widthHost = widthWrapper ?? inputEl;
this.hasCustomWidthHost = Boolean(widthWrapper);
this.limit = 20;
if (!surpessPlaceholder) {
this.setPlaceholder(t("INLINE_HINT"));
}
this.emptyStateText = "No match";
this.syncWidth();
}
public isBlockingKeys() {
return this.block;
}
getItems(): InlineSuggestion[] {
return getLinkSuggestionsFiltered(this.app) as InlineSuggestion[];
}
/**
* Keep the suggestion dropdown aligned to the provided width host (input or wrapper).
*/
private syncWidth() {
const hostRect = this.widthHost?.getBoundingClientRect();
const width = hostRect?.width ?? this.widthHost?.clientWidth;
if (width && this.hasCustomWidthHost) {
this.suggestEl.style.width = `${width}px`;
this.suggestEl.style.maxWidth = `${width}px`;
this.suggestEl.style.minWidth = `${width}px`;
return;
}
const minWidth = Math.max(width || this.inputEl.clientWidth || this.inputEl.getBoundingClientRect().width, 450);
if (!minWidth) {
return;
}
const anchorRect = hostRect ?? this.inputEl.getBoundingClientRect();
let availableWidth = this.collisionBoundary
? this.collisionBoundary.innerWidth - 16 //SuggestionModal padding
: Math.max(0, window.innerWidth - anchorRect.left - 16);
if (!this.hasCustomWidthHost) {
availableWidth = minWidth <= 450
? Math.min(availableWidth, 450)
: Math.min(availableWidth, minWidth);
}
const clampedMinWidth = Math.min(minWidth, availableWidth);
this.suggestEl.style.width = "";
this.suggestEl.style.minWidth = `${clampedMinWidth}px`;
this.suggestEl.style.maxWidth = `${availableWidth}px`;
}
/**
* Refreshes the suggestion data (e.g. when vault changes) without recreating the instance.
*/
public refreshItems() {
this.items = getLinkSuggestionsFiltered(this.app) as InlineSuggestion[];
}
modifyInput(input: string): string {
return input;
}
async onInputChanged(): Promise<void> {
const inputStr = this.modifyInput(this.inputEl.value);
this.caretPos = this.inputEl.selectionStart ?? inputStr.length;
if ((this.inputEl.selectionEnd ?? this.caretPos) - (this.inputEl.selectionStart ?? 0) > 0) {
this.resetSuggestions();
return;
}
const active = this.findActiveLink(inputStr, this.caretPos);
if (!active) {
this.resetSuggestions();
return;
}
this.activeOpen = active.open;
this.activeClose = active.close;
const context = this.parseLinkContext(inputStr, this.caretPos, active.open, active.close);
this.activeAlias = context.alias;
this.activeSearchTerm = context.searchTerm;
this.activeFile = context.file;
this.mode = context.mode;
if (context.inAlias) {
this.resetSuggestions();
return;
}
if (this.mode === "heading") {
await this.loadHeadings(this.activeFile);
} else if (this.mode === "block") {
await this.loadParagraphs(this.activeFile);
} else {
this.headingItems = [];
this.paragraphItems = [];
}
this.block = true;
await super.onInputChanged();
}
getSuggestions(query: string): FuzzyMatch<InlineSuggestion>[] {
if (this.activeOpen === -1) return [];
if (this.mode === "heading") {
return fuzzyMatchTextItems(this.activeSearchTerm ?? "", this.headingItems, (h) => h.heading);
}
if (this.mode === "block") {
return fuzzyMatchParagraphsWithId(this.activeSearchTerm ?? "", this.paragraphItems);
}
const term = this.activeSearchTerm ?? "";
return getSortedLinkMatches(term, this.items as LinkSuggestion[]);
}
private isHeading(item: InlineSuggestion): item is HeadingSuggestion {
return (item as HeadingSuggestion)?.kind === "heading";
}
private isParagraph(item: InlineSuggestion): item is ParagraphSuggestion {
return (item as ParagraphSuggestion)?.kind === "paragraph";
}
getItemText(item: InlineSuggestion): string {
if (this.isHeading(item)) {
return item.heading;
}
if (this.isParagraph(item)) {
return item.text;
}
return (item as LinkSuggestion).path + ((item as LinkSuggestion).alias ? `|${(item as LinkSuggestion).alias}` : "");
}
async onChooseItem(item: InlineSuggestion | undefined): Promise<void> {
if (!item) return;
if (this.isHeading(item)) {
const linktext = this.app.metadataCache.fileToLinktext(
item.file,
this.getSourcePath() ?? "",
true,
);
const aliasSuffix = this.activeAlias !== null ? `|${this.activeAlias}` : "";
this.insertLink(`[[${linktext}#${item.anchor}${aliasSuffix}]]`);
return;
}
if (this.isParagraph(item)) {
const id = await this.ensureParagraphHasId(item);
if (!id) return;
const linktext = this.app.metadataCache.fileToLinktext(
item.file,
this.getSourcePath() ?? "",
true,
);
const aliasSuffix = this.activeAlias !== null ? `|${this.activeAlias}` : "";
this.insertLink(`[[${linktext}#^${id}${aliasSuffix}]]`);
return;
}
const linkString = this.buildLink(item as LinkSuggestion);
this.insertLink(linkString);
}
async selectSuggestion(value: FuzzyMatch<InlineSuggestion>, evt: MouseEvent | KeyboardEvent) {
evt?.preventDefault?.();
evt?.stopPropagation?.();
await this.onChooseItem(value?.item);
}
open(): void {
this.block = true;
this.syncWidth();
this.suggestEl.style.pointerEvents = "all";
super.open();
}
renderSuggestion(result: FuzzyMatch<InlineSuggestion>, itemEl: HTMLElement) {
const { item } = result || {};
if (this.isHeading(item as InlineSuggestion)) {
const note = item
? this.app.metadataCache.fileToLinktext((item as HeadingSuggestion).file, this.getSourcePath() ?? "", true)
: "";
renderHeadingSuggestionRow(result as FuzzyMatch<HeadingSuggestion>, note, itemEl);
return;
}
if (this.isParagraph(item as InlineSuggestion)) {
const note = item
? this.app.metadataCache.fileToLinktext((item as ParagraphSuggestion).file, this.getSourcePath() ?? "", true)
: "";
renderParagraphSuggestionRow(result as FuzzyMatch<ParagraphSuggestion>, note, itemEl);
return;
}
renderLinkSuggestion(this.plugin, result as FuzzyMatch<LinkSuggestion>, itemEl, this.emptyStateText);
}
private buildLink(item: LinkSuggestion): string {
const sourcePath = this.getSourcePath();
const aliasFromContext = this.activeAlias;
const aliasSuffix = aliasFromContext !== null
? `|${aliasFromContext}`
: item.alias
? `|${item.alias}`
: "";
if (item.file) {
const linktext = this.app.metadataCache.fileToLinktext(
item.file,
sourcePath ?? "",
true,
);
return `[[${linktext}${aliasSuffix}]]`;
}
// unresolved/ghost
return `[[${item.path}${aliasSuffix}]]`;
}
private insertLink(link: string) {
const cursor = this.inputEl.selectionStart ?? this.inputEl.value.length;
const start = this.activeOpen >= 0 ? this.activeOpen : this.inputEl.value.lastIndexOf("[[", cursor);
if (start === -1) {
return;
}
const closeIndex = this.activeClose >= 0 ? this.activeClose : this.inputEl.value.indexOf("]]", start + 2);
const end = closeIndex >= 0 ? closeIndex + 2 : cursor;
const prefix = this.inputEl.value.substring(0, start);
const suffix = this.inputEl.value.substring(end);
this.inputEl.value = prefix + link + suffix;
this.inputEl.dispatchEvent(new Event("input"));
const newPos = start + link.length;
this.inputEl.setSelectionRange(newPos, newPos);
this.close();
}
private resetSuggestions() {
this.suggester.setSuggestions([]);
if (this.popper?.deref()) {
this.popper.deref().destroy();
}
this.suggestEl.detach();
this.activeOpen = -1;
this.activeClose = -1;
this.activeAlias = null;
this.activeSearchTerm = "";
this.activeFile = null;
this.mode = null;
this.headingItems = [];
this.paragraphItems = [];
setTimeout(() => {
this.block = false;
});
}
private parseLinkContext(value: string, caret: number, open: number, close: number) {
const activeInfo = this.extractActiveInfo(value, caret, open, close);
const closeIndex = close >= 0 ? close : value.length;
const linkText = value.substring(open + 2, closeIndex);
const pipeIndex = linkText.indexOf("|");
const linkWithoutAlias = pipeIndex >= 0 ? linkText.substring(0, pipeIndex) : linkText;
const hashIndex = linkWithoutAlias.indexOf("#");
const caretInLink = Math.max(0, Math.min(caret - (open + 2), linkText.length));
const inSubpath = hashIndex >= 0 && caretInLink > hashIndex;
const isBlockMode = inSubpath && linkWithoutAlias.charAt(hashIndex + 1) === "^";
const basePath = hashIndex >= 0 ? linkWithoutAlias.substring(0, hashIndex) : linkWithoutAlias;
const subpathTerm = inSubpath
? linkWithoutAlias.substring(hashIndex + (isBlockMode ? 2 : 1), caretInLink)
: "";
const file = basePath
? this.app.metadataCache.getFirstLinkpathDest(basePath, this.getSourcePath() ?? "")
: null;
const mode = file && file.extension === "md" && inSubpath ? (isBlockMode ? "block" : "heading") : "file";
const searchTerm = mode === "file" ? activeInfo.searchTerm : subpathTerm;
return {
alias: activeInfo.alias,
inAlias: activeInfo.inAlias,
searchTerm,
file: mode === "file" ? null : file,
mode,
} as const;
}
private async loadHeadings(file: TFile | null) {
if (!file || file.extension !== "md") {
this.headingItems = [];
return;
}
const cache = await this.app.metadataCache.blockCache.getForFile({ isCancelled: () => false }, file);
const blocks = cache?.blocks ?? [];
this.headingItems = blocks
.filter((b: any) => b.display && b.node?.type === "heading")
.map((b: any) => ({
kind: "heading",
heading: this.cleanHeading(b.display),
anchor: this.cleanHeading(b.display),
level: b.node?.depth ?? b.node?.level ?? 1,
file,
}));
}
private async loadParagraphs(file: TFile | null) {
if (!file || file.extension !== "md") {
this.paragraphItems = [];
return;
}
const cache = await this.app.metadataCache.blockCache.getForFile({ isCancelled: () => false }, file);
const blocks = cache?.blocks ?? [];
this.paragraphItems = blocks
.filter((b: any) =>
b.display &&
b.node &&
(b.node.type === "paragraph" ||
b.node.type === "blockquote" ||
b.node.type === "listItem" ||
b.node.type === "table" ||
b.node.type === "callout"),
)
.map((b: any) => ({
kind: "paragraph",
text: b.display.trim(),
id: b.node?.id,
node: b.node,
file,
}));
}
private cleanHeading(display: string): string {
return display.replace(/^#+\s*/, "").trim();
}
private async ensureParagraphHasId(item: ParagraphSuggestion): Promise<string | null> {
if (item.id) return item.id;
const offset = item.node?.position?.end?.offset;
if (!offset) return null;
const fileContents = await this.plugin.app.vault.cachedRead(item.file);
const newId = nanoid();
await this.plugin.app.vault.modify(
item.file,
`${fileContents.slice(0, offset)} ^${newId}${fileContents.slice(offset)}`,
);
await sleep(200);
item.id = newId;
return newId;
}
// Keep listeners so the suggester can trigger multiple times in the same input session.
close(): void {
this.app.keymap.popScope(this.scope);
this.suggester.setSuggestions([]);
if (this.popper?.deref()) {
this.popper.deref().destroy();
}
this.suggestEl.detach();
this.shouldNotOpen = false;
setTimeout(() => {
this.block = false;
});
}
onEscape(): void {
this.close();
this.shouldNotOpen = false;
}
private findActiveLink(value: string, pos: number): {open: number; close: number} | null {
let searchFrom = 0;
let candidate: {open: number; close: number} | null = null;
while (true) {
const open = value.indexOf("[[", searchFrom);
if (open === -1 || open > pos) break;
const close = value.indexOf("]]", open + 2);
if (close === -1 || pos <= close) {
candidate = { open, close };
break;
}
searchFrom = close + 2;
}
return candidate;
}
private extractActiveInfo(value: string, caret: number, open: number, close: number): {alias: string | null; inAlias: boolean; searchTerm: string} {
const closeIndex = close >= 0 ? close : value.length;
const linkText = value.substring(open + 2, closeIndex);
const caretInLink = Math.max(0, Math.min(caret - (open + 2), linkText.length));
const pipeIndex = linkText.indexOf("|");
const alias = pipeIndex >= 0 ? linkText.substring(pipeIndex + 1) : null;
const inAlias = pipeIndex >= 0 && caretInLink > pipeIndex;
const linkPart = pipeIndex >= 0 ? linkText.substring(0, pipeIndex) : linkText;
const caretInLinkPart = Math.min(caretInLink, linkPart.length);
const rawTerm = linkPart.substring(0, caretInLinkPart);
const searchTerm = rawTerm.replace(/^.*[\\/]/, "");
return { alias, inAlias, searchTerm };
}
}
+268
View File
@@ -0,0 +1,268 @@
import { App, FuzzyMatch, prepareFuzzySearch, setIcon } from "obsidian";
import { LinkSuggestion } from "src/types/types";
import {
AUDIO_TYPES,
CODE_TYPES,
ICON_NAME,
IMAGE_TYPES,
REG_LINKINDEX_INVALIDCHARS,
VIDEO_TYPES,
} from "src/constants/constants";
import ExcalidrawPlugin from "src/core/main";
/**
* Returns Obsidian link suggestions (files, aliases, unresolved) filtered for invalid characters.
*/
export const getLinkSuggestionsFiltered = (app: App): LinkSuggestion[] => {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore Obsidian internal helper
const suggestions = app.metadataCache.getLinkSuggestions?.();
if (!suggestions) return [];
const filtered = suggestions.filter((x: LinkSuggestion) => !x.path.match(REG_LINKINDEX_INVALIDCHARS));
const now = Date.now();
const weekMs = 7 * 24 * 60 * 60 * 1000;
const isRecent = (s: LinkSuggestion) => !!s.file && now - s.file.stat.mtime <= weekMs;
return filtered.sort((a: LinkSuggestion, b: LinkSuggestion) => {
const aRecent = isRecent(a);
const bRecent = isRecent(b);
if (aRecent !== bRecent) {
return aRecent ? -1 : 1; // recent first
}
if (aRecent && bRecent && a.file && b.file && a.file.stat.mtime !== b.file.stat.mtime) {
return b.file.stat.mtime - a.file.stat.mtime; // newer recent first
}
const aKey = `${a.path}${a.alias ?? ""}`.toLowerCase();
const bKey = `${b.path}${b.alias ?? ""}`.toLowerCase();
return aKey.localeCompare(bKey);
});
};
/**
* Returns fuzzy matches sorted by fuzzy score, then recency, then name for stability.
*/
export const getSortedLinkMatches = (
term: string,
items: LinkSuggestion[],
): FuzzyMatch<LinkSuggestion>[] => {
const search = prepareFuzzySearch(term);
const matches = items
.map((item) => {
const target = `${item.path}${item.alias ? `|${item.alias}` : ""}`;
const matchFull = search(target);
if (!item.alias) {
return matchFull ? { item, match: matchFull } : null;
}
// Also search alias alone; if better, shift ranges to alias segment in the full string
const matchAliasOnly = search(item.alias);
let best = matchFull;
if (matchAliasOnly && (!best || matchAliasOnly.score > best.score)) {
const aliasOffset = item.path.length + 1; // position where alias starts in "path|alias"
const shiftedMatches = matchAliasOnly.matches.map(([from, to]) => [from + aliasOffset, to + aliasOffset]) as [number, number][];
best = { ...matchAliasOnly, matches: shiftedMatches } as typeof matchAliasOnly;
}
return best ? { item, match: best } : null;
})
.filter(Boolean) as FuzzyMatch<LinkSuggestion>[];
const now = Date.now();
const weekMs = 7 * 24 * 60 * 60 * 1000;
const isRecent = (s: LinkSuggestion) => !!s.file && now - s.file.stat.mtime <= weekMs;
return matches.sort((a, b) => {
const aScore = a?.match?.score ?? 0;
const bScore = b?.match?.score ?? 0;
if (aScore !== bScore) return bScore - aScore;
const aRecent = isRecent(a.item);
const bRecent = isRecent(b.item);
if (aRecent !== bRecent) return aRecent ? -1 : 1; // recent first
if (aRecent && bRecent && a.item.file && b.item.file && a.item.file.stat.mtime !== b.item.file.stat.mtime) {
return b.item.file.stat.mtime - a.item.file.stat.mtime; // newer recent first
}
const aKey = `${a.item.path}${a.item.alias ?? ""}`.toLowerCase();
const bKey = `${b.item.path}${b.item.alias ?? ""}`.toLowerCase();
return aKey.localeCompare(bKey);
});
};
const renderTextWithHighlights = (titleEl: HTMLElement, text: string, matches: [number, number][]) => {
if (!matches?.length) {
titleEl.setText(text);
return;
}
const sorted = [...matches].sort((a, b) => a[0] - b[0]);
for (let i = 0; i < text.length; i++) {
const match = sorted.find((m) => m[0] === i);
if (match) {
const span = createSpan("suggestion-highlight");
span.appendText(text.substring(match[0], match[1]));
titleEl.appendChild(span);
i = match[1] - 1;
continue;
}
titleEl.appendText(text[i]);
}
};
export const fuzzyMatchTextItems = <T>(
term: string,
items: T[],
getText: (item: T) => string,
): FuzzyMatch<T>[] => {
const search = prepareFuzzySearch(term ?? "");
return items
.map((item) => {
const match = search(getText(item));
return match ? { item, match } : null;
})
.filter(Boolean) as FuzzyMatch<T>[];
};
export const fuzzyMatchParagraphsWithId = <T extends { id?: string; text: string }>(
term: string,
items: T[],
): FuzzyMatch<T>[] => {
const search = prepareFuzzySearch(term ?? "");
const needle = term?.trim().replace(/^\^/, "").toLowerCase();
return items
.map((item) => {
const display = `${item.id ? `^${item.id} ` : ""}${item.text}`;
const match = search(display);
if (!match) return null;
if (item.id && needle) {
const idLower = item.id.toLowerCase();
if (idLower === needle) {
match.score = Number.MAX_SAFE_INTEGER; // strongest priority for exact id
} else if (idLower.includes(needle)) {
match.score = match.score + 1000; // strong priority if id contains term
}
}
return { item, match } as FuzzyMatch<T>;
})
.filter(Boolean)
.sort((a, b) => (b.match?.score ?? 0) - (a.match?.score ?? 0)) as FuzzyMatch<T>[];
};
export const renderHeadingSuggestionRow = (
result: FuzzyMatch<{ heading: string; level?: number }>,
note: string,
itemEl: HTMLElement,
) => {
const { item, match } = result || {};
itemEl.addClass("suggestion-item");
itemEl.addClass("mod-complex");
const contentEl = itemEl.createDiv("suggestion-content");
const titleEl = contentEl.createDiv("suggestion-title");
if (!item) {
titleEl.setText("No match");
itemEl.addClass("is-selected");
return;
}
renderTextWithHighlights(titleEl, item.heading, match?.matches ?? []);
const noteEl = contentEl.createDiv("suggestion-note");
noteEl.setText(note ?? "");
const auxEl = itemEl.createDiv("suggestion-aux");
const flair = auxEl.createSpan("suggestion-flair");
flair.setText(`H${item.level ?? 1}`);
};
export const renderParagraphSuggestionRow = (
result: FuzzyMatch<{ text: string; id?: string }>,
note: string,
itemEl: HTMLElement,
) => {
const { item, match } = result || {};
itemEl.addClass("suggestion-item");
itemEl.addClass("mod-complex");
const contentEl = itemEl.createDiv("suggestion-content");
const titleEl = contentEl.createDiv("suggestion-title");
if (!item) {
titleEl.setText("No match");
itemEl.addClass("is-selected");
return;
}
const display = `${item.id ? `^${item.id} ` : ""}${item.text}`;
renderTextWithHighlights(titleEl, display, match?.matches ?? []);
const noteEl = contentEl.createDiv("suggestion-note");
noteEl.setText(note ?? "");
if (item.id) {
const auxEl = itemEl.createDiv("suggestion-aux");
const flair = auxEl.createSpan("suggestion-flair");
flair.setText(`^${item.id}`);
}
};
/**
* Standard rendering for link suggestions with icons and highlights.
*/
export const renderLinkSuggestion = (
plugin: ExcalidrawPlugin,
result: FuzzyMatch<LinkSuggestion>,
itemEl: HTMLElement,
emptyStateText: string,
) => {
const { item, match: matches } = result || {};
itemEl.addClass("mod-complex");
const contentEl = itemEl.createDiv("suggestion-content");
const auxEl = itemEl.createDiv("suggestion-aux");
const titleEl = contentEl.createDiv("suggestion-title");
const noteEl = contentEl.createDiv("suggestion-note");
if (!item) {
titleEl.setText(emptyStateText);
itemEl.addClass("is-selected");
return;
}
const path = item.file?.path ?? item.path;
// For unresolved (ghost) files, highlight the full path. For resolved files, skip folder prefixes.
const pathLength = item.file ? path.length - (item.file?.name.length ?? 0) : 0;
const matchElements = matches.matches.map(() => createSpan("suggestion-highlight"));
const itemText = item.path + (item.alias ? `|${item.alias}` : "");
for (let i = pathLength; i < itemText.length; i++) {
const match = matches.matches.find((m) => m[0] === i);
if (match) {
const element = matchElements[matches.matches.indexOf(match)];
titleEl.appendChild(element);
element.appendText(itemText.substring(match[0], match[1]));
i += match[1] - match[0] - 1;
continue;
}
titleEl.appendText(itemText[i]);
}
noteEl.setText(path);
if (!item.file) {
setIcon(auxEl, "ghost");
} else if (plugin.isExcalidrawFile(item.file)) {
setIcon(auxEl, ICON_NAME);
} else if (item.file.extension === "md") {
setIcon(auxEl, "square-pen");
} else if (IMAGE_TYPES.includes(item.file.extension)) {
setIcon(auxEl, "image");
} else if (VIDEO_TYPES.includes(item.file.extension)) {
setIcon(auxEl, "monitor-play");
} else if (AUDIO_TYPES.includes(item.file.extension)) {
setIcon(auxEl, "file-audio");
} else if (CODE_TYPES.includes(item.file.extension)) {
setIcon(auxEl, "file-code");
} else if (item.file.extension === "canvas") {
setIcon(auxEl, "layout-dashboard");
} else if (item.file.extension === "pdf") {
setIcon(auxEl, "book-open-text");
} else {
auxEl.setText(item.file.extension);
}
};
+17 -2
View File
@@ -16,13 +16,16 @@ export class PathSuggestionModal extends SuggestionModal<
files: TFile[];
text: TextComponent;
cache: CachedMetadata;
private handleGetFile: () => void;
constructor(app: App, input: TextComponent, items: TFile[]) {
super(app, input.inputEl, items);
this.files = [...items];
this.text = input;
//this.getFile();
this.inputEl.addEventListener("input", this.getFile.bind(this));
// Pre-bind the handler
this.handleGetFile = this.getFile.bind(this);
this.inputEl.addEventListener("input", this.handleGetFile);
}
getFile() {
@@ -40,6 +43,12 @@ export class PathSuggestionModal extends SuggestionModal<
}
this.onInputChanged();
}
close(): void {
this.inputEl.removeEventListener("input", this.handleGetFile);
super.close();
}
getItemText(item: TFile | HeadingCache | BlockCache) {
if (item instanceof TFile) {
return item.path;
@@ -51,6 +60,7 @@ export class PathSuggestionModal extends SuggestionModal<
return (<BlockCache>item).id;
}
}
onChooseItem(item: TFile | HeadingCache | BlockCache) {
if (item instanceof TFile) {
this.text.setValue(item.basename);
@@ -64,6 +74,7 @@ export class PathSuggestionModal extends SuggestionModal<
this.text.setValue(`${this.file.basename}^${(<BlockCache>item).id}`);
}
}
selectSuggestion({ item }: FuzzyMatch<TFile | BlockCache | HeadingCache>) {
let link: string;
if (item instanceof TFile) {
@@ -79,6 +90,7 @@ export class PathSuggestionModal extends SuggestionModal<
this.close();
}
renderSuggestion(
result: FuzzyMatch<TFile | BlockCache | HeadingCache>,
el: HTMLElement,
@@ -131,6 +143,7 @@ export class PathSuggestionModal extends SuggestionModal<
content.setText((<BlockCache>item).id);
}
}
get headings() {
if (!this.file) {
return [];
@@ -140,6 +153,7 @@ export class PathSuggestionModal extends SuggestionModal<
}
return this.cache.headings || [];
}
get blocks() {
if (!this.file) {
return [];
@@ -149,6 +163,7 @@ export class PathSuggestionModal extends SuggestionModal<
}
return Object.values(this.cache.blocks || {}) || [];
}
getItems() {
const v = this.inputEl.value;
if (/#/.test(v)) {
+59 -33
View File
@@ -6,6 +6,7 @@ import {
} from "obsidian";
import { createPopper, Instance as PopperInstance } from "@popperjs/core";
import { Suggester } from "./Suggester";
import { t } from "src/lang/helpers";
export abstract class SuggestionModal<T> extends FuzzySuggestModal<T> {
items: T[] = [];
@@ -16,27 +17,39 @@ export abstract class SuggestionModal<T> extends FuzzySuggestModal<T> {
suggester: Suggester<FuzzyMatch<T>>;
suggestEl: HTMLDivElement;
promptEl: HTMLDivElement;
emptyStateText: string = "No match found";
emptyStateText: string = t("SUGGESTION_NOMATCH");
limit: number = 100;
shouldNotOpen: boolean;
constructor(app: App, inputEl: HTMLInputElement, items: T[]) {
// Pre-bound event handlers
private handleInput: () => void;
private handleFocus: () => void;
private handleBlur: () => void;
private handleMouseDown: (event: MouseEvent) => void;
public readonly collisionBoundary?: HTMLElement;
constructor(app: App, inputEl: HTMLInputElement | HTMLTextAreaElement, items: T[], collisionBoundary?: HTMLElement) {
super(app);
this.inputEl = inputEl;
this.inputEl = inputEl as HTMLInputElement;
this.items = items;
this.collisionBoundary = collisionBoundary;
// Pre-bind event handlers
this.handleInput = this.onInputChanged.bind(this);
this.handleFocus = this.onFocus.bind(this);
this.handleBlur = this.close.bind(this);
this.handleMouseDown = (event: MouseEvent) => {
event.preventDefault();
};
this.suggestEl = createDiv("suggestion-container");
this.contentEl = this.suggestEl.createDiv("suggestion");
this.suggester = new Suggester(this, this.contentEl, this.scope);
this.scope.register([], "Escape", this.onEscape.bind(this));
this.inputEl.addEventListener("input", this.onInputChanged.bind(this));
this.inputEl.addEventListener("focus", this.onFocus.bind(this));
this.inputEl.addEventListener("blur", this.close.bind(this));
this.suggestEl.on(
"mousedown",
".suggestion-container",
(event: MouseEvent) => {
event.preventDefault();
},
);
this.inputEl.addEventListener("input", this.handleInput);
this.inputEl.addEventListener("focus", this.handleFocus);
this.inputEl.addEventListener("blur", this.handleBlur);
this.suggestEl.on("mousedown", ".suggestion-container", this.handleMouseDown);
}
empty() {
@@ -74,24 +87,37 @@ export abstract class SuggestionModal<T> extends FuzzySuggestModal<T> {
open(): void {
// TODO: Figure out a better way to do this. Idea from Periodic Notes plugin
this.app.keymap.pushScope(this.scope);
this.inputEl.ownerDocument.body.appendChild(this.suggestEl);
this.popper = new WeakRef(createPopper(this.inputEl, this.suggestEl, {
placement: "bottom-start",
modifiers: [
{
name: "offset",
options: {
offset: [0, 10],
//setTimeout(() => {
const modal = this.inputEl.closest(".modal");
const modalContainer =
(this.inputEl.closest(".modal-container") as HTMLElement) ??
(modal?.parentElement?.matches(".modal-container")
? (modal.parentElement as HTMLElement)
: null);
const host = modalContainer ?? this.inputEl.ownerDocument.body;
host.appendChild(this.suggestEl);
const boundary = this.collisionBoundary ?? host;
this.popper = new WeakRef(createPopper(this.inputEl, this.suggestEl, {
placement: "bottom-start",
strategy: host.matches(".modal-container") ? "absolute" : "fixed",
modifiers: [
{ name: "offset", options: { offset: [0, 10] } },
{ name: "flip", options: { fallbackPlacements: ["top"] } },
{ name:
"preventOverflow",
options: {
boundary,
altBoundary: true,
padding: { left: 8, right: 8 },
}
},
},
{
name: "flip",
options: {
fallbackPlacements: ["top"],
},
},
],
}));
],
}));
//},50);
}
onEscape(): void {
@@ -106,9 +132,9 @@ export abstract class SuggestionModal<T> extends FuzzySuggestModal<T> {
if (this.popper?.deref()) {
this.popper.deref().destroy();
}
this.inputEl.removeEventListener("input", this.onInputChanged.bind(this));
this.inputEl.removeEventListener("focus", this.onFocus.bind(this));
this.inputEl.removeEventListener("blur", this.close.bind(this));
this.inputEl.removeEventListener("input", this.handleInput);
this.inputEl.removeEventListener("focus", this.handleFocus);
this.inputEl.removeEventListener("blur", this.handleBlur);
this.suggestEl.detach();
}
+46
View File
@@ -0,0 +1,46 @@
type MessageContent =
| string
| (string | { type: "image_url"; image_url: string })[];
export type GPTCompletionRequest = {
model: string;
messages?: {
role?: "system" | "user" | "assistant" | "function";
content?: MessageContent;
name?: string | undefined;
}[];
functions?: any[] | undefined;
function_call?: any | undefined;
stream?: boolean | undefined;
temperature?: number | undefined;
top_p?: number | undefined;
max_tokens?: number | undefined;
n?: number | undefined;
best_of?: number | undefined;
frequency_penalty?: number | undefined;
presence_penalty?: number | undefined;
logit_bias?:
| {
[x: string]: number;
}
| undefined;
stop?: (string[] | string) | undefined;
size?: string;
quality?: "standard" | "hd";
prompt?: string;
image?: string;
mask?: string;
};
export type AIRequest = {
image?: string;
text?: string;
instruction?: string;
systemPrompt?: string;
imageGenerationProperties?: {
size?: string; //depends on model
quality?: "standard" | "hd"; //depends on model
n?: number; //dall-e-3 only accepts 1
mask?: string; //dall-e-2 only (image editing)
};
};
+52
View File
@@ -0,0 +1,52 @@
import { FileId } from "@zsviczian/excalidraw/types/element/src/types";
import { BinaryFileData, DataURL } from "@zsviczian/excalidraw/types/excalidraw/types";
import { ValueOf } from "../types/types";
export const IMAGE_MIME_TYPES = {
svg: "image/svg+xml",
png: "image/png",
jpg: "image/jpeg",
jpeg: "image/jpeg",
gif: "image/gif",
webp: "image/webp",
bmp: "image/bmp",
ico: "image/x-icon",
avif: "image/avif",
jfif: "image/jfif",
} as const;
export type ImgData = {
mimeType: MimeType;
fileId: FileId;
dataURL: DataURL;
created: number;
hasSVGwithBitmap: boolean;
size: Size;
pdfPageViewProps?: PDFPageViewProps;
};
export declare type MimeType = ValueOf<typeof IMAGE_MIME_TYPES> | "application/octet-stream";
export type FileData = BinaryFileData & {
size: Size;
hasSVGwithBitmap: boolean;
shouldScale: boolean; //true if image should maintain its area, false if image should display at 100% its size
pdfPageViewProps?: PDFPageViewProps;
};
export type PDFPageViewProps = {
left: number;
bottom: number;
right: number;
top: number;
rotate?: number; //may be undefined in legacy files
}
export type Size = {
height: number;
width: number;
};
export interface ColorMap {
[color: string]: string;
};
+19 -2
View File
@@ -1,7 +1,7 @@
import { DataURL } from "@zsviczian/excalidraw/types/excalidraw/types";
import { TFile } from "obsidian";
import { FileId } from "src/core";
import { ColorMap, MimeType, PDFPageViewProps, Size } from "src/shared/EmbeddedFileLoader";
import { ColorMap, PDFPageViewProps, Size, MimeType } from "./embeddedFileLoaderTypes";
export type SVGColorInfo = Map<string, {
mappedTo: string;
@@ -9,6 +9,23 @@ export type SVGColorInfo = Map<string, {
stroke: boolean;
}>;
export type ScriptSettingValue = {
value?:string | number | boolean,
hidden?: boolean,
description?: string,
valueset?: string[],
height?: number, //height of textarea in Plugin Settings if type is string
};
/**
* Marker for UI helpers (e.g., suggesters) that, while active, should signal
* host scripts to ignore or block their own keydown handlers.
*/
export interface KeyBlocker {
isBlockingKeys(): boolean;
close(): void;
}
export type ImageInfo = {
mimeType: MimeType,
id: FileId,
@@ -31,4 +48,4 @@ export interface AddImageOptions {
scale?: boolean;
anchor?: boolean;
colorMap?: ColorMap;
}
}
+1 -7
View File
@@ -106,13 +106,6 @@ declare namespace ExcalidrawLib {
},
): { x: number; y: number };
function determineFocusDistance(
element: ExcalidrawBindableElement,
elementsMap: ElementsMap,
a: GlobalPoint,
b: GlobalPoint,
): number;
function intersectElementWithLine(
element: ExcalidrawBindableElement,
a: GlobalPoint,
@@ -233,5 +226,6 @@ declare namespace ExcalidrawLib {
function loadMermaid(): Promise<any>;
function syncInvalidIndices(elements: readonly ExcalidrawElement[]): OrderedExcalidrawElement[];
function syncMovedIndices(elements: readonly ExcalidrawElement[], movedElements: ElementsMap): OrderedExcalidrawElement[];
function getDefaultColorPalette(): [string, string, string, string, string][];
}
+66
View File
@@ -0,0 +1,66 @@
import { FrameRenderingOptions } from "./utilTypes";
export type PDFPageAlignment =
| "center"
| "top-left"
| "top-center"
| "top-right"
| "bottom-left"
| "bottom-center"
| "bottom-right"
| "center-left"
| "center-right";
export type PDFPageMarginString = "none" | "tiny" | "normal";
export interface PDFExportScale {
fitToPage: number; // 0 means use zoom, >1 means fit to that many pages exactly
zoom?: number;
}
export interface PDFMargin {
left: number;
right: number;
top: number;
bottom: number;
}
export interface PDFPageProperties {
dimensions?: {width: number; height: number};
backgroundColor?: string;
margin: PDFMargin;
alignment: PDFPageAlignment;
}
export interface PageDimensions {
width: number;
height: number;
}
export type PageOrientation = "portrait" | "landscape";
// All dimensions in pixels (pt)
export const STANDARD_PAGE_SIZES = {
A0: { width: 3179.52, height: 4494.96 }, // 33.11 × 46.81 inches
A1: { width: 2245.76, height: 3179.52 }, // 23.39 × 33.11 inches
A2: { width: 1587.76, height: 2245.76 }, // 16.54 × 23.39 inches
A3: { width: 1122.56, height: 1587.76 }, // 11.69 × 16.54 inches
A4: { width: 794.56, height: 1122.56 }, // 8.27 × 11.69 inches
A5: { width: 559.37, height: 794.56 }, // 5.83 × 8.27 inches
A6: { width: 397.28, height: 559.37 }, // 4.13 × 5.83 inches
Legal: { width: 816, height: 1344 }, // 8.5 × 14 inches
Letter: { width: 816, height: 1056 }, // 8.5 × 11 inches
Tabloid: { width: 1056, height: 1632 }, // 11 × 17 inches
Ledger: { width: 1632, height: 1056 }, // 17 × 11 inches
"HD Screen": { width: 1920, height: 1080 },// 16:9 aspect ratio
"MATCH IMAGE": { width: 0, height: 0 }, // 0 means use the current screen size
} as const;
export type PageSize = keyof typeof STANDARD_PAGE_SIZES;
export interface ExportSettings {
withBackground: boolean;
withTheme: boolean;
isMask: boolean;
frameRendering?: FrameRenderingOptions; //optional, overrides relevant appState settings for rendering the frame
skipInliningFonts?: boolean;
}
+1 -1
View File
@@ -1,4 +1,4 @@
export type ButtonDefinition = { caption: string; tooltip?:string; action: Function };
export type ButtonDefinition = { caption: string; tooltip?:string; action: Function, iconId?: string };
export interface InputPromptOptions {
header: string,
+73
View File
@@ -0,0 +1,73 @@
import { ExcalidrawAutomate } from "src/shared/ExcalidrawAutomate";
import type ExcalidrawView from "src/view/ExcalidrawView";
/**
* SidepanelTab defines the public surface of a sidepanel tab as exposed to scripts.
* Tabs are lightweight modal-like containers with their own DOM (title/content) that the host sidepanel activates, focuses, and closes.
* Typical flow for scripts:
* 1) Create the tab via ea.createSidepanelTab(title, persist=false, reveal=true). Note the sidepanelTab is immediately created even if not revealed.
* If the sidepanel tab is the first in the sidepanel, then onOpen will not be called becase the tab is already open/active.
* Reveal simply opens the obisidan sidepanel and the Excalidraw sidepanel view which already displays the active tab.
* 2) Render UI into `contentEl` or use `setContent(...)` / `setTitle(...)`.
* 3) Implement lifecycle hooks: `onOpen` (only runs when the user changes tabs in the Excalidraw sidepanel), `onFocus(view)` (runs on host focus changes), `onClose`/`setCloseCallback` (cleanup), `onExcalidrawViewClosed` (canvas closed).
* Use `onWindowMigrated(win)` to reattach any window-bound event handlers if the sidepanel moves between the main workspace and a popout window (the DOM is reparented during this migration). The `win` argument is the new Window hosting the sidepanel DOM.
* 4) Use `setDisabled`, `focus`, `close`, `reset`, and persistence helpers (from host) as needed.
* 5) Use ea.sidepanelTab.open() to show the sidepanel tab associated with the script.
* 6) When the sidepanel is nolonger required the script should call ea.sidepanelTab.close() to close the tab and trigger cleanup.
* The sidpanel associated with an ea script is available on ea.sidepanelTab. Persisted tabs are restored on Obsidian startup, such that scripts associated with the persisted tabs are
* loaded and executed on Excalidraw startup, and the scripts are in turn responsible for recreating their sidepanel tabs via ea.createSidepanelTab as per their normal script initiation sequence.
* This description is intentionally explicit so an LLM can generate sidepanel-aware script code without inspecting the implementation.
*/
export interface SidepanelTab {
/** Unique tab identifier used by the host sidepanel. */
readonly id: string;
/** Optional script name backing this tab (used for persistence and lookup). */
readonly scriptName?: string;
/** Current title shown in the sidepanel selector. */
readonly title: string;
/** Root container element for the tab (same as modalEl). */
readonly containerEl: HTMLDivElement;
/** Wrapper element for the tab. */
readonly modalEl: HTMLDivElement;
/** Content element where scripts render their UI. */
readonly contentEl: HTMLDivElement;
/** Title element whose text mirrors `title`. */
readonly titleEl: HTMLDivElement;
/**
* Focus hook fired when the host marks this tab active; set by scripts.
* Because sidpanel tabs may outlive their associated Excalidraw views on focus is designed to notify scripts of the most recently active view.
* The script can verify if the view has changed by comparing against ea.targetView (ea.targetView === view means no change).
* The script is responsible for calling ea.setView(view) if it wishes to bind to the new view.
* The script may also wish to call ea.clear() or ea.reset() to discard state associated with the prior view.
* In case the script performs view specific actions it should update its UI in onFocus when the received view !== ea.targetView.
* @param view The most recently active ExcalidrawView, or null if no ExcalidrawViews are present in the workspace.
*/
onFocus: (view: ExcalidrawView | null) => void;
/** Hook fired when the associated Excalidraw view closes; set by ScriptEngine. */
onExcalidrawViewClosed: () => void;
/** Hook fired when the sidepanel's DOM is migrated to another window (e.g., into or out of a popout) so scripts can rebind listeners. */
onWindowMigrated: (win: Window) => void;
/** Clears all children from the content element. */
clear(): void;
/** Sets the tab title and updates host UI; returns the tab for chaining. */
setTitle(title: string): this;
/** Replaces tab content with text or a fragment; returns the tab for chaining. */
setContent(content: string | DocumentFragment): this;
/** Activates this tab within the host sidepanel. */
focus(): void;
/** Marks the tab open, activates it, and triggers `onOpen`. */
open(): void;
/** Runs close handlers then asks the host to remove the tab. */
close(): void;
/** Lifecycle hook called when the tab is opened/activated. */
onOpen(): Promise<void> | void;
/** Lifecycle hook called once when the tab closes. */
onClose(): void;
/** Toggles pointer interactivity and opacity; returns the tab for chaining. */
setDisabled(disabled: boolean): this;
/** Returns the ExcalidrawAutomate instance associated with the sidepanel tab */
getHostEA(): ExcalidrawAutomate;
/** Returns whether the tab is currently visible in the UI */
isVisible(): boolean;
}
+4 -49
View File
@@ -1,52 +1,6 @@
import { Notice, RequestUrlResponse } from "obsidian";
import ExcalidrawPlugin from "src/core/main";
type MessageContent =
| string
| (string | { type: "image_url"; image_url: string })[];
export type GPTCompletionRequest = {
model: string;
messages?: {
role?: "system" | "user" | "assistant" | "function";
content?: MessageContent;
name?: string | undefined;
}[];
functions?: any[] | undefined;
function_call?: any | undefined;
stream?: boolean | undefined;
temperature?: number | undefined;
top_p?: number | undefined;
max_tokens?: number | undefined;
n?: number | undefined;
best_of?: number | undefined;
frequency_penalty?: number | undefined;
presence_penalty?: number | undefined;
logit_bias?:
| {
[x: string]: number;
}
| undefined;
stop?: (string[] | string) | undefined;
size?: string;
quality?: "standard" | "hd";
prompt?: string;
image?: string;
mask?: string;
};
export type AIRequest = {
image?: string;
text?: string;
instruction?: string;
systemPrompt?: string;
imageGenerationProperties?: {
size?: string; //depends on model
quality?: "standard" | "hd"; //depends on model
n?: number; //dall-e-3 only accepts 1
mask?: string; //dall-e-2 only (image editing)
};
};
import { GPTCompletionRequest, AIRequest } from "src/types/AIUtilTypes";
const handleImageEditPrompt = async (request: AIRequest) : Promise<RequestUrlResponse> => {
const plugin: ExcalidrawPlugin = window.ExcalidrawAutomate.plugin;
@@ -104,6 +58,7 @@ const handleGenericPrompt = async (request: AIRequest) : Promise<RequestUrlRespo
const {
openAIAPIToken,
openAIDefaultTextModel,
openAIDefaultTextModelMaxTokens,
openAIDefaultVisionModel,
openAIURL,
openAIImageGenerationURL,
@@ -118,7 +73,7 @@ const handleGenericPrompt = async (request: AIRequest) : Promise<RequestUrlRespo
case "text":
body = {
model: openAIDefaultTextModel,
max_tokens: 4096,
...(openAIDefaultTextModelMaxTokens > 0 && { max_tokens: openAIDefaultTextModelMaxTokens }),
messages: [
...(systemPrompt && systemPrompt.trim() !=="" ? [{role: "system" as const,content: systemPrompt}] : []),
{
@@ -132,7 +87,7 @@ const handleGenericPrompt = async (request: AIRequest) : Promise<RequestUrlRespo
case "image":
body = {
model: openAIDefaultVisionModel,
max_tokens: 4096,
...(openAIDefaultTextModelMaxTokens > 0 && { max_tokens: openAIDefaultTextModelMaxTokens }),
messages: [
...(systemPrompt && systemPrompt.trim() !=="" ? [{role: "system" as const,content: systemPrompt}] : []),
{
+1 -1
View File
@@ -1,7 +1,7 @@
//for future use, not used currently
import { ImageCrop } from "@zsviczian/excalidraw/types/element/src/types";
import { PDFPageViewProps } from "src/shared/EmbeddedFileLoader";
import { PDFPageViewProps } from "src/types/embeddedFileLoaderTypes";
export function getPDFCropRect (props: {
scale: number,
+26
View File
@@ -1,10 +1,36 @@
const REG_YOUTUBE = /^(?:http(?:s)?:\/\/)?(?:www\.)?youtu(?:be\.com|\.be)\/(embed\/|watch\?v=|shorts\/|playlist\?list=|embed\/videoseries\?list=)?([a-zA-Z0-9_-]+)(?:\?t=|.*&t=|\?start=|.*&start=)?([a-zA-Z0-9_-]+)?[^\s]*$/;
const REG_VIMEO = /^(?:http(?:s)?:\/\/)?(?:(?:w){3}\.)?(?:player\.)?vimeo\.com\/(?:video\/)?([^?\s]+)(?:\?.*)?$/;
export const isVimeo = (url: string): boolean => {
return Boolean(
url.match(REG_VIMEO)
);
}
export const isYouTube = (url: string): boolean => {
return Boolean(
url.match(REG_YOUTUBE)
);
}
export const getAspectRatio = (url: string): { w: number; h: number } => {
const normalizedUrl = url.toLowerCase();
if (isYouTube(url)) {
const isShorts = normalizedUrl.includes("shorts/");
return isShorts ? { w: 9, h: 16 } : { w: 16, h: 9 };
}
if (isVimeo(url)) {
return { w: 16, h: 9 };
}
return { w: 1, h: 1 };
}
export const getYouTubeStartAt = (url: string): string => {
const ytLink = url.match(REG_YOUTUBE);
if (ytLink?.[2]) {
+41 -2
View File
@@ -1,5 +1,5 @@
import { ExcalidrawImperativeAPI } from "@zsviczian/excalidraw/types/excalidraw/types";
import { ColorMaster } from "@zsviczian/colormaster";
import CM, { ColorMaster } from "@zsviczian/colormaster";
import { ExcalidrawAutomate } from "src/shared/ExcalidrawAutomate";
import ExcalidrawView from "src/view/ExcalidrawView";
import { DynamicStyle } from "src/types/types";
@@ -190,4 +190,43 @@ export const setDynamicStyle = (
color = null;
dynamicStyle = null;
});
}
}
const colorsCache: Map<string,string> = new Map();
export function getHighlightColor(
ea: ExcalidrawAutomate,
bgColor: string,
opacity:number = 1
): string {
bgColor = bgColor==="transparent" ? "#ffffff": bgColor;
let contrastedRGBA = colorsCache.get(bgColor);
if(!contrastedRGBA) {
const bg = ea.getCM(bgColor);
const bgMix = ea.getCM(bgColor);
const isDark = bg.isDark();
const step = 15;
const candidates = [
CM((isDark ? bg.lighterBy(step) : bg.darkerBy(step)).stringHEX()),
CM((isDark ? bg.lighterBy(step) : bg.darkerBy(step)).stringHEX()),
isDark ? bg.lighterBy(step) : bg.darkerBy(step),
// Vibrancy boost by mixing toward the opposite theme color
bgMix.mix({color: ea.getCM(isDark ? "#ffffff" : "#000000"), ratio:0.35}),
ea.getCM(isDark ? "#ffffff" : "#000000"),
ea.getCM(isDark ? "#000000" : "#ffffff"),
];
const desiredContrast = 2.5;
const contrasted = candidates.find(color =>
color.contrast({bgColor, ratio:false}) as number >= desiredContrast) ??
candidates.reduce((best, color) =>
(color.contrast({bgColor, ratio: false}) > best.contrast({bgColor, ratio:false}) ? color : best)
);
contrastedRGBA = `rgba(${Math.round(contrasted.red)
},${Math.round(contrasted.green)},${Math.round(contrasted.blue)}`;
colorsCache.set(bgColor,contrastedRGBA);
}
return `${contrastedRGBA},${opacity})`;
}
+131 -26
View File
@@ -5,10 +5,11 @@ import {
ExcalidrawElement,
ExcalidrawImageElement,
FileId,
FixedPoint,
} from "@zsviczian/excalidraw/types/element/src/types";
import { normalizePath, TFile } from "obsidian";
import ExcalidrawView, { ExportSettings, getTextMode } from "src/view/ExcalidrawView";
import ExcalidrawView, { getTextMode } from "src/view/ExcalidrawView";
import {
GITHUB_RELEASES,
getCommonBoundingBox,
@@ -30,19 +31,21 @@ import {
isVersionNewerThanOther,
scaleLoadedImage,
} from "src/utils/utils";
import { GenericInputPrompt, NewFileActions } from "src/shared/Dialogs/Prompt";
import { GenericInputPrompt, LaTexPrompt, NewFileActions } from "src/shared/Dialogs/Prompt";
import { t } from "src/lang/helpers";
import { Mutable } from "@zsviczian/excalidraw/types/common/src/utility-types";
import {
postOpenAI as _postOpenAI,
extractCodeBlocks as _extractCodeBlocks,
} from "../utils/AIUtils";
import { ColorMap, EmbeddedFilesLoader, FileData } from "src/shared/EmbeddedFileLoader";
import { SVGColorInfo } from "src/types/excalidrawAutomateTypes";
import { ExcalidrawData, getExcalidrawMarkdownHeaderSection, REGEX_LINK } from "src/shared/ExcalidrawData";
import { getFrameBasedOnFrameNameOrId } from "./excalidrawViewUtils";
import { EmbeddedFilesLoader } from "src/shared/EmbeddedFileLoader";
import { ScriptSettingValue, SVGColorInfo } from "src/types/excalidrawAutomateTypes";
import { ExcalidrawData, getExcalidrawMarkdownHeaderSection, REG_LINKINDEX_HYPERLINK, REGEX_LINK } from "src/shared/ExcalidrawData";
import { getFrameBasedOnFrameNameOrId, sceneRemoveInternalLinks } from "./excalidrawViewUtils";
import { ScriptEngine } from "src/shared/Scripts";
import { getEA } from "src/core";
import { ColorMap, FileData } from "src/types/embeddedFileLoaderTypes";
import { ExportSettings } from "src/types/exportUtilTypes";
declare const PLUGIN_VERSION:string;
@@ -150,7 +153,7 @@ export function errorMessage(message: string, source: string):void {
export function isColorStringTransparent(color: string): boolean {
const rgbaHslaTransparentRegex = /^(rgba|hsla)\(.*?,.*?,.*?,\s*0(\.0+)?\)$/i;
const hexTransparentRegex = /^#[a-fA-F0-9]{8}00$/i;
const hexTransparentRegex = /^#[a-fA-F0-9]{6}00$/i;
return rgbaHslaTransparentRegex.test(color) || hexTransparentRegex.test(color);
}
@@ -188,10 +191,6 @@ export function getLineBox(
};
}
export function getFontFamily(id: number):string {
return getFontFamilyString({fontFamily:id})
}
export function _measureText(
newText: string,
fontSize: number,
@@ -208,7 +207,7 @@ export function _measureText(
}
const metrics = measureText(
newText,
`${fontSize.toString()}px ${getFontFamily(fontFamily)}` as any,
`${fontSize.toString()}px ${getFontFamilyString({fontFamily})}` as any,
lineHeight
);
return { w: metrics.width, h: metrics.height };
@@ -448,6 +447,12 @@ export const updateElementLinksToObsidianLinks = ({elements, hostFile}:{
const partsArray = REGEX_LINK.getResList(el.link)[0];
if(!partsArray?.value) return el;
let linkText = REGEX_LINK.getLink(partsArray);
if (linkText.match(REG_LINKINDEX_HYPERLINK)) {
if(linkText.startsWith("obsidian://") || linkText.startsWith("cmd://")) return el;
const newElement: Mutable<ExcalidrawElement> = cloneElement(el);
newElement.link = linkText;
return newElement;
}
if (linkText.search("#") > -1) {
const linkParts = getLinkParts(linkText, hostFile);
linkText = linkParts.path;
@@ -504,6 +509,7 @@ export async function createSVG(
padding?: number,
imagesDict?: any,
convertMarkdownLinksToObsidianURLs: boolean = false,
includeInternalLinks: boolean = true,
): Promise<SVGSVGElement> {
if (!loader) {
loader = new EmbeddedFilesLoader(plugin);
@@ -534,7 +540,7 @@ export async function createSVG(
type: "excalidraw",
version: 2,
source: GITHUB_RELEASES+PLUGIN_VERSION,
elements,
elements: includeInternalLinks ? elements : sceneRemoveInternalLinks({elements}),
appState: {
theme,
viewBackgroundColor:
@@ -647,18 +653,38 @@ export function repositionElementsToCursor(
export const insertLaTeXToView = (view: ExcalidrawView, center: boolean = false) => {
const app = view.plugin.app;
const ea = getEA(view) as ExcalidrawAutomate;
GenericInputPrompt.Prompt(
view,
view.plugin,
app,
t("ENTER_LATEX"),
"\\color{red}\\oint_S {E_n dA = \\frac{1}{{\\varepsilon _0 }}} Q_{inside}",
view.plugin.settings.latexBoilerplate,
undefined,
3
const isLatexSuitAvailable = !!app.plugins.plugins["obsidian-latex-suite"];
(isLatexSuitAvailable
? LaTexPrompt.Prompt(app, t("ENTER_LATEX"), view.plugin.settings.latexBoilerplate)
: GenericInputPrompt.Prompt(
view,
view.plugin,
app,
t("ENTER_LATEX"),
"\\color{red}\\oint_S {E_n dA = \\frac{1}{{\\varepsilon _0 }}} Q_{inside}",
view.plugin.settings.latexBoilerplate,
undefined,
3
)
).then(async (formula: string) => {
const lastLatexEl = ea.getViewElements()
.filter((el) => el.type === "image" && view.excalidrawData.hasEquation(el.fileId))
.reduce(
(maxel, curr) => (!maxel || curr.updated > maxel.updated) ? curr : maxel,
undefined
) as ExcalidrawImageElement;
let scaleX = 1;
let scaleY = 1;
if (lastLatexEl) {
const equation = view.excalidrawData.getEquation(lastLatexEl.fileId);
const dataurl = await ea.tex2dataURL(equation.latex);
if (dataurl.size.width > 0 && dataurl.size.height > 0) {
scaleX = lastLatexEl.width/dataurl.size.width;
scaleY = lastLatexEl.height/dataurl.size.height;
}
}
if (formula) {
const id = await ea.addLaTex(0, 0, formula);
const id = await ea.addLaTex(0, 0, formula, scaleX, scaleY);
if(center) {
const el = ea.getElement(id);
let {width, height} = el;
@@ -670,7 +696,7 @@ export const insertLaTeXToView = (view: ExcalidrawView, center: boolean = false)
ea.selectElementsInView([id]);
}
ea.destroy();
});
}, () => {});
};
export const search = async (view: ExcalidrawView) => {
@@ -836,11 +862,90 @@ export const cloneElement = (el: ExcalidrawElement):any => {
}
export const verifyMinimumPluginVersion = (requiredVersion: string): boolean => {
return PLUGIN_VERSION === requiredVersion || isVersionNewerThanOther(PLUGIN_VERSION,requiredVersion);
return PLUGIN_VERSION.split("-")[0] === requiredVersion || isVersionNewerThanOther(PLUGIN_VERSION.split("-")[0],requiredVersion);
}
export const getBoundTextElementId = (container: ExcalidrawElement | null) => {
return container?.boundElements?.length
? container?.boundElements?.find((ele) => ele.type === "text")?.id || null
: null;
};
};
/**
*
* FixedPoint represents the fixed point binding information in form of a vertical and
* horizontal ratio (i.e. a percentage value in the 0.0-1.0 range). This ratio
* gives the user selected fixed point by multiplying the bound element width
* with fixedPoint[0] and the bound element height with fixedPoint[1] to get the
* bound element-local point coordinate.
*/
export const normalizeFixedPoint = <T extends FixedPoint | null | undefined>(
fixedPoint: T,
): T extends null ? null : FixedPoint => {
if (!fixedPoint) {
return [0.50001, 0.5001] as any as T extends null ? null : FixedPoint;
}
if (fixedPoint[0] < 0 || fixedPoint[0] > 1) {
fixedPoint[0] = 0.5001;
}
if (fixedPoint[1] < 0 || fixedPoint[1] > 1) {
fixedPoint[1] = 0.5001;
}
// Do not allow a precise 0.5 for fixed point ratio
// to avoid jumping arrow heading due to floating point imprecision
if (
fixedPoint &&
(Math.abs(fixedPoint[0] - 0.5) < 0.0001 ||
Math.abs(fixedPoint[1] - 0.5) < 0.0001)
) {
return fixedPoint.map((ratio) =>
Math.abs(ratio - 0.5) < 0.0001 ? 0.5001 : ratio,
) as T extends null ? null : FixedPoint;
}
return fixedPoint as any as T extends null ? null : FixedPoint;
};
export const normalizeBindMode = (bindMode?: string): "orbit" | "inside" => {
if (!bindMode || (bindMode !== "orbit" && bindMode !== "inside")) {
return "orbit";
}
return bindMode;
};
/**
* Ensures that plugin.settings.scriptEngineSettings and the active script's settings object exist.
* Handles undefined/null during initialization.
*
* Note: kept in utils (not as an EA private method) so it won't be exposed on window.ExcalidrawAutomate.
*/
export function ensureActiveScriptSettingsObject(
ea: ExcalidrawAutomate
): Record<string, ScriptSettingValue> | null {
const activeScript = ea?.activeScript;
const plugin = ea?.plugin;
if (!activeScript || !plugin?.settings) {
return null;
}
// Ensure the top-level container exists
if (!plugin.settings.scriptEngineSettings || typeof plugin.settings.scriptEngineSettings !== "object") {
plugin.settings.scriptEngineSettings = {};
}
// Ensure the per-script settings object exists (handle null/undefined)
const current = plugin.settings.scriptEngineSettings[activeScript];
if (!current || typeof current !== "object") {
plugin.settings.scriptEngineSettings[activeScript] = {};
}
return plugin.settings.scriptEngineSettings[activeScript] as Record<string, ScriptSettingValue>;
}
export function getLastActiveExcalidrawView(plugin: ExcalidrawPlugin): ExcalidrawView | null {
const leaf = plugin.app.workspace.getLeafById(plugin.lastActiveExcalidrawLeafID);
if(leaf && leaf.view instanceof ExcalidrawView) {
return leaf.view as ExcalidrawView;
}
return null;
}
+1
View File
@@ -20,6 +20,7 @@ export function updateElementIdsInScene(
if(elementToChange.boundElements?.length>0) {
elementToChange.boundElements.forEach( binding => {
const boundEl = sceneElements.find(el=>el.id === binding.id) as unknown as Mutable<ExcalidrawElement>;
if(!boundEl) return;
boundEl.boundElements?.filter(x=>x.id === elementToChange.id).forEach( x => {
(x.id as Mutable<string>) = newID;
});
+115 -4
View File
@@ -1,5 +1,5 @@
import { MAX_IMAGE_SIZE, IMAGE_TYPES, ANIMATED_IMAGE_TYPES, MD_EX_SECTIONS, AUDIO_TYPES, CARD_WIDTH, CARD_HEIGHT } from "src/constants/constants";
import { MAX_IMAGE_SIZE, IMAGE_TYPES, ANIMATED_IMAGE_TYPES, MD_EX_SECTIONS, AUDIO_TYPES, CARD_WIDTH, CARD_HEIGHT, getDefaultColorPalette } from "src/constants/constants";
import { App, Modal, Notice, TFile } from "obsidian";
import { ExcalidrawAutomate } from "src/shared/ExcalidrawAutomate";
import { REGEX_LINK, REG_LINKINDEX_HYPERLINK, getExcalidrawMarkdownHeaderSection, REGEX_TAGS, getExcalidrawMarkdownHeader } from "../shared/ExcalidrawData";
@@ -137,6 +137,23 @@ function getLinkFromMarkdownLink(link: string): string {
return result ? result[1] : link;
}
function isInternalLink(link:string):boolean {
link = getLinkFromMarkdownLink(link);
if (link.startsWith("cmd://")) return true;
if (link.startsWith("obsidian://")) return true;
if (link.match(REG_LINKINDEX_HYPERLINK)) return false;
return true;
}
export function sceneRemoveInternalLinks(scene: {elements: ExcalidrawElement[]}): ExcalidrawElement[] {
const elements: ExcalidrawElement[] = JSON.parse(JSON.stringify(scene.elements));
elements.forEach(el => {
if(!el.link) return;
if(isInternalLink(el.link)) (el as Mutable<ExcalidrawElement>).link = null;
});
return elements;
}
export function openExternalLink (link:string, app: App, element?: ExcalidrawElement):boolean {
link = getLinkFromMarkdownLink(link);
if (link.match(/^cmd:\/\/.*/)) {
@@ -254,12 +271,11 @@ export async function addBackOfTheNoteCard(
const shouldRemoveTrailingHashtag = Boolean(hastag);
view.data = data.replace(
header,
(shouldRemoveTrailingHashtag
() => (shouldRemoveTrailingHashtag
? header.substring(0,header.length-hastag[0].length)
: header) +
`\n# ${title}\n\n${cardBody ? cardBody+"\n\n" : ""}${
shouldAddHashtag || shouldRemoveTrailingHashtag ? "#\n" : ""}`);
await view.forceSave(true);
let watchdog = 0;
await sleep(200);
@@ -512,4 +528,99 @@ export function onLoadMessages(plugin: ExcalidrawPlugin, scene: {elements: Excal
new Notice(t("DRAWING_HAS_BACK_OF_THE_CARD"));
}*/
});
}
}
export function getViewColorPalette(
palette: "canvasBackground"|"elementBackground"|"elementStroke",
view?: ExcalidrawView,
includeSceneColors: boolean = false,
): (string[] | string)[] {
if (!view) {
return getDefaultColorPalette() as (string[] | string)[];
}
const api = view.excalidrawAPI as ExcalidrawImperativeAPI;
const {colorPalette} = api.getAppState();
if (!colorPalette || !colorPalette.hasOwnProperty(palette)) {
return getDefaultColorPalette() as (string[] | string)[];
}
const basePalette = colorPalette[palette];
if (!Array.isArray(basePalette)) {
return [basePalette];
}
const cmFactory = view.hookServer?.getCM?.bind(view.hookServer) ?? view.plugin.ea.getCM.bind(view.plugin.ea);
const getLightness = (color: string): number => {
const cm = cmFactory?.(color);
const value = (cm as any)?.lightness;
return typeof value === "number" ? value : Number.POSITIVE_INFINITY;
};
const normalize = (color: string): string => {
if (!color) {return color;}
if (color.toLowerCase() === "transparent") {return "transparent";}
const cm = cmFactory?.(color);
if (cm && typeof (cm as any).stringHEX === "function") {
try {
const alpha = (cm as any).alpha;
const includeAlpha = typeof alpha === "number" ? alpha !== 1 : true;
return (cm as any).stringHEX({alpha: includeAlpha}).toLowerCase();
} catch {
// fall through to string coercion
}
}
if (cm && typeof (cm as any).toString === "function") {
return (cm as any).toString().toLowerCase();
}
return color.toLowerCase();
};
const groups = basePalette
.filter((entry) => Array.isArray(entry))
.map((entry) => (entry as string[]).slice().sort((a, b) => getLightness(b) - getLightness(a)));
const singles = basePalette.filter((entry) => typeof entry === "string") as string[];
const groupColors = groups
.flatMap((entry) => entry as string[])
.filter(Boolean)
.map((c) => normalize(c));
const groupColorSet = new Set(groupColors);
const seenSingles = new Set<string>();
const filteredSingles = singles.filter((entry) => {
const norm = normalize(entry);
if (!norm) {return false;}
if (groupColorSet.has(norm)) {return false;}
if (seenSingles.has(norm)) {return false;}
seenSingles.add(norm);
return true;
});
if (!includeSceneColors || !["elementBackground", "elementStroke"].includes(palette)) {
return [...groups, ...filteredSingles];
}
const flattenPalette = (pal: any[]): string[] => pal
.flatMap((entry: any) => Array.isArray(entry) ? entry : [entry])
.filter((color: any): color is string => typeof color === "string" && Boolean(color));
const paletteColors = flattenPalette(basePalette).map((c) => normalize(c));
const extraColors = new Set<string>(filteredSingles.filter((c) => c.toLowerCase() !== "transparent"));
view.getViewElements().forEach((el) => {
const color = (palette === "elementStroke" ? el.strokeColor : (el as any).backgroundColor) as string;
if (!color || normalize(color) === "transparent") {return;}
if (paletteColors.includes(normalize(color))) {return;}
extraColors.add(color);
});
if (!extraColors.size) {
return [...groups];
}
const sortedExtras = cmFactory
? Array.from(extraColors).sort((a, b) => getLightness(b) - getLightness(a))
: Array.from(extraColors);
return [...groups, ...sortedExtras];
}
+4 -58
View File
@@ -3,66 +3,10 @@ import { DEVICE } from 'src/constants/constants';
import { t } from 'src/lang/helpers';
import { download } from './fileUtils';
import { svgToBase64 } from './utils';
import { PageDimensions, PageOrientation, PageSize, PDFExportScale, PDFMargin, PDFPageAlignment, PDFPageMarginString, PDFPageProperties, STANDARD_PAGE_SIZES } from 'src/types/exportUtilTypes';
const DPI = 96;
export type PDFPageAlignment =
| "center"
| "top-left"
| "top-center"
| "top-right"
| "bottom-left"
| "bottom-center"
| "bottom-right"
| "center-left"
| "center-right";
export type PDFPageMarginString = "none" | "tiny" | "normal";
export interface PDFExportScale {
fitToPage: number; // 0 means use zoom, >1 means fit to that many pages exactly
zoom?: number;
}
export interface PDFMargin {
left: number;
right: number;
top: number;
bottom: number;
}
export interface PDFPageProperties {
dimensions?: {width: number; height: number};
backgroundColor?: string;
margin: PDFMargin;
alignment: PDFPageAlignment;
}
export interface PageDimensions {
width: number;
height: number;
}
export type PageOrientation = "portrait" | "landscape";
// All dimensions in pixels (pt)
export const STANDARD_PAGE_SIZES = {
A0: { width: 3179.52, height: 4494.96 }, // 33.11 × 46.81 inches
A1: { width: 2245.76, height: 3179.52 }, // 23.39 × 33.11 inches
A2: { width: 1587.76, height: 2245.76 }, // 16.54 × 23.39 inches
A3: { width: 1122.56, height: 1587.76 }, // 11.69 × 16.54 inches
A4: { width: 794.56, height: 1122.56 }, // 8.27 × 11.69 inches
A5: { width: 559.37, height: 794.56 }, // 5.83 × 8.27 inches
A6: { width: 397.28, height: 559.37 }, // 4.13 × 5.83 inches
Legal: { width: 816, height: 1344 }, // 8.5 × 14 inches
Letter: { width: 816, height: 1056 }, // 8.5 × 11 inches
Tabloid: { width: 1056, height: 1632 }, // 11 × 17 inches
Ledger: { width: 1632, height: 1056 }, // 17 × 11 inches
"HD Screen": { width: 1920, height: 1080 },// 16:9 aspect ratio
"MATCH IMAGE": { width: 0, height: 0 }, // 0 means use the current screen size
} as const;
export type PageSize = keyof typeof STANDARD_PAGE_SIZES;
//margins are in pixels
export function getMarginValue(margin:PDFPageMarginString): PDFMargin {
switch(margin) {
@@ -232,7 +176,9 @@ async function printPdf(
printDiv.style.top = "0";
printDiv.style.left = "0";
printDiv.style.display = "flex";
printDiv.appendChild(elementToPrint);
//printDiv.appendChild(elementToPrint); // if I append directly, rounded images and clip paths get messed up
// see https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2544
printDiv.innerHTML = elementToPrint.outerHTML;
const options: PrintToPDFOptions = {
includeName: false,
+1 -1
View File
@@ -1,12 +1,12 @@
import { DataURL } from "@zsviczian/excalidraw/types/excalidraw/types";
import { App, loadPdfJs, MetadataCache, normalizePath, Notice, requestUrl, RequestUrlResponse, TAbstractFile, TFile, TFolder, Vault } from "obsidian";
import { DEVICE, EXCALIDRAW_PLUGIN, FRONTMATTER_KEYS, URLFETCHTIMEOUT } from "src/constants/constants";
import { IMAGE_MIME_TYPES, MimeType } from "../shared/EmbeddedFileLoader";
import { ExcalidrawSettings } from "src/core/settings";
import { errorlog, getDataURL } from "./utils";
import ExcalidrawPlugin from "src/core/main";
import { getAttachmentsFolderAndFilePath } from "./obsidianUtils";
import ExcalidrawView from "src/view/ExcalidrawView";
import { IMAGE_MIME_TYPES, MimeType } from "src/types/embeddedFileLoaderTypes";
/**
* Splits a full path including a folderpath and a filename into separate folderpath and filename components
+3 -1
View File
@@ -36,11 +36,13 @@ export async function diagramToHTML({
apiKey,
text,
theme = THEME.LIGHT,
openAIURL = "https://api.openai.com/v1/chat/completions",
}: {
image: DataURL;
apiKey: string;
text: string;
theme?: Theme;
openAIURL?: string;
}) {
const body: OpenAIInput.ChatCompletionCreateParamsBase = {
model: EXCALIDRAW_PLUGIN.settings.openAIDefaultVisionModel,
@@ -79,7 +81,7 @@ export async function diagramToHTML({
| ({ ok: true } & OpenAIOutput.ChatCompletion)
| ({ ok: false } & OpenAIOutput.APIError);
return await fetch("https://api.openai.com/v1/chat/completions", {
return await fetch(openAIURL, {
method: "POST",
headers: {
"Content-Type": "application/json",
Loaded 100 of 110 files, more files were not shown because too many files have changed in this diff. Show more