mirror of
https://github.com/zsviczian/obsidian-excalidraw-plugin.git
synced 2026-11-27 06:32:42 +00:00
Compare commits
141
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b37101e606 | ||
|
|
9650f98d5d | ||
|
|
15e44ffd34 | ||
|
|
eb3fd734e8 | ||
|
|
69afe79aa7 | ||
|
|
d013c1a4b2 | ||
|
|
2ecc0fedf9 | ||
|
|
ee6bb5a341 | ||
|
|
c97284ce2e | ||
|
|
1893053cf6 | ||
|
|
fea19d11ed | ||
|
|
868609ac2d | ||
|
|
3043827402 | ||
|
|
d41b2af32d | ||
|
|
fc23213f4a | ||
|
|
b05d102294 | ||
|
|
9472e18047 | ||
|
|
9342942fce | ||
|
|
15041121fa | ||
|
|
e1c77dab1d | ||
|
|
2c1f92484f | ||
|
|
64c1e1c166 | ||
|
|
85bba4a6b6 | ||
|
|
aaeb8433b4 | ||
|
|
eb4718e5a8 | ||
|
|
070dc487ab | ||
|
|
d809ad5e97 | ||
|
|
bd79b09fb7 | ||
|
|
6c2057e4ce | ||
|
|
d38a2ed9fd | ||
|
|
762a2dd39e | ||
|
|
c1417a1f4e | ||
|
|
07b20b2c3b | ||
|
|
0b8992542c | ||
|
|
13fa5c95b5 | ||
|
|
b4d2f78c76 | ||
|
|
894ac734f2 | ||
|
|
0e768ca1c8 | ||
|
|
93ec4f7072 | ||
|
|
704d853ce2 | ||
|
|
9a17e83c3b | ||
|
|
f4dbe51066 | ||
|
|
f3dddd3d1d | ||
|
|
aaab8fff62 | ||
|
|
869ad088a5 | ||
|
|
b9a3b1c71e | ||
|
|
ce2713ecdb | ||
|
|
8fefcbcf66 | ||
|
|
d765e36326 | ||
|
|
f6a5236a14 | ||
|
|
18c547d0f1 | ||
|
|
10f0e26316 | ||
|
|
a2f277e232 | ||
|
|
130f518b3b | ||
|
|
b30abb0406 | ||
|
|
6a7e3b41e4 | ||
|
|
6749c078cc | ||
|
|
7475a1ad41 | ||
|
|
982e9e0848 | ||
|
|
8df4364bc8 | ||
|
|
7ca40ceb4f | ||
|
|
3275a7a168 | ||
|
|
41e1a0dd02 | ||
|
|
15c0d34ecc | ||
|
|
9fe30df73a | ||
|
|
1a774d1ed4 | ||
|
|
bf5ea9c27a | ||
|
|
4170847411 | ||
|
|
407bdf11ad | ||
|
|
cc6fc24d77 | ||
|
|
1c69f36031 | ||
|
|
9e0347c4ab | ||
|
|
25474af843 | ||
|
|
444ac933fa | ||
|
|
5bfd690c7a | ||
|
|
95c562b15c | ||
|
|
7e18367075 | ||
|
|
713f197381 | ||
|
|
d1e4b9a905 | ||
|
|
29c215bbfb | ||
|
|
fb21d5516d | ||
|
|
c2f986dff7 | ||
|
|
d2c8abf0fc | ||
|
|
22835f3c1f | ||
|
|
e1ad165313 | ||
|
|
67f291177d | ||
|
|
ad0e47033a | ||
|
|
65b8de8965 | ||
|
|
27b899ecbc | ||
|
|
62e6142813 | ||
|
|
b967cddf4c | ||
|
|
45709e5f1e | ||
|
|
5e9eb66510 | ||
|
|
af7891da4e | ||
|
|
65831073a6 | ||
|
|
7093c221d1 | ||
|
|
675700696a | ||
|
|
becb650902 | ||
|
|
1a7d9c6f8c | ||
|
|
403467c134 | ||
|
|
8a1b90c06b | ||
|
|
f93b3b9306 | ||
|
|
f7ce333fea | ||
|
|
78b2a351bd | ||
|
|
1db888991a | ||
|
|
a72ecbc75d | ||
|
|
ef4f638eb9 | ||
|
|
9bfcf68ef7 | ||
|
|
e3916141ca | ||
|
|
8fb4ad1cd6 | ||
|
|
d08eaeef57 | ||
|
|
0e34b13c8d | ||
|
|
d4e23af17f | ||
|
|
c6450a1e91 | ||
|
|
bfaaf6dac0 | ||
|
|
4373dc5d04 | ||
|
|
bf35f8f9a7 | ||
|
|
54594bf73d | ||
|
|
ff9f1f53d7 | ||
|
|
9f7d78f2d6 | ||
|
|
ccc4e3921e | ||
|
|
5fae43094f | ||
|
|
aa200953dc | ||
|
|
4ccda30e72 | ||
|
|
309721df11 | ||
|
|
c455b8fa01 | ||
|
|
8f899277fd | ||
|
|
512ef8c1e7 | ||
|
|
0aaf1fb9d8 | ||
|
|
bb3065058e | ||
|
|
13b80db77c | ||
|
|
b6a204da4e | ||
|
|
e87a936887 | ||
|
|
b3d0a5a571 | ||
|
|
f212db7223 | ||
|
|
48143ead47 | ||
|
|
d053d51672 | ||
|
|
2cd9119ad1 | ||
|
|
75a0af8ee4 | ||
|
|
b32de61199 | ||
|
|
ece9a9d064 |
No files matched your search
@@ -1,4 +0,0 @@
|
||||
node_modules/
|
||||
.github/
|
||||
docs/
|
||||
images/
|
||||
@@ -0,0 +1,74 @@
|
||||
name: Build, Release, and Attest Assets
|
||||
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- '*.*.*' # Triggers if you tag exactly like: 2.23.0 or 2.23.0-beta-1
|
||||
- 'v*.*.*' # Triggers if you tag like: v2.23.0 or v2.23.0-beta-1
|
||||
|
||||
jobs:
|
||||
release:
|
||||
name: Create Release and Attest Assets
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
# CRITICAL: Give GitHub the required permissions to sign your files
|
||||
permissions:
|
||||
id-token: write
|
||||
contents: write
|
||||
attestations: write
|
||||
|
||||
steps:
|
||||
# 1. Pull down your repository code
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
# 2. Tell the server to install Node 22
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '22'
|
||||
|
||||
# 3. Install dependencies and build assets
|
||||
# This naturally generates dist/manifest.json from the stable one
|
||||
- name: Install dependencies and build
|
||||
run: |
|
||||
npm ci
|
||||
npm run build
|
||||
|
||||
# 4. Check if the tag has a hyphen (e.g. v2.2.5-beta). If yes, mark as pre-release.
|
||||
- name: Determine if Pre-release
|
||||
id: check-prerelease
|
||||
run: |
|
||||
if [[ "${{ github.ref_name }}" == *"-"* ]]; then
|
||||
echo "is_prerelease=true" >> $GITHUB_OUTPUT
|
||||
else
|
||||
echo "is_prerelease=false" >> $GITHUB_OUTPUT
|
||||
fi
|
||||
|
||||
# 5. Swap to the Beta Manifest if it's a pre-release
|
||||
- name: Prepare Beta Manifest
|
||||
if: steps.check-prerelease.outputs.is_prerelease == 'true'
|
||||
run: |
|
||||
echo "Pre-release detected! Swapping dist/manifest.json with manifest-beta.json..."
|
||||
cp manifest-beta.json dist/manifest.json
|
||||
|
||||
# 6. Generate the cryptographic attestations for your built files
|
||||
# (Because this runs AFTER step 5, it will correctly sign the beta manifest!)
|
||||
- name: Attest Build Provenance
|
||||
uses: actions/attest-build-provenance@v2
|
||||
with:
|
||||
subject-path: 'dist/*'
|
||||
|
||||
# 7. Automatically create a GitHub Release and attach the files
|
||||
- name: Create GitHub Release
|
||||
uses: softprops/action-gh-release@v2
|
||||
with:
|
||||
generate_release_notes: true
|
||||
files: |
|
||||
dist/main.js
|
||||
dist/styles.css
|
||||
dist/manifest.json
|
||||
# Dynamically set pre-release based on step 4
|
||||
prerelease: ${{ steps.check-prerelease.outputs.is_prerelease == 'true' }}
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
@@ -0,0 +1,661 @@
|
||||
GNU AFFERO GENERAL PUBLIC LICENSE
|
||||
Version 3, 19 November 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU Affero General Public License is a free, copyleft license for
|
||||
software and other kinds of works, specifically designed to ensure
|
||||
cooperation with the community in the case of network server software.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
our General Public Licenses are intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
Developers that use our General Public Licenses protect your rights
|
||||
with two steps: (1) assert copyright on the software, and (2) offer
|
||||
you this License which gives you legal permission to copy, distribute
|
||||
and/or modify the software.
|
||||
|
||||
A secondary benefit of defending all users' freedom is that
|
||||
improvements made in alternate versions of the program, if they
|
||||
receive widespread use, become available for other developers to
|
||||
incorporate. Many developers of free software are heartened and
|
||||
encouraged by the resulting cooperation. However, in the case of
|
||||
software used on network servers, this result may fail to come about.
|
||||
The GNU General Public License permits making a modified version and
|
||||
letting the public access it on a server without ever releasing its
|
||||
source code to the public.
|
||||
|
||||
The GNU Affero General Public License is designed specifically to
|
||||
ensure that, in such cases, the modified source code becomes available
|
||||
to the community. It requires the operator of a network server to
|
||||
provide the source code of the modified version running there to the
|
||||
users of that server. Therefore, public use of a modified version, on
|
||||
a publicly accessible server, gives the public access to the source
|
||||
code of the modified version.
|
||||
|
||||
An older license, called the Affero General Public License and
|
||||
published by Affero, was designed to accomplish similar goals. This is
|
||||
a different license, not a version of the Affero GPL, but Affero has
|
||||
released a new version of the Affero GPL which permits relicensing under
|
||||
this license.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU Affero General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Remote Network Interaction; Use with the GNU General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, if you modify the
|
||||
Program, your modified version must prominently offer all users
|
||||
interacting with it remotely through a computer network (if your version
|
||||
supports such interaction) an opportunity to receive the Corresponding
|
||||
Source of your version by providing access to the Corresponding Source
|
||||
from a network server at no charge, through some standard or customary
|
||||
means of facilitating copying of software. This Corresponding Source
|
||||
shall include the Corresponding Source for any work covered by version 3
|
||||
of the GNU General Public License that is incorporated pursuant to the
|
||||
following paragraph.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the work with which it is combined will remain governed by version
|
||||
3 of the GNU General Public License.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU Affero General Public License from time to time. Such new versions
|
||||
will be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU Affero General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU Affero General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU Affero General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as published
|
||||
by the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If your software can interact with users remotely through a computer
|
||||
network, you should also make sure that it provides a way for users to
|
||||
get its source. For example, if your program is a web application, its
|
||||
interface could display a "Source" link that leads users to an archive
|
||||
of the code. There are many ways you could offer source, and different
|
||||
solutions will be better for different programs; see section 13 for the
|
||||
specific requirements.
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU AGPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
+26
-15
@@ -1,17 +1,31 @@
|
||||
import {mathjax} from "mathjax-full/js/mathjax";
|
||||
import {TeX} from 'mathjax-full/js/input/tex.js';
|
||||
import {SVG} from 'mathjax-full/js/output/svg.js';
|
||||
import {LiteAdaptor, liteAdaptor} from 'mathjax-full/js/adaptors/liteAdaptor.js';
|
||||
import {RegisterHTMLHandler} from 'mathjax-full/js/handlers/html.js';
|
||||
import {AllPackages} from 'mathjax-full/js/input/tex/AllPackages.js';
|
||||
import { mathjax } from "mathjax-full/js/mathjax";
|
||||
import { TeX } from 'mathjax-full/js/input/tex.js';
|
||||
import { SVG } from 'mathjax-full/js/output/svg.js';
|
||||
import { LiteAdaptor,liteAdaptor } from 'mathjax-full/js/adaptors/liteAdaptor.js';
|
||||
import { RegisterHTMLHandler } from 'mathjax-full/js/handlers/html.js';
|
||||
import { AllPackages } from 'mathjax-full/js/input/tex/AllPackages.js';
|
||||
import { customAlphabet } from "nanoid";
|
||||
import type { TAbstractFile, TFile } from "obsidian";
|
||||
|
||||
type DataURL = string & { _brand: "DataURL" };
|
||||
type FileId = string & { _brand: "FileId" };
|
||||
const fileid = customAlphabet("1234567890abcdef", 40);
|
||||
|
||||
type LatexPluginLike = {
|
||||
app: {
|
||||
vault: {
|
||||
getFileByPath: (path: string) => TFile | null;
|
||||
getAbstractFileByPath: (path: string) => TAbstractFile | null;
|
||||
read: (file: TAbstractFile) => Promise<string>;
|
||||
};
|
||||
};
|
||||
settings: {
|
||||
latexPreambleLocation?: string;
|
||||
};
|
||||
};
|
||||
|
||||
let adaptor: LiteAdaptor;
|
||||
let html: any;
|
||||
let html: ReturnType<typeof mathjax.document>;
|
||||
let preamble: string;
|
||||
|
||||
function svgToBase64(svg: string): string {
|
||||
@@ -38,7 +52,7 @@ async function getImageSize(src: string): Promise<{ height: number; width: numbe
|
||||
export async function tex2dataURL(
|
||||
tex: string,
|
||||
scale: number = 4,
|
||||
plugin?: any
|
||||
plugin?: LatexPluginLike
|
||||
): Promise<{
|
||||
mimeType: string;
|
||||
fileId: FileId;
|
||||
@@ -46,12 +60,12 @@ export async function tex2dataURL(
|
||||
created: number;
|
||||
size: { height: number; width: number };
|
||||
}> {
|
||||
let input: TeX<unknown, unknown, unknown>;
|
||||
let output: SVG<unknown, unknown, unknown>;
|
||||
let input: TeX<Record<string, never>, Record<string, never>, Record<string, never>>;
|
||||
let output: SVG<Record<string, never>, Record<string, never>, Record<string, never>>;
|
||||
|
||||
if(!adaptor) {
|
||||
if (plugin) {
|
||||
const file = plugin.app.vault.getAbstractFileByPath(plugin.settings.latexPreambleLocation || "preamble.sty");
|
||||
const file = plugin.app.vault.getFileByPath(plugin.settings.latexPreambleLocation || "preamble.sty");
|
||||
preamble = file ? await plugin.app.vault.read(file) : null;
|
||||
}
|
||||
adaptor = liteAdaptor();
|
||||
@@ -76,10 +90,7 @@ export async function tex2dataURL(
|
||||
|
||||
//https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2195
|
||||
//https://stackoverflow.com/a/77181931
|
||||
let styleNode = document.createElement('style');
|
||||
styleNode.setAttribute("type", "text/css");
|
||||
styleNode.appendChild(document.createTextNode(".mjx-solid { stroke-width: 80px; }"));
|
||||
svg.appendChild(styleNode);
|
||||
svg.insertAdjacentHTML("beforeend", "<style>.mjx-solid { stroke-width: 80px; }</style>");
|
||||
|
||||
if (svg) {
|
||||
if(svg.width.baseVal.valueInSpecifiedUnits < 2) {
|
||||
|
||||
Generated
+564
-249
File diff suppressed because it is too large.
Load diff
@@ -3,8 +3,8 @@
|
||||
"version": "1.0.0",
|
||||
"main": "dist/index.js",
|
||||
"scripts": {
|
||||
"build": "cross-env NODE_ENV=production rollup --config rollup.config.js",
|
||||
"dev": "cross-env NODE_ENV=development rollup --config rollup.config.js"
|
||||
"build": "cross-env NODE_ENV=production rollup --config rollup.config.mjs",
|
||||
"dev": "cross-env NODE_ENV=development rollup --config rollup.config.mjs"
|
||||
},
|
||||
"dependencies": {
|
||||
"mathjax-full": "^3.2.2",
|
||||
@@ -13,12 +13,16 @@
|
||||
"devDependencies": {
|
||||
"@rollup/plugin-commonjs": "^26.0.1",
|
||||
"@rollup/plugin-node-resolve": "^15.2.3",
|
||||
"@rollup/plugin-terser": "^0.4.4",
|
||||
"@rollup/plugin-typescript": "^12.1.2",
|
||||
"cross-env": "^7.0.3",
|
||||
"obsidian": "1.5.7-1",
|
||||
"rollup": "^2.70.1",
|
||||
"rollup-plugin-terser": "^7.0.2",
|
||||
"rollup": "^4.14.0",
|
||||
"tslib": "^2.8.1",
|
||||
"typescript": "^5.7.3"
|
||||
"typescript": "5.9.3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=22.0.0",
|
||||
"npm": ">=10.0.0"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
import { nodeResolve } from '@rollup/plugin-node-resolve';
|
||||
import commonjs from '@rollup/plugin-commonjs';
|
||||
import typescript from '@rollup/plugin-typescript';
|
||||
import { terser } from 'rollup-plugin-terser';
|
||||
import terser from '@rollup/plugin-terser'; // <-- Updated import
|
||||
|
||||
const isProd = (process.env.NODE_ENV === 'production');
|
||||
|
||||
@@ -17,6 +17,7 @@ export default {
|
||||
plugins: [
|
||||
typescript({
|
||||
tsconfig: 'tsconfig.json',
|
||||
sourceMap: !isProd, // <-- Explicitly tell TS compiler to output maps in dev
|
||||
}),
|
||||
commonjs(),
|
||||
nodeResolve({
|
||||
@@ -32,4 +33,4 @@ export default {
|
||||
}
|
||||
})
|
||||
].filter(Boolean)
|
||||
};
|
||||
};
|
||||
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"baseUrl": ".",
|
||||
"sourceMap": false,
|
||||
"module": "es2020",
|
||||
"target": "es2022", //min es2017 because script engine requires for async execution and min es2018 for named capture groups
|
||||
"sourceMap": true,
|
||||
"module": "es2022",
|
||||
"target": "es2022",
|
||||
"allowJs": false,
|
||||
"noImplicitAny": true,
|
||||
"moduleResolution": "node",
|
||||
"moduleResolution": "bundler",
|
||||
"esModuleInterop": true,
|
||||
"importHelpers": true,
|
||||
"resolveJsonModule": true,
|
||||
@@ -16,11 +16,12 @@
|
||||
"es2022",
|
||||
"DOM.Iterable"
|
||||
],
|
||||
"jsx": "react",
|
||||
"jsx": "react"
|
||||
},
|
||||
"include": [
|
||||
"**/*.ts",
|
||||
"**/*.tsx", "src/shared/Dialogs/OpenDrawing.ts",
|
||||
"src/types/types.d.ts",
|
||||
"**/*.tsx",
|
||||
"src/shared/Dialogs/OpenDrawing.ts",
|
||||
"src/types/types.d.ts"
|
||||
]
|
||||
}
|
||||
@@ -2,11 +2,81 @@
|
||||
|
||||
【English | [简体中文](./docs/zh-cn/README.md)】
|
||||
|
||||
👉👉👉 Check out and contribute to the new [Obsidian-Excalidraw Community Wiki](https://excalidraw-obsidian.online/WIKI/Welcome+to+the+WIKI)
|
||||
👉👉👉 Check out and contribute to the new [Obsidian-Excalidraw Community Wiki](https://community.sketch-your-mind.com/Wiki)
|
||||
|
||||
The Obsidian-Excalidraw plugin integrates [Excalidraw](https://excalidraw.com/), a feature rich sketching tool, into Obsidian. You can store and edit Excalidraw files in your vault, you can embed drawings into your documents, and you can link to documents and other drawings to/and from Excalidraw. For a showcase of Excalidraw features, please read my blog post [here](https://www.zsolt.blog/2021/03/showcasing-excalidraw.html) and/or watch the videos below.
|
||||
The Obsidian-Excalidraw plugin integrates [Excalidraw](https://excalidraw.com/), a feature rich sketching tool, into Obsidian. You can store and edit Excalidraw files in your vault, you can embed drawings into your documents, and you can link to documents and other drawings to/and from Excalidraw. For a showcase of Excalidraw features watch the videos below.
|
||||
|
||||
Excalidraw for Obsidian keeps evolving; it is extremely feature‑rich and can feel intimidating at first. The Video Walkthrough below should ease that initial overwhelm. For a comprehensive, searchable knowledge base covering features, settings, scripting, workflows, and visual thinking methods, explore the public [NotebookLM workbook](https://notebooklm.google.com/notebook/42d76a2f-c11d-4002-9286-1683c43d0ab0) (a must‑have learning resource). If you are curious about the Visual PKM philosophy behind the plugin, consider my book [Sketch Your Mind](https://sketch-your-mind.com/) and the [Visual Thinking Workshops](https://visual-thinking-workshop.com/). Finally, keep the [Excalidraw Plugin Wiki](https://excalidraw-obsidian.online/) at hand—it is an essential companion.
|
||||
Excalidraw for Obsidian keeps evolving; it is extremely feature‑rich and can feel intimidating at first. The Video Walkthrough below should ease that initial overwhelm. For a comprehensive, searchable knowledge base covering features, settings, scripting, workflows, and visual thinking methods, explore the public [NotebookLM workbook](https://notebooklm.google.com/notebook/42d76a2f-c11d-4002-9286-1683c43d0ab0) (a must‑have learning resource).
|
||||
|
||||
<a href="https://community.sketch-your-mind.com/ee"><img src="https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/images/logo-EE.png?raw=true" width="150"></a>
|
||||
|
||||
[**Excalidraw Essentials**](https://community.sketch-your-mind.com/ee) is a free course to get started with Excalidraw.
|
||||
|
||||
<a href="https://community.sketch-your-mind.com/sym"><img src="https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/images/sym-cover.jpg?raw=true" width="150"></a>
|
||||
|
||||
If you are curious about the Visual PKM philosophy behind the plugin, consider my book [Sketch Your Mind](https://community.sketch-your-mind.com/sym) and the [Visual Thinking Workshops](https://community.sketch-your-mind.com/vtw). To learn about all the different options available and how they fit together, check out the [Welcome to the Sketch Your Mind Ecosystem](https://community.sketch-your-mind.com/t/welcome-to-the-sketch-your-mind-ecosystem/375) introduction page. Finally, keep the [Excalidraw Plugin Wiki](https://community.sketch-your-mind.com/Wiki) and the [NotebookLM workbook](https://notebooklm.google.com/notebook/42d76a2f-c11d-4002-9286-1683c43d0ab0) at hand, those are essential companions.
|
||||
|
||||
## Disclaimer / Disclosure: Plugin Access and Privileges
|
||||
|
||||
I treat privacy as a top priority. Apart from the few technical limitations outlined below, Excalidraw is 100% local and runs without network access. Most of the findings published on sites such as [obsidianpluginaudit.com](https://obsidianpluginaudit.com/), [plugin.observer](https://plugin.observer/), and [community.obsidian.md/plugins](https://community.obsidian.md/plugins) can be misleading without proper context.
|
||||
|
||||
Obsidian is fundamentally a locally executed web application. Automated code scanners apply the same vulnerability rules used for public-facing websites, even though the risk model inside a local Obsidian vault is very different. For example, patterns such as `innerHTML` or `outerHTML` manipulation are considered problematic on public websites because they can expose visitors to malicious third-party content. In a local-first application such as Obsidian, these risks are significantly different in nature and impact.
|
||||
|
||||
Excalidraw for Obsidian is a large and feature-rich tool with many integrations and performance optimizations. Below, I explain how the most common findings reported by these scanners are actually used within the plugin.
|
||||
|
||||
When evaluating these findings, please keep the following in mind:
|
||||
|
||||
1. Obsidian.md currently does not provide plugin developers with proper mechanisms for deploying local assets such as fonts, auxiliary packages, or official APIs for certain features like Obsidian Publish or PDF generation. As a result, plugin developers sometimes need to rely on workaround solutions such as IPC calls or dynamic code execution (`eval`) to deliver functionality users expect.
|
||||
|
||||
2. Excalidraw for Obsidian is not maintained by a company or engineering team. It is a one-person hobby project and an open-source contribution developed alongside a full-time job. If you would like to support continued development and improved code quality, the best way is through financial support via [Ko-fi](https://ko-fi.com/zsolt). Open-source software is not truly “free.” The cost is usually paid in developer time, personal energy, or by supporters who help sustain the project. I will continue striving to improve the codebase, but expectations around enterprise-grade engineering standards for a free community contribution can easily become unrealistic and unsustainable without corresponding support structures.
|
||||
|
||||
3. In general, I recommend using the minimum number of plugins necessary for your workflow. Personally, I use around 10–15 plugins and disable plugins when not actively needed. This is not because I distrust plugin safety, but because most Obsidian plugins are hobby-driven community projects, and I believe users should maintain realistic expectations regarding maintenance, complexity, and long-term support.
|
||||
|
||||
<details><summary><h3>Detailed Findings</h3></summary>
|
||||
|
||||
- **Plugin might make requests to external domains:**
|
||||
- The plugin works fully offline and locally by default.
|
||||
- If you configure API keys for AI features and explicitly use those features, the corresponding AI providers are contacted.
|
||||
- The Taskbone OCR service requires a separate API key and explicit user opt-in in plugin settings.
|
||||
- Iframely is optionally used to resolve reader-friendly webpage titles when dragging website links into Excalidraw. This feature is disabled by default.
|
||||
- The Ko-fi support button, when enabled, downloads its image asset from `cdn.ko-fi.com`.
|
||||
- The CJK font package exceeds 12 MB in size. To avoid significantly increasing plugin startup time and bundle size, these fonts are downloaded from GitHub only when required.
|
||||
|
||||
- **`requestUrl` and `fetch` calls:**
|
||||
- Used for AI integrations and Taskbone OCR functionality.
|
||||
- Excalidraw supports embedding images from external sources (local URIs and public URLs). `requestUrl` is used to retrieve those images when needed.
|
||||
- The Excalidraw Script Library accesses GitHub to download scripts only when the user explicitly chooses to install them.
|
||||
|
||||
- **Excalidraw accesses files in your vault:**
|
||||
- To detect legacy `.excalidraw` files and support conversion workflows.
|
||||
- To search for and load custom fonts stored inside the vault.
|
||||
- To populate file picker dialogs such as “Insert any file.”
|
||||
|
||||
- **Clipboard access:**
|
||||
- Allows users to copy and paste Excalidraw scenes between Obsidian and excalidraw.com.
|
||||
- Allows users to copy links to scene elements and paste them into markdown documents as embeds.
|
||||
|
||||
- **Local Storage:**
|
||||
- Excalidraw stores image caches locally to improve loading performance for large and complex scenes.
|
||||
- Mermaid text-to-diagram chat history is stored locally.
|
||||
- Backup versions of drawings are stored locally to support crash recovery.
|
||||
|
||||
- **Dynamic Code Execution:**
|
||||
- Excalidraw dynamically loads user-created scripts and scripts installed from the Script Library.
|
||||
- Excalidraw also dynamically loads parts of the Excalidraw React component and supporting packages. This improves startup performance and supports functionality such as desktop popout windows.
|
||||
|
||||
- **Electron remote module privilege IPC bridge calls:**
|
||||
- Used to access Electron’s built-in PDF generation capabilities so users can export drawings as PDFs.
|
||||
- This avoids bundling additional large PDF libraries, reducing plugin size and improving performance.
|
||||
- The process also enables Electron’s native file-save dialog when exporting PDFs.
|
||||
|
||||
- **Document-level keyboard listener:**
|
||||
- Comes from the core excalidraw.com component to support keyboard shortcuts and interactions.
|
||||
|
||||
- **Direct Node.js file system access allowing access outside the vault:**
|
||||
- Used exclusively to support embedding images located outside the Obsidian vault into Excalidraw scenes.
|
||||
|
||||
</details>
|
||||
|
||||
## Video Walkthrough
|
||||
<a href="https://youtu.be/P_Q6avJGoWI" target="_blank"><img src="https://github.com/zsviczian/obsidian-excalidraw-plugin/assets/14358394/da34bb33-7610-45e6-b36f-cb7a02a9141b" width="300"/></a>
|
||||
@@ -14,7 +84,7 @@ Excalidraw for Obsidian keeps evolving; it is extremely feature‑rich and can f
|
||||
<a href="https://youtu.be/QKnQgSjJVuc" target="_blank"><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/thumbnail-getting-started.jpg" width="300"/></a>
|
||||
|
||||
### Here's my complete catalog of videos:
|
||||
<a href="https://excalidraw-obsidian.online/wiki/catalogue"><img width="380" alt="image" src="https://github.com/zsviczian/obsidian-excalidraw-plugin/assets/14358394/2577e5ad-7a21-4c62-acd5-4fe80c8a8a95"></a>
|
||||
<a href="https://community.sketch-your-mind.com/t/a-visual-catalogue-of-all-my-youtube-videos/701"><img width="380" alt="image" src="https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/images/catalogue.jpg?raw=true"></a>
|
||||
<br>
|
||||
|
||||
<details><summary>10 Part (slightly outdated) Video Walkthrough</summary>
|
||||
@@ -33,7 +103,7 @@ Excalidraw for Obsidian keeps evolving; it is extremely feature‑rich and can f
|
||||
<a href="https://www.youtube.com/watch?v=_c_0zpBJ4Xc&" target="_blank"><img src="https://user-images.githubusercontent.com/14358394/138607067-ccb62f92-48a4-4880-ac6e-68c1bf86ac2c.png" width="100" style="vertical-align: middle;"/> Image Elements</a><br>
|
||||
<a href="https://youtu.be/r08wk-58DPk" target="_blank"><img src="https://user-images.githubusercontent.com/14358394/143732412-1c65227e-4381-406d-847a-b001ab3506ca.jpg" width="100" style="vertical-align: middle;"/> LaTex Demo</a><br>
|
||||
<a href="https://youtu.be/tsecSfnTMow" target="_blank"><img src="https://user-images.githubusercontent.com/14358394/143732440-90bfa029-8615-462e-ada3-c903d71a82c9.jpg" width="100" style="vertical-align: middle;"/> Markdown embeds</a><br>
|
||||
<a href="https://youtu.be/K6qZkTz8GHs" target="_blank"><img src="https://user-images.githubusercontent.com/14358394/143783906-15cee494-c6d5-4495-a2ca-74634e4e7355.jpg" width="100" style="vertical-align: middle;"/> Markdown embeds advanced features</a><br>
|
||||
<a href="https://youtu.be/K6qZkTz8GHs" target="_blank"><img src="https://user-images.githubusercontent.com/143783906-15cee494-c6d5-4495-a2ca-74634e4e7355.jpg" width="100" style="vertical-align: middle;"/> Markdown embeds advanced features</a><br>
|
||||
<a href="https://youtu.be/Etskjw7a5zo" target="_blank"><img src="https://user-images.githubusercontent.com/14358394/156931461-0979b821-315a-41dd-86f1-31d169b7c127.jpg" width="100" style="vertical-align: middle;"/> Link to Elements, Vertical text alignment, Markdown Styling</a><br>
|
||||
</details>
|
||||
<details><summary>The Script Engine Store - Excalidraw Automation</summary>
|
||||
@@ -70,7 +140,7 @@ Excalidraw for Obsidian keeps evolving; it is extremely feature‑rich and can f
|
||||
</details>
|
||||
|
||||
### Beta testing
|
||||
The plugin follows a monthly release schedule. If you want to receive more frequent updates with new features (e.g. shiny new stuff available on excalidraw.com, but not yet in Obsidian) and minor bug fixes, then join the beta community.
|
||||
The plugin follows a monthly release schedule. If you want to receive more frequent updates with new features (e.g. shiny new stuff available on excalidraw.com, but not yet in Obsidian) and minor bug fixes, then [join the beta community](https://community.sketch-your-mind.com/t/about-the-beta-releases-category/329).
|
||||
|
||||
[](https://youtu.be/2poSS-Z91lY)
|
||||
|
||||
@@ -307,5 +377,4 @@ You can find me on Twitter [@zsviczian](https://twitter.com/zsviczian), and on m
|
||||
## Friends of Excalidraw
|
||||
If you enjoy Excalidraw, consider giving [ExcaliBrain](https://github.com/zsviczian/excalibrain) a try (also available via Obsidian Community Plugins).
|
||||
|
||||
<a href="https://youtu.be/gOkniMkDPyM" target="_blank"><img src="https://user-images.githubusercontent.com/14358394/169708346-9e41289d-9536-43ec-8f70-2d2ad2d369d6.png" width="300"/></a>
|
||||
|
||||
<a href="https://youtu.be/gOkniMkDPyM" target="_blank"><img src="https://user-images.githubusercontent.com/14358394/169708346-9e41289d-9536-43ec-8f70-2d2ad2d369d6.png" width="300"/></a>
|
||||
@@ -5,6 +5,11 @@
|
||||
/* ************************************** */
|
||||
/* lib/shared/ExcalidrawAutomate.d.ts */
|
||||
/* ************************************** */
|
||||
type ExcalidrawCustomDataValue = string | number | boolean | null | ExcalidrawCustomDataValue[] | {
|
||||
[key: string]: ExcalidrawCustomDataValue;
|
||||
};
|
||||
type ExcalidrawCustomDataPatch = Partial<Record<string, ExcalidrawCustomDataValue | undefined>>;
|
||||
type ExcalidrawAutomateHelpTarget = ((...args: any[]) => any) | string;
|
||||
/**
|
||||
* ExcalidrawAutomate is a utility class that provides a simplified API to interact with Excalidraw elements and the Excalidraw canvas.
|
||||
* Elements in the Excalidraw Scene are immutable. You should never directly change element properties in the scene object.
|
||||
@@ -90,25 +95,71 @@ export declare class ExcalidrawAutomate {
|
||||
* Add or modify keys in an element's customData while preserving existing keys.
|
||||
* Creates customData={} if it does not exist.
|
||||
* @param {string} id - The element ID in elementsDict to modify.
|
||||
* @param {Partial<Record<string, unknown>>} newData - Object containing key-value pairs to add/update. Set value to undefined to delete a key.
|
||||
* @param {ExcalidrawCustomDataPatch} newData - Object containing key-value pairs to add/update. Set value to undefined to delete a key.
|
||||
* @returns {Mutable<ExcalidrawElement> | undefined} The modified element, or undefined if element does not exist.
|
||||
*/
|
||||
addAppendUpdateCustomData(id: string, newData: Partial<Record<string, unknown>>): ExcalidrawElement;
|
||||
addAppendUpdateCustomData(id: string, newData: ExcalidrawCustomDataPatch): ExcalidrawElement;
|
||||
/**
|
||||
* Displays help information for EA functions and properties intended to be used in Obsidian developer console.
|
||||
* @param {Function | string} target - Function reference or property name as string.
|
||||
* @param {ExcalidrawAutomateHelpTarget} target - Function reference or property name as string.
|
||||
* Usage examples:
|
||||
* - ea.help(ea.functionName)
|
||||
* - ea.help('propertyName')
|
||||
* - ea.help('utils.functionName')
|
||||
*/
|
||||
help(target: Function | string): void;
|
||||
help(target: ExcalidrawAutomateHelpTarget): void;
|
||||
/**
|
||||
* Posts an AI request to the currently configured provider and returns the response.
|
||||
* @param {AIRequest} request - The AI request configuration.
|
||||
* @returns {Promise<RequestUrlResponse>} Promise resolving to the provider-normalized API response.
|
||||
*/
|
||||
postAI(request: AIRequest): Promise<RequestUrlResponse>;
|
||||
/**
|
||||
* Posts an AI request to the OpenAI API and returns the response.
|
||||
* @param {AIRequest} request - The AI request configuration.
|
||||
* @returns {Promise<RequestUrlResponse>} Promise resolving to the API response.
|
||||
*/
|
||||
postOpenAI(request: AIRequest): Promise<RequestUrlResponse>;
|
||||
/**
|
||||
* Returns the sanitized Excalidraw AI configuration currently available to scripts.
|
||||
*/
|
||||
getAISettings(): ExcalidrawAISettings | null;
|
||||
/**
|
||||
* Sends a text or multimodal chat request to the configured AI text model.
|
||||
*/
|
||||
generateAIText(request: AIRequest): Promise<{
|
||||
response: RequestUrlResponse;
|
||||
json: any;
|
||||
content: string;
|
||||
rateLimit: number | null;
|
||||
rateLimitRemaining: number | null;
|
||||
}>;
|
||||
/**
|
||||
* Sends an image-analysis request to the configured multimodal text model.
|
||||
*/
|
||||
analyzeAIImage(request: AIRequest): Promise<{
|
||||
response: RequestUrlResponse;
|
||||
json: any;
|
||||
content: string;
|
||||
rateLimit: number | null;
|
||||
rateLimitRemaining: number | null;
|
||||
}>;
|
||||
/**
|
||||
* Generates a new image using the configured AI image model.
|
||||
*/
|
||||
generateAIImage(request: AIRequest): Promise<import("../utils/AIUtils").GenerateAIImageResult>;
|
||||
/**
|
||||
* Applies a prompt-driven edit to an input image using the configured AI image model.
|
||||
*/
|
||||
transformAIImage(request: AIRequest): Promise<import("../utils/AIUtils").GenerateAIImageResult>;
|
||||
/**
|
||||
* Applies a mask-based edit to an input image using the configured AI image model.
|
||||
*/
|
||||
maskEditAIImage(request: AIRequest): Promise<import("../utils/AIUtils").GenerateAIImageResult>;
|
||||
/**
|
||||
* Creates a lightweight chat session wrapper that preserves prior messages between calls.
|
||||
*/
|
||||
createAIChatSession(initialRequest?: Omit<AIRequest, "messages">): import("../utils/AIUtils").AIChatSession;
|
||||
/**
|
||||
* Extracts code blocks from markdown text.
|
||||
* @param {string} markdown - The markdown string to parse.
|
||||
@@ -209,7 +260,7 @@ export declare class ExcalidrawAutomate {
|
||||
* @returns {{view:any}|{file:TFile, editor:Editor}|null} The active embeddable view or editor.
|
||||
*/
|
||||
getActiveEmbeddableViewOrEditor(view?: ExcalidrawView): {
|
||||
view: any;
|
||||
view: View;
|
||||
} | {
|
||||
file: TFile;
|
||||
editor: Editor;
|
||||
@@ -256,7 +307,7 @@ export declare class ExcalidrawAutomate {
|
||||
viewBackgroundColor: string;
|
||||
gridSize: number;
|
||||
};
|
||||
colorPalette: {};
|
||||
colorPalette: object;
|
||||
sidepanelTab: ExcalidrawSidepanelTab | null;
|
||||
constructor(plugin: ExcalidrawPlugin, view?: ExcalidrawView);
|
||||
/**
|
||||
@@ -271,7 +322,7 @@ export declare class ExcalidrawAutomate {
|
||||
* 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.
|
||||
*/
|
||||
*/
|
||||
checkForActiveSidepanelTabForScript(scriptName?: string): ExcalidrawSidepanelTab | null;
|
||||
/**
|
||||
* Creates a new sidepanel tab associated with this ExcalidrawAutomate instance.
|
||||
@@ -316,6 +367,17 @@ export declare class ExcalidrawAutomate {
|
||||
* @returns {KeyBlocker} The suggester instance; call close() to detach; call .isBlockingKeys() to check if suggester dropdown is open.
|
||||
*/
|
||||
attachInlineLinkSuggester(inputEl: HTMLInputElement, widthWrapper?: HTMLElement): KeyBlocker;
|
||||
/**
|
||||
* Parses text using the target view's ExcalidrawData parser.
|
||||
*
|
||||
* This reuses ExcalidrawData parsing logic directly, including transclusion
|
||||
* resolution, link bracket rendering, and link/url prefixes based on the
|
||||
* target file's frontmatter.
|
||||
*
|
||||
* @param {string} text - Raw text to parse.
|
||||
* @returns {Promise<string | undefined>} Parsed text, or undefined when input/view is unavailable.
|
||||
*/
|
||||
parseText(text: string): Promise<string | undefined>;
|
||||
/**
|
||||
* Returns the last recorded pointer position on the Excalidraw canvas.
|
||||
* @returns {{x:number, y:number}} The last recorded pointer position.
|
||||
@@ -401,6 +463,9 @@ export declare class ExcalidrawAutomate {
|
||||
getElement(id: string): Mutable<ExcalidrawElement>;
|
||||
/**
|
||||
* Returns an object describing the bound text element.
|
||||
*
|
||||
* IMPORTANT: The returned object contains EITHER `eaElement` OR `sceneElement`, never both.
|
||||
*
|
||||
* 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
|
||||
@@ -409,6 +474,15 @@ export declare class ExcalidrawAutomate {
|
||||
* - 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.
|
||||
*
|
||||
* Recommended usage pattern for editing:
|
||||
* const boundText = ea.getBoundTextElement(container, true);
|
||||
* let textEl = boundText.eaElement;
|
||||
* if (!textEl && boundText.sceneElement) {
|
||||
* ea.copyViewElementsToEAforEditing([boundText.sceneElement]);
|
||||
* textEl = ea.getElement(boundText.sceneElement.id);
|
||||
* }
|
||||
* if (textEl) { ... safely modify textEl ... }
|
||||
* @param element: ExcalidrawElement | ExcalidrawElement[] - The selected container with text (an array of 2 elements) to check.
|
||||
* @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.
|
||||
@@ -436,6 +510,7 @@ export declare class ExcalidrawAutomate {
|
||||
onNewPane?: boolean;
|
||||
silent?: boolean;
|
||||
frontmatterKeys?: {
|
||||
[key: string]: string | number | boolean | undefined;
|
||||
"excalidraw-plugin"?: "raw" | "parsed";
|
||||
"excalidraw-link-prefix"?: string;
|
||||
"excalidraw-link-brackets"?: boolean;
|
||||
@@ -452,7 +527,7 @@ export declare class ExcalidrawAutomate {
|
||||
"excalidraw-mask"?: boolean;
|
||||
"excalidraw-open-md"?: boolean;
|
||||
"excalidraw-export-internal-links"?: boolean;
|
||||
"cssclasses"?: string;
|
||||
cssclasses?: string;
|
||||
};
|
||||
plaintext?: string;
|
||||
}): Promise<string>;
|
||||
@@ -470,7 +545,7 @@ export declare class ExcalidrawAutomate {
|
||||
* @example
|
||||
* const dimensions = getPageDimensions("A4", "portrait");
|
||||
* console.log(dimensions); // { width: 794.56, height: 1122.56 }
|
||||
*/
|
||||
*/
|
||||
getPagePDFDimensions(pageSize: PageSize, orientation: PageOrientation): PageDimensions;
|
||||
/**
|
||||
* Creates a PDF from the provided SVG elements with specified scaling and page properties.
|
||||
@@ -493,7 +568,7 @@ export declare class ExcalidrawAutomate {
|
||||
* }
|
||||
* filename: "example.pdf",
|
||||
* });
|
||||
*/
|
||||
*/
|
||||
createPDF({ SVG, scale, pageProps, filename, }: {
|
||||
SVG: SVGSVGElement[];
|
||||
scale?: PDFExportScale;
|
||||
@@ -513,7 +588,7 @@ export declare class ExcalidrawAutomate {
|
||||
* @param {boolean} [options.embedScene=false] - Whether to embed the scene in the SVG.
|
||||
* @param {ExcalidrawElement[]} [options.elementsOverride] - Optional override for the elements to include in the SVG. Primary to support the Printable Layout Wizard script
|
||||
* @returns {Promise<SVGSVGElement>} A promise that resolves to the SVG element.
|
||||
*/
|
||||
*/
|
||||
createViewSVG({ withBackground, theme, frameRendering, padding, selectedOnly, skipInliningFonts, embedScene, elementsOverride, }: {
|
||||
withBackground?: boolean;
|
||||
theme?: "light" | "dark";
|
||||
@@ -776,7 +851,7 @@ export declare class ExcalidrawAutomate {
|
||||
* Adds an image element to the ExcalidrawAutomate instance.
|
||||
* @param {number | AddImageOptions} topXOrOpts - The x-coordinate of the top-left corner or an options object.
|
||||
* @param {number} topY - The y-coordinate of the top-left corner.
|
||||
* @param {TFile | string} imageFile - The image file or URL.
|
||||
* @param {TFile | string} imageFile - The image file, hyperlink, vault path, PDF++ reference, or data URL.
|
||||
* @param {boolean} [scale=true] - Whether to scale the image to MAX_IMAGE_SIZE.
|
||||
* @param {boolean} [anchor=true] - Whether to anchor the image at 100% size.
|
||||
* @returns {Promise<string>} Promise resolving to the ID of the added image element.
|
||||
@@ -882,14 +957,14 @@ export declare class ExcalidrawAutomate {
|
||||
setView(view?: ExcalidrawView | "auto" | "first" | "active" | null, show?: boolean): ExcalidrawView;
|
||||
/**
|
||||
* Returns the Excalidraw API for the current view.
|
||||
* @returns {any} The Excalidraw API.
|
||||
* @returns {ExcalidrawImperativeAPI} The Excalidraw API.
|
||||
*/
|
||||
getExcalidrawAPI(): any;
|
||||
getExcalidrawAPI(): ExcalidrawImperativeAPI;
|
||||
/**
|
||||
* Gets elements in the current view.
|
||||
* @returns {ExcalidrawElement[]} Array of elements in the view.
|
||||
* @returns {readonly ExcalidrawElement[]} Array of elements in the view.
|
||||
*/
|
||||
getViewElements(): ExcalidrawElement[];
|
||||
getViewElements(): readonly ExcalidrawElement[];
|
||||
/**
|
||||
* Deletes elements in the view by removing them from the scene (not by setting isDeleted to true).
|
||||
* @param {ExcalidrawElement[]} elToDelete - Array of elements to delete.
|
||||
@@ -944,10 +1019,10 @@ export declare class ExcalidrawAutomate {
|
||||
/**
|
||||
* Gets the color information from an Excalidraw file.
|
||||
* @param {TFile} file - The Excalidraw file.
|
||||
* @param {ExcalidrawImageElement} img - The image element.
|
||||
* @param {ExcalidrawImageElement} img? - Optional, if not provided, the function returns colors from all elements.
|
||||
* @returns {Promise<SVGColorInfo>} Promise resolving to the SVG color information.
|
||||
*/
|
||||
getColosFromExcalidrawFile(file: TFile, img: ExcalidrawImageElement): Promise<SVGColorInfo>;
|
||||
getColosFromExcalidrawFile(file: TFile, img?: ExcalidrawImageElement): Promise<SVGColorInfo>;
|
||||
/**
|
||||
* Extracts color information from an SVG string.
|
||||
* @param {string} svgString - The SVG string.
|
||||
@@ -975,7 +1050,7 @@ export declare class ExcalidrawAutomate {
|
||||
* @param {Object} scene - The scene to load to Excalidraw.
|
||||
* @param {ExcalidrawElement[]} [scene.elements] - Array of elements in the scene.
|
||||
* @param {AppState} [scene.appState] - The app state of the scene.
|
||||
* @param {BinaryFileData} [scene.files] - The files in the scene.
|
||||
* @param {BinaryFiles} [scene.files] - The files in the scene.
|
||||
* @param {boolean} [scene.commitToHistory] - Whether to commit the scene to history. @deprecated Use scene.storageOption instead
|
||||
* @param {"capture" | "none" | "update"} [scene.storeAction] - The store action for the scene. @deprecated Use scene.storageOption instead
|
||||
* @param {"IMMEDIATELY" | "NEVER" | "EVENTUALLY"} [scene.captureUpdate] - The capture update action for the scene.
|
||||
@@ -983,8 +1058,8 @@ export declare class ExcalidrawAutomate {
|
||||
*/
|
||||
viewUpdateScene(scene: {
|
||||
elements?: ExcalidrawElement[];
|
||||
appState?: AppState | {};
|
||||
files?: BinaryFileData;
|
||||
appState?: AppState | object;
|
||||
files?: BinaryFiles;
|
||||
commitToHistory?: boolean;
|
||||
storeAction?: "capture" | "none" | "update";
|
||||
captureUpdate?: SceneData["captureUpdate"];
|
||||
@@ -1044,18 +1119,18 @@ export declare class ExcalidrawAutomate {
|
||||
*/
|
||||
onViewModeChangeHook: (isViewModeEnabled: boolean, view: ExcalidrawView, ea: ExcalidrawAutomate) => void;
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
* 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;
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
* 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;
|
||||
/**
|
||||
* If set, this callback is triggered, when Excalidraw receives an onDrop event.
|
||||
@@ -1233,7 +1308,7 @@ export declare class ExcalidrawAutomate {
|
||||
* @param {ExcalidrawView} view - The Excalidraw view.
|
||||
* @param {string} color - The new canvas color.
|
||||
*/
|
||||
onCanvasColorChangeHook: (ea: ExcalidrawAutomate, view: ExcalidrawView, //the excalidraw view
|
||||
onCanvasColorChangeHook: (ea: ExcalidrawAutomate, view: ExcalidrawView, //the excalidraw view
|
||||
color: string) => void;
|
||||
/**
|
||||
* If set, this callback is triggered whenever a drawing is exported to SVG.
|
||||
@@ -1279,7 +1354,7 @@ export declare class ExcalidrawAutomate {
|
||||
* @param {ExcalidrawElement[]} elements - Array of elements to get the bounding box for.
|
||||
* @returns {{topX: number; topY: number; width: number; height: number}} The bounding box of the elements.
|
||||
*/
|
||||
getBoundingBox(elements: ExcalidrawElement[]): {
|
||||
getBoundingBox(elements: readonly ExcalidrawElement[]): {
|
||||
topX: number;
|
||||
topY: number;
|
||||
width: number;
|
||||
@@ -1320,7 +1395,7 @@ export declare class ExcalidrawAutomate {
|
||||
* @param {boolean} [includeFrameElements=false] - Whether to include frame elements in the search.
|
||||
* @returns {ExcalidrawElement[]} Array of elements in the same group as the specified element.
|
||||
*/
|
||||
getElementsInTheSameGroupWithElement(element: ExcalidrawElement, elements: ExcalidrawElement[], includeFrameElements?: boolean): ExcalidrawElement[];
|
||||
getElementsInTheSameGroupWithElement(element: ExcalidrawElement, elements: readonly NonDeletedExcalidrawElement[], includeFrameElements?: boolean): ExcalidrawElement[];
|
||||
/**
|
||||
* Gets all the elements from elements[] that are contained in the specified frame.
|
||||
* @param {ExcalidrawElement} frameElement - The frame element.
|
||||
@@ -1328,7 +1403,7 @@ export declare class ExcalidrawAutomate {
|
||||
* @param {boolean} [shouldIncludeFrame=false] - Whether to include the frame element in the result.
|
||||
* @returns {ExcalidrawElement[]} Array of elements contained in the frame.
|
||||
*/
|
||||
getElementsInFrame(frameElement: ExcalidrawElement, elements: ExcalidrawElement[], shouldIncludeFrame?: boolean): ExcalidrawElement[];
|
||||
getElementsInFrame(frameElement: ExcalidrawElement, elements: readonly NonDeletedExcalidrawElement[], shouldIncludeFrame?: boolean): ExcalidrawElement[];
|
||||
/**
|
||||
* Sets the active script for the ScriptEngine.
|
||||
* @param {string} scriptName - The name of the active script.
|
||||
@@ -1339,7 +1414,7 @@ export declare class ExcalidrawAutomate {
|
||||
* Saves settings in plugin settings, under the activeScript key.
|
||||
* @returns {Object} The script settings.
|
||||
*/
|
||||
getScriptSettings(): {};
|
||||
getScriptSettings(): object;
|
||||
/**
|
||||
* Sets the script settings for the active script.
|
||||
* @param {Object} settings - The script settings to set.
|
||||
@@ -1393,10 +1468,10 @@ export declare class ExcalidrawAutomate {
|
||||
verifyMinimumPluginVersion(requiredVersion: string): boolean;
|
||||
/**
|
||||
* Checks if the provided view is an instance of ExcalidrawView.
|
||||
* @param {any} view - The view to check.
|
||||
* @param {ExcalidrawView | null | undefined} view - The view to check.
|
||||
* @returns {boolean} True if the view is an instance of ExcalidrawView, false otherwise.
|
||||
*/
|
||||
isExcalidrawView(view: any): boolean;
|
||||
isExcalidrawView(view: ExcalidrawView | null | undefined): boolean;
|
||||
/**
|
||||
* Sets the selection in the view.
|
||||
* @param {ExcalidrawElement[] | string[]} elements - Array of elements or element IDs to select.
|
||||
@@ -1485,7 +1560,7 @@ export declare class ExcalidrawAutomate {
|
||||
* Gets the PolyBool class from https://github.com/velipso/polybooljs.
|
||||
* @returns {PolyBool} The PolyBool class.
|
||||
*/
|
||||
getPolyBool(): any;
|
||||
getPolyBool(): typeof PolyBool;
|
||||
/**
|
||||
* Imports an SVG string into ExcalidrawAutomate elements.
|
||||
* @param {string} svgString - The SVG string to import.
|
||||
@@ -1534,6 +1609,7 @@ export type ImageInfo = {
|
||||
size?: Size;
|
||||
colorMap?: ColorMap;
|
||||
pdfPageViewProps?: PDFPageViewProps;
|
||||
renderScale?: number;
|
||||
};
|
||||
export interface AddImageOptions {
|
||||
topX: number;
|
||||
@@ -1580,14 +1656,14 @@ export interface SidepanelTab {
|
||||
/** 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.
|
||||
*/
|
||||
* 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;
|
||||
@@ -1757,8 +1833,8 @@ export declare const STANDARD_PAGE_SIZES: {
|
||||
readonly height: 1632;
|
||||
};
|
||||
readonly Ledger: {
|
||||
readonly width: 1632;
|
||||
readonly height: 1056;
|
||||
readonly width: 1056;
|
||||
readonly height: 1632;
|
||||
};
|
||||
readonly "HD Screen": {
|
||||
readonly width: 1920;
|
||||
@@ -1798,16 +1874,20 @@ export type ImgData = {
|
||||
fileId: FileId;
|
||||
dataURL: DataURL;
|
||||
created: number;
|
||||
loadedFromCache?: boolean;
|
||||
hasSVGwithBitmap: boolean;
|
||||
size: Size;
|
||||
pdfPageViewProps?: PDFPageViewProps;
|
||||
renderScale?: number;
|
||||
};
|
||||
export declare type MimeType = ValueOf<typeof IMAGE_MIME_TYPES> | "application/octet-stream";
|
||||
export type FileData = BinaryFileData & {
|
||||
size: Size;
|
||||
loadedFromCache?: boolean;
|
||||
hasSVGwithBitmap: boolean;
|
||||
shouldScale: boolean;
|
||||
pdfPageViewProps?: PDFPageViewProps;
|
||||
renderScale?: number;
|
||||
};
|
||||
export type PDFPageViewProps = {
|
||||
left: number;
|
||||
@@ -1827,10 +1907,70 @@ export interface ColorMap {
|
||||
/* ******************************** */
|
||||
/* lib/types/AIUtilTypes.d.ts */
|
||||
/* ******************************** */
|
||||
type MessageContent = string | (string | {
|
||||
export type AIProvider = "openai" | "anthropic" | "google" | "xai" | "openai-compatible";
|
||||
export type AIFileInput = string | {
|
||||
url: string;
|
||||
filename?: string;
|
||||
mimeType?: string;
|
||||
} | {
|
||||
dataURL: string;
|
||||
filename?: string;
|
||||
mimeType?: string;
|
||||
};
|
||||
export type AIImageInput = string | {
|
||||
url: string;
|
||||
detail?: "low" | "high" | "auto";
|
||||
filename?: string;
|
||||
mimeType?: string;
|
||||
} | {
|
||||
dataURL: string;
|
||||
detail?: "low" | "high" | "auto";
|
||||
filename?: string;
|
||||
mimeType?: string;
|
||||
};
|
||||
export type AIImageModelCapability = {
|
||||
supportedSizes: string[];
|
||||
supportsPromptImageTransforms: boolean;
|
||||
supportsMaskImageEdits: boolean;
|
||||
};
|
||||
export type AIProviderProfile = {
|
||||
provider: AIProvider;
|
||||
apiKey: string;
|
||||
baseURL: string;
|
||||
};
|
||||
export type AIModelConfig = {
|
||||
providerId: string;
|
||||
model: string;
|
||||
endpoint?: string;
|
||||
multimodalSupport?: boolean;
|
||||
};
|
||||
export type AIImageModelConfig = AIModelConfig & AIImageModelCapability;
|
||||
export type ExcalidrawAISettings = {
|
||||
enabled: boolean;
|
||||
providerProfiles: Record<string, {
|
||||
provider: AIProvider;
|
||||
baseURL: string;
|
||||
hasApiKey: boolean;
|
||||
}>;
|
||||
textModels: Record<string, AIModelConfig>;
|
||||
imageModels: Record<string, AIImageModelConfig>;
|
||||
defaultTextModel: string;
|
||||
defaultMultimodalTextModel: string;
|
||||
defaultImageModel: string;
|
||||
defaultMaxOutgoingTokens: number;
|
||||
defaultMaxResponseTokens: number;
|
||||
};
|
||||
export type OpenAIImageURLPart = {
|
||||
type: "image_url";
|
||||
image_url: string;
|
||||
})[];
|
||||
image_url: string | {
|
||||
url: string;
|
||||
detail?: "low" | "high" | "auto";
|
||||
};
|
||||
};
|
||||
type MessageContent = string | ({
|
||||
type: "text";
|
||||
text: string;
|
||||
} | OpenAIImageURLPart)[];
|
||||
export type GPTCompletionRequest = {
|
||||
model: string;
|
||||
messages?: {
|
||||
@@ -1838,12 +1978,19 @@ export type GPTCompletionRequest = {
|
||||
content?: MessageContent;
|
||||
name?: string | undefined;
|
||||
}[];
|
||||
functions?: any[] | undefined;
|
||||
function_call?: any | undefined;
|
||||
functions?: {
|
||||
name: string;
|
||||
description?: string;
|
||||
parameters?: Record<string, string | number | boolean | null | Record<string, string | number | boolean | null>>;
|
||||
}[] | undefined;
|
||||
function_call?: "none" | "auto" | {
|
||||
name: string;
|
||||
} | undefined;
|
||||
stream?: boolean | undefined;
|
||||
temperature?: number | undefined;
|
||||
top_p?: number | undefined;
|
||||
max_tokens?: number | undefined;
|
||||
max_completion_tokens?: number | undefined;
|
||||
n?: number | undefined;
|
||||
best_of?: number | undefined;
|
||||
frequency_penalty?: number | undefined;
|
||||
@@ -1858,16 +2005,43 @@ export type GPTCompletionRequest = {
|
||||
image?: string;
|
||||
mask?: string;
|
||||
};
|
||||
export type AIRequestMessagePart = {
|
||||
type: "text";
|
||||
text: string;
|
||||
} | {
|
||||
type: "image";
|
||||
image: AIImageInput;
|
||||
} | {
|
||||
type: "file";
|
||||
file: AIFileInput;
|
||||
} | {
|
||||
type: "audio";
|
||||
audio: AIFileInput;
|
||||
};
|
||||
export type AIRequestMessage = {
|
||||
role: "system" | "user" | "assistant";
|
||||
content: string | AIRequestMessagePart[];
|
||||
};
|
||||
export type AIRequest = {
|
||||
image?: string;
|
||||
provider?: AIProvider;
|
||||
baseURL?: string;
|
||||
apiKey?: string;
|
||||
model?: string;
|
||||
textModelId?: string;
|
||||
imageModelId?: string;
|
||||
image?: AIImageInput;
|
||||
text?: string;
|
||||
instruction?: string;
|
||||
systemPrompt?: string;
|
||||
messages?: AIRequestMessage[];
|
||||
temperature?: number;
|
||||
maxOutgoingTokens?: number;
|
||||
maxTokens?: number;
|
||||
imageGenerationProperties?: {
|
||||
size?: string;
|
||||
quality?: "standard" | "hd";
|
||||
n?: number;
|
||||
mask?: string;
|
||||
mask?: AIImageInput;
|
||||
};
|
||||
};
|
||||
|
||||
@@ -2106,7 +2280,10 @@ export type PointsPositionUpdates = Map<Index, {
|
||||
point: LocalPoint;
|
||||
isDragging?: boolean;
|
||||
}>;
|
||||
export type Arrowhead = "arrow" | "bar" | "dot" | "circle" | "circle_outline" | "triangle" | "triangle_outline" | "diamond" | "diamond_outline" | "crowfoot_one" | "crowfoot_many" | "crowfoot_one_or_many";
|
||||
export type CardinalityArrowhead = "cardinality_one" | "cardinality_many" | "cardinality_one_or_many" | "cardinality_exactly_one" | "cardinality_zero_or_one" | "cardinality_zero_or_many";
|
||||
export type ArrowheadLegacy = "dot" | "crowfoot_one" | "crowfoot_many" | "crowfoot_one_or_many";
|
||||
export type Arrowhead = "arrow" | "bar" | "circle" | "circle_outline" | "triangle" | "triangle_outline" | "diamond" | "diamond_outline" | CardinalityArrowhead;
|
||||
export type AnyArrowhead = Arrowhead | ArrowheadLegacy;
|
||||
export type ExcalidrawLinearElement = _ExcalidrawElementBase & Readonly<{
|
||||
type: "line" | "arrow";
|
||||
points: readonly LocalPoint[];
|
||||
@@ -2314,7 +2491,7 @@ export type InteractiveCanvasAppState = Readonly<_CommonCanvasAppState & {
|
||||
multiElement: AppState["multiElement"];
|
||||
newElement: AppState["newElement"];
|
||||
isBindingEnabled: AppState["isBindingEnabled"];
|
||||
invertBindingBehaviour: AppState["invertBindingBehaviour"];
|
||||
isMidpointSnappingEnabled: AppState["isMidpointSnappingEnabled"];
|
||||
suggestedBinding: AppState["suggestedBinding"];
|
||||
isRotating: AppState["isRotating"];
|
||||
elementsToHighlight: AppState["elementsToHighlight"];
|
||||
@@ -2354,6 +2531,7 @@ export type ObservedElementsAppState = {
|
||||
lockedMultiSelections: AppState["lockedMultiSelections"];
|
||||
activeLockedId: AppState["activeLockedId"];
|
||||
};
|
||||
export type BoxSelectionMode = "contain" | "overlap";
|
||||
export interface AppState {
|
||||
contextMenu: {
|
||||
items: ContextMenuItems;
|
||||
@@ -2387,8 +2565,21 @@ export interface AppState {
|
||||
* - set on pointer down, updated during pointer move
|
||||
*/
|
||||
selectionElement: NonDeletedExcalidrawElement | null;
|
||||
/**
|
||||
* tracking current arrow binding editor state (takes into account
|
||||
* `bindingPreference` and keyboard modifiers (ctrl/alt)
|
||||
*/
|
||||
isBindingEnabled: boolean;
|
||||
startBoundElement: NonDeleted<ExcalidrawBindableElement> | null;
|
||||
/** user box selection preference; defaults to "contain" when unset */
|
||||
boxSelectionMode: BoxSelectionMode;
|
||||
/** user arrow binding preference */
|
||||
bindingPreference: "enabled" | "disabled";
|
||||
/** user preference whether arrow snap to midpoints while binding */
|
||||
isMidpointSnappingEnabled: boolean;
|
||||
/**
|
||||
* The bindable element the UI highlights for the user when an arrow is
|
||||
* dragged or otherwise its endpoint being close to said element.
|
||||
*/
|
||||
suggestedBinding: {
|
||||
element: NonDeleted<ExcalidrawBindableElement>;
|
||||
midPoint?: GlobalPoint;
|
||||
@@ -2407,7 +2598,7 @@ export interface AppState {
|
||||
/**
|
||||
* set when a new text is created or when an existing text is being edited
|
||||
*/
|
||||
editingTextElement: NonDeletedExcalidrawElement | null;
|
||||
editingTextElement: ExcalidrawTextElement | null;
|
||||
activeTool: {
|
||||
/**
|
||||
* indicates a previous tool we should revert back to if we deselect the
|
||||
@@ -2496,7 +2687,7 @@ export interface AppState {
|
||||
selectedElementsAreBeingDragged: boolean;
|
||||
shouldCacheIgnoreZoom: boolean;
|
||||
toast: {
|
||||
message: string;
|
||||
message: React.ReactNode;
|
||||
closable?: boolean;
|
||||
duration?: number;
|
||||
} | null;
|
||||
@@ -2518,7 +2709,7 @@ export interface AppState {
|
||||
height: number;
|
||||
offsetTop: number;
|
||||
offsetLeft: number;
|
||||
fileHandle: FileSystemHandle | null;
|
||||
fileHandle: FileSystemFileHandle | null;
|
||||
collaborators: Map<SocketId, Collaborator>;
|
||||
stats: {
|
||||
open: boolean;
|
||||
@@ -2561,7 +2752,6 @@ export interface AppState {
|
||||
fill: string;
|
||||
nameColor: string;
|
||||
};
|
||||
invertBindingBehaviour: boolean;
|
||||
selectedLinearElement: LinearElementEditor | null;
|
||||
snapLines: readonly SnapLine[];
|
||||
originSnapOffset: {
|
||||
@@ -2599,7 +2789,7 @@ export type SearchMatch = {
|
||||
showOnCanvas: boolean;
|
||||
}[];
|
||||
};
|
||||
export type UIAppState = Omit<AppState, "startBoundElement" | "cursorButton" | "scrollX" | "scrollY">;
|
||||
export type UIAppState = Omit<AppState, "cursorButton" | "scrollX" | "scrollY">;
|
||||
export type NormalizedZoomValue = number & {
|
||||
_brand: "normalizedZoom";
|
||||
};
|
||||
@@ -2647,11 +2837,36 @@ export type OnUserFollowedPayload = {
|
||||
userToFollow: UserToFollow;
|
||||
action: "FOLLOW" | "UNFOLLOW";
|
||||
};
|
||||
export type OnExportProgress = {
|
||||
type: "progress";
|
||||
message?: React.ReactNode;
|
||||
/** 0-1 range */
|
||||
progress?: number;
|
||||
};
|
||||
export interface ExcalidrawProps {
|
||||
onChange?: (elements: readonly OrderedExcalidrawElement[], appState: AppState, files: BinaryFiles) => void;
|
||||
/**
|
||||
* note: only subscribes if the props.onIncrement is defined on initial render
|
||||
*/
|
||||
onIncrement?: (event: DurableIncrement | EphemeralIncrement) => void;
|
||||
initialData?: (() => MaybePromise<ExcalidrawInitialDataState | null>) | MaybePromise<ExcalidrawInitialDataState | null>;
|
||||
excalidrawAPI?: (api: ExcalidrawImperativeAPI) => void;
|
||||
/**
|
||||
* Invoked as soon as the Excalidraw API is available
|
||||
* NOTE editor is not yet mounted, and state is not yet initialized
|
||||
*/
|
||||
onExcalidrawAPI?: (api: ExcalidrawImperativeAPI | null) => void;
|
||||
/**
|
||||
* Invoked once the editor root is mounted.
|
||||
*/
|
||||
onMount?: (payload: ExcalidrawMountPayload) => void;
|
||||
/**
|
||||
* Invoked when the editor root is unmounted.
|
||||
*/
|
||||
onUnmount?: () => void;
|
||||
/**
|
||||
* Invoked once the initial scene is loaded.
|
||||
*/
|
||||
onInitialize?: (api: ExcalidrawImperativeAPI) => void;
|
||||
isCollaborating?: boolean;
|
||||
onPointerUpdate?: (payload: {
|
||||
pointer: {
|
||||
@@ -2724,6 +2939,29 @@ export interface ExcalidrawProps {
|
||||
showDeprecatedFonts?: boolean;
|
||||
insertLinkAction?: (linkVal: string) => void;
|
||||
renderScrollbars?: boolean;
|
||||
/**
|
||||
* Called before exporting to a file.
|
||||
*
|
||||
* Allows the host app to intercept and delay saving until async operations
|
||||
* (e.g., images are loaded) complete.
|
||||
*
|
||||
* If Promise/AsyncGenerator is returned, a progress toast will be shown
|
||||
* until the operation completes. Generator can yield progress updates.
|
||||
*/
|
||||
onExport?: (
|
||||
/** type of export. Currently we only call for JSON exports or
|
||||
* JSON-embedded PNG (which is also identified as `json` type here)*/
|
||||
type: "json", data: {
|
||||
elements: readonly ExcalidrawElement[];
|
||||
appState: AppState;
|
||||
files: BinaryFiles;
|
||||
}, options: {
|
||||
/** signal that gets aborted if user cancels the export (e.g. closes
|
||||
* the native file picker dialog). In that case, you can either
|
||||
* return immediately, or throw AbortError.
|
||||
*/
|
||||
signal: AbortSignal;
|
||||
}) => MaybePromise<void> | AsyncGenerator<OnExportProgress, void>;
|
||||
}
|
||||
export type SceneData = {
|
||||
elements?: ImportedDataState["elements"];
|
||||
@@ -2776,6 +3014,8 @@ export type AppProps = Merge<ExcalidrawProps, {
|
||||
export type AppClassProperties = {
|
||||
props: AppProps;
|
||||
state: AppState;
|
||||
api: App["api"];
|
||||
sessionExportThemeOverride: App["sessionExportThemeOverride"];
|
||||
interactiveCanvas: HTMLCanvasElement | null;
|
||||
/** static canvas */
|
||||
canvas: HTMLCanvasElement;
|
||||
@@ -2817,8 +3057,11 @@ export type AppClassProperties = {
|
||||
onPointerUpEmitter: App["onPointerUpEmitter"];
|
||||
updateEditorAtom: App["updateEditorAtom"];
|
||||
onPointerDownEmitter: App["onPointerDownEmitter"];
|
||||
onEvent: App["onEvent"];
|
||||
onStateChange: App["onStateChange"];
|
||||
lastPointerMoveCoords: App["lastPointerMoveCoords"];
|
||||
bindModeHandler: App["bindModeHandler"];
|
||||
setAppState: App["setAppState"];
|
||||
};
|
||||
export type PointerDownState = Readonly<{
|
||||
origin: Readonly<{
|
||||
@@ -2879,7 +3122,18 @@ export type PointerDownState = Readonly<{
|
||||
};
|
||||
}>;
|
||||
export type UnsubscribeCallback = () => void;
|
||||
export type ExcalidrawMountPayload = {
|
||||
excalidrawAPI: ExcalidrawImperativeAPI;
|
||||
container: HTMLDivElement | null;
|
||||
};
|
||||
export type ExcalidrawImperativeAPIEventMap = {
|
||||
"editor:mount": [payload: ExcalidrawMountPayload];
|
||||
"editor:initialize": [api: ExcalidrawImperativeAPI];
|
||||
"editor:unmount": [];
|
||||
};
|
||||
export interface ExcalidrawImperativeAPI {
|
||||
/** Whether the editor has been unmounted and the API is no longer usable. */
|
||||
isDestroyed: boolean;
|
||||
updateScene: InstanceType<typeof App>["updateScene"];
|
||||
applyDeltas: InstanceType<typeof App>["applyDeltas"];
|
||||
mutateElement: InstanceType<typeof App>["mutateElement"];
|
||||
@@ -2936,6 +3190,8 @@ export interface ExcalidrawImperativeAPI {
|
||||
onPointerUp: (callback: (activeTool: AppState["activeTool"], pointerDownState: PointerDownState, event: PointerEvent) => void) => UnsubscribeCallback;
|
||||
onScrollChange: (callback: (scrollX: number, scrollY: number, zoom: Zoom) => void) => UnsubscribeCallback;
|
||||
onUserFollow: (callback: (payload: OnUserFollowedPayload) => void) => UnsubscribeCallback;
|
||||
onStateChange: InstanceType<typeof App>["onStateChange"];
|
||||
onEvent: InstanceType<typeof App>["onEvent"];
|
||||
}
|
||||
export type FrameNameBounds = {
|
||||
x: number;
|
||||
@@ -3015,12 +3271,12 @@ export declare const getRectangleBoxAbsoluteCoords: (boxSceneCoords: RectangleBo
|
||||
export declare const getDiamondPoints: (element: ExcalidrawElement) => number[];
|
||||
export declare const getCubicBezierCurveBound: (p0: GlobalPoint, p1: GlobalPoint, p2: GlobalPoint, p3: GlobalPoint) => Bounds;
|
||||
export declare const getMinMaxXYFromCurvePathOps: (ops: Op[], transformXY?: (p: GlobalPoint) => GlobalPoint) => Bounds;
|
||||
export declare const getBoundsFromPoints: (points: ExcalidrawFreeDrawElement["points"]) => Bounds;
|
||||
export declare const getBoundsFromPoints: <P extends GlobalPoint | LocalPoint>(points: readonly P[], padding?: number) => Bounds;
|
||||
/** @returns number in pixels */
|
||||
export declare const getArrowheadSize: (arrowhead: Arrowhead) => number;
|
||||
/** @returns number in degrees */
|
||||
export declare const getArrowheadAngle: (arrowhead: Arrowhead) => Degrees;
|
||||
export declare const getArrowheadPoints: (element: ExcalidrawLinearElement, shape: Drawable[], position: "start" | "end", arrowhead: Arrowhead) => number[] | null;
|
||||
export declare const getArrowheadPoints: (element: ExcalidrawLinearElement, shape: Drawable[], position: "start" | "end", arrowhead: Arrowhead, offsetMultiplier?: number) => number[] | null;
|
||||
export declare const getElementBounds: (element: ExcalidrawElement, elementsMap: ElementsMap, nonRotated?: boolean) => Bounds;
|
||||
export declare const getCommonBounds: (elements: ElementsMapOrArray, elementsMap?: ElementsMap) => Bounds;
|
||||
export declare const getDraggedElementsBounds: (elements: ExcalidrawElement[], dragOffset: {
|
||||
@@ -3054,16 +3310,34 @@ export declare const getCenterForBounds: (bounds: Bounds) => GlobalPoint;
|
||||
*/
|
||||
export declare const aabbForElement: (element: Readonly<ExcalidrawElement>, elementsMap: ElementsMap, offset?: [number, number, number, number]) => Bounds;
|
||||
export declare const pointInsideBounds: <P extends GlobalPoint | LocalPoint>(p: P, bounds: Bounds) => boolean;
|
||||
export declare const pointInsideBoundsInclusive: <P extends GlobalPoint | LocalPoint>(p: P, bounds: Bounds) => boolean;
|
||||
export declare const doBoundsIntersect: (bounds1: Bounds | null, bounds2: Bounds | null) => boolean;
|
||||
export declare const boundsContainBounds: (outerBounds: Bounds, innerBounds: Bounds) => boolean;
|
||||
export declare const elementCenterPoint: (element: ExcalidrawElement, elementsMap: ElementsMap, xOffset?: number, yOffset?: number) => GlobalPoint;
|
||||
|
||||
/* ************************************** */
|
||||
/* node_modules/@zsviczian/excalidraw/types/excalidraw/components/App.d.ts */
|
||||
/* ************************************** */
|
||||
declare const editorLifecycleEventBehavior: {
|
||||
readonly "editor:mount": {
|
||||
readonly cardinality: "once";
|
||||
readonly replay: "last";
|
||||
};
|
||||
readonly "editor:initialize": {
|
||||
readonly cardinality: "once";
|
||||
readonly replay: "last";
|
||||
};
|
||||
readonly "editor:unmount": {
|
||||
readonly cardinality: "once";
|
||||
readonly replay: "last";
|
||||
};
|
||||
};
|
||||
export declare const ExcalidrawContainerContext: React.Context<{
|
||||
container: HTMLDivElement | null;
|
||||
id: string | null;
|
||||
}>;
|
||||
export declare const ExcalidrawAPIContext: React.Context<ExcalidrawImperativeAPI | null>;
|
||||
export declare const ExcalidrawAPISetContext: React.Context<((api: ExcalidrawImperativeAPI | null) => void) | null>;
|
||||
export declare const useApp: () => AppClassProperties;
|
||||
export declare const useAppProps: () => AppProps;
|
||||
export declare const useEditorInterface: () => Readonly<{
|
||||
@@ -3086,9 +3360,14 @@ export declare const useExcalidrawElements: () => readonly NonDeletedExcalidrawE
|
||||
export declare const useExcalidrawAppState: () => AppState;
|
||||
export declare const useExcalidrawSetAppState: () => <K extends keyof AppState>(state: AppState | ((prevState: Readonly<AppState>, props: Readonly<any>) => AppState | Pick<AppState, K> | null) | Pick<AppState, K> | null, callback?: (() => void) | undefined) => void;
|
||||
export declare const useExcalidrawActionManager: () => ActionManager;
|
||||
/**
|
||||
* Requires wrapping your component in <ExcalidrawAPIContext.Provider>
|
||||
*/
|
||||
export declare const useExcalidrawAPI: () => ExcalidrawImperativeAPI | null;
|
||||
declare class App extends React.Component<AppProps, AppState> {
|
||||
canvas: AppClassProperties["canvas"];
|
||||
interactiveCanvas: AppClassProperties["interactiveCanvas"];
|
||||
sessionExportThemeOverride: AppState["theme"] | undefined;
|
||||
rc: RoughCanvas;
|
||||
unmounted: boolean;
|
||||
actionManager: ActionManager;
|
||||
@@ -3123,20 +3402,26 @@ declare class App extends React.Component<AppProps, AppState> {
|
||||
/** embeds that have been inserted to DOM (as a perf optim, we don't want to
|
||||
* insert to DOM before user initially scrolls to them) */
|
||||
private initializedEmbeds;
|
||||
private handleToastClose;
|
||||
private elementsPendingErasure;
|
||||
private _initialized;
|
||||
private readonly editorLifecycleEvents;
|
||||
onEvent: AppEventBus<ExcalidrawImperativeAPIEventMap, typeof editorLifecycleEventBehavior>["on"];
|
||||
private appStateObserver;
|
||||
onStateChange: OnStateChange;
|
||||
flowChartCreator: FlowChartCreator;
|
||||
private flowChartNavigator;
|
||||
bindModeHandler: ReturnType<typeof setTimeout> | null;
|
||||
hitLinkElement?: NonDeletedExcalidrawElement;
|
||||
lastPointerDownEvent: React.PointerEvent<HTMLElement> | null;
|
||||
lastPointerUpEvent: React.PointerEvent<HTMLElement> | PointerEvent | null;
|
||||
lastPointerUpIsDoubleClick: boolean;
|
||||
lastPointerMoveEvent: PointerEvent | null;
|
||||
/** current frame pointer cords */
|
||||
lastPointerMoveCoords: {
|
||||
x: number;
|
||||
y: number;
|
||||
} | null;
|
||||
private lastCompletedCanvasClicks;
|
||||
/** previous frame pointer coords */
|
||||
previousPointerMoveCoords: {
|
||||
x: number;
|
||||
@@ -3282,6 +3567,8 @@ declare class App extends React.Component<AppProps, AppState> {
|
||||
}>]>;
|
||||
missingPointerEventCleanupEmitter: Emitter<[event: PointerEvent | null]>;
|
||||
onRemoveEventListenersEmitter: Emitter<[]>;
|
||||
api: ExcalidrawImperativeAPI;
|
||||
private createExcalidrawAPI;
|
||||
constructor(props: AppProps);
|
||||
updateEditorAtom: <Value, Args extends unknown[], Result>(atom: WritableAtom<Value, Args, Result>, ...args: Args) => Result;
|
||||
private onWindowMessage;
|
||||
@@ -3295,10 +3582,12 @@ declare class App extends React.Component<AppProps, AppState> {
|
||||
* If disabled, returns null.
|
||||
*/
|
||||
getEffectiveGridSize: () => NullableGridSize;
|
||||
private getTextCreationGridPoint;
|
||||
private getHTMLIFrameElement;
|
||||
private handleIframeLikeElementHover;
|
||||
/** @returns true if iframe-like element click handled */
|
||||
private handleIframeLikeCenterClick;
|
||||
private isDoubleClick;
|
||||
private isIframeLikeElementCenter;
|
||||
private updateEmbedValidationStatus;
|
||||
private updateEmbeddables;
|
||||
@@ -3378,6 +3667,7 @@ declare class App extends React.Component<AppProps, AppState> {
|
||||
} | "cursor" | "center";
|
||||
retainSeed?: boolean;
|
||||
fitToContent?: boolean;
|
||||
preserveFrameChildrenOrder?: boolean;
|
||||
}) => void;
|
||||
private addElementsFromMixedContentPaste;
|
||||
private addTextFromPaste;
|
||||
@@ -3437,11 +3727,7 @@ declare class App extends React.Component<AppProps, AppState> {
|
||||
startLineEditor: (el: ExcalidrawLinearElement, selectedPointsIndices?: number[] | null) => void;
|
||||
refreshAllArrows: () => void;
|
||||
updateContainerSize: (containers: NonDeletedExcalidrawElement[]) => void;
|
||||
setToast: (toast: {
|
||||
message: string;
|
||||
closable?: boolean;
|
||||
duration?: number;
|
||||
} | null) => void;
|
||||
setToast: (toast: AppState["toast"]) => void;
|
||||
restoreFileFromShare: () => Promise<void>;
|
||||
/**
|
||||
* adds supplied files to existing files in the appState.
|
||||
@@ -3515,7 +3801,11 @@ declare class App extends React.Component<AppProps, AppState> {
|
||||
private onGestureEnd;
|
||||
private handleTextWysiwyg;
|
||||
private deselectElements;
|
||||
private getSelectedTextElement;
|
||||
private getSelectedTextEditingContainerAtPosition;
|
||||
private getTextElementAtPosition;
|
||||
private isHittingTextAutoResizeHandle;
|
||||
private handleTextAutoResizeHandlePointerDown;
|
||||
private getElementAtPosition;
|
||||
private getElementsAtPosition;
|
||||
getElementHitThreshold(element: ExcalidrawElement): number;
|
||||
@@ -3525,10 +3815,20 @@ declare class App extends React.Component<AppProps, AppState> {
|
||||
private debounceDoubleClickTimestamp;
|
||||
private startImageCropping;
|
||||
private finishImageCropping;
|
||||
private shouldHandleBrowserCanvasDoubleClick;
|
||||
private handleCanvasDoubleClick;
|
||||
private handleCanvasClick;
|
||||
private getElementLinkAtPosition;
|
||||
private handleElementLinkClick;
|
||||
/**
|
||||
* finds candidate frame under cursor (when dragging frame children/elements
|
||||
* inside frames)
|
||||
*/
|
||||
private getTopLayerFrameAtSceneCoords;
|
||||
private updateFrameToHighlight;
|
||||
private maybeUpdateFrameToHighlightOnPointerMove;
|
||||
private insertNewElements;
|
||||
private insertNewElement;
|
||||
private handleCanvasPointerMove;
|
||||
private handleEraser;
|
||||
private handleTouchMove;
|
||||
@@ -3599,13 +3899,12 @@ declare class App extends React.Component<AppProps, AppState> {
|
||||
/** generally you should use `addNewImagesToImageCache()` directly if you need
|
||||
* to render new images. This is just a failsafe */
|
||||
private scheduleImageRefresh;
|
||||
private updateBindingEnabledOnPointerMove;
|
||||
setSelection(elements: readonly NonDeletedExcalidrawElement[]): void;
|
||||
private clearSelection;
|
||||
private handleInteractiveCanvasRef;
|
||||
private insertImages;
|
||||
private handleAppOnDrop;
|
||||
loadFileToCanvas: (file: File, fileHandle: FileSystemHandle | null) => Promise<void>;
|
||||
loadFileToCanvas: (file: File, fileHandle: FileSystemFileHandle | null) => Promise<void>;
|
||||
private handleCanvasContextMenu;
|
||||
private maybeDragNewGenericElement;
|
||||
private maybeHandleCrop;
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
Vendored
+24
-13
@@ -1,12 +1,12 @@
|
||||
import ExcalidrawPlugin from "src/core/main";
|
||||
import { FillStyle, StrokeStyle, ExcalidrawElement, ExcalidrawBindableElement, FileId, NonDeletedExcalidrawElement, ExcalidrawImageElement, StrokeRoundness, RoundnessType } from "@zsviczian/excalidraw/types/element/src/types";
|
||||
import { ColorMap, MimeType } from "./EmbeddedFileLoader";
|
||||
import { Editor, OpenViewState, RequestUrlResponse, TFile, TFolder, WorkspaceLeaf } from "obsidian";
|
||||
import { FillStyle,StrokeStyle,ExcalidrawElement,ExcalidrawBindableElement,FileId,NonDeletedExcalidrawElement,ExcalidrawImageElement,StrokeRoundness,RoundnessType } from "@zsviczian/excalidraw/types/element/src/types";
|
||||
import { ColorMap,MimeType } from "./EmbeddedFileLoader";
|
||||
import { Editor,OpenViewState,RequestUrlResponse,TFile,TFolder,WorkspaceLeaf } from "obsidian";
|
||||
import * as obsidian_module from "obsidian";
|
||||
import ExcalidrawView, { ExportSettings } from "src/view/ExcalidrawView";
|
||||
import { AppState, BinaryFileData, DataURL } from "@zsviczian/excalidraw/types/excalidraw/types";
|
||||
import ExcalidrawView,{ ExportSettings } from "src/view/ExcalidrawView";
|
||||
import { AppState,BinaryFileData,DataURL } from "@zsviczian/excalidraw/types/excalidraw/types";
|
||||
import { EmbeddedFilesLoader } from "./EmbeddedFileLoader";
|
||||
import { ConnectionPoint, DeviceType, Point } from "src/types/types";
|
||||
import { ConnectionPoint,DeviceType,Point } from "src/types/types";
|
||||
import { ColorMaster } from "@zsviczian/colormaster";
|
||||
import { TInput } from "@zsviczian/colormaster/types";
|
||||
import { ClipboardData } from "@zsviczian/excalidraw/types/excalidraw/clipboard";
|
||||
@@ -14,7 +14,18 @@ import { PaneTarget } from "src/utils/modifierkeyHelper";
|
||||
import { Mutable } from "@zsviczian/excalidraw/types/common/src/utility-types";
|
||||
import { EmbeddableMDCustomProps } from "./Dialogs/EmbeddableSettings";
|
||||
import { AIRequest } from "../utils/AIUtils";
|
||||
import { AddImageOptions, ImageInfo, SVGColorInfo } from "src/types/excalidrawAutomateTypes";
|
||||
import { AddImageOptions,ImageInfo,SVGColorInfo } from "src/types/excalidrawAutomateTypes";
|
||||
|
||||
type ExcalidrawCustomDataValue =
|
||||
| string
|
||||
| number
|
||||
| boolean
|
||||
| null
|
||||
| ExcalidrawCustomDataValue[]
|
||||
| { [key: string]: ExcalidrawCustomDataValue };
|
||||
|
||||
type ExcalidrawCustomDataPatch = Partial<Record<string, ExcalidrawCustomDataValue | undefined>>;
|
||||
type ExcalidrawAutomateHelpTarget = ((...args: any[]) => any) | string;
|
||||
/**
|
||||
* ExcalidrawAutomate is a utility class that provides a simplified API to interact with Excalidraw elements and the Excalidraw canvas.
|
||||
* Elements in the Excalidraw Scene are immutable. You should never directly change element properties in the scene object.
|
||||
@@ -93,19 +104,19 @@ export declare class ExcalidrawAutomate {
|
||||
* Add or modify keys in an element's customData while preserving existing keys.
|
||||
* Creates customData={} if it does not exist.
|
||||
* @param {string} id - The element ID in elementsDict to modify.
|
||||
* @param {Partial<Record<string, unknown>>} newData - Object containing key-value pairs to add/update. Set value to undefined to delete a key.
|
||||
* @param {ExcalidrawCustomDataPatch} newData - Object containing key-value pairs to add/update. Set value to undefined to delete a key.
|
||||
* @returns {Mutable<ExcalidrawElement> | undefined} The modified element, or undefined if element does not exist.
|
||||
*/
|
||||
addAppendUpdateCustomData(id: string, newData: Partial<Record<string, unknown>>): ExcalidrawElement;
|
||||
addAppendUpdateCustomData(id: string, newData: ExcalidrawCustomDataPatch): ExcalidrawElement;
|
||||
/**
|
||||
* Displays help information for EA functions and properties intended to be used in Obsidian developer console.
|
||||
* @param {Function | string} target - Function reference or property name as string.
|
||||
* @param {ExcalidrawAutomateHelpTarget} target - Function reference or property name as string.
|
||||
* Usage examples:
|
||||
* - ea.help(ea.functionName)
|
||||
* - ea.help('propertyName')
|
||||
* - ea.help('utils.functionName')
|
||||
*/
|
||||
help(target: Function | string): void;
|
||||
help(target: ExcalidrawAutomateHelpTarget): void;
|
||||
/**
|
||||
* Posts an AI request to the OpenAI API and returns the response.
|
||||
* @param {AIRequest} request - The AI request configuration.
|
||||
@@ -247,7 +258,7 @@ export declare class ExcalidrawAutomate {
|
||||
viewBackgroundColor: string;
|
||||
gridSize: number;
|
||||
};
|
||||
colorPalette: {};
|
||||
colorPalette: object;
|
||||
constructor(plugin: ExcalidrawPlugin, view?: ExcalidrawView);
|
||||
/**
|
||||
* Returns the last recorded pointer position on the Excalidraw canvas.
|
||||
@@ -986,7 +997,7 @@ export declare class ExcalidrawAutomate {
|
||||
* Saves settings in plugin settings, under the activeScript key.
|
||||
* @returns {Object} The script settings.
|
||||
*/
|
||||
getScriptSettings(): {};
|
||||
getScriptSettings(): object;
|
||||
/**
|
||||
* Sets the script settings for the active script.
|
||||
* @param {Object} settings - The script settings to set.
|
||||
|
||||
@@ -171,7 +171,7 @@ Key values include:
|
||||
|
||||
- `ADD`, `ADD_SIBLING_AFTER`, `ADD_SIBLING_BEFORE`,
|
||||
- `ADD_FOLLOW`, `ADD_FOLLOW_FOCUS`, `ADD_FOLLOW_ZOOM`,
|
||||
- `EDIT`, `PIN`, `BOX`, `TOGGLE_BOUNDARY`, `TOGGLE_SUBMAP_ROOT`, `TOGGLE_GROUP`,
|
||||
- `EDIT`, `PIN`, `BOX`, `TOGGLE_EMBED`, `TOGGLE_BOUNDARY`, `TOGGLE_SUBMAP_ROOT`, `TOGGLE_GROUP`,
|
||||
- `FOLD`, `FOLD_L1`, `FOLD_ALL`,
|
||||
- `COPY`, `CUT`, `PASTE`,
|
||||
- `ZOOM`, `FOCUS`,
|
||||
|
||||
+24
-13
@@ -1,12 +1,12 @@
|
||||
import ExcalidrawPlugin from "src/core/main";
|
||||
import { FillStyle, StrokeStyle, ExcalidrawElement, ExcalidrawBindableElement, FileId, NonDeletedExcalidrawElement, ExcalidrawImageElement, StrokeRoundness, RoundnessType } from "@zsviczian/excalidraw/types/element/src/types";
|
||||
import { ColorMap, MimeType } from "./EmbeddedFileLoader";
|
||||
import { Editor, OpenViewState, RequestUrlResponse, TFile, TFolder, WorkspaceLeaf } from "obsidian";
|
||||
import { FillStyle,StrokeStyle,ExcalidrawElement,ExcalidrawBindableElement,FileId,NonDeletedExcalidrawElement,ExcalidrawImageElement,StrokeRoundness,RoundnessType } from "@zsviczian/excalidraw/types/element/src/types";
|
||||
import { ColorMap,MimeType } from "./EmbeddedFileLoader";
|
||||
import { Editor,OpenViewState,RequestUrlResponse,TFile,TFolder,WorkspaceLeaf } from "obsidian";
|
||||
import * as obsidian_module from "obsidian";
|
||||
import ExcalidrawView, { ExportSettings } from "src/view/ExcalidrawView";
|
||||
import { AppState, BinaryFileData, DataURL } from "@zsviczian/excalidraw/types/excalidraw/types";
|
||||
import ExcalidrawView,{ ExportSettings } from "src/view/ExcalidrawView";
|
||||
import { AppState,BinaryFileData,DataURL } from "@zsviczian/excalidraw/types/excalidraw/types";
|
||||
import { EmbeddedFilesLoader } from "./EmbeddedFileLoader";
|
||||
import { ConnectionPoint, DeviceType, Point } from "src/types/types";
|
||||
import { ConnectionPoint,DeviceType,Point } from "src/types/types";
|
||||
import { ColorMaster } from "@zsviczian/colormaster";
|
||||
import { TInput } from "@zsviczian/colormaster/types";
|
||||
import { ClipboardData } from "@zsviczian/excalidraw/types/excalidraw/clipboard";
|
||||
@@ -14,7 +14,18 @@ import { PaneTarget } from "src/utils/modifierkeyHelper";
|
||||
import { Mutable } from "@zsviczian/excalidraw/types/common/src/utility-types";
|
||||
import { EmbeddableMDCustomProps } from "./Dialogs/EmbeddableSettings";
|
||||
import { AIRequest } from "../utils/AIUtils";
|
||||
import { AddImageOptions, ImageInfo, SVGColorInfo } from "src/types/excalidrawAutomateTypes";
|
||||
import { AddImageOptions,ImageInfo,SVGColorInfo } from "src/types/excalidrawAutomateTypes";
|
||||
|
||||
type ExcalidrawCustomDataValue =
|
||||
| string
|
||||
| number
|
||||
| boolean
|
||||
| null
|
||||
| ExcalidrawCustomDataValue[]
|
||||
| { [key: string]: ExcalidrawCustomDataValue };
|
||||
|
||||
type ExcalidrawCustomDataPatch = Partial<Record<string, ExcalidrawCustomDataValue | undefined>>;
|
||||
type ExcalidrawAutomateHelpTarget = ((...args: any[]) => any) | string;
|
||||
/**
|
||||
* ExcalidrawAutomate is a utility class that provides a simplified API to interact with Excalidraw elements and the Excalidraw canvas.
|
||||
* Elements in the Excalidraw Scene are immutable. You should never directly change element properties in the scene object.
|
||||
@@ -93,19 +104,19 @@ export declare class ExcalidrawAutomate {
|
||||
* Add or modify keys in an element's customData while preserving existing keys.
|
||||
* Creates customData={} if it does not exist.
|
||||
* @param {string} id - The element ID in elementsDict to modify.
|
||||
* @param {Partial<Record<string, unknown>>} newData - Object containing key-value pairs to add/update. Set value to undefined to delete a key.
|
||||
* @param {ExcalidrawCustomDataPatch} newData - Object containing key-value pairs to add/update. Set value to undefined to delete a key.
|
||||
* @returns {Mutable<ExcalidrawElement> | undefined} The modified element, or undefined if element does not exist.
|
||||
*/
|
||||
addAppendUpdateCustomData(id: string, newData: Partial<Record<string, unknown>>): ExcalidrawElement;
|
||||
addAppendUpdateCustomData(id: string, newData: ExcalidrawCustomDataPatch): ExcalidrawElement;
|
||||
/**
|
||||
* Displays help information for EA functions and properties intended to be used in Obsidian developer console.
|
||||
* @param {Function | string} target - Function reference or property name as string.
|
||||
* @param {ExcalidrawAutomateHelpTarget} target - Function reference or property name as string.
|
||||
* Usage examples:
|
||||
* - ea.help(ea.functionName)
|
||||
* - ea.help('propertyName')
|
||||
* - ea.help('utils.functionName')
|
||||
*/
|
||||
help(target: Function | string): void;
|
||||
help(target: ExcalidrawAutomateHelpTarget): void;
|
||||
/**
|
||||
* Posts an AI request to the OpenAI API and returns the response.
|
||||
* @param {AIRequest} request - The AI request configuration.
|
||||
@@ -247,7 +258,7 @@ export declare class ExcalidrawAutomate {
|
||||
viewBackgroundColor: string;
|
||||
gridSize: number;
|
||||
};
|
||||
colorPalette: {};
|
||||
colorPalette: object;
|
||||
constructor(plugin: ExcalidrawPlugin, view?: ExcalidrawView);
|
||||
/**
|
||||
* Returns the last recorded pointer position on the Excalidraw canvas.
|
||||
@@ -986,7 +997,7 @@ export declare class ExcalidrawAutomate {
|
||||
* Saves settings in plugin settings, under the activeScript key.
|
||||
* @returns {Object} The script settings.
|
||||
*/
|
||||
getScriptSettings(): {};
|
||||
getScriptSettings(): object;
|
||||
/**
|
||||
* Sets the script settings for the active script.
|
||||
* @param {Object} settings - The script settings to set.
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
+2467
-341
File diff suppressed because it is too large.
Load diff
+633
-123
File diff suppressed because it is too large.
Load diff
+573
-453
File diff suppressed because it is too large.
Load diff
@@ -20,12 +20,37 @@ if(!ea.verifyMinimumPluginVersion || !ea.verifyMinimumPluginVersion("2.14.2")) {
|
||||
return;
|
||||
}
|
||||
|
||||
function requestFullscreen() {
|
||||
const el = ea.targetView.ownerDocument.body;
|
||||
if (el.requestFullscreen) {
|
||||
el.requestFullscreen();
|
||||
} else if (el.webkitRequestFullscreen) {
|
||||
el.webkitRequestFullscreen();
|
||||
}
|
||||
ea.targetView.gotoFullscreen();
|
||||
}
|
||||
|
||||
function exitFullscreen() {
|
||||
const doc = ea.targetView.ownerDocument;
|
||||
if (doc.exitFullscreen) {
|
||||
doc.exitFullscreen();
|
||||
} else if (doc.webkitExitFullscreen) {
|
||||
doc.webkitExitFullscreen();
|
||||
}
|
||||
ea.targetView.exitFullscreen();
|
||||
}
|
||||
|
||||
async function run() {
|
||||
if(window.excalidrawPalmGuard) {
|
||||
window.excalidrawPalmGuard()
|
||||
return;
|
||||
}
|
||||
const modal = new ea.FloatingModal(ea.plugin.app);
|
||||
if (modal.bgEl) {
|
||||
modal.containerEl.removeChild(modal.bgEl);
|
||||
}
|
||||
modal.modalEl.style.borderRadius = "6px";
|
||||
modal.contentEl.style.padding = "4px";
|
||||
const FULLSCREEN = "Goto fullscreen?";
|
||||
let settings = ea.getScriptSettings() || {};
|
||||
if(!settings[FULLSCREEN]) {
|
||||
@@ -94,7 +119,9 @@ async function run() {
|
||||
};
|
||||
|
||||
// Enter fullscreen view mode
|
||||
if(enableFullscreen) ea.targetView.gotoFullscreen();
|
||||
if(enableFullscreen) {
|
||||
requestFullscreen ();
|
||||
}
|
||||
setTimeout(()=>toggleUIVisibility(true),100);
|
||||
|
||||
// Create floating toolbar modal
|
||||
@@ -193,7 +220,9 @@ async function run() {
|
||||
toggleUIVisibility(false);
|
||||
|
||||
// Exit fullscreen
|
||||
if(ea.targetView && enableFullscreen) ea.targetView.exitFullscreen();
|
||||
if(ea.targetView && enableFullscreen) {
|
||||
exitFullscreen();
|
||||
}
|
||||
clearInterval(autocloseTimer);
|
||||
delete window.excalidrawPalmGuard;
|
||||
};
|
||||
@@ -212,4 +241,4 @@ async function run() {
|
||||
}, 100);
|
||||
}
|
||||
|
||||
run();
|
||||
run();
|
||||
+642
-354
File diff suppressed because it is too large.
Load diff
@@ -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":1767536720161},{"fname":"Scribble Helper.svg","mtime":1645944722000},{"fname":"Select Elements of Type.md","mtime":1643464321000},{"fname":"Select Elements of Type.svg","mtime":1645960639000},{"fname":"Set Dimensions.md","mtime":1645305706000},{"fname":"Set Dimensions.svg","mtime":1645944722000},{"fname":"Set Font Family.md","mtime":1645305706000},{"fname":"Set Font Family.svg","mtime":1645944722000},{"fname":"Set Grid.md","mtime":1693725826368},{"fname":"Set Grid.svg","mtime":1645960639000},{"fname":"Set Link Alias.md","mtime":1645305706000},{"fname":"Set Link Alias.svg","mtime":1645960639000},{"fname":"Set Stroke Width of Selected Elements.md","mtime":1748189277Line truncated
|
||||
[{"fname":"Mindmap connector.md","mtime":1658686599427},{"fname":"Mindmap connector.svg","mtime":1658686599427},{"fname":"Add Connector Point.md","mtime":1735420748564},{"fname":"Add Connector Point.svg","mtime":1645944722000},{"fname":"Add Link to Existing File and Open.md","mtime":1647807918345},{"fname":"Add Link to Existing File and Open.svg","mtime":1645964261000},{"fname":"Add Link to New Page and Open.md","mtime":1654168862138},{"fname":"Add Link to New Page and Open.svg","mtime":1645960639000},{"fname":"Add Next Step in Process.md","mtime":1688304760357},{"fname":"Add Next Step in Process.svg","mtime":1645960639000},{"fname":"Box Each Selected Groups.md","mtime":1645305706000},{"fname":"Box Each Selected Groups.svg","mtime":1645967510000},{"fname":"Box Selected Elements.md","mtime":1645305706000},{"fname":"Box Selected Elements.svg","mtime":1645960639000},{"fname":"Change shape of selected elements.md","mtime":1652701169236},{"fname":"Change shape of selected elements.svg","mtime":1645960775000},{"fname":"Connect elements.md","mtime":1645305706000},{"fname":"Connect elements.svg","mtime":1645960639000},{"fname":"Convert freedraw to line.md","mtime":1645305706000},{"fname":"Convert freedraw to line.svg","mtime":1645960639000},{"fname":"Convert selected text elements to sticky notes.md","mtime":1670169501383},{"fname":"Convert selected text elements to sticky notes.svg","mtime":1645960639000},{"fname":"Convert text to link with folder and alias.md","mtime":1641639819000},{"fname":"Convert text to link with folder and alias.svg","mtime":1645960639000},{"fname":"Copy Selected Element Styles to Global.md","mtime":1642232088000},{"fname":"Copy Selected Element Styles to Global.svg","mtime":1645960639000},{"fname":"Create new markdown file and embed into active drawing.md","mtime":1640866935000},{"fname":"Create new markdown file and embed into active drawing.svg","mtime":1645960639000},{"fname":"Darken background color.md","mtime":1663059051059},{"fname":"Darken background color.svg","mtime":1645960639000},{"fname":"Elbow connectors.md","mtime":1671126911490},{"fname":"Elbow connectors.svg","mtime":1645960639000},{"fname":"Expand rectangles horizontally keep text centered.md","mtime":1646563692000},{"fname":"Expand rectangles horizontally keep text centered.svg","mtime":1645967510000},{"fname":"Expand rectangles horizontally.md","mtime":1644950235000},{"fname":"Expand rectangles horizontally.svg","mtime":1645967510000},{"fname":"Expand rectangles vertically keep text centered.md","mtime":1646563692000},{"fname":"Expand rectangles vertically keep text centered.svg","mtime":1645967510000},{"fname":"Expand rectangles vertically.md","mtime":1658686599427},{"fname":"Expand rectangles vertically.svg","mtime":1645967510000},{"fname":"Fixed horizontal distance between centers.md","mtime":1646743234000},{"fname":"Fixed horizontal distance between centers.svg","mtime":1645960639000},{"fname":"Fixed inner distance.md","mtime":1646743234000},{"fname":"Fixed inner distance.svg","mtime":1645960639000},{"fname":"Fixed spacing.md","mtime":1646743234000},{"fname":"Fixed spacing.svg","mtime":1645967510000},{"fname":"Fixed vertical distance between centers.md","mtime":1646743234000},{"fname":"Fixed vertical distance between centers.svg","mtime":1645967510000},{"fname":"Fixed vertical distance.md","mtime":1646743234000},{"fname":"Fixed vertical distance.svg","mtime":1645967510000},{"fname":"Lighten background color.md","mtime":1663059051059},{"fname":"Lighten background color.svg","mtime":1645959546000},{"fname":"Modify background color opacity.md","mtime":1644924415000},{"fname":"Modify background color opacity.svg","mtime":1645944722000},{"fname":"Normalize Selected Arrows.md","mtime":1670403743278},{"fname":"Normalize Selected Arrows.svg","mtime":1645960639000},{"fname":"Organic Line.md","mtime":1672920172531},{"fname":"Organic Line.svg","mtime":1645964261000},{"fname":"Organic Line Legacy.md","mtime":1690607372668},{"fname":"Organic Line Legacy.svg","mtime":1690607372668},{"fname":"README.md","mtime":1645175700000},{"fname":"Repeat Elements.md","mtime":1663059051059},{"fname":"Repeat Elements.svg","mtime":1645960639000},{"fname":"Reverse arrows.md","mtime":1645305706000},{"fname":"Reverse arrows.svg","mtime":1645960639000},{"fname":"Scribble Helper.md","mtime":1767536720161},{"fname":"Scribble Helper.svg","mtime":1645944722000},{"fname":"Select Elements of Type.md","mtime":1643464321000},{"fname":"Select Elements of Type.svg","mtime":1645960639000},{"fname":"Set Dimensions.md","mtime":1645305706000},{"fname":"Set Dimensions.svg","mtime":1645944722000},{"fname":"Set Font Family.md","mtime":1645305706000},{"fname":"Set Font Family.svg","mtime":1645944722000},{"fname":"Set Grid.md","mtime":1693725826368},{"fname":"Set Grid.svg","mtime":1645960639000},{"fname":"Set Link Alias.md","mtime":1645305706000},{"fname":"Set Link Alias.svg","mtime":1645960639000},{"fname":"Set Stroke Width of Selected Elements.md","mtime":1748189277Line truncated
|
||||
+21
-4
@@ -1,6 +1,14 @@
|
||||
If you are enjoying the Excalidraw plugin then please support my work and enthusiasm by buying me a coffee on [https://ko-fi/zsolt](https://ko-fi.com/zsolt).
|
||||
<div style="text-align:center;margin-bottom:20px;">
|
||||
<a href="https://community.sketch-your-mind.com/em" target="_blank"><img src="https://sketch-your-mind.com/images/logo-EM.png" style="width:50%; max-width: 200px;"></a>
|
||||
</div>
|
||||
|
||||
[<img src="https://user-images.githubusercontent.com/14358394/115450238-f39e8100-a21b-11eb-89d0-fa4b82cdbce8.png" class="coffee">](https://ko-fi.com/zsolt)
|
||||
**It looks like you want to get more out of Excalidraw!**
|
||||
|
||||
Scripts are a true superpower in Excalidraw. If you are ready to eliminate tool friction and build heavy-duty workflows, join[Excalidraw Mastery](https://community.sketch-your-mind.com/em). Master Excalidraw and Visual PKM alongside a supportive community of fellow visual thinkers in the [Sketch Your Mind Community](https://community.sketch-your-mind.com)!
|
||||
|
||||
---
|
||||
|
||||
If you are enjoying the Excalidraw plugin then please support my work and enthusiasm by buying me a coffee on [https://ko-fi/zsolt](https://ko-fi.com/zsolt). [<img src="https://user-images.githubusercontent.com/14358394/115450238-f39e8100-a21b-11eb-89d0-fa4b82cdbce8.png" class="coffee">](https://ko-fi.com/zsolt)
|
||||
|
||||
---
|
||||
|
||||
@@ -13,6 +21,16 @@ Script Engine scripts are installed in the `Downloaded` subfolder of the `Excali
|
||||
|
||||
In the `Command Palette` installed scripts are prefixed with `Downloaded/`, thus you can always know if you are executing a local script of your own, or one that you have downloaded from GitHub.
|
||||
|
||||
## Create Your Own Scripts with AI Superpowers
|
||||
|
||||
You don't need to know how to code to build custom scripts! In this video, I show how to create powerful, custom Excalidraw scripts from scratch using the power of AI.
|
||||
|
||||
Follow along as I generate a complete Layer Manager script for Excalidraw in Obsidian, allowing you to hide, show, lock, and manage elements on different layers. I'll walk you through the entire process, from using a custom training library for Excalidraw Automate to prompting Google's Gemini AI Studio to write the code for us. Discover how to unlock a true superpower for your Obsidian and Excalidraw workflow by generating any script you can imagine.
|
||||
|
||||
<div class="excalidraw-videoWrapper">
|
||||
<a href="https://youtu.be/6BjhUyfS4iM" target="_blank"><img src="https://i.ytimg.com/vi/6BjhUyfS4iM/maxresdefault.jpg" style="width:560px;"></a>
|
||||
</div>
|
||||
|
||||
## Attention developers and hobby hackers
|
||||
<img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/hobby-programmer.svg' align='left' style='background-color:whitesmoke; width:80px; margin-right:15px; margin-bottom:10px;'/>
|
||||
If you want to modify scripts, I recommend moving them to the `Excalidraw Automate script folder` or a different subfolder under the script folder. Scripts in the `Downloaded` folder will be overwritten when you click the `Update this script` button. Note also, that at this time, I do not check if the script file has been updated on GitHub, thus the `Update this script` button is always visible once you have installed a script, not only when an update is available (hope to build this feature in the future).
|
||||
@@ -20,8 +38,7 @@ If you want to modify scripts, I recommend moving them to the `Excalidraw Automa
|
||||
I would love to include your contribution in the script library. If you have a script of your own that you would like to share with the community, please open a [PR](https://github.com/zsviczian/obsidian-excalidraw-plugin/pulls) on GitHub. Be sure to include the following in your pull request
|
||||
- The [script file](https://github.com/zsviczian/obsidian-excalidraw-plugin/tree/master/ea-scripts) with a self explanetory name. The name of the file will be the name of the script in the Command Palette.
|
||||
- An [image](https://github.com/zsviczian/obsidian-excalidraw-plugin/tree/master/images) explaining the scripts purpose. Remember a picture speaks thousand words!
|
||||
- An update to this file [ea-scripts/index-new.md](https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/ea-scripts/index-new.md)
|
||||
|
||||
- An update to this file[ea-scripts/index-new.md](https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/ea-scripts/index-new.md)
|
||||
---
|
||||
|
||||
# List of available scripts
|
||||
|
||||
+4214
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,119 @@
|
||||
const { FlatCompat } = require("@eslint/eslintrc");
|
||||
|
||||
const compat = new FlatCompat({
|
||||
baseDirectory: __dirname,
|
||||
});
|
||||
|
||||
const legacyConfig = require("./.eslintrc.json");
|
||||
|
||||
module.exports = (async () => {
|
||||
const { default: obsidianmd } = await import("eslint-plugin-obsidianmd");
|
||||
const tsRulesOffForJs = Object.fromEntries(
|
||||
[
|
||||
"@typescript-eslint/await-thenable",
|
||||
"@typescript-eslint/ban-ts-comment",
|
||||
"@typescript-eslint/no-array-constructor",
|
||||
"@typescript-eslint/no-array-delete",
|
||||
"@typescript-eslint/no-base-to-string",
|
||||
"@typescript-eslint/no-deprecated",
|
||||
"@typescript-eslint/no-duplicate-enum-values",
|
||||
"@typescript-eslint/no-duplicate-type-constituents",
|
||||
"@typescript-eslint/no-empty-object-type",
|
||||
"@typescript-eslint/no-explicit-any",
|
||||
"@typescript-eslint/no-extra-non-null-assertion",
|
||||
"@typescript-eslint/no-floating-promises",
|
||||
"@typescript-eslint/no-for-in-array",
|
||||
"@typescript-eslint/no-implied-eval",
|
||||
"@typescript-eslint/no-misused-new",
|
||||
"@typescript-eslint/no-misused-promises",
|
||||
"@typescript-eslint/no-namespace",
|
||||
"@typescript-eslint/no-non-null-asserted-optional-chain",
|
||||
"@typescript-eslint/no-redundant-type-constituents",
|
||||
"@typescript-eslint/no-require-imports",
|
||||
"@typescript-eslint/no-this-alias",
|
||||
"@typescript-eslint/no-unnecessary-type-assertion",
|
||||
"@typescript-eslint/no-unnecessary-type-constraint",
|
||||
"@typescript-eslint/no-unsafe-argument",
|
||||
"@typescript-eslint/no-unsafe-assignment",
|
||||
"@typescript-eslint/no-unsafe-call",
|
||||
"@typescript-eslint/no-unsafe-declaration-merging",
|
||||
"@typescript-eslint/no-unsafe-enum-comparison",
|
||||
"@typescript-eslint/no-unsafe-function-type",
|
||||
"@typescript-eslint/no-unsafe-member-access",
|
||||
"@typescript-eslint/no-unsafe-return",
|
||||
"@typescript-eslint/no-unsafe-unary-minus",
|
||||
"@typescript-eslint/no-unused-expressions",
|
||||
"@typescript-eslint/no-unused-vars",
|
||||
"@typescript-eslint/no-wrapper-object-types",
|
||||
"@typescript-eslint/only-throw-error",
|
||||
"@typescript-eslint/prefer-as-const",
|
||||
"@typescript-eslint/prefer-namespace-keyword",
|
||||
"@typescript-eslint/prefer-promise-reject-errors",
|
||||
"@typescript-eslint/require-await",
|
||||
"@typescript-eslint/restrict-plus-operands",
|
||||
"@typescript-eslint/restrict-template-expressions",
|
||||
"@typescript-eslint/triple-slash-reference",
|
||||
"@typescript-eslint/unbound-method",
|
||||
].map((rule) => [rule, "off"]),
|
||||
);
|
||||
const obsidianTypedRulesOffForJs = {
|
||||
"obsidianmd/no-plugin-as-component": "off",
|
||||
"obsidianmd/no-view-references-in-plugin": "off",
|
||||
"obsidianmd/no-unsupported-api": "off",
|
||||
"obsidianmd/prefer-file-manager-trash-file": "off",
|
||||
"obsidianmd/prefer-instanceof": "off",
|
||||
};
|
||||
|
||||
return [
|
||||
{
|
||||
ignores: [
|
||||
"lib/**",
|
||||
"dist/**",
|
||||
"node_modules/**",
|
||||
".github/**",
|
||||
"MathjaxToSVG/**",
|
||||
"docs/**",
|
||||
"ea-scripts/**",
|
||||
"images/**",
|
||||
"test-data/**",
|
||||
],
|
||||
},
|
||||
...compat.config(legacyConfig),
|
||||
...obsidianmd.configs.recommended,
|
||||
{
|
||||
files: ["**/*.{js,jsx}"],
|
||||
rules: {
|
||||
...tsRulesOffForJs,
|
||||
...obsidianTypedRulesOffForJs,
|
||||
},
|
||||
},
|
||||
{
|
||||
files: ["**/*.{ts,tsx}"],
|
||||
languageOptions: {
|
||||
parser: require("@typescript-eslint/parser"),
|
||||
parserOptions: {
|
||||
project: "./tsconfig.json",
|
||||
tsconfigRootDir: __dirname,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
files: ["**/*.{ts,tsx,js,jsx}"],
|
||||
rules: {
|
||||
"no-unused-vars": "off",
|
||||
"@typescript-eslint/no-unused-vars": [
|
||||
"error",
|
||||
{
|
||||
args: "after-used",
|
||||
argsIgnorePattern: "^_",
|
||||
varsIgnorePattern: "^_",
|
||||
ignoreRestSiblings: true,
|
||||
caughtErrors: "all",
|
||||
caughtErrorsIgnorePattern: "^_",
|
||||
},
|
||||
],
|
||||
"no-useless-escape": "error",
|
||||
},
|
||||
},
|
||||
];
|
||||
})();
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 1.6 MiB |
Binary file not shown.
|
After Width: | Height: | Size: 46 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 24 KiB |
+3
-3
@@ -1,9 +1,9 @@
|
||||
{
|
||||
"id": "obsidian-excalidraw-plugin",
|
||||
"name": "Excalidraw",
|
||||
"version": "2.20.6",
|
||||
"minAppVersion": "1.5.7",
|
||||
"description": "Sketch Your Mind. An Obsidian plugin to edit and view Excalidraw drawings. Enter the world of 4D Visual PKM.",
|
||||
"version": "2.23.0",
|
||||
"minAppVersion": "1.5.7",
|
||||
"description": "Sketch Your Mind. Edit and view Excalidraw drawings. Enter the world of 4D Visual PKM.",
|
||||
"author": "Zsolt Viczian",
|
||||
"authorUrl": "https://excalidraw-obsidian.online",
|
||||
"isDesktopOnly": false
|
||||
|
||||
+2
-2
@@ -1,9 +1,9 @@
|
||||
{
|
||||
"id": "obsidian-excalidraw-plugin",
|
||||
"name": "Excalidraw",
|
||||
"version": "2.20.6",
|
||||
"version": "2.23.0",
|
||||
"minAppVersion": "1.5.7",
|
||||
"description": "Sketch Your Mind. An Obsidian plugin to edit and view Excalidraw drawings. Enter the world of 4D Visual PKM.",
|
||||
"description": "Sketch Your Mind. 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",
|
||||
|
||||
Generated
+4324
-8478
File diff suppressed because it is too large.
Load diff
+32
-28
@@ -8,10 +8,16 @@
|
||||
"lib/**/*"
|
||||
],
|
||||
"scripts": {
|
||||
"dev": "cross-env NODE_ENV=development rollup --config rollup.config.js",
|
||||
"build": "cross-env NODE_ENV=production rollup --config rollup.config.js",
|
||||
"lib": "cross-env NODE_ENV=lib rollup --config rollup.config.js",
|
||||
"predev": "node scripts/build-mathjax.mjs",
|
||||
"dev": "cross-env NODE_ENV=development rollup --config rollup.config.mjs",
|
||||
"prebuild": "node scripts/build-mathjax.mjs",
|
||||
"build": "cross-env NODE_ENV=production rollup --config rollup.config.mjs",
|
||||
"prelib": "node scripts/build-mathjax.mjs",
|
||||
"lib": "cross-env NODE_ENV=lib rollup --config rollup.config.mjs",
|
||||
"code": "eslint --max-warnings=0 --ext .ts,.tsx ./src",
|
||||
"code:fix": "eslint --max-warnings=0 --ext .ts,.tsx ./src --fix",
|
||||
"code:unused": "eslint --max-warnings=0 --ext .ts,.tsx ./src --quiet --format json | node -e \"let d='';process.stdin.on('data',c=>d+=c).on('end',()=>{const r=JSON.parse(d);for(const f of r){for(const m of f.messages||[]){if(m.ruleId==='@typescript-eslint/no-unused-vars'||m.ruleId==='no-unused-vars'){console.log(f.filePath+':'+m.line+':'+m.column+' '+m.ruleId+' '+m.message);}}}})\"",
|
||||
"code:escape": "eslint --max-warnings=0 --ext .ts,.tsx ./src --quiet --format json | node -e \"let d='';process.stdin.on('data',c=>d+=c).on('end',()=>{const r=JSON.parse(d);for(const f of r){for(const m of f.messages||[]){if(m.ruleId==='no-useless-escape'){console.log(f.filePath+':'+m.line+':'+m.column+' '+m.ruleId+' '+m.message);}}}})\"",
|
||||
"madge": "madge --circular .",
|
||||
"build:mathjax": "cd MathjaxToSVG && npm run build",
|
||||
"build:all": "npm run build:mathjax && npm run build",
|
||||
@@ -25,12 +31,12 @@
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@popperjs/core": "^2.11.8",
|
||||
"@zsviczian/excalidraw": "0.18.0-84",
|
||||
"@zsviczian/colormaster": "^1.2.2",
|
||||
"@zsviczian/excalidraw": "0.18.0-91",
|
||||
"chroma-js": "^3.1.2",
|
||||
"clsx": "^2.0.0",
|
||||
"@zsviczian/colormaster": "^1.2.2",
|
||||
"es6-promise-pool": "2.5.0",
|
||||
"gl-matrix": "^3.4.3",
|
||||
"js-yaml": "^4.1.0",
|
||||
"mathjax-full": "^3.2.2",
|
||||
"monkey-around": "^2.3.0",
|
||||
"nanoid": "^4.0.2",
|
||||
@@ -40,51 +46,49 @@
|
||||
"react-dom": "^18.2.0",
|
||||
"roughjs": "^4.5.2",
|
||||
"woff2sfnt-sfnt2woff": "^1.0.0",
|
||||
"es6-promise-pool": "2.5.0"
|
||||
"yaml": "^2.9.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"jsesc": "^3.0.2",
|
||||
"@babel/core": "^7.22.9",
|
||||
"@babel/preset-env": "^7.22.10",
|
||||
"@babel/preset-react": "^7.22.5",
|
||||
"@codemirror/commands": "^6.3.3",
|
||||
"@codemirror/language": "^6.10.0",
|
||||
"@codemirror/search": "^6.5.5",
|
||||
"@codemirror/state": "^6.4.0",
|
||||
"@codemirror/view": "^6.23.0",
|
||||
"@codemirror/commands": "6.8.1",
|
||||
"@codemirror/language": "6.11.0",
|
||||
"@codemirror/search": "6.5.11",
|
||||
"@codemirror/state": "6.5.0",
|
||||
"@codemirror/view": "6.38.6",
|
||||
"@eslint/eslintrc": "^3.1.0",
|
||||
"@excalidraw/eslint-config": "^1.0.3",
|
||||
"@excalidraw/prettier-config": "^1.0.2",
|
||||
"@rollup/plugin-babel": "^6.0.3",
|
||||
"@rollup/plugin-commonjs": "^26.0.1",
|
||||
"@rollup/plugin-json": "^6.1.0",
|
||||
"@rollup/plugin-node-resolve": "^15.2.3",
|
||||
"@rollup/plugin-replace": "^5.0.2",
|
||||
"@rollup/plugin-terser": "^0.4.4",
|
||||
"@rollup/plugin-typescript": "^12.1.2",
|
||||
"@rollup/plugin-json": "^6.1.0",
|
||||
"@types/chroma-js": "^3.1.1",
|
||||
"@types/js-beautify": "^1.14.0",
|
||||
"@types/js-yaml": "^4.0.9",
|
||||
"@types/node": "^20.10.5",
|
||||
"@types/node": "^22.19.19",
|
||||
"@types/opentype.js": "^1.3.8",
|
||||
"@types/react": "^18.2.45",
|
||||
"@types/react-dom": "^18.2.18",
|
||||
"@zerollup/ts-transform-paths": "^1.7.18",
|
||||
"@zsviczian/rollup-plugin-postprocess": "^1.0.3",
|
||||
"cross-env": "^7.0.3",
|
||||
"cssnano": "^6.0.2",
|
||||
"dotenv": "^16.4.5",
|
||||
"eslint": "^9.27.0",
|
||||
"eslint-config-prettier": "^9.0.0",
|
||||
"eslint-plugin-obsidianmd": "^0.3.0",
|
||||
"eslint-plugin-prettier": "^5.0.0",
|
||||
"jsesc": "^3.0.2",
|
||||
"lz-string": "^1.5.0",
|
||||
"obsidian": "^1.10.0",
|
||||
"obsidian": "1.12.3",
|
||||
"postcss": "^8.4.31",
|
||||
"prettier": "^3.0.1",
|
||||
"rollup": "^2.70.1",
|
||||
"rollup": "^4.14.0",
|
||||
"rollup-plugin-copy": "^3.5.0",
|
||||
"@zsviczian/rollup-plugin-postprocess": "^1.0.3",
|
||||
"rollup-plugin-terser": "^7.0.2",
|
||||
"rollup-plugin-typescript2": "^0.36.0",
|
||||
"tslib": "^2.8.1",
|
||||
"ttypescript": "^1.5.15",
|
||||
"typescript": "^5.7.3",
|
||||
"fs-extra": "^11.2.0",
|
||||
"typescript": "5.9.3",
|
||||
"uglify-js": "^3.19.3"
|
||||
},
|
||||
"resolutions": {
|
||||
@@ -92,7 +96,7 @@
|
||||
},
|
||||
"prettier": "@excalidraw/prettier-config",
|
||||
"engines": {
|
||||
"node": ">=20.0.0",
|
||||
"node": ">=22.0.0",
|
||||
"npm": ">=10.0.0"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
Uses .github/workflows/release.yml
|
||||
1) add release id to manifest.json and/or manifest-beta.json
|
||||
2.23.0, or 2.23.0-beta-x
|
||||
2) add, commit, push
|
||||
git add .
|
||||
git commit -m "..."
|
||||
git push origin master
|
||||
3) Tag and trigger release
|
||||
git tag 2.23.0-beta-x
|
||||
git push origin 2.23.0-beta-x
|
||||
@@ -1,228 +1,332 @@
|
||||
import { nodeResolve } from '@rollup/plugin-node-resolve';
|
||||
import commonjs from '@rollup/plugin-commonjs';
|
||||
import replace from "@rollup/plugin-replace";
|
||||
import { terser } from "rollup-plugin-terser";
|
||||
import copy from "rollup-plugin-copy";
|
||||
import typescript2 from "rollup-plugin-typescript2";
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
import LZString from 'lz-string';
|
||||
import postprocess from '@zsviczian/rollup-plugin-postprocess';
|
||||
import cssnano from 'cssnano';
|
||||
import jsesc from 'jsesc';
|
||||
import { minify } from 'uglify-js';
|
||||
import json from '@rollup/plugin-json';
|
||||
|
||||
// Load environment variables
|
||||
import dotenv from 'dotenv';
|
||||
dotenv.config();
|
||||
|
||||
const DIST_FOLDER = 'dist';
|
||||
const absolutePath = path.resolve(DIST_FOLDER);
|
||||
fs.mkdirSync(absolutePath, { recursive: true });
|
||||
const isProd = (process.env.NODE_ENV === "production");
|
||||
const isLib = (process.env.NODE_ENV === "lib");
|
||||
console.log(`Running: ${process.env.NODE_ENV}; isProd: ${isProd}; isLib: ${isLib}`);
|
||||
|
||||
|
||||
// Excalidraw React 19 compatiblity shim
|
||||
// Create JSX runtime compatibility layer
|
||||
const jsxRuntimeShim = `
|
||||
const jsx = (type, props, key) => {
|
||||
return React.createElement(type, props);
|
||||
};
|
||||
const jsxs = (type, props, key) => {
|
||||
return React.createElement(type, props);
|
||||
};
|
||||
const Fragment = React.Fragment;
|
||||
React.jsx = jsx;
|
||||
React.jsxs = jsxs;
|
||||
React.Fragment = Fragment;
|
||||
React.jsxRuntime = { jsx, jsxs, Fragment };
|
||||
window.__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__ = { jsx, jsxs, Fragment };
|
||||
window.__WEBPACK_EXTERNAL_MODULE_react_jsx_dev_runtime__ = { jsx, jsxs, Fragment, jsxDEV: jsx };
|
||||
window['react/jsx-runtime'] = { jsx, jsxs, Fragment };
|
||||
window['react/jsx-dev-runtime'] = { jsx, jsxs, Fragment, jsxDEV: jsx };
|
||||
`;
|
||||
|
||||
|
||||
|
||||
const mathjaxtosvg_pkg = isLib ? "" : fs.readFileSync("./MathjaxToSVG/dist/index.js", "utf8");
|
||||
|
||||
const LANGUAGES = ['ru', 'zh-cn', 'zh-tw', 'es']; //english is not compressed as it is always loaded by default
|
||||
|
||||
function trimLastSemicolon(input) {
|
||||
if (input.endsWith(";")) {
|
||||
return input.slice(0, -1);
|
||||
}
|
||||
return input;
|
||||
}
|
||||
|
||||
function minifyCode(code) {
|
||||
const minified = minify(code, {
|
||||
compress: {
|
||||
//https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2170
|
||||
reduce_vars: false,
|
||||
},
|
||||
mangle: true,
|
||||
output: {
|
||||
comments: false,
|
||||
beautify: false,
|
||||
}
|
||||
});
|
||||
|
||||
if (minified.error) {
|
||||
throw new Error(minified.error);
|
||||
}
|
||||
return minified.code;
|
||||
}
|
||||
|
||||
function compressLanguageFile(lang) {
|
||||
const inputDir = "./src/lang/locale";
|
||||
const filePath = `${inputDir}/${lang}.ts`;
|
||||
let content = fs.readFileSync(filePath, "utf-8");
|
||||
content = trimLastSemicolon(content.split("export default")[1].trim());
|
||||
return LZString.compressToBase64(minifyCode(`x = ${content};`));
|
||||
}
|
||||
|
||||
const excalidraw_pkg = isLib ? "" : minifyCode(isProd
|
||||
? fs.readFileSync("./node_modules/@zsviczian/excalidraw/dist/excalidraw.production.min.js", "utf8")
|
||||
: fs.readFileSync("./node_modules/@zsviczian/excalidraw/dist/excalidraw.development.js", "utf8"));
|
||||
const react_pkg = isLib ? "" : minifyCode(isProd
|
||||
? fs.readFileSync("./node_modules/react/umd/react.production.min.js", "utf8")
|
||||
: fs.readFileSync("./node_modules/react/umd/react.development.js", "utf8"));
|
||||
const reactdom_pkg = isLib ? "" : minifyCode(isProd
|
||||
? fs.readFileSync("./node_modules/react-dom/umd/react-dom.production.min.js", "utf8")
|
||||
: fs.readFileSync("./node_modules/react-dom/umd/react-dom.development.js", "utf8"));
|
||||
|
||||
const lzstring_pkg = isLib ? "" : fs.readFileSync("./node_modules/lz-string/libs/lz-string.min.js", "utf8");
|
||||
if (!isLib) {
|
||||
const excalidraw_styles = isProd
|
||||
? fs.readFileSync("./node_modules/@zsviczian/excalidraw/dist/styles.production.css", "utf8")
|
||||
: fs.readFileSync("./node_modules/@zsviczian/excalidraw/dist/styles.development.css", "utf8");
|
||||
const plugin_styles = fs.readFileSync("./styles.css", "utf8");
|
||||
const styles = excalidraw_styles + plugin_styles;
|
||||
cssnano()
|
||||
.process(styles) // Process the CSS
|
||||
.then(result => {
|
||||
fs.writeFileSync(`./${DIST_FOLDER}/styles.css`, result.css);
|
||||
})
|
||||
.catch(error => {
|
||||
console.error('Error while processing CSS:', error);
|
||||
});
|
||||
}
|
||||
|
||||
const manifestStr = isLib ? "" : fs.readFileSync("manifest.json", "utf-8");
|
||||
const manifest = isLib ? {} : JSON.parse(manifestStr);
|
||||
if (!isLib) {
|
||||
console.log(manifest.version);
|
||||
}
|
||||
|
||||
const packageString = isLib
|
||||
? ""
|
||||
: ';const INITIAL_TIMESTAMP=Date.now();' + lzstring_pkg +
|
||||
'\nlet REACT_PACKAGES = `' +
|
||||
jsesc(react_pkg + reactdom_pkg + jsxRuntimeShim, { quotes: 'backtick' }) +
|
||||
'`;\n' +
|
||||
'const unpackExcalidraw = () => LZString.decompressFromBase64("' + LZString.compressToBase64(excalidraw_pkg) + '");\n' +
|
||||
'let {react, reactDOM } = new Function(`${REACT_PACKAGES}; return {react: React, reactDOM: ReactDOM};`)();\n' +
|
||||
'let excalidrawLib = {};\n' +
|
||||
'const loadMathjaxToSVG = () => new Function(`${LZString.decompressFromBase64("' + LZString.compressToBase64(mathjaxtosvg_pkg) + '")}; return MathjaxToSVG;`)();\n' +
|
||||
`const PLUGIN_LANGUAGES = {${LANGUAGES.map(lang => `"${lang}": "${compressLanguageFile(lang)}"`).join(",")}};\n` +
|
||||
'const PLUGIN_VERSION="' + manifest.version + '";';
|
||||
|
||||
const BASE_CONFIG = {
|
||||
input: 'src/core/main.ts',
|
||||
external: [
|
||||
'@codemirror/autocomplete',
|
||||
'@codemirror/collab',
|
||||
'@codemirror/commands',
|
||||
'@codemirror/language',
|
||||
'@codemirror/lint',
|
||||
'@codemirror/search',
|
||||
'@codemirror/state',
|
||||
'@codemirror/view',
|
||||
'@lezer/common',
|
||||
'@lezer/highlight',
|
||||
'@lezer/lr',
|
||||
'obsidian',
|
||||
'@zsviczian/excalidraw',
|
||||
'react',
|
||||
'react-dom'
|
||||
],
|
||||
};
|
||||
|
||||
const getRollupPlugins = (tsconfig, ...plugins) => [
|
||||
typescript2(tsconfig),
|
||||
json(),
|
||||
replace({
|
||||
preventAssignment: true,
|
||||
"process.env.NODE_ENV": JSON.stringify(process.env.NODE_ENV),
|
||||
}),
|
||||
commonjs(),
|
||||
nodeResolve({ browser: true, preferBuiltins: false }),
|
||||
].concat(plugins);
|
||||
|
||||
const BUILD_CONFIG = {
|
||||
...BASE_CONFIG,
|
||||
output: {
|
||||
dir: DIST_FOLDER,
|
||||
entryFileNames: 'main.js',
|
||||
format: 'cjs',
|
||||
exports: 'default',
|
||||
inlineDynamicImports: true, // Add this line only
|
||||
},
|
||||
plugins: getRollupPlugins(
|
||||
{
|
||||
tsconfig: isProd ? "tsconfig.json" : "tsconfig.dev.json",
|
||||
sourcemap: !isProd,
|
||||
clean: true,
|
||||
//verbosity: isProd ? 1 : 2,
|
||||
},
|
||||
...(isProd ? [
|
||||
terser({
|
||||
toplevel: false,
|
||||
compress: { passes: 2 },
|
||||
format: {
|
||||
comments: false, // Remove all comments
|
||||
},
|
||||
}),
|
||||
postprocess([
|
||||
[
|
||||
/(var[^;]*?),\s*React\s*=\s*require\(["']react["']\)([^;]*;)/,
|
||||
(_, g1, g2) => `${g1}${g2}${packageString}`
|
||||
],
|
||||
]),
|
||||
] : [
|
||||
postprocess([ [/var React = require\('react'\);/, packageString] ]),
|
||||
]),
|
||||
copy({
|
||||
targets: [ { src: 'manifest.json', dest: DIST_FOLDER } ],
|
||||
verbose: true,
|
||||
}),
|
||||
),
|
||||
};
|
||||
|
||||
const LIB_CONFIG = {
|
||||
...BASE_CONFIG,
|
||||
input: "src/core/index.ts",
|
||||
output: {
|
||||
dir: "lib",
|
||||
sourcemap: false,
|
||||
format: "cjs",
|
||||
name: "Excalidraw (Library)",
|
||||
},
|
||||
plugins: getRollupPlugins(
|
||||
{ tsconfig: "tsconfig-lib.json" },
|
||||
copy({ targets: [{ src: "src/*.d.ts", dest: "lib/typings" }] })
|
||||
),
|
||||
};
|
||||
|
||||
let config = [];
|
||||
if (process.env.NODE_ENV === "lib") {
|
||||
config.push(LIB_CONFIG);
|
||||
} else {
|
||||
config.push(BUILD_CONFIG);
|
||||
}
|
||||
|
||||
export default config;
|
||||
import { nodeResolve } from '@rollup/plugin-node-resolve';
|
||||
import commonjs from '@rollup/plugin-commonjs';
|
||||
import replace from "@rollup/plugin-replace";
|
||||
import terser from "@rollup/plugin-terser";
|
||||
import copy from "rollup-plugin-copy";
|
||||
import typescript from "@rollup/plugin-typescript";
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
import LZString from 'lz-string';
|
||||
import postprocess from '@zsviczian/rollup-plugin-postprocess';
|
||||
import cssnano from 'cssnano';
|
||||
import jsesc from 'jsesc';
|
||||
import { minify } from 'uglify-js';
|
||||
import json from '@rollup/plugin-json';
|
||||
import { parseEnv } from 'node:util';
|
||||
|
||||
try {
|
||||
const envContent = fs.readFileSync(path.resolve('.env'), 'utf8');
|
||||
Object.assign(process.env, parseEnv(envContent));
|
||||
} catch (error) {
|
||||
}
|
||||
|
||||
const DIST_FOLDER = 'dist';
|
||||
const absolutePath = path.resolve(DIST_FOLDER);
|
||||
fs.mkdirSync(absolutePath, { recursive: true });
|
||||
const isProd = (process.env.NODE_ENV === "production");
|
||||
const isLib = (process.env.NODE_ENV === "lib");
|
||||
console.log(`Running: ${process.env.NODE_ENV}; isProd: ${isProd}; isLib: ${isLib}`);
|
||||
|
||||
|
||||
// Excalidraw React 19 compatiblity shim
|
||||
// Create JSX runtime compatibility layer
|
||||
const jsxRuntimeShim = `
|
||||
const jsx = (type, props, key) => {
|
||||
return React.createElement(type, props);
|
||||
};
|
||||
const jsxs = (type, props, key) => {
|
||||
return React.createElement(type, props);
|
||||
};
|
||||
const Fragment = React.Fragment;
|
||||
React.jsx = jsx;
|
||||
React.jsxs = jsxs;
|
||||
React.Fragment = Fragment;
|
||||
React.jsxRuntime = { jsx, jsxs, Fragment };
|
||||
window.__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__ = { jsx, jsxs, Fragment };
|
||||
window.__WEBPACK_EXTERNAL_MODULE_react_jsx_dev_runtime__ = { jsx, jsxs, Fragment, jsxDEV: jsx };
|
||||
window['react/jsx-runtime'] = { jsx, jsxs, Fragment };
|
||||
window['react/jsx-dev-runtime'] = { jsx, jsxs, Fragment, jsxDEV: jsx };
|
||||
`;
|
||||
|
||||
|
||||
|
||||
const mathjaxtosvg_pkg = isLib ? "" : fs.readFileSync("./MathjaxToSVG/dist/index.js", "utf8");
|
||||
|
||||
// Add non-English locales here to embed them as compressed payloads in main.js.
|
||||
// When adding a locale file:
|
||||
// 1) add its code to this list, 2) build once, 3) if build fails because the locale
|
||||
// contains a new dynamic expression, extend tokenizeLocaleContent below and mirror
|
||||
// the new token in src/lang/helpers.ts token resolution.
|
||||
const LANGUAGES = ['ru', 'zh-cn', 'zh-tw', 'es']; // english is loaded by default
|
||||
|
||||
function trimLastSemicolon(input) {
|
||||
if (input.endsWith(";")) {
|
||||
return input.slice(0, -1);
|
||||
}
|
||||
return input;
|
||||
}
|
||||
|
||||
function minifyCode(code) {
|
||||
const minified = minify(code, {
|
||||
compress: {
|
||||
//https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2170
|
||||
reduce_vars: false,
|
||||
},
|
||||
mangle: true,
|
||||
output: {
|
||||
comments: false,
|
||||
beautify: false,
|
||||
}
|
||||
});
|
||||
|
||||
if (minified.error) {
|
||||
throw new Error(minified.error);
|
||||
}
|
||||
return minified.code;
|
||||
}
|
||||
|
||||
// Build-time placeholders that are resolved at runtime in src/lang/helpers.ts.
|
||||
// Kept in sync with TOKENS in helpers.ts.
|
||||
const DEVICE_TOKEN_VALUES = {
|
||||
IF_DESKTOP_START: "__EXD_IF_DESKTOP__",
|
||||
IF_DESKTOP_END: "__EXD_END_IF_DESKTOP__",
|
||||
IF_APPLE_START: "__EXD_IF_APPLE__",
|
||||
IF_APPLE_ELSE: "__EXD_ELSE_APPLE__",
|
||||
IF_APPLE_END: "__EXD_END_IF_APPLE__",
|
||||
// We no longer need DEVTOOLS_SHORTCUT here, the Apple ternary regex catches it naturally.
|
||||
|
||||
// Variables mocked in our sandbox evaluation
|
||||
LABEL_ALT: "__EXD_LABEL_ALT__",
|
||||
LABEL_CTRL: "__EXD_LABEL_CTRL__",
|
||||
LABEL_META: "__EXD_LABEL_META__",
|
||||
LABEL_SHIFT: "__EXD_LABEL_SHIFT__",
|
||||
FRONTMATTER_LINK_BRACKETS: "__EXD_FRONTMATTER_LINK_BRACKETS__",
|
||||
FRONTMATTER_LINK_PREFIX: "__EXD_FRONTMATTER_LINK_PREFIX__",
|
||||
FRONTMATTER_URL_PREFIX: "__EXD_FRONTMATTER_URL_PREFIX__",
|
||||
CJK_FONTS: "__EXD_CJK_FONTS__",
|
||||
PLUGIN_VERSION: "__EXD_PLUGIN_VERSION__",
|
||||
};
|
||||
|
||||
function tokenizeLocaleContent(content, deviceTokens = DEVICE_TOKEN_VALUES) {
|
||||
let tokenized = content;
|
||||
|
||||
// 1. Desktop Conditional
|
||||
// Matches: ${ DEVICE.isDesktop ? `...` : "" }
|
||||
// Robust against arbitrary spaces, newlines, and empty string quote types ("", '', or ``).
|
||||
const desktopRegex = /\$\{\s*DEVICE\.isDesktop\s*\?\s*`([\s\S]*?)`\s*:\s*["'`]{2}\s*\}/g;
|
||||
tokenized = tokenized.replace(desktopRegex, (match, trueBranch) => {
|
||||
return `${deviceTokens.IF_DESKTOP_START}${trueBranch}${deviceTokens.IF_DESKTOP_END}`;
|
||||
});
|
||||
|
||||
// 2. Apple / MacOS Ternaries
|
||||
// Matches both: ( DEVICE.isIOS || DEVICE.isMacOS ? "A" : "B" ) AND DEVICE.isMacOS ? "A" : "B"
|
||||
// Robust against optional parentheses, line breaks, and varying quote types.
|
||||
const appleTernaryRegex = /(?:\(\s*)?(?:DEVICE\.isIOS\s*\|\|\s*)?DEVICE\.isMacOS\s*\?\s*(["'`])([\s\S]*?)\1\s*:\s*(["'`])([\s\S]*?)\3(?:\s*\))?/g;
|
||||
tokenized = tokenized.replace(appleTernaryRegex, (match, quote1, trueBranch, quote2, falseBranch) => {
|
||||
// Wrap in double quotes so the resulting JS is a valid string literal
|
||||
return `"${deviceTokens.IF_APPLE_START}${trueBranch}${deviceTokens.IF_APPLE_ELSE}${falseBranch}${deviceTokens.IF_APPLE_END}"`;
|
||||
});
|
||||
|
||||
return tokenized;
|
||||
}
|
||||
|
||||
function serializeLocaleToJson(content, deviceTokens = DEVICE_TOKEN_VALUES) {
|
||||
// Rather than regex-replacing variables, we inject mock variables into the Node sandbox.
|
||||
// When Node evaluates the file, it will natively resolve ${labelALT()} to the token string,
|
||||
// perfectly bypassing any linter formatting, ES6 template literal breaks, or comment syntax.
|
||||
const sandboxEnvironment = `
|
||||
const TAG_AUTOEXPORT = "Autoexport";
|
||||
const TAG_MDREADINGMODE = "MDReadingMode";
|
||||
const TAG_PDFEXPORT = "PDFExport";
|
||||
|
||||
const PLUGIN_VERSION = "${deviceTokens.PLUGIN_VERSION}";
|
||||
const CJK_FONTS = "${deviceTokens.CJK_FONTS}";
|
||||
|
||||
const labelALT = () => "${deviceTokens.LABEL_ALT}";
|
||||
const labelCTRL = () => "${deviceTokens.LABEL_CTRL}";
|
||||
const labelMETA = () => "${deviceTokens.LABEL_META}";
|
||||
const labelSHIFT = () => "${deviceTokens.LABEL_SHIFT}";
|
||||
|
||||
const FRONTMATTER_KEYS = {
|
||||
"link-brackets": { name: "${deviceTokens.FRONTMATTER_LINK_BRACKETS}" },
|
||||
"link-prefix": { name: "${deviceTokens.FRONTMATTER_LINK_PREFIX}" },
|
||||
"url-prefix": { name: "${deviceTokens.FRONTMATTER_URL_PREFIX}" }
|
||||
};
|
||||
|
||||
// Fallback for DEVICE to prevent ReferenceErrors if a conditional regex misses an edge case
|
||||
const DEVICE = { isDesktop: false, isIOS: false, isMacOS: false };
|
||||
|
||||
let x = ${content};
|
||||
return x;
|
||||
`;
|
||||
|
||||
try {
|
||||
const locale = new Function(sandboxEnvironment)();
|
||||
return JSON.stringify(locale);
|
||||
} catch (err) {
|
||||
console.error("Error evaluating locale content.");
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
function compressLanguageFile(lang) {
|
||||
const inputDir = "./src/lang/locale";
|
||||
const filePath = `${inputDir}/${lang}.ts`;
|
||||
let content = fs.readFileSync(filePath, "utf-8");
|
||||
|
||||
// Safely extract the default export object, ignoring surrounding types/interfaces
|
||||
const exportMatch = content.match(/export\s+default\s+([\s\S]+)/);
|
||||
if (!exportMatch) throw new Error(`Could not find 'export default' in ${filePath}`);
|
||||
|
||||
let objectContent = exportMatch[1].trim();
|
||||
if (objectContent.endsWith(";")) {
|
||||
objectContent = objectContent.slice(0, -1);
|
||||
}
|
||||
|
||||
const tokenizedContent = tokenizeLocaleContent(objectContent);
|
||||
const localeJson = serializeLocaleToJson(tokenizedContent);
|
||||
return LZString.compressToBase64(localeJson);
|
||||
}
|
||||
|
||||
const excalidraw_pkg = isLib ? "" : minifyCode(isProd
|
||||
? fs.readFileSync("./node_modules/@zsviczian/excalidraw/dist/excalidraw.production.min.js", "utf8")
|
||||
: fs.readFileSync("./node_modules/@zsviczian/excalidraw/dist/excalidraw.development.js", "utf8"));
|
||||
const react_pkg = isLib ? "" : minifyCode(isProd
|
||||
? fs.readFileSync("./node_modules/react/umd/react.production.min.js", "utf8")
|
||||
: fs.readFileSync("./node_modules/react/umd/react.development.js", "utf8"));
|
||||
const reactdom_pkg = isLib ? "" : minifyCode(isProd
|
||||
? fs.readFileSync("./node_modules/react-dom/umd/react-dom.production.min.js", "utf8")
|
||||
: fs.readFileSync("./node_modules/react-dom/umd/react-dom.development.js", "utf8"));
|
||||
|
||||
const lzstring_pkg = isLib ? "" : fs.readFileSync("./node_modules/lz-string/libs/lz-string.min.js", "utf8");
|
||||
if (!isLib) {
|
||||
const excalidraw_styles = isProd
|
||||
? fs.readFileSync("./node_modules/@zsviczian/excalidraw/dist/styles.production.css", "utf8")
|
||||
: fs.readFileSync("./node_modules/@zsviczian/excalidraw/dist/styles.development.css", "utf8");
|
||||
const plugin_styles = fs.readFileSync("./styles.css", "utf8");
|
||||
const styles = excalidraw_styles + plugin_styles;
|
||||
cssnano()
|
||||
.process(styles, {
|
||||
from: path.resolve("styles.css"),
|
||||
to: path.resolve(DIST_FOLDER, "styles.css"),
|
||||
})
|
||||
.then(result => {
|
||||
fs.writeFileSync(`./${DIST_FOLDER}/styles.css`, result.css);
|
||||
})
|
||||
.catch(error => {
|
||||
console.error('Error while processing CSS:', error);
|
||||
});
|
||||
}
|
||||
|
||||
const manifestStr = isLib ? "" : fs.readFileSync("manifest-beta.json", "utf-8");
|
||||
const manifest = isLib ? {} : JSON.parse(manifestStr);
|
||||
if (!isLib) {
|
||||
console.log(manifest.version);
|
||||
}
|
||||
|
||||
const packageString = isLib
|
||||
? ""
|
||||
: ';const INITIAL_TIMESTAMP=Date.now();' + lzstring_pkg +
|
||||
'\nlet REACT_PACKAGES = `' +
|
||||
jsesc(react_pkg + reactdom_pkg + jsxRuntimeShim, { quotes: 'backtick' }) +
|
||||
'`;\n' +
|
||||
'const unpackExcalidraw = () => LZString.decompressFromBase64("' + LZString.compressToBase64(excalidraw_pkg) + '");\n' +
|
||||
'let {react, reactDOM } = new Function(`${REACT_PACKAGES}; return {react: React, reactDOM: ReactDOM};`)();\n' +
|
||||
'let excalidrawLib = {};\n' +
|
||||
'const loadMathjaxToSVG = () => new Function(`${LZString.decompressFromBase64("' + LZString.compressToBase64(mathjaxtosvg_pkg) + '")}; return MathjaxToSVG;`)();\n' +
|
||||
`const PLUGIN_LANGUAGES = {${LANGUAGES.map(lang => `"${lang}": "${compressLanguageFile(lang)}"`).join(",")}};\n` +
|
||||
'const PLUGIN_VERSION="' + manifest.version + '";';
|
||||
|
||||
const BASE_CONFIG = {
|
||||
input: 'src/core/main.ts',
|
||||
external: [
|
||||
'@codemirror/autocomplete',
|
||||
'@codemirror/collab',
|
||||
'@codemirror/commands',
|
||||
'@codemirror/language',
|
||||
'@codemirror/lint',
|
||||
'@codemirror/search',
|
||||
'@codemirror/state',
|
||||
'@codemirror/view',
|
||||
'@lezer/common',
|
||||
'@lezer/highlight',
|
||||
'@lezer/lr',
|
||||
'obsidian',
|
||||
'@zsviczian/excalidraw',
|
||||
'react',
|
||||
'react-dom'
|
||||
],
|
||||
};
|
||||
|
||||
const getRollupPlugins = (tsconfig, ...plugins) => [
|
||||
typescript(tsconfig),
|
||||
json(),
|
||||
replace({
|
||||
preventAssignment: true,
|
||||
"process.env.NODE_ENV": JSON.stringify(process.env.NODE_ENV),
|
||||
}),
|
||||
commonjs(),
|
||||
nodeResolve({ browser: true, preferBuiltins: false }),
|
||||
].concat(plugins);
|
||||
|
||||
const BUILD_CONFIG = {
|
||||
...BASE_CONFIG,
|
||||
output: {
|
||||
dir: DIST_FOLDER,
|
||||
entryFileNames: 'main.js',
|
||||
format: 'cjs',
|
||||
exports: 'default',
|
||||
inlineDynamicImports: true, // Add this line only
|
||||
},
|
||||
plugins: getRollupPlugins(
|
||||
{
|
||||
tsconfig: isProd ? "tsconfig.json" : "tsconfig.dev.json",
|
||||
sourceMap: !isProd,
|
||||
},
|
||||
...(isProd ? [
|
||||
terser({
|
||||
toplevel: false,
|
||||
compress: { passes: 2 },
|
||||
format: {
|
||||
comments: false, // Remove all comments
|
||||
},
|
||||
}),
|
||||
postprocess([
|
||||
[
|
||||
/(var[^;]*?),\s*React\s*=\s*require\(["']react["']\)([^;]*;)/,
|
||||
(_, g1, g2) => `${g1}${g2}${packageString}`
|
||||
],
|
||||
]),
|
||||
] : [
|
||||
postprocess([ [/var React = require\('react'\);/, packageString] ]),
|
||||
]),
|
||||
copy({
|
||||
targets: [ { src: 'manifest.json', dest: DIST_FOLDER } ],
|
||||
verbose: true,
|
||||
}),
|
||||
),
|
||||
};
|
||||
|
||||
const LIB_CONFIG = {
|
||||
...BASE_CONFIG,
|
||||
input: "src/core/index.ts",
|
||||
output: {
|
||||
dir: "lib",
|
||||
sourcemap: false,
|
||||
format: "cjs",
|
||||
name: "Excalidraw (Library)",
|
||||
},
|
||||
plugins: getRollupPlugins(
|
||||
{ tsconfig: "tsconfig-lib.json" },
|
||||
copy({ targets: [{ src: "src/*.d.ts", dest: "lib/typings" }] })
|
||||
),
|
||||
};
|
||||
|
||||
let config = [];
|
||||
if (process.env.NODE_ENV === "lib") {
|
||||
config.push(LIB_CONFIG);
|
||||
} else {
|
||||
config.push(BUILD_CONFIG);
|
||||
}
|
||||
|
||||
export default config;
|
||||
@@ -0,0 +1,63 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import crypto from 'node:crypto';
|
||||
import { execSync } from 'node:child_process';
|
||||
|
||||
const mathjaxDir = path.resolve('MathjaxToSVG');
|
||||
const distDir = path.join(mathjaxDir, 'dist');
|
||||
const distFile = path.join(distDir, 'index.js');
|
||||
const hashFile = path.join(distDir, '.build-hash');
|
||||
const nodeModulesDir = path.join(mathjaxDir, 'node_modules');
|
||||
|
||||
// Recursively generates an MD5 hash of all source files in a directory
|
||||
function hashDirectory(dir) {
|
||||
const files = fs.readdirSync(dir, { withFileTypes: true });
|
||||
const hash = crypto.createHash('md5');
|
||||
|
||||
// Sort to ensure consistent hashing across different operating systems
|
||||
for (const file of files.sort((a, b) => a.name.localeCompare(b.name))) {
|
||||
// Ignore build outputs, dependencies, and hidden files (like .git, .DS_Store)
|
||||
if (file.name === 'node_modules' || file.name === 'dist' || file.name.startsWith('.')) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const fullPath = path.join(dir, file.name);
|
||||
if (file.isDirectory()) {
|
||||
hash.update(hashDirectory(fullPath));
|
||||
} else {
|
||||
hash.update(fs.readFileSync(fullPath));
|
||||
}
|
||||
}
|
||||
return hash.digest('hex');
|
||||
}
|
||||
|
||||
const currentHash = hashDirectory(mathjaxDir);
|
||||
let previousHash = '';
|
||||
|
||||
if (fs.existsSync(hashFile)) {
|
||||
previousHash = fs.readFileSync(hashFile, 'utf8');
|
||||
}
|
||||
|
||||
// Rebuild if the output file is missing, or if the source files have changed
|
||||
if (!fs.existsSync(distFile) || currentHash !== previousHash) {
|
||||
console.log('🔄 MathjaxToSVG changes detected (or missing build). Rebuilding...');
|
||||
|
||||
// Run npm install if node_modules is missing or if we know things changed
|
||||
if (!fs.existsSync(nodeModulesDir) || currentHash !== previousHash) {
|
||||
console.log('📦 Installing MathjaxToSVG dependencies...');
|
||||
execSync('npm install', { stdio: 'inherit', cwd: mathjaxDir });
|
||||
}
|
||||
|
||||
console.log('🔨 Building MathjaxToSVG...');
|
||||
execSync('npm run build', { stdio: 'inherit', cwd: mathjaxDir });
|
||||
|
||||
// Save the new hash for next time
|
||||
if (!fs.existsSync(distDir)) {
|
||||
fs.mkdirSync(distDir, { recursive: true });
|
||||
}
|
||||
fs.writeFileSync(hashFile, currentHash);
|
||||
|
||||
console.log('✅ MathjaxToSVG build complete.\n');
|
||||
} else {
|
||||
console.log('⚡ MathjaxToSVG is up to date. Skipping build.\n');
|
||||
}
|
||||
@@ -40,8 +40,8 @@ The script balances **automation** (auto-layout, recursive grouping, and contras
|
||||
const FOOTER = `
|
||||
const VERSION = "v${new Date().toISOString().slice(2, 10).replace(/-/g, ".")}";
|
||||
|
||||
if (!ea.verifyMinimumPluginVersion || !ea.verifyMinimumPluginVersion("2.20.6")) {
|
||||
new Notice("Please update the Excalidraw Plugin to version 2.20.6 or higher.");
|
||||
if (!ea.verifyMinimumPluginVersion || !ea.verifyMinimumPluginVersion("2.21.0")) {
|
||||
new Notice("Please update the Excalidraw Plugin to version 2.21.0 or higher.");
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
+612
-220
File diff suppressed because it is too large.
Load diff
@@ -1,3 +1,3 @@
|
||||
export const TAG_PDFEXPORT = "PDFExport";
|
||||
export const TAG_MDREADINGMODE = "MDReadingMode";
|
||||
export const TAG_AUTOEXPORT = "Autoexport";
|
||||
export const TAG_AUTOEXPORT = "Autoexport";
|
||||
+214
-131
@@ -3,8 +3,9 @@ import { ExcalidrawLib } from "../types/excalidrawLib";
|
||||
import ExcalidrawPlugin from "src/core/main";
|
||||
import { DeviceType } from "src/types/types";
|
||||
import { errorHandler } from "../utils/ErrorHandler";
|
||||
import { getLanguage } from "obsidian";
|
||||
//This is only for backward compatibility because an early version of obsidian included an encoding to avoid fantom links from littering Obsidian graph view
|
||||
declare const PLUGIN_VERSION:string;
|
||||
declare const PLUGIN_VERSION: string;
|
||||
export let EXCALIDRAW_PLUGIN: ExcalidrawPlugin = null;
|
||||
export const setExcalidrawPlugin = (plugin: ExcalidrawPlugin) => {
|
||||
EXCALIDRAW_PLUGIN = plugin;
|
||||
@@ -20,69 +21,74 @@ const MD_ELEMENTLINKS = "## Element Links";
|
||||
const MD_EMBEDFILES = "## Embedded Files";
|
||||
const MD_DRAWING = "## Drawing";
|
||||
|
||||
export const MD_EX_SECTIONS = [MD_EXCALIDRAW, MD_TEXTELEMENTS, MD_ELEMENTLINKS, MD_EMBEDFILES, MD_DRAWING];
|
||||
export const MD_EX_SECTIONS = [
|
||||
MD_EXCALIDRAW,
|
||||
MD_TEXTELEMENTS,
|
||||
MD_ELEMENTLINKS,
|
||||
MD_EMBEDFILES,
|
||||
MD_DRAWING,
|
||||
];
|
||||
|
||||
export const ERROR_IFRAME_CONVERSION_CANCELED = "iframe conversion canceled";
|
||||
|
||||
declare const excalidrawLib: typeof ExcalidrawLib;
|
||||
|
||||
export const LOCALE = localStorage.getItem("language")?.toLowerCase() || "en";
|
||||
export const LOCALE = getLanguage().toLowerCase();
|
||||
export const CJK_FONTS = "CJK Fonts";
|
||||
|
||||
export const obsidianToExcalidrawMap: { [key: string]: string } = {
|
||||
'en': 'en-US',
|
||||
'af': 'af-ZA', // Assuming South Africa for Afrikaans
|
||||
'am': 'am-ET', // Assuming Ethiopia for Amharic
|
||||
'ar': 'ar-SA',
|
||||
'eu': 'eu-ES',
|
||||
'be': 'be-BY', // Assuming Belarus for Belarusian
|
||||
'bg': 'bg-BG',
|
||||
'bn': 'bn-BD', // Assuming Bangladesh for Bengali
|
||||
'ca': 'ca-ES',
|
||||
'cs': 'cs-CZ',
|
||||
'da': 'da-DK', // Assuming Denmark for Danish
|
||||
'de': 'de-DE',
|
||||
'el': 'el-GR',
|
||||
'eo': 'eo-EO', // Esperanto doesn't have a country
|
||||
'es': 'es-ES',
|
||||
'fa': 'fa-IR',
|
||||
'fi-fi': 'fi-FI',
|
||||
'fr': 'fr-FR',
|
||||
'gl': 'gl-ES',
|
||||
'he': 'he-IL',
|
||||
'hi': 'hi-IN',
|
||||
'hu': 'hu-HU',
|
||||
'id': 'id-ID',
|
||||
'it': 'it-IT',
|
||||
'ja': 'ja-JP',
|
||||
'ko': 'ko-KR',
|
||||
'lv': 'lv-LV',
|
||||
'ml': 'ml-IN', // Assuming India for Malayalam
|
||||
'ms': 'ms-MY', // Assuming Malaysia for Malay
|
||||
'nl': 'nl-NL',
|
||||
'no': 'nb-NO', // Using Norwegian Bokmål for Norwegian
|
||||
'oc': 'oc-FR', // Assuming France for Occitan
|
||||
'pl': 'pl-PL',
|
||||
'pt': 'pt-PT',
|
||||
'pt-BR': 'pt-BR',
|
||||
'ro': 'ro-RO',
|
||||
'ru': 'ru-RU',
|
||||
'sr': 'sr-RS', // Assuming Serbia for Serbian
|
||||
'se': 'sv-SE', // Assuming Swedish for 'se'
|
||||
'sk': 'sk-SK',
|
||||
'sq': 'sq-AL', // Assuming Albania for Albanian
|
||||
'ta': 'ta-IN', // Assuming India for Tamil
|
||||
'te': 'te-IN', // Assuming India for Telugu
|
||||
'th': 'th-TH',
|
||||
'tr': 'tr-TR',
|
||||
'uk': 'uk-UA',
|
||||
'ur': 'ur-PK', // Assuming Pakistan for Urdu
|
||||
'vi': 'vi-VN',
|
||||
'zh': 'zh-CN',
|
||||
'zh-tw': 'zh-TW',
|
||||
en: "en-US",
|
||||
af: "af-ZA", // Assuming South Africa for Afrikaans
|
||||
am: "am-ET", // Assuming Ethiopia for Amharic
|
||||
ar: "ar-SA",
|
||||
eu: "eu-ES",
|
||||
be: "be-BY", // Assuming Belarus for Belarusian
|
||||
bg: "bg-BG",
|
||||
bn: "bn-BD", // Assuming Bangladesh for Bengali
|
||||
ca: "ca-ES",
|
||||
cs: "cs-CZ",
|
||||
da: "da-DK", // Assuming Denmark for Danish
|
||||
de: "de-DE",
|
||||
el: "el-GR",
|
||||
eo: "eo-EO", // Esperanto doesn't have a country
|
||||
es: "es-ES",
|
||||
fa: "fa-IR",
|
||||
"fi-fi": "fi-FI",
|
||||
fr: "fr-FR",
|
||||
gl: "gl-ES",
|
||||
he: "he-IL",
|
||||
hi: "hi-IN",
|
||||
hu: "hu-HU",
|
||||
id: "id-ID",
|
||||
it: "it-IT",
|
||||
ja: "ja-JP",
|
||||
ko: "ko-KR",
|
||||
lv: "lv-LV",
|
||||
ml: "ml-IN", // Assuming India for Malayalam
|
||||
ms: "ms-MY", // Assuming Malaysia for Malay
|
||||
nl: "nl-NL",
|
||||
no: "nb-NO", // Using Norwegian Bokmål for Norwegian
|
||||
oc: "oc-FR", // Assuming France for Occitan
|
||||
pl: "pl-PL",
|
||||
pt: "pt-PT",
|
||||
"pt-BR": "pt-BR",
|
||||
ro: "ro-RO",
|
||||
ru: "ru-RU",
|
||||
sr: "sr-RS", // Assuming Serbia for Serbian
|
||||
se: "sv-SE", // Assuming Swedish for 'se'
|
||||
sk: "sk-SK",
|
||||
sq: "sq-AL", // Assuming Albania for Albanian
|
||||
ta: "ta-IN", // Assuming India for Tamil
|
||||
te: "te-IN", // Assuming India for Telugu
|
||||
th: "th-TH",
|
||||
tr: "tr-TR",
|
||||
uk: "uk-UA",
|
||||
ur: "ur-PK", // Assuming Pakistan for Urdu
|
||||
vi: "vi-VN",
|
||||
zh: "zh-CN",
|
||||
"zh-tw": "zh-TW",
|
||||
};
|
||||
|
||||
|
||||
export let {
|
||||
sceneCoordsToViewportCoords,
|
||||
viewportCoordsToSceneCoords,
|
||||
@@ -91,9 +97,9 @@ export let {
|
||||
getMaximumGroups,
|
||||
measureText,
|
||||
getLineHeight,
|
||||
wrapText,
|
||||
getFontString,
|
||||
getBoundTextMaxWidth,
|
||||
wrapText,
|
||||
getFontString,
|
||||
getBoundTextMaxWidth,
|
||||
exportToSvg,
|
||||
exportToBlob,
|
||||
mutateElement,
|
||||
@@ -115,24 +121,30 @@ export function updateExcalidrawLib() {
|
||||
if (!excalidrawLib) {
|
||||
throw new Error("excalidrawLib is undefined");
|
||||
}
|
||||
|
||||
|
||||
// Check that critical functions exist before assigning them
|
||||
const requiredFunctions = [
|
||||
'sceneCoordsToViewportCoords',
|
||||
'viewportCoordsToSceneCoords',
|
||||
'intersectElementWithLine',
|
||||
'getCommonBoundingBox',
|
||||
'measureText',
|
||||
'getLineHeight',
|
||||
'restoreElements'
|
||||
"sceneCoordsToViewportCoords",
|
||||
"viewportCoordsToSceneCoords",
|
||||
"intersectElementWithLine",
|
||||
"getCommonBoundingBox",
|
||||
"measureText",
|
||||
"getLineHeight",
|
||||
"restoreElements",
|
||||
];
|
||||
|
||||
|
||||
for (const fnName of requiredFunctions) {
|
||||
if (!(fnName in excalidrawLib) || typeof excalidrawLib[fnName as keyof typeof excalidrawLib] !== 'function') {
|
||||
throw new Error(`Required function ${fnName} is missing from excalidrawLib`);
|
||||
if (
|
||||
!(fnName in excalidrawLib) ||
|
||||
typeof excalidrawLib[fnName as keyof typeof excalidrawLib] !==
|
||||
"function"
|
||||
) {
|
||||
throw new Error(
|
||||
`Required function ${fnName} is missing from excalidrawLib`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// If validation passes, update the exported functions
|
||||
({
|
||||
sceneCoordsToViewportCoords,
|
||||
@@ -142,9 +154,9 @@ export function updateExcalidrawLib() {
|
||||
getMaximumGroups,
|
||||
measureText,
|
||||
getLineHeight,
|
||||
wrapText,
|
||||
getFontString,
|
||||
getBoundTextMaxWidth,
|
||||
wrapText,
|
||||
getFontString,
|
||||
getBoundTextMaxWidth,
|
||||
exportToSvg,
|
||||
exportToBlob,
|
||||
mutateElement,
|
||||
@@ -169,38 +181,42 @@ export function updateExcalidrawLib() {
|
||||
export const FONTS_STYLE_ID = "excalidraw-custom-fonts";
|
||||
export const CJK_STYLE_ID = "excalidraw-cjk-fonts";
|
||||
|
||||
export function JSON_parse(x: string): any {
|
||||
return JSON.parse(x.replaceAll("[", "["));
|
||||
export function JSON_parse<T>(x: string): T {
|
||||
return JSON.parse(x.replaceAll("[", "[")) as T;
|
||||
}
|
||||
export const isDarwin = /Mac|iPod|iPhone|iPad/.test(window.navigator.platform);
|
||||
|
||||
export const DEVICE: DeviceType = {
|
||||
isDesktop: !document.body.hasClass("is-tablet") && !document.body.hasClass("is-mobile"),
|
||||
isDesktop:
|
||||
!document.body.hasClass("is-tablet") &&
|
||||
!document.body.hasClass("is-mobile"),
|
||||
isPhone: document.body.hasClass("is-phone"),
|
||||
isTablet: document.body.hasClass("is-tablet"),
|
||||
isMobile: document.body.hasClass("is-mobile"), //running Obsidian Mobile, need to also check isTablet
|
||||
isLinux: document.body.hasClass("mod-linux") && ! document.body.hasClass("is-android"),
|
||||
isMacOS: document.body.hasClass("mod-macos") && ! document.body.hasClass("is-ios"),
|
||||
isLinux:
|
||||
document.body.hasClass("mod-linux") &&
|
||||
!document.body.hasClass("is-android"),
|
||||
isMacOS:
|
||||
document.body.hasClass("mod-macos") && !document.body.hasClass("is-ios"),
|
||||
isWindows: document.body.hasClass("mod-windows"),
|
||||
isIOS: document.body.hasClass("is-ios"),
|
||||
isAndroid: document.body.hasClass("is-android"),
|
||||
};
|
||||
|
||||
export let ROOTELEMENTSIZE: number = 16;
|
||||
export function setRootElementSize(size?:number) {
|
||||
if(size) {
|
||||
export function setRootElementSize(size?: number) {
|
||||
if (size) {
|
||||
ROOTELEMENTSIZE = size;
|
||||
return;
|
||||
}
|
||||
const tempElement = document.createElement('div');
|
||||
tempElement.style.fontSize = '1rem';
|
||||
tempElement.style.display = 'none'; // Hide the element
|
||||
const tempElement = document.createElement("div");
|
||||
tempElement.style.fontSize = "1rem";
|
||||
tempElement.hidden = true;
|
||||
document.body.appendChild(tempElement);
|
||||
const computedStyle = getComputedStyle(tempElement);
|
||||
const pixelSize = parseFloat(computedStyle.fontSize);
|
||||
document.body.removeChild(tempElement);
|
||||
return pixelSize;
|
||||
};
|
||||
}
|
||||
|
||||
export const nanoid = customAlphabet(
|
||||
"1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",
|
||||
@@ -209,13 +225,15 @@ export const nanoid = customAlphabet(
|
||||
export const KEYCODE = {
|
||||
ESC: 27,
|
||||
};
|
||||
export const ROUNDNESS = { //should at one point publish @zsviczian/excalidraw/types/constants
|
||||
export const ROUNDNESS = {
|
||||
//should at one point publish @zsviczian/excalidraw/types/constants
|
||||
LEGACY: 1,
|
||||
PROPORTIONAL_RADIUS: 2,
|
||||
ADAPTIVE_RADIUS: 3,
|
||||
} as const;
|
||||
export const THEME_FILTER = "invert(93%) hue-rotate(180deg) saturate(1.25)";
|
||||
export const GITHUB_RELEASES = "https://github.com/zsviczian/obsidian-excalidraw-plugin/releases/tag/";
|
||||
export const GITHUB_RELEASES =
|
||||
"https://github.com/zsviczian/obsidian-excalidraw-plugin/releases/tag/";
|
||||
export const URLFETCHTIMEOUT = 3000;
|
||||
export const PLUGIN_ID = "obsidian-excalidraw-plugin";
|
||||
export const SCRIPT_INSTALL_CODEBLOCK = "excalidraw-script-install";
|
||||
@@ -225,45 +243,110 @@ export const REG_LINKINDEX_INVALIDCHARS = /[<>:"\\|?*#]/g;
|
||||
|
||||
//taken from Obsidian source code
|
||||
export const REG_SECTION_REF_CLEAN = /([:#|^\\\r\n]|%%|\[\[|]])/g;
|
||||
export const REG_BLOCK_REF_CLEAN = /[!"#$%&()*+,.:;<=>?@^`{|}~\/\[\]\\\r\n]/g;
|
||||
// /[!"#$%&()*+,.:;<=>?@^`{|}~\/\[\]\\]/g;
|
||||
export const REG_BLOCK_REF_CLEAN = /[!"#$%&()*+,.:;<=>?@^`{|}~/[\]\\\r\n]/g;
|
||||
// /[!"#$%&()*+,.:;<=>?@^`{|}~/[\]\\]/g;
|
||||
// https://discord.com/channels/686053708261228577/989603365606531104/1000128926619816048
|
||||
// /\+|\/|~|=|%|\(|\)|{|}|,|&|\.|\$|!|\?|;|\[|]|\^|#|\*|<|>|&|@|\||\\|"|:|\s/g;
|
||||
export const IMAGE_TYPES = ["jpeg", "jpg", "png", "gif", "svg", "webp", "bmp", "ico", "jtif", "tif", "jfif", "avif"];
|
||||
export const IMAGE_TYPES = [
|
||||
"jpeg",
|
||||
"jpg",
|
||||
"png",
|
||||
"gif",
|
||||
"svg",
|
||||
"webp",
|
||||
"bmp",
|
||||
"ico",
|
||||
"jtif",
|
||||
"tif",
|
||||
"jfif",
|
||||
"avif",
|
||||
];
|
||||
export const ANIMATED_IMAGE_TYPES = ["gif", "webp", "apng", "svg"];
|
||||
export const EXPORT_TYPES = ["svg", "dark.svg", "light.svg", "png", "dark.png", "light.png"];
|
||||
export const EXPORT_TYPES = [
|
||||
"svg",
|
||||
"dark.svg",
|
||||
"light.svg",
|
||||
"png",
|
||||
"dark.png",
|
||||
"light.png",
|
||||
];
|
||||
export const MAX_IMAGE_SIZE = 500;
|
||||
export const CARD_WIDTH = 400;
|
||||
export const CARD_HEIGHT = 500;
|
||||
export const VIDEO_TYPES = ["mp4","webm","ogv","mov","mkv","avi","m4v","wmv"];
|
||||
export const AUDIO_TYPES = ["mp3","wav", "m4a", "3gp", "flac", "ogg", "oga", "opus", "aac", "aiff", "aif", "mid", "midi"];
|
||||
export const VIDEO_TYPES = [
|
||||
"mp4",
|
||||
"webm",
|
||||
"ogv",
|
||||
"mov",
|
||||
"mkv",
|
||||
"avi",
|
||||
"m4v",
|
||||
"wmv",
|
||||
];
|
||||
export const AUDIO_TYPES = [
|
||||
"mp3",
|
||||
"wav",
|
||||
"m4a",
|
||||
"3gp",
|
||||
"flac",
|
||||
"ogg",
|
||||
"oga",
|
||||
"opus",
|
||||
"aac",
|
||||
"aiff",
|
||||
"aif",
|
||||
"mid",
|
||||
"midi",
|
||||
];
|
||||
export const CODE_TYPES = ["json", "css", "js"];
|
||||
|
||||
export const FRONTMATTER_KEYS:{[key:string]: {name: string, type: string, depricated?:boolean}} = {
|
||||
"plugin": {name: "excalidraw-plugin", type: "text"},
|
||||
"export-transparent": {name: "excalidraw-export-transparent", type: "checkbox"},
|
||||
"mask": {name: "excalidraw-mask", type: "checkbox"},
|
||||
"export-dark": {name: "excalidraw-export-dark", type: "checkbox"},
|
||||
"export-svgpadding": {name: "excalidraw-export-svgpadding", type: "number", depricated: true},
|
||||
"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"},
|
||||
"onload-script": {name: "excalidraw-onload-script", type: "text"},
|
||||
"linkbutton-opacity": {name: "excalidraw-linkbutton-opacity", type: "number"},
|
||||
"default-mode": {name: "excalidraw-default-mode", type: "text"},
|
||||
"font": {name: "excalidraw-font", type: "text"},
|
||||
"font-color": {name: "excalidraw-font-color", type: "text"},
|
||||
"border-color": {name: "excalidraw-border-color", type: "text"},
|
||||
"md-css": {name: "excalidraw-css", type: "text"},
|
||||
"autoexport": {name: "excalidraw-autoexport", type: "text"},
|
||||
"iframe-theme": {name: "excalidraw-iframe-theme", type: "text", depricated: true},
|
||||
"embeddable-theme": {name: "excalidraw-embeddable-theme", type: "text"},
|
||||
"open-as-markdown": {name: "excalidraw-open-md", type: "checkbox"},
|
||||
"embed-as-markdown": {name: "excalidraw-embed-md", type: "checkbox"},
|
||||
export const FRONTMATTER_KEYS: {
|
||||
[key: string]: { name: string; type: string; depricated?: boolean };
|
||||
} = {
|
||||
plugin: { name: "excalidraw-plugin", type: "text" },
|
||||
"export-transparent": {
|
||||
name: "excalidraw-export-transparent",
|
||||
type: "checkbox",
|
||||
},
|
||||
mask: { name: "excalidraw-mask", type: "checkbox" },
|
||||
"export-dark": { name: "excalidraw-export-dark", type: "checkbox" },
|
||||
"export-svgpadding": {
|
||||
name: "excalidraw-export-svgpadding",
|
||||
type: "number",
|
||||
depricated: true,
|
||||
},
|
||||
"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" },
|
||||
"onload-script": { name: "excalidraw-onload-script", type: "text" },
|
||||
"linkbutton-opacity": {
|
||||
name: "excalidraw-linkbutton-opacity",
|
||||
type: "number",
|
||||
},
|
||||
"default-mode": { name: "excalidraw-default-mode", type: "text" },
|
||||
font: { name: "excalidraw-font", type: "text" },
|
||||
"font-color": { name: "excalidraw-font-color", type: "text" },
|
||||
"border-color": { name: "excalidraw-border-color", type: "text" },
|
||||
"md-css": { name: "excalidraw-css", type: "text" },
|
||||
autoexport: { name: "excalidraw-autoexport", type: "text" },
|
||||
"iframe-theme": {
|
||||
name: "excalidraw-iframe-theme",
|
||||
type: "text",
|
||||
depricated: true,
|
||||
},
|
||||
"embeddable-theme": { name: "excalidraw-embeddable-theme", type: "text" },
|
||||
"open-as-markdown": { name: "excalidraw-open-md", type: "checkbox" },
|
||||
"embed-as-markdown": { name: "excalidraw-embed-md", type: "checkbox" },
|
||||
};
|
||||
|
||||
export const CaptureUpdateAction = {
|
||||
@@ -299,7 +382,12 @@ export const CaptureUpdateAction = {
|
||||
EVENTUALLY: "EVENTUALLY",
|
||||
} as const;
|
||||
|
||||
export const EMBEDDABLE_THEME_FRONTMATTER_VALUES = ["light", "dark", "auto", "dafault"];
|
||||
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";
|
||||
@@ -307,14 +395,12 @@ export const ICON_NAME = "excalidraw-icon";
|
||||
export const MAX_COLORS = 5;
|
||||
export const COLOR_FREQ = 6;
|
||||
export const RERENDER_EVENT = "excalidraw-embed-rerender";
|
||||
export const BLANK_DRAWING =
|
||||
`{"type":"excalidraw","version":2,"source":"${GITHUB_RELEASES+PLUGIN_VERSION}","elements":[],"appState":{"gridSize":null,"viewBackgroundColor":"#ffffff"}}`;
|
||||
export const DARK_BLANK_DRAWING =
|
||||
`{"type":"excalidraw","version":2,"source":"${GITHUB_RELEASES+PLUGIN_VERSION}","elements":[],"appState":{"theme":"dark","gridSize":null,"viewBackgroundColor":"#ffffff"}}`;
|
||||
export const BLANK_DRAWING = `{"type":"excalidraw","version":2,"source":"${GITHUB_RELEASES + PLUGIN_VERSION}","elements":[],"appState":{"gridSize":null,"viewBackgroundColor":"#ffffff"}}`;
|
||||
export const DARK_BLANK_DRAWING = `{"type":"excalidraw","version":2,"source":"${GITHUB_RELEASES + PLUGIN_VERSION}","elements":[],"appState":{"theme":"dark","gridSize":null,"viewBackgroundColor":"#ffffff"}}`;
|
||||
export const FRONTMATTER = [
|
||||
"---",
|
||||
"",
|
||||
`${FRONTMATTER_KEYS["plugin"].name}: parsed`,
|
||||
`${FRONTMATTER_KEYS.plugin.name}: parsed`,
|
||||
"tags: [excalidraw]",
|
||||
"",
|
||||
"---",
|
||||
@@ -329,14 +415,10 @@ export const TEXT_DISPLAY_RAW_ICON_NAME = "presentation";
|
||||
export const EXIT_FULLSCREEN_ICON_NAME = "exit-fullscreen";*/
|
||||
export const SCRIPTENGINE_ICON_NAME = "ScriptEngine";
|
||||
|
||||
export const KEYBOARD_EVENT_TYPES = [
|
||||
"keydown",
|
||||
"keyup",
|
||||
"keypress"
|
||||
];
|
||||
export const KEYBOARD_EVENT_TYPES = ["keydown", "keyup", "keypress"] as const;
|
||||
|
||||
export const EXTENDED_EVENT_TYPES = [
|
||||
/* "pointerdown",
|
||||
/* "pointerdown",
|
||||
"pointerup",
|
||||
"pointermove",
|
||||
"mousedown",
|
||||
@@ -362,11 +444,10 @@ export const EXTENDED_EVENT_TYPES = [
|
||||
"touchstart",
|
||||
"touchend",
|
||||
"touchmove",*/
|
||||
];
|
||||
] as const;
|
||||
|
||||
//export const TWITTER_REG = /^(?:http(?:s)?:\/\/)?(?:(?:w){3}.)?twitter.com/;
|
||||
|
||||
|
||||
export const COLOR_NAMES = new Map<string, string>();
|
||||
COLOR_NAMES.set("aliceblue", "#f0f8ff");
|
||||
COLOR_NAMES.set("antiquewhite", "#faebd7");
|
||||
@@ -515,3 +596,5 @@ export const DISK_ICON_NAME = "save";
|
||||
export const EXPORT_IMG_ICON = ` <g transform="scale(4.166)" strokeWidth="1.25" fill="none" stroke="currentColor"><path stroke="none" d="M0 0h24v24H0z" fill="none"></path><path d="M15 8h.01"></path><path d="M12 20h-5a3 3 0 0 1 -3 -3v-10a3 3 0 0 1 3 -3h10a3 3 0 0 1 3 3v5"></path><path d="M4 15l4 -4c.928 -.893 2.072 -.893 3 0l4 4"></path><path d="M14 14l1 -1c.617 -.593 1.328 -.793 2.009 -.598"></path><path d="M19 16v6"></path><path d="M22 19l-3 3l-3 -3"></path></g>`;
|
||||
export const EXPORT_IMG_ICON_NAME = `export-img`;
|
||||
export const EXCALIDRAW_ICON = `<path d="M24 17h121v121H24z" style="fill:none" transform="matrix(.8843 0 0 .83471 -21.223 -14.19)"/><path d="M119.81 105.98a.549.549 0 0 0-.53-.12c-4.19-6.19-9.52-12.06-14.68-17.73l-.85-.93c0-.11-.05-.21-.12-.3a.548.548 0 0 0-.34-.2l-.17-.18-.12-.09c-.15-.32-.53-.56-.95-.35-1.58.81-3 1.97-4.4 3.04-1.87 1.43-3.7 2.92-5.42 4.52-.7.65-1.39 1.33-1.97 2.09-.28.37-.07.72.27.87-1.22 1.2-2.45 2.45-3.68 3.74-.11.12-.17.28-.16.44.01.16.09.31.22.41l2.16 1.65s.01.03.03.04c3.09 3.05 8.51 7.28 14.25 11.76.85.67 1.71 1.34 2.57 2.01.39.47.76.94 1.12 1.4.19.25.55.3.8.11.13.1.26.21.39.31a.57.57 0 0 0 .8-.1c.07-.09.1-.2.11-.31.04 0 .07.03.1.03.15 0 .31-.06.42-.18l10.18-11.12a.56.56 0 0 0-.04-.8l.01-.01Zm-29.23-3.85c.07.09.14.17.21.25 1.16.98 2.4 2.04 3.66 3.12l-5.12-3.91s-.32-.22-.52-.36c-.11-.08-.21-.16-.31-.24l-.38-.32s.07-.07.1-.11l.35-.35c1.72-1.74 4.67-4.64 6.19-6.06-1.61 1.62-4.87 6.37-4.17 7.98h-.01Zm17.53 13.81-4.22-3.22c-1.65-1.71-3.43-3.4-5.24-5.03 2.28 1.76 4.23 3.25 4.52 3.51 2.21 1.97 2.11 1.61 3.63 2.91l1.83 1.33c-.18.16-.36.33-.53.49l.01.01Zm1.06.81-.08-.06c.16-.13.33-.25.49-.38l-.4.44h-.01Zm-66.93-65.3c.14.72.27 1.43.4 2.11.69 3.7 1.33 7.03 2.55 9.56l.48 1.92c.19.73.46 1.64.71 1.83 2.85 2.52 7.22 6.28 11.89 9.82.21.16.5.15.7-.01.01.02.03.03.04.04.11.1.24.15.38.15.16 0 .31-.06.42-.19 5.98-6.65 10.43-12.12 13.6-16.7.2-.25.3-.54.29-.84.2-.24.41-.48.6-.68a.558.558 0 0 0-.1-.86.578.578 0 0 0-.17-.36c-1.39-1.34-2.42-2.31-3.46-3.28-1.84-1.72-3.74-3.5-7.77-7.51-.02-.02-.05-.04-.07-.06a.555.555 0 0 0-.22-.14c-1.11-.39-3.39-.78-6.26-1.28-4.22-.72-10-1.72-15.2-3.27h-.04v-.01s-.02 0-.03.02h-.01l.04-.02s-.31.01-.37.04c-.08.04-.14.09-.19.15-.05.06-.09.12-.47.2-.38.08.08 0 .11 0h-.11v.03c.07.34.05.58.16.97-.02.1.21 1.02.24 1.11l1.83 7.26h.03Zm30.95 6.54s-.03.04-.04.05l-.64-.71c.22.21.44.42.68.66Zm-7.09 9.39s-.07.08-.1.12l-.02-.02c.04-.03.08-.07.13-.1h-.01Zm-7.07 8.47Zm3.02-28.57c.35.35 1.74 1.65 2.06 1.97-1.45-.66-5.06-2.34-6.74-2.88 1.65.29 3.93.66 4.68.91Zm-19.18-2.77c.84 1.44 1.5 6.49 2.16 11.4-.37-1.58-.69-3.12-.99-4.6-.52-2.56-1-4.85-1.67-6.88.14.01.31.03.49.05 0 .01 0 .02.02.03h-.01Zm-.29-1.21c-.23-.02-.44-.04-.62-.05-.02-.04-.03-.08-.04-.12l.66.18v-.01Zm-2.22.45v-.02.02Zm78.54-1.18c.04-.23-1.1-1.24-.74-1.26.85-.04.86-1.35 0-1.31-1.13.06-2.27.32-3.37.53-1.98.37-3.95.78-5.92 1.21-4.39.94-8.77 1.93-13.1 3.11-1.36.37-2.86.7-4.11 1.36-.42.22-.4.67-.17.95-.09.05-.18.08-.28.09-.37.07-.74.13-1.11.19a.566.566 0 0 0-.39.86c-2.32 3.1-4.96 6.44-7.82 9.95-2.81 3.21-5.73 6.63-8.72 10.14-9.41 11.06-20.08 23.6-31.9 34.64-.23.21-.24.57-.03.8.05.06.12.1.19.13-.16.15-.32.3-.48.44-.1.09-.14.2-.16.32-.08.08-.16.17-.23.25-.21.23-.2.59.03.8.23.21.59.2.8-.03.04-.04.08-.09.12-.13a.84.84 0 0 1 1.22 0c.69.74 1.34 1.44 1.95 2.09l-1.38-1.15a.57.57 0 0 0-.8.07c-.2.24-.17.6.07.8l14.82 12.43c.11.09.24.13.37.13.15 0 .29-.06.4-.17l.36-.36a.56.56 0 0 0 .63-.12c20.09-20.18 36.27-35.43 54.8-49.06.17-.12.25-.32.23-.51a.57.57 0 0 0 .48-.39c3.42-10.46 4.08-19.72 4.28-24.27 0-.03.01-.05.02-.07.02-.05.03-.1.04-.14.03-.11.05-.19.05-.19.26-.78.17-1.53-.15-2.15v.02ZM82.98 58.94c.9-1.03 1.79-2.04 2.67-3.02-5.76 7.58-15.3 19.26-28.81 33.14 9.2-10.18 18.47-20.73 26.14-30.12Zm-32.55 52.81-.03-.03c.11.02.19.04.2.04a.47.47 0 0 0-.17 0v-.01Zm6.9 6.42-.05-.04.03-.03c.02 0 .03.02.04.02 0 .02-.02.03-.03.05h.01Zm8.36-7.21 1.38-1.44c.01.01.02.03.03.05-.47.46-.94.93-1.42 1.39h.01Zm2.24-2.21c.26-.3.56-.65.87-1.02.01-.01.02-.03.04-.04 3.29-3.39 6.68-6.82 10.18-10.25.02-.02.05-.04.07-.06.86-.66 1.82-1.39 2.72-2.08-4.52 4.32-9.11 8.78-13.88 13.46v-.01Zm21.65-55.88c-1.86 2.42-3.9 5.56-5.63 8.07-5.46 7.91-23.04 27.28-23.43 27.65-2.71 2.62-10.88 10.46-16.09 15.37-.14.13-.25.24-.34.35a.794.794 0 0 1 .03-1.13c24.82-23.4 39.88-42.89 46-51.38-.13.33-.24.69-.55 1.09l.01-.02Zm16.51 7.1-.01.02c0-.02-.02-.07.01-.02Zm-.91-5.13Zm-5.89 9.45c-2.26-1.31-3.32-3.27-2.71-5.25l.19-.66c.08-.19.17-.38.28-.57.59-.98 1.49-1.85 2.52-2.36.05-.02.1-.03.15-.04a.795.795 0 0 1-.04-.43c.05-.31.25-.58.66-.58.67 0 2.75.62 3.54 1.3.24.19.47.4.68.63.3.35.74.92.96 1.33.13.06.23.62.38.91.14.46.2.93.18 1.4 0 .02 0 .02.01.03-.03.07 0 .37-.04.4-.1.72-.36 1.43-.75 2.05-.04.05-.07.11-.11.16 0 .01-.02.02-.03.04-.3.43-.65.83-1.08 1.13-1.26.89-2.73 1.16-4.2.79a6.33 6.33 0 0 1-.57-.25l-.02-.03Zm16.27-1.63c-.49 2.05-1.09 4.19-1.8 6.38-.03.08-.03.16-.03.23-.1.01-.19.05-.27.11-4.44 3.26-8.73 6.62-12.98 10.11 3.67-3.32 7.39-6.62 11.23-9.95a6.409 6.409 0 0 0 2.11-3.74l.56-3.37.03-.1c.25-.71 1.34-.4 1.17.33h-.02Z" style="fill:currentColor;fill-rule:nonzero" transform="translate(-26.41 -29.49)"/>`;
|
||||
|
||||
export const LOGO_EXCALIDRAW_MASTERY = `data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAMQAAADECAYAAADApo5rAAAQAElEQVR4AeydB5xU1fn3n1lQEaWIBV0pSwdB0bAWgsCuDWPsRo389QWUptFoYmJMVFiwxBaTqImIRECxJ7H3sgtobGgUKzYWVGpARGwI7Hu/9865c26buTNzp+zu8OHZ0+t9fud5nnPOvVMmpX+lGSjNgD0DJUDYU5Ejz8SJFQKNHVsl48aNtmn8+Mmi04QJMx1hPS9loRx1sVRtYgZKgEjMReY+GB4GVgw+blytwfi1BoM3yJYti00qK6uVWGymTSI1olNDw2hHWM9LWWj8+AajzsUm0QYgol2oBBhj+rL/XwJEunMI88N8MD9MCZPC9DCwYvBYrMpg/Kp0qw6Zv8LIV2HWD4hoF7IAs9gEogIKfTUyl/6Hn4ESIFLNFUzlZn6YT6TGZEopqn9OoADU8eMXSwkgoR9SIwJE6DFln1GBAGaCqSJg/ooOO4iiqp7dRdHo/SpFJxWPq/LjZjGoClGShLEwJgCOlMui0qZatKypDiztccEgMIpSgQCBSIWE/AfTwsQw9+TDDxWo9uwJsnjS76XhL1ebLn6o9uyJomjmyJNEJxWPS143USf5qZ+2aDNkF1U2xlQjSDnAoaSHSm3mbvMGREISNJgMYoEgJUvA/BBMCXMqhoeJCdcYgICqevYwpULKCkNkoD2IOgEC9dMWbar2CZNWZUigEFWSJSE9AAcLAgsDKc2UmicgePAYxKgQIUBgMWJ3x6rPyg1TwoDFwDv0kb4ACj+QhOijU3KwcxWiUFPL0nwAoUsDQMBOUJKnCYMhAVBRYH6YDABUGat+kmJFlcQYFEisMUwwQV2VWoJUGBsGnItYBjlzV1Qjy11nmj4geJhIhBDSAAYCBDAPlDEAcve8Mq6ZsVUZYGZMgJvxIU2qkoPDUqm2bKk1d6qYy4x70DgKNl1A8PBCAAFGcYOAuHw8vvolS6Xm8iulbt4L+WjO0QZjRHoocDAHjgzOgAKGJTGasJ3R9AABENg5SSERYAiYgJWSVZOwkwdyG5o1507p1m8vmWIAovrwn5rAyG2LwbUzduaAuUgpNdjCZYeKOW6CwGg6gAAISiLw0AKevwIBDx8mCMiWs2glFcaMP8vRxmwDIJa0eN4Rn88AwAgtNZhjBQzmPp8dzWFbTQMQCggYywGTBRDYngQEPPiAbJFFz5pzl8wymLxu3vMCCPDD8EoqqIaqhh5oesljSYsjTckBYMgPURYSiUm+/jFHzBULB3MX2C7AwMbgGQRmajwJjRsQiGz2zwOAwEPlYSog5OuxwPRjxp8pMHX14QkGh+H1Pky+6EKZOf3vgqvHAw4AQH6IeqBu/fbUs0XiT1UJcxgCGBVGPTXmpUOeiRForP8bJyAQ0eiwiOyA02SAwOrGw8z3w4Ghk7WJVFj83kKpMQBBPlzCAIM04oqNQgODZ8Kz4RkV2yBC9KfxAYIDIwxmRLXPANGB8y0R3N2AsVUcDD761JECEQ/j1z75iJlcPcKSHkgUJALAII08ENKjomsXMy9/Rhn14BaSQgGDZ9NI1ajGAwhWHE6XuerswxE8KA7R2CXxSc5rFCBQDQ4fdqCpFsHcMLxicFSguvmWAY1EQTXC3qAceSDqIY04iPK4xUDMN9IXKYzfp0+WGsUz49n5ZCjGqMYBCPRSpILP6TIPQ6lHVcbBUzFMMsys+sHukfIrF2mgwKDnBRQqD64eRroQV2zE/HOWwTPw7RvPDGmBZPfNUFyRxQ8Idi/QS33mDfWIFYqVyie5YFEwOas7HWCFVys/YTfpalD90qWOZAUaIqkTtxgJUPAMeBYBwKgQJDvPMvMB5KVk8QICMYu49dlB4gEUi3oU9JRQlVSaztgqzs+t6JKwF0gHTLgQNghuMRPPBWAkUVutnSiebZEOpDgBkURFqurZ3Xy3oKpI1KOg56okBOlzjbMIXEU64+tqkS4FUKtU/sYABtVXXCW5q4xnRdhFFVLEKlTxAQJdM0BFQhyjr7omuCiDOnO7VaEqw9DWAaMGoKtPOoj0eJW32F2kxcyRJ5u3a336igplfXXEJ7GQUcUFCHRMdE3XjDC5qEiIY1dS0QYBhGJ6VB+3HcGuk0onb+0TjwhAUQPSJYQer9Ibg8tz45lhW+B39bnCCKNCTTbcovlfPIAIsBcQu0xoVZGrSH5PFEZX8W47gjTOHBq+WSecOehMr4OhsalLary6CxiQ7Eh4PT7urzG/FBIPFNqJBhDZjAIDCzCwPeeqB12UiXRFN5pgV+1QTVeBUg0AiaLy6Ma5imuMLqDgefqCgmfPFRx4ocCDKywgmIDNm2caW3JV7nmYGX/53h3fmMJKJaLPbjuCuCBasiSx/arXEZS/scQDClQoX1BwBQdjG54o4IAKBwgGHgAG7AVWkwLOSyRNoxYphmbVh8JUrKtX1BGmTGPKAyhQg336bO1AwRs+ifmIKgwgGLAPGFhBAENjtBf8HhbMrKs8YQERNp9fm40ljmcNKHBdfS4oKPIPiCRgYIKaChjUQ1YSgrC+8hP2Ix0MTcGg9hujigMM2Ii4Ki7uFgwU+QVECjDEJyOnTiErD2NY66DRjfJC9juXbQOGYgJF/gDRTMGA2qQYKh3DWpVpDm4xgSJ/gAiwGVCTmvJDBxBKbdLVoaAx63koG5SvqcWnBEWeBpwfQPicMzABTR0Mfs/QfWLtzqNvuep3ntz5mmIYnghUn3gLLw+Dzj0grOsYjnMGBt6cwJDpSp9puTzwTc6agDd8QcFbePBSzlq2Ks4tILi1KlIjrn8curmimk0wDTui2cyJe6AKFO54I5zzu0+5AwRg8Lm1Wuhzhg0bvhbUlrvv+5esWLnSmOPc/9d3i5SN8N333xvtr5Jvvv1WGrQuqHQtKmvvylWr5P6HHpE77r7XHPt3332XdZ1hK9DbfuqZ5+TL9etDFbVAMcEv72iBt/xSIojLDSDYUfIBA5Ih3+cMDQ0N5neRJl/2R+m7977SZpfdhU/DnDLqDLl4ymWyadOmCKYxeRW66kN/Pl+2XBZ98KHALB9+9LG8/c47snzFStmyZYvoebMBxw8//CCAvueAfWTXit5y/M9PlVNPH2+OvW3HznLZldfI119/k7zjGaZS76zb7xR32yOOPl7a79pFTjp1tHz2+bKUtcMrM0ee5M5XIWVlM80fsnSnRBDODSDYUXJ1jqsYkCs6J0GY7oMPP5LzfnuhdCivMD/8NfWKq0wm1Bu8/8FHBIbU43Lh143j1f/7n/xvzRpHM1u2NMiq1avlAwMcGzdudKSlG4AZ//q3abJT5+4C6D/+ZLGnCsByydTLZeD+Q+TV1173pGca8elnn8svzvuNtO3YScZMOEv82qbu+/79gHTfY6DcdsfdwrMiLojgGZ+7TxXG6lEbVCab+OgBgeHD7UWtV1U9u5u/kqNFRe5lYllRWfU7du0lfQZWCoyx7ssvA9ta+8UXMu+F/wSmR5Xwn5detqtqMJjfDrg83xtqVLv27Vyx4YIA4err/io7d+luLgTr13+VsiAMO+SgEaEYM1lliwxphwTq0ru//H36DINXtyTLbqYBylHjJsp11/8tFCgAhlkw8afC/CJ5IhyJL1pAjB1bZfTKYURbuuBEIzo3/1E7YIROPfuZkuDyq64VVuGwrT39bG3O1CbUAhjloppLw3ZHkgHGr5Jvv/1Obp09R8p79JHfXTxZCPvlC4qDMVnNZ8+5S1hUgvK548m78O135LCjjpO+e+9r2ijuPGHCF1w0Sf794MNJs8JDSAkWVkdGdp4snnNEZxOIFhDodq7ezPTqgK4c6QdZDefcdY/sc8BQUz+GEZYtX5F+RUaJBa//19DlVxu+6P7DlIAUtQBjVq+5vHxXPZjU/+DDjwamb968We791/2GXVQpZ5x5toSRCEGVbTFsF+pIxZiUV0D4cfVhMnC/IcKCQnymRNtjzzxHXlnwWtIqAMXMkSd788Bz2KzelIxiogMEh2/cade6YaG6hxaTuRcGQPX46XEnmTrqaWdMkDcWvpV5hfGSSz/9TN57f1E8lJ1DH++695/Stc8Ac7Vm9U23xspB+9hF7rv/Ac+qrRhycNWhcvJpY4T+2wWy8MCYE8/5lbzz3vuBtbxrpGEYA4SXXnk1MF+6Cai1p0/4hWlHJStrgcLHyG5oiOw11GgAwYcBfOyGmsMPTTa+UGkYaudfeJG5O4S++9iTT4XSUUNVbmSCwWrnzTd8mf+njpdfXSCDDSYdOXpsUpWt8kcJhvdrsXy3hARZuWq16JIPFeyEU04zV+YojWHVD4z9Cy+u8ahdiwwb4ZgTT5H+gw7IWiKottwuQLzi6j95FgB3PmwJX9UJ29WdOYNw9oBAXPl8GGCmn3gL2UFUIrVth6GG4YUaErJ42tleePEl4Xwi7YJGgUUGsxx70kg5YPghoXZsynfbzSgV/J90BRq2hBfXLzG3R6+89s/mzoxbBQuuKbOUR594Uh5/6mmzMGMDCGxXP/To42ZcLv/cdMut8vx/XkrZxEyDt5AWroyjo9iKzR4QPlusHL75dNjVf2cQdeM/xm4MakCqbTtnyexDb739rnz62WdpVYSYP/H/Rhk6/L4SllnaGztI04yHrmiSsfWJ/uymZcuX231hexSD+feTpohbBWvfvr2dLyoP0o4t6qNO+HlaY4uifbacsb1SLX7wFuq4q80K8eFFVx6RFBHZAQIL36UqWSItvN2wZu1aYRJ269ZHUIkwFNFnU/Q70mS2Xz/8+JO06vzWOGFOZQi6K1y37kuZNuNWmwASRr2bdDWpzlDnggzmdevWyY47dnA3k3X4zbfelkcefyLrejKpAAk193nrI9DJysNnkCMPvAhPOiLTC2QHiFjMY8z4INfTI1YhDLT/N3ai7NSpu2mAprNV6qkwgohnnqtLu5avv/467
Line truncated
|
||||
@@ -0,0 +1,852 @@
|
||||
import type { ExcalidrawElement } from "@zsviczian/excalidraw/types/element/src/types";
|
||||
|
||||
type JsonValue =
|
||||
| string
|
||||
| number
|
||||
| boolean
|
||||
| null
|
||||
| { [key: string]: JsonValue }
|
||||
| JsonValue[];
|
||||
|
||||
type SerializedExcalidrawElement = {
|
||||
id: string;
|
||||
type: string;
|
||||
isDeleted: boolean;
|
||||
index: string;
|
||||
[key: string]: JsonValue;
|
||||
};
|
||||
|
||||
export const emptyDrawingElements: SerializedExcalidrawElement[] = [
|
||||
{
|
||||
id: "Oz2QdWCi",
|
||||
type: "rectangle",
|
||||
x: -2274.162907130364,
|
||||
y: -1142.3983283445061,
|
||||
width: 783.7114117816327,
|
||||
height: 529.5216919049586,
|
||||
angle: 0,
|
||||
strokeColor: "black",
|
||||
backgroundColor: "#E6E6E5",
|
||||
fillStyle: "solid",
|
||||
strokeWidth: 4,
|
||||
strokeStyle: "solid",
|
||||
roughness: 1,
|
||||
opacity: 100,
|
||||
groupIds: [],
|
||||
frameId: null,
|
||||
index: "a3",
|
||||
roundness: {
|
||||
type: 3,
|
||||
},
|
||||
seed: 2027540967,
|
||||
version: 418,
|
||||
versionNonce: 1735324542,
|
||||
isDeleted: false,
|
||||
boundElements: [],
|
||||
updated: 1778337140133,
|
||||
link: null,
|
||||
locked: false,
|
||||
hasTextLink: false,
|
||||
},
|
||||
{
|
||||
id: "Bu3M1Rba",
|
||||
type: "text",
|
||||
x: -2243.8551748723603,
|
||||
y: -1142.3983282791253,
|
||||
width: 723.095947265625,
|
||||
height: 149.40129644433168,
|
||||
angle: 0,
|
||||
strokeColor: "black",
|
||||
backgroundColor: "#E6E6E5",
|
||||
fillStyle: "solid",
|
||||
strokeWidth: 2,
|
||||
strokeStyle: "solid",
|
||||
roughness: 1,
|
||||
opacity: 100,
|
||||
groupIds: [],
|
||||
frameId: null,
|
||||
index: "aB",
|
||||
roundness: null,
|
||||
seed: 701511497,
|
||||
version: 236,
|
||||
versionNonce: 598083561,
|
||||
isDeleted: false,
|
||||
boundElements: [],
|
||||
updated: 1778336273821,
|
||||
locked: false,
|
||||
text: "PLACEHOLDER",
|
||||
rawText: "PLACEHOLDER",
|
||||
fontSize: 119.52103715546534,
|
||||
fontFamily: 8,
|
||||
textAlign: "left",
|
||||
verticalAlign: "top",
|
||||
containerId: null,
|
||||
originalText: "PLACEHOLDER",
|
||||
autoResize: true,
|
||||
lineHeight: 1.25,
|
||||
hasTextLink: false,
|
||||
link: null,
|
||||
},
|
||||
{
|
||||
points: [
|
||||
[0, 0],
|
||||
[-10.447891750387207, 6.919391131677716],
|
||||
[-16.282984196683074, 12.631414763648362],
|
||||
[-19.671442261868517, 19.334062178748006],
|
||||
[-21.852507973483135, 24.637953873112647],
|
||||
[-23.82527027162518, 32.77969592387441],
|
||||
[-21.43393414083056, 41.15312014558172],
|
||||
[-22.871017575649848, 46.14459969832669],
|
||||
[-26.34666443382062, 56.57154027283925],
|
||||
[-26.810094621742596, 68.85216624293122],
|
||||
[-26.34666443382062, 80.90106828003505],
|
||||
[-24.261272783307376, 93.18169425012704],
|
||||
[-19.858800905400887, 106.38914523995447],
|
||||
[-16.573296509900576, 115.22541077698732],
|
||||
[-8.504999326612035, 116.5843795595332],
|
||||
[0.09895008049422967, 119.13369171177577],
|
||||
[6.790903977079977, 122.63900769732602],
|
||||
[14.12018971050622, 127.4189752004618],
|
||||
[21.44947544393198, 134.27027117332844],
|
||||
[27.504109659771867, 141.75888682694068],
|
||||
[33.08074195895783, 150.84083207265374],
|
||||
[37.82326380221856, 160.57538112825472],
|
||||
[42.795497720257764, 152.49547213571557],
|
||||
[57.8566341056647, 127.47080768566397],
|
||||
[59.94202575617803, 121.67806292204587],
|
||||
[56.466378898007186, 115.42190564856014],
|
||||
[48.81994873880972, 103.60469218833597],
|
||||
[43.25892790817966, 94.10459431161321],
|
||||
[39.31985086208695, 84.60449643489045],
|
||||
[36.77104670170581, 75.10439855816752],
|
||||
[35.84420400391614, 65.37258558748393],
|
||||
[34.91736130612643, 56.10419396569499],
|
||||
[34.91736130612643, 50.3114492020769],
|
||||
[34.685655051192526, 44.518704438458975],
|
||||
[33.19125819237214, 40.71567726425276],
|
||||
[0, 0],
|
||||
],
|
||||
lastCommittedPoint: null,
|
||||
startBinding: null,
|
||||
endBinding: null,
|
||||
startArrowhead: null,
|
||||
endArrowhead: null,
|
||||
id: "WB85P5W_xK26DjdYIJnA0",
|
||||
type: "line",
|
||||
x: -1856.0996309335153,
|
||||
y: -837.6181728205813,
|
||||
width: 86.75212037792063,
|
||||
height: 160.57538112825472,
|
||||
angle: 0,
|
||||
strokeColor: "black",
|
||||
backgroundColor: "#ffffff",
|
||||
fillStyle: "solid",
|
||||
strokeWidth: 4,
|
||||
strokeStyle: "solid",
|
||||
roughness: 1,
|
||||
opacity: 100,
|
||||
roundness: null,
|
||||
seed: 1032008711,
|
||||
version: 1685,
|
||||
versionNonce: 1398565385,
|
||||
updated: 1778336273821,
|
||||
isDeleted: false,
|
||||
groupIds: [
|
||||
"df44dfgWcHwiNzu8Yy342",
|
||||
"TXjbtV7-h_Ule7avoyuzF",
|
||||
"1BvUccs30Onzs-FiAe46Q",
|
||||
],
|
||||
boundElements: [],
|
||||
link: null,
|
||||
locked: false,
|
||||
frameId: null,
|
||||
hasTextLink: false,
|
||||
index: "aC",
|
||||
polygon: true,
|
||||
},
|
||||
{
|
||||
points: [
|
||||
[0, 0],
|
||||
[8.197954147025316, 5.899767115283074],
|
||||
[15.496052318242121, 11.952965908108858],
|
||||
[21.84723636511511, 20.396043600124575],
|
||||
[29.355114926299706, 30.939022819436175],
|
||||
[32.24099701375395, 38.98910733433114],
|
||||
[34.233670196880226, 46.96533247542913],
|
||||
[41.48226610160632, 43.769077876490606],
|
||||
[51.53159917464678, 41.220600849460574],
|
||||
[61.41020009933892, 40.742605010854355],
|
||||
[69.02887285744329, 41.61429157920188],
|
||||
[65.74336846194296, 32.77802604216904],
|
||||
[61.340896584036486, 19.57057505234159],
|
||||
[59.25550493352324, 7.289949082249611],
|
||||
[58.79207474560127, -4.758952954854223],
|
||||
[59.25550493352324, -17.039578924946202],
|
||||
[62.73115179169401, -27.46651949945876],
|
||||
[63.732723780645124, -33.09628661979107],
|
||||
[61.52623518769919, -41.397474977966425],
|
||||
[58.96896100416394, -48.308392883522885],
|
||||
[54.72592659464387, -55.25968659986459],
|
||||
[49.373173821378195, -60.070292848469315],
|
||||
[42.98945194412115, -65.46539330441325],
|
||||
[36.66104112904977, -69.11943650060215],
|
||||
[11.059861428999364, -47.16184285673294],
|
||||
[8.279342174657316, -43.91791109252307],
|
||||
[7.352508315894605, -38.58857883877297],
|
||||
[0, 0],
|
||||
],
|
||||
lastCommittedPoint: null,
|
||||
startBinding: null,
|
||||
endBinding: null,
|
||||
startArrowhead: null,
|
||||
endArrowhead: null,
|
||||
id: "jaoiKgNhDiPBePRdUqxpg",
|
||||
type: "line",
|
||||
x: -1941.4700941541105,
|
||||
y: -762.9660552388243,
|
||||
width: 69.02887285744329,
|
||||
height: 116.08476897603128,
|
||||
angle: 0,
|
||||
strokeColor: "black",
|
||||
backgroundColor: "#ffffff",
|
||||
fillStyle: "solid",
|
||||
strokeWidth: 4,
|
||||
strokeStyle: "solid",
|
||||
roughness: 1,
|
||||
opacity: 100,
|
||||
roundness: null,
|
||||
seed: 1529682727,
|
||||
version: 1952,
|
||||
versionNonce: 573849833,
|
||||
updated: 1778336273821,
|
||||
isDeleted: false,
|
||||
groupIds: [
|
||||
"df44dfgWcHwiNzu8Yy342",
|
||||
"TXjbtV7-h_Ule7avoyuzF",
|
||||
"1BvUccs30Onzs-FiAe46Q",
|
||||
],
|
||||
boundElements: [],
|
||||
link: null,
|
||||
locked: false,
|
||||
frameId: null,
|
||||
hasTextLink: false,
|
||||
index: "aD",
|
||||
polygon: true,
|
||||
},
|
||||
{
|
||||
id: "vHMoH1-tmqJyIlQI_N-9W",
|
||||
type: "line",
|
||||
x: -1921.0599543415585,
|
||||
y: -644.9810509263477,
|
||||
width: 62.800965084190814,
|
||||
height: 117.98500431247697,
|
||||
angle: 0,
|
||||
strokeColor: "black",
|
||||
backgroundColor: "#ffffff",
|
||||
fillStyle: "solid",
|
||||
strokeWidth: 4,
|
||||
strokeStyle: "solid",
|
||||
roughness: 1,
|
||||
opacity: 100,
|
||||
groupIds: [
|
||||
"df44dfgWcHwiNzu8Yy342",
|
||||
"TXjbtV7-h_Ule7avoyuzF",
|
||||
"1BvUccs30Onzs-FiAe46Q",
|
||||
],
|
||||
frameId: null,
|
||||
index: "aE",
|
||||
roundness: null,
|
||||
seed: 1967988295,
|
||||
version: 1434,
|
||||
versionNonce: 967719881,
|
||||
isDeleted: false,
|
||||
boundElements: [],
|
||||
updated: 1778336273821,
|
||||
link: null,
|
||||
locked: false,
|
||||
points: [
|
||||
[0, 0],
|
||||
[4.46816131572484, -10.646107161983204],
|
||||
[7.657815585788744, -19.759423286426326],
|
||||
[11.0014611530763, -27.87499585153127],
|
||||
[13.73335194330698, -37.83413467951031],
|
||||
[15.100349941381728, -48.31443721386236],
|
||||
[15.404122123991224, -59.402295701599385],
|
||||
[14.055254945748922, -71.01967183704785],
|
||||
[12.062581762622651, -78.99589697814584],
|
||||
[9.176699675168404, -87.04598149304081],
|
||||
[1.6688211139838078, -97.5889607123524],
|
||||
[-4.682362932889177, -106.03203840436812],
|
||||
[-11.980461104105984, -112.08523719719392],
|
||||
[-20.1784152511313, -117.98500431247697],
|
||||
[-33.05453717435193, -89.49570440727598],
|
||||
[-43.92084001059562, -67.37503763941812],
|
||||
[-47.17390351726269, -59.402295701599385],
|
||||
[-47.39684296019959, -52.037100000668055],
|
||||
[-44.59179940650083, -46.64366703317796],
|
||||
[-39.55022447342473, -41.28924894289286],
|
||||
[0, 0],
|
||||
],
|
||||
startBinding: null,
|
||||
endBinding: null,
|
||||
startArrowhead: null,
|
||||
endArrowhead: null,
|
||||
polygon: true,
|
||||
hasTextLink: false,
|
||||
},
|
||||
{
|
||||
id: "pO7RkEnMMeNY6WXwIwsLu",
|
||||
type: "line",
|
||||
x: -1921.3253543795477,
|
||||
y: -644.9810509263477,
|
||||
width: 103.01529335701053,
|
||||
height: 90.34145357949649,
|
||||
angle: 0,
|
||||
strokeColor: "black",
|
||||
backgroundColor: "#ffffff",
|
||||
fillStyle: "solid",
|
||||
strokeWidth: 4,
|
||||
strokeStyle: "solid",
|
||||
roughness: 1,
|
||||
opacity: 100,
|
||||
groupIds: [
|
||||
"df44dfgWcHwiNzu8Yy342",
|
||||
"TXjbtV7-h_Ule7avoyuzF",
|
||||
"1BvUccs30Onzs-FiAe46Q",
|
||||
],
|
||||
frameId: null,
|
||||
index: "aF",
|
||||
roundness: null,
|
||||
seed: 1321188711,
|
||||
version: 2368,
|
||||
versionNonce: 166058665,
|
||||
isDeleted: false,
|
||||
boundElements: [],
|
||||
updated: 1778336273821,
|
||||
link: null,
|
||||
locked: false,
|
||||
points: [
|
||||
[0, 0],
|
||||
[4.46816131572484, -10.646107161983204],
|
||||
[7.657815585788744, -19.759423286426326],
|
||||
[11.0014611530763, -27.87499585153127],
|
||||
[13.73335194330698, -37.83413467951031],
|
||||
[15.100349941381728, -48.31443721386236],
|
||||
[15.404122123991224, -59.402295701599385],
|
||||
[14.055254945748922, -71.01967183704785],
|
||||
[21.30385085047502, -74.21592643598623],
|
||||
[31.353183923515484, -76.76440346301627],
|
||||
[41.23178484820762, -77.24239930162247],
|
||||
[48.85045760631198, -76.37071273327494],
|
||||
[56.68703022817994, -75.01174395072923],
|
||||
[65.2909796352862, -72.46243179848666],
|
||||
[71.98293353187195, -68.95711581293641],
|
||||
[79.3122192652982, -64.17714830980061],
|
||||
[86.64150499872396, -57.325852336933984],
|
||||
[92.69613921456384, -49.837236683321734],
|
||||
[98.2727715137498, -40.7552914376087],
|
||||
[103.01529335701053, -31.020742382007704],
|
||||
[100.18475486817623, -24.662720298843272],
|
||||
[97.3167676804432, -19.245423997890878],
|
||||
[95.56411424620316, -10.163478752177838],
|
||||
[94.92679456545713, -2.1968611819120665],
|
||||
[92.21813729791047, 4.813764711140642],
|
||||
[87.75683875221766, 9.11573333664674],
|
||||
[82.97686821005779, 12.302380364753693],
|
||||
[75.64758247663178, 13.099054277874018],
|
||||
[66.24697131249918, 10.390397010327248],
|
||||
[57.802351825579656, 8.000411739247435],
|
||||
[43.94044211575424, 3.8577730339279026],
|
||||
[29.91919032964881, 0.9897858461942421],
|
||||
[12.073971834690179, -0.28486567139179025],
|
||||
[0, 0],
|
||||
],
|
||||
startBinding: null,
|
||||
endBinding: null,
|
||||
startArrowhead: null,
|
||||
endArrowhead: null,
|
||||
polygon: true,
|
||||
hasTextLink: false,
|
||||
},
|
||||
{
|
||||
points: [
|
||||
[0, 0],
|
||||
[6.328410815071378, 3.654043196188891],
|
||||
[12.712132692328417, 9.049143652132836],
|
||||
[18.0648854655941, 13.85974990073756],
|
||||
[22.307919875114163, 20.811043617079264],
|
||||
[24.88415181991997, 27.24701484271974],
|
||||
[26.85691411806201, 19.105272791957972],
|
||||
[29.037979829676626, 13.801381097593339],
|
||||
[32.426437894862076, 7.09873368249369],
|
||||
[38.261530341157936, 1.3867100505230447],
|
||||
[48.70942209154515, -5.532681081154671],
|
||||
[38.02311477297028, -79.88405397009586],
|
||||
[3.778374266255806, -78.91256815886308],
|
||||
[0, 0],
|
||||
],
|
||||
lastCommittedPoint: null,
|
||||
startBinding: null,
|
||||
endBinding: null,
|
||||
startArrowhead: null,
|
||||
endArrowhead: null,
|
||||
id: "fpNo4FP64EJ9CjILed6-Q",
|
||||
type: "line",
|
||||
x: -1905.4230994570548,
|
||||
y: -831.5123542086587,
|
||||
width: 48.70942209154515,
|
||||
height: 107.1310688128156,
|
||||
angle: 0,
|
||||
strokeColor: "black",
|
||||
backgroundColor: "white",
|
||||
fillStyle: "solid",
|
||||
strokeWidth: 4,
|
||||
strokeStyle: "solid",
|
||||
roughness: 1,
|
||||
opacity: 100,
|
||||
roundness: null,
|
||||
seed: 449935495,
|
||||
version: 807,
|
||||
versionNonce: 1938201993,
|
||||
updated: 1778336273821,
|
||||
isDeleted: false,
|
||||
groupIds: [
|
||||
"4LA69zNKD4qokYIDapfZf",
|
||||
"TXjbtV7-h_Ule7avoyuzF",
|
||||
"1BvUccs30Onzs-FiAe46Q",
|
||||
],
|
||||
boundElements: [],
|
||||
link: null,
|
||||
locked: false,
|
||||
frameId: null,
|
||||
hasTextLink: false,
|
||||
index: "aG",
|
||||
polygon: true,
|
||||
},
|
||||
{
|
||||
id: "Ct5D6FegYZgUulrACP3mW",
|
||||
type: "line",
|
||||
x: -1879.9487796707037,
|
||||
y: -804.6969007837399,
|
||||
width: 5.642244431932001,
|
||||
height: 106.27657189329217,
|
||||
angle: 0,
|
||||
strokeColor: "black",
|
||||
backgroundColor: "white",
|
||||
fillStyle: "solid",
|
||||
strokeWidth: 2,
|
||||
strokeStyle: "solid",
|
||||
roughness: 1,
|
||||
opacity: 100,
|
||||
groupIds: [
|
||||
"4LA69zNKD4qokYIDapfZf",
|
||||
"TXjbtV7-h_Ule7avoyuzF",
|
||||
"1BvUccs30Onzs-FiAe46Q",
|
||||
],
|
||||
frameId: null,
|
||||
index: "aH",
|
||||
roundness: null,
|
||||
seed: 1866387367,
|
||||
version: 873,
|
||||
versionNonce: 902562921,
|
||||
isDeleted: false,
|
||||
boundElements: [],
|
||||
updated: 1778336273821,
|
||||
link: null,
|
||||
locked: false,
|
||||
points: [
|
||||
[0, 0],
|
||||
[-5.642244431932001, -106.27657189329217],
|
||||
],
|
||||
startBinding: null,
|
||||
endBinding: null,
|
||||
startArrowhead: null,
|
||||
endArrowhead: null,
|
||||
polygon: false,
|
||||
hasTextLink: false,
|
||||
},
|
||||
{
|
||||
id: "G0fJX2kgvmvaMpI4xyMJv",
|
||||
type: "line",
|
||||
x: -1926.1491693530807,
|
||||
y: -920.5199469657498,
|
||||
width: 82.67322797707577,
|
||||
height: 17.80462352274956,
|
||||
angle: 0,
|
||||
strokeColor: "black",
|
||||
backgroundColor: "white",
|
||||
fillStyle: "solid",
|
||||
strokeWidth: 4,
|
||||
strokeStyle: "solid",
|
||||
roughness: 1,
|
||||
opacity: 100,
|
||||
groupIds: ["TXjbtV7-h_Ule7avoyuzF", "1BvUccs30Onzs-FiAe46Q"],
|
||||
frameId: null,
|
||||
index: "aI",
|
||||
roundness: null,
|
||||
seed: 1983136455,
|
||||
version: 1068,
|
||||
versionNonce: 478252873,
|
||||
isDeleted: false,
|
||||
boundElements: [],
|
||||
updated: 1778336273821,
|
||||
link: null,
|
||||
locked: false,
|
||||
points: [
|
||||
[0, 0],
|
||||
[8.466538513954601, -8.21751708754654],
|
||||
[74.3311954267271, -8.840056404772763],
|
||||
[82.67322797707577, -0.6225393172262244],
|
||||
[74.82922878034724, 8.093011123940434],
|
||||
[6.474409849071899, 8.964567117976797],
|
||||
[0, 0],
|
||||
],
|
||||
startBinding: null,
|
||||
endBinding: null,
|
||||
startArrowhead: null,
|
||||
endArrowhead: null,
|
||||
polygon: true,
|
||||
hasTextLink: false,
|
||||
},
|
||||
{
|
||||
id: "ZQMzypkkcClDHyf0tSqFo",
|
||||
type: "line",
|
||||
x: -1899.379983759002,
|
||||
y: -929.2101650711131,
|
||||
width: 44.69832487667995,
|
||||
height: 77.69291106446725,
|
||||
angle: 0,
|
||||
strokeColor: "black",
|
||||
backgroundColor: "white",
|
||||
fillStyle: "solid",
|
||||
strokeWidth: 4,
|
||||
strokeStyle: "solid",
|
||||
roughness: 1,
|
||||
opacity: 100,
|
||||
groupIds: ["TXjbtV7-h_Ule7avoyuzF", "1BvUccs30Onzs-FiAe46Q"],
|
||||
frameId: null,
|
||||
index: "aJ",
|
||||
roundness: null,
|
||||
seed: 1615745511,
|
||||
version: 1665,
|
||||
versionNonce: 1845673513,
|
||||
isDeleted: false,
|
||||
boundElements: [],
|
||||
updated: 1778336273821,
|
||||
link: null,
|
||||
locked: false,
|
||||
points: [
|
||||
[0, 0],
|
||||
[0.996066707240395, -7.843999196728378],
|
||||
[1.992123915284619, -18.302656876369674],
|
||||
[1.2450786344522875, -29.881891976455236],
|
||||
[-0.871551244438278, -41.212105650132735],
|
||||
[-3.4862239761451312, -52.791336000620376],
|
||||
[-5.851865782247751, -61.00885546296596],
|
||||
[-7.221459879502317, -67.48326531203801],
|
||||
[-8.591044477560711, -70.72046786177494],
|
||||
[-2.1166298788907265, -70.09793091934775],
|
||||
[4.108763293371356, -70.96948453858505],
|
||||
[9.660024475191033, -74.10389686663343],
|
||||
[12.714153549466424, -77.16539352949236],
|
||||
[13.944886405384516, -77.69291106446725],
|
||||
[15.380409455193288, -76.65998909538564],
|
||||
[17.11614100417455, -74.60929655114174],
|
||||
[20.04577361404017, -72.83710011546437],
|
||||
[23.89076857043217, -71.82629725454467],
|
||||
[28.937026590773698, -70.84497857497912],
|
||||
[36.10728039911924, -70.59596189816898],
|
||||
[32.99458381298828, -64.61958540271704],
|
||||
[30.87795393409771, -58.02066721523999],
|
||||
[29.01033598241904, -51.42175140256198],
|
||||
[27.39172995795258, -44.57381891307384],
|
||||
[26.271157287106078, -36.72982446594338],
|
||||
[25.399606042667962, -29.63287529964526],
|
||||
[25.399606042667962, -20.668308181668465],
|
||||
[25.773123933485966, -12.575301807325797],
|
||||
[27.51623592155853, -4.233269256977301],
|
||||
[28.761324055207147, -0.7470452808321705],
|
||||
[0, 0],
|
||||
],
|
||||
startBinding: null,
|
||||
endBinding: null,
|
||||
startArrowhead: null,
|
||||
endArrowhead: null,
|
||||
polygon: true,
|
||||
hasTextLink: false,
|
||||
},
|
||||
{
|
||||
id: "spxryE9jWtfqbCV8JnaR0",
|
||||
type: "ellipse",
|
||||
x: -1889.0443681368367,
|
||||
y: -994.9236350059542,
|
||||
width: 7.672460231862718,
|
||||
height: 11.889385877477583,
|
||||
angle: 0,
|
||||
strokeColor: "black",
|
||||
backgroundColor: "white",
|
||||
fillStyle: "solid",
|
||||
strokeWidth: 4,
|
||||
strokeStyle: "solid",
|
||||
roughness: 1,
|
||||
opacity: 100,
|
||||
groupIds: ["TXjbtV7-h_Ule7avoyuzF", "1BvUccs30Onzs-FiAe46Q"],
|
||||
frameId: null,
|
||||
index: "aK",
|
||||
roundness: null,
|
||||
seed: 379157767,
|
||||
version: 673,
|
||||
versionNonce: 423301385,
|
||||
isDeleted: false,
|
||||
boundElements: [],
|
||||
updated: 1778336273821,
|
||||
link: null,
|
||||
locked: false,
|
||||
hasTextLink: false,
|
||||
},
|
||||
{
|
||||
id: "ovA4OfI2JrsAzvQpC7Fwg",
|
||||
type: "line",
|
||||
x: -2267.974339768966,
|
||||
y: -622.4791877783617,
|
||||
width: 300.7993383158848,
|
||||
height: 200.6658406637331,
|
||||
angle: 0,
|
||||
strokeColor: "black",
|
||||
backgroundColor: "#ffffff",
|
||||
fillStyle: "solid",
|
||||
strokeWidth: 2,
|
||||
strokeStyle: "solid",
|
||||
roughness: 1,
|
||||
opacity: 100,
|
||||
groupIds: [],
|
||||
frameId: null,
|
||||
index: "aL",
|
||||
roundness: {
|
||||
type: 2,
|
||||
},
|
||||
seed: 223986825,
|
||||
version: 118,
|
||||
versionNonce: 932306889,
|
||||
isDeleted: false,
|
||||
boundElements: [],
|
||||
updated: 1778336392623,
|
||||
link: null,
|
||||
locked: false,
|
||||
points: [
|
||||
[0, 0],
|
||||
[300.7993383158848, -200.6658406637331],
|
||||
],
|
||||
startBinding: null,
|
||||
endBinding: null,
|
||||
startArrowhead: null,
|
||||
endArrowhead: null,
|
||||
polygon: false,
|
||||
hasTextLink: false,
|
||||
},
|
||||
{
|
||||
id: "t3xrk0vcdp6RCsnyf6IbE",
|
||||
type: "line",
|
||||
x: -1829.940349703624,
|
||||
y: -912.5071675204925,
|
||||
width: 170.34652493133967,
|
||||
height: 113.29839525586146,
|
||||
angle: 0,
|
||||
strokeColor: "black",
|
||||
backgroundColor: "#ffffff",
|
||||
fillStyle: "solid",
|
||||
strokeWidth: 2,
|
||||
strokeStyle: "solid",
|
||||
roughness: 1,
|
||||
opacity: 100,
|
||||
groupIds: [],
|
||||
frameId: null,
|
||||
index: "aM",
|
||||
roundness: {
|
||||
type: 2,
|
||||
},
|
||||
seed: 776802759,
|
||||
version: 227,
|
||||
versionNonce: 1764203209,
|
||||
isDeleted: false,
|
||||
boundElements: [],
|
||||
updated: 1778336399948,
|
||||
link: null,
|
||||
locked: false,
|
||||
points: [
|
||||
[0, 0],
|
||||
[170.34652493133967, -113.29839525586146],
|
||||
],
|
||||
startBinding: null,
|
||||
endBinding: null,
|
||||
startArrowhead: null,
|
||||
endArrowhead: null,
|
||||
polygon: false,
|
||||
hasTextLink: false,
|
||||
},
|
||||
{
|
||||
id: "_VVuYZU1rZG6h_04Uw56t",
|
||||
type: "line",
|
||||
x: -1497.6248397227794,
|
||||
y: -1134.316743363017,
|
||||
width: 25.133152436062346,
|
||||
height: 17.55328015890541,
|
||||
angle: 0,
|
||||
strokeColor: "black",
|
||||
backgroundColor: "#ffffff",
|
||||
fillStyle: "solid",
|
||||
strokeWidth: 2,
|
||||
strokeStyle: "solid",
|
||||
roughness: 1,
|
||||
opacity: 100,
|
||||
groupIds: [],
|
||||
frameId: null,
|
||||
index: "aN",
|
||||
roundness: {
|
||||
type: 2,
|
||||
},
|
||||
seed: 1773106921,
|
||||
version: 147,
|
||||
versionNonce: 757598151,
|
||||
isDeleted: false,
|
||||
boundElements: [],
|
||||
updated: 1778336411619,
|
||||
link: null,
|
||||
locked: false,
|
||||
points: [
|
||||
[0, 0],
|
||||
[-25.133152436062346, 17.55328015890541],
|
||||
],
|
||||
startBinding: null,
|
||||
endBinding: null,
|
||||
startArrowhead: null,
|
||||
endArrowhead: null,
|
||||
polygon: false,
|
||||
hasTextLink: false,
|
||||
},
|
||||
{
|
||||
id: "I2vN9P46g-ZrZfjKJEm7Q",
|
||||
type: "line",
|
||||
x: -1502.8110830389114,
|
||||
y: -627.2664170069975,
|
||||
width: 321.1452261615798,
|
||||
height: 214.22975700310758,
|
||||
angle: 0,
|
||||
strokeColor: "black",
|
||||
backgroundColor: "#ffffff",
|
||||
fillStyle: "solid",
|
||||
strokeWidth: 2,
|
||||
strokeStyle: "solid",
|
||||
roughness: 1,
|
||||
opacity: 100,
|
||||
groupIds: [],
|
||||
frameId: null,
|
||||
index: "aP",
|
||||
roundness: {
|
||||
type: 2,
|
||||
},
|
||||
seed: 2003689097,
|
||||
version: 182,
|
||||
versionNonce: 631974921,
|
||||
isDeleted: false,
|
||||
boundElements: [],
|
||||
updated: 1778336356966,
|
||||
link: null,
|
||||
locked: false,
|
||||
points: [
|
||||
[0, 0],
|
||||
[-321.1452261615798, -214.22975700310758],
|
||||
],
|
||||
startBinding: null,
|
||||
endBinding: null,
|
||||
startArrowhead: null,
|
||||
endArrowhead: null,
|
||||
polygon: false,
|
||||
hasTextLink: false,
|
||||
},
|
||||
{
|
||||
id: "tSRi_B3MJaYSXpmDmHh7o",
|
||||
type: "line",
|
||||
x: -1940.0472754674006,
|
||||
y: -918.0923007629168,
|
||||
width: 153.19225350562328,
|
||||
height: 103.7238927483935,
|
||||
angle: 0,
|
||||
strokeColor: "black",
|
||||
backgroundColor: "#ffffff",
|
||||
fillStyle: "solid",
|
||||
strokeWidth: 2,
|
||||
strokeStyle: "solid",
|
||||
roughness: 1,
|
||||
opacity: 100,
|
||||
groupIds: [],
|
||||
frameId: null,
|
||||
index: "aQ",
|
||||
roundness: {
|
||||
type: 2,
|
||||
},
|
||||
seed: 2100420423,
|
||||
version: 165,
|
||||
versionNonce: 351954087,
|
||||
isDeleted: false,
|
||||
boundElements: [],
|
||||
updated: 1778336363640,
|
||||
link: null,
|
||||
locked: false,
|
||||
points: [
|
||||
[0, 0],
|
||||
[-153.19225350562328, -103.7238927483935],
|
||||
],
|
||||
startBinding: null,
|
||||
endBinding: null,
|
||||
startArrowhead: null,
|
||||
endArrowhead: null,
|
||||
polygon: false,
|
||||
hasTextLink: false,
|
||||
},
|
||||
{
|
||||
id: "yWybvrm6G6gsM_XGWI_kL",
|
||||
type: "line",
|
||||
x: -2246.830681184611,
|
||||
y: -1124.3432867829038,
|
||||
width: 17.952202203977777,
|
||||
height: 11.569206089262934,
|
||||
angle: 0,
|
||||
strokeColor: "black",
|
||||
backgroundColor: "#ffffff",
|
||||
fillStyle: "solid",
|
||||
strokeWidth: 2,
|
||||
strokeStyle: "solid",
|
||||
roughness: 1,
|
||||
opacity: 100,
|
||||
groupIds: [],
|
||||
frameId: null,
|
||||
index: "aR",
|
||||
roundness: {
|
||||
type: 2,
|
||||
},
|
||||
seed: 1804001033,
|
||||
version: 60,
|
||||
versionNonce: 1453310409,
|
||||
isDeleted: false,
|
||||
boundElements: [],
|
||||
updated: 1778336373137,
|
||||
link: null,
|
||||
locked: false,
|
||||
points: [
|
||||
[0, 0],
|
||||
[-17.952202203977777, -11.569206089262934],
|
||||
],
|
||||
startBinding: null,
|
||||
endBinding: null,
|
||||
startArrowhead: null,
|
||||
endArrowhead: null,
|
||||
polygon: false,
|
||||
hasTextLink: false,
|
||||
},
|
||||
];
|
||||
|
||||
export const getEmptyDrawingElementsRuntime = (): ExcalidrawElement[] =>
|
||||
emptyDrawingElements.map(
|
||||
(element) => element as SerializedExcalidrawElement & ExcalidrawElement,
|
||||
);
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
f = app.vault.getAbstractFileByPath("startuphooks.md");
|
||||
f = app.vault.getFileByPath("startuphooks.md");
|
||||
s = await app.vault.read(f);
|
||||
ea = ExcalidrawAutomate;
|
||||
url = await ea.convertStringToDataURL(s);
|
||||
@@ -7,4 +7,7 @@ window.navigator.clipboard.writeText(`export const startupScript = () => atob("$
|
||||
console.log("String copied to clipboard");
|
||||
*/
|
||||
|
||||
export const startupScript = () => atob("LyoKI2V4Y2x1ZGUKYGBganMqLwovKioKICogSWYgc2V0LCB0aGlzIGNhbGxiYWNrIGlzIHRyaWdnZXJlZCB3aGVuIHRoZSB1c2VyIGNsb3NlcyBhbiBFeGNhbGlkcmF3IHZpZXcuCiAqICAgb25WaWV3VW5sb2FkSG9vazogKHZpZXc6IEV4Y2FsaWRyYXdWaWV3KSA9PiB2b2lkID0gbnVsbDsKICovCi8vZWEub25WaWV3VW5sb2FkSG9vayA9ICh2aWV3KSA9PiB7fTsKCi8qKgogKiBJZiBzZXQsIHRoaXMgY2FsbGJhY2sgaXMgdHJpZ2dlcmVkLCB3aGVuIHRoZSB1c2VyIGNoYW5nZXMgdGhlIHZpZXcgbW9kZS4KICogWW91IGNhbiB1c2UgdGhpcyBjYWxsYmFjayBpbiBjYXNlIHlvdSB3YW50IHRvIGRvIHNvbWV0aGluZyBhZGRpdGlvbmFsIHdoZW4gdGhlIHVzZXIgc3dpdGNoZXMgdG8gdmlldyBtb2RlIGFuZCBiYWNrLgogKiAgIG9uVmlld01vZGVDaGFuZ2VIb29rOiAoaXNWaWV3TW9kZUVuYWJsZWQ6Ym9vbGVhbiwgdmlldzogRXhjYWxpZHJhd1ZpZXcsIGVhOiBFeGNhbGlkcmF3QXV0b21hdGUpID0+IHZvaWQgPSBudWxsOwogKi8KLy9lYS5vblZpZXdNb2RlQ2hhbmdlSG9vayA9IChpc1ZpZXdNb2RlRW5hYmxlZCwgdmlldywgZWEpID0+IHt9OwoKLyoqCiAqIElmIHNldCwgdGhpcyBjYWxsYmFjayBpcyB0cmlnZ2VyZWQsIHdoZW4gdGhlIHVzZXIgaG92ZXJzIGEgbGluayBpbiB0aGUgc2NlbmUuCiAqIFlvdSBjYW4gdXNlIHRoaXMgY2FsbGJhY2sgaW4gY2FzZSB5b3Ugd2FudCB0byBkbyBzb21ldGhpbmcgYWRkaXRpb25hbCB3aGVuIHRoZSBvbkxpbmtIb3ZlciBldmVudCBvY2N1cnMuCiAqIFRoaXMgY2FsbGJhY2sgbXVzdCByZXR1cm4gYSBib29sZWFuIHZhbHVlLgogKiBJbiBjYXNlIHlvdSB3YW50IHRvIHByZXZlbnQgdGhlIGV4Y2FsaWRyYXcgb25MaW5rSG92ZXIgYWN0aW9uIHlvdSBtdXN0IHJldHVybiBmYWxzZSwgaXQgd2lsbCBzdG9wIHRoZSBuYXRpdmUgZXhjYWxpZHJhdyBvbkxpbmtIb3ZlciBtYW5hZ2VtZW50IGZsb3cuCiAqICAgb25MaW5rSG92ZXJIb29rOiAoCiAqICAgICBlbGVtZW50OiBOb25EZWxldGVkRXhjYWxpZHJhd0VsZW1lbnQsCiAqICAgICBsaW5rVGV4dDogc3RyaW5nLAogKiAgICAgdmlldzogRXhjYWxpZHJhd1ZpZXcsCiAqICAgICBlYTogRXhjYWxpZHJhd0F1dG9tYXRlCiAqICAgKSA9PiBib29sZWFuID0gbnVsbDsKICovCi8vZWEub25MaW5rSG92ZXJIb29rID0gKGVsZW1lbnQsIGxpbmtUZXh0LCB2aWV3LCBlYSkgPT4ge307CiAgIAovKioKICogSWYgc2V0LCB0aGlzIGNhbGxiYWNrIGlzIHRyaWdnZXJlZCwgd2hlbiB0aGUgdXNlciBjbGlja3MgYSBsaW5rIGluIHRoZSBzY2VuZS4KICogWW91IGNhbiB1c2UgdGhpcyBjYWxsYmFjayBpbiBjYXNlIHlvdSB3YW50IHRvIGRvIHNvbWV0aGluZyBhZGRpdGlvbmFsIHdoZW4gdGhlIG9uTGlua0NsaWNrIGV2ZW50IG9jY3Vycy4KICogVGhpcyBjYWxsYmFjayBtdXN0IHJldHVybiBhIGJvb2xlYW4gdmFsdWUuCiAqIEluIGNhc2UgeW91IHdhbnQgdG8gcHJldmVudCB0aGUgZXhjYWxpZHJhdyBvbkxpbmtDbGljayBhY3Rpb24geW91IG11c3QgcmV0dXJuIGZhbHNlLCBpdCB3aWxsIHN0b3AgdGhlIG5hdGl2ZSBleGNhbGlkcmF3IG9uTGlua0NsaWNrIG1hbmFnZW1lbnQgZmxvdy4KICogICBvbkxpbmtDbGlja0hvb2s6KAogKiAgICAgZWxlbWVudDogRXhjYWxpZHJhd0VsZW1lbnQsCiAqICAgICBsaW5rVGV4dDogc3RyaW5nLAogKiAgICAgZXZlbnQ6IE1vdXNlRXZlbnQsCiAqICAgICB2aWV3OiBFeGNhbGlkcmF3VmlldywKICogICAgIGVhOiBFeGNhbGlkcmF3QXV0b21hdGUKICogICApID0+IGJvb2xlYW4gPSBudWxsOwogKi8KLy9lYS5vbkxpbmtDbGlja0hvb2sgPSAoZWxlbWVudCxsaW5rVGV4dCxldmVudCwgdmlldywgZWEpID0+IHt9OwogICAKLyoqCiAqIElmIHNldCwgdGhpcyBjYWxsYmFjayBpcyB0cmlnZ2VyZWQsIHdoZW4gRXhjYWxpZHJhdyByZWNlaXZlcyBhbiBvbkRyb3AgZXZlbnQuIAogKiBZb3UgY2FuIHVzZSB0aGlzIGNhbGxiYWNrIGluIGNhc2UgeW91IHdhbnQgdG8gZG8gc29tZXRoaW5nIGFkZGl0aW9uYWwgd2hlbiB0aGUgb25Ecm9wIGV2ZW50IG9jY3Vycy4KICogVGhpcyBjYWxsYmFjayBtdXN0IHJldHVybiBhIGJvb2xlYW4gdmFsdWUuCiAqIEluIGNhc2UgeW91IHdhbnQgdG8gcHJldmVudCB0aGUgZXhjYWxpZHJhdyBvbkRyb3AgYWN0aW9uIHlvdSBtdXN0IHJldHVybiBmYWxzZSwgaXQgd2lsbCBzdG9wIHRoZSBuYXRpdmUgZXhjYWxpZHJhdyBvbkRyb3AgbWFuYWdlbWVudCBmbG93LgogKiAgIG9uRHJvcEhvb2s6IChkYXRhOiB7CiAqICAgICBlYTogRXhjYWxpZHJhd0F1dG9tYXRlOwogKiAgICAgZXZlbnQ6IFJlYWN0LkRyYWdFdmVudDxIVE1MRGl2RWxlbWVudD47CiAqICAgICBkcmFnZ2FibGU6IGFueTsgLy9PYnNpZGlhbiBkcmFnZ2FibGUgb2JqZWN0CiAqICAgICB0eXBlOiAiZmlsZSIgfCAidGV4dCIgfCAidW5rbm93biI7CiAqICAgICBwYXlsb2FkOiB7CiAqICAgICAgIGZpbGVzOiBURmlsZVtdOyAvL1RGaWxlW10gYXJyYXkgb2YgZHJvcHBlZCBmaWxlcwogKiAgICAgICB0ZXh0OiBzdHJpbmc7IC8vc3RyaW5nCiAqICAgICB9OwogKiAgICAgZXhjYWxpZHJhd0ZpbGU6IFRGaWxlOyAvL3RoZSBmaWxlIHJlY2VpdmluZyB0aGUgZHJvcCBldmVudAogKiAgICAgdmlldzogRXhjYWxpZHJhd1ZpZXc7IC8vdGhlIGV4Y2FsaWRyYXcgdmlldyByZWNlaXZpbmcgdGhlIGRyb3AKICogICAgIHBvaW50ZXJQb3NpdGlvbjogeyB4OiBudW1iZXI7IHk6IG51bWJlciB9OyAvL3RoZSBwb2ludGVyIHBvc2l0aW9uIG9uIGNhbnZhcyBhdCB0aGUgdGltZSBvZiBkcm9wCiAqICAgfSkgPT4gYm9vbGVhbiA9IG51bGw7CiAqLwovL2VhLm9uRHJvcEhvb2sgPSAoZGF0YSkgPT4ge307CiAKLyoqCiAqIElmIHNldCwgdGhpcyBjYWxsYmFjayBpcyB0cmlnZ2VyZWQsIHdoZW4gRXhjYWxpZHJhdyByZWNlaXZlcyBhbiBvblBhc3RlIGV2ZW50LgogKiBZb3UgY2FuIHVzZSB0aGlzIGNhbGxiYWNrIGluIGNhc2UgeW91IHdhbnQgdG8gZG8gc29tZXRoaW5nIGFkZGl0aW9uYWwgd2hlbiB0aGUKICogb25QYXN0ZSBldmVudCBvY2N1cnMuCiAqIFRoaXMgY2FsbGJhY2sgbXVzdCByZXR1cm4gYSBib29sZWFuIHZhbHVlLgogKiBJbiBjYXNlIHlvdSB3YW50IHRvIHByZXZlbnQgdGhlIGV4Y2FsaWRyYXcgb25QYXN0ZSBhY3Rpb24geW91IG11c3QgcmV0dXJuIGZhbHNlLAogKiBpdCB3aWxsIHN0b3AgdGhlIG5hdGl2ZSBleGNhbGlkcmF3IG9uUGFzdGUgbWFuYWdlbWVudCBmbG93LgogKiAgIG9uUGFzdGVIb29rOiAoZGF0YTogewogKiAgICAgZWE6IEV4Y2FsaWRyYXdBdXRvbWF0ZTsKICogICAgIHBheWxvYWQ6IENsaXBib2FyZERhdGE7CiAqICAgICBldmVudDogQ2xpcGJvYXJkRXZlbnQ7CiAqICAgICBleGNhbGlkcmF3RmlsZTogVEZpbGU7IC8vdGhlIGZpbGUgcmVjZWl2aW5nIHRoZSBwYXN0ZSBldmVudAogKiAgICAgdmlldzogRXhjYWxpZHJhd1ZpZXc7IC8vdGhlIGV4Y2FsaWRyYXcgdmlldyByZWNlaXZpbmcgdGhlIHBhc3RlCiAqICAgICBwb2ludGVyUG9zaXRpb246IHsgeDogbnVtYmVyOyB5OiBudW1iZXIgfTsgLy90aGUgcG9pbnRlciBwb3NpdGlvbiBvbiBjYW52YXMKICogICB9KSA9PiBib29sZWFuID0gbnVsbDsKICovCi8vZWEub25QYXN0ZUhvb2sgPSAoZGF0YSkgPT4ge307CgovKioKICogaWYgc2V0LCB0aGlzIGNhbGxiYWNrIGlzIHRyaWdnZXJlZCLine truncated
|
||||
export const startupScript = () =>
|
||||
atob(
|
||||
"LyoKI2V4Y2x1ZGUKYGBganMqLwovKioKICogSWYgc2V0LCB0aGlzIGNhbGxiYWNrIGlzIHRyaWdnZXJlZCB3aGVuIHRoZSB1c2VyIGNsb3NlcyBhbiBFeGNhbGlkcmF3IHZpZXcuCiAqICAgb25WaWV3VW5sb2FkSG9vazogKHZpZXc6IEV4Y2FsaWRyYXdWaWV3KSA9PiB2b2lkID0gbnVsbDsKICovCi8vZWEub25WaWV3VW5sb2FkSG9vayA9ICh2aWV3KSA9PiB7fTsKCi8qKgogKiBJZiBzZXQsIHRoaXMgY2FsbGJhY2sgaXMgdHJpZ2dlcmVkLCB3aGVuIHRoZSB1c2VyIGNoYW5nZXMgdGhlIHZpZXcgbW9kZS4KICogWW91IGNhbiB1c2UgdGhpcyBjYWxsYmFjayBpbiBjYXNlIHlvdSB3YW50IHRvIGRvIHNvbWV0aGluZyBhZGRpdGlvbmFsIHdoZW4gdGhlIHVzZXIgc3dpdGNoZXMgdG8gdmlldyBtb2RlIGFuZCBiYWNrLgogKiAgIG9uVmlld01vZGVDaGFuZ2VIb29rOiAoaXNWaWV3TW9kZUVuYWJsZWQ6Ym9vbGVhbiwgdmlldzogRXhjYWxpZHJhd1ZpZXcsIGVhOiBFeGNhbGlkcmF3QXV0b21hdGUpID0+IHZvaWQgPSBudWxsOwogKi8KLy9lYS5vblZpZXdNb2RlQ2hhbmdlSG9vayA9IChpc1ZpZXdNb2RlRW5hYmxlZCwgdmlldywgZWEpID0+IHt9OwoKLyoqCiAqIElmIHNldCwgdGhpcyBjYWxsYmFjayBpcyB0cmlnZ2VyZWQsIHdoZW4gdGhlIHVzZXIgaG92ZXJzIGEgbGluayBpbiB0aGUgc2NlbmUuCiAqIFlvdSBjYW4gdXNlIHRoaXMgY2FsbGJhY2sgaW4gY2FzZSB5b3Ugd2FudCB0byBkbyBzb21ldGhpbmcgYWRkaXRpb25hbCB3aGVuIHRoZSBvbkxpbmtIb3ZlciBldmVudCBvY2N1cnMuCiAqIFRoaXMgY2FsbGJhY2sgbXVzdCByZXR1cm4gYSBib29sZWFuIHZhbHVlLgogKiBJbiBjYXNlIHlvdSB3YW50IHRvIHByZXZlbnQgdGhlIGV4Y2FsaWRyYXcgb25MaW5rSG92ZXIgYWN0aW9uIHlvdSBtdXN0IHJldHVybiBmYWxzZSwgaXQgd2lsbCBzdG9wIHRoZSBuYXRpdmUgZXhjYWxpZHJhdyBvbkxpbmtIb3ZlciBtYW5hZ2VtZW50IGZsb3cuCiAqICAgb25MaW5rSG92ZXJIb29rOiAoCiAqICAgICBlbGVtZW50OiBOb25EZWxldGVkRXhjYWxpZHJhd0VsZW1lbnQsCiAqICAgICBsaW5rVGV4dDogc3RyaW5nLAogKiAgICAgdmlldzogRXhjYWxpZHJhd1ZpZXcsCiAqICAgICBlYTogRXhjYWxpZHJhd0F1dG9tYXRlCiAqICAgKSA9PiBib29sZWFuID0gbnVsbDsKICovCi8vZWEub25MaW5rSG92ZXJIb29rID0gKGVsZW1lbnQsIGxpbmtUZXh0LCB2aWV3LCBlYSkgPT4ge307CiAgIAovKioKICogSWYgc2V0LCB0aGlzIGNhbGxiYWNrIGlzIHRyaWdnZXJlZCwgd2hlbiB0aGUgdXNlciBjbGlja3MgYSBsaW5rIGluIHRoZSBzY2VuZS4KICogWW91IGNhbiB1c2UgdGhpcyBjYWxsYmFjayBpbiBjYXNlIHlvdSB3YW50IHRvIGRvIHNvbWV0aGluZyBhZGRpdGlvbmFsIHdoZW4gdGhlIG9uTGlua0NsaWNrIGV2ZW50IG9jY3Vycy4KICogVGhpcyBjYWxsYmFjayBtdXN0IHJldHVybiBhIGJvb2xlYW4gdmFsdWUuCiAqIEluIGNhc2UgeW91IHdhbnQgdG8gcHJldmVudCB0aGUgZXhjYWxpZHJhdyBvbkxpbmtDbGljayBhY3Rpb24geW91IG11c3QgcmV0dXJuIGZhbHNlLCBpdCB3aWxsIHN0b3AgdGhlIG5hdGl2ZSBleGNhbGlkcmF3IG9uTGlua0NsaWNrIG1hbmFnZW1lbnQgZmxvdy4KICogICBvbkxpbmtDbGlja0hvb2s6KAogKiAgICAgZWxlbWVudDogRXhjYWxpZHJhd0VsZW1lbnQsCiAqICAgICBsaW5rVGV4dDogc3RyaW5nLAogKiAgICAgZXZlbnQ6IE1vdXNlRXZlbnQsCiAqICAgICB2aWV3OiBFeGNhbGlkcmF3VmlldywKICogICAgIGVhOiBFeGNhbGlkcmF3QXV0b21hdGUKICogICApID0+IGJvb2xlYW4gPSBudWxsOwogKi8KLy9lYS5vbkxpbmtDbGlja0hvb2sgPSAoZWxlbWVudCxsaW5rVGV4dCxldmVudCwgdmlldywgZWEpID0+IHt9OwogICAKLyoqCiAqIElmIHNldCwgdGhpcyBjYWxsYmFjayBpcyB0cmlnZ2VyZWQsIHdoZW4gRXhjYWxpZHJhdyByZWNlaXZlcyBhbiBvbkRyb3AgZXZlbnQuIAogKiBZb3UgY2FuIHVzZSB0aGlzIGNhbGxiYWNrIGluIGNhc2UgeW91IHdhbnQgdG8gZG8gc29tZXRoaW5nIGFkZGl0aW9uYWwgd2hlbiB0aGUgb25Ecm9wIGV2ZW50IG9jY3Vycy4KICogVGhpcyBjYWxsYmFjayBtdXN0IHJldHVybiBhIGJvb2xlYW4gdmFsdWUuCiAqIEluIGNhc2UgeW91IHdhbnQgdG8gcHJldmVudCB0aGUgZXhjYWxpZHJhdyBvbkRyb3AgYWN0aW9uIHlvdSBtdXN0IHJldHVybiBmYWxzZSwgaXQgd2lsbCBzdG9wIHRoZSBuYXRpdmUgZXhjYWxpZHJhdyBvbkRyb3AgbWFuYWdlbWVudCBmbG93LgogKiAgIG9uRHJvcEhvb2s6IChkYXRhOiB7CiAqICAgICBlYTogRXhjYWxpZHJhd0F1dG9tYXRlOwogKiAgICAgZXZlbnQ6IFJlYWN0LkRyYWdFdmVudDxIVE1MRGl2RWxlbWVudD47CiAqICAgICBkcmFnZ2FibGU6IGFueTsgLy9PYnNpZGlhbiBkcmFnZ2FibGUgb2JqZWN0CiAqICAgICB0eXBlOiAiZmlsZSIgfCAidGV4dCIgfCAidW5rbm93biI7CiAqICAgICBwYXlsb2FkOiB7CiAqICAgICAgIGZpbGVzOiBURmlsZVtdOyAvL1RGaWxlW10gYXJyYXkgb2YgZHJvcHBlZCBmaWxlcwogKiAgICAgICB0ZXh0OiBzdHJpbmc7IC8vc3RyaW5nCiAqICAgICB9OwogKiAgICAgZXhjYWxpZHJhd0ZpbGU6IFRGaWxlOyAvL3RoZSBmaWxlIHJlY2VpdmluZyB0aGUgZHJvcCBldmVudAogKiAgICAgdmlldzogRXhjYWxpZHJhd1ZpZXc7IC8vdGhlIGV4Y2FsaWRyYXcgdmlldyByZWNlaXZpbmcgdGhlIGRyb3AKICogICAgIHBvaW50ZXJQb3NpdGlvbjogeyB4OiBudW1iZXI7IHk6IG51bWJlciB9OyAvL3RoZSBwb2ludGVyIHBvc2l0aW9uIG9uIGNhbnZhcyBhdCB0aGUgdGltZSBvZiBkcm9wCiAqICAgfSkgPT4gYm9vbGVhbiA9IG51bGw7CiAqLwovL2VhLm9uRHJvcEhvb2sgPSAoZGF0YSkgPT4ge307CiAKLyoqCiAqIElmIHNldCwgdGhpcyBjYWxsYmFjayBpcyB0cmlnZ2VyZWQsIHdoZW4gRXhjYWxpZHJhdyByZWNlaXZlcyBhbiBvblBhc3RlIGV2ZW50LgogKiBZb3UgY2FuIHVzZSB0aGlzIGNhbGxiYWNrIGluIGNhc2UgeW91IHdhbnQgdG8gZG8gc29tZXRoaW5nIGFkZGl0aW9uYWwgd2hlbiB0aGUKICogb25QYXN0ZSBldmVudCBvY2N1cnMuCiAqIFRoaXMgY2FsbGJhY2sgbXVzdCByZXR1cm4gYSBib29sZWFuIHZhbHVlLgogKiBJbiBjYXNlIHlvdSB3YW50IHRvIHByZXZlbnQgdGhlIGV4Y2FsaWRyYXcgb25QYXN0ZSBhY3Rpb24geW91IG11c3QgcmV0dXJuIGZhbHNlLAogKiBpdCB3aWxsIHN0b3AgdGhlIG5hdGl2ZSBleGNhbGlkcmF3IG9uUGFzdGUgbWFuYWdlbWVudCBmbG93LgogKiAgIG9uUGFzdGVIb29rOiAoZGF0YTogewogKiAgICAgZWE6IEV4Y2FsaWRyYXdBdXRvbWF0ZTsKICogICAgIHBheWxvYWQ6IENsaXBib2FyZERhdGE7CiAqICAgICBldmVudDogQ2xpcGJvYXJkRXZlbnQ7CiAqICAgICBleGNhbGlkcmF3RmlsZTogVEZpbGU7IC8vdGhlIGZpbGUgcmVjZWl2aW5nIHRoZSBwYXN0ZSBldmVudAogKiAgICAgdmlldzogRXhjYWxpZHJhd1ZpZXc7IC8vdGhlIGV4Y2FsaWRyYXcgdmlldyByZWNlaXZpbmcgdGhlIHBhc3RlCiAqICAgICBwb2ludGVyUG9zaXRpb246IHsgeDogbnVtYmVyOyB5OiBudW1iZXIgfTsgLy90aGUgcG9pbnRlciBwb3NpdGlvbiBvbiBjYW52YXMKICogICB9KSA9PiBib29sZWFuID0gbnVsbDsKICovCi8vZWEub25QYXN0ZUhvb2sgPSAoZGF0YSkgPT4ge307CgovKioKICogaWYgc2V0LCB0aGlzIGNhbGxiYWNrIGlzIHRyaWdnZXJlZCwgd2hlbiBhbiBFeGNhbGlkcmF3IGZpbGUgaXLine truncated
|
||||
);
|
||||
@@ -1,44 +1,43 @@
|
||||
import { Extension } from "@codemirror/state";
|
||||
import ExcalidrawPlugin from "src/core/main";
|
||||
import { HideTextBetweenCommentsExtension } from "./Fadeout";
|
||||
import { debug, DEBUGGING } from "src/utils/debugHelper";
|
||||
export const EDITOR_FADEOUT = "fadeOutExcalidrawMarkup";
|
||||
|
||||
const editorExtensions: {[key:string]:Extension}= {
|
||||
[EDITOR_FADEOUT]: HideTextBetweenCommentsExtension,
|
||||
}
|
||||
type TaggedExtension = Extension & { exID?: string };
|
||||
|
||||
const editorExtensions: { [key: string]: Extension } = {
|
||||
[EDITOR_FADEOUT]: HideTextBetweenCommentsExtension,
|
||||
};
|
||||
|
||||
export class EditorHandler {
|
||||
private activeEditorExtensions: Extension[] = [];
|
||||
private activeEditorExtensions: TaggedExtension[] = [];
|
||||
|
||||
constructor(private plugin: ExcalidrawPlugin) {
|
||||
(process.env.NODE_ENV === 'development') && DEBUGGING && debug(EditorHandler, `ExcalidrawPlugin.construct EditorHandler`);
|
||||
}
|
||||
constructor(private plugin: ExcalidrawPlugin) {}
|
||||
|
||||
destroy(): void {
|
||||
this.plugin = null;
|
||||
}
|
||||
|
||||
setup(): void {
|
||||
(process.env.NODE_ENV === 'development') && DEBUGGING && debug(this.setup, `ExcalidrawPlugin.construct EditorHandler.setup`);
|
||||
this.plugin.registerEditorExtension(this.activeEditorExtensions);
|
||||
this.updateCMExtensionState(EDITOR_FADEOUT, this.plugin.settings.fadeOutExcalidrawMarkup);
|
||||
this.updateCMExtensionState(
|
||||
EDITOR_FADEOUT,
|
||||
this.plugin.settings.fadeOutExcalidrawMarkup,
|
||||
);
|
||||
}
|
||||
|
||||
updateCMExtensionState(
|
||||
extensionIdentifier: string,
|
||||
extensionState: boolean,
|
||||
) {
|
||||
updateCMExtensionState(extensionIdentifier: string, extensionState: boolean) {
|
||||
const extension = editorExtensions[extensionIdentifier];
|
||||
if(!extension) return;
|
||||
if (!extension) {
|
||||
return;
|
||||
}
|
||||
if (extensionState == true) {
|
||||
this.activeEditorExtensions.push(extension);
|
||||
// @ts-ignore
|
||||
this.activeEditorExtensions[this.activeEditorExtensions.length - 1].exID = extensionIdentifier;
|
||||
this.activeEditorExtensions.push(extension as TaggedExtension);
|
||||
this.activeEditorExtensions[this.activeEditorExtensions.length - 1].exID =
|
||||
extensionIdentifier;
|
||||
} else {
|
||||
for (let i = 0; i < this.activeEditorExtensions.length; i++) {
|
||||
const ext = this.activeEditorExtensions[i];
|
||||
// @ts-ignore
|
||||
if (ext.exID === extensionIdentifier) {
|
||||
this.activeEditorExtensions.splice(i, 1);
|
||||
break;
|
||||
@@ -50,4 +49,4 @@ export class EditorHandler {
|
||||
update(): void {
|
||||
this.plugin.app.workspace.updateOptions();
|
||||
}
|
||||
}
|
||||
}
|
||||
+35
-23
@@ -1,11 +1,17 @@
|
||||
import { RangeSetBuilder } from "@codemirror/state";
|
||||
import { Decoration, DecorationSet, EditorView, ViewPlugin, ViewUpdate } from "@codemirror/view";
|
||||
import {
|
||||
Decoration,
|
||||
DecorationSet,
|
||||
EditorView,
|
||||
ViewPlugin,
|
||||
ViewUpdate,
|
||||
} from "@codemirror/view";
|
||||
|
||||
const o30 = Decoration.line({ attributes: {class: "ex-opacity-30"} });
|
||||
const o15 = Decoration.line({ attributes: {class: "ex-opacity-15"} });
|
||||
const o8 = Decoration.line({ attributes: {class: "ex-opacity-8"} });
|
||||
const o5 = Decoration.line({ attributes: {class: "ex-opacity-5"} });
|
||||
const o0 = Decoration.line({ attributes: {class: "ex-opacity-0"} });
|
||||
const o30 = Decoration.line({ attributes: { class: "ex-opacity-30" } });
|
||||
const o15 = Decoration.line({ attributes: { class: "ex-opacity-15" } });
|
||||
const o8 = Decoration.line({ attributes: { class: "ex-opacity-8" } });
|
||||
const o5 = Decoration.line({ attributes: { class: "ex-opacity-5" } });
|
||||
const o0 = Decoration.line({ attributes: { class: "ex-opacity-0" } });
|
||||
|
||||
export const HideTextBetweenCommentsExtension = ViewPlugin.fromClass(
|
||||
class {
|
||||
@@ -16,51 +22,57 @@ export const HideTextBetweenCommentsExtension = ViewPlugin.fromClass(
|
||||
reDrawing = /^%%(?:\r\n|\r|\n)##? Drawing$/gm;
|
||||
linecount = 0;
|
||||
isExcalidraw = false;
|
||||
|
||||
|
||||
constructor(view: EditorView) {
|
||||
this.view = view;
|
||||
this.isExcalidraw = view.state.doc.toString().search(/^excalidraw-plugin: /m) > 0;
|
||||
if(!this.isExcalidraw) {
|
||||
this.isExcalidraw =
|
||||
view.state.doc.toString().search(/^excalidraw-plugin: /m) > 0;
|
||||
if (!this.isExcalidraw) {
|
||||
this.decorations = Decoration.none;
|
||||
return;
|
||||
}
|
||||
this.decorations = this.updateDecorations(view);
|
||||
}
|
||||
|
||||
updateDecorations (view: EditorView) {
|
||||
updateDecorations(view: EditorView) {
|
||||
const { state } = view;
|
||||
const { doc } = state;
|
||||
|
||||
|
||||
const text = doc.toString();
|
||||
|
||||
let start = text.search(this.reExcalidrawData);
|
||||
if(start == -1) {
|
||||
if (start == -1) {
|
||||
start = text.search(this.reTextElements);
|
||||
}
|
||||
if(start == -1) {
|
||||
if (start == -1) {
|
||||
start = text.search(this.reDrawing);
|
||||
}
|
||||
if(start == -1) return Decoration.none;
|
||||
|
||||
if (start == -1) {
|
||||
return Decoration.none;
|
||||
}
|
||||
|
||||
const startLine = doc.lineAt(start).number;
|
||||
const endLine = doc.lines;
|
||||
let builder = new RangeSetBuilder<Decoration>()
|
||||
const builder = new RangeSetBuilder<Decoration>();
|
||||
for (let l = startLine; l <= endLine; l++) {
|
||||
const line = doc.line(l);
|
||||
const pos = l-startLine;
|
||||
builder.add(line.from, line.from,
|
||||
pos == 0 ? o30 : (pos == 1) ? o15 : (pos < 6) ? o8 : (pos < 12) ? o5 : o0);
|
||||
const pos = l - startLine;
|
||||
builder.add(
|
||||
line.from,
|
||||
line.from,
|
||||
pos == 0 ? o30 : pos == 1 ? o15 : pos < 6 ? o8 : pos < 12 ? o5 : o0,
|
||||
);
|
||||
}
|
||||
return builder.finish()
|
||||
return builder.finish();
|
||||
}
|
||||
|
||||
update(update: ViewUpdate) {
|
||||
if (this.isExcalidraw && update.docChanged) {
|
||||
this.decorations = this.updateDecorations(update.view)
|
||||
this.decorations = this.updateDecorations(update.view);
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
decorations: (x) => x.decorations,
|
||||
}
|
||||
);
|
||||
},
|
||||
);
|
||||
+14
-5
@@ -1,14 +1,23 @@
|
||||
import "obsidian";
|
||||
import type { ExcalidrawAutomate } from "src/shared/ExcalidrawAutomate";
|
||||
import type ExcalidrawView from "src/view/ExcalidrawView";
|
||||
//import { ExcalidrawAutomate } from "./ExcalidrawAutomate";
|
||||
//export ExcalidrawAutomate from "./ExcalidrawAutomate";
|
||||
//export {ExcalidrawAutomate} from "./ExcaildrawAutomate";
|
||||
export type { ExcalidrawBindableElement, ExcalidrawElement, FileId, FillStyle, StrokeRoundness, StrokeStyle } from "@zsviczian/excalidraw/types/element/src/types";
|
||||
export type {
|
||||
ExcalidrawBindableElement,
|
||||
ExcalidrawElement,
|
||||
FileId,
|
||||
FillStyle,
|
||||
StrokeRoundness,
|
||||
StrokeStyle,
|
||||
} from "@zsviczian/excalidraw/types/element/src/types";
|
||||
export type { Point } from "src/types/types";
|
||||
export const getEA = (view?:any): any => {
|
||||
export const getEA = (view?: ExcalidrawView): ExcalidrawAutomate | null => {
|
||||
try {
|
||||
return window.ExcalidrawAutomate.getAPI(view);
|
||||
} catch(e) {
|
||||
console.log({message: "Excalidraw not available", fn: getEA});
|
||||
} catch (_) {
|
||||
console.log({ message: "Excalidraw not available", fn: getEA });
|
||||
return null;
|
||||
}
|
||||
}
|
||||
};
|
||||
+974
-283
File diff suppressed because it is too large.
Load diff
+1151
-514
File diff suppressed because it is too large.
Load diff
+221
-108
@@ -1,34 +1,54 @@
|
||||
import { WorkspaceLeaf, TFile, Editor, MarkdownView, MarkdownFileInfo, MetadataCache, App, EventRef, Menu, FileView } from "obsidian";
|
||||
import {
|
||||
WorkspaceLeaf,
|
||||
TFile,
|
||||
Editor,
|
||||
MarkdownView,
|
||||
MarkdownFileInfo,
|
||||
MetadataCache,
|
||||
App,
|
||||
EventRef,
|
||||
Menu,
|
||||
FileView,
|
||||
} from "obsidian";
|
||||
import { ExcalidrawElement } from "@zsviczian/excalidraw/types/element/src/types";
|
||||
import { getLink } from "../../utils/fileUtils";
|
||||
import { editorInsertText, getExcalidrawViews, getParentOfClass, isUnwantedLeaf, setExcalidrawView } from "../../utils/obsidianUtils";
|
||||
import {
|
||||
editorInsertText,
|
||||
getExcalidrawViews,
|
||||
getParentOfClass,
|
||||
isUnwantedLeaf,
|
||||
setExcalidrawView,
|
||||
} from "../../utils/obsidianUtils";
|
||||
import ExcalidrawPlugin from "src/core/main";
|
||||
import { DEBUGGING, debug } from "src/utils/debugHelper";
|
||||
import { ExcalidrawAutomate } from "src/shared/ExcalidrawAutomate";
|
||||
import { DEVICE, FRONTMATTER_KEYS, ICON_NAME, VIEW_TYPE_EXCALIDRAW } from "src/constants/constants";
|
||||
import {
|
||||
FRONTMATTER_KEYS,
|
||||
ICON_NAME,
|
||||
VIEW_TYPE_EXCALIDRAW,
|
||||
} from "src/constants/constants";
|
||||
import ExcalidrawView from "src/view/ExcalidrawView";
|
||||
import { t } from "src/lang/helpers";
|
||||
import { setMobileNavbarPosition } from "src/utils/excalidrawViewUtils";
|
||||
|
||||
/**
|
||||
* Registers event listeners for the plugin
|
||||
* Must be constructed after the workspace is ready (onLayoutReady)
|
||||
* Must be constructed after the workspace is ready (onLayoutReady)
|
||||
* Intended to be called from onLayoutReady in onload()
|
||||
*/
|
||||
export class EventManager {
|
||||
private plugin: ExcalidrawPlugin;
|
||||
private app: App;
|
||||
public leafChangeTimeout: number|null = null;
|
||||
private removeEventLisnters:(()=>void)[] = []; //only used if I register an event directly, not via Obsidian's registerEvent
|
||||
public leafChangeTimeout: number | null = null;
|
||||
private removeEventLisnters: (() => void)[] = []; //only used if I register an event directly, not via Obsidian's registerEvent
|
||||
private previouslyActiveLeaf: WorkspaceLeaf;
|
||||
private splitViewLeafSwitchTimestamp: number = 0;
|
||||
private debunceActiveLeafChangeHandlerTimer: number|null = null;
|
||||
private debunceActiveLeafChangeHandlerTimer: number | null = null;
|
||||
|
||||
get settings() {
|
||||
return this.plugin.settings;
|
||||
}
|
||||
|
||||
get ea():ExcalidrawAutomate {
|
||||
get ea(): ExcalidrawAutomate {
|
||||
return this.plugin.ea;
|
||||
}
|
||||
|
||||
@@ -43,18 +63,18 @@ export class EventManager {
|
||||
private registerEvent(eventRef: EventRef): void {
|
||||
this.plugin.registerEvent(eventRef);
|
||||
}
|
||||
|
||||
|
||||
constructor(plugin: ExcalidrawPlugin) {
|
||||
this.plugin = plugin;
|
||||
this.app = plugin.app;
|
||||
}
|
||||
|
||||
destroy() {
|
||||
if(this.leafChangeTimeout) {
|
||||
if (this.leafChangeTimeout) {
|
||||
window.clearTimeout(this.leafChangeTimeout);
|
||||
this.leafChangeTimeout = null;
|
||||
}
|
||||
if(this.debunceActiveLeafChangeHandlerTimer) {
|
||||
if (this.debunceActiveLeafChangeHandlerTimer) {
|
||||
window.clearTimeout(this.debunceActiveLeafChangeHandlerTimer);
|
||||
this.debunceActiveLeafChangeHandlerTimer = null;
|
||||
}
|
||||
@@ -73,30 +93,60 @@ export class EventManager {
|
||||
this.plugin.logStartupEvent("Event listeners registered");
|
||||
}
|
||||
|
||||
public isRecentSplitViewSwitch():boolean {
|
||||
return (Date.now() - this.splitViewLeafSwitchTimestamp) < 3000;
|
||||
public isRecentSplitViewSwitch(): boolean {
|
||||
return Date.now() - this.splitViewLeafSwitchTimestamp < 3000;
|
||||
}
|
||||
|
||||
public async registerEvents() {
|
||||
await this.plugin.awaitInit();
|
||||
this.registerEvent(this.app.workspace.on("editor-paste", this.onPasteHandler.bind(this)));
|
||||
this.registerEvent(this.app.vault.on("rename", this.onRenameHandler.bind(this)));
|
||||
this.registerEvent(this.app.vault.on("modify", this.onModifyHandler.bind(this)));
|
||||
this.registerEvent(this.app.vault.on("delete", this.onDeleteHandler.bind(this)));
|
||||
this.registerEvent(
|
||||
this.app.workspace.on("editor-paste", this.onPasteHandler.bind(this)),
|
||||
);
|
||||
this.registerEvent(
|
||||
this.app.vault.on("rename", this.onRenameHandler.bind(this)),
|
||||
);
|
||||
this.registerEvent(
|
||||
this.app.vault.on("modify", this.onModifyHandler.bind(this)),
|
||||
);
|
||||
this.registerEvent(
|
||||
this.app.vault.on("delete", this.onDeleteHandler.bind(this)),
|
||||
);
|
||||
|
||||
//save Excalidraw leaf and update embeds when switching to another leaf
|
||||
this.registerEvent(this.plugin.app.workspace.on("active-leaf-change", this.onActiveLeafChangeHandler.bind(this)));
|
||||
this.registerEvent(
|
||||
this.plugin.app.workspace.on(
|
||||
"active-leaf-change",
|
||||
this.onActiveLeafChangeHandler.bind(this),
|
||||
),
|
||||
);
|
||||
|
||||
this.registerEvent(this.app.workspace.on("layout-change", this.onLayoutChangeHandler.bind(this)));
|
||||
this.registerEvent(
|
||||
this.app.workspace.on(
|
||||
"layout-change",
|
||||
this.onLayoutChangeHandler.bind(this),
|
||||
),
|
||||
);
|
||||
|
||||
//File Save Trigger Handlers
|
||||
//Save the drawing if the user clicks outside the Excalidraw Canvas
|
||||
const onClickEventSaveActiveDrawing = this.onClickSaveActiveDrawing.bind(this);
|
||||
this.app.workspace.containerEl.addEventListener("click", onClickEventSaveActiveDrawing);
|
||||
const onClickEventSaveActiveDrawing =
|
||||
this.onClickSaveActiveDrawing.bind(this);
|
||||
this.app.workspace.containerEl.addEventListener(
|
||||
"click",
|
||||
onClickEventSaveActiveDrawing,
|
||||
);
|
||||
this.removeEventLisnters.push(() => {
|
||||
this.app.workspace.containerEl.removeEventListener("click", onClickEventSaveActiveDrawing)
|
||||
this.app.workspace.containerEl.removeEventListener(
|
||||
"click",
|
||||
onClickEventSaveActiveDrawing,
|
||||
);
|
||||
});
|
||||
this.registerEvent(this.app.workspace.on("file-menu", this.onFileMenuSaveActiveDrawing.bind(this)));
|
||||
this.registerEvent(
|
||||
this.app.workspace.on(
|
||||
"file-menu",
|
||||
this.onFileMenuSaveActiveDrawing.bind(this),
|
||||
),
|
||||
);
|
||||
|
||||
const metaCache: MetadataCache = this.app.metadataCache;
|
||||
this.registerEvent(
|
||||
@@ -105,12 +155,19 @@ export class EventManager {
|
||||
),
|
||||
);
|
||||
|
||||
this.registerEvent(this.app.workspace.on("file-menu", this.onFileMenuHandler.bind(this)));
|
||||
this.plugin.registerEvent(this.plugin.app.workspace.on("editor-menu", this.onEditorMenuHandler.bind(this)));
|
||||
this.registerEvent(
|
||||
this.app.workspace.on("file-menu", this.onFileMenuHandler.bind(this)),
|
||||
);
|
||||
this.plugin.registerEvent(
|
||||
this.plugin.app.workspace.on(
|
||||
"editor-menu",
|
||||
this.onEditorMenuHandler.bind(this),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
public setDebounceActiveLeafChangeHandler() {
|
||||
if(this.debunceActiveLeafChangeHandlerTimer) {
|
||||
if (this.debunceActiveLeafChangeHandlerTimer) {
|
||||
window.clearTimeout(this.debunceActiveLeafChangeHandlerTimer);
|
||||
}
|
||||
this.debunceActiveLeafChangeHandlerTimer = window.setTimeout(() => {
|
||||
@@ -119,34 +176,57 @@ export class EventManager {
|
||||
}
|
||||
|
||||
private onLayoutChangeHandler() {
|
||||
getExcalidrawViews(this.app).forEach(excalidrawView=>excalidrawView.refresh());
|
||||
if (this.app.workspace.layoutReady) {
|
||||
getExcalidrawViews(this.app, true).forEach(
|
||||
(excalidrawView) =>
|
||||
!!excalidrawView?.refresh && excalidrawView.refresh(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private onPasteHandler (evt: ClipboardEvent, editor: Editor, info: MarkdownView | MarkdownFileInfo ) {
|
||||
if(evt.defaultPrevented) return
|
||||
private onPasteHandler(
|
||||
evt: ClipboardEvent,
|
||||
editor: Editor,
|
||||
info: MarkdownView | MarkdownFileInfo,
|
||||
) {
|
||||
if (evt.defaultPrevented) {
|
||||
return;
|
||||
}
|
||||
const data = evt.clipboardData.getData("text/plain");
|
||||
if (!data) return;
|
||||
if (!data) {
|
||||
return;
|
||||
}
|
||||
if (data.startsWith(`{"type":"excalidraw/clipboard"`)) {
|
||||
evt.preventDefault();
|
||||
try {
|
||||
const drawing = JSON.parse(data);
|
||||
const hasOneTextElement = drawing.elements.filter((el:ExcalidrawElement)=>el.type==="text").length === 1;
|
||||
const hasOneTextElement =
|
||||
drawing.elements.filter((el: ExcalidrawElement) => el.type === "text")
|
||||
.length === 1;
|
||||
if (!(hasOneTextElement || drawing.elements?.length === 1)) {
|
||||
return;
|
||||
}
|
||||
const element = hasOneTextElement
|
||||
? drawing.elements.filter((el:ExcalidrawElement)=>el.type==="text")[0]
|
||||
? drawing.elements.filter(
|
||||
(el: ExcalidrawElement) => el.type === "text",
|
||||
)[0]
|
||||
: drawing.elements[0];
|
||||
if (element.type === "image") {
|
||||
const fileinfo = this.plugin.filesMaster.get(element.fileId);
|
||||
if(fileinfo && fileinfo.path) {
|
||||
let path = fileinfo.path;
|
||||
if (fileinfo && fileinfo.path) {
|
||||
let path = fileinfo.path.split("|")[0]; // strip size anchoring (e.g. |100%)
|
||||
const sourceFile = info.file;
|
||||
const imageFile = this.app.vault.getAbstractFileByPath(path);
|
||||
if(sourceFile && imageFile && imageFile instanceof TFile) {
|
||||
path = this.app.metadataCache.fileToLinktext(imageFile,sourceFile.path);
|
||||
if (sourceFile && imageFile && imageFile instanceof TFile) {
|
||||
path = this.app.metadataCache.fileToLinktext(
|
||||
imageFile,
|
||||
sourceFile.path,
|
||||
);
|
||||
}
|
||||
editorInsertText(editor, getLink(this.plugin, {path}));
|
||||
if (fileinfo.blockrefData) {
|
||||
path = `${path}#${fileinfo.blockrefData.split("|")[0]}`; // strip size anchoring (e.g. |100%)
|
||||
}
|
||||
editorInsertText(editor, getLink(this.plugin, { path }));
|
||||
}
|
||||
return;
|
||||
}
|
||||
@@ -156,36 +236,33 @@ export class EventManager {
|
||||
}
|
||||
if (element.link) {
|
||||
editorInsertText(editor, `${element.link}`);
|
||||
return;
|
||||
}
|
||||
} catch (e) {
|
||||
}
|
||||
} catch (_) {}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private onRenameHandler(file: TFile, oldPath: string) {
|
||||
this.plugin.renameEventHandler(file, oldPath);
|
||||
void this.plugin.renameEventHandler(file, oldPath);
|
||||
}
|
||||
|
||||
private onModifyHandler(file: TFile) {
|
||||
this.plugin.modifyEventHandler(file);
|
||||
void this.plugin.modifyEventHandler(file);
|
||||
}
|
||||
|
||||
private onDeleteHandler(file: TFile) {
|
||||
this.plugin.deleteEventHandler(file);
|
||||
void this.plugin.deleteEventHandler(file);
|
||||
}
|
||||
|
||||
public async onActiveLeafChangeHandler (leaf: WorkspaceLeaf) {
|
||||
(process.env.NODE_ENV === 'development') && DEBUGGING && debug(this.onActiveLeafChangeHandler,`onActiveLeafChangeEventHandler`, leaf);
|
||||
public async onActiveLeafChangeHandler(leaf: WorkspaceLeaf) {
|
||||
//https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/723
|
||||
|
||||
if(this.debunceActiveLeafChangeHandlerTimer) {
|
||||
return;
|
||||
}
|
||||
if (this.debunceActiveLeafChangeHandlerTimer) {
|
||||
return;
|
||||
}
|
||||
|
||||
//In Obsidian 1.8.x the active excalidraw leaf is obscured by an empty leaf without a parent
|
||||
//This hack resolves it
|
||||
if(this.app.workspace.activeLeaf === leaf && isUnwantedLeaf(leaf)) {
|
||||
if (this.app.workspace.activeLeaf === leaf && isUnwantedLeaf(leaf)) {
|
||||
leaf.detach();
|
||||
return;
|
||||
}
|
||||
@@ -197,21 +274,25 @@ export class EventManager {
|
||||
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)) {
|
||||
const lastLeaf = this.app.workspace.getLeafById(
|
||||
this.plugin.lastActiveExcalidrawLeafID,
|
||||
);
|
||||
if (!lastLeaf || !(lastLeaf.view instanceof ExcalidrawView)) {
|
||||
this.plugin.lastActiveExcalidrawLeafID = null;
|
||||
}
|
||||
}
|
||||
|
||||
if(this.leafChangeTimeout) {
|
||||
if (this.leafChangeTimeout) {
|
||||
window.clearTimeout(this.leafChangeTimeout);
|
||||
}
|
||||
this.leafChangeTimeout = window.setTimeout(()=>{this.leafChangeTimeout = null;},1000);
|
||||
this.leafChangeTimeout = window.setTimeout(() => {
|
||||
this.leafChangeTimeout = null;
|
||||
}, 1000);
|
||||
|
||||
if(this.settings.overrideObsidianFontSize) {
|
||||
if(leaf.view && (leaf.view.getViewType() === VIEW_TYPE_EXCALIDRAW)) {
|
||||
if (this.settings.overrideObsidianFontSize) {
|
||||
if (leaf.view && leaf.view.getViewType() === VIEW_TYPE_EXCALIDRAW) {
|
||||
document.documentElement.style.fontSize = "";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const previouslyActiveEV = this.activeExcalidrawView;
|
||||
@@ -221,13 +302,16 @@ export class EventManager {
|
||||
const previousFile = (this.previouslyActiveLeaf?.view as FileView)?.file;
|
||||
const currentFile = (leaf?.view as FileView).file;
|
||||
//editing the same file in a different leaf
|
||||
if(currentFile && (previousFile === currentFile)) {
|
||||
if((this.previouslyActiveLeaf.view instanceof MarkdownView && leaf.view instanceof ExcalidrawView)) {
|
||||
if (currentFile && previousFile === currentFile) {
|
||||
if (
|
||||
this.previouslyActiveLeaf.view instanceof MarkdownView &&
|
||||
leaf.view instanceof ExcalidrawView
|
||||
) {
|
||||
this.splitViewLeafSwitchTimestamp = Date.now();
|
||||
}
|
||||
}
|
||||
this.previouslyActiveLeaf = leaf;
|
||||
|
||||
|
||||
if (newActiveviewEV) {
|
||||
this.plugin.addModalContainerObserver();
|
||||
this.plugin.lastActiveExcalidrawFilePath = newActiveviewEV.file?.path;
|
||||
@@ -243,7 +327,10 @@ export class EventManager {
|
||||
if (previouslyActiveEV.leaf !== leaf) {
|
||||
//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) {
|
||||
if (
|
||||
previouslyActiveEV?.isDirty() &&
|
||||
!previouslyActiveEV.semaphores?.viewunload
|
||||
) {
|
||||
await previouslyActiveEV.save(true); //this will update transclusions in the drawing
|
||||
}
|
||||
}
|
||||
@@ -260,7 +347,7 @@ export class EventManager {
|
||||
//timeout gives time to the view being exited to finish saving
|
||||
const f = newActiveviewEV.file;
|
||||
if (newActiveviewEV.file) {
|
||||
setTimeout(() => {
|
||||
window.setTimeout(() => {
|
||||
if (!newActiveviewEV || !newActiveviewEV._loaded) {
|
||||
return;
|
||||
}
|
||||
@@ -270,21 +357,22 @@ export class EventManager {
|
||||
if (newActiveviewEV.activeLoader) {
|
||||
return;
|
||||
}
|
||||
newActiveviewEV.loadSceneFiles();
|
||||
void newActiveviewEV.loadSceneFiles();
|
||||
}, 2000);
|
||||
} //refresh embedded files
|
||||
}
|
||||
|
||||
|
||||
if (
|
||||
newActiveviewEV && newActiveviewEV._loaded &&
|
||||
newActiveviewEV.isLoaded && newActiveviewEV.excalidrawAPI &&
|
||||
newActiveviewEV &&
|
||||
newActiveviewEV._loaded &&
|
||||
newActiveviewEV.isLoaded &&
|
||||
newActiveviewEV.excalidrawAPI &&
|
||||
this.ea.onCanvasColorChangeHook
|
||||
) {
|
||||
this.ea.onCanvasColorChangeHook(
|
||||
this.ea,
|
||||
newActiveviewEV,
|
||||
newActiveviewEV.excalidrawAPI.getAppState().viewBackgroundColor
|
||||
newActiveviewEV.excalidrawAPI.getAppState().viewBackgroundColor,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -303,64 +391,89 @@ export class EventManager {
|
||||
if (
|
||||
!this.activeExcalidrawView ||
|
||||
!this.activeExcalidrawView?.isDirty() ||
|
||||
e.target && ((e.target as Element).className === "excalidraw__canvas" ||
|
||||
getParentOfClass((e.target as Element),"excalidraw-wrapper"))
|
||||
(e.target &&
|
||||
((e.target as Element).className === "excalidraw__canvas" ||
|
||||
getParentOfClass(e.target as Element, "excalidraw-wrapper")))
|
||||
) {
|
||||
return;
|
||||
}
|
||||
this.activeExcalidrawView.save();
|
||||
void this.activeExcalidrawView.save();
|
||||
}
|
||||
|
||||
private onFileMenuSaveActiveDrawing () {
|
||||
(process.env.NODE_ENV === 'development') && DEBUGGING && debug(this.onFileMenuSaveActiveDrawing,`onFileMenuSaveActiveDrawing`);
|
||||
private onFileMenuSaveActiveDrawing() {
|
||||
if (!this.activeExcalidrawView || !this.activeExcalidrawView?.isDirty()) {
|
||||
return;
|
||||
}
|
||||
void this.activeExcalidrawView.save();
|
||||
}
|
||||
|
||||
private onFileMenuHandler(
|
||||
menu: Menu,
|
||||
file: TFile,
|
||||
source: string,
|
||||
leaf: WorkspaceLeaf,
|
||||
) {
|
||||
if (!leaf) {
|
||||
return;
|
||||
}
|
||||
const view = leaf.view;
|
||||
if (!view || !(view instanceof MarkdownView)) {
|
||||
return;
|
||||
}
|
||||
if (!(file instanceof TFile)) {
|
||||
return;
|
||||
}
|
||||
const cache = this.app.metadataCache.getFileCache(file);
|
||||
if (
|
||||
!this.activeExcalidrawView ||
|
||||
!this.activeExcalidrawView?.isDirty()
|
||||
!cache?.frontmatter ||
|
||||
!cache.frontmatter[FRONTMATTER_KEYS.plugin.name]
|
||||
) {
|
||||
return;
|
||||
}
|
||||
this.activeExcalidrawView.save();
|
||||
};
|
||||
|
||||
private onFileMenuHandler(menu: Menu, file: TFile, source: string, leaf: WorkspaceLeaf) {
|
||||
(process.env.NODE_ENV === 'development') && DEBUGGING && debug(this.onFileMenuHandler, `EventManager.onFileMenuHandler`, file, source, leaf);
|
||||
if (!leaf) return;
|
||||
const view = leaf.view;
|
||||
if(!view || !(view instanceof MarkdownView)) return;
|
||||
if (!(file instanceof TFile)) return;
|
||||
const cache = this.app.metadataCache.getFileCache(file);
|
||||
if (!cache?.frontmatter || !cache.frontmatter[FRONTMATTER_KEYS["plugin"].name]) return;
|
||||
|
||||
menu.addItem(item => {
|
||||
menu.addItem((item) => {
|
||||
item
|
||||
.setTitle(t("OPEN_AS_EXCALIDRAW"))
|
||||
.setIcon(ICON_NAME)
|
||||
.setSection("pane")
|
||||
.onClick(async () => {
|
||||
await view.save();
|
||||
this.plugin.excalidrawFileModes[leaf.id || file.path] = VIEW_TYPE_EXCALIDRAW;
|
||||
setExcalidrawView(leaf);
|
||||
})});
|
||||
.setTitle(t("OPEN_AS_EXCALIDRAW"))
|
||||
.setIcon(ICON_NAME)
|
||||
.setSection("pane")
|
||||
.onClick(async () => {
|
||||
await view.save();
|
||||
this.plugin.excalidrawFileModes[leaf.id || file.path] =
|
||||
VIEW_TYPE_EXCALIDRAW;
|
||||
void setExcalidrawView(leaf);
|
||||
});
|
||||
});
|
||||
menu.items.unshift(menu.items.pop());
|
||||
}
|
||||
|
||||
private onEditorMenuHandler(menu: Menu, editor: Editor, view: MarkdownView) {
|
||||
if(!view || !(view instanceof MarkdownView)) return;
|
||||
if (!view || !(view instanceof MarkdownView)) {
|
||||
return;
|
||||
}
|
||||
const file = view.file;
|
||||
const leaf = view.leaf;
|
||||
if (!view.file) return;
|
||||
if (!view.file) {
|
||||
return;
|
||||
}
|
||||
const cache = this.app.metadataCache.getFileCache(file);
|
||||
if (!cache?.frontmatter || !cache.frontmatter[FRONTMATTER_KEYS["plugin"].name]) return;
|
||||
|
||||
menu.addItem(item => item
|
||||
.setTitle(t("OPEN_AS_EXCALIDRAW"))
|
||||
.setIcon(ICON_NAME)
|
||||
.setSection("excalidraw")
|
||||
.onClick(async () => {
|
||||
await view.save();
|
||||
this.plugin.excalidrawFileModes[leaf.id || file.path] = VIEW_TYPE_EXCALIDRAW;
|
||||
setExcalidrawView(leaf);
|
||||
})
|
||||
if (
|
||||
!cache?.frontmatter ||
|
||||
!cache.frontmatter[FRONTMATTER_KEYS.plugin.name]
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
menu.addItem((item) =>
|
||||
item
|
||||
.setTitle(t("OPEN_AS_EXCALIDRAW"))
|
||||
.setIcon(ICON_NAME)
|
||||
.setSection("excalidraw")
|
||||
.onClick(async () => {
|
||||
await view.save();
|
||||
this.plugin.excalidrawFileModes[leaf.id || file.path] =
|
||||
VIEW_TYPE_EXCALIDRAW;
|
||||
void setExcalidrawView(leaf);
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
+366
-198
@@ -1,14 +1,50 @@
|
||||
import { debug } from "src/utils/debugHelper";
|
||||
import { App, FrontMatterCache, MarkdownView, MetadataCache, normalizePath, Notice, TAbstractFile, TFile, WorkspaceLeaf } from "obsidian";
|
||||
import { BLANK_DRAWING, DARK_BLANK_DRAWING, DEVICE, EXPORT_TYPES, FRONTMATTER, FRONTMATTER_KEYS, JSON_parse, nanoid, VIEW_TYPE_EXCALIDRAW } from "src/constants/constants";
|
||||
import {
|
||||
App,
|
||||
FrontMatterCache,
|
||||
MarkdownView,
|
||||
MetadataCache,
|
||||
normalizePath,
|
||||
Notice,
|
||||
TAbstractFile,
|
||||
TFile,
|
||||
WorkspaceLeaf,
|
||||
} from "obsidian";
|
||||
import {
|
||||
BLANK_DRAWING,
|
||||
DARK_BLANK_DRAWING,
|
||||
DEVICE,
|
||||
EXPORT_TYPES,
|
||||
FRONTMATTER,
|
||||
FRONTMATTER_KEYS,
|
||||
JSON_parse,
|
||||
nanoid,
|
||||
VIEW_TYPE_EXCALIDRAW,
|
||||
} from "src/constants/constants";
|
||||
import { Prompt, templatePromt } from "src/shared/Dialogs/Prompt";
|
||||
import { changeThemeOfExcalidrawMD, ExcalidrawData, getMarkdownDrawingSection } from "../../shared/ExcalidrawData";
|
||||
import ExcalidrawView, { getTextMode } from "src/view/ExcalidrawView";
|
||||
import {
|
||||
changeThemeOfExcalidrawMD,
|
||||
ExcalidrawData,
|
||||
getMarkdownDrawingSection,
|
||||
} from "../../shared/ExcalidrawData";
|
||||
import ExcalidrawView from "src/view/ExcalidrawView";
|
||||
import { getTextMode } from "src/shared/TextMode";
|
||||
import ExcalidrawPlugin from "src/core/main";
|
||||
import { DEBUGGING } from "src/utils/debugHelper";
|
||||
import { checkAndCreateFolder, createFileAndAwaitMetacacheUpdate, download, getIMGFilename, getLink, getListOfTemplateFiles, getNewUniqueFilepath } from "src/utils/fileUtils";
|
||||
import {
|
||||
checkAndCreateFolder,
|
||||
createFileAndAwaitMetacacheUpdate,
|
||||
download,
|
||||
getIMGFilename,
|
||||
getLink,
|
||||
getListOfTemplateFiles,
|
||||
getNewUniqueFilepath,
|
||||
} from "src/utils/fileUtils";
|
||||
import { PaneTarget } from "src/utils/modifierkeyHelper";
|
||||
import { getExcalidrawViews, getNewOrAdjacentLeaf, isObsidianThemeDark, openLeaf } from "src/utils/obsidianUtils";
|
||||
import {
|
||||
getExcalidrawViews,
|
||||
getNewOrAdjacentLeaf,
|
||||
isObsidianThemeDark,
|
||||
openLeaf,
|
||||
} from "src/utils/obsidianUtils";
|
||||
import { errorlog, getExportTheme } from "src/utils/utils";
|
||||
import { imageCache } from "src/shared/ImageCache";
|
||||
|
||||
@@ -32,24 +68,26 @@ export class PluginFileManager {
|
||||
metaCache.getCachedFiles().forEach((filename: string) => {
|
||||
const fm = metaCache.getCache(filename)?.frontmatter;
|
||||
if (
|
||||
(fm && typeof fm[FRONTMATTER_KEYS["plugin"].name] !== "undefined") ||
|
||||
(fm && typeof fm[FRONTMATTER_KEYS.plugin.name] !== "undefined") ||
|
||||
filename.match(/\.excalidraw$/)
|
||||
) {
|
||||
this.updateFileCache(
|
||||
this.app.vault.getAbstractFileByPath(filename) as TFile,
|
||||
fm,
|
||||
);
|
||||
this.updateFileCache(this.app.vault.getFileByPath(filename), fm);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public isExcalidrawFile(f: TFile): boolean {
|
||||
if(!f) return false;
|
||||
if (!f) {
|
||||
return false;
|
||||
}
|
||||
if (f.extension === "excalidraw") {
|
||||
return true;
|
||||
}
|
||||
const fileCache = f ? this.plugin.app.metadataCache.getFileCache(f) : null;
|
||||
return !!fileCache?.frontmatter && !!fileCache.frontmatter[FRONTMATTER_KEYS["plugin"].name];
|
||||
return (
|
||||
!!fileCache?.frontmatter &&
|
||||
!!fileCache.frontmatter[FRONTMATTER_KEYS.plugin.name]
|
||||
);
|
||||
}
|
||||
|
||||
//managing my own list of Excalidraw files because in the onDelete event handler
|
||||
@@ -59,7 +97,10 @@ export class PluginFileManager {
|
||||
frontmatter?: FrontMatterCache,
|
||||
deleted: boolean = false,
|
||||
) {
|
||||
if (frontmatter && typeof frontmatter[FRONTMATTER_KEYS["plugin"].name] !== "undefined") {
|
||||
if (
|
||||
frontmatter &&
|
||||
typeof frontmatter[FRONTMATTER_KEYS.plugin.name] !== "undefined"
|
||||
) {
|
||||
this.excalidrawFiles.add(file);
|
||||
return;
|
||||
}
|
||||
@@ -92,15 +133,23 @@ export class PluginFileManager {
|
||||
fname,
|
||||
initData ?? (await this.plugin.getBlankDrawing()),
|
||||
);
|
||||
|
||||
|
||||
//wait for metadata cache
|
||||
let counter = 0;
|
||||
while(file instanceof TFile && !this.isExcalidrawFile(file) && counter++<10) {
|
||||
while (
|
||||
file instanceof TFile &&
|
||||
!this.isExcalidrawFile(file) &&
|
||||
counter++ < 10
|
||||
) {
|
||||
await sleep(50);
|
||||
}
|
||||
|
||||
if(counter > 10) {
|
||||
errorlog({file, error: "new drawing not recognized as an excalidraw file", fn: this.createDrawing});
|
||||
|
||||
if (counter > 10) {
|
||||
errorlog({
|
||||
file,
|
||||
error: "new drawing not recognized as an excalidraw file",
|
||||
fn: this.createDrawing,
|
||||
});
|
||||
}
|
||||
|
||||
return file;
|
||||
@@ -108,12 +157,13 @@ export class PluginFileManager {
|
||||
|
||||
public async getBlankDrawing(): Promise<string> {
|
||||
const templates = getListOfTemplateFiles(this.plugin);
|
||||
if(templates) {
|
||||
if (templates) {
|
||||
const template = await templatePromt(templates, this.app);
|
||||
if (template && template instanceof TFile) {
|
||||
if (
|
||||
(template.extension == "md" && !this.settings.compatibilityMode) ||
|
||||
(template.extension == "excalidraw" && this.settings.compatibilityMode)
|
||||
(template.extension == "excalidraw" &&
|
||||
this.settings.compatibilityMode)
|
||||
) {
|
||||
const data = await this.app.vault.read(template);
|
||||
if (data) {
|
||||
@@ -152,7 +202,7 @@ export class PluginFileManager {
|
||||
//embed Excalidraw
|
||||
if (this.settings.embedType === "excalidraw") {
|
||||
editor.replaceSelection(
|
||||
getLink(this.plugin, {path: excalidrawRelativePath}),
|
||||
getLink(this.plugin, { path: excalidrawRelativePath }),
|
||||
);
|
||||
editor.focus();
|
||||
return;
|
||||
@@ -160,60 +210,117 @@ export class PluginFileManager {
|
||||
|
||||
//embed image
|
||||
let theme = this.settings.autoExportLightAndDark
|
||||
? getExportTheme (
|
||||
this.plugin,
|
||||
file,
|
||||
this.settings.exportWithTheme
|
||||
? isObsidianThemeDark() ? "dark":"light"
|
||||
: "light"
|
||||
? getExportTheme(
|
||||
this.plugin,
|
||||
file,
|
||||
this.settings.exportWithTheme
|
||||
? isObsidianThemeDark()
|
||||
? "dark"
|
||||
: "light"
|
||||
: "light",
|
||||
)
|
||||
: "";
|
||||
|
||||
theme = (theme === "")
|
||||
? ""
|
||||
: theme + ".";
|
||||
theme = theme === "" ? "" : `${theme}.`;
|
||||
|
||||
const exportExtension = theme+this.settings.embedType.toLowerCase();
|
||||
let imageFullpath = getIMGFilename(
|
||||
file.path,
|
||||
exportExtension,
|
||||
);
|
||||
|
||||
if(this.plugin.ea?.onImageExportPathHook) {
|
||||
const exportExtension = theme + this.settings.embedType.toLowerCase();
|
||||
let imageFullpath = getIMGFilename(file.path, exportExtension);
|
||||
|
||||
if (this.plugin.ea?.onImageExportPathHook) {
|
||||
try {
|
||||
imageFullpath = this.plugin.ea.onImageExportPathHook({
|
||||
exportFilepath: imageFullpath,
|
||||
exportExtension,
|
||||
excalidrawFile: file,
|
||||
action: "export",
|
||||
}) ?? imageFullpath;
|
||||
imageFullpath =
|
||||
this.plugin.ea.onImageExportPathHook({
|
||||
exportFilepath: imageFullpath,
|
||||
exportExtension,
|
||||
excalidrawFile: file,
|
||||
action: "export",
|
||||
}) ?? imageFullpath;
|
||||
} catch (e) {
|
||||
errorlog({where: "FileManager.embedDrawing", fn: this.plugin.ea.onImageExportPathHook, error: e});
|
||||
errorlog({
|
||||
where: "FileManager.embedDrawing",
|
||||
fn: this.plugin.ea.onImageExportPathHook,
|
||||
error: e,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const createFile = async (path: string):Promise<TFile> => {
|
||||
return await createFileAndAwaitMetacacheUpdate(this.app, path,
|
||||
const createFile = async (path: string): Promise<TFile> => {
|
||||
return await createFileAndAwaitMetacacheUpdate(
|
||||
this.app,
|
||||
path,
|
||||
this.settings.embedType === "SVG"
|
||||
? `<svg version="1.1" xmlns="http://www.w3.org/2000/svg" width="0" height="0"></svg>`
|
||||
: new Uint8Array([
|
||||
0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, // PNG signature
|
||||
0x00, 0x00, 0x00, 0x0D, // IHDR chunk length
|
||||
0x49, 0x48, 0x44, 0x52, // IHDR
|
||||
0x00, 0x00, 0x00, 0x01, // width: 1
|
||||
0x00, 0x00, 0x00, 0x01, // height: 1
|
||||
0x08, 0x06, 0x00, 0x00, 0x00, // bit depth: 8, color type: 6 (RGBA), compression: 0, filter: 0, interlace: 0
|
||||
0x1F, 0x15, 0xC4, 0x89, // IHDR CRC
|
||||
0x00, 0x00, 0x00, 0x0B, // IDAT chunk length
|
||||
0x49, 0x44, 0x41, 0x54, // IDAT
|
||||
0x78, 0x9C, 0x62, 0x00, 0x02, 0x00, 0x00, 0x05, 0x00, 0x01, 0x0D, // compressed data (1x1 transparent pixel)
|
||||
0x0A, 0x2D, 0xB4, // IDAT CRC
|
||||
0x00, 0x00, 0x00, 0x00, // IEND chunk length
|
||||
0x49, 0x45, 0x4E, 0x44, // IEND
|
||||
0xAE, 0x42, 0x60, 0x82 // IEND CRC
|
||||
]).buffer
|
||||
0x89,
|
||||
0x50,
|
||||
0x4e,
|
||||
0x47,
|
||||
0x0d,
|
||||
0x0a,
|
||||
0x1a,
|
||||
0x0a, // PNG signature
|
||||
0x00,
|
||||
0x00,
|
||||
0x00,
|
||||
0x0d, // IHDR chunk length
|
||||
0x49,
|
||||
0x48,
|
||||
0x44,
|
||||
0x52, // IHDR
|
||||
0x00,
|
||||
0x00,
|
||||
0x00,
|
||||
0x01, // width: 1
|
||||
0x00,
|
||||
0x00,
|
||||
0x00,
|
||||
0x01, // height: 1
|
||||
0x08,
|
||||
0x06,
|
||||
0x00,
|
||||
0x00,
|
||||
0x00, // bit depth: 8, color type: 6 (RGBA), compression: 0, filter: 0, interlace: 0
|
||||
0x1f,
|
||||
0x15,
|
||||
0xc4,
|
||||
0x89, // IHDR CRC
|
||||
0x00,
|
||||
0x00,
|
||||
0x00,
|
||||
0x0b, // IDAT chunk length
|
||||
0x49,
|
||||
0x44,
|
||||
0x41,
|
||||
0x54, // IDAT
|
||||
0x78,
|
||||
0x9c,
|
||||
0x62,
|
||||
0x00,
|
||||
0x02,
|
||||
0x00,
|
||||
0x00,
|
||||
0x05,
|
||||
0x00,
|
||||
0x01,
|
||||
0x0d, // compressed data (1x1 transparent pixel)
|
||||
0x0a,
|
||||
0x2d,
|
||||
0xb4, // IDAT CRC
|
||||
0x00,
|
||||
0x00,
|
||||
0x00,
|
||||
0x00, // IEND chunk length
|
||||
0x49,
|
||||
0x45,
|
||||
0x4e,
|
||||
0x44, // IEND
|
||||
0xae,
|
||||
0x42,
|
||||
0x60,
|
||||
0x82, // IEND CRC
|
||||
]).buffer,
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
let imgFile = this.app.vault.getFileByPath(imageFullpath);
|
||||
if (!imgFile) {
|
||||
@@ -230,13 +337,21 @@ export class PluginFileManager {
|
||||
const otherTheme = theme === "dark." ? "light." : "dark.";
|
||||
//if the hook tinkers with the extension, then I cannot predict the other theme's extension
|
||||
//it would become a messy heuristic to try to guess the other theme's extension
|
||||
const otherImageRelativePath = ((theme === "") || !imageRelativePath.endsWith(exportExtension))
|
||||
? null
|
||||
: (imageRelativePath.substring(0, imageRelativePath.lastIndexOf(exportExtension)) + otherTheme+this.settings.embedType.toLowerCase());
|
||||
const otherImageRelativePath =
|
||||
theme === "" || !imageRelativePath.endsWith(exportExtension)
|
||||
? null
|
||||
: imageRelativePath.substring(
|
||||
0,
|
||||
imageRelativePath.lastIndexOf(exportExtension),
|
||||
) +
|
||||
otherTheme +
|
||||
this.settings.embedType.toLowerCase();
|
||||
|
||||
if(otherImageRelativePath) {
|
||||
if (otherImageRelativePath) {
|
||||
await createFile(
|
||||
imgFile.path.substring(0, imgFile.path.lastIndexOf(exportExtension)) + otherTheme+this.settings.embedType.toLowerCase()
|
||||
imgFile.path.substring(0, imgFile.path.lastIndexOf(exportExtension)) +
|
||||
otherTheme +
|
||||
this.settings.embedType.toLowerCase(),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -244,17 +359,24 @@ export class PluginFileManager {
|
||||
|
||||
editor.replaceSelection(
|
||||
this.settings.embedWikiLink
|
||||
? `![[${imageRelativePath}]]\n` +
|
||||
(inclCom
|
||||
? `%%[[${excalidrawRelativePath}|🖋 Edit in Excalidraw]]${
|
||||
otherImageRelativePath
|
||||
? ", and the [["+otherImageRelativePath+"|"+otherTheme.split(".")[0]+" exported image]]"
|
||||
: ""
|
||||
}%%`
|
||||
: "")
|
||||
: `})\n` +
|
||||
(inclCom ? `%%[🖋 Edit in Excalidraw](${encodeURI(excalidrawRelativePath,
|
||||
)})${otherImageRelativePath?", and the ["+otherTheme.split(".")[0]+" exported image]("+encodeURI(otherImageRelativePath)+")":""}%%` : ""),
|
||||
? `![[${imageRelativePath}]]\n${
|
||||
inclCom
|
||||
? `%%[[${excalidrawRelativePath}|🖋 Edit in Excalidraw]]${
|
||||
otherImageRelativePath
|
||||
? `, and the [[${otherImageRelativePath}|${
|
||||
otherTheme.split(".")[0]
|
||||
} exported image]]`
|
||||
: ""
|
||||
}%%`
|
||||
: ""
|
||||
}`
|
||||
: `})\n${
|
||||
inclCom
|
||||
? `%%[🖋 Edit in Excalidraw](${encodeURI(
|
||||
excalidrawRelativePath,
|
||||
)})${otherImageRelativePath ? `, and the [${otherTheme.split(".")[0]} exported image](${encodeURI(otherImageRelativePath)})` : ""}%%`
|
||||
: ""
|
||||
}`,
|
||||
);
|
||||
editor.focus();
|
||||
}
|
||||
@@ -268,7 +390,7 @@ export class PluginFileManager {
|
||||
"my-library",
|
||||
"filename, leave blank to cancel action",
|
||||
);
|
||||
prompt.openAndGetValue(async (filename: string) => {
|
||||
void prompt.openAndGetValue(async (filename: string) => {
|
||||
if (!filename) {
|
||||
return;
|
||||
}
|
||||
@@ -280,7 +402,7 @@ export class PluginFileManager {
|
||||
filename,
|
||||
folderpath,
|
||||
);
|
||||
this.app.vault.create(fname, this.settings.library);
|
||||
await this.app.vault.create(fname, this.settings.library);
|
||||
new Notice(`Exported library to ${fname}`, 6000);
|
||||
});
|
||||
return;
|
||||
@@ -294,12 +416,12 @@ export class PluginFileManager {
|
||||
|
||||
/**
|
||||
* Opens a drawing file
|
||||
* @param drawingFile
|
||||
* @param location
|
||||
* @param active
|
||||
* @param subpath
|
||||
* @param justCreated
|
||||
* @param popoutLocation
|
||||
* @param drawingFile
|
||||
* @param location
|
||||
* @param active
|
||||
* @param subpath
|
||||
* @param justCreated
|
||||
* @param popoutLocation
|
||||
*/
|
||||
public openDrawing(
|
||||
drawingFile: TFile,
|
||||
@@ -307,66 +429,84 @@ export class PluginFileManager {
|
||||
active: boolean = false,
|
||||
subpath?: string,
|
||||
justCreated: boolean = false,
|
||||
popoutLocation?: {x?: number, y?: number, width?: number, height?: number},
|
||||
popoutLocation?: {
|
||||
x?: number;
|
||||
y?: number;
|
||||
width?: number;
|
||||
height?: number;
|
||||
},
|
||||
) {
|
||||
|
||||
const fnGetLeaf = ():WorkspaceLeaf => {
|
||||
if(location === "md-properties") {
|
||||
const fnGetLeaf = (): WorkspaceLeaf => {
|
||||
if (location === "md-properties") {
|
||||
location = "new-tab";
|
||||
}
|
||||
let leaf: WorkspaceLeaf;
|
||||
if(location === "popout-window") {
|
||||
if (location === "popout-window") {
|
||||
leaf = this.app.workspace.openPopoutLeaf(popoutLocation);
|
||||
}
|
||||
if(location === "new-tab") {
|
||||
leaf = this.app.workspace.getLeaf('tab');
|
||||
if (location === "new-tab") {
|
||||
leaf = this.app.workspace.getLeaf("tab");
|
||||
}
|
||||
if(!leaf) {
|
||||
if (!leaf) {
|
||||
leaf = this.app.workspace.getLeaf(false);
|
||||
if ((leaf.view.getViewType() !== 'empty') && (location === "new-pane")) {
|
||||
leaf = getNewOrAdjacentLeaf(this.plugin, leaf)
|
||||
if (leaf.view.getViewType() !== "empty" && location === "new-pane") {
|
||||
leaf = getNewOrAdjacentLeaf(this.plugin, leaf);
|
||||
}
|
||||
}
|
||||
return leaf;
|
||||
}
|
||||
};
|
||||
|
||||
const {leaf, promise} = openLeaf({
|
||||
const { leaf, promise } = openLeaf({
|
||||
plugin: this.plugin,
|
||||
fnGetLeaf: () => fnGetLeaf(),
|
||||
file: drawingFile,
|
||||
openState:!subpath || subpath === ""
|
||||
? {active}
|
||||
: { active, eState: { subpath } }
|
||||
openState:
|
||||
!subpath || subpath === ""
|
||||
? { active }
|
||||
: { active, eState: { subpath } },
|
||||
});
|
||||
|
||||
promise.then(()=>{
|
||||
void promise.then(() => {
|
||||
const ea = this.plugin.ea;
|
||||
if(justCreated && ea.onFileCreateHook) {
|
||||
if (justCreated && ea.onFileCreateHook) {
|
||||
try {
|
||||
ea.onFileCreateHook({
|
||||
void ea.onFileCreateHook({
|
||||
ea,
|
||||
excalidrawFile: drawingFile,
|
||||
view: leaf.view as ExcalidrawView,
|
||||
});
|
||||
} catch(e) {
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
}
|
||||
}
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Extracts the text elements from an Excalidraw scene into a string of ids as headers followed by the text contents
|
||||
* @param {string} data - Excalidraw scene JSON string
|
||||
* @returns {string} - Text starting with the "# Text Elements" header and followed by each "## id-value" and text
|
||||
*/
|
||||
public async exportSceneToMD(data: string, compressOverride?: boolean): Promise<string> {
|
||||
* Extracts the text elements from an Excalidraw scene into a string of ids as headers followed by the text contents
|
||||
* @param {string} data - Excalidraw scene JSON string
|
||||
* @returns {string} - Text starting with the "# Text Elements" header and followed by each "## id-value" and text
|
||||
*/
|
||||
public async exportSceneToMD(
|
||||
data: string,
|
||||
compressOverride?: boolean,
|
||||
): Promise<string> {
|
||||
if (!data) {
|
||||
return "";
|
||||
}
|
||||
const excalidrawData = JSON_parse(data);
|
||||
const textElements = excalidrawData.elements?.filter(
|
||||
(el: any) => el.type == "text",
|
||||
type ExcalidrawSceneTextElement = {
|
||||
id: string;
|
||||
type?: string;
|
||||
text?: string;
|
||||
originalText?: string;
|
||||
};
|
||||
type ExcalidrawSceneData = {
|
||||
elements?: ExcalidrawSceneTextElement[];
|
||||
};
|
||||
|
||||
const excalidrawData = JSON_parse<ExcalidrawSceneData>(data);
|
||||
const textElements = (excalidrawData.elements ?? []).filter(
|
||||
(el) => el.type == "text",
|
||||
);
|
||||
let outString = `# Excalidraw Data\n\n## Text Elements\n`;
|
||||
let id: string;
|
||||
@@ -386,77 +526,94 @@ export class PluginFileManager {
|
||||
getMarkdownDrawingSection(
|
||||
JSON.stringify(JSON_parse(data), null, "\t"),
|
||||
typeof compressOverride === "undefined"
|
||||
? this.settings.compress
|
||||
: compressOverride,
|
||||
? this.settings.compress
|
||||
: compressOverride,
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
// -------------------------------------------------------
|
||||
// ------------------ Event Handlers ---------------------
|
||||
// -------------------------------------------------------
|
||||
|
||||
/**
|
||||
* watch filename change to rename .svg, .png; to sync to .md; to update links
|
||||
* @param file
|
||||
* @param oldPath
|
||||
* @returns
|
||||
* @param file
|
||||
* @param oldPath
|
||||
* @returns
|
||||
*/
|
||||
public async renameEventHandler (file: TAbstractFile, oldPath: string) {
|
||||
(process.env.NODE_ENV === 'development') && DEBUGGING && debug(this.renameEventHandler, `ExcalidrawPlugin.renameEventHandler`, file, oldPath);
|
||||
public async renameEventHandler(file: TAbstractFile, oldPath: string) {
|
||||
if (!(file instanceof TFile)) {
|
||||
return;
|
||||
}
|
||||
if (!this.isExcalidrawFile(file)) {
|
||||
return;
|
||||
}
|
||||
this.moveBAKFile(oldPath, file.path);
|
||||
|
||||
|
||||
if (
|
||||
this.app.workspace.activeLeaf?.view instanceof ExcalidrawView &&
|
||||
this.app.workspace.activeLeaf.view.file === file
|
||||
) {
|
||||
this.plugin.lastActiveExcalidrawFilePath = file.path;
|
||||
}
|
||||
|
||||
await this.moveBAKFile(oldPath, file.path);
|
||||
|
||||
if (!this.settings.keepInSync) {
|
||||
return;
|
||||
}
|
||||
const imgMap = new Map<string, {oldImgPath: string, newImgPath: string}>();
|
||||
[EXPORT_TYPES, "excalidraw"].flat().forEach(ext => {
|
||||
const imgMap = new Map<
|
||||
string,
|
||||
{ oldImgPath: string; newImgPath: string }
|
||||
>();
|
||||
[EXPORT_TYPES, "excalidraw"].flat().forEach((ext) => {
|
||||
let oldImgPath = getIMGFilename(oldPath, ext);
|
||||
let newImgPath = getIMGFilename(file.path, ext);
|
||||
if(this.plugin.ea?.onImageExportPathHook) {
|
||||
if (this.plugin.ea?.onImageExportPathHook) {
|
||||
try {
|
||||
oldImgPath = this.plugin.ea.onImageExportPathHook({
|
||||
exportFilepath: oldImgPath,
|
||||
exportExtension: ext,
|
||||
excalidrawFile: file,
|
||||
oldExcalidrawPath: oldPath,
|
||||
action: "move",
|
||||
}) ?? oldImgPath;
|
||||
newImgPath = this.plugin.ea.onImageExportPathHook({
|
||||
exportFilepath: newImgPath,
|
||||
exportExtension: ext,
|
||||
excalidrawFile: file,
|
||||
action: "export",
|
||||
}) ?? newImgPath;
|
||||
oldImgPath =
|
||||
this.plugin.ea.onImageExportPathHook({
|
||||
exportFilepath: oldImgPath,
|
||||
exportExtension: ext,
|
||||
excalidrawFile: file,
|
||||
oldExcalidrawPath: oldPath,
|
||||
action: "move",
|
||||
}) ?? oldImgPath;
|
||||
newImgPath =
|
||||
this.plugin.ea.onImageExportPathHook({
|
||||
exportFilepath: newImgPath,
|
||||
exportExtension: ext,
|
||||
excalidrawFile: file,
|
||||
action: "export",
|
||||
}) ?? newImgPath;
|
||||
} catch (e) {
|
||||
errorlog({where: "FileManager.renameEventHandler", fn: this.plugin.ea.onImageExportPathHook, error: e});
|
||||
errorlog({
|
||||
where: "FileManager.renameEventHandler",
|
||||
fn: this.plugin.ea.onImageExportPathHook,
|
||||
error: e,
|
||||
});
|
||||
}
|
||||
}
|
||||
imgMap.set(ext, { oldImgPath, newImgPath });
|
||||
});
|
||||
|
||||
imgMap.forEach((path, ext) => {
|
||||
imgMap.forEach((path) => {
|
||||
const imgFile = this.app.vault.getFileByPath(
|
||||
normalizePath(path.oldImgPath),
|
||||
);
|
||||
if (imgFile) {
|
||||
this.app.fileManager.renameFile(imgFile, normalizePath(path.newImgPath));
|
||||
void this.app.fileManager.renameFile(
|
||||
imgFile,
|
||||
normalizePath(path.newImgPath),
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public async modifyEventHandler (file: TFile) {
|
||||
(process.env.NODE_ENV === 'development') && DEBUGGING && debug(this.modifyEventHandler,`FileManager.modifyEventHandler`, file);
|
||||
public async modifyEventHandler(file: TFile) {
|
||||
const excalidrawViews = getExcalidrawViews(this.app);
|
||||
excalidrawViews.forEach(async (excalidrawView) => {
|
||||
if(excalidrawView.semaphores?.viewunload) {
|
||||
if (excalidrawView.semaphores?.viewunload) {
|
||||
return;
|
||||
}
|
||||
if (
|
||||
@@ -468,12 +625,11 @@ export class PluginFileManager {
|
||||
file.path.lastIndexOf(".excalidraw"),
|
||||
)}.md` === excalidrawView.file.path))
|
||||
) {
|
||||
if(excalidrawView.semaphores?.preventReload) {
|
||||
if (excalidrawView.semaphores?.preventReload) {
|
||||
excalidrawView.semaphores.preventReload = false;
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
// Avoid synchronizing or reloading if the user hasn't interacted with the file for 5 minutes.
|
||||
// This prevents complex sync issues when multiple remote changes occur outside an active collaboration session.
|
||||
|
||||
@@ -484,40 +640,51 @@ export class PluginFileManager {
|
||||
// 4. The "modify" event may fire while Excalidraw is active, triggering an unwanted reload and zoom reset.
|
||||
|
||||
// To address this:
|
||||
// - We check if the user is currently editing the Markdown version of the Excalidraw file in a split view.
|
||||
// - As a heuristic, we also check for recent leaf switches.
|
||||
// This is not perfectly accurate (e.g., rapid switching between views within a few seconds),
|
||||
// - We check if the user is currently editing the Markdown version of the Excalidraw file in a split view.
|
||||
// - As a heuristic, we also check for recent leaf switches.
|
||||
// This is not perfectly accurate (e.g., rapid switching between views within a few seconds),
|
||||
// but it is sufficient to avoid most edge cases without introducing complexity.
|
||||
|
||||
// Edge case impact:
|
||||
// - In extremely rare situations, an update arriving within the "recent switch" timeframe (e.g., from Obsidian Sync)
|
||||
// Edge case impact:
|
||||
// - In extremely rare situations, an update arriving within the "recent switch" timeframe (e.g., from Obsidian Sync)
|
||||
// might not trigger a reload. This is unlikely and an acceptable trade-off for better user experience.
|
||||
const activeView = this.app.workspace.activeLeaf.view;
|
||||
const isEditingMarkdownSideInSplitView = ((activeView !== excalidrawView) &&
|
||||
activeView instanceof MarkdownView && activeView.file === excalidrawView.file) ||
|
||||
(activeView === excalidrawView && this.plugin.isRecentSplitViewSwitch());
|
||||
const isEditingMarkdownSideInSplitView =
|
||||
(activeView !== excalidrawView &&
|
||||
activeView instanceof MarkdownView &&
|
||||
activeView.file === excalidrawView.file) ||
|
||||
(activeView === excalidrawView &&
|
||||
this.plugin.isRecentSplitViewSwitch());
|
||||
|
||||
if(!isEditingMarkdownSideInSplitView && (excalidrawView.lastSaveTimestamp + 300000 < Date.now())) {
|
||||
excalidrawView.reload(true, excalidrawView.file);
|
||||
if (
|
||||
!isEditingMarkdownSideInSplitView &&
|
||||
excalidrawView.lastSaveTimestamp + 300000 < Date.now()
|
||||
) {
|
||||
await excalidrawView.reload(true, excalidrawView.file);
|
||||
return;
|
||||
}
|
||||
if(file.extension==="md") {
|
||||
if(excalidrawView.semaphores?.embeddableIsEditingSelf) return;
|
||||
}
|
||||
if (file.extension === "md") {
|
||||
if (excalidrawView.semaphores?.embeddableIsEditingSelf) {
|
||||
return;
|
||||
}
|
||||
const inData = new ExcalidrawData(this.plugin);
|
||||
const data = await this.app.vault.read(file);
|
||||
await inData.loadData(data,file,getTextMode(data));
|
||||
excalidrawView.synchronizeWithData(inData);
|
||||
await inData.loadData(data, file, getTextMode(data));
|
||||
await excalidrawView.synchronizeWithData(inData);
|
||||
inData.destroy();
|
||||
if(excalidrawView?.isDirty()) {
|
||||
if(excalidrawView.autosaveTimer && excalidrawView.autosaveFunction) {
|
||||
if (excalidrawView?.isDirty()) {
|
||||
if (
|
||||
excalidrawView.autosaveTimer &&
|
||||
excalidrawView.autosaveFunction
|
||||
) {
|
||||
clearTimeout(excalidrawView.autosaveTimer);
|
||||
}
|
||||
if(excalidrawView.autosaveFunction) {
|
||||
excalidrawView.autosaveFunction();
|
||||
if (excalidrawView.autosaveFunction) {
|
||||
await excalidrawView.autosaveFunction();
|
||||
}
|
||||
}
|
||||
} else {
|
||||
excalidrawView.reload(true, excalidrawView.file);
|
||||
await excalidrawView.reload(true, excalidrawView.file);
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -527,25 +694,25 @@ export class PluginFileManager {
|
||||
//this will not work in a short period when Obsidian is starting up, however
|
||||
//because there is housekeeping in ImageCache at each startup to delete
|
||||
//BAK files, this is not a major issue.
|
||||
if(!imageCache.isReady() || !path) {
|
||||
if (!imageCache.isReady() || !path) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
await imageCache.removeBAKFromCache(path);
|
||||
}
|
||||
|
||||
private async moveBAKFile(oldPath: string, newPath: string) {
|
||||
if(!oldPath || !newPath) {
|
||||
if (!oldPath || !newPath) {
|
||||
return;
|
||||
}
|
||||
//this will not work in the short period when Obsidian is starting up, however
|
||||
//this will only effect a very few files, statistically unlikely to cause
|
||||
//much/any real user impact.
|
||||
//a proper queuing feels overkill for this.
|
||||
if(!imageCache.isReady()) {
|
||||
if (!imageCache.isReady()) {
|
||||
return;
|
||||
}
|
||||
const backup = await imageCache.getBAKFromCache(oldPath);
|
||||
if(backup) {
|
||||
if (backup) {
|
||||
await imageCache.addBAKToCache(newPath, `${backup}`);
|
||||
await this.removeBAKFromCache(oldPath);
|
||||
}
|
||||
@@ -553,11 +720,10 @@ export class PluginFileManager {
|
||||
|
||||
/**
|
||||
* watch file delete and delete corresponding .svg and .png
|
||||
* @param file
|
||||
* @returns
|
||||
* @param file
|
||||
* @returns
|
||||
*/
|
||||
public async deleteEventHandler (file: TFile) {
|
||||
(process.env.NODE_ENV === 'development') && DEBUGGING && debug(this.deleteEventHandler,`ExcalidrawPlugin.deleteEventHandler`, file);
|
||||
public async deleteEventHandler(file: TFile) {
|
||||
if (!(file instanceof TFile)) {
|
||||
return;
|
||||
}
|
||||
@@ -579,39 +745,41 @@ export class PluginFileManager {
|
||||
}
|
||||
}
|
||||
|
||||
this.removeBAKFromCache(file.path);
|
||||
void this.removeBAKFromCache(file.path);
|
||||
|
||||
//delete PNG and SVG files as well
|
||||
if (this.settings.keepInSync) {
|
||||
const imgMap = new Map<string, string>();
|
||||
[EXPORT_TYPES, "excalidraw"].flat().forEach(ext => {
|
||||
[EXPORT_TYPES, "excalidraw"].flat().forEach((ext) => {
|
||||
let imgPath = getIMGFilename(file.path, ext);
|
||||
if(this.plugin.ea?.onImageExportPathHook) {
|
||||
if (this.plugin.ea?.onImageExportPathHook) {
|
||||
try {
|
||||
imgPath = this.plugin.ea.onImageExportPathHook({
|
||||
exportFilepath: imgPath,
|
||||
exportExtension: ext,
|
||||
excalidrawFile: file,
|
||||
action: "delete",
|
||||
}) ?? imgPath;
|
||||
imgPath =
|
||||
this.plugin.ea.onImageExportPathHook({
|
||||
exportFilepath: imgPath,
|
||||
exportExtension: ext,
|
||||
excalidrawFile: file,
|
||||
action: "delete",
|
||||
}) ?? imgPath;
|
||||
} catch (e) {
|
||||
errorlog({where: "FileManager.deleteEventHandler", fn: this.plugin.ea.onImageExportPathHook, error: e});
|
||||
errorlog({
|
||||
where: "FileManager.deleteEventHandler",
|
||||
fn: this.plugin.ea.onImageExportPathHook,
|
||||
error: e,
|
||||
});
|
||||
}
|
||||
}
|
||||
imgMap.set(ext, imgPath);
|
||||
});
|
||||
|
||||
|
||||
window.setTimeout(() => {
|
||||
imgMap.forEach((imgPath: string, ext: string) => {
|
||||
const imgFile = this.app.vault.getFileByPath(
|
||||
normalizePath(imgPath),
|
||||
);
|
||||
imgMap.forEach((imgPath: string) => {
|
||||
const imgFile = this.app.vault.getFileByPath(normalizePath(imgPath));
|
||||
if (imgFile) {
|
||||
this.app.vault.delete(imgFile);
|
||||
void this.app.vault.delete(imgFile);
|
||||
}
|
||||
});
|
||||
}, 500);
|
||||
}
|
||||
};
|
||||
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,10 +1,12 @@
|
||||
import { debug, DEBUGGING } from "src/utils/debugHelper";
|
||||
import { DEBUGGING } from "src/utils/debugHelper";
|
||||
import ExcalidrawPlugin from "src/core/main";
|
||||
import { CustomMutationObserver } from "src/utils/debugHelper";
|
||||
import { DEVICE } from "src/constants/constants";
|
||||
import { getExcalidrawViews, isObsidianThemeDark } from "src/utils/obsidianUtils";
|
||||
import {
|
||||
getExcalidrawViews,
|
||||
isObsidianThemeDark,
|
||||
} from "src/utils/obsidianUtils";
|
||||
import { App, Notice, TFile } from "obsidian";
|
||||
import { ExcalidrawImperativeAPI } from "@zsviczian/excalidraw/types/excalidraw/types";
|
||||
|
||||
export class ObserverManager {
|
||||
private plugin: ExcalidrawPlugin;
|
||||
@@ -12,8 +14,12 @@ export class ObserverManager {
|
||||
private themeObserver: MutationObserver | CustomMutationObserver;
|
||||
private fileExplorerObserver: MutationObserver | CustomMutationObserver;
|
||||
private modalContainerObserver: MutationObserver | CustomMutationObserver;
|
||||
private workspaceDrawerLeftObserver: MutationObserver | CustomMutationObserver;
|
||||
private workspaceDrawerRightObserver: MutationObserver | CustomMutationObserver;
|
||||
private workspaceDrawerLeftObserver:
|
||||
| MutationObserver
|
||||
| CustomMutationObserver;
|
||||
private workspaceDrawerRightObserver:
|
||||
| MutationObserver
|
||||
| CustomMutationObserver;
|
||||
private activeViewDoc: Document;
|
||||
|
||||
get settings() {
|
||||
@@ -27,8 +33,12 @@ export class ObserverManager {
|
||||
|
||||
public initialize() {
|
||||
try {
|
||||
if(this.settings.matchThemeTrigger) this.addThemeObserver();
|
||||
this.experimentalFileTypeDisplayToggle(this.settings.experimentalFileType);
|
||||
if (this.settings.matchThemeTrigger) {
|
||||
this.addThemeObserver();
|
||||
}
|
||||
this.experimentalFileTypeDisplayToggle(
|
||||
this.settings.experimentalFileType,
|
||||
);
|
||||
this.addModalContainerObserver();
|
||||
if (this.app.isMobile) {
|
||||
this.addWorkspaceDrawerObserver();
|
||||
@@ -62,27 +72,39 @@ export class ObserverManager {
|
||||
}
|
||||
|
||||
public addThemeObserver() {
|
||||
if(this.themeObserver) return;
|
||||
if (this.themeObserver) {
|
||||
return;
|
||||
}
|
||||
const { matchThemeTrigger } = this.settings;
|
||||
if (!matchThemeTrigger) return;
|
||||
if (!matchThemeTrigger) {
|
||||
return;
|
||||
}
|
||||
|
||||
const themeObserverFn:MutationCallback = async (mutations: MutationRecord[]) => {
|
||||
(process.env.NODE_ENV === 'development') && DEBUGGING && debug(themeObserverFn, `ExcalidrawPlugin.addThemeObserver`, mutations);
|
||||
const themeObserverFn: MutationCallback = async (
|
||||
mutations: MutationRecord[],
|
||||
) => {
|
||||
const { matchThemeTrigger } = this.settings;
|
||||
if (!matchThemeTrigger) return;
|
||||
if (!matchThemeTrigger) {
|
||||
return;
|
||||
}
|
||||
|
||||
const bodyClassList = document.body.classList;
|
||||
const mutation = mutations[0];
|
||||
if (mutation?.oldValue === bodyClassList.value) return;
|
||||
|
||||
const darkClass = bodyClassList.contains('theme-dark');
|
||||
if (mutation?.oldValue?.includes('theme-dark') === darkClass) return;
|
||||
if (mutation?.oldValue === bodyClassList.value) {
|
||||
return;
|
||||
}
|
||||
|
||||
setTimeout(()=>{ //run async to avoid blocking the UI
|
||||
const darkClass = bodyClassList.contains("theme-dark");
|
||||
if (mutation?.oldValue?.includes("theme-dark") === darkClass) {
|
||||
return;
|
||||
}
|
||||
|
||||
window.setTimeout(() => {
|
||||
//run async to avoid blocking the UI
|
||||
const theme = isObsidianThemeDark() ? "dark" : "light";
|
||||
const excalidrawViews = getExcalidrawViews(this.app);
|
||||
excalidrawViews.forEach(excalidrawView => {
|
||||
if (excalidrawView.file && excalidrawView.excalidrawAPI) {
|
||||
const excalidrawViews = getExcalidrawViews(this.app, true);
|
||||
excalidrawViews.forEach((excalidrawView) => {
|
||||
if (excalidrawView.file) {
|
||||
excalidrawView.setTheme(theme);
|
||||
}
|
||||
});
|
||||
@@ -92,7 +114,7 @@ export class ObserverManager {
|
||||
this.themeObserver = DEBUGGING
|
||||
? new CustomMutationObserver(themeObserverFn, "themeObserver")
|
||||
: new MutationObserver(themeObserverFn);
|
||||
|
||||
|
||||
this.themeObserver.observe(document.body, {
|
||||
attributeOldValue: true,
|
||||
attributeFilter: ["class"],
|
||||
@@ -100,14 +122,16 @@ export class ObserverManager {
|
||||
}
|
||||
|
||||
public removeThemeObserver() {
|
||||
if(!this.themeObserver) return;
|
||||
if (!this.themeObserver) {
|
||||
return;
|
||||
}
|
||||
this.themeObserver.disconnect();
|
||||
this.themeObserver = null;
|
||||
}
|
||||
|
||||
public experimentalFileTypeDisplayToggle(enabled: boolean) {
|
||||
if (enabled) {
|
||||
this.experimentalFileTypeDisplay();
|
||||
void this.experimentalFileTypeDisplay();
|
||||
return;
|
||||
}
|
||||
if (this.fileExplorerObserver) {
|
||||
@@ -122,7 +146,6 @@ export class ObserverManager {
|
||||
* The function is called from onload()
|
||||
*/
|
||||
private async experimentalFileTypeDisplay() {
|
||||
(process.env.NODE_ENV === 'development') && DEBUGGING && debug(this.experimentalFileTypeDisplay, `ExcalidrawPlugin.experimentalFileTypeDisplay`);
|
||||
const tagClassName = "excalidraw-filetype-tag";
|
||||
const insertFiletype = (el: HTMLElement) => {
|
||||
if (!el || el.querySelector(`.${tagClassName}`)) {
|
||||
@@ -147,8 +170,7 @@ export class ObserverManager {
|
||||
}
|
||||
};
|
||||
|
||||
const fileExplorerObserverFn:MutationCallback = (mutationsList) => {
|
||||
(process.env.NODE_ENV === 'development') && DEBUGGING && debug(fileExplorerObserverFn, `ExcalidrawPlugin.experimentalFileTypeDisplay > fileExplorerObserverFn`, mutationsList);
|
||||
const fileExplorerObserverFn: MutationCallback = (mutationsList) => {
|
||||
const ensureFiletypes = (target: Element | DocumentFragment) => {
|
||||
target.querySelectorAll?.(".nav-file-title").forEach(insertFiletype);
|
||||
};
|
||||
@@ -167,18 +189,26 @@ export class ObserverManager {
|
||||
return;
|
||||
}
|
||||
|
||||
if (mutation.type === "attributes" && mutation.target instanceof Element) {
|
||||
if (
|
||||
mutation.type === "attributes" &&
|
||||
mutation.target instanceof Element
|
||||
) {
|
||||
ensureFiletypes(mutation.target);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
this.fileExplorerObserver = DEBUGGING
|
||||
? new CustomMutationObserver(fileExplorerObserverFn, "fileExplorerObserver")
|
||||
? new CustomMutationObserver(
|
||||
fileExplorerObserverFn,
|
||||
"fileExplorerObserver",
|
||||
)
|
||||
: new MutationObserver(fileExplorerObserverFn);
|
||||
|
||||
const attachObserversToContainers = (): boolean => {
|
||||
const containers = Array.from(document.querySelectorAll(".nav-files-container"));
|
||||
const containers = Array.from(
|
||||
document.querySelectorAll(".nav-files-container"),
|
||||
);
|
||||
if (!containers.length) {
|
||||
return false;
|
||||
}
|
||||
@@ -198,21 +228,29 @@ export class ObserverManager {
|
||||
|
||||
if (!attachObserversToContainers() && DEVICE.isMobile) {
|
||||
// On mobile, the file explorer lives inside drawers and may not be in the DOM yet.
|
||||
const waitForFileExplorer = new MutationObserver((mutations, observer) => {
|
||||
for (const mutation of mutations) {
|
||||
if (mutation.type !== "childList") continue;
|
||||
const added = Array.from(mutation.addedNodes ?? []);
|
||||
const hasContainer = added.some((node) =>
|
||||
node instanceof Element &&
|
||||
(node.matches?.(".nav-files-container") || node.querySelector?.(".nav-files-container")),
|
||||
);
|
||||
if (!hasContainer) continue;
|
||||
if (attachObserversToContainers()) {
|
||||
observer.disconnect();
|
||||
break;
|
||||
const waitForFileExplorer = new MutationObserver(
|
||||
(mutations, observer) => {
|
||||
for (const mutation of mutations) {
|
||||
if (mutation.type !== "childList") {
|
||||
continue;
|
||||
}
|
||||
const added = Array.from(mutation.addedNodes ?? []);
|
||||
const hasContainer = added.some(
|
||||
(node) =>
|
||||
node instanceof Element &&
|
||||
(node.matches?.(".nav-files-container") ||
|
||||
node.querySelector?.(".nav-files-container")),
|
||||
);
|
||||
if (!hasContainer) {
|
||||
continue;
|
||||
}
|
||||
if (attachObserversToContainers()) {
|
||||
observer.disconnect();
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
waitForFileExplorer.observe(document.body, {
|
||||
childList: true,
|
||||
@@ -223,46 +261,58 @@ export class ObserverManager {
|
||||
|
||||
/**
|
||||
* Monitors if the user clicks outside the Excalidraw view, and saves the drawing if it's dirty
|
||||
* @returns
|
||||
* @returns
|
||||
*/
|
||||
public addModalContainerObserver() {
|
||||
if(!this.plugin.activeExcalidrawView) return;
|
||||
if(this.modalContainerObserver) {
|
||||
if(this.activeViewDoc === this.plugin.activeExcalidrawView.ownerDocument) {
|
||||
if (!this.plugin.activeExcalidrawView) {
|
||||
return;
|
||||
}
|
||||
if (this.modalContainerObserver) {
|
||||
if (
|
||||
this.activeViewDoc === this.plugin.activeExcalidrawView.ownerDocument
|
||||
) {
|
||||
return;
|
||||
}
|
||||
this.removeModalContainerObserver();
|
||||
}
|
||||
//The user clicks settings, or "open another vault", or the command palette
|
||||
const modalContainerObserverFn: MutationCallback = async (m: MutationRecord[]) => {
|
||||
(process.env.NODE_ENV === 'development') && DEBUGGING && debug(modalContainerObserverFn,`ExcalidrawPlugin.modalContainerObserverFn`, m);
|
||||
const modalContainerObserverFn: MutationCallback = async (
|
||||
m: MutationRecord[],
|
||||
) => {
|
||||
const view = this.plugin.activeExcalidrawView;
|
||||
if (
|
||||
(m.length !== 1) ||
|
||||
(m[0].type !== "childList") ||
|
||||
(m[0].addedNodes.length !== 1) ||
|
||||
(!view) ||
|
||||
m.length !== 1 ||
|
||||
m[0].type !== "childList" ||
|
||||
m[0].addedNodes.length !== 1 ||
|
||||
!view ||
|
||||
view.semaphores?.viewunload ||
|
||||
(!view.isDirty())
|
||||
!view.isDirty()
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
const { errorMessage } = (view.excalidrawAPI as ExcalidrawImperativeAPI).getAppState();
|
||||
if (!errorMessage) this.plugin.activeExcalidrawView.save();
|
||||
|
||||
const { errorMessage } = view.excalidrawAPI.getAppState();
|
||||
if (!errorMessage) {
|
||||
await this.plugin.activeExcalidrawView.save();
|
||||
}
|
||||
};
|
||||
|
||||
this.modalContainerObserver = DEBUGGING
|
||||
? new CustomMutationObserver(modalContainerObserverFn, "modalContainerObserver")
|
||||
? new CustomMutationObserver(
|
||||
modalContainerObserverFn,
|
||||
"modalContainerObserver",
|
||||
)
|
||||
: new MutationObserver(modalContainerObserverFn);
|
||||
this.activeViewDoc = this.plugin.activeExcalidrawView.ownerDocument;
|
||||
this.modalContainerObserver.observe(this.activeViewDoc.body, {
|
||||
childList: true,
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
public removeModalContainerObserver() {
|
||||
if(!this.modalContainerObserver) return;
|
||||
if (!this.modalContainerObserver) {
|
||||
return;
|
||||
}
|
||||
this.modalContainerObserver.disconnect();
|
||||
this.activeViewDoc = null;
|
||||
this.modalContainerObserver = null;
|
||||
@@ -270,24 +320,41 @@ export class ObserverManager {
|
||||
|
||||
private addWorkspaceDrawerObserver() {
|
||||
//when the user activates the sliding drawers on Obsidian Mobile
|
||||
if (this.workspaceDrawerLeftObserver || this.workspaceDrawerRightObserver) 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 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 "";
|
||||
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;
|
||||
if (!activeView || activeView.semaphores?.viewunload) {
|
||||
return;
|
||||
}
|
||||
|
||||
for (const mutation of mutations) {
|
||||
if (mutation.type !== "attributes" || mutation.attributeName !== "style") continue;
|
||||
if (
|
||||
mutation.type !== "attributes" ||
|
||||
mutation.attributeName !== "style"
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const target = mutation.target as HTMLElement;
|
||||
const newDisplay = target.style.display;
|
||||
@@ -300,8 +367,12 @@ export class ObserverManager {
|
||||
}
|
||||
|
||||
// Drawer just opened after being hidden: keep the previous autosave safeguard
|
||||
if (oldDisplay === "none" && newDisplay !== "none" && activeView.isDirty()) {
|
||||
activeView.save();
|
||||
if (
|
||||
oldDisplay === "none" &&
|
||||
newDisplay !== "none" &&
|
||||
activeView.isDirty()
|
||||
) {
|
||||
void activeView.save();
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -326,4 +397,4 @@ export class ObserverManager {
|
||||
this.workspaceDrawerRightObserver.observe(rightWorkspaceDrawer, options);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,18 +1,17 @@
|
||||
import { updateExcalidrawLib } from "src/constants/constants";
|
||||
import { ExcalidrawLib } from "../../types/excalidrawLib";
|
||||
import { Packages } from "../../types/types";
|
||||
import { debug, DEBUGGING } from "../../utils/debugHelper";
|
||||
import { Notice } from "obsidian";
|
||||
import ExcalidrawPlugin from "src/core/main";
|
||||
import { errorHandler } from "../../utils/ErrorHandler";
|
||||
import React from "react";
|
||||
import ReactDOM from "react-dom";
|
||||
import ReactDOM from "react-dom/client";
|
||||
|
||||
declare let REACT_PACKAGES:string;
|
||||
declare let REACT_PACKAGES: string;
|
||||
declare let react: typeof React;
|
||||
declare let reactDOM:typeof ReactDOM;
|
||||
declare let reactDOM: typeof ReactDOM;
|
||||
declare let excalidrawLib: typeof ExcalidrawLib;
|
||||
declare const unpackExcalidraw: Function;
|
||||
declare const unpackExcalidraw: () => string;
|
||||
|
||||
export class PackageManager {
|
||||
private packageMap: Map<Window, Packages> = new Map<Window, Packages>();
|
||||
@@ -22,27 +21,27 @@ export class PackageManager {
|
||||
|
||||
constructor(plugin: ExcalidrawPlugin) {
|
||||
this.plugin = plugin;
|
||||
|
||||
|
||||
try {
|
||||
this.EXCALIDRAW_PACKAGE = unpackExcalidraw();
|
||||
|
||||
|
||||
// Use safe evaluation for unpacking the Excalidraw package
|
||||
excalidrawLib = errorHandler.safeEval(
|
||||
`(function() {${this.EXCALIDRAW_PACKAGE};return ExcalidrawLib;})()`,
|
||||
"PackageManager constructor - excalidrawLib initialization",
|
||||
window
|
||||
`(function() {${this.EXCALIDRAW_PACKAGE};return ExcalidrawLib;})()`,
|
||||
"PackageManager constructor - excalidrawLib initialization",
|
||||
window,
|
||||
);
|
||||
|
||||
|
||||
if (!excalidrawLib) {
|
||||
throw new Error("Failed to initialize excalidrawLib");
|
||||
}
|
||||
|
||||
|
||||
// Update the exported functions
|
||||
updateExcalidrawLib();
|
||||
|
||||
|
||||
// Create a package with the loaded libraries
|
||||
const initialPackage = {react, reactDOM, excalidrawLib};
|
||||
|
||||
const initialPackage = { react, reactDOM, excalidrawLib };
|
||||
|
||||
// Validate the package before storing
|
||||
if (this.validatePackage(initialPackage)) {
|
||||
this.setPackage(window, initialPackage);
|
||||
@@ -52,10 +51,13 @@ export class PackageManager {
|
||||
}
|
||||
} catch (e) {
|
||||
errorHandler.handleError(e, "PackageManager constructor");
|
||||
new Notice("Error loading the Excalidraw package. Some features may not work correctly.", 10000);
|
||||
new Notice(
|
||||
"Error loading the Excalidraw package. Some features may not work correctly.",
|
||||
10000,
|
||||
);
|
||||
console.error("Error loading the Excalidraw package", e);
|
||||
}
|
||||
|
||||
|
||||
plugin.logStartupEvent("Excalidraw package unpacked");
|
||||
}
|
||||
|
||||
@@ -63,20 +65,22 @@ export class PackageManager {
|
||||
* Validates that a package contains all required components
|
||||
*/
|
||||
private validatePackage(pkg: Packages): boolean {
|
||||
if (!pkg) return false;
|
||||
|
||||
if (!pkg) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check that all components exist
|
||||
if (!pkg.react || !pkg.reactDOM || !pkg.excalidrawLib) {
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
// Verify that excalidrawLib has essential methods
|
||||
const lib = pkg.excalidrawLib;
|
||||
return (
|
||||
typeof lib === 'object' &&
|
||||
typeof lib === "object" &&
|
||||
lib !== null &&
|
||||
typeof lib.restoreElements === 'function' &&
|
||||
typeof lib.exportToSvg === 'function'
|
||||
typeof lib.restoreElements === "function" &&
|
||||
typeof lib.exportToSvg === "function"
|
||||
);
|
||||
}
|
||||
|
||||
@@ -86,15 +90,15 @@ export class PackageManager {
|
||||
public setPackage(window: Window, pkg: Packages) {
|
||||
if (this.validatePackage(pkg)) {
|
||||
this.packageMap.set(window, pkg);
|
||||
|
||||
|
||||
// Update fallback if we don't have one
|
||||
if (!this.fallbackPackage) {
|
||||
this.fallbackPackage = pkg;
|
||||
}
|
||||
} else {
|
||||
errorHandler.handleError(
|
||||
"Attempted to set invalid package",
|
||||
"PackageManager.setPackage"
|
||||
"Attempted to set invalid package",
|
||||
"PackageManager.setPackage",
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -109,10 +113,6 @@ export class PackageManager {
|
||||
*/
|
||||
public getPackage(win: Window): Packages {
|
||||
try {
|
||||
if ((process.env.NODE_ENV === 'development') && DEBUGGING) {
|
||||
debug(this.getPackage, `PackageManager.getPackage`, win);
|
||||
}
|
||||
|
||||
// Return existing package if available
|
||||
if (this.packageMap.has(win)) {
|
||||
const pkg = this.packageMap.get(win);
|
||||
@@ -124,38 +124,46 @@ export class PackageManager {
|
||||
}
|
||||
|
||||
// Create new package
|
||||
return errorHandler.wrapWithTryCatch(() => {
|
||||
// Use safe evaluation to load packages in the window context
|
||||
const evalResult = errorHandler.safeEval<{react: typeof React, reactDOM: typeof ReactDOM, excalidrawLib: typeof ExcalidrawLib}>(
|
||||
`(function() {
|
||||
return errorHandler.wrapWithTryCatch(
|
||||
() => {
|
||||
// Use safe evaluation to load packages in the window context
|
||||
const evalResult = errorHandler.safeEval<{
|
||||
react: typeof React;
|
||||
reactDOM: typeof ReactDOM;
|
||||
excalidrawLib: typeof ExcalidrawLib;
|
||||
}>(
|
||||
`(function() {
|
||||
${REACT_PACKAGES + this.EXCALIDRAW_PACKAGE};
|
||||
return {react: React, reactDOM: ReactDOM, excalidrawLib: ExcalidrawLib};
|
||||
})()`,
|
||||
"PackageManager.getPackage - package evaluation",
|
||||
win
|
||||
);
|
||||
|
||||
if (!evalResult || !this.validatePackage(evalResult)) {
|
||||
throw new Error("Failed to create valid package");
|
||||
}
|
||||
|
||||
const newPackage = {
|
||||
react: evalResult.react,
|
||||
reactDOM: evalResult.reactDOM,
|
||||
excalidrawLib: evalResult.excalidrawLib
|
||||
};
|
||||
|
||||
this.packageMap.set(win, newPackage);
|
||||
return newPackage;
|
||||
}, "PackageManager.getPackage", this.fallbackPackage);
|
||||
"PackageManager.getPackage - package evaluation",
|
||||
win,
|
||||
);
|
||||
|
||||
if (!evalResult || !this.validatePackage(evalResult)) {
|
||||
throw new Error("Failed to create valid package");
|
||||
}
|
||||
|
||||
const newPackage = {
|
||||
react: evalResult.react,
|
||||
reactDOM: evalResult.reactDOM,
|
||||
excalidrawLib: evalResult.excalidrawLib,
|
||||
};
|
||||
|
||||
this.packageMap.set(win, newPackage);
|
||||
return newPackage;
|
||||
},
|
||||
"PackageManager.getPackage",
|
||||
this.fallbackPackage,
|
||||
);
|
||||
} catch (error) {
|
||||
errorHandler.handleError(error, "PackageManager.getPackage");
|
||||
|
||||
|
||||
// Return fallback package if available to prevent data loss
|
||||
if (this.fallbackPackage) {
|
||||
return this.fallbackPackage;
|
||||
}
|
||||
|
||||
|
||||
// If no fallback, throw error to prevent undefined behavior
|
||||
throw new Error("Failed to get package and no fallback available");
|
||||
}
|
||||
@@ -164,14 +172,19 @@ export class PackageManager {
|
||||
public deletePackage(win: Window) {
|
||||
try {
|
||||
const pkg = this.packageMap.get(win);
|
||||
if (!pkg) return;
|
||||
if (!pkg) {
|
||||
return;
|
||||
}
|
||||
|
||||
const { react, reactDOM, excalidrawLib } = pkg;
|
||||
|
||||
if (win.ExcalidrawLib === excalidrawLib) {
|
||||
// Safely clean up resources
|
||||
errorHandler.wrapWithTryCatch(() => {
|
||||
if (excalidrawLib && typeof excalidrawLib.destroyObsidianUtils === 'function') {
|
||||
if (
|
||||
excalidrawLib &&
|
||||
typeof excalidrawLib.destroyObsidianUtils === "function"
|
||||
) {
|
||||
excalidrawLib.destroyObsidianUtils();
|
||||
}
|
||||
delete win.ExcalidrawLib;
|
||||
@@ -180,18 +193,12 @@ export class PackageManager {
|
||||
|
||||
if (win.React === react) {
|
||||
errorHandler.wrapWithTryCatch(() => {
|
||||
Object.keys(win.React || {}).forEach((key) => {
|
||||
delete win.React[key];
|
||||
});
|
||||
delete win.React;
|
||||
}, "PackageManager.deletePackage - cleanup React");
|
||||
}
|
||||
|
||||
if (win.ReactDOM === reactDOM) {
|
||||
errorHandler.wrapWithTryCatch(() => {
|
||||
Object.keys(win.ReactDOM || {}).forEach((key) => {
|
||||
delete win.ReactDOM[key];
|
||||
});
|
||||
delete win.ReactDOM;
|
||||
}, "PackageManager.deletePackage - cleanup ReactDOM");
|
||||
}
|
||||
@@ -209,15 +216,15 @@ export class PackageManager {
|
||||
public destroy() {
|
||||
try {
|
||||
REACT_PACKAGES = "";
|
||||
|
||||
Array.from(this.packageMap.entries()).forEach(([win, p]) => {
|
||||
|
||||
Array.from(this.packageMap.entries()).forEach(([win, _]) => {
|
||||
this.deletePackage(win);
|
||||
});
|
||||
|
||||
|
||||
this.packageMap.clear();
|
||||
this.EXCALIDRAW_PACKAGE = "";
|
||||
this.fallbackPackage = null;
|
||||
|
||||
|
||||
react = null;
|
||||
reactDOM = null;
|
||||
excalidrawLib = null;
|
||||
@@ -225,4 +232,4 @@ export class PackageManager {
|
||||
errorHandler.handleError(error, "PackageManager.destroy");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
import { WorkspaceWindow } from "obsidian";
|
||||
import ExcalidrawPlugin from "src/core/main";
|
||||
import { getAllWindowDocuments } from "../../utils/obsidianUtils";
|
||||
import { DEBUGGING, debug } from "../../utils/debugHelper";
|
||||
import { setStyleText } from "src/utils/htmlUtils";
|
||||
|
||||
export let REM_VALUE = 16;
|
||||
|
||||
@@ -32,7 +32,10 @@ const STYLE_VARIABLES = [
|
||||
const EXCALIDRAW_CONTAINER_CLASS = "excalidraw__embeddable__outer";
|
||||
|
||||
export class StylesManager {
|
||||
private stylesMap = new Map<Document,{light: HTMLStyleElement, dark: HTMLStyleElement}>();
|
||||
private stylesMap = new Map<
|
||||
Document,
|
||||
{ light: HTMLStyleElement; dark: HTMLStyleElement }
|
||||
>();
|
||||
private styleLight: string;
|
||||
private styleDark: string;
|
||||
private plugin: ExcalidrawPlugin;
|
||||
@@ -40,54 +43,64 @@ export class StylesManager {
|
||||
constructor(plugin: ExcalidrawPlugin) {
|
||||
this.plugin = plugin;
|
||||
plugin.app.workspace.onLayoutReady(async () => {
|
||||
(process.env.NODE_ENV === 'development') && DEBUGGING && debug(undefined, "StylesManager.constructor > app.workspace.onLayoutReady", this);
|
||||
await plugin.awaitInit();
|
||||
await this.harvestStyles();
|
||||
getAllWindowDocuments(plugin.app).forEach(doc => this.copyPropertiesToTheme(doc));
|
||||
getAllWindowDocuments(plugin.app).forEach((doc) =>
|
||||
this.copyPropertiesToTheme(doc),
|
||||
);
|
||||
|
||||
//initialize
|
||||
plugin.registerEvent(
|
||||
plugin.app.workspace.on("css-change", ()=>this.onCSSChange()),
|
||||
)
|
||||
plugin.app.workspace.on("css-change", () => this.onCSSChange()),
|
||||
);
|
||||
|
||||
plugin.registerEvent(
|
||||
plugin.app.workspace.on("window-open", (win)=>this.onWindowOpen(win)),
|
||||
)
|
||||
plugin.app.workspace.on("window-open", (win) => this.onWindowOpen(win)),
|
||||
);
|
||||
|
||||
plugin.registerEvent(
|
||||
plugin.app.workspace.on("window-close", (win)=>this.onWindowClose(win)),
|
||||
)
|
||||
plugin.app.workspace.on("window-close", (win) =>
|
||||
this.onWindowClose(win),
|
||||
),
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
private async onCSSChange () {
|
||||
private async onCSSChange() {
|
||||
await this.harvestStyles();
|
||||
getAllWindowDocuments(this.plugin.app).forEach(doc => {
|
||||
getAllWindowDocuments(this.plugin.app).forEach((doc) => {
|
||||
this.copyPropertiesToTheme(doc);
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
private onWindowOpen (win: WorkspaceWindow) {
|
||||
private onWindowOpen(win: WorkspaceWindow) {
|
||||
this.stylesMap.set(win.doc, {
|
||||
light: document.head.querySelector(`style[id="excalidraw-embedded-light"]`),
|
||||
dark: document.head.querySelector(`style[id="excalidraw-embedded-dark"]`)
|
||||
light: document.head.querySelector(
|
||||
`style[id="excalidraw-embedded-light"]`,
|
||||
),
|
||||
dark: document.head.querySelector(`style[id="excalidraw-embedded-dark"]`),
|
||||
});
|
||||
//this.copyPropertiesToTheme(win.doc);
|
||||
}
|
||||
|
||||
private onWindowClose (win: WorkspaceWindow) {
|
||||
private onWindowClose(win: WorkspaceWindow) {
|
||||
this.stylesMap.delete(win.doc);
|
||||
}
|
||||
|
||||
private async harvestStyles() {
|
||||
REM_VALUE = parseInt(window.getComputedStyle(document.body).getPropertyValue('--font-text-size').trim());
|
||||
REM_VALUE = parseInt(
|
||||
window
|
||||
.getComputedStyle(document.body)
|
||||
.getPropertyValue("--font-text-size")
|
||||
.trim(),
|
||||
);
|
||||
if (isNaN(REM_VALUE)) {
|
||||
REM_VALUE = 16;
|
||||
}
|
||||
|
||||
const body = document.body;
|
||||
const iframe:HTMLIFrameElement = document.createElement("iframe");
|
||||
iframe.style.display = "none";
|
||||
const iframe: HTMLIFrameElement = document.createElement("iframe");
|
||||
iframe.hidden = true;
|
||||
body.appendChild(iframe);
|
||||
|
||||
const iframeLoadedPromise = new Promise<void>((resolve) => {
|
||||
@@ -110,21 +123,23 @@ export class StylesManager {
|
||||
iframeBody.classList.remove("theme-light");
|
||||
iframeBody.classList.remove("theme-dark");
|
||||
iframeBody.classList.add(theme);
|
||||
}
|
||||
};
|
||||
|
||||
const getCSSVariables = (): string => {
|
||||
const computedStyles = iframeWin.getComputedStyle(iframeBody);
|
||||
const allVariables: {[key:string]:string} = {};
|
||||
const allVariables: { [key: string]: string } = {};
|
||||
for (const variable of STYLE_VARIABLES) {
|
||||
allVariables[variable] = computedStyles.getPropertyValue(variable);
|
||||
}
|
||||
const cm = this.plugin.ea.getCM(computedStyles.getPropertyValue("--background-primary"));
|
||||
const cm = this.plugin.ea.getCM(
|
||||
computedStyles.getPropertyValue("--background-primary"),
|
||||
);
|
||||
cm.alphaTo(0.9);
|
||||
allVariables["--background-primary"] = cm.stringHEX();
|
||||
return Object.entries(allVariables)
|
||||
.map(([key, value]) => `${key}: ${value} !important;`)
|
||||
.join(" ");
|
||||
}
|
||||
};
|
||||
|
||||
setTheme("theme-light");
|
||||
this.styleLight = getCSSVariables();
|
||||
@@ -136,25 +151,37 @@ export class StylesManager {
|
||||
private copyPropertiesToTheme(doc: Document) {
|
||||
const styleTags = this.stylesMap.get(doc);
|
||||
if (styleTags) {
|
||||
styleTags.light.innerHTML = `.${EXCALIDRAW_CONTAINER_CLASS} .theme-light {\n${this.styleLight}\n}`;
|
||||
styleTags.dark.innerHTML = `.${EXCALIDRAW_CONTAINER_CLASS} .theme-dark {\n${this.styleDark}\n}`;
|
||||
setStyleText(
|
||||
styleTags.light,
|
||||
`.${EXCALIDRAW_CONTAINER_CLASS} .theme-light {\n${this.styleLight}\n}`,
|
||||
);
|
||||
setStyleText(
|
||||
styleTags.dark,
|
||||
`.${EXCALIDRAW_CONTAINER_CLASS} .theme-dark {\n${this.styleDark}\n}`,
|
||||
);
|
||||
} else {
|
||||
const lightStyleTag = doc.createElement("style");
|
||||
lightStyleTag.type = "text/css";
|
||||
lightStyleTag.setAttribute("id", "excalidraw-embedded-light");
|
||||
lightStyleTag.innerHTML = `.${EXCALIDRAW_CONTAINER_CLASS} .theme-light {\n${this.styleLight}\n}`;
|
||||
setStyleText(
|
||||
lightStyleTag,
|
||||
`.${EXCALIDRAW_CONTAINER_CLASS} .theme-light {\n${this.styleLight}\n}`,
|
||||
);
|
||||
doc.head.appendChild(lightStyleTag);
|
||||
|
||||
const darkStyleTag = doc.createElement("style");
|
||||
darkStyleTag.type = "text/css";
|
||||
darkStyleTag.setAttribute("id", "excalidraw-embedded-dark");
|
||||
darkStyleTag.innerHTML = `.${EXCALIDRAW_CONTAINER_CLASS} .theme-dark {\n${this.styleDark}\n}`;
|
||||
setStyleText(
|
||||
darkStyleTag,
|
||||
`.${EXCALIDRAW_CONTAINER_CLASS} .theme-dark {\n${this.styleDark}\n}`,
|
||||
);
|
||||
doc.head.appendChild(darkStyleTag);
|
||||
|
||||
this.stylesMap.set(doc, {light: lightStyleTag, dark: darkStyleTag});
|
||||
this.stylesMap.set(doc, { light: lightStyleTag, dark: darkStyleTag });
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public destroy() {
|
||||
for (const [doc, styleTags] of this.stylesMap) {
|
||||
doc.head.removeChild(styleTags.light);
|
||||
@@ -162,5 +189,4 @@ export class StylesManager {
|
||||
}
|
||||
this.plugin = null;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
+2138
-881
File diff suppressed because it is too large.
Load diff
+106
-9
@@ -1,21 +1,118 @@
|
||||
//Solution copied from obsidian-kanban: https://github.com/mgmeyers/obsidian-kanban/blob/44118e25661bff9ebfe54f71ae33805dc88ffa53/src/lang/helpers.ts
|
||||
|
||||
import { LOCALE } from "src/constants/constants";
|
||||
import {
|
||||
CJK_FONTS,
|
||||
DEVICE,
|
||||
FRONTMATTER_KEYS,
|
||||
LOCALE,
|
||||
} from "src/constants/constants";
|
||||
import {
|
||||
labelALT,
|
||||
labelCTRL,
|
||||
labelMETA,
|
||||
labelSHIFT,
|
||||
} from "src/utils/modifierKeyLabels";
|
||||
import en from "./locale/en";
|
||||
|
||||
declare const PLUGIN_LANGUAGES: Record<string, string>;
|
||||
declare var LZString: any;
|
||||
declare const PLUGIN_VERSION: string;
|
||||
declare const LZString: {
|
||||
decompressFromBase64: (value: string) => string | null;
|
||||
};
|
||||
|
||||
let locale: Partial<typeof en> | null = null;
|
||||
|
||||
// Runtime token map for compressed locales.
|
||||
// Keep this in sync with token emission in rollup.config.js tokenizeLocaleContent.
|
||||
// If you add a locale and it needs a new dynamic placeholder, add it in both places.
|
||||
const TOKENS = {
|
||||
IF_DESKTOP_START: "__EXD_IF_DESKTOP__",
|
||||
IF_DESKTOP_END: "__EXD_END_IF_DESKTOP__",
|
||||
LABEL_ALT: "__EXD_LABEL_ALT__",
|
||||
LABEL_CTRL: "__EXD_LABEL_CTRL__",
|
||||
LABEL_META: "__EXD_LABEL_META__",
|
||||
LABEL_SHIFT: "__EXD_LABEL_SHIFT__",
|
||||
FRONTMATTER_LINK_BRACKETS: "__EXD_FRONTMATTER_LINK_BRACKETS__",
|
||||
FRONTMATTER_LINK_PREFIX: "__EXD_FRONTMATTER_LINK_PREFIX__",
|
||||
FRONTMATTER_URL_PREFIX: "__EXD_FRONTMATTER_URL_PREFIX__",
|
||||
CJK_FONTS: "__EXD_CJK_FONTS__",
|
||||
PLUGIN_VERSION: "__EXD_PLUGIN_VERSION__",
|
||||
DEVTOOLS_SHORTCUT: "__EXD_DEVTOOLS_SHORTCUT__",
|
||||
} as const;
|
||||
|
||||
function resolveTokenizedString(value: string): string {
|
||||
// Evaluate deferred desktop-only fragments generated during build.
|
||||
const desktopResolved = value.replace(
|
||||
/__EXD_IF_DESKTOP__([\s\S]*?)__EXD_END_IF_DESKTOP__/g,
|
||||
(_, content: string) => (DEVICE.isDesktop ? content : ""),
|
||||
);
|
||||
|
||||
// Evaluate deferred Apple vs non-Apple fragments generated during build.
|
||||
const appleResolved = desktopResolved.replace(
|
||||
/__EXD_IF_APPLE__([\s\S]*?)__EXD_ELSE_APPLE__([\s\S]*?)__EXD_END_IF_APPLE__/g,
|
||||
(_, appleValue: string, nonAppleValue: string) =>
|
||||
DEVICE.isIOS || DEVICE.isMacOS ? appleValue : nonAppleValue,
|
||||
);
|
||||
|
||||
// Token replacements for runtime-dependent values.
|
||||
const replacements: Record<string, string> = {
|
||||
[TOKENS.LABEL_ALT]: labelALT(),
|
||||
[TOKENS.LABEL_CTRL]: labelCTRL(),
|
||||
[TOKENS.LABEL_META]: labelMETA(),
|
||||
[TOKENS.LABEL_SHIFT]: labelSHIFT(),
|
||||
[TOKENS.FRONTMATTER_LINK_BRACKETS]: FRONTMATTER_KEYS["link-brackets"].name,
|
||||
[TOKENS.FRONTMATTER_LINK_PREFIX]: FRONTMATTER_KEYS["link-prefix"].name,
|
||||
[TOKENS.FRONTMATTER_URL_PREFIX]: FRONTMATTER_KEYS["url-prefix"].name,
|
||||
[TOKENS.CJK_FONTS]: CJK_FONTS,
|
||||
[TOKENS.PLUGIN_VERSION]: PLUGIN_VERSION,
|
||||
[TOKENS.DEVTOOLS_SHORTCUT]:
|
||||
DEVICE.isIOS || DEVICE.isMacOS ? "CMD+OPT+i" : "CTRL+SHIFT+i",
|
||||
};
|
||||
|
||||
let resolved = appleResolved;
|
||||
for (const [token, replacement] of Object.entries(replacements)) {
|
||||
resolved = resolved.split(token).join(replacement);
|
||||
}
|
||||
return resolved;
|
||||
}
|
||||
|
||||
function resolveTokensDeep(value: unknown): unknown {
|
||||
if (typeof value === "string") {
|
||||
return resolveTokenizedString(value);
|
||||
}
|
||||
|
||||
if (Array.isArray(value)) {
|
||||
return value.map(resolveTokensDeep);
|
||||
}
|
||||
|
||||
if (value && typeof value === "object") {
|
||||
const entries = Object.entries(value as Record<string, unknown>);
|
||||
return Object.fromEntries(
|
||||
entries.map(([k, v]) => [k, resolveTokensDeep(v)]),
|
||||
);
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
function loadLocale(lang: string): Partial<typeof en> {
|
||||
if(lang === "zh") lang = "zh-cn"; //https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2247
|
||||
if (Object.keys(PLUGIN_LANGUAGES).includes(lang)) {
|
||||
const decompressed = LZString.decompressFromBase64(PLUGIN_LANGUAGES[lang]);
|
||||
let x = {};
|
||||
eval(decompressed);
|
||||
return x;
|
||||
} else {
|
||||
if (lang === "zh") {
|
||||
lang = "zh-cn";
|
||||
} //https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2247
|
||||
if (!Object.prototype.hasOwnProperty.call(PLUGIN_LANGUAGES, lang)) {
|
||||
return en;
|
||||
}
|
||||
|
||||
try {
|
||||
const compressed = PLUGIN_LANGUAGES[lang];
|
||||
const decompressed = LZString.decompressFromBase64(compressed);
|
||||
if (!decompressed) {
|
||||
return en;
|
||||
}
|
||||
|
||||
const parsed = JSON.parse(decompressed) as Partial<typeof en>;
|
||||
return resolveTokensDeep(parsed) as Partial<typeof en>;
|
||||
} catch {
|
||||
return en;
|
||||
}
|
||||
}
|
||||
|
||||
+149
-149
@@ -1,149 +1,149 @@
|
||||
/**
|
||||
* Language Pack Diff Checker Script
|
||||
*
|
||||
* Purpose:
|
||||
* Compare src/lang/locale/en.ts and a target language file (e.g. zh-cn.ts), output missing and extra keys.
|
||||
* Output is color-coded:
|
||||
* - Green: Key exists in en.ts but missing in the target language file
|
||||
* - Red: Key exists in the target language file but not in en.ts
|
||||
* - Yellow: The same key exists in both files but the line numbers are different
|
||||
*
|
||||
* Dependencies:
|
||||
* Node.js environment, no extra dependencies required.
|
||||
*
|
||||
* Usage:
|
||||
* 1. Open a terminal in this file's directory (or project root).
|
||||
* 2. Run:
|
||||
* node src/lang/langDiffWithEn.js zh-cn
|
||||
* # or node src/lang/langDiffWithEn.js ja
|
||||
* # The argument is the language file name (without extension), default is zh-cn
|
||||
*
|
||||
* Output:
|
||||
* + (green): Key exists in en.ts but missing in the target language file
|
||||
* - (red): Key exists in the target language file but not in en.ts
|
||||
* ! (yellow): The same key exists in both files but the line numbers are different
|
||||
* If there is no output, the two files have identical keys.
|
||||
*/
|
||||
/**
|
||||
* 语言包差异检测脚本
|
||||
*
|
||||
* 用途:
|
||||
* 比较 src/lang/locale/en.ts 与指定语言文件(如 zh-cn.ts)中的 key,输出缺失和多余的 key。
|
||||
* 输出内容会用不同颜色区分:
|
||||
* - 绿色:en.ts 有但目标语言缺失的 key
|
||||
* - 红色:目标语言有但 en.ts 没有的 key
|
||||
* - 黄色:相同的 key 所在的行号不相同
|
||||
*
|
||||
* 依赖:
|
||||
* Node.js 环境,无需额外依赖。
|
||||
*
|
||||
* 用法:
|
||||
* 1. 在命令行进入本文件所在目录(或项目根目录)。
|
||||
* 2. 运行:
|
||||
* node src/lang/langDiffWithEn.js zh-cn
|
||||
* # 或 node src/lang/langDiffWithEn.js ja
|
||||
* # 参数为语言文件名(不带扩展名),默认为 zh-cn
|
||||
*
|
||||
* 输出说明:
|
||||
* + 开头(绿色):en.ts 有但目标语言缺失的 key
|
||||
* - 开头(红色):目标语言有但 en.ts 没有的 key
|
||||
* ! 开头(黄色):相同的 key 所在的行号不相同
|
||||
* 若无输出则表示两个文件 key 完全一致。
|
||||
*/
|
||||
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
|
||||
/**
|
||||
* 读取 locale 文件夹下指定语言和 en.ts 文件,逐行解析键值和行号
|
||||
* @param lang 语言文件名(不含扩展名),如 zh-cn
|
||||
* @returns { en: Record<string, {value: string, line: number}>, lang: Record<string, {value: string, line: number}> }
|
||||
*/
|
||||
function readLocaleFiles(lang = "zh-cn") {
|
||||
// 构造 locale 目录路径
|
||||
const localeDir = path.join(__dirname, "./locale");
|
||||
// 获取 en.ts 文件路径
|
||||
const enFile = path.join(localeDir, "en.ts");
|
||||
// 获取指定语言文件路径
|
||||
const langFile = path.join(localeDir, `${lang}.ts`);
|
||||
/**
|
||||
* 解析指定的语言文件,提取每个 key 的值和所在行号
|
||||
* @param file 文件路径
|
||||
* @returns {Record<string, {value: string, line: number}>}
|
||||
*/
|
||||
const parse = (file) => {
|
||||
// 读取文件内容并按行分割
|
||||
const lines = fs.readFileSync(file, "utf8").split(/\r?\n/);
|
||||
const result = {};
|
||||
let inExport = false;
|
||||
for (let i = 0; i < lines.length; i++) {
|
||||
const line = lines[i];
|
||||
// 检查是否进入 export default 块
|
||||
if (!inExport && line.includes("export default")) {
|
||||
inExport = true;
|
||||
continue;
|
||||
}
|
||||
if (!inExport) continue;
|
||||
// 匹配 key: "value", 格式的行
|
||||
const m = line.match(/^\s*([A-Z0-9_]+)\s*:\s*.*?,?$/);
|
||||
if (m) {
|
||||
let key = m[1];
|
||||
// 保存 key 及其所在行号
|
||||
result[key] = i + 1;
|
||||
}
|
||||
}
|
||||
return result;
|
||||
};
|
||||
// 返回 en 和指定语言的解析结果
|
||||
return {
|
||||
en: parse(enFile),
|
||||
lang: parse(langFile),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 比较 en 和 lang 的 key/value,输出差异
|
||||
*/
|
||||
|
||||
function diffLang(lang = "zh-cn") {
|
||||
const { en, lang: l } = readLocaleFiles(lang);
|
||||
const allKeys = new Set([...Object.keys(en), ...Object.keys(l)]);
|
||||
const diffs = [];
|
||||
for (const key of allKeys) {
|
||||
if (!(key in en)) {
|
||||
diffs.push(`- ${key}: ${l[key]}`);
|
||||
} else if (!(key in l)) {
|
||||
diffs.push(`+ ${key}: ${en[key]}`);
|
||||
} else {
|
||||
if (en[key] !== l[key]) {
|
||||
diffs.push(`! ${key}: en: ${en[key]} <--> lang: ${l[key]}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
return diffs;
|
||||
}
|
||||
|
||||
// CLI
|
||||
if (require.main === module) {
|
||||
const lang = process.argv[2] || "zh-cn";
|
||||
const diffs = diffLang(lang);
|
||||
if (diffs.length === 0) {
|
||||
console.log(`语言文件 ${lang} 与 en.ts 无差异`);
|
||||
} else {
|
||||
diffs.forEach((line) => {
|
||||
if (line.startsWith("+")) {
|
||||
// 绿色
|
||||
console.log("\x1b[32m%s\x1b[0m", line);
|
||||
} else if (line.startsWith("-")) {
|
||||
// 红色
|
||||
console.log("\x1b[31m%s\x1b[0m", line);
|
||||
} else if (line.startsWith("!")) {
|
||||
// 黄色
|
||||
console.log("\x1b[33m%s\x1b[0m", line);
|
||||
} else {
|
||||
// 默认
|
||||
console.log(line);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Language Pack Diff Checker Script
|
||||
*
|
||||
* Purpose:
|
||||
* Compare src/lang/locale/en.ts and a target language file (e.g. zh-cn.ts), output missing and extra keys.
|
||||
* Output is color-coded:
|
||||
* - Green: Key exists in en.ts but missing in the target language file
|
||||
* - Red: Key exists in the target language file but not in en.ts
|
||||
* - Yellow: The same key exists in both files but the line numbers are different
|
||||
*
|
||||
* Dependencies:
|
||||
* Node.js environment, no extra dependencies required.
|
||||
*
|
||||
* Usage:
|
||||
* 1. Open a terminal in this file's directory (or project root).
|
||||
* 2. Run:
|
||||
* node src/lang/langDiffWithEn.js zh-cn
|
||||
* # or node src/lang/langDiffWithEn.js ja
|
||||
* # The argument is the language file name (without extension), default is zh-cn
|
||||
*
|
||||
* Output:
|
||||
* + (green): Key exists in en.ts but missing in the target language file
|
||||
* - (red): Key exists in the target language file but not in en.ts
|
||||
* ! (yellow): The same key exists in both files but the line numbers are different
|
||||
* If there is no output, the two files have identical keys.
|
||||
*/
|
||||
/**
|
||||
* 语言包差异检测脚本
|
||||
*
|
||||
* 用途:
|
||||
* 比较 src/lang/locale/en.ts 与指定语言文件(如 zh-cn.ts)中的 key,输出缺失和多余的 key。
|
||||
* 输出内容会用不同颜色区分:
|
||||
* - 绿色:en.ts 有但目标语言缺失的 key
|
||||
* - 红色:目标语言有但 en.ts 没有的 key
|
||||
* - 黄色:相同的 key 所在的行号不相同
|
||||
*
|
||||
* 依赖:
|
||||
* Node.js 环境,无需额外依赖。
|
||||
*
|
||||
* 用法:
|
||||
* 1. 在命令行进入本文件所在目录(或项目根目录)。
|
||||
* 2. 运行:
|
||||
* node src/lang/langDiffWithEn.js zh-cn
|
||||
* # 或 node src/lang/langDiffWithEn.js ja
|
||||
* # 参数为语言文件名(不带扩展名),默认为 zh-cn
|
||||
*
|
||||
* 输出说明:
|
||||
* + 开头(绿色):en.ts 有但目标语言缺失的 key
|
||||
* - 开头(红色):目标语言有但 en.ts 没有的 key
|
||||
* ! 开头(黄色):相同的 key 所在的行号不相同
|
||||
* 若无输出则表示两个文件 key 完全一致。
|
||||
*/
|
||||
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
|
||||
/**
|
||||
* 读取 locale 文件夹下指定语言和 en.ts 文件,逐行解析键值和行号
|
||||
* @param lang 语言文件名(不含扩展名),如 zh-cn
|
||||
* @returns { en: Record<string, {value: string, line: number}>, lang: Record<string, {value: string, line: number}> }
|
||||
*/
|
||||
function readLocaleFiles(lang = "zh-cn") {
|
||||
// 构造 locale 目录路径
|
||||
const localeDir = path.join(__dirname, "./locale");
|
||||
// 获取 en.ts 文件路径
|
||||
const enFile = path.join(localeDir, "en.ts");
|
||||
// 获取指定语言文件路径
|
||||
const langFile = path.join(localeDir, `${lang}.ts`);
|
||||
/**
|
||||
* 解析指定的语言文件,提取每个 key 的值和所在行号
|
||||
* @param file 文件路径
|
||||
* @returns {Record<string, {value: string, line: number}>}
|
||||
*/
|
||||
const parse = (file) => {
|
||||
// 读取文件内容并按行分割
|
||||
const lines = fs.readFileSync(file, "utf8").split(/\r?\n/);
|
||||
const result = {};
|
||||
let inExport = false;
|
||||
for (let i = 0; i < lines.length; i++) {
|
||||
const line = lines[i];
|
||||
// 检查是否进入 export default 块
|
||||
if (!inExport && line.includes("export default")) {
|
||||
inExport = true;
|
||||
continue;
|
||||
}
|
||||
if (!inExport) {
|
||||
continue;
|
||||
}
|
||||
// 匹配 key: "value", 格式的行
|
||||
const m = line.match(/^\s*([A-Z0-9_]+)\s*:\s*.*?,?$/);
|
||||
if (m) {
|
||||
let key = m[1];
|
||||
// 保存 key 及其所在行号
|
||||
result[key] = i + 1;
|
||||
}
|
||||
}
|
||||
return result;
|
||||
};
|
||||
// 返回 en 和指定语言的解析结果
|
||||
return {
|
||||
en: parse(enFile),
|
||||
lang: parse(langFile),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 比较 en 和 lang 的 key/value,输出差异
|
||||
*/
|
||||
|
||||
function diffLang(lang = "zh-cn") {
|
||||
const { en, lang: l } = readLocaleFiles(lang);
|
||||
const allKeys = new Set([...Object.keys(en), ...Object.keys(l)]);
|
||||
const diffs = [];
|
||||
for (const key of allKeys) {
|
||||
if (!(key in en)) {
|
||||
diffs.push(`- ${key}: ${l[key]}`);
|
||||
} else if (!(key in l)) {
|
||||
diffs.push(`+ ${key}: ${en[key]}`);
|
||||
} else if (en[key] !== l[key]) {
|
||||
diffs.push(`! ${key}: en: ${en[key]} <--> lang: ${l[key]}`);
|
||||
}
|
||||
}
|
||||
return diffs;
|
||||
}
|
||||
|
||||
// CLI
|
||||
if (require.main === module) {
|
||||
const lang = process.argv[2] || "zh-cn";
|
||||
const diffs = diffLang(lang);
|
||||
if (diffs.length === 0) {
|
||||
console.log(`语言文件 ${lang} 与 en.ts 无差异`);
|
||||
} else {
|
||||
diffs.forEach((line) => {
|
||||
if (line.startsWith("+")) {
|
||||
// 绿色
|
||||
console.log("\x1b[32m%s\x1b[0m", line);
|
||||
} else if (line.startsWith("-")) {
|
||||
// 红色
|
||||
console.log("\x1b[31m%s\x1b[0m", line);
|
||||
} else if (line.startsWith("!")) {
|
||||
// 黄色
|
||||
console.log("\x1b[33m%s\x1b[0m", line);
|
||||
} else {
|
||||
// 默认
|
||||
console.log(line);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
+561
-252
File diff suppressed because it is too large.
Load diff
+594
-301
File diff suppressed because it is too large.
Load diff
+533
-225
File diff suppressed because it is too large.
Load diff
+422
-235
File diff suppressed because it is too large.
Load diff
+429
-242
File diff suppressed because it is too large.
Load diff
+110
-67
@@ -1,34 +1,37 @@
|
||||
import { ExcalidrawElement, FileId } from "@zsviczian/excalidraw/types/element/src/types";
|
||||
import {
|
||||
ExcalidrawElement,
|
||||
FileId,
|
||||
} from "@zsviczian/excalidraw/types/element/src/types";
|
||||
import { BinaryFileData } from "@zsviczian/excalidraw/types/excalidraw/types";
|
||||
import { Mutable } from "@zsviczian/excalidraw/types/common/src/utility-types";
|
||||
import { Notice } from "obsidian";
|
||||
|
||||
import { getEA } from "src/core";
|
||||
import { ExcalidrawAutomate } from "src/shared/ExcalidrawAutomate";
|
||||
import { cloneElement } from "src/utils/excalidrawAutomateUtils";
|
||||
import { cloneElement } from "src/utils/excalidrawViewHelpers";
|
||||
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.
|
||||
*
|
||||
*
|
||||
* The scene must contain:
|
||||
* - One element.type="frame" element that defines the crop area
|
||||
* - One or more element.type="image" elements
|
||||
* - Zero or more non-image shape elements (rectangles, ellipses etc) that define the mask
|
||||
*
|
||||
*
|
||||
* The class splits the scene into two parts:
|
||||
* 1. Images (managed in imageEA)
|
||||
* 2. Mask shapes (managed in maskEA)
|
||||
*
|
||||
*
|
||||
* A transparent rectangle matching the combined bounding box is added to both
|
||||
* imageEA and maskEA to ensure consistent sizing between image and mask.
|
||||
*
|
||||
*
|
||||
* For performance, if there is only one image, it is not rotated, and
|
||||
* its size matches the bounding box,
|
||||
* the image data is used directly from cache rather than regenerating.
|
||||
*
|
||||
*
|
||||
* @example
|
||||
* const cropper = new CropImage(elements, files);
|
||||
* const pngBlob = await cropper.getCroppedPNG();
|
||||
@@ -37,15 +40,15 @@ import { ExportSettings } from "src/types/exportUtilTypes";
|
||||
export class CropImage {
|
||||
private imageEA: ExcalidrawAutomate;
|
||||
private maskEA: ExcalidrawAutomate;
|
||||
private bbox: {topX: number, topY: number, width: number, height: number};
|
||||
private bbox: { topX: number; topY: number; width: number; height: number };
|
||||
|
||||
constructor (
|
||||
constructor(
|
||||
private elements: ExcalidrawElement[],
|
||||
files: Map<FileId,BinaryFileData>,
|
||||
files: Map<FileId, BinaryFileData>,
|
||||
) {
|
||||
const imageEA = getEA() as ExcalidrawAutomate;
|
||||
const imageEA = getEA();
|
||||
this.imageEA = imageEA;
|
||||
const maskEA = getEA() as ExcalidrawAutomate;
|
||||
const maskEA = getEA();
|
||||
this.maskEA = maskEA;
|
||||
|
||||
this.bbox = imageEA.getBoundingBox(elements);
|
||||
@@ -54,20 +57,20 @@ export class CropImage {
|
||||
this.setBoundingEl(imageEA, "transparent");
|
||||
this.setBoundingEl(maskEA, "white"); //the bbox should not mask the image. White lets everything through.
|
||||
|
||||
elements.forEach(el => {
|
||||
elements.forEach((el) => {
|
||||
const newEl = cloneElement(el) as Mutable<ExcalidrawElement>;
|
||||
if(el.type !== "image" && el.type !== "frame") {
|
||||
if (el.type !== "image" && el.type !== "frame") {
|
||||
newEl.opacity = 100;
|
||||
maskEA.elementsDict[el.id] = newEl;
|
||||
}
|
||||
if(el.type === "image") {
|
||||
if (el.type === "image") {
|
||||
imageEA.elementsDict[el.id] = newEl;
|
||||
}
|
||||
})
|
||||
});
|
||||
|
||||
Object.values(files).forEach(file => {
|
||||
Object.values(files).forEach((file) => {
|
||||
imageEA.imagesDict[file.id] = file;
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
public destroy() {
|
||||
@@ -78,127 +81,157 @@ export class CropImage {
|
||||
this.elements = null;
|
||||
this.bbox = null;
|
||||
}
|
||||
|
||||
|
||||
private setBoundingEl(ea: ExcalidrawAutomate, bgColor: string) {
|
||||
const {topX, topY, width, height} = this.bbox;
|
||||
const { topX, topY, width, height } = this.bbox;
|
||||
ea.style.backgroundColor = bgColor;
|
||||
ea.style.strokeColor = "transparent";
|
||||
//@ts-ignore: Setting this to string "0" will produce a rectangle with zero stroke width
|
||||
ea.style.strokeWidth = "0";
|
||||
ea.style.strokeWidth = 0;
|
||||
ea.style.strokeStyle = "solid";
|
||||
ea.style.fillStyle = "solid";
|
||||
ea.style.roughness = 0;
|
||||
ea.addRect(topX, topY, width, height);
|
||||
}
|
||||
|
||||
private getViewBoxAndSize(): {viewBox: string, vbWidth: number, vbHeight: number, width: number, height: number} {
|
||||
const frames = this.elements.filter(el=>el.type === "frame");
|
||||
if(frames.length > 1) {
|
||||
new Notice("Multiple frames are not supported for image cropping. Discarding frames from mask.");
|
||||
private getViewBoxAndSize(): {
|
||||
viewBox: string;
|
||||
vbWidth: number;
|
||||
vbHeight: number;
|
||||
width: number;
|
||||
height: number;
|
||||
} {
|
||||
const frames = this.elements.filter((el) => el.type === "frame");
|
||||
if (frames.length > 1) {
|
||||
new Notice(
|
||||
"Multiple frames are not supported for image cropping. Discarding frames from mask.",
|
||||
);
|
||||
}
|
||||
const images = this.imageEA.getElements().filter(el=>el.type === "image");
|
||||
const {x: frameX, y: frameY, width: frameWidth, height: frameHeight} = frames.length === 1
|
||||
const images = this.imageEA
|
||||
.getElements()
|
||||
.filter((el) => el.type === "image");
|
||||
const {
|
||||
x: frameX,
|
||||
y: frameY,
|
||||
width: frameWidth,
|
||||
height: frameHeight,
|
||||
} = frames.length === 1
|
||||
? frames[0]
|
||||
: mapToXY(this.imageEA.getBoundingBox(images));
|
||||
const {topX, topY, width, height} = this.bbox;
|
||||
const { topX, topY, width, height } = this.bbox;
|
||||
return {
|
||||
viewBox: `${frameX-topX} ${frameY-topY} ${frameWidth} ${frameHeight}`,
|
||||
viewBox: `${frameX - topX} ${frameY - topY} ${frameWidth} ${frameHeight}`,
|
||||
vbWidth: frameWidth,
|
||||
vbHeight: frameHeight,
|
||||
width,
|
||||
height,
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private async getMaskSVG():Promise<{style: string, mask: string}> {
|
||||
const exportSettings:ExportSettings = {
|
||||
private async getMaskSVG(): Promise<{ style: string; mask: string }> {
|
||||
const exportSettings: ExportSettings = {
|
||||
withBackground: false,
|
||||
withTheme: false,
|
||||
isMask: false,
|
||||
}
|
||||
};
|
||||
|
||||
const maskSVG = await this.maskEA.createSVG(null,true,exportSettings,null,null,0);
|
||||
const maskSVG = await this.maskEA.createSVG(
|
||||
null,
|
||||
true,
|
||||
exportSettings,
|
||||
null,
|
||||
null,
|
||||
0,
|
||||
);
|
||||
const defs = maskSVG.querySelector("defs");
|
||||
const styleEl = maskSVG.querySelector("style");
|
||||
const style = styleEl ? styleEl.outerHTML : "";
|
||||
defs.parentElement.removeChild(defs);
|
||||
return {style, mask:maskSVG.innerHTML};
|
||||
return { style, mask: maskSVG.innerHTML };
|
||||
}
|
||||
|
||||
private async getImage() {
|
||||
const exportSettings:ExportSettings = {
|
||||
const exportSettings: ExportSettings = {
|
||||
withBackground: false,
|
||||
withTheme: false,
|
||||
isMask: false,
|
||||
}
|
||||
const images = this.imageEA.getElements().filter(el=>el.type === "image" && el.isDeleted === false);
|
||||
const isRotated = images.some(el=>el.angle !== 0);
|
||||
};
|
||||
const images = this.imageEA
|
||||
.getElements()
|
||||
.filter((el) => el.type === "image" && el.isDeleted === false);
|
||||
const isRotated = images.some((el) => el.angle !== 0);
|
||||
const imageDataURLs = Object.values(this.imageEA.imagesDict);
|
||||
if(!isRotated && images.length === 1 && imageDataURLs.length === 1) {
|
||||
if (!isRotated && images.length === 1 && imageDataURLs.length === 1) {
|
||||
const { width, height } = this.bbox;
|
||||
if(images[0].width === width && images[0].height === height) {
|
||||
if (images[0].width === width && images[0].height === height) {
|
||||
//get image from the cache if mask is not bigger than the image, and if there is a single image element
|
||||
return imageDataURLs[0].dataURL;
|
||||
}
|
||||
}
|
||||
return await this.imageEA.createPNGBase64(null,1,exportSettings,null,null,0);
|
||||
return await this.imageEA.createPNGBase64(
|
||||
null,
|
||||
1,
|
||||
exportSettings,
|
||||
null,
|
||||
null,
|
||||
0,
|
||||
);
|
||||
}
|
||||
|
||||
private async buildSVG(): Promise<SVGSVGElement> {
|
||||
if(this.imageEA.getElements().filter(el=>el.type === "image").length === 0) {
|
||||
if (
|
||||
this.imageEA.getElements().filter((el) => el.type === "image").length ===
|
||||
0
|
||||
) {
|
||||
new Notice("No image found. Cannot crop.");
|
||||
return;
|
||||
}
|
||||
const maskID = nanoid();
|
||||
const imageID = nanoid();
|
||||
const {viewBox, vbWidth, vbHeight, width, height} = this.getViewBoxAndSize();
|
||||
const { viewBox, vbWidth, vbHeight, width, height } =
|
||||
this.getViewBoxAndSize();
|
||||
const parser = new DOMParser();
|
||||
const {style, mask} = await this.getMaskSVG();
|
||||
const svgString = `<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="${viewBox}" width="${vbWidth}" height="${vbHeight}">\n` +
|
||||
const { style, mask } = await this.getMaskSVG();
|
||||
const svgString =
|
||||
`<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="${viewBox}" width="${vbWidth}" height="${vbHeight}">\n` +
|
||||
`<symbol id="${imageID}"><image width="100%" height="100%" href="${await this.getImage()}"/></symbol>\n` +
|
||||
`<defs>${style}\n<mask id="${maskID}" x="0" y="0" width="${width}" height="${height}" maskUnits="userSpaceOnUse">\n${mask}\n</mask>\n</defs>\n` +
|
||||
`<use x="0" y="0" width="${width}" height="${height}" mask="url(#${maskID})" mask-type="alpha" href="#${imageID}"/>\n</svg>`;
|
||||
return parser.parseFromString(
|
||||
svgString,
|
||||
"image/svg+xml",
|
||||
).firstElementChild as SVGSVGElement
|
||||
|
||||
return parser.parseFromString(svgString, "image/svg+xml")
|
||||
.firstElementChild as SVGSVGElement;
|
||||
}
|
||||
|
||||
async getCroppedPNG(): Promise<Blob> {
|
||||
//@ts-ignore
|
||||
const PLUGIN = app.plugins.plugins["obsidian-excalidraw-plugin"];
|
||||
const svg = await this.buildSVG();
|
||||
return new Promise((resolve, reject) => {
|
||||
//https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2026
|
||||
const svgData = svg.outerHTML;
|
||||
//const svgData = new XMLSerializer().serializeToString(svg);
|
||||
const canvas = document.createElement('canvas');
|
||||
const context = canvas.getContext('2d');
|
||||
|
||||
const canvas = document.createElement("canvas");
|
||||
const context = canvas.getContext("2d");
|
||||
|
||||
if (!context) {
|
||||
reject('Unable to get 2D context');
|
||||
reject("Unable to get 2D context");
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
canvas.width = svg.width.baseVal.value;
|
||||
canvas.height = svg.height.baseVal.value;
|
||||
|
||||
|
||||
const image = new Image();
|
||||
image.onload = () => {
|
||||
context.clearRect(0, 0, canvas.width, canvas.height);
|
||||
context.drawImage(image, 0, 0);
|
||||
|
||||
|
||||
canvas.toBlob(
|
||||
(blob) => {
|
||||
if (blob) {
|
||||
resolve(blob);
|
||||
} else {
|
||||
reject(new Error('Failed to convert to PNG'));
|
||||
reject(new Error("Failed to convert to PNG"));
|
||||
}
|
||||
},
|
||||
'image/png',
|
||||
1 // image quality (0 - 1)
|
||||
"image/png",
|
||||
1, // image quality (0 - 1)
|
||||
);
|
||||
};
|
||||
image.src = svgToBase64(svgData);
|
||||
@@ -210,11 +243,21 @@ export class CropImage {
|
||||
}
|
||||
}
|
||||
|
||||
const mapToXY = ({topX, topY, width, height}: {topX: number, topY: number, width: number, height: number}): {x: number, y: number, width: number, height: number} => {
|
||||
const mapToXY = ({
|
||||
topX,
|
||||
topY,
|
||||
width,
|
||||
height,
|
||||
}: {
|
||||
topX: number;
|
||||
topY: number;
|
||||
width: number;
|
||||
height: number;
|
||||
}): { x: number; y: number; width: number; height: number } => {
|
||||
return {
|
||||
x: topX,
|
||||
y: topY,
|
||||
width,
|
||||
height,
|
||||
}
|
||||
}
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,207 @@
|
||||
import { App, Modal, Notice, Setting } from "obsidian";
|
||||
import { t } from "src/lang/helpers";
|
||||
import { AIImageModelCapability } from "src/types/AIUtilTypes";
|
||||
import { isWinCTRLorMacCMD } from "src/utils/modifierkeyHelper";
|
||||
|
||||
type SaveHandler = (
|
||||
modelId: string,
|
||||
capability: AIImageModelCapability,
|
||||
previousModelId?: string,
|
||||
) => Promise<void> | void;
|
||||
|
||||
export class AIImageModelCapabilityModal extends Modal {
|
||||
private modelId: string;
|
||||
private supportsPromptImageTransforms: boolean;
|
||||
private supportsMaskImageEdits: boolean;
|
||||
private supportedSizes: string[];
|
||||
private onKeyDown: (ev: KeyboardEvent) => void;
|
||||
private listenerHost: Document | null = null;
|
||||
|
||||
constructor(
|
||||
app: App,
|
||||
private readonly existingModelIds: string[],
|
||||
private readonly onSave: SaveHandler,
|
||||
private readonly options: {
|
||||
previousModelId?: string;
|
||||
initialModelId?: string;
|
||||
initialCapability?: AIImageModelCapability;
|
||||
} = {},
|
||||
) {
|
||||
super(app);
|
||||
this.modelId = options.initialModelId ?? "";
|
||||
this.supportsPromptImageTransforms =
|
||||
options.initialCapability?.supportsPromptImageTransforms ?? true;
|
||||
this.supportsMaskImageEdits =
|
||||
options.initialCapability?.supportsMaskImageEdits ?? true;
|
||||
this.supportedSizes = [
|
||||
...(options.initialCapability?.supportedSizes?.length
|
||||
? options.initialCapability.supportedSizes
|
||||
: ["1024x1024"]),
|
||||
];
|
||||
}
|
||||
|
||||
onOpen(): void {
|
||||
this.createForm();
|
||||
}
|
||||
|
||||
onClose() {
|
||||
if (this.listenerHost && this.onKeyDown) {
|
||||
this.listenerHost.removeEventListener("keydown", this.onKeyDown);
|
||||
this.listenerHost = null;
|
||||
}
|
||||
this.contentEl.empty();
|
||||
}
|
||||
|
||||
private createForm() {
|
||||
const contentEl = this.contentEl;
|
||||
contentEl.empty();
|
||||
contentEl.createEl("h1", {
|
||||
text: this.options.previousModelId
|
||||
? t("AI_IMAGE_MODEL_CAPABILITY_MODAL_EDIT_TITLE")
|
||||
: t("AI_IMAGE_MODEL_CAPABILITY_MODAL_ADD_TITLE"),
|
||||
});
|
||||
|
||||
new Setting(contentEl)
|
||||
.setName(t("AI_IMAGE_MODEL_CAPABILITIES_MODAL_MODEL_NAME"))
|
||||
.setDesc(t("AI_IMAGE_MODEL_CAPABILITIES_MODAL_MODEL_DESC"))
|
||||
.addText((text) =>
|
||||
text
|
||||
.setPlaceholder(
|
||||
t("AI_IMAGE_MODEL_CAPABILITIES_MODAL_MODEL_PLACEHOLDER"),
|
||||
)
|
||||
.setValue(this.modelId)
|
||||
.onChange((value) => {
|
||||
this.modelId = value.trim();
|
||||
}),
|
||||
);
|
||||
|
||||
new Setting(contentEl)
|
||||
.setName(t("AI_IMAGE_MODEL_CAPABILITIES_TRANSFORMS_NAME"))
|
||||
.setDesc(t("AI_IMAGE_MODEL_CAPABILITIES_TRANSFORMS_DESC"))
|
||||
.addToggle((toggle) =>
|
||||
toggle
|
||||
.setValue(this.supportsPromptImageTransforms)
|
||||
.onChange((value) => {
|
||||
this.supportsPromptImageTransforms = value;
|
||||
}),
|
||||
);
|
||||
|
||||
new Setting(contentEl)
|
||||
.setName(t("AI_IMAGE_MODEL_CAPABILITIES_MASK_EDITS_NAME"))
|
||||
.setDesc(t("AI_IMAGE_MODEL_CAPABILITIES_MASK_EDITS_DESC"))
|
||||
.addToggle((toggle) =>
|
||||
toggle.setValue(this.supportsMaskImageEdits).onChange((value) => {
|
||||
this.supportsMaskImageEdits = value;
|
||||
}),
|
||||
);
|
||||
|
||||
contentEl.createEl("h3", {
|
||||
text: t("AI_IMAGE_MODEL_CAPABILITIES_SIZES_NAME"),
|
||||
});
|
||||
contentEl.createEl("p", {
|
||||
text: t("AI_IMAGE_MODEL_CAPABILITIES_MODAL_SIZES_DESC"),
|
||||
});
|
||||
|
||||
const sizesContainer = contentEl.createDiv();
|
||||
const renderSizes = () => {
|
||||
sizesContainer.empty();
|
||||
this.supportedSizes.forEach((size, index) => {
|
||||
new Setting(sizesContainer)
|
||||
.setName(
|
||||
`${t("AI_IMAGE_MODEL_CAPABILITIES_MODAL_SIZE_LABEL")} ${index + 1}`,
|
||||
)
|
||||
.addText((text) =>
|
||||
text
|
||||
.setPlaceholder(
|
||||
t("AI_IMAGE_MODEL_CAPABILITIES_SIZES_PLACEHOLDER"),
|
||||
)
|
||||
.setValue(size)
|
||||
.onChange((value) => {
|
||||
this.supportedSizes[index] = value.trim();
|
||||
}),
|
||||
)
|
||||
.addButton((button) =>
|
||||
button
|
||||
.setButtonText(t("AI_IMAGE_MODEL_CAPABILITIES_MODAL_REMOVE_SIZE"))
|
||||
.setDisabled(this.supportedSizes.length <= 1)
|
||||
.onClick(() => {
|
||||
this.supportedSizes.splice(index, 1);
|
||||
renderSizes();
|
||||
}),
|
||||
);
|
||||
});
|
||||
};
|
||||
|
||||
renderSizes();
|
||||
|
||||
new Setting(contentEl).addButton((button) =>
|
||||
button
|
||||
.setButtonText(t("AI_IMAGE_MODEL_CAPABILITIES_MODAL_ADD_SIZE"))
|
||||
.onClick(() => {
|
||||
this.supportedSizes.push("1024x1024");
|
||||
renderSizes();
|
||||
}),
|
||||
);
|
||||
|
||||
new Setting(contentEl)
|
||||
.addButton((button) =>
|
||||
button
|
||||
.setButtonText(t("PROMPT_BUTTON_CANCEL"))
|
||||
.onClick(() => this.close()),
|
||||
)
|
||||
.addButton((button) =>
|
||||
button
|
||||
.setButtonText(t("PROMPT_BUTTON_OK"))
|
||||
.setCta()
|
||||
.onClick(() => void this.save()),
|
||||
);
|
||||
|
||||
this.onKeyDown = (ev: KeyboardEvent) => {
|
||||
if (isWinCTRLorMacCMD(ev) && ev.key === "Enter") {
|
||||
void this.save();
|
||||
}
|
||||
};
|
||||
|
||||
const ownerDoc = this.containerEl.ownerDocument;
|
||||
if (ownerDoc) {
|
||||
this.listenerHost = ownerDoc;
|
||||
ownerDoc.addEventListener("keydown", this.onKeyDown);
|
||||
}
|
||||
}
|
||||
|
||||
private async save() {
|
||||
const normalizedModelId = this.modelId.trim();
|
||||
const normalizedSizes = Array.from(
|
||||
new Set(this.supportedSizes.map((size) => size.trim()).filter(Boolean)),
|
||||
);
|
||||
|
||||
if (!normalizedModelId) {
|
||||
new Notice(t("AI_IMAGE_MODEL_CAPABILITIES_MODAL_MODEL_REQUIRED"));
|
||||
return;
|
||||
}
|
||||
|
||||
if (normalizedSizes.length === 0) {
|
||||
new Notice(t("AI_IMAGE_MODEL_CAPABILITIES_MODAL_SIZE_REQUIRED"));
|
||||
return;
|
||||
}
|
||||
|
||||
const duplicateExists =
|
||||
this.existingModelIds.includes(normalizedModelId) &&
|
||||
normalizedModelId !== this.options.previousModelId;
|
||||
if (duplicateExists) {
|
||||
new Notice(t("AI_IMAGE_MODEL_CAPABILITIES_MODAL_DUPLICATE_MODEL"));
|
||||
return;
|
||||
}
|
||||
|
||||
await this.onSave(
|
||||
normalizedModelId,
|
||||
{
|
||||
supportedSizes: normalizedSizes,
|
||||
supportsPromptImageTransforms: this.supportsPromptImageTransforms,
|
||||
supportsMaskImageEdits: this.supportsMaskImageEdits,
|
||||
},
|
||||
this.options.previousModelId,
|
||||
);
|
||||
this.close();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,346 @@
|
||||
import { App, Modal, Notice, Setting } from "obsidian";
|
||||
import { t } from "src/lang/helpers";
|
||||
import { AIImageModelConfig, AIModelConfig } from "src/types/AIUtilTypes";
|
||||
import { isWinCTRLorMacCMD } from "src/utils/modifierkeyHelper";
|
||||
|
||||
type SaveHandler<TConfig extends AIModelConfig> = (
|
||||
modelId: string,
|
||||
config: TConfig,
|
||||
previousModelId?: string,
|
||||
) => Promise<void> | void;
|
||||
|
||||
type AIModelConfigModalOptions<TConfig extends AIModelConfig> = {
|
||||
kind: "text" | "vision" | "image";
|
||||
providerIds: string[];
|
||||
previousModelId?: string;
|
||||
initialModelId?: string;
|
||||
initialConfig?: TConfig;
|
||||
};
|
||||
|
||||
export class AIModelConfigModal<
|
||||
TConfig extends AIModelConfig | AIImageModelConfig,
|
||||
> extends Modal {
|
||||
private modelId: string;
|
||||
private config: TConfig;
|
||||
private onKeyDown: (ev: KeyboardEvent) => void;
|
||||
private listenerHost: Document | null = null;
|
||||
private backdropInteractionHandler: ((ev: Event) => void) | null = null;
|
||||
|
||||
constructor(
|
||||
app: App,
|
||||
private readonly existingModelIds: string[],
|
||||
private readonly onSave: SaveHandler<TConfig>,
|
||||
private readonly options: AIModelConfigModalOptions<TConfig>,
|
||||
) {
|
||||
super(app);
|
||||
const firstProviderId = options.providerIds[0] ?? "";
|
||||
this.modelId = options.initialModelId ?? "";
|
||||
this.config = {
|
||||
providerId: options.initialConfig?.providerId ?? firstProviderId,
|
||||
model: options.initialConfig?.model ?? "",
|
||||
endpoint: options.initialConfig?.endpoint ?? "",
|
||||
...(options.kind === "text"
|
||||
? {
|
||||
multimodalSupport: options.initialConfig?.multimodalSupport ?? true,
|
||||
}
|
||||
: {}),
|
||||
...(options.kind === "image"
|
||||
? {
|
||||
supportedSizes: [
|
||||
...((options.initialConfig as AIImageModelConfig | undefined)
|
||||
?.supportedSizes?.length
|
||||
? (options.initialConfig as AIImageModelConfig).supportedSizes
|
||||
: ["1024x1024"]),
|
||||
],
|
||||
supportsPromptImageTransforms:
|
||||
(options.initialConfig as AIImageModelConfig | undefined)
|
||||
?.supportsPromptImageTransforms ?? true,
|
||||
supportsMaskImageEdits:
|
||||
(options.initialConfig as AIImageModelConfig | undefined)
|
||||
?.supportsMaskImageEdits ?? true,
|
||||
}
|
||||
: {}),
|
||||
} as TConfig;
|
||||
}
|
||||
|
||||
onOpen(): void {
|
||||
this.backdropInteractionHandler = (ev: Event) => {
|
||||
if (ev.target === this.containerEl) {
|
||||
ev.preventDefault();
|
||||
ev.stopImmediatePropagation();
|
||||
}
|
||||
};
|
||||
this.containerEl.addEventListener(
|
||||
"mousedown",
|
||||
this.backdropInteractionHandler,
|
||||
true,
|
||||
);
|
||||
this.containerEl.addEventListener(
|
||||
"click",
|
||||
this.backdropInteractionHandler,
|
||||
true,
|
||||
);
|
||||
this.createForm();
|
||||
}
|
||||
|
||||
onClose() {
|
||||
if (this.backdropInteractionHandler) {
|
||||
this.containerEl.removeEventListener(
|
||||
"mousedown",
|
||||
this.backdropInteractionHandler,
|
||||
true,
|
||||
);
|
||||
this.containerEl.removeEventListener(
|
||||
"click",
|
||||
this.backdropInteractionHandler,
|
||||
true,
|
||||
);
|
||||
this.backdropInteractionHandler = null;
|
||||
}
|
||||
if (this.listenerHost && this.onKeyDown) {
|
||||
this.listenerHost.removeEventListener("keydown", this.onKeyDown, true);
|
||||
this.listenerHost = null;
|
||||
}
|
||||
this.contentEl.empty();
|
||||
}
|
||||
|
||||
private getTitle() {
|
||||
const isEdit = Boolean(this.options.previousModelId);
|
||||
switch (this.options.kind) {
|
||||
case "vision":
|
||||
return isEdit
|
||||
? t("AI_VISION_MODEL_MODAL_EDIT_TITLE")
|
||||
: t("AI_VISION_MODEL_MODAL_ADD_TITLE");
|
||||
case "image":
|
||||
return isEdit
|
||||
? t("AI_IMAGE_MODEL_MODAL_EDIT_TITLE")
|
||||
: t("AI_IMAGE_MODEL_MODAL_ADD_TITLE");
|
||||
default:
|
||||
return isEdit
|
||||
? t("AI_TEXT_MODEL_MODAL_EDIT_TITLE")
|
||||
: t("AI_TEXT_MODEL_MODAL_ADD_TITLE");
|
||||
}
|
||||
}
|
||||
|
||||
private createForm() {
|
||||
const contentEl = this.contentEl;
|
||||
contentEl.empty();
|
||||
contentEl.createEl("h1", { text: this.getTitle() });
|
||||
|
||||
new Setting(contentEl)
|
||||
.setName(t("AI_MODEL_CONFIG_MODAL_NAME_NAME"))
|
||||
.setDesc(t("AI_MODEL_CONFIG_MODAL_NAME_DESC"))
|
||||
.addText((text) =>
|
||||
text
|
||||
.setPlaceholder(t("AI_MODEL_CONFIG_MODAL_NAME_PLACEHOLDER"))
|
||||
.setValue(this.modelId)
|
||||
.onChange((value) => {
|
||||
this.modelId = value.trim();
|
||||
}),
|
||||
);
|
||||
|
||||
new Setting(contentEl)
|
||||
.setName(t("AI_MODEL_CONFIG_MODAL_PROVIDER_NAME"))
|
||||
.setDesc(t("AI_MODEL_CONFIG_MODAL_PROVIDER_DESC"))
|
||||
.addDropdown((dropdown) => {
|
||||
this.options.providerIds.forEach((providerId) =>
|
||||
dropdown.addOption(providerId, providerId),
|
||||
);
|
||||
return dropdown.setValue(this.config.providerId).onChange((value) => {
|
||||
this.config.providerId = value;
|
||||
});
|
||||
});
|
||||
|
||||
new Setting(contentEl)
|
||||
.setName(t("AI_MODEL_CONFIG_MODAL_MODEL_NAME"))
|
||||
.setDesc(t("AI_MODEL_CONFIG_MODAL_MODEL_DESC"))
|
||||
.addText((text) =>
|
||||
text
|
||||
.setPlaceholder(t("AI_MODEL_CONFIG_MODAL_MODEL_PLACEHOLDER"))
|
||||
.setValue(this.config.model)
|
||||
.onChange((value) => {
|
||||
this.config.model = value.trim();
|
||||
}),
|
||||
);
|
||||
|
||||
if (this.options.kind !== "image") {
|
||||
new Setting(contentEl)
|
||||
.setName(t("AI_MODEL_CONFIG_MODAL_ENDPOINT_NAME"))
|
||||
.setDesc(t("AI_MODEL_CONFIG_MODAL_ENDPOINT_DESC"))
|
||||
.addText((text) =>
|
||||
text
|
||||
.setPlaceholder(t("AI_MODEL_CONFIG_MODAL_ENDPOINT_PLACEHOLDER"))
|
||||
.setValue(this.config.endpoint ?? "")
|
||||
.onChange((value) => {
|
||||
this.config.endpoint = value.trim();
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
if (this.options.kind === "text") {
|
||||
new Setting(contentEl)
|
||||
.setName(t("AI_MODEL_CONFIG_MODAL_MULTIMODAL_NAME"))
|
||||
.setDesc(t("AI_MODEL_CONFIG_MODAL_MULTIMODAL_DESC"))
|
||||
.addToggle((toggle) =>
|
||||
toggle
|
||||
.setValue(this.config.multimodalSupport !== false)
|
||||
.onChange((value) => {
|
||||
this.config.multimodalSupport = value;
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
if (this.options.kind === "image") {
|
||||
const imageConfig = this.config as AIImageModelConfig;
|
||||
contentEl.createEl("h3", {
|
||||
text: t("AI_IMAGE_MODEL_CAPABILITIES_SIZES_NAME"),
|
||||
});
|
||||
contentEl.createEl("p", {
|
||||
text: t("AI_IMAGE_MODEL_CAPABILITIES_MODAL_SIZES_DESC"),
|
||||
});
|
||||
const sizesContainer = contentEl.createDiv();
|
||||
const renderSizes = () => {
|
||||
sizesContainer.empty();
|
||||
imageConfig.supportedSizes.forEach((size, index) => {
|
||||
new Setting(sizesContainer)
|
||||
.setName(
|
||||
`${t("AI_IMAGE_MODEL_CAPABILITIES_MODAL_SIZE_LABEL")} ${index + 1}`,
|
||||
)
|
||||
.addText((text) =>
|
||||
text
|
||||
.setPlaceholder(
|
||||
t("AI_IMAGE_MODEL_CAPABILITIES_SIZES_PLACEHOLDER"),
|
||||
)
|
||||
.setValue(size)
|
||||
.onChange((value) => {
|
||||
imageConfig.supportedSizes[index] = value.trim();
|
||||
}),
|
||||
)
|
||||
.addButton((button) =>
|
||||
button
|
||||
.setButtonText(
|
||||
t("AI_IMAGE_MODEL_CAPABILITIES_MODAL_REMOVE_SIZE"),
|
||||
)
|
||||
.setDisabled(imageConfig.supportedSizes.length <= 1)
|
||||
.onClick(() => {
|
||||
imageConfig.supportedSizes.splice(index, 1);
|
||||
renderSizes();
|
||||
}),
|
||||
);
|
||||
});
|
||||
};
|
||||
renderSizes();
|
||||
|
||||
new Setting(contentEl).addButton((button) =>
|
||||
button
|
||||
.setButtonText(t("AI_IMAGE_MODEL_CAPABILITIES_MODAL_ADD_SIZE"))
|
||||
.onClick(() => {
|
||||
imageConfig.supportedSizes.push("1024x1024");
|
||||
renderSizes();
|
||||
}),
|
||||
);
|
||||
|
||||
new Setting(contentEl)
|
||||
.setName(t("AI_IMAGE_MODEL_CAPABILITIES_TRANSFORMS_NAME"))
|
||||
.setDesc(t("AI_IMAGE_MODEL_CAPABILITIES_TRANSFORMS_DESC"))
|
||||
.addToggle((toggle) =>
|
||||
toggle
|
||||
.setValue(imageConfig.supportsPromptImageTransforms)
|
||||
.onChange((value) => {
|
||||
imageConfig.supportsPromptImageTransforms = value;
|
||||
}),
|
||||
);
|
||||
|
||||
new Setting(contentEl)
|
||||
.setName(t("AI_IMAGE_MODEL_CAPABILITIES_MASK_EDITS_NAME"))
|
||||
.setDesc(t("AI_IMAGE_MODEL_CAPABILITIES_MASK_EDITS_DESC"))
|
||||
.addToggle((toggle) =>
|
||||
toggle
|
||||
.setValue(imageConfig.supportsMaskImageEdits)
|
||||
.onChange((value) => {
|
||||
imageConfig.supportsMaskImageEdits = value;
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
new Setting(contentEl)
|
||||
.addButton((button) =>
|
||||
button
|
||||
.setButtonText(t("PROMPT_BUTTON_CANCEL"))
|
||||
.onClick(() => this.close()),
|
||||
)
|
||||
.addButton((button) =>
|
||||
button
|
||||
.setButtonText(t("PROMPT_BUTTON_OK"))
|
||||
.setCta()
|
||||
.onClick(() => void this.save()),
|
||||
);
|
||||
|
||||
this.onKeyDown = (ev: KeyboardEvent) => {
|
||||
if (ev.key === "Escape") {
|
||||
ev.preventDefault();
|
||||
ev.stopImmediatePropagation();
|
||||
return;
|
||||
}
|
||||
if (isWinCTRLorMacCMD(ev) && ev.key === "Enter") {
|
||||
ev.preventDefault();
|
||||
ev.stopImmediatePropagation();
|
||||
void this.save();
|
||||
}
|
||||
};
|
||||
|
||||
const ownerDoc = this.containerEl.ownerDocument;
|
||||
if (ownerDoc) {
|
||||
this.listenerHost = ownerDoc;
|
||||
ownerDoc.addEventListener("keydown", this.onKeyDown, true);
|
||||
}
|
||||
}
|
||||
|
||||
private async save() {
|
||||
const normalizedModelId = this.modelId.trim();
|
||||
if (!normalizedModelId) {
|
||||
new Notice(t("AI_MODEL_CONFIG_MODAL_NAME_REQUIRED"));
|
||||
return;
|
||||
}
|
||||
if (!this.config.providerId) {
|
||||
new Notice(t("AI_MODEL_CONFIG_MODAL_PROVIDER_REQUIRED"));
|
||||
return;
|
||||
}
|
||||
if (!this.config.model.trim()) {
|
||||
new Notice(t("AI_MODEL_CONFIG_MODAL_MODEL_REQUIRED"));
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.options.kind === "image") {
|
||||
const imageConfig = this.config as AIImageModelConfig;
|
||||
imageConfig.supportedSizes = Array.from(
|
||||
new Set(
|
||||
imageConfig.supportedSizes.map((size) => size.trim()).filter(Boolean),
|
||||
),
|
||||
);
|
||||
if (imageConfig.supportedSizes.length === 0) {
|
||||
new Notice(t("AI_IMAGE_MODEL_CAPABILITIES_MODAL_SIZE_REQUIRED"));
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
const duplicateExists =
|
||||
this.existingModelIds.includes(normalizedModelId) &&
|
||||
normalizedModelId !== this.options.previousModelId;
|
||||
if (duplicateExists) {
|
||||
new Notice(t("AI_MODEL_CONFIG_MODAL_DUPLICATE_NAME"));
|
||||
return;
|
||||
}
|
||||
|
||||
await this.onSave(
|
||||
normalizedModelId,
|
||||
{
|
||||
...this.config,
|
||||
model: this.config.model.trim(),
|
||||
endpoint: this.config.endpoint?.trim() || "",
|
||||
} as TConfig,
|
||||
this.options.previousModelId,
|
||||
);
|
||||
this.close();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,232 @@
|
||||
import { App, Modal, Notice, Setting, TextComponent } from "obsidian";
|
||||
import { t } from "src/lang/helpers";
|
||||
import { AIProvider, AIProviderProfile } from "src/types/AIUtilTypes";
|
||||
import { isWinCTRLorMacCMD } from "src/utils/modifierkeyHelper";
|
||||
|
||||
type SaveHandler = (
|
||||
profileId: string,
|
||||
profile: AIProviderProfile,
|
||||
previousProfileId?: string,
|
||||
) => Promise<void> | void;
|
||||
|
||||
const configurePasswordTextInput = (text: TextComponent) => {
|
||||
const { inputEl } = text;
|
||||
inputEl.type = "password";
|
||||
inputEl.autocomplete = "off";
|
||||
inputEl.spellcheck = false;
|
||||
inputEl.addEventListener("focus", () => {
|
||||
inputEl.type = "text";
|
||||
});
|
||||
inputEl.addEventListener("blur", () => {
|
||||
inputEl.type = "password";
|
||||
});
|
||||
};
|
||||
|
||||
export class AIProviderProfileModal extends Modal {
|
||||
private profileId: string;
|
||||
private profile: AIProviderProfile;
|
||||
private onKeyDown: (ev: KeyboardEvent) => void;
|
||||
private listenerHost: Document | null = null;
|
||||
private backdropInteractionHandler: ((ev: Event) => void) | null = null;
|
||||
|
||||
constructor(
|
||||
app: App,
|
||||
private readonly existingProfileIds: string[],
|
||||
private readonly onSave: SaveHandler,
|
||||
private readonly options: {
|
||||
previousProfileId?: string;
|
||||
initialProfileId?: string;
|
||||
initialProfile?: AIProviderProfile;
|
||||
} = {},
|
||||
) {
|
||||
super(app);
|
||||
this.profileId = options.initialProfileId ?? "";
|
||||
this.profile = {
|
||||
provider: options.initialProfile?.provider ?? "openai",
|
||||
apiKey: options.initialProfile?.apiKey ?? "",
|
||||
baseURL: options.initialProfile?.baseURL ?? "",
|
||||
};
|
||||
}
|
||||
|
||||
onOpen(): void {
|
||||
this.backdropInteractionHandler = (ev: Event) => {
|
||||
if (ev.target === this.containerEl) {
|
||||
ev.preventDefault();
|
||||
ev.stopImmediatePropagation();
|
||||
}
|
||||
};
|
||||
this.containerEl.addEventListener(
|
||||
"mousedown",
|
||||
this.backdropInteractionHandler,
|
||||
true,
|
||||
);
|
||||
this.containerEl.addEventListener(
|
||||
"click",
|
||||
this.backdropInteractionHandler,
|
||||
true,
|
||||
);
|
||||
this.createForm();
|
||||
}
|
||||
|
||||
onClose() {
|
||||
if (this.backdropInteractionHandler) {
|
||||
this.containerEl.removeEventListener(
|
||||
"mousedown",
|
||||
this.backdropInteractionHandler,
|
||||
true,
|
||||
);
|
||||
this.containerEl.removeEventListener(
|
||||
"click",
|
||||
this.backdropInteractionHandler,
|
||||
true,
|
||||
);
|
||||
this.backdropInteractionHandler = null;
|
||||
}
|
||||
if (this.listenerHost && this.onKeyDown) {
|
||||
this.listenerHost.removeEventListener("keydown", this.onKeyDown, true);
|
||||
this.listenerHost = null;
|
||||
}
|
||||
this.contentEl.empty();
|
||||
}
|
||||
|
||||
private createForm() {
|
||||
const contentEl = this.contentEl;
|
||||
contentEl.empty();
|
||||
contentEl.createEl("h1", {
|
||||
text: this.options.previousProfileId
|
||||
? t("AI_PROVIDER_PROFILE_MODAL_EDIT_TITLE")
|
||||
: t("AI_PROVIDER_PROFILE_MODAL_ADD_TITLE"),
|
||||
});
|
||||
|
||||
new Setting(contentEl)
|
||||
.setName(t("AI_PROVIDER_PROFILE_MODAL_NAME_NAME"))
|
||||
.setDesc(t("AI_PROVIDER_PROFILE_MODAL_NAME_DESC"))
|
||||
.addText((text) =>
|
||||
text
|
||||
.setPlaceholder(t("AI_PROVIDER_PROFILE_MODAL_NAME_PLACEHOLDER"))
|
||||
.setValue(this.profileId)
|
||||
.onChange((value) => {
|
||||
this.profileId = value.trim();
|
||||
}),
|
||||
);
|
||||
|
||||
new Setting(contentEl)
|
||||
.setName(t("AI_PROVIDER_PROFILE_MODAL_TYPE_NAME"))
|
||||
.setDesc(t("AI_PROVIDER_PROFILE_MODAL_TYPE_DESC"))
|
||||
.addDropdown((dropdown) =>
|
||||
dropdown
|
||||
.addOption("openai", t("AI_PROVIDER_OPTION_OPENAI"))
|
||||
.addOption("anthropic", t("AI_PROVIDER_OPTION_ANTHROPIC"))
|
||||
.addOption("google", t("AI_PROVIDER_OPTION_GOOGLE"))
|
||||
.addOption("xai", t("AI_PROVIDER_OPTION_XAI"))
|
||||
.addOption(
|
||||
"openai-compatible",
|
||||
t("AI_PROVIDER_OPTION_OPENAI_COMPATIBLE"),
|
||||
)
|
||||
.setValue(this.profile.provider)
|
||||
.onChange((value) => {
|
||||
this.profile.provider = value as AIProvider;
|
||||
updateProviderTypeHint();
|
||||
}),
|
||||
);
|
||||
|
||||
const providerTypeHintEl = contentEl.createDiv({
|
||||
cls: "setting-item-description",
|
||||
});
|
||||
const updateProviderTypeHint = () => {
|
||||
if (this.profile.provider === "openai-compatible") {
|
||||
providerTypeHintEl.setText(
|
||||
t("AI_PROVIDER_PROFILE_MODAL_OPENAI_COMPATIBLE_HINT"),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
providerTypeHintEl.empty();
|
||||
};
|
||||
updateProviderTypeHint();
|
||||
|
||||
new Setting(contentEl)
|
||||
.setName(t("AI_PROVIDER_PROFILE_MODAL_API_KEY_NAME"))
|
||||
.setDesc(t("AI_PROVIDER_PROFILE_MODAL_API_KEY_DESC"))
|
||||
.addText((text) => {
|
||||
configurePasswordTextInput(text);
|
||||
return text
|
||||
.setPlaceholder(t("AI_PROVIDER_PROFILE_MODAL_API_KEY_PLACEHOLDER"))
|
||||
.setValue(this.profile.apiKey)
|
||||
.onChange((value) => {
|
||||
this.profile.apiKey = value;
|
||||
});
|
||||
});
|
||||
|
||||
new Setting(contentEl)
|
||||
.setName(t("AI_PROVIDER_PROFILE_MODAL_BASE_URL_NAME"))
|
||||
.setDesc(t("AI_PROVIDER_PROFILE_MODAL_BASE_URL_DESC"))
|
||||
.addText((text) =>
|
||||
text
|
||||
.setPlaceholder(t("AI_PROVIDER_PROFILE_MODAL_BASE_URL_PLACEHOLDER"))
|
||||
.setValue(this.profile.baseURL)
|
||||
.onChange((value) => {
|
||||
this.profile.baseURL = value.trim();
|
||||
}),
|
||||
);
|
||||
|
||||
new Setting(contentEl)
|
||||
.addButton((button) =>
|
||||
button
|
||||
.setButtonText(t("PROMPT_BUTTON_CANCEL"))
|
||||
.onClick(() => this.close()),
|
||||
)
|
||||
.addButton((button) =>
|
||||
button
|
||||
.setButtonText(t("PROMPT_BUTTON_OK"))
|
||||
.setCta()
|
||||
.onClick(() => void this.save()),
|
||||
);
|
||||
|
||||
this.onKeyDown = (ev: KeyboardEvent) => {
|
||||
if (ev.key === "Escape") {
|
||||
ev.preventDefault();
|
||||
ev.stopImmediatePropagation();
|
||||
return;
|
||||
}
|
||||
if (isWinCTRLorMacCMD(ev) && ev.key === "Enter") {
|
||||
ev.preventDefault();
|
||||
ev.stopImmediatePropagation();
|
||||
void this.save();
|
||||
}
|
||||
};
|
||||
|
||||
const ownerDoc = this.containerEl.ownerDocument;
|
||||
if (ownerDoc) {
|
||||
this.listenerHost = ownerDoc;
|
||||
ownerDoc.addEventListener("keydown", this.onKeyDown, true);
|
||||
}
|
||||
}
|
||||
|
||||
private async save() {
|
||||
const normalizedProfileId = this.profileId.trim();
|
||||
if (!normalizedProfileId) {
|
||||
new Notice(t("AI_PROVIDER_PROFILE_MODAL_NAME_REQUIRED"));
|
||||
return;
|
||||
}
|
||||
|
||||
const duplicateExists =
|
||||
this.existingProfileIds.includes(normalizedProfileId) &&
|
||||
normalizedProfileId !== this.options.previousProfileId;
|
||||
if (duplicateExists) {
|
||||
new Notice(t("AI_PROVIDER_PROFILE_MODAL_DUPLICATE_NAME"));
|
||||
return;
|
||||
}
|
||||
|
||||
await this.onSave(
|
||||
normalizedProfileId,
|
||||
{
|
||||
provider: this.profile.provider,
|
||||
apiKey: this.profile.apiKey,
|
||||
baseURL: this.profile.baseURL,
|
||||
},
|
||||
this.options.previousProfileId,
|
||||
);
|
||||
this.close();
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
import ExcalidrawView from "src/view/ExcalidrawView";
|
||||
import { getViewColorPalette } from "src/utils/excalidrawViewUtils";
|
||||
|
||||
type PaletteName = "canvasBackground"|"elementBackground"|"elementStroke";
|
||||
type PaletteName = "canvasBackground" | "elementBackground" | "elementStroke";
|
||||
|
||||
const GRID_COLUMNS = 5;
|
||||
const CELL_SIZE = 32;
|
||||
@@ -9,119 +9,124 @@ 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[] = [];
|
||||
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);
|
||||
}
|
||||
});
|
||||
raw.forEach((entry: string[] | string) => {
|
||||
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;
|
||||
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;
|
||||
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;
|
||||
let left = rect.left;
|
||||
let top = rect.bottom + 8;
|
||||
|
||||
if (left + popupWidth > innerWidth - 8) {
|
||||
left = Math.max(8, innerWidth - popupWidth - 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);
|
||||
}
|
||||
if (top + popupHeight > innerHeight - 8) {
|
||||
top = Math.max(8, rect.top - popupHeight - 8);
|
||||
}
|
||||
|
||||
popup.style.left = `${left}px`;
|
||||
popup.style.top = `${top}px`;
|
||||
popup.style.left = `${left}px`;
|
||||
popup.style.top = `${top}px`;
|
||||
};
|
||||
|
||||
const attachOutsideHandlers = (
|
||||
overlay: HTMLElement,
|
||||
popup: HTMLElement,
|
||||
resolve: (color: string | null) => void,
|
||||
overlay: HTMLElement,
|
||||
popup: HTMLElement,
|
||||
resolve: (color: string | null) => void,
|
||||
) => {
|
||||
const stopPropagation = (evt: Event) => evt.stopPropagation();
|
||||
let cleanup: (color: string | null) => void;
|
||||
const stopPropagation = (evt: Event) => evt.stopPropagation();
|
||||
|
||||
const onKeyDown = (evt: KeyboardEvent) => {
|
||||
if (evt.key === "Escape") {
|
||||
evt.stopPropagation();
|
||||
cleanup(null);
|
||||
}
|
||||
};
|
||||
const onKeyDown = (evt: KeyboardEvent) => {
|
||||
if (evt.key === "Escape") {
|
||||
evt.stopPropagation();
|
||||
cleanup(null);
|
||||
}
|
||||
};
|
||||
|
||||
const onOverlayClick = () => 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);
|
||||
};
|
||||
const 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);
|
||||
document.addEventListener("keydown", onKeyDown, true);
|
||||
overlay.addEventListener("click", onOverlayClick);
|
||||
popup.addEventListener("click", stopPropagation);
|
||||
|
||||
return cleanup;
|
||||
return cleanup;
|
||||
};
|
||||
|
||||
export const showColorPicker = async (
|
||||
palette: PaletteName,
|
||||
anchorElement: HTMLElement,
|
||||
view?: ExcalidrawView,
|
||||
includeSceneColors: boolean = false,
|
||||
palette: PaletteName,
|
||||
anchorElement: HTMLElement,
|
||||
view?: ExcalidrawView,
|
||||
includeSceneColors: boolean = false,
|
||||
): Promise<string | null> => {
|
||||
const colors = getColors(palette, view, includeSceneColors);
|
||||
const colors = getColors(palette, view, includeSceneColors);
|
||||
|
||||
if (!colors.length) {
|
||||
return null;
|
||||
}
|
||||
if (!colors.length) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return new Promise((resolve) => {
|
||||
const overlay = document.createElement("div");
|
||||
overlay.classList.add("excalidraw-colorpicker-overlay");
|
||||
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 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`;
|
||||
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);
|
||||
});
|
||||
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);
|
||||
popup.appendChild(grid);
|
||||
overlay.appendChild(popup);
|
||||
document.body.appendChild(overlay);
|
||||
|
||||
positionPopup(popup, anchorElement);
|
||||
positionPopup(popup, anchorElement);
|
||||
|
||||
const cleanup = attachOutsideHandlers(overlay, popup, resolve);
|
||||
});
|
||||
const cleanup = attachOutsideHandlers(overlay, popup, resolve);
|
||||
});
|
||||
};
|
||||
@@ -4,186 +4,192 @@ import { fragWithHTML } from "src/utils/utils";
|
||||
import { t } from "src/lang/helpers";
|
||||
|
||||
export class EmbeddalbeMDFileCustomDataSettingsComponent {
|
||||
constructor (
|
||||
constructor(
|
||||
private contentEl: HTMLElement,
|
||||
private mdCustomData: EmbeddableMDCustomProps,
|
||||
private update?: Function,
|
||||
private update?: () => void,
|
||||
private isMDFile: boolean = true,
|
||||
) {
|
||||
if(!update) this.update = () => {};
|
||||
) {
|
||||
if (!update) {
|
||||
this.update = () => {};
|
||||
}
|
||||
}
|
||||
|
||||
render() {
|
||||
let detailsDIV: HTMLDivElement;
|
||||
|
||||
new Setting(this.contentEl)
|
||||
.setName(t("ES_USE_OBSIDIAN_DEFAULTS"))
|
||||
.addToggle(toggle =>
|
||||
.addToggle((toggle) =>
|
||||
toggle
|
||||
.setValue(this.mdCustomData.useObsidianDefaults)
|
||||
.onChange(value => {
|
||||
.onChange((value) => {
|
||||
this.mdCustomData.useObsidianDefaults = value;
|
||||
detailsDIV.style.display = value ? "none" : "block";
|
||||
this.update();
|
||||
})
|
||||
}),
|
||||
);
|
||||
|
||||
|
||||
this.contentEl.createEl("hr", { cls: "excalidraw-setting-hr" });
|
||||
|
||||
detailsDIV = this.contentEl.createDiv();
|
||||
detailsDIV.style.display = this.mdCustomData.useObsidianDefaults ? "none" : "block";
|
||||
|
||||
const contentEl = detailsDIV
|
||||
if(this.isMDFile) {
|
||||
new Setting(contentEl)
|
||||
.setName(t("ES_FILENAME_VISIBLE"))
|
||||
.addToggle(toggle =>
|
||||
toggle
|
||||
.setValue(this.mdCustomData.filenameVisible)
|
||||
.onChange(value => {
|
||||
this.mdCustomData.filenameVisible = value;
|
||||
})
|
||||
);
|
||||
}
|
||||
contentEl.createEl("h4",{text: t("ES_BACKGROUND_HEAD")});
|
||||
const descDiv = contentEl.createDiv({ cls: "excalidraw-setting-desc" });
|
||||
descDiv.textContent = t("ES_BACKGROUND_DESC_INFO");
|
||||
const detailsDIV = this.contentEl.createDiv();
|
||||
detailsDIV.style.display = this.mdCustomData.useObsidianDefaults
|
||||
? "none"
|
||||
: "block";
|
||||
|
||||
descDiv.addEventListener("click", () => {
|
||||
if (descDiv.textContent === t("ES_BACKGROUND_DESC_INFO")) {
|
||||
descDiv.textContent = t("ES_BACKGROUND_DESC_DETAIL");
|
||||
} else {
|
||||
descDiv.textContent = t("ES_BACKGROUND_DESC_INFO");
|
||||
}
|
||||
});
|
||||
|
||||
let bgSetting: Setting;
|
||||
let bgMatchElementToggle: ToggleComponent;
|
||||
let bgMatchCanvasToggle: ToggleComponent;
|
||||
const contentEl = detailsDIV;
|
||||
if (this.isMDFile) {
|
||||
new Setting(contentEl)
|
||||
.setName(t("ES_BACKGROUND_MATCH_ELEMENT"))
|
||||
.addToggle(toggle => {
|
||||
bgMatchElementToggle = toggle;
|
||||
.setName(t("ES_FILENAME_VISIBLE"))
|
||||
.addToggle((toggle) =>
|
||||
toggle
|
||||
.setValue(this.mdCustomData.backgroundMatchElement)
|
||||
.onChange(value => {
|
||||
this.mdCustomData.backgroundMatchElement = value;
|
||||
if(value) {
|
||||
bgSetting.settingEl.style.display = "none";
|
||||
if(this.mdCustomData.backgroundMatchCanvas) {
|
||||
bgMatchCanvasToggle.setValue(false);
|
||||
}
|
||||
} else {
|
||||
if(!this.mdCustomData.backgroundMatchCanvas) {
|
||||
bgSetting.settingEl.style.display = "";
|
||||
}
|
||||
}
|
||||
this.update();
|
||||
})
|
||||
});
|
||||
|
||||
new Setting(contentEl)
|
||||
.setName(t("ES_BACKGROUND_MATCH_CANVAS"))
|
||||
.addToggle(toggle => {
|
||||
bgMatchCanvasToggle = toggle;
|
||||
toggle
|
||||
.setValue(this.mdCustomData.backgroundMatchCanvas)
|
||||
.onChange(value => {
|
||||
this.mdCustomData.backgroundMatchCanvas = value;
|
||||
if(value) {
|
||||
bgSetting.settingEl.style.display = "none";
|
||||
if(this.mdCustomData.backgroundMatchElement) {
|
||||
bgMatchElementToggle.setValue(false);
|
||||
}
|
||||
} else {
|
||||
if(!this.mdCustomData.backgroundMatchElement) {
|
||||
bgSetting.settingEl.style.display = "";
|
||||
}
|
||||
}
|
||||
this.update();
|
||||
})
|
||||
});
|
||||
|
||||
if(this.mdCustomData.backgroundMatchElement && this.mdCustomData.backgroundMatchCanvas) {
|
||||
bgMatchCanvasToggle.setValue(false);
|
||||
}
|
||||
|
||||
bgSetting = new Setting(contentEl)
|
||||
.setName(t("ES_BACKGROUND_COLOR"))
|
||||
.addColorPicker(colorPicker =>
|
||||
colorPicker
|
||||
.setValue(this.mdCustomData.backgroundColor)
|
||||
.setValue(this.mdCustomData.filenameVisible)
|
||||
.onChange((value) => {
|
||||
this.mdCustomData.backgroundColor = value;
|
||||
this.update();
|
||||
})
|
||||
this.mdCustomData.filenameVisible = value;
|
||||
}),
|
||||
);
|
||||
|
||||
bgSetting.settingEl.style.display = (this.mdCustomData.backgroundMatchElement || this.mdCustomData.backgroundMatchCanvas) ? "none" : "";
|
||||
const opacity = (value:number):DocumentFragment => {
|
||||
return fragWithHTML(`Current opacity is <b>${value}%</b>`);
|
||||
}
|
||||
}
|
||||
contentEl.createEl("h4", { text: t("ES_BACKGROUND_HEAD") });
|
||||
const descDiv = contentEl.createDiv({ cls: "excalidraw-setting-desc" });
|
||||
descDiv.textContent = t("ES_BACKGROUND_DESC_INFO");
|
||||
|
||||
const bgOpacitySetting = new Setting(contentEl)
|
||||
.setName(t("ES_BACKGROUND_OPACITY"))
|
||||
.setDesc(opacity(this.mdCustomData.backgroundOpacity))
|
||||
.addSlider(slider =>
|
||||
descDiv.addEventListener("click", () => {
|
||||
if (descDiv.textContent === t("ES_BACKGROUND_DESC_INFO")) {
|
||||
descDiv.textContent = t("ES_BACKGROUND_DESC_DETAIL");
|
||||
} else {
|
||||
descDiv.textContent = t("ES_BACKGROUND_DESC_INFO");
|
||||
}
|
||||
});
|
||||
|
||||
let bgMatchElementToggle: ToggleComponent;
|
||||
let bgMatchCanvasToggle: ToggleComponent;
|
||||
new Setting(contentEl)
|
||||
.setName(t("ES_BACKGROUND_MATCH_ELEMENT"))
|
||||
.addToggle((toggle) => {
|
||||
bgMatchElementToggle = toggle;
|
||||
toggle
|
||||
.setValue(this.mdCustomData.backgroundMatchElement)
|
||||
.onChange((value) => {
|
||||
this.mdCustomData.backgroundMatchElement = value;
|
||||
if (value) {
|
||||
bgSetting.settingEl.style.display = "none";
|
||||
if (this.mdCustomData.backgroundMatchCanvas) {
|
||||
bgMatchCanvasToggle.setValue(false);
|
||||
}
|
||||
} else if (!this.mdCustomData.backgroundMatchCanvas) {
|
||||
bgSetting.settingEl.style.display = "";
|
||||
}
|
||||
this.update();
|
||||
});
|
||||
});
|
||||
|
||||
new Setting(contentEl)
|
||||
.setName(t("ES_BACKGROUND_MATCH_CANVAS"))
|
||||
.addToggle((toggle) => {
|
||||
bgMatchCanvasToggle = toggle;
|
||||
toggle
|
||||
.setValue(this.mdCustomData.backgroundMatchCanvas)
|
||||
.onChange((value) => {
|
||||
this.mdCustomData.backgroundMatchCanvas = value;
|
||||
if (value) {
|
||||
bgSetting.settingEl.style.display = "none";
|
||||
if (this.mdCustomData.backgroundMatchElement) {
|
||||
bgMatchElementToggle.setValue(false);
|
||||
}
|
||||
} else if (!this.mdCustomData.backgroundMatchElement) {
|
||||
bgSetting.settingEl.style.display = "";
|
||||
}
|
||||
this.update();
|
||||
});
|
||||
});
|
||||
|
||||
if (
|
||||
this.mdCustomData.backgroundMatchElement &&
|
||||
this.mdCustomData.backgroundMatchCanvas
|
||||
) {
|
||||
bgMatchCanvasToggle.setValue(false);
|
||||
}
|
||||
|
||||
const bgSetting = new Setting(contentEl)
|
||||
.setName(t("ES_BACKGROUND_COLOR"))
|
||||
.addColorPicker((colorPicker) =>
|
||||
colorPicker
|
||||
.setValue(this.mdCustomData.backgroundColor)
|
||||
.onChange((value) => {
|
||||
this.mdCustomData.backgroundColor = value;
|
||||
this.update();
|
||||
}),
|
||||
);
|
||||
|
||||
bgSetting.settingEl.style.display =
|
||||
this.mdCustomData.backgroundMatchElement ||
|
||||
this.mdCustomData.backgroundMatchCanvas
|
||||
? "none"
|
||||
: "";
|
||||
const opacity = (value: number): DocumentFragment => {
|
||||
return fragWithHTML(`Current opacity is <b>${value}%</b>`);
|
||||
};
|
||||
|
||||
const bgOpacitySetting = new Setting(contentEl)
|
||||
.setName(t("ES_BACKGROUND_OPACITY"))
|
||||
.setDesc(opacity(this.mdCustomData.backgroundOpacity))
|
||||
.addSlider((slider) =>
|
||||
slider
|
||||
.setLimits(0, 100, 5)
|
||||
.setValue(this.mdCustomData.backgroundOpacity)
|
||||
.onChange((value) => {
|
||||
this.mdCustomData.backgroundOpacity = value;
|
||||
bgOpacitySetting.setDesc(opacity(value));
|
||||
this.update();
|
||||
}),
|
||||
);
|
||||
|
||||
if (this.isMDFile) {
|
||||
contentEl.createEl("h4", { text: t("ES_BORDER_HEAD") });
|
||||
|
||||
new Setting(contentEl)
|
||||
.setName(t("ES_BORDER_MATCH_ELEMENT"))
|
||||
.addToggle((toggle) =>
|
||||
toggle
|
||||
.setValue(this.mdCustomData.borderMatchElement)
|
||||
.onChange((value) => {
|
||||
this.mdCustomData.borderMatchElement = value;
|
||||
if (value) {
|
||||
borderSetting.settingEl.style.display = "none";
|
||||
} else {
|
||||
borderSetting.settingEl.style.display = "";
|
||||
}
|
||||
this.update();
|
||||
}),
|
||||
);
|
||||
|
||||
const borderSetting = new Setting(contentEl)
|
||||
.setName(t("ES_BORDER_COLOR"))
|
||||
.addColorPicker((colorPicker) =>
|
||||
colorPicker
|
||||
.setValue(this.mdCustomData.borderColor)
|
||||
.onChange((value) => {
|
||||
this.mdCustomData.borderColor = value;
|
||||
this.update();
|
||||
}),
|
||||
);
|
||||
|
||||
borderSetting.settingEl.style.display = this.mdCustomData
|
||||
.borderMatchElement
|
||||
? "none"
|
||||
: "";
|
||||
|
||||
const borderOpacitySetting = new Setting(contentEl)
|
||||
.setName(t("ES_BORDER_OPACITY"))
|
||||
.setDesc(opacity(this.mdCustomData.borderOpacity))
|
||||
.addSlider((slider) =>
|
||||
slider
|
||||
.setLimits(0,100,5)
|
||||
.setValue(this.mdCustomData.backgroundOpacity)
|
||||
.onChange(value => {
|
||||
this.mdCustomData.backgroundOpacity = value;
|
||||
bgOpacitySetting.setDesc(opacity(value));
|
||||
.setLimits(0, 100, 5)
|
||||
.setValue(this.mdCustomData.borderOpacity)
|
||||
.onChange((value) => {
|
||||
this.mdCustomData.borderOpacity = value;
|
||||
borderOpacitySetting.setDesc(opacity(value));
|
||||
this.update();
|
||||
})
|
||||
}),
|
||||
);
|
||||
|
||||
if(this.isMDFile) {
|
||||
contentEl.createEl("h4",{text: t("ES_BORDER_HEAD")});
|
||||
let borderSetting: Setting;
|
||||
|
||||
new Setting(contentEl)
|
||||
.setName(t("ES_BORDER_MATCH_ELEMENT"))
|
||||
.addToggle(toggle =>
|
||||
toggle
|
||||
.setValue(this.mdCustomData.borderMatchElement)
|
||||
.onChange(value => {
|
||||
this.mdCustomData.borderMatchElement = value;
|
||||
if(value) {
|
||||
borderSetting.settingEl.style.display = "none";
|
||||
} else {
|
||||
borderSetting.settingEl.style.display = "";
|
||||
}
|
||||
this.update();
|
||||
})
|
||||
);
|
||||
|
||||
borderSetting = new Setting(contentEl)
|
||||
.setName(t("ES_BORDER_COLOR"))
|
||||
.addColorPicker(colorPicker =>
|
||||
colorPicker
|
||||
.setValue(this.mdCustomData.borderColor)
|
||||
.onChange((value) => {
|
||||
this.mdCustomData.borderColor = value;
|
||||
this.update();
|
||||
})
|
||||
);
|
||||
|
||||
borderSetting.settingEl.style.display = this.mdCustomData.borderMatchElement ? "none" : "";
|
||||
|
||||
const borderOpacitySetting = new Setting(contentEl)
|
||||
.setName(t("ES_BORDER_OPACITY"))
|
||||
.setDesc(opacity(this.mdCustomData.borderOpacity))
|
||||
.addSlider(slider =>
|
||||
slider
|
||||
.setLimits(0,100,5)
|
||||
.setValue(this.mdCustomData.borderOpacity)
|
||||
.onChange(value => {
|
||||
this.mdCustomData.borderOpacity = value;
|
||||
borderOpacitySetting.setDesc(opacity(value));
|
||||
this.update();
|
||||
})
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,17 +1,25 @@
|
||||
import { ExcalidrawEmbeddableElement } from "@zsviczian/excalidraw/types/element/src/types";
|
||||
import { Mutable } from "@zsviczian/excalidraw/types/common/src/utility-types";
|
||||
import { Modal, Notice, Setting, TFile, ToggleComponent } from "obsidian";
|
||||
import { Modal, Notice, Setting, TFile } from "obsidian";
|
||||
import { getEA } from "src/core";
|
||||
import { ExcalidrawAutomate } from "src/shared/ExcalidrawAutomate";
|
||||
import ExcalidrawView from "src/view/ExcalidrawView";
|
||||
import { t } from "src/lang/helpers";
|
||||
import ExcalidrawPlugin from "src/core/main";
|
||||
import { getNewUniqueFilepath, getPathWithoutExtension, splitFolderAndFilename } from "src/utils/fileUtils";
|
||||
import {
|
||||
getNewUniqueFilepath,
|
||||
getPathWithoutExtension,
|
||||
splitFolderAndFilename,
|
||||
} from "src/utils/fileUtils";
|
||||
import { addAppendUpdateCustomData, fragWithHTML } from "src/utils/utils";
|
||||
import { getYouTubeStartAt, isValidYouTubeStart, isYouTube, updateYouTubeStartTime } from "src/utils/YoutTubeUtils";
|
||||
import {
|
||||
getYouTubeStartAt,
|
||||
isValidYouTubeStart,
|
||||
isYouTube,
|
||||
updateYouTubeStartTime,
|
||||
} from "src/utils/YoutTubeUtils";
|
||||
import { EmbeddalbeMDFileCustomDataSettingsComponent } from "./EmbeddableMDFileCustomDataSettingsComponent";
|
||||
import { isWinCTRLorMacCMD } from "src/utils/modifierkeyHelper";
|
||||
import { ExcalidrawImperativeAPI } from "@zsviczian/excalidraw/types/excalidraw/types";
|
||||
import { CaptureUpdateAction } from "src/constants/constants";
|
||||
|
||||
export type EmbeddableMDCustomProps = {
|
||||
@@ -24,7 +32,7 @@ export type EmbeddableMDCustomProps = {
|
||||
borderColor: string;
|
||||
borderOpacity: number;
|
||||
filenameVisible: boolean;
|
||||
}
|
||||
};
|
||||
|
||||
export class EmbeddableSettings extends Modal {
|
||||
private ea: ExcalidrawAutomate;
|
||||
@@ -43,25 +51,30 @@ export class EmbeddableSettings extends Modal {
|
||||
private plugin: ExcalidrawPlugin,
|
||||
private view: ExcalidrawView,
|
||||
private file: TFile,
|
||||
private element: ExcalidrawEmbeddableElement
|
||||
private element: ExcalidrawEmbeddableElement,
|
||||
) {
|
||||
super(plugin.app);
|
||||
this.ea = getEA(this.view);
|
||||
this.ea.copyViewElementsToEAforEditing([this.element]);
|
||||
this.zoomValue = element.scale[0];
|
||||
this.isYouTube = isYouTube(this.element.link);
|
||||
this.notExcalidrawIsInternal = this.file && !this.view.plugin.isExcalidrawFile(this.file)
|
||||
this.notExcalidrawIsInternal =
|
||||
this.file && !this.view.plugin.isExcalidrawFile(this.file);
|
||||
this.isMDFile = this.file && this.file.extension.toLowerCase() === "md"; // && !this.view.plugin.isExcalidrawFile(this.file);
|
||||
this.isLocalURI = this.element.link.startsWith("file://");
|
||||
if(isYouTube) this.youtubeStart = getYouTubeStartAt(this.element.link);
|
||||
if (isYouTube) {
|
||||
this.youtubeStart = getYouTubeStartAt(this.element.link);
|
||||
}
|
||||
|
||||
this.mdCustomData = element.customData?.mdProps ?? view.plugin.settings.embeddableMarkdownDefaults;
|
||||
if(!element.customData?.mdProps) {
|
||||
this.mdCustomData =
|
||||
element.customData?.mdProps ??
|
||||
view.plugin.settings.embeddableMarkdownDefaults;
|
||||
if (!element.customData?.mdProps) {
|
||||
const bgCM = this.plugin.ea.getCM(element.backgroundColor);
|
||||
this.mdCustomData.backgroundColor = bgCM.stringHEX({alpha: false});
|
||||
this.mdCustomData.backgroundColor = bgCM.stringHEX({ alpha: false });
|
||||
this.mdCustomData.backgroundOpacity = element.opacity;
|
||||
const borderCM = this.plugin.ea.getCM(element.strokeColor);
|
||||
this.mdCustomData.borderColor = borderCM.stringHEX({alpha: false});
|
||||
this.mdCustomData.borderColor = borderCM.stringHEX({ alpha: false });
|
||||
this.mdCustomData.borderOpacity = element.opacity;
|
||||
}
|
||||
}
|
||||
@@ -69,12 +82,12 @@ export class EmbeddableSettings extends Modal {
|
||||
onOpen(): void {
|
||||
this.containerEl.classList.add("excalidraw-release");
|
||||
//this.titleEl.setText(t("ES_TITLE"));
|
||||
this.createForm();
|
||||
void this.createForm();
|
||||
}
|
||||
|
||||
onClose() {
|
||||
if(this.listenerHost && this.onKeyDown) {
|
||||
this.listenerHost.removeEventListener("keydown",this.onKeyDown);
|
||||
if (this.listenerHost && this.onKeyDown) {
|
||||
this.listenerHost.removeEventListener("keydown", this.onKeyDown);
|
||||
this.listenerHost = null;
|
||||
}
|
||||
this.plugin = null;
|
||||
@@ -86,160 +99,178 @@ export class EmbeddableSettings extends Modal {
|
||||
this.mdCustomData = null;
|
||||
}
|
||||
|
||||
|
||||
async createForm() {
|
||||
this.contentEl.createEl("h1", { text: t("ES_TITLE") });
|
||||
|
||||
this.contentEl.createEl("h1",{text: t("ES_TITLE")});
|
||||
|
||||
if(this.file) {
|
||||
new Setting(this.contentEl)
|
||||
.setName(t("ES_RENAME"))
|
||||
.addText(text =>
|
||||
text
|
||||
if (this.file) {
|
||||
new Setting(this.contentEl).setName(t("ES_RENAME")).addText((text) =>
|
||||
text
|
||||
.setValue(getPathWithoutExtension(this.file))
|
||||
.onChange(async (value) => {
|
||||
this.updatedFilepath = value;
|
||||
})
|
||||
)
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
const zoomValue = ():DocumentFragment => {
|
||||
return fragWithHTML(`${t("ES_ZOOM_100_RELATIVE_DESC")}<br>Current zoom is <b>${Math.round(this.zoomValue*100)}%</b>`);
|
||||
}
|
||||
const zoomValue = (): DocumentFragment => {
|
||||
return fragWithHTML(
|
||||
`${t("ES_ZOOM_100_RELATIVE_DESC")}<br>Current zoom is <b>${Math.round(this.zoomValue * 100)}%</b>`,
|
||||
);
|
||||
};
|
||||
|
||||
const zoomSetting = new Setting(this.contentEl)
|
||||
.setName(t("ES_ZOOM"))
|
||||
.setDesc(zoomValue())
|
||||
.addButton(button =>
|
||||
button
|
||||
.setButtonText(t("ES_ZOOM_100"))
|
||||
.onClick(() => {
|
||||
const api = this.view.excalidrawAPI as ExcalidrawImperativeAPI;
|
||||
this.zoomValue = 1/api.getAppState().zoom.value;
|
||||
zoomSetting.setDesc(zoomValue());
|
||||
})
|
||||
.addButton((button) =>
|
||||
button.setButtonText(t("ES_ZOOM_100")).onClick(() => {
|
||||
const api = this.view.excalidrawAPI;
|
||||
this.zoomValue = 1 / api.getAppState().zoom.value;
|
||||
zoomSetting.setDesc(zoomValue());
|
||||
}),
|
||||
)
|
||||
.addSlider(slider =>
|
||||
.addSlider((slider) =>
|
||||
slider
|
||||
.setLimits(10,400,5)
|
||||
.setValue(this.zoomValue*100)
|
||||
.onChange(value => {
|
||||
this.zoomValue = value/100;
|
||||
.setLimits(10, 400, 5)
|
||||
.setValue(this.zoomValue * 100)
|
||||
.onChange((value) => {
|
||||
this.zoomValue = value / 100;
|
||||
zoomSetting.setDesc(zoomValue());
|
||||
})
|
||||
)
|
||||
}),
|
||||
);
|
||||
|
||||
if(this.isYouTube) {
|
||||
if (this.isYouTube) {
|
||||
new Setting(this.contentEl)
|
||||
.setName(t("ES_YOUTUBE_START"))
|
||||
.setDesc(t("ES_YOUTUBE_START_DESC"))
|
||||
.addText(text =>
|
||||
text
|
||||
.setValue(this.youtubeStart)
|
||||
.onChange(async (value) => {
|
||||
.addText((text) =>
|
||||
text.setValue(this.youtubeStart).onChange(async (value) => {
|
||||
this.youtubeStart = value;
|
||||
})
|
||||
)
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
if(this.isMDFile || this.notExcalidrawIsInternal) {
|
||||
this.contentEl.createEl("h3",{text: t("ES_EMBEDDABLE_SETTINGS")});
|
||||
new EmbeddalbeMDFileCustomDataSettingsComponent(this.contentEl,this.mdCustomData, undefined, this.isMDFile).render();
|
||||
if (this.isMDFile || this.notExcalidrawIsInternal) {
|
||||
this.contentEl.createEl("h3", { text: t("ES_EMBEDDABLE_SETTINGS") });
|
||||
new EmbeddalbeMDFileCustomDataSettingsComponent(
|
||||
this.contentEl,
|
||||
this.mdCustomData,
|
||||
undefined,
|
||||
this.isMDFile,
|
||||
).render();
|
||||
}
|
||||
|
||||
|
||||
new Setting(this.contentEl)
|
||||
.addButton(button =>
|
||||
button
|
||||
.setButtonText(t("PROMPT_BUTTON_CANCEL"))
|
||||
.setTooltip("ESC")
|
||||
.onClick(this.close.bind(this))
|
||||
)
|
||||
.addButton(button =>
|
||||
button
|
||||
.setButtonText(t("PROMPT_BUTTON_OK"))
|
||||
.setTooltip("CTRL/Opt+Enter")
|
||||
.setCta()
|
||||
.onClick(this.applySettings.bind(this))
|
||||
)
|
||||
|
||||
.addButton((button) =>
|
||||
button
|
||||
.setButtonText(t("PROMPT_BUTTON_CANCEL"))
|
||||
.setTooltip("ESC")
|
||||
.onClick(this.close.bind(this)),
|
||||
)
|
||||
.addButton((button) =>
|
||||
button
|
||||
.setButtonText(t("PROMPT_BUTTON_OK"))
|
||||
.setTooltip("CTRL/Opt+Enter")
|
||||
.setCta()
|
||||
.onClick(this.applySettings.bind(this)),
|
||||
);
|
||||
|
||||
const onKeyDown = (ev: KeyboardEvent) => {
|
||||
if(isWinCTRLorMacCMD(ev) && ev.key === "Enter") {
|
||||
this.applySettings();
|
||||
if (isWinCTRLorMacCMD(ev) && ev.key === "Enter") {
|
||||
void this.applySettings();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
this.onKeyDown = onKeyDown;
|
||||
const ownerDoc = this.containerEl.ownerDocument;
|
||||
if(ownerDoc) {
|
||||
if (ownerDoc) {
|
||||
this.listenerHost = ownerDoc;
|
||||
ownerDoc.addEventListener("keydown",onKeyDown);
|
||||
ownerDoc.addEventListener("keydown", onKeyDown);
|
||||
}
|
||||
}
|
||||
|
||||
private async applySettings() {
|
||||
let dirty = false;
|
||||
const el = this.ea.getElement(this.element.id) as Mutable<ExcalidrawEmbeddableElement>;
|
||||
if(this.updatedFilepath) {
|
||||
const el = this.ea.getElement(
|
||||
this.element.id,
|
||||
) as Mutable<ExcalidrawEmbeddableElement>;
|
||||
if (this.updatedFilepath) {
|
||||
const newPathWithExt = `${this.updatedFilepath}.${this.file.extension}`;
|
||||
if(newPathWithExt !== this.file.path) {
|
||||
if (newPathWithExt !== this.file.path) {
|
||||
const fnparts = splitFolderAndFilename(newPathWithExt);
|
||||
const newPath = getNewUniqueFilepath(
|
||||
this.app.vault,
|
||||
fnparts.filename,
|
||||
fnparts.folderpath,
|
||||
);
|
||||
if(this.app.vault.getAbstractFileByPath(newPath)) {
|
||||
new Notice("File rename failed. A file with this name already exists.\n"+newPath,10000);
|
||||
if (this.app.vault.getAbstractFileByPath(newPath)) {
|
||||
new Notice(
|
||||
`File rename failed. A file with this name already exists.\n${
|
||||
newPath
|
||||
}`,
|
||||
10000,
|
||||
);
|
||||
} else {
|
||||
try {
|
||||
await this.app.fileManager.renameFile(this.file,newPath);
|
||||
await this.app.fileManager.renameFile(this.file, newPath);
|
||||
el.link = this.element.link.replace(
|
||||
/(\[\[)([^#\]]*)([^\]]*]])/,`$1${
|
||||
this.plugin.app.metadataCache.fileToLinktext(
|
||||
this.file,this.view.file.path,true)
|
||||
}$3`);
|
||||
/(\[\[)([^#\]]*)([^\]]*]])/,
|
||||
`$1${this.plugin.app.metadataCache.fileToLinktext(
|
||||
this.file,
|
||||
this.view.file.path,
|
||||
true,
|
||||
)}$3`,
|
||||
);
|
||||
dirty = true;
|
||||
} catch(e) {
|
||||
new Notice("File rename failed. "+e,10000);
|
||||
} catch (e) {
|
||||
new Notice(`File rename failed. ${e}`, 10000);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if(this.isYouTube && this.youtubeStart !== getYouTubeStartAt(this.element.link)) {
|
||||
if (
|
||||
this.isYouTube &&
|
||||
this.youtubeStart !== getYouTubeStartAt(this.element.link)
|
||||
) {
|
||||
dirty = true;
|
||||
if(this.youtubeStart === "" || isValidYouTubeStart(this.youtubeStart)) {
|
||||
el.link = updateYouTubeStartTime(el.link,this.youtubeStart);
|
||||
if (this.youtubeStart === "" || isValidYouTubeStart(this.youtubeStart)) {
|
||||
el.link = updateYouTubeStartTime(el.link, this.youtubeStart);
|
||||
} else {
|
||||
new Notice(t("ES_YOUTUBE_START_INVALID"));
|
||||
}
|
||||
}
|
||||
if(
|
||||
this.isMDFile && (
|
||||
this.mdCustomData.backgroundColor !== this.element.customData?.backgroundColor ||
|
||||
this.mdCustomData.borderColor !== this.element.customData?.borderColor ||
|
||||
this.mdCustomData.backgroundOpacity !== this.element.customData?.backgroundOpacity ||
|
||||
this.mdCustomData.borderOpacity !== this.element.customData?.borderOpacity ||
|
||||
this.mdCustomData.filenameVisible !== this.element.customData?.filenameVisible)
|
||||
if (
|
||||
this.isMDFile &&
|
||||
(this.mdCustomData.backgroundColor !==
|
||||
this.element.customData?.backgroundColor ||
|
||||
this.mdCustomData.borderColor !==
|
||||
this.element.customData?.borderColor ||
|
||||
this.mdCustomData.backgroundOpacity !==
|
||||
this.element.customData?.backgroundOpacity ||
|
||||
this.mdCustomData.borderOpacity !==
|
||||
this.element.customData?.borderOpacity ||
|
||||
this.mdCustomData.filenameVisible !==
|
||||
this.element.customData?.filenameVisible)
|
||||
) {
|
||||
addAppendUpdateCustomData(el,{mdProps: this.mdCustomData});
|
||||
addAppendUpdateCustomData(el, { mdProps: this.mdCustomData });
|
||||
dirty = true;
|
||||
}
|
||||
|
||||
if(this.zoomValue !== this.element.scale[0]) {
|
||||
if (this.zoomValue !== this.element.scale[0]) {
|
||||
dirty = true;
|
||||
|
||||
el.scale = [this.zoomValue,this.zoomValue];
|
||||
|
||||
el.scale = [this.zoomValue, this.zoomValue];
|
||||
}
|
||||
if(dirty) {
|
||||
(async() => {
|
||||
if (dirty) {
|
||||
void (async () => {
|
||||
await this.ea.addElementsToView();
|
||||
this.ea.viewUpdateScene({appState: {}, captureUpdate: CaptureUpdateAction.NEVER});
|
||||
this.ea.viewUpdateScene({
|
||||
appState: {},
|
||||
captureUpdate: CaptureUpdateAction.NEVER,
|
||||
});
|
||||
this.close(); //close should only run once update scene is done
|
||||
})();
|
||||
} else {
|
||||
this.close();
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
+232
-171
@@ -1,20 +1,38 @@
|
||||
import { ExcalidrawImperativeAPI } from "@zsviczian/excalidraw/types/excalidraw/types";
|
||||
import { Modal, Notice, Setting, TFile, ButtonComponent } from "obsidian";
|
||||
import { Modal, Notice, Setting, TFile } from "obsidian";
|
||||
import { getEA } from "src/core";
|
||||
import { DEVICE } from "src/constants/constants";
|
||||
import { ExcalidrawAutomate } from "src/shared/ExcalidrawAutomate";
|
||||
import ExcalidrawView from "src/view/ExcalidrawView";
|
||||
import ExcalidrawPlugin from "src/core/main";
|
||||
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 {
|
||||
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 {
|
||||
PDFExportSettings,
|
||||
PDFExportSettingsComponent,
|
||||
} from "./PDFExportSettingsComponent";
|
||||
import { captureScreenshot } from "src/utils/screenshot";
|
||||
import { exportImageToFile, getIMGFilename } from "src/utils/fileUtils";
|
||||
|
||||
|
||||
|
||||
export class ExportDialog extends Modal {
|
||||
private ea: ExcalidrawAutomate;
|
||||
private api: ExcalidrawImperativeAPI;
|
||||
@@ -25,7 +43,7 @@ export class ExportDialog extends Modal {
|
||||
public exportInternalLinks: boolean = true;
|
||||
public saveSettings: boolean;
|
||||
public dirty: boolean = false;
|
||||
private selectedOnlySetting: Setting;
|
||||
private selectedOnlySetting: Setting | null = null;
|
||||
private hasSelectedElements: boolean = false;
|
||||
private boundingBox: {
|
||||
topX: number;
|
||||
@@ -39,15 +57,15 @@ export class ExportDialog extends Modal {
|
||||
public pageSize: PageSize = "A4";
|
||||
public pageOrientation: PageOrientation = "portrait";
|
||||
private activeTab: "image" | "pdf" | "screenshot" = "image";
|
||||
private contentContainer: HTMLDivElement;
|
||||
private buttonContainerRow1: HTMLDivElement;
|
||||
private buttonContainerRow2: HTMLDivElement;
|
||||
private contentContainer: HTMLDivElement | null = null;
|
||||
private buttonContainerRow1: HTMLDivElement | null = null;
|
||||
private buttonContainerRow2: HTMLDivElement | null = null;
|
||||
public fitToPage: number = 1;
|
||||
public paperColor: "white" | "scene" | "custom" = "white";
|
||||
public customPaperColor: string = "#ffffff";
|
||||
public alignment: PDFPageAlignment = "center";
|
||||
public margin: PDFPageMarginString = "normal";
|
||||
private scaleSetting:Setting;
|
||||
private scaleSetting: Setting | null = null;
|
||||
|
||||
constructor(
|
||||
private plugin: ExcalidrawPlugin,
|
||||
@@ -56,10 +74,14 @@ export class ExportDialog extends Modal {
|
||||
) {
|
||||
super(plugin.app);
|
||||
this.ea = getEA(this.view);
|
||||
this.api = this.ea.getExcalidrawAPI() as ExcalidrawImperativeAPI;
|
||||
this.padding = getExportPadding(this.plugin,this.file);
|
||||
this.scale = getPNGScale(this.plugin,this.file)
|
||||
this.theme = getExportTheme(this.plugin, this.file, (this.api).getAppState().theme)
|
||||
this.api = this.ea.getExcalidrawAPI();
|
||||
this.padding = getExportPadding(this.plugin, this.file);
|
||||
this.scale = getPNGScale(this.plugin, this.file);
|
||||
this.theme = getExportTheme(
|
||||
this.plugin,
|
||||
this.file,
|
||||
this.api.getAppState().theme,
|
||||
);
|
||||
this.boundingBox = this.ea.getBoundingBox(this.ea.getViewElements());
|
||||
this.embedScene = shouldEmbedScene(this.plugin, this.file);
|
||||
this.exportSelectedOnly = false;
|
||||
@@ -95,14 +117,16 @@ export class ExportDialog extends Modal {
|
||||
get isSelectedOnly(): boolean {
|
||||
return this.hasSelectedElements && this.exportSelectedOnly;
|
||||
}
|
||||
|
||||
|
||||
updateBoundingBox() {
|
||||
if(this.isSelectedOnly) {
|
||||
this.boundingBox = this.ea.getBoundingBox(this.view.getViewSelectedElements());
|
||||
if (this.isSelectedOnly) {
|
||||
this.boundingBox = this.ea.getBoundingBox(
|
||||
this.view.getViewSelectedElements(),
|
||||
);
|
||||
} else {
|
||||
this.boundingBox = this.ea.getBoundingBox(this.ea.getViewElements());
|
||||
}
|
||||
if(this.scaleSetting) {
|
||||
if (this.scaleSetting) {
|
||||
this.scaleSetting.setDesc(this.size());
|
||||
}
|
||||
}
|
||||
@@ -111,7 +135,6 @@ export class ExportDialog extends Modal {
|
||||
this.containerEl.classList.add("excalidraw-release");
|
||||
this.titleEl.setText(t("EXPORTDIALOG_TITLE"));
|
||||
this.hasSelectedElements = this.view.getViewSelectedElements().length > 0;
|
||||
//@ts-ignore
|
||||
this.selectedOnlySetting.setVisibility(this.hasSelectedElements);
|
||||
this.updateBoundingBox();
|
||||
}
|
||||
@@ -121,23 +144,22 @@ export class ExportDialog extends Modal {
|
||||
}
|
||||
|
||||
createForm() {
|
||||
if(DEVICE.isDesktop) {
|
||||
if (DEVICE.isDesktop) {
|
||||
// Create tab container
|
||||
const tabContainer = this.contentEl.createDiv("nav-buttons-container");
|
||||
const imageTab = tabContainer.createEl("button", {
|
||||
const imageTab = tabContainer.createEl("button", {
|
||||
text: t("EXPORTDIALOG_TAB_IMAGE"),
|
||||
cls: `nav-button ${this.activeTab === "image" ? "is-active" : ""}`
|
||||
cls: `nav-button ${this.activeTab === "image" ? "is-active" : ""}`,
|
||||
});
|
||||
|
||||
|
||||
const pdfTab = tabContainer.createEl("button", {
|
||||
const pdfTab = tabContainer.createEl("button", {
|
||||
text: t("EXPORTDIALOG_TAB_PDF"),
|
||||
cls: `nav-button ${this.activeTab === "pdf" ? "is-active" : ""}`
|
||||
cls: `nav-button ${this.activeTab === "pdf" ? "is-active" : ""}`,
|
||||
});
|
||||
|
||||
const screenshotTab = tabContainer.createEl("button", {
|
||||
text: t("EXPORTDIALOG_TAB_SCREENSHOT"),
|
||||
cls: `nav-button ${this.activeTab === "screenshot" ? "is-active" : ""}`
|
||||
cls: `nav-button ${this.activeTab === "screenshot" ? "is-active" : ""}`,
|
||||
});
|
||||
|
||||
// Tab click handlers
|
||||
@@ -163,13 +185,17 @@ export class ExportDialog extends Modal {
|
||||
imageTab.removeClass("is-active");
|
||||
pdfTab.removeClass("is-active");
|
||||
this.renderContent();
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
// Create content container
|
||||
this.contentContainer = this.contentEl.createDiv();
|
||||
this.buttonContainerRow1 = this.contentEl.createDiv({cls: "excalidraw-export-buttons-div"});
|
||||
this.buttonContainerRow2 = this.contentEl.createDiv({cls: "excalidraw-export-buttons-div"});
|
||||
this.buttonContainerRow1 = this.contentEl.createDiv({
|
||||
cls: "excalidraw-export-buttons-div",
|
||||
});
|
||||
this.buttonContainerRow2 = this.contentEl.createDiv({
|
||||
cls: "excalidraw-export-buttons-div",
|
||||
});
|
||||
this.buttonContainerRow2.style.marginTop = "10px";
|
||||
|
||||
this.renderContent();
|
||||
@@ -178,14 +204,14 @@ export class ExportDialog extends Modal {
|
||||
private createSaveSettingsDropdown() {
|
||||
new Setting(this.contentContainer)
|
||||
.setName(t("EXPORTDIALOG_SAVE_SETTINGS"))
|
||||
.addDropdown(dropdown =>
|
||||
.addDropdown((dropdown) =>
|
||||
dropdown
|
||||
.addOption("save", t("EXPORTDIALOG_SAVE_SETTINGS_SAVE"))
|
||||
.addOption("one-time", t("EXPORTDIALOG_SAVE_SETTINGS_ONETIME"))
|
||||
.setValue(this.saveSettings ? "save" : "one-time")
|
||||
.onChange(value => {
|
||||
.onChange((value) => {
|
||||
this.saveSettings = value === "save";
|
||||
})
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -202,155 +228,173 @@ export class ExportDialog extends Modal {
|
||||
this.createPDFButton();
|
||||
break;
|
||||
case "screenshot":
|
||||
if(this.view.isInMainObsidianWorkspace) {
|
||||
if (this.view.isInMainObsidianWorkspace) {
|
||||
this.createImageSettings(true);
|
||||
this.createImageButtons(true);
|
||||
}
|
||||
break;
|
||||
case "image":
|
||||
default:
|
||||
this.createImageSettings(false);
|
||||
this.createExportSettings();
|
||||
this.createImageButtons();
|
||||
break;
|
||||
this.createImageSettings(false);
|
||||
this.createExportSettings();
|
||||
this.createImageButtons();
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private size ():DocumentFragment {
|
||||
const width = Math.round(this.scale*this.boundingBox.width + this.padding*2);
|
||||
const height = Math.round(this.scale*this.boundingBox.height + this.padding*2);
|
||||
return fragWithHTML(`${t("EXPORTDIALOG_SIZE_DESC")}<br>${t("EXPORTDIALOG_SCALE_VALUE")} <b>${this.scale}</b><br>${t("EXPORTDIALOG_IMAGE_SIZE")} <b>${width}x${height}</b>`);
|
||||
private size(): DocumentFragment {
|
||||
const width = Math.round(
|
||||
this.scale * this.boundingBox.width + this.padding * 2,
|
||||
);
|
||||
const height = Math.round(
|
||||
this.scale * this.boundingBox.height + this.padding * 2,
|
||||
);
|
||||
return fragWithHTML(
|
||||
`${t("EXPORTDIALOG_SIZE_DESC")}<br>${t("EXPORTDIALOG_SCALE_VALUE")} <b>${this.scale}</b><br>${t("EXPORTDIALOG_IMAGE_SIZE")} <b>${width}x${height}</b>`,
|
||||
);
|
||||
}
|
||||
|
||||
private createHeader() {
|
||||
switch (this.activeTab) {
|
||||
case "pdf":
|
||||
this.contentContainer.createEl("h1",{text: t("EXPORTDIALOG_PDF_SETTINGS")});
|
||||
this.contentContainer.createEl("h1", {
|
||||
text: t("EXPORTDIALOG_PDF_SETTINGS"),
|
||||
});
|
||||
//this.contentContainer.createEl("p",{text: t("EXPORTDIALOG_PDF_DESC")});
|
||||
break;
|
||||
case "screenshot":
|
||||
this.contentContainer.createEl("h1",{text: t("EXPORTDIALOG_TAB_SCREENSHOT")});
|
||||
if(this.view.isInMainObsidianWorkspace) {
|
||||
this.contentContainer.createEl("p",{text: t("EXPORTDIALOG_SCREENSHOT_DESC")})
|
||||
this.contentContainer.createEl("h1", {
|
||||
text: t("EXPORTDIALOG_TAB_SCREENSHOT"),
|
||||
});
|
||||
if (this.view.isInMainObsidianWorkspace) {
|
||||
this.contentContainer.createEl("p", {
|
||||
text: t("EXPORTDIALOG_SCREENSHOT_DESC"),
|
||||
});
|
||||
} else {
|
||||
this.contentContainer.createEl("p",{text: t("EXPORTDIALOG_NOT_AVAILALBE")})
|
||||
this.contentContainer.createEl("p", {
|
||||
text: t("EXPORTDIALOG_NOT_AVAILALBE"),
|
||||
});
|
||||
}
|
||||
break;
|
||||
case "image":
|
||||
default:
|
||||
this.contentContainer.createEl("h1",{text: t("EXPORTDIALOG_IMAGE_SETTINGS")});
|
||||
this.contentContainer.createEl("p",{text: t("EXPORTDIALOG_IMAGE_DESC")})
|
||||
this.contentContainer.createEl("h1", {
|
||||
text: t("EXPORTDIALOG_IMAGE_SETTINGS"),
|
||||
});
|
||||
this.contentContainer.createEl("p", {
|
||||
text: t("EXPORTDIALOG_IMAGE_DESC"),
|
||||
});
|
||||
break;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private createImageSettings(isScreenshot: boolean = false) {
|
||||
let paddingSetting: Setting;
|
||||
|
||||
private createImageSettings(isScreenshot: boolean = false) {
|
||||
this.createSaveSettingsDropdown();
|
||||
|
||||
const padding = ():DocumentFragment => {
|
||||
return fragWithHTML(`${t("EXPORTDIALOG_CURRENT_PADDING")} <b>${this.padding}</b>`);
|
||||
}
|
||||
const padding = (): DocumentFragment => {
|
||||
return fragWithHTML(
|
||||
`${t("EXPORTDIALOG_CURRENT_PADDING")} <b>${this.padding}</b>`,
|
||||
);
|
||||
};
|
||||
|
||||
paddingSetting = new Setting(this.contentContainer)
|
||||
const paddingSetting = new Setting(this.contentContainer)
|
||||
.setName(t("EXPORTDIALOG_PADDING"))
|
||||
.setDesc(padding())
|
||||
.addSlider(slider => {
|
||||
.addSlider((slider) => {
|
||||
slider
|
||||
.setLimits(0,100,1)
|
||||
.setLimits(0, 100, 1)
|
||||
.setValue(this.padding)
|
||||
.onChange(value => {
|
||||
.onChange((value) => {
|
||||
this.padding = value;
|
||||
this.scaleSetting.setDesc(this.size());
|
||||
paddingSetting.setDesc(padding());
|
||||
})
|
||||
})
|
||||
|
||||
});
|
||||
});
|
||||
|
||||
this.scaleSetting = new Setting(this.contentContainer)
|
||||
.setName(t("EXPORTDIALOG_SCALE"))
|
||||
.setDesc(this.size())
|
||||
.addSlider(slider =>
|
||||
.addSlider((slider) =>
|
||||
slider
|
||||
.setLimits(0.2,7,0.1)
|
||||
.setLimits(0.2, 7, 0.1)
|
||||
.setValue(this.scale)
|
||||
.onChange(value => {
|
||||
.onChange((value) => {
|
||||
this.scale = value;
|
||||
this.scaleSetting.setDesc(this.size());
|
||||
})
|
||||
)
|
||||
|
||||
}),
|
||||
);
|
||||
|
||||
new Setting(this.contentContainer)
|
||||
.setName(t("EXPORTDIALOG_EXPORT_THEME"))
|
||||
.addDropdown(dropdown =>
|
||||
.addDropdown((dropdown) =>
|
||||
dropdown
|
||||
.addOption("light", t("EXPORTDIALOG_THEME_LIGHT"))
|
||||
.addOption("dark", t("EXPORTDIALOG_THEME_DARK"))
|
||||
.setValue(this.theme)
|
||||
.onChange(value => {
|
||||
.onChange((value) => {
|
||||
this.theme = value;
|
||||
})
|
||||
)
|
||||
}),
|
||||
);
|
||||
|
||||
if(!isScreenshot) {
|
||||
if (!isScreenshot) {
|
||||
new Setting(this.contentContainer)
|
||||
.setName(t("EXPORTDIALOG_BACKGROUND"))
|
||||
.addDropdown(dropdown =>
|
||||
.addDropdown((dropdown) =>
|
||||
dropdown
|
||||
.addOption("transparent", t("EXPORTDIALOG_BACKGROUND_TRANSPARENT"))
|
||||
.addOption("with-color", t("EXPORTDIALOG_BACKGROUND_USE_COLOR"))
|
||||
.setValue(this.transparent?"transparent":"with-color")
|
||||
.onChange(value => {
|
||||
.setValue(this.transparent ? "transparent" : "with-color")
|
||||
.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;
|
||||
})
|
||||
.addToggle((toggle) =>
|
||||
toggle.setValue(this.exportInternalLinks).onChange((value) => {
|
||||
this.exportInternalLinks = value;
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
this.selectedOnlySetting = new Setting(this.contentContainer)
|
||||
.setName(t("EXPORTDIALOG_SELECTED_ELEMENTS"))
|
||||
.addDropdown(dropdown =>
|
||||
.addDropdown((dropdown) =>
|
||||
dropdown
|
||||
.addOption("all", t("EXPORTDIALOG_SELECTED_ALL"))
|
||||
.addOption("selected", t("EXPORTDIALOG_SELECTED_SELECTED"))
|
||||
.setValue(this.exportSelectedOnly?"selected":"all")
|
||||
.onChange(value => {
|
||||
.setValue(this.exportSelectedOnly ? "selected" : "all")
|
||||
.onChange((value) => {
|
||||
this.exportSelectedOnly = value === "selected";
|
||||
this.updateBoundingBox();
|
||||
})
|
||||
}),
|
||||
);
|
||||
//@ts-ignore
|
||||
this.selectedOnlySetting.setVisibility(this.hasSelectedElements);
|
||||
}
|
||||
|
||||
private createExportSettings() {
|
||||
new Setting(this.contentContainer)
|
||||
.setName(t("EXPORTDIALOG_EMBED_SCENE"))
|
||||
.addDropdown(dropdown =>
|
||||
.addDropdown((dropdown) =>
|
||||
dropdown
|
||||
.addOption("embed",t("EXPORTDIALOG_EMBED_YES"))
|
||||
.addOption("no-embed",t("EXPORTDIALOG_EMBED_NO"))
|
||||
.setValue(this.embedScene?"embed":"no-embed")
|
||||
.onChange(value => {
|
||||
.addOption("embed", t("EXPORTDIALOG_EMBED_YES"))
|
||||
.addOption("no-embed", t("EXPORTDIALOG_EMBED_NO"))
|
||||
.setValue(this.embedScene ? "embed" : "no-embed")
|
||||
.onChange((value) => {
|
||||
this.embedScene = value === "embed";
|
||||
})
|
||||
)
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
private createPDFSettings() {
|
||||
if (!DEVICE.isDesktop) return;
|
||||
if (!DEVICE.isDesktop) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.contentContainer.createEl("h1", { text: t("EXPORTDIALOG_PDF_SETTINGS") });
|
||||
this.contentContainer.createEl("h1", {
|
||||
text: t("EXPORTDIALOG_PDF_SETTINGS"),
|
||||
});
|
||||
|
||||
const pdfSettings: PDFExportSettings = {
|
||||
pageSize: this.pageSize,
|
||||
@@ -362,142 +406,153 @@ export class ExportDialog extends Modal {
|
||||
margin: this.margin,
|
||||
};
|
||||
|
||||
new PDFExportSettingsComponent(
|
||||
this.contentContainer,
|
||||
pdfSettings,
|
||||
() => {
|
||||
this.pageSize = pdfSettings.pageSize;
|
||||
this.pageOrientation = pdfSettings.pageOrientation;
|
||||
this.fitToPage = pdfSettings.fitToPage;
|
||||
this.paperColor = pdfSettings.paperColor;
|
||||
this.customPaperColor = pdfSettings.customPaperColor;
|
||||
this.alignment = pdfSettings.alignment;
|
||||
this.margin = pdfSettings.margin;
|
||||
}
|
||||
).render();
|
||||
new PDFExportSettingsComponent(this.contentContainer, pdfSettings, () => {
|
||||
this.pageSize = pdfSettings.pageSize;
|
||||
this.pageOrientation = pdfSettings.pageOrientation;
|
||||
this.fitToPage = pdfSettings.fitToPage;
|
||||
this.paperColor = pdfSettings.paperColor;
|
||||
this.customPaperColor = pdfSettings.customPaperColor;
|
||||
this.alignment = pdfSettings.alignment;
|
||||
this.margin = pdfSettings.margin;
|
||||
}).render();
|
||||
}
|
||||
|
||||
private createImageButtons(isScreenshot: boolean = false) {
|
||||
if(DEVICE.isDesktop) {
|
||||
const bPNG = this.buttonContainerRow1.createEl("button", {
|
||||
text: t("EXPORTDIALOG_PNGTOFILE"),
|
||||
cls: "excalidraw-export-button"
|
||||
if (DEVICE.isDesktop) {
|
||||
const bPNG = this.buttonContainerRow1.createEl("button", {
|
||||
text: t("EXPORTDIALOG_PNGTOFILE"),
|
||||
cls: "excalidraw-export-button",
|
||||
});
|
||||
bPNG.onclick = () => {
|
||||
if(isScreenshot) {
|
||||
if (isScreenshot) {
|
||||
//allow dialog to close before taking screenshot
|
||||
setTimeout(async () => {
|
||||
window.setTimeout(async () => {
|
||||
const png = await captureScreenshot(this.view, {
|
||||
zoom: this.scale,
|
||||
margin: this.padding,
|
||||
selectedOnly: this.isSelectedOnly,
|
||||
theme: this.theme
|
||||
theme: this.theme,
|
||||
});
|
||||
if(png) {
|
||||
if (png) {
|
||||
exportPNG(png, this.view.file.basename);
|
||||
}
|
||||
});
|
||||
} else {
|
||||
this.view.exportPNG(this.embedScene, this.isSelectedOnly);
|
||||
void this.view.exportPNG(this.embedScene, this.isSelectedOnly);
|
||||
}
|
||||
this.close();
|
||||
};
|
||||
}
|
||||
|
||||
const bPNGVault = this.buttonContainerRow1.createEl("button", {
|
||||
text: t("EXPORTDIALOG_PNGTOVAULT"),
|
||||
cls: "excalidraw-export-button"
|
||||
const bPNGVault = this.buttonContainerRow1.createEl("button", {
|
||||
text: t("EXPORTDIALOG_PNGTOVAULT"),
|
||||
cls: "excalidraw-export-button",
|
||||
});
|
||||
bPNGVault.onclick = () => {
|
||||
if(isScreenshot) {
|
||||
if (isScreenshot) {
|
||||
//allow dialog to close before taking screenshot
|
||||
setTimeout(async () => {
|
||||
window.setTimeout(async () => {
|
||||
const png = await captureScreenshot(this.view, {
|
||||
zoom: this.scale,
|
||||
margin: this.padding,
|
||||
selectedOnly: this.isSelectedOnly,
|
||||
theme: this.theme
|
||||
theme: this.theme,
|
||||
});
|
||||
if(png) {
|
||||
exportImageToFile(this.view, getIMGFilename(this.view.file.path,"png"), png, ".png");
|
||||
if (png) {
|
||||
void exportImageToFile(
|
||||
this.view,
|
||||
getIMGFilename(this.view.file.path, "png"),
|
||||
png,
|
||||
".png",
|
||||
);
|
||||
}
|
||||
});
|
||||
} else {
|
||||
this.view.savePNG({scene: this.view.getScene(this.isSelectedOnly)});
|
||||
void this.view.savePNG({
|
||||
scene: this.view.getScene(this.isSelectedOnly),
|
||||
});
|
||||
}
|
||||
this.close();
|
||||
};
|
||||
|
||||
const bPNGClipboard = this.buttonContainerRow1.createEl("button", {
|
||||
text: t("EXPORTDIALOG_PNGTOCLIPBOARD"),
|
||||
cls: "excalidraw-export-button"
|
||||
const bPNGClipboard = this.buttonContainerRow1.createEl("button", {
|
||||
text: t("EXPORTDIALOG_PNGTOCLIPBOARD"),
|
||||
cls: "excalidraw-export-button",
|
||||
});
|
||||
bPNGClipboard.onclick = async () => {
|
||||
if(isScreenshot) {
|
||||
if (isScreenshot) {
|
||||
//allow dialog to close before taking screenshot
|
||||
setTimeout(async () => {
|
||||
window.setTimeout(async () => {
|
||||
const png = await captureScreenshot(this.view, {
|
||||
zoom: this.scale,
|
||||
margin: this.padding,
|
||||
selectedOnly: this.isSelectedOnly,
|
||||
theme: this.theme
|
||||
theme: this.theme,
|
||||
});
|
||||
if(png) {
|
||||
exportPNGToClipboard(png);
|
||||
if (png) {
|
||||
await exportPNGToClipboard(png);
|
||||
}
|
||||
});
|
||||
} else {
|
||||
this.view.exportPNGToClipboard(this.embedScene, this.isSelectedOnly);
|
||||
await this.view.exportPNGToClipboard(
|
||||
this.embedScene,
|
||||
this.isSelectedOnly,
|
||||
);
|
||||
}
|
||||
this.close();
|
||||
};
|
||||
|
||||
if(isScreenshot) return;
|
||||
if (isScreenshot) {
|
||||
return;
|
||||
}
|
||||
|
||||
if(DEVICE.isDesktop) {
|
||||
const bExcalidraw = this.buttonContainerRow2.createEl("button", {
|
||||
text: t("EXPORTDIALOG_EXCALIDRAW"),
|
||||
cls: "excalidraw-export-button"
|
||||
if (DEVICE.isDesktop) {
|
||||
const bExcalidraw = this.buttonContainerRow2.createEl("button", {
|
||||
text: t("EXPORTDIALOG_EXCALIDRAW"),
|
||||
cls: "excalidraw-export-button",
|
||||
});
|
||||
bExcalidraw.onclick = () => {
|
||||
this.view.exportExcalidraw();
|
||||
void this.view.exportExcalidraw();
|
||||
this.close();
|
||||
};
|
||||
|
||||
const bSVG = this.buttonContainerRow2.createEl("button", {
|
||||
text: t("EXPORTDIALOG_SVGTOFILE"),
|
||||
cls: "excalidraw-export-button"
|
||||
const bSVG = this.buttonContainerRow2.createEl("button", {
|
||||
text: t("EXPORTDIALOG_SVGTOFILE"),
|
||||
cls: "excalidraw-export-button",
|
||||
});
|
||||
bSVG.onclick = () => {
|
||||
this.view.exportSVG(this.embedScene, this.isSelectedOnly);
|
||||
void this.view.exportSVG(this.embedScene, this.isSelectedOnly);
|
||||
this.close();
|
||||
};
|
||||
}
|
||||
|
||||
const bSVGVault = this.buttonContainerRow2.createEl("button", {
|
||||
text: t("EXPORTDIALOG_SVGTOVAULT"),
|
||||
cls: "excalidraw-export-button"
|
||||
const bSVGVault = this.buttonContainerRow2.createEl("button", {
|
||||
text: t("EXPORTDIALOG_SVGTOVAULT"),
|
||||
cls: "excalidraw-export-button",
|
||||
});
|
||||
bSVGVault.onclick = () => {
|
||||
this.view.saveSVG({scene: this.view.getScene(this.isSelectedOnly)});
|
||||
void this.view.saveSVG({
|
||||
scene: this.view.getScene(this.isSelectedOnly),
|
||||
});
|
||||
this.close();
|
||||
};
|
||||
|
||||
const bSVGClipboard = this.buttonContainerRow2.createEl("button", {
|
||||
text: t("EXPORTDIALOG_SVGTOCLIPBOARD"),
|
||||
cls: "excalidraw-export-button"
|
||||
const bSVGClipboard = this.buttonContainerRow2.createEl("button", {
|
||||
text: t("EXPORTDIALOG_SVGTOCLIPBOARD"),
|
||||
cls: "excalidraw-export-button",
|
||||
});
|
||||
bSVGClipboard.onclick = async () => {
|
||||
const svg = await this.view.getSVG(this.embedScene, this.isSelectedOnly);
|
||||
exportSVGToClipboard(svg);
|
||||
await exportSVGToClipboard(svg);
|
||||
this.close();
|
||||
};
|
||||
}
|
||||
|
||||
private createPDFButton() {
|
||||
const bSavePDFSettings = this.buttonContainerRow1.createEl("button",
|
||||
{ text: t("EXPORTDIALOG_SAVE_PDF_SETTINGS"), cls: "excalidraw-export-button" }
|
||||
);
|
||||
const bSavePDFSettings = this.buttonContainerRow1.createEl("button", {
|
||||
text: t("EXPORTDIALOG_SAVE_PDF_SETTINGS"),
|
||||
cls: "excalidraw-export-button",
|
||||
});
|
||||
bSavePDFSettings.onclick = async () => {
|
||||
//in case sync loaded a new version of settings in the mean time
|
||||
await this.plugin.loadSettings();
|
||||
@@ -514,16 +569,18 @@ export class ExportDialog extends Modal {
|
||||
new Notice(t("EXPORTDIALOG_SAVE_CONFIRMATION"));
|
||||
};
|
||||
|
||||
if (!DEVICE.isDesktop) return;
|
||||
const bPDFExport = this.buttonContainerRow1.createEl("button", {
|
||||
text: t("EXPORTDIALOG_PDF"),
|
||||
cls: "excalidraw-export-button"
|
||||
if (!DEVICE.isDesktop) {
|
||||
return;
|
||||
}
|
||||
const bPDFExport = this.buttonContainerRow1.createEl("button", {
|
||||
text: t("EXPORTDIALOG_PDF"),
|
||||
cls: "excalidraw-export-button",
|
||||
});
|
||||
bPDFExport.onclick = () => {
|
||||
this.view.exportPDF(
|
||||
void this.view.exportPDF(
|
||||
this.isSelectedOnly,
|
||||
this.pageSize,
|
||||
this.pageOrientation
|
||||
this.pageOrientation,
|
||||
);
|
||||
this.close();
|
||||
};
|
||||
@@ -531,10 +588,14 @@ export class ExportDialog extends Modal {
|
||||
|
||||
public getPaperColor(): string {
|
||||
switch (this.paperColor) {
|
||||
case "white": return this.theme === "light" ? "#ffffff" : "#000000";
|
||||
case "scene": return this.api.getAppState().viewBackgroundColor;
|
||||
case "custom": return this.customPaperColor;
|
||||
default: return "#ffffff";
|
||||
case "white":
|
||||
return this.theme === "light" ? "#ffffff" : "#000000";
|
||||
case "scene":
|
||||
return this.api.getAppState().viewBackgroundColor;
|
||||
case "custom":
|
||||
return this.customPaperColor;
|
||||
default:
|
||||
return "#ffffff";
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,14 +3,19 @@ import { clamp } from "@radix-ui/number";
|
||||
|
||||
function getClientPoint(e: PointerEvent | TouchEvent) {
|
||||
if (e.type.startsWith("touch")) {
|
||||
const t = (e as TouchEvent).touches[0] ?? (e as TouchEvent).changedTouches[0];
|
||||
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 {
|
||||
function pointInRect(
|
||||
pt: { x: number; y: number },
|
||||
r: DOMRect,
|
||||
padding = 1,
|
||||
): boolean {
|
||||
return (
|
||||
pt.x >= r.left - padding &&
|
||||
pt.x <= r.right + padding &&
|
||||
@@ -21,7 +26,9 @@ function pointInRect(pt: { x: number; y: number }, r: DOMRect, padding = 1): boo
|
||||
|
||||
function isPointOnText(e: PointerEvent | TouchEvent, doc: Document): boolean {
|
||||
const pt = getClientPoint(e);
|
||||
if (!pt) return false;
|
||||
if (!pt) {
|
||||
return false;
|
||||
}
|
||||
|
||||
let offsetNode: Node | null = null;
|
||||
let offset: number | null = null;
|
||||
@@ -36,12 +43,19 @@ function isPointOnText(e: PointerEvent | TouchEvent, doc: Document): boolean {
|
||||
const caretRange = doc.caretRangeFromPoint?.(pt.x, pt.y);
|
||||
if (caretRange?.startContainer) {
|
||||
offsetNode = caretRange.startContainer;
|
||||
offset = typeof caretRange.startOffset === "number" ? caretRange.startOffset : null;
|
||||
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;
|
||||
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;
|
||||
@@ -59,7 +73,9 @@ function isPointOnText(e: PointerEvent | TouchEvent, doc: Document): boolean {
|
||||
}
|
||||
|
||||
const rects = Array.from(range.getClientRects());
|
||||
if (rects.length === 0) return false;
|
||||
if (rects.length === 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return rects.some((r) => pointInRect(pt, r, 1));
|
||||
}
|
||||
@@ -89,7 +105,10 @@ export class FloatingModal extends Modal {
|
||||
this.setDimBackground(false);
|
||||
}
|
||||
|
||||
protected shouldNotStartDrag(target: HTMLElement, event: PointerEvent | TouchEvent): boolean {
|
||||
protected shouldNotStartDrag(
|
||||
target: HTMLElement,
|
||||
event: PointerEvent | TouchEvent,
|
||||
): boolean {
|
||||
return Boolean(
|
||||
target instanceof HTMLInputElement ||
|
||||
target instanceof HTMLTextAreaElement ||
|
||||
@@ -98,8 +117,8 @@ export class FloatingModal extends Modal {
|
||||
isPointOnText(event, this.ownerDocument) ||
|
||||
target.closest(".clickable-icon") ||
|
||||
// ensure close button never starts drag
|
||||
target.closest(".modal-close-button")
|
||||
)
|
||||
target.closest(".modal-close-button"),
|
||||
);
|
||||
}
|
||||
|
||||
private handlePointerDown(e: PointerEvent | TouchEvent): void {
|
||||
@@ -116,7 +135,9 @@ export class FloatingModal extends Modal {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
|
||||
if ((e as TouchEvent).touches.length !== 1) return;
|
||||
if ((e as TouchEvent).touches.length !== 1) {
|
||||
return;
|
||||
}
|
||||
|
||||
const touch = (e as TouchEvent).touches[0];
|
||||
this.dragging = true;
|
||||
@@ -126,9 +147,13 @@ export class FloatingModal extends Modal {
|
||||
modalEl.style.height = "fit-content";
|
||||
|
||||
// Add touch-specific event listeners
|
||||
this.ownerDocument.addEventListener("touchmove", this.pointerMoveHandler as (e: TouchEvent) => void, {
|
||||
passive: false,
|
||||
});
|
||||
this.ownerDocument.addEventListener(
|
||||
"touchmove",
|
||||
this.pointerMoveHandler as (e: TouchEvent) => void,
|
||||
{
|
||||
passive: false,
|
||||
},
|
||||
);
|
||||
this.ownerDocument.addEventListener("touchend", this.pointerUpHandler);
|
||||
this.ownerDocument.addEventListener("touchcancel", this.pointerUpHandler);
|
||||
} else {
|
||||
@@ -136,11 +161,15 @@ export class FloatingModal extends Modal {
|
||||
this.dragging = true;
|
||||
const { modalEl } = this;
|
||||
const pointerEvent = e as PointerEvent;
|
||||
this.offsetX = pointerEvent.clientX - modalEl.getBoundingClientRect().left;
|
||||
this.offsetX =
|
||||
pointerEvent.clientX - modalEl.getBoundingClientRect().left;
|
||||
this.offsetY = pointerEvent.clientY - modalEl.getBoundingClientRect().top;
|
||||
|
||||
// Add pointer-specific event listeners
|
||||
this.ownerDocument.addEventListener("pointermove", this.pointerMoveHandler as (e: PointerEvent) => void);
|
||||
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);
|
||||
@@ -148,21 +177,33 @@ export class FloatingModal extends Modal {
|
||||
}
|
||||
|
||||
private handlePointerMove(e: PointerEvent | TouchEvent): void {
|
||||
if (!this.dragging) return;
|
||||
if (!this.dragging) {
|
||||
return;
|
||||
}
|
||||
const { modalEl } = this;
|
||||
|
||||
// Prevent default behavior
|
||||
e.preventDefault();
|
||||
if (e.type === "touchmove") e.stopPropagation();
|
||||
if (e.type === "touchmove") {
|
||||
e.stopPropagation();
|
||||
}
|
||||
|
||||
const { clientX, clientY } = (e.type === "touchmove") ?
|
||||
(e as TouchEvent).touches[0] : e as PointerEvent;
|
||||
const { clientX, clientY } =
|
||||
e.type === "touchmove"
|
||||
? (e as TouchEvent).touches[0]
|
||||
: (e as PointerEvent);
|
||||
|
||||
// Prevent moving the modal offscreen
|
||||
const { width, height } = modalEl.getBoundingClientRect();
|
||||
const margin = 8;
|
||||
const x = clamp(clientX - this.offsetX, [margin, this.ownerWindow.innerWidth - width - margin]);
|
||||
const y = clamp(clientY - this.offsetY, [margin, this.ownerWindow.innerHeight - height - margin]);
|
||||
const x = clamp(clientX - this.offsetX, [
|
||||
margin,
|
||||
this.ownerWindow.innerWidth - width - margin,
|
||||
]);
|
||||
const y = clamp(clientY - this.offsetY, [
|
||||
margin,
|
||||
this.ownerWindow.innerHeight - height - margin,
|
||||
]);
|
||||
|
||||
// Position the modal element
|
||||
modalEl.style.left = `${x}px`;
|
||||
@@ -172,11 +213,20 @@ export class FloatingModal extends Modal {
|
||||
private handlePointerUp(): void {
|
||||
this.dragging = false;
|
||||
// Remove all event listeners
|
||||
this.ownerDocument.removeEventListener("pointermove", this.pointerMoveHandler as (e: PointerEvent) => void);
|
||||
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(
|
||||
"touchmove",
|
||||
this.pointerMoveHandler as (e: TouchEvent) => void,
|
||||
);
|
||||
this.ownerDocument.removeEventListener("touchend", this.pointerUpHandler);
|
||||
this.ownerDocument.removeEventListener("touchcancel", this.pointerUpHandler);
|
||||
this.ownerDocument.removeEventListener(
|
||||
"touchcancel",
|
||||
this.pointerUpHandler,
|
||||
);
|
||||
}
|
||||
|
||||
open(): void {
|
||||
@@ -185,19 +235,18 @@ export class FloatingModal extends Modal {
|
||||
this.ownerWindow = this.ownerDocument.defaultView ?? window;
|
||||
// NEW: capture previously focused element & release Obsidian modal key trapping
|
||||
if (this.disableKeyCapture) {
|
||||
this.previousActive = this.ownerDocument.activeElement as HTMLElement | null;
|
||||
this.previousActive = this.ownerDocument
|
||||
.activeElement as HTMLElement | null;
|
||||
try {
|
||||
// Release modal scope so focus and key handling can return to the workspace.
|
||||
// @ts-ignore
|
||||
this.app.keymap.popScope(this.scope);
|
||||
} catch {}
|
||||
// prevent automatic selection / focus restoration
|
||||
this.shouldRestoreSelection = false;
|
||||
}
|
||||
setTimeout(() => {
|
||||
// @ts-ignore
|
||||
window.setTimeout(() => {
|
||||
const { containerEl, modalEl, bgEl } = this;
|
||||
containerEl.addClass("mod-excalidraw-draggable")
|
||||
containerEl.addClass("mod-excalidraw-draggable");
|
||||
|
||||
// Set initial position and make modal draggable
|
||||
if (modalEl) {
|
||||
@@ -215,10 +264,17 @@ export class FloatingModal extends Modal {
|
||||
modalEl.style.transform = "none";
|
||||
|
||||
// Add event listeners for both pointer and touch events
|
||||
modalEl.addEventListener("pointerdown", this.pointerDownHandler as (e: PointerEvent) => void);
|
||||
modalEl.addEventListener("touchstart", this.pointerDownHandler as (e: TouchEvent) => void, {
|
||||
passive: false,
|
||||
});
|
||||
modalEl.addEventListener(
|
||||
"pointerdown",
|
||||
this.pointerDownHandler as (e: PointerEvent) => void,
|
||||
);
|
||||
modalEl.addEventListener(
|
||||
"touchstart",
|
||||
this.pointerDownHandler as (e: TouchEvent) => void,
|
||||
{
|
||||
passive: false,
|
||||
},
|
||||
);
|
||||
|
||||
if (this.disableKeyCapture) {
|
||||
// Prevent the modal from stealing focus
|
||||
@@ -227,14 +283,18 @@ export class FloatingModal extends Modal {
|
||||
// In order to propagate keypresses, modal container and backdrop
|
||||
// need to ignore (and thus propagate) any pointerEvents.
|
||||
containerEl.style.pointerEvents = "none";
|
||||
if (bgEl) bgEl.style.pointerEvents = "none";
|
||||
if (bgEl) {
|
||||
bgEl.style.pointerEvents = "none";
|
||||
}
|
||||
|
||||
// Refocus previous element (if still in DOM)
|
||||
if (this.previousActive?.isConnected) {
|
||||
this.previousActive.focus({ preventScroll: true });
|
||||
}
|
||||
// Stop key events originating inside the modal from bubbling back
|
||||
modalEl.addEventListener("keydown", this.modalKeydownStopHandler, { capture: true });
|
||||
modalEl.addEventListener("keydown", this.modalKeydownStopHandler, {
|
||||
capture: true,
|
||||
});
|
||||
}
|
||||
|
||||
// NEW: re-enable pointer events on the close button so it is tappable on mobile
|
||||
@@ -248,16 +308,30 @@ export class FloatingModal extends Modal {
|
||||
|
||||
close(): void {
|
||||
// Optional: restore previous focus if body ended up focused
|
||||
if (this.disableKeyCapture && this.previousActive?.isConnected && this.ownerDocument.activeElement === this.ownerDocument.body) {
|
||||
try { this.previousActive.focus({ preventScroll: true }); } catch {}
|
||||
if (
|
||||
this.disableKeyCapture &&
|
||||
this.previousActive?.isConnected &&
|
||||
this.ownerDocument.activeElement === this.ownerDocument.body
|
||||
) {
|
||||
try {
|
||||
this.previousActive.focus({ preventScroll: true });
|
||||
} catch {}
|
||||
}
|
||||
const { modalEl } = this;
|
||||
// Clean up event listeners
|
||||
if (modalEl) {
|
||||
modalEl.removeEventListener("pointerdown", this.pointerDownHandler as (e: PointerEvent) => void);
|
||||
modalEl.removeEventListener("touchstart", this.pointerDownHandler as (e: TouchEvent) => void);
|
||||
modalEl.removeEventListener(
|
||||
"pointerdown",
|
||||
this.pointerDownHandler as (e: PointerEvent) => void,
|
||||
);
|
||||
modalEl.removeEventListener(
|
||||
"touchstart",
|
||||
this.pointerDownHandler as (e: TouchEvent) => void,
|
||||
);
|
||||
// Remove the capturing keydown stopper if it was added
|
||||
modalEl.removeEventListener("keydown", this.modalKeydownStopHandler, { capture: true });
|
||||
modalEl.removeEventListener("keydown", this.modalKeydownStopHandler, {
|
||||
capture: true,
|
||||
});
|
||||
}
|
||||
// Remove any remaining document event listeners
|
||||
this.handlePointerUp();
|
||||
@@ -266,6 +340,10 @@ export class FloatingModal extends Modal {
|
||||
}
|
||||
|
||||
// (Optional helper if you want to toggle later)
|
||||
enableKeyCapture() { this.disableKeyCapture = false; }
|
||||
disableKeyCaptureFn() { this.disableKeyCapture = true; }
|
||||
}
|
||||
enableKeyCapture() {
|
||||
this.disableKeyCapture = false;
|
||||
}
|
||||
disableKeyCaptureFn() {
|
||||
this.disableKeyCapture = true;
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,3 @@
|
||||
import { ExcalidrawAutomate } from "src/shared/ExcalidrawAutomate";
|
||||
import { t } from "src/lang/helpers";
|
||||
import { CaptureUpdateAction } from "src/constants/constants";
|
||||
import { FloatingModal } from "./FloatingModal";
|
||||
@@ -6,50 +5,60 @@ import ExcalidrawView from "src/view/ExcalidrawView";
|
||||
import { Setting } from "obsidian";
|
||||
|
||||
export const showFrameSettings = (view: ExcalidrawView) => {
|
||||
const {enabled, clip, name, outline, markerName, markerEnabled} = view.excalidrawAPI.getAppState().frameRendering;
|
||||
|
||||
const { enabled, clip, name, outline, markerName, markerEnabled } =
|
||||
view.excalidrawAPI.getAppState().frameRendering;
|
||||
|
||||
// Create modal dialog
|
||||
const frameSettingsModal = new FloatingModal(view.app);
|
||||
|
||||
|
||||
frameSettingsModal.onOpen = () => {
|
||||
const {contentEl} = frameSettingsModal;
|
||||
|
||||
contentEl.createEl("h1", {text: t("FRAME_SETTINGS_TITLE")});
|
||||
|
||||
const settings = { enabled, clip, name, outline, markerName, markerEnabled };
|
||||
const { contentEl } = frameSettingsModal;
|
||||
|
||||
contentEl.createEl("h1", { text: t("FRAME_SETTINGS_TITLE") });
|
||||
|
||||
const settings = {
|
||||
enabled,
|
||||
clip,
|
||||
name,
|
||||
outline,
|
||||
markerName,
|
||||
markerEnabled,
|
||||
};
|
||||
|
||||
// Add toggles
|
||||
new Setting(contentEl)
|
||||
.setName(t("FRAME_SETTINGS_ENABLE"))
|
||||
.addToggle(toggle => toggle
|
||||
.setValue(settings.enabled)
|
||||
.onChange(value => {
|
||||
.addToggle((toggle) =>
|
||||
toggle.setValue(settings.enabled).onChange((value) => {
|
||||
settings.enabled = value;
|
||||
hideComponent(displayFrameNameSetting, !value);
|
||||
hideComponent(displayFrameOutlineSetting, !value);
|
||||
hideComponent(enableFrameClippingSetting, !value);
|
||||
})
|
||||
}),
|
||||
);
|
||||
|
||||
const displayFrameNameSetting = new Setting(contentEl)
|
||||
.setName(t("FRAME_SETTIGNS_NAME"))
|
||||
.addToggle(toggle => toggle
|
||||
.setValue(settings.name)
|
||||
.onChange(value => settings.name = value)
|
||||
.addToggle((toggle) =>
|
||||
toggle
|
||||
.setValue(settings.name)
|
||||
.onChange((value) => (settings.name = value)),
|
||||
);
|
||||
|
||||
const displayFrameOutlineSetting = new Setting(contentEl)
|
||||
.setName(t("FRAME_SETTINGS_OUTLINE"))
|
||||
.addToggle(toggle => toggle
|
||||
.setValue(settings.outline)
|
||||
.onChange(value => settings.outline = value)
|
||||
.addToggle((toggle) =>
|
||||
toggle
|
||||
.setValue(settings.outline)
|
||||
.onChange((value) => (settings.outline = value)),
|
||||
);
|
||||
|
||||
const enableFrameClippingSetting = new Setting(contentEl)
|
||||
.setName(t("FRAME_SETTINGS_CLIP"))
|
||||
.addToggle(toggle => toggle
|
||||
.setValue(settings.clip)
|
||||
.onChange(value => settings.clip = value)
|
||||
.addToggle((toggle) =>
|
||||
toggle
|
||||
.setValue(settings.clip)
|
||||
.onChange((value) => (settings.clip = value)),
|
||||
);
|
||||
|
||||
// Hide or show components based on initial state
|
||||
@@ -58,27 +67,24 @@ export const showFrameSettings = (view: ExcalidrawView) => {
|
||||
hideComponent(enableFrameClippingSetting, !settings.enabled);
|
||||
|
||||
// Add OK button
|
||||
new Setting(contentEl)
|
||||
.addButton(button => button
|
||||
.setButtonText("OK")
|
||||
.onClick(() => {
|
||||
// Update appState with new settings
|
||||
view.updateScene({
|
||||
// @ts-ignore
|
||||
appState: {
|
||||
frameRendering: settings
|
||||
},
|
||||
captureUpdate: CaptureUpdateAction.NEVER,
|
||||
});
|
||||
frameSettingsModal.close();
|
||||
})
|
||||
);
|
||||
new Setting(contentEl).addButton((button) =>
|
||||
button.setButtonText("OK").onClick(() => {
|
||||
// Update appState with new settings
|
||||
view.updateScene({
|
||||
appState: {
|
||||
frameRendering: settings,
|
||||
},
|
||||
captureUpdate: CaptureUpdateAction.NEVER,
|
||||
});
|
||||
frameSettingsModal.close();
|
||||
}),
|
||||
);
|
||||
};
|
||||
|
||||
frameSettingsModal.open();
|
||||
};
|
||||
|
||||
// Function to hide or show a component
|
||||
function hideComponent(comp:any, value:any) {
|
||||
function hideComponent(comp: Setting, value: boolean) {
|
||||
comp.settingEl.style.display = value ? "none" : "";
|
||||
}
|
||||
@@ -1,9 +1,9 @@
|
||||
import { BaseComponent, Setting, Modifier } from 'obsidian';
|
||||
import { DEVICE } from 'src/constants/constants';
|
||||
import { t } from 'src/lang/helpers';
|
||||
import { ExcalidrawSettings } from 'src/core/settings';
|
||||
import { modifierLabel } from 'src/utils/modifierkeyHelper';
|
||||
import { fragWithHTML } from 'src/utils/utils';
|
||||
import { BaseComponent, Setting, Modifier } from "obsidian";
|
||||
import { DEVICE } from "src/constants/constants";
|
||||
import { t } from "src/lang/helpers";
|
||||
import { ExcalidrawSettings } from "src/core/settings";
|
||||
import { modifierLabel } from "src/utils/modifierkeyHelper";
|
||||
import { fragWithHTML } from "src/utils/utils";
|
||||
|
||||
export class HotkeyEditor extends BaseComponent {
|
||||
private settings: ExcalidrawSettings;
|
||||
@@ -11,13 +11,17 @@ export class HotkeyEditor extends BaseComponent {
|
||||
private capturing: boolean = false;
|
||||
private activeModifiers: Modifier[] = [];
|
||||
public isDirty: boolean = false;
|
||||
private applySettingsUpdate: Function;
|
||||
private applySettingsUpdate: () => void;
|
||||
|
||||
// Store bound event handlers
|
||||
private boundKeydownHandler: (event: KeyboardEvent) => void;
|
||||
private boundKeyupHandler: (event: KeyboardEvent) => void;
|
||||
|
||||
constructor(containerEl: HTMLElement, settings: ExcalidrawSettings, applySettingsUpdate: Function) {
|
||||
constructor(
|
||||
containerEl: HTMLElement,
|
||||
settings: ExcalidrawSettings,
|
||||
applySettingsUpdate: () => void,
|
||||
) {
|
||||
super();
|
||||
this.containerEl = containerEl.createDiv();
|
||||
this.settings = settings;
|
||||
@@ -40,9 +44,13 @@ export class HotkeyEditor extends BaseComponent {
|
||||
this.settings.modifierKeyOverrides.forEach((override, index) => {
|
||||
const key = override.key.toUpperCase();
|
||||
new Setting(this.containerEl)
|
||||
.setDesc(fragWithHTML(`<b>Code:</b> <kbd>${override.modifiers.join("+")} + ${key}</kbd> | ` +
|
||||
`<b>Apple:</b> <kbd>${modifierLabel(override.modifiers, "Mac")} + ${key}</kbd> | ` +
|
||||
`<b>Windows:</b> <kbd>${modifierLabel(override.modifiers, "Other")} + ${key}</kbd>`))
|
||||
.setDesc(
|
||||
fragWithHTML(
|
||||
`<b>Code:</b> <kbd>${override.modifiers.join("+")} + ${key}</kbd> | ` +
|
||||
`<b>Apple:</b> <kbd>${modifierLabel(override.modifiers, "Mac")} + ${key}</kbd> | ` +
|
||||
`<b>Windows:</b> <kbd>${modifierLabel(override.modifiers, "Other")} + ${key}</kbd>`,
|
||||
),
|
||||
)
|
||||
.addButton((button) =>
|
||||
button
|
||||
.setButtonText(t("HOTKEY_BUTTON_REMOVE"))
|
||||
@@ -52,7 +60,7 @@ export class HotkeyEditor extends BaseComponent {
|
||||
this.isDirty = true;
|
||||
this.applySettingsUpdate();
|
||||
this.render();
|
||||
})
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
@@ -60,16 +68,15 @@ export class HotkeyEditor extends BaseComponent {
|
||||
if (this.capturing) {
|
||||
new Setting(this.containerEl)
|
||||
.setName(t("HOTKEY_PRESS_COMBO_NANE"))
|
||||
.setDesc(t("HOTKEY_PRESS_COMBO_DESC"))
|
||||
.controlEl.style.cursor = 'pointer';
|
||||
.setDesc(t("HOTKEY_PRESS_COMBO_DESC")).controlEl.style.cursor =
|
||||
"pointer";
|
||||
} else {
|
||||
new Setting(this.containerEl)
|
||||
.addButton((button) =>
|
||||
button
|
||||
.setButtonText(t("HOTKEY_BUTTON_ADD_OVERRIDE"))
|
||||
.setCta()
|
||||
.onClick(() => this.startCapture())
|
||||
);
|
||||
new Setting(this.containerEl).addButton((button) =>
|
||||
button
|
||||
.setButtonText(t("HOTKEY_BUTTON_ADD_OVERRIDE"))
|
||||
.setCta()
|
||||
.onClick(() => this.startCapture()),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -78,8 +85,8 @@ export class HotkeyEditor extends BaseComponent {
|
||||
this.activeModifiers = [];
|
||||
this.render();
|
||||
// Use the pre-bound handlers
|
||||
window.addEventListener('keydown', this.boundKeydownHandler);
|
||||
window.addEventListener('keyup', this.boundKeyupHandler);
|
||||
window.addEventListener("keydown", this.boundKeydownHandler);
|
||||
window.addEventListener("keyup", this.boundKeyupHandler);
|
||||
}
|
||||
|
||||
private onKeydown(event: KeyboardEvent): void {
|
||||
@@ -89,7 +96,7 @@ export class HotkeyEditor extends BaseComponent {
|
||||
const modifiers = this.getModifiersFromEvent(event);
|
||||
|
||||
// If only modifiers are pressed, update activeModifiers and continue listening
|
||||
if (['Control', 'Shift', 'Alt', 'Meta'].includes(event.key)) {
|
||||
if (["Control", "Shift", "Alt", "Meta"].includes(event.key)) {
|
||||
this.activeModifiers = modifiers;
|
||||
return;
|
||||
}
|
||||
@@ -101,7 +108,7 @@ export class HotkeyEditor extends BaseComponent {
|
||||
(override) =>
|
||||
override.key === key &&
|
||||
override.modifiers.length === modifiers.length &&
|
||||
override.modifiers.every((mod) => modifiers.includes(mod))
|
||||
override.modifiers.every((mod) => modifiers.includes(mod)),
|
||||
);
|
||||
|
||||
if (!exists) {
|
||||
@@ -123,8 +130,8 @@ export class HotkeyEditor extends BaseComponent {
|
||||
private stopCapture(): void {
|
||||
this.capturing = false;
|
||||
// Use the pre-bound handlers for removal
|
||||
window.removeEventListener('keydown', this.boundKeydownHandler);
|
||||
window.removeEventListener('keyup', this.boundKeyupHandler);
|
||||
window.removeEventListener("keydown", this.boundKeydownHandler);
|
||||
window.removeEventListener("keyup", this.boundKeyupHandler);
|
||||
this.render();
|
||||
}
|
||||
|
||||
@@ -137,24 +144,24 @@ export class HotkeyEditor extends BaseComponent {
|
||||
const modifiers: Modifier[] = [];
|
||||
|
||||
if (DEVICE.isMacOS && event.metaKey) {
|
||||
modifiers.push('Mod');
|
||||
modifiers.push("Mod");
|
||||
} else if (!DEVICE.isMacOS && event.ctrlKey) {
|
||||
modifiers.push('Mod');
|
||||
modifiers.push("Mod");
|
||||
}
|
||||
|
||||
if (DEVICE.isMacOS && event.ctrlKey) {
|
||||
modifiers.push('Ctrl');
|
||||
modifiers.push("Ctrl");
|
||||
}
|
||||
|
||||
if (!DEVICE.isMacOS && event.metaKey) {
|
||||
modifiers.push('Meta');
|
||||
modifiers.push("Meta");
|
||||
}
|
||||
|
||||
if (event.shiftKey) {
|
||||
modifiers.push('Shift');
|
||||
modifiers.push("Shift");
|
||||
}
|
||||
if (event.altKey) {
|
||||
modifiers.push('Alt');
|
||||
modifiers.push("Alt");
|
||||
}
|
||||
|
||||
return modifiers;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { App, FuzzySuggestModal, TFile } from "obsidian";
|
||||
import { FuzzySuggestModal, TFile } from "obsidian";
|
||||
import { REG_LINKINDEX_INVALIDCHARS } from "../../constants/constants";
|
||||
import ExcalidrawView from "../../view/ExcalidrawView";
|
||||
import { t } from "../../lang/helpers";
|
||||
@@ -33,7 +33,8 @@ export class ImportSVGDialog extends FuzzySuggestModal<TFile> {
|
||||
|
||||
getItems(): TFile[] {
|
||||
return (this.app.vault.getFiles() || []).filter(
|
||||
(f: TFile) => f.extension === "svg" &&
|
||||
(f: TFile) =>
|
||||
f.extension === "svg" &&
|
||||
//https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/422
|
||||
!f.path.match(REG_LINKINDEX_INVALIDCHARS),
|
||||
);
|
||||
@@ -44,13 +45,17 @@ export class ImportSVGDialog extends FuzzySuggestModal<TFile> {
|
||||
}
|
||||
|
||||
async onChooseItem(item: TFile, _: KeyboardEvent): Promise<void> {
|
||||
if(!item) return;
|
||||
const ea = getEA(this.view) as ExcalidrawAutomate;
|
||||
if (!item) {
|
||||
return;
|
||||
}
|
||||
const ea = getEA(this.view);
|
||||
const svg = await this.app.vault.read(item);
|
||||
if(!svg || svg === "") return;
|
||||
if (!svg || svg === "") {
|
||||
return;
|
||||
}
|
||||
ea.importSVG(svg);
|
||||
ea.addToGroup(ea.getElements().map(el=>el.id));
|
||||
await ea.addElementsToView(true, true, true,true);
|
||||
ea.addToGroup(ea.getElements().map((el) => el.id));
|
||||
await ea.addElementsToView(true, true, true, true);
|
||||
ea.destroy();
|
||||
}
|
||||
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import { App, FuzzySuggestModal, TFile } from "obsidian";
|
||||
import { App, FuzzySuggestModal } from "obsidian";
|
||||
import { t } from "../../lang/helpers";
|
||||
import type { ObsidianCommand } from "src/types/types";
|
||||
|
||||
export class InsertCommandDialog extends FuzzySuggestModal<TFile> {
|
||||
private addText: Function;
|
||||
export class InsertCommandDialog extends FuzzySuggestModal<ObsidianCommand> {
|
||||
private addText: ((value: string) => void) | null = null;
|
||||
|
||||
destroy() {
|
||||
this.app = null;
|
||||
@@ -23,30 +24,28 @@ export class InsertCommandDialog extends FuzzySuggestModal<TFile> {
|
||||
this.emptyStateText = t("NO_MATCHING_COMMAND");
|
||||
}
|
||||
|
||||
getItems(): any[] {
|
||||
//@ts-ignore
|
||||
getItems(): ObsidianCommand[] {
|
||||
return this.app.commands.listCommands();
|
||||
}
|
||||
|
||||
getItemText(item: any): string {
|
||||
getItemText(item: ObsidianCommand): string {
|
||||
return item.name;
|
||||
}
|
||||
|
||||
onChooseItem(item: any): void {
|
||||
const cmdId = item?.id;
|
||||
this.addText(`⚙️[${item.name}](cmd://${item.id})`);
|
||||
onChooseItem(item: ObsidianCommand): void {
|
||||
this.addText?.(`⚙️[${item.name}](cmd://${item.id})`);
|
||||
this.addText = null;
|
||||
}
|
||||
|
||||
public start(addText: Function) {
|
||||
public start(addText: (value: string) => void) {
|
||||
this.addText = addText;
|
||||
this.open();
|
||||
}
|
||||
|
||||
onClose(): void {
|
||||
window.setTimeout(()=>{
|
||||
window.setTimeout(() => {
|
||||
this.addText = null;
|
||||
}) //onChooseItem must run first
|
||||
}); //onChooseItem must run first
|
||||
super.onClose();
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,10 @@
|
||||
import { FuzzySuggestModal, TFile } from "obsidian";
|
||||
import { scaleToFullsizeModifier } from "src/utils/modifierkeyHelper";
|
||||
import { DEVICE, IMAGE_TYPES, REG_LINKINDEX_INVALIDCHARS } from "../../constants/constants";
|
||||
import {
|
||||
DEVICE,
|
||||
IMAGE_TYPES,
|
||||
REG_LINKINDEX_INVALIDCHARS,
|
||||
} from "../../constants/constants";
|
||||
import ExcalidrawView from "../../view/ExcalidrawView";
|
||||
import { t } from "../../lang/helpers";
|
||||
import ExcalidrawPlugin from "../../core/main";
|
||||
@@ -39,20 +43,22 @@ export class InsertImageDialog extends FuzzySuggestModal<TFile> {
|
||||
this.setPlaceholder(t("SELECT_DRAWING"));
|
||||
this.emptyStateText = t("NO_MATCH");
|
||||
this.inputEl.onkeyup = (e) => {
|
||||
//@ts-ignore
|
||||
if (e.key === "Enter" && scaleToFullsizeModifier(e) && this.chooser.values) {
|
||||
if (
|
||||
e.key === "Enter" &&
|
||||
scaleToFullsizeModifier(e) &&
|
||||
this.chooser.values
|
||||
) {
|
||||
this.onChooseItem(
|
||||
//@ts-ignore
|
||||
this.chooser.values[this.chooser.selectedItem].item,
|
||||
new KeyboardEvent("keypress",{
|
||||
new KeyboardEvent("keypress", {
|
||||
shiftKey: true,
|
||||
metaKey: !(DEVICE.isIOS || DEVICE.isMacOS),
|
||||
ctrlKey: (DEVICE.isIOS || DEVICE.isMacOS),
|
||||
})
|
||||
ctrlKey: DEVICE.isIOS || DEVICE.isMacOS,
|
||||
}),
|
||||
);
|
||||
this.close();
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
getItems(): TFile[] {
|
||||
@@ -73,7 +79,7 @@ export class InsertImageDialog extends FuzzySuggestModal<TFile> {
|
||||
const ea = getEA(this.view);
|
||||
ea.canvas.theme = this.view.excalidrawAPI.getAppState().theme;
|
||||
const scaleToFullsize = scaleToFullsizeModifier(event);
|
||||
(async () => {
|
||||
void (async () => {
|
||||
//this.view.currentPosition = this.position;
|
||||
await ea.addImage(0, 0, item, !scaleToFullsize);
|
||||
await ea.addElementsToView(true, true, true);
|
||||
|
||||
@@ -3,11 +3,16 @@ 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";
|
||||
|
||||
import {
|
||||
getLinkSuggestionsFiltered,
|
||||
getSortedLinkMatches,
|
||||
renderLinkSuggestion,
|
||||
} from "src/shared/Suggesters/LinkSuggesterUtils";
|
||||
|
||||
export class InsertLinkDialog extends FuzzySuggestModal<LinkSuggestion> {
|
||||
private addText: Function;
|
||||
private addText:
|
||||
| ((markdownlink: string, path?: string, alias?: string) => void)
|
||||
| null;
|
||||
private drawingPath: string;
|
||||
|
||||
destroy() {
|
||||
@@ -48,8 +53,11 @@ export class InsertLinkDialog extends FuzzySuggestModal<LinkSuggestion> {
|
||||
true,
|
||||
);
|
||||
}
|
||||
const link = getLink(this.plugin,{embed: false, path: filepath, alias: item.alias});
|
||||
this.addText(getLink(this.plugin,{embed: false, path: filepath, alias: item.alias}), filepath, item.alias);
|
||||
this.addText(
|
||||
getLink(this.plugin, { embed: false, path: filepath, alias: item.alias }),
|
||||
filepath,
|
||||
item.alias,
|
||||
);
|
||||
}
|
||||
|
||||
renderSuggestion(result: FuzzyMatch<LinkSuggestion>, itemEl: HTMLElement) {
|
||||
@@ -61,22 +69,26 @@ export class InsertLinkDialog extends FuzzySuggestModal<LinkSuggestion> {
|
||||
}
|
||||
|
||||
onClose(): void {
|
||||
window.setTimeout(()=>{
|
||||
this.addText = null
|
||||
window.setTimeout(() => {
|
||||
this.addText = null;
|
||||
}); //make sure this happens after onChooseItem runs
|
||||
super.onClose();
|
||||
}
|
||||
|
||||
private inLink: string;
|
||||
onOpen(): void {
|
||||
super.onOpen();
|
||||
if(this.inLink) {
|
||||
void super.onOpen();
|
||||
if (this.inLink) {
|
||||
this.inputEl.value = this.inLink;
|
||||
this.inputEl.dispatchEvent(new Event('input'));
|
||||
this.inputEl.dispatchEvent(new Event("input"));
|
||||
}
|
||||
}
|
||||
|
||||
public start(drawingPath: string, addText: Function, link?: string) {
|
||||
public start(
|
||||
drawingPath: string,
|
||||
addText: (markdownlink: string, path?: string, alias?: string) => void,
|
||||
link?: string,
|
||||
) {
|
||||
this.addText = addText;
|
||||
this.drawingPath = drawingPath;
|
||||
this.inLink = link;
|
||||
|
||||
@@ -41,7 +41,7 @@ export class InsertMDDialog extends FuzzySuggestModal<TFile> {
|
||||
|
||||
onChooseItem(item: TFile): void {
|
||||
const ea = getEA(this.view);
|
||||
(async () => {
|
||||
void (async () => {
|
||||
await ea.addImage(0, 0, item);
|
||||
await ea.addElementsToView(true, false, true);
|
||||
ea.destroy();
|
||||
|
||||
@@ -2,25 +2,29 @@ import { ButtonComponent, TFile, ToggleComponent } from "obsidian";
|
||||
import ExcalidrawView from "../../view/ExcalidrawView";
|
||||
import ExcalidrawPlugin from "../../core/main";
|
||||
import { getPDFDoc } from "src/utils/fileUtils";
|
||||
import { Modal, Setting, TextComponent } from "obsidian";
|
||||
import { Modal, Setting, TextComponent } from "obsidian";
|
||||
import { FileSuggestionModal } from "../Suggesters/FileSuggestionModal";
|
||||
import { getEA } from "src/core";
|
||||
import { ExcalidrawAutomate } from "src/shared/ExcalidrawAutomate";
|
||||
import { ExcalidrawImperativeAPI } from "@zsviczian/excalidraw/types/excalidraw/types";
|
||||
import { t } from "src/lang/helpers";
|
||||
import { setSanitizedHtml } from "src/utils/htmlUtils";
|
||||
|
||||
export class InsertPDFModal extends Modal {
|
||||
private borderBox: boolean = true;
|
||||
private frame: boolean = false;
|
||||
private gapSize:number = 20;
|
||||
private gapSize: number = 20;
|
||||
private groupPages: boolean = false;
|
||||
private direction: "down" | "right" = "right";
|
||||
private numColumns: number = 1;
|
||||
private numRows: number = 1;
|
||||
private lockAfterImport: boolean = true;
|
||||
private pagesToImport:number[] = [];
|
||||
private pageDimensions: {width: number, height: number} = {width: 0, height: 0};
|
||||
private pageDimensionsByPage: Map<number, {width: number; height: number}> = new Map();
|
||||
private pagesToImport: number[] = [];
|
||||
private pageDimensions: { width: number; height: number } = {
|
||||
width: 0,
|
||||
height: 0,
|
||||
};
|
||||
private pageDimensionsByPage: Map<number, { width: number; height: number }> =
|
||||
new Map();
|
||||
private importScale = 0.3;
|
||||
private imageSizeMessage: HTMLElement;
|
||||
private pdfDoc: any;
|
||||
@@ -34,8 +38,8 @@ export class InsertPDFModal extends Modal {
|
||||
super(plugin.app);
|
||||
}
|
||||
|
||||
open (file?: TFile) {
|
||||
if(file && file.extension.toLowerCase() === "pdf") {
|
||||
open(file?: TFile) {
|
||||
if (file && file.extension.toLowerCase() === "pdf") {
|
||||
this.pdfFile = file;
|
||||
}
|
||||
super.open();
|
||||
@@ -44,11 +48,11 @@ export class InsertPDFModal extends Modal {
|
||||
onOpen(): void {
|
||||
this.containerEl.classList.add("excalidraw-release");
|
||||
this.titleEl.setText(`Import PDF`);
|
||||
this.createForm();
|
||||
void this.createForm();
|
||||
}
|
||||
|
||||
async onClose() {
|
||||
if(this.dirty) {
|
||||
if (this.dirty) {
|
||||
this.plugin.settings.pdfImportScale = this.importScale;
|
||||
this.plugin.settings.pdfBorderBox = this.borderBox;
|
||||
this.plugin.settings.pdfFrame = this.frame;
|
||||
@@ -60,7 +64,7 @@ export class InsertPDFModal extends Modal {
|
||||
this.plugin.settings.pdfLockAfterImport = this.lockAfterImport;
|
||||
await this.plugin.saveSettings();
|
||||
}
|
||||
if(this.pdfDoc) {
|
||||
if (this.pdfDoc) {
|
||||
this.pdfDoc.destroy();
|
||||
this.pdfDoc = null;
|
||||
}
|
||||
@@ -69,20 +73,27 @@ export class InsertPDFModal extends Modal {
|
||||
this.view = null;
|
||||
this.app = null;
|
||||
this.imageSizeMessage.remove();
|
||||
this.setImageSizeMessage = null;
|
||||
this.setImageSizeMessage = null;
|
||||
}
|
||||
|
||||
private async loadPageDimensions(pages?: number[]) {
|
||||
if(!this.pdfDoc) return;
|
||||
if (!this.pdfDoc) {
|
||||
return;
|
||||
}
|
||||
const scale = this.plugin.settings.pdfScale;
|
||||
const pagesToLoad = pages && pages.length > 0 ? [...new Set(pages)] : [1];
|
||||
for (const pageNum of pagesToLoad) {
|
||||
if(this.pageDimensionsByPage.has(pageNum)) continue;
|
||||
if (this.pageDimensionsByPage.has(pageNum)) {
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
const page = await this.pdfDoc.getPage(pageNum);
|
||||
const viewport = page.getViewport({ scale });
|
||||
this.pageDimensionsByPage.set(pageNum, { width: viewport.width, height: viewport.height });
|
||||
} catch(e) {
|
||||
this.pageDimensionsByPage.set(pageNum, {
|
||||
width: viewport.width,
|
||||
height: viewport.height,
|
||||
});
|
||||
} catch (e) {
|
||||
console.log(e);
|
||||
}
|
||||
}
|
||||
@@ -93,18 +104,21 @@ export class InsertPDFModal extends Modal {
|
||||
private getMaxSelectedPageDimensions() {
|
||||
let width = 0;
|
||||
let height = 0;
|
||||
const pages = this.pagesToImport.length > 0
|
||||
? this.pagesToImport
|
||||
: Array.from(this.pageDimensionsByPage.keys());
|
||||
const pages =
|
||||
this.pagesToImport.length > 0
|
||||
? this.pagesToImport
|
||||
: Array.from(this.pageDimensionsByPage.keys());
|
||||
pages.forEach((p) => {
|
||||
const dims = this.pageDimensionsByPage.get(p);
|
||||
if(!dims) return;
|
||||
if (!dims) {
|
||||
return;
|
||||
}
|
||||
width = Math.max(width, dims.width);
|
||||
height = Math.max(height, dims.height);
|
||||
});
|
||||
if(width === 0 || height === 0) {
|
||||
if (width === 0 || height === 0) {
|
||||
const first = this.pageDimensionsByPage.values().next().value;
|
||||
if(first) {
|
||||
if (first) {
|
||||
width = first.width;
|
||||
height = first.height;
|
||||
}
|
||||
@@ -112,28 +126,28 @@ export class InsertPDFModal extends Modal {
|
||||
return { width, height };
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Creates a list of numbers from page ranges representing the pages to import.
|
||||
* sets the pagesToImport property.
|
||||
* @param pageRanges A string representing the pages to import. e.g.: 1,3-5,7,9-10
|
||||
* @returns A list of numbers representing the pages to import.
|
||||
*/
|
||||
private createPageListFromString(pageRanges:string):number[] {
|
||||
const cleanNonDigits = (str:string) => str.replace(/\D/g, "");
|
||||
private createPageListFromString(pageRanges: string): number[] {
|
||||
const cleanNonDigits = (str: string) => str.replace(/\D/g, "");
|
||||
this.pagesToImport = [];
|
||||
const pageRangesArray:string[] = pageRanges.split(",");
|
||||
const pageRangesArray: string[] = pageRanges.split(",");
|
||||
pageRangesArray.forEach((pageRange) => {
|
||||
const pageRangeArray = pageRange.split("-");
|
||||
if(pageRangeArray.length === 1) {
|
||||
if (pageRangeArray.length === 1) {
|
||||
const page = parseInt(cleanNonDigits(pageRangeArray[0]));
|
||||
!isNaN(page) && this.pagesToImport.push(page);
|
||||
} else if(pageRangeArray.length === 2) {
|
||||
|
||||
} else if (pageRangeArray.length === 2) {
|
||||
const start = parseInt(cleanNonDigits(pageRangeArray[0]));
|
||||
const end = parseInt(cleanNonDigits(pageRangeArray[1]));
|
||||
if(isNaN(start) || isNaN(end)) return;
|
||||
for(let i = start; i <= end; i++) {
|
||||
if (isNaN(start) || isNaN(end)) {
|
||||
return;
|
||||
}
|
||||
for (let i = start; i <= end; i++) {
|
||||
this.pagesToImport.push(i);
|
||||
}
|
||||
}
|
||||
@@ -142,9 +156,11 @@ export class InsertPDFModal extends Modal {
|
||||
}
|
||||
|
||||
private setImageSizeMessage = () => {
|
||||
if(!this.imageSizeMessage) return;
|
||||
if (!this.imageSizeMessage) {
|
||||
return;
|
||||
}
|
||||
const dims = this.getMaxSelectedPageDimensions();
|
||||
this.imageSizeMessage.innerText = `${Math.round(dims.width*this.importScale)} x ${Math.round(dims.height*this.importScale)}`;
|
||||
this.imageSizeMessage.innerText = `${Math.round(dims.width * this.importScale)} x ${Math.round(dims.height * this.importScale)}`;
|
||||
};
|
||||
|
||||
async createForm() {
|
||||
@@ -159,77 +175,81 @@ export class InsertPDFModal extends Modal {
|
||||
this.lockAfterImport = this.plugin.settings.pdfLockAfterImport;
|
||||
this.importScale = this.plugin.settings.pdfImportScale;
|
||||
|
||||
const ce = this.contentEl;
|
||||
const ce = this.contentEl;
|
||||
|
||||
|
||||
let numPagesMessage: HTMLParagraphElement;
|
||||
let numPages: number = 0;
|
||||
let importButton: ButtonComponent;
|
||||
let importMessage: HTMLElement;
|
||||
|
||||
|
||||
const importButtonMessages = () => {
|
||||
if(!this.pdfDoc) {
|
||||
if (!this.pdfDoc) {
|
||||
importMessage.innerText = t("IPM_SELECT_PDF");
|
||||
importButton.buttonEl.style.display="none";
|
||||
importButton.buttonEl.style.display = "none";
|
||||
return;
|
||||
}
|
||||
if(this.pagesToImport.length === 0) {
|
||||
importButton.buttonEl.style.display="none";
|
||||
}
|
||||
if (this.pagesToImport.length === 0) {
|
||||
importButton.buttonEl.style.display = "none";
|
||||
importMessage.innerText = t("IPM_SELECT_PAGES_TO_IMPORT");
|
||||
return
|
||||
}
|
||||
if(Math.max(...this.pagesToImport) <= this.pdfDoc.numPages) {
|
||||
importButton.buttonEl.style.display="block";
|
||||
importMessage.innerText = "";
|
||||
return;
|
||||
}
|
||||
else {
|
||||
importButton.buttonEl.style.display="none";
|
||||
if (Math.max(...this.pagesToImport) <= this.pdfDoc.numPages) {
|
||||
importButton.buttonEl.style.display = "block";
|
||||
importMessage.innerText = "";
|
||||
} else {
|
||||
importButton.buttonEl.style.display = "none";
|
||||
importMessage.innerText = `The selected document has ${this.pdfDoc.numPages} pages. Please select pages between 1 and ${this.pdfDoc.numPages}`;
|
||||
return
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const numPagesMessages = () => {
|
||||
if(numPages === 0) {
|
||||
if (numPages === 0) {
|
||||
numPagesMessage.innerText = t("IPM_SELECT_PDF");
|
||||
return;
|
||||
}
|
||||
numPagesMessage.innerHTML = `There are <b>${numPages}</b> pages in the selected document.`;
|
||||
}
|
||||
setSanitizedHtml(
|
||||
numPagesMessage,
|
||||
`There are <b>${numPages}</b> pages in the selected document.`,
|
||||
);
|
||||
};
|
||||
|
||||
let pageRangesTextComponent: TextComponent
|
||||
let importPagesMessage: HTMLParagraphElement;
|
||||
let pageRangesTextComponent: TextComponent;
|
||||
|
||||
const rangeOnChange = async (value:string) => {
|
||||
const rangeOnChange = async (value: string) => {
|
||||
const pages = this.createPageListFromString(value);
|
||||
if(this.pdfDoc && pages.length > 0) {
|
||||
if (this.pdfDoc && pages.length > 0) {
|
||||
await this.loadPageDimensions(pages);
|
||||
} else {
|
||||
this.pageDimensionsByPage.clear();
|
||||
this.pageDimensions = {width: 0, height: 0};
|
||||
this.pageDimensions = { width: 0, height: 0 };
|
||||
this.setImageSizeMessage();
|
||||
}
|
||||
if(pages.length > 15) {
|
||||
importPagesMessage.innerHTML = `You are importing <b>${pages.length}</b> pages. ⚠️ This may take a while. ⚠️`;
|
||||
if (pages.length > 15) {
|
||||
setSanitizedHtml(
|
||||
importPagesMessage,
|
||||
`You are importing <b>${pages.length}</b> pages. ⚠️ This may take a while. ⚠️`,
|
||||
);
|
||||
} else {
|
||||
importPagesMessage.innerHTML = `You are importing <b>${pages.length}</b> pages.`;
|
||||
setSanitizedHtml(
|
||||
importPagesMessage,
|
||||
`You are importing <b>${pages.length}</b> pages.`,
|
||||
);
|
||||
}
|
||||
importButtonMessages();
|
||||
}
|
||||
};
|
||||
|
||||
const setFile = async (file: TFile) => {
|
||||
if(this.pdfDoc) await this.pdfDoc.destroy();
|
||||
if (this.pdfDoc) {
|
||||
await this.pdfDoc.destroy();
|
||||
}
|
||||
this.pdfDoc = null;
|
||||
this.pageDimensionsByPage.clear();
|
||||
this.pageDimensions = {width: 0, height: 0};
|
||||
this.pageDimensions = { width: 0, height: 0 };
|
||||
numPages = 0;
|
||||
this.setImageSizeMessage();
|
||||
|
||||
if(file) {
|
||||
if (file) {
|
||||
this.pdfDoc = await getPDFDoc(file);
|
||||
this.pdfFile = file;
|
||||
if(this.pdfDoc) {
|
||||
if (this.pdfDoc) {
|
||||
numPages = this.pdfDoc.numPages;
|
||||
pageRangesTextComponent.setValue(`1-${numPages}`);
|
||||
await rangeOnChange(`1-${numPages}`);
|
||||
@@ -242,34 +262,37 @@ export class InsertPDFModal extends Modal {
|
||||
importButtonMessages();
|
||||
numPagesMessages();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const search = new TextComponent(ce);
|
||||
search.inputEl.style.width = "100%";
|
||||
const suggester = new FileSuggestionModal(
|
||||
this.app,
|
||||
search,this.app.vault.getFiles().filter((f: TFile) => f.extension.toLowerCase() === "pdf"),
|
||||
this.plugin
|
||||
search,
|
||||
this.app.vault
|
||||
.getFiles()
|
||||
.filter((f: TFile) => f.extension.toLowerCase() === "pdf"),
|
||||
this.plugin,
|
||||
);
|
||||
search.onChange(async () => {
|
||||
const file = suggester.getSelectedItem();
|
||||
await setFile(file);
|
||||
});
|
||||
|
||||
numPagesMessage = ce.createEl("p", {text: ""});
|
||||
|
||||
const numPagesMessage = ce.createEl("p", { text: "" });
|
||||
numPagesMessages();
|
||||
new Setting(ce)
|
||||
.setName(t("IPM_PAGES_TO_IMPORT_NAME"))
|
||||
.setDesc("e.g.: 1,3-5,7,9-10")
|
||||
.addText(text => {
|
||||
.addText((text) => {
|
||||
pageRangesTextComponent = text;
|
||||
text
|
||||
.setValue("")
|
||||
.onChange(async (value) => { await rangeOnChange(value); })
|
||||
text.setValue("").onChange(async (value) => {
|
||||
await rangeOnChange(value);
|
||||
});
|
||||
text.inputEl.style.width = "100%";
|
||||
})
|
||||
importPagesMessage = ce.createEl("p", {text: ""});
|
||||
|
||||
});
|
||||
const importPagesMessage = ce.createEl("p", { text: "" });
|
||||
|
||||
let bbToggle: ToggleComponent;
|
||||
let fToggle: ToggleComponent;
|
||||
let laiToggle: ToggleComponent;
|
||||
@@ -278,68 +301,59 @@ export class InsertPDFModal extends Modal {
|
||||
|
||||
new Setting(ce)
|
||||
.setName(t("IPM_ADD_BORDER_BOX_NAME"))
|
||||
.addToggle(toggle => {
|
||||
.addToggle((toggle) => {
|
||||
bbToggle = toggle;
|
||||
toggle
|
||||
.setValue(this.borderBox)
|
||||
.onChange((value) => {
|
||||
this.borderBox = value;
|
||||
if(value) {
|
||||
this.frame = false;
|
||||
fToggle.setValue(false);
|
||||
}
|
||||
this.dirty = true;
|
||||
})
|
||||
})
|
||||
toggle.setValue(this.borderBox).onChange((value) => {
|
||||
this.borderBox = value;
|
||||
if (value) {
|
||||
this.frame = false;
|
||||
fToggle.setValue(false);
|
||||
}
|
||||
this.dirty = true;
|
||||
});
|
||||
});
|
||||
|
||||
new Setting(ce)
|
||||
.setName(t("IPM_ADD_FRAME_NAME"))
|
||||
.setDesc(t("IPM_ADD_FRAME_DESC"))
|
||||
.addToggle(toggle => {
|
||||
.addToggle((toggle) => {
|
||||
fToggle = toggle;
|
||||
toggle
|
||||
.setValue(this.frame)
|
||||
.onChange((value) => {
|
||||
this.frame = value;
|
||||
if(value) {
|
||||
this.borderBox = false;
|
||||
bbToggle.setValue(false);
|
||||
if(!this.lockAfterImport) {
|
||||
this.lockAfterImport = true;
|
||||
laiToggle.setValue(true);
|
||||
}
|
||||
toggle.setValue(this.frame).onChange((value) => {
|
||||
this.frame = value;
|
||||
if (value) {
|
||||
this.borderBox = false;
|
||||
bbToggle.setValue(false);
|
||||
if (!this.lockAfterImport) {
|
||||
this.lockAfterImport = true;
|
||||
laiToggle.setValue(true);
|
||||
}
|
||||
this.dirty = true;
|
||||
})
|
||||
})
|
||||
}
|
||||
this.dirty = true;
|
||||
});
|
||||
});
|
||||
|
||||
new Setting(ce)
|
||||
.setName(t("IPM_GROUP_PAGES_NAME"))
|
||||
.setDesc(t("IPM_GROUP_PAGES_DESC"))
|
||||
.addToggle(toggle => toggle
|
||||
.setValue(this.groupPages)
|
||||
.onChange((value) => {
|
||||
this.groupPages = value
|
||||
.addToggle((toggle) =>
|
||||
toggle.setValue(this.groupPages).onChange((value) => {
|
||||
this.groupPages = value;
|
||||
this.dirty = true;
|
||||
}))
|
||||
|
||||
|
||||
}),
|
||||
);
|
||||
|
||||
new Setting(ce)
|
||||
.setName("Lock pages on canvas after import")
|
||||
.addToggle(toggle => {
|
||||
.addToggle((toggle) => {
|
||||
laiToggle = toggle;
|
||||
toggle
|
||||
.setValue(this.lockAfterImport)
|
||||
.onChange((value) => {
|
||||
this.lockAfterImport = value
|
||||
this.dirty = true;
|
||||
})
|
||||
})
|
||||
toggle.setValue(this.lockAfterImport).onChange((value) => {
|
||||
this.lockAfterImport = value;
|
||||
this.dirty = true;
|
||||
});
|
||||
});
|
||||
|
||||
let numColumnsSetting: Setting;
|
||||
let numRowsSetting: Setting;
|
||||
const colRowVisibility = () => {
|
||||
switch(this.direction) {
|
||||
switch (this.direction) {
|
||||
case "down":
|
||||
numColumnsSetting.settingEl.style.display = "none";
|
||||
numRowsSetting.settingEl.style.display = "";
|
||||
@@ -349,34 +363,36 @@ export class InsertPDFModal extends Modal {
|
||||
numRowsSetting.settingEl.style.display = "none";
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
new Setting(ce)
|
||||
.setName("Import direction")
|
||||
.addDropdown(dropdown => dropdown
|
||||
};
|
||||
|
||||
new Setting(ce).setName("Import direction").addDropdown((dropdown) =>
|
||||
dropdown
|
||||
.addOptions({
|
||||
"down": "Top > Down",
|
||||
"right": "Left > Right"
|
||||
down: "Top > Down",
|
||||
right: "Left > Right",
|
||||
})
|
||||
.setValue(this.direction)
|
||||
.onChange(value => {
|
||||
.onChange((value) => {
|
||||
this.direction = value as "down" | "right";
|
||||
colRowVisibility();
|
||||
this.dirty = true;
|
||||
}))
|
||||
}),
|
||||
);
|
||||
|
||||
let columnsText: HTMLDivElement;
|
||||
numColumnsSetting = new Setting(ce);
|
||||
const numColumnsSetting = new Setting(ce);
|
||||
numColumnsSetting
|
||||
.setName("Number of columns")
|
||||
.addSlider(slider => slider
|
||||
.setLimits(1, 100, 1)
|
||||
.setValue(this.numColumns)
|
||||
.onChange(value => {
|
||||
this.numColumns = value;
|
||||
columnsText.innerText = ` ${value.toString()}`;
|
||||
this.dirty = true;
|
||||
}))
|
||||
.addSlider((slider) =>
|
||||
slider
|
||||
.setLimits(1, 100, 1)
|
||||
.setValue(this.numColumns)
|
||||
.onChange((value) => {
|
||||
this.numColumns = value;
|
||||
columnsText.innerText = ` ${value.toString()}`;
|
||||
this.dirty = true;
|
||||
}),
|
||||
)
|
||||
.settingEl.createDiv("", (el) => {
|
||||
columnsText = el;
|
||||
el.style.minWidth = "2.3em";
|
||||
@@ -385,17 +401,19 @@ export class InsertPDFModal extends Modal {
|
||||
});
|
||||
|
||||
let rowsText: HTMLDivElement;
|
||||
numRowsSetting = new Setting(ce);
|
||||
const numRowsSetting = new Setting(ce);
|
||||
numRowsSetting
|
||||
.setName("Number of rows")
|
||||
.addSlider(slider => slider
|
||||
.setLimits(1, 100, 1)
|
||||
.setValue(this.numRows)
|
||||
.onChange(value => {
|
||||
this.numRows = value;
|
||||
rowsText.innerText = ` ${value.toString()}`;
|
||||
this.dirty = true;
|
||||
}))
|
||||
.addSlider((slider) =>
|
||||
slider
|
||||
.setLimits(1, 100, 1)
|
||||
.setValue(this.numRows)
|
||||
.onChange((value) => {
|
||||
this.numRows = value;
|
||||
rowsText.innerText = ` ${value.toString()}`;
|
||||
this.dirty = true;
|
||||
}),
|
||||
)
|
||||
.settingEl.createDiv("", (el) => {
|
||||
rowsText = el;
|
||||
el.style.minWidth = "2.3em";
|
||||
@@ -407,14 +425,16 @@ export class InsertPDFModal extends Modal {
|
||||
let gapSizeText: HTMLDivElement;
|
||||
new Setting(ce)
|
||||
.setName("Size of gap between pages")
|
||||
.addSlider(slider => slider
|
||||
.setLimits(10, 200, 10)
|
||||
.setValue(this.gapSize)
|
||||
.onChange(value => {
|
||||
this.gapSize = value;
|
||||
gapSizeText.innerText = ` ${value.toString()}`;
|
||||
this.dirty = true;
|
||||
}))
|
||||
.addSlider((slider) =>
|
||||
slider
|
||||
.setLimits(10, 200, 10)
|
||||
.setValue(this.gapSize)
|
||||
.onChange((value) => {
|
||||
this.gapSize = value;
|
||||
gapSizeText.innerText = ` ${value.toString()}`;
|
||||
this.dirty = true;
|
||||
}),
|
||||
)
|
||||
.settingEl.createDiv("", (el) => {
|
||||
gapSizeText = el;
|
||||
el.style.minWidth = "2.3em";
|
||||
@@ -425,110 +445,135 @@ export class InsertPDFModal extends Modal {
|
||||
const initialDims = this.getMaxSelectedPageDimensions();
|
||||
const importSizeSetting = new Setting(ce)
|
||||
.setName("Imported page size")
|
||||
.setDesc(`${Math.round(initialDims.width*this.importScale)} x ${Math.round(initialDims.height*this.importScale)}`)
|
||||
.addSlider(slider => slider
|
||||
.setLimits(0.1, 1.5, 0.1)
|
||||
.setValue(this.importScale)
|
||||
.onChange(value => {
|
||||
this.importScale = value;
|
||||
this.dirty = true;
|
||||
this.setImageSizeMessage();
|
||||
}))
|
||||
|
||||
.setDesc(
|
||||
`${Math.round(initialDims.width * this.importScale)} x ${Math.round(initialDims.height * this.importScale)}`,
|
||||
)
|
||||
.addSlider((slider) =>
|
||||
slider
|
||||
.setLimits(0.1, 1.5, 0.1)
|
||||
.setValue(this.importScale)
|
||||
.onChange((value) => {
|
||||
this.importScale = value;
|
||||
this.dirty = true;
|
||||
this.setImageSizeMessage();
|
||||
}),
|
||||
);
|
||||
|
||||
this.imageSizeMessage = importSizeSetting.descEl;
|
||||
this.setImageSizeMessage();
|
||||
|
||||
const actionButton = new Setting(ce)
|
||||
.setDesc("Select a document first")
|
||||
.addButton(button => {
|
||||
.addButton((button) => {
|
||||
button
|
||||
.setButtonText("Import PDF")
|
||||
.setCta()
|
||||
.onClick(async () => {
|
||||
const ea = getEA(this.view) as ExcalidrawAutomate;
|
||||
const ea = getEA(this.view);
|
||||
let column = 0;
|
||||
let row = 0;
|
||||
await this.loadPageDimensions(this.pagesToImport);
|
||||
const maxPageDimensions = this.getMaxSelectedPageDimensions();
|
||||
const cellWidth = Math.round(maxPageDimensions.width*this.importScale);
|
||||
const cellHeight = Math.round(maxPageDimensions.height*this.importScale);
|
||||
if(cellWidth === 0 || cellHeight === 0) {
|
||||
const cellWidth = Math.round(
|
||||
maxPageDimensions.width * this.importScale,
|
||||
);
|
||||
const cellHeight = Math.round(
|
||||
maxPageDimensions.height * this.importScale,
|
||||
);
|
||||
if (cellWidth === 0 || cellHeight === 0) {
|
||||
importMessage.innerText = t("IPM_SELECT_PAGES_TO_IMPORT");
|
||||
return;
|
||||
}
|
||||
for(let i = 0; i < this.pagesToImport.length; i++) {
|
||||
for (let i = 0; i < this.pagesToImport.length; i++) {
|
||||
const page = this.pagesToImport[i];
|
||||
importMessage.innerText = `Importing page ${page} (${i+1} of ${this.pagesToImport.length})`;
|
||||
const dims = this.pageDimensionsByPage.get(page) ?? maxPageDimensions;
|
||||
const imgWidth = Math.round(dims.width*this.importScale);
|
||||
const imgHeight = Math.round(dims.height*this.importScale);
|
||||
const topX = Math.round(cellWidth*column + this.gapSize*column);
|
||||
const topY = Math.round(cellHeight*row + this.gapSize*row);
|
||||
importMessage.innerText = `Importing page ${page} (${i + 1} of ${this.pagesToImport.length})`;
|
||||
const dims =
|
||||
this.pageDimensionsByPage.get(page) ?? maxPageDimensions;
|
||||
const imgWidth = Math.round(dims.width * this.importScale);
|
||||
const imgHeight = Math.round(dims.height * this.importScale);
|
||||
const topX = Math.round(
|
||||
cellWidth * column + this.gapSize * column,
|
||||
);
|
||||
const topY = Math.round(cellHeight * row + this.gapSize * row);
|
||||
|
||||
ea.style.strokeColor = this.borderBox ? "#000000" : "transparent";
|
||||
const boxID = ea.addRect(
|
||||
topX,
|
||||
topY,
|
||||
imgWidth,
|
||||
imgHeight
|
||||
);
|
||||
const boxID = ea.addRect(topX, topY, imgWidth, imgHeight);
|
||||
const boxEl = ea.getElement(boxID) as any;
|
||||
if(this.lockAfterImport) boxEl.locked = true;
|
||||
if (this.lockAfterImport) {
|
||||
boxEl.locked = true;
|
||||
}
|
||||
|
||||
const imageID = await ea.addImage(
|
||||
topX,
|
||||
topY,
|
||||
this.pdfFile.path + `#page=${page}`,
|
||||
`${this.pdfFile.path}#page=${page}`,
|
||||
false,
|
||||
false);
|
||||
false,
|
||||
);
|
||||
const imgEl = ea.getElement(imageID) as any;
|
||||
imgEl.width = imgWidth;
|
||||
imgEl.height = imgHeight;
|
||||
if(this.lockAfterImport) imgEl.locked = true;
|
||||
if (this.lockAfterImport) {
|
||||
imgEl.locked = true;
|
||||
}
|
||||
|
||||
ea.addToGroup([boxID,imageID]);
|
||||
ea.addToGroup([boxID, imageID]);
|
||||
|
||||
if(this.frame) {
|
||||
const frameID = ea.addFrame(topX, topY,imgWidth,imgHeight,`${page}`);
|
||||
if (this.frame) {
|
||||
const frameID = ea.addFrame(
|
||||
topX,
|
||||
topY,
|
||||
imgWidth,
|
||||
imgHeight,
|
||||
`${page}`,
|
||||
);
|
||||
const frameEl = ea.getElement(frameID) as any;
|
||||
frameEl.frameRole = "marker";
|
||||
ea.addToGroup([frameID,boxID,imageID]);
|
||||
ea.addToGroup([frameID, boxID, imageID]);
|
||||
//ea.addElementsToFrame(frameID, [boxID,imageID]);
|
||||
ea.getElement(frameID).link = this.pdfFile.path + `#page=${page}`;
|
||||
ea.getElement(frameID).link =
|
||||
`${this.pdfFile.path}#page=${page}`;
|
||||
}
|
||||
|
||||
switch(this.direction) {
|
||||
|
||||
switch (this.direction) {
|
||||
case "right":
|
||||
column = (column + 1) % this.numColumns;
|
||||
if(column === 0) row++;
|
||||
if (column === 0) {
|
||||
row++;
|
||||
}
|
||||
break;
|
||||
case "down":
|
||||
row = (row + 1) % this.numRows;
|
||||
if(row === 0) column++;
|
||||
if (row === 0) {
|
||||
column++;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
if(this.groupPages) {
|
||||
const ids = ea.getElements()
|
||||
.filter(el=>!this.frame || (el.type === "frame"))
|
||||
.map(el => el.id);
|
||||
if (this.groupPages) {
|
||||
const ids = ea
|
||||
.getElements()
|
||||
.filter((el) => !this.frame || el.type === "frame")
|
||||
.map((el) => el.id);
|
||||
ea.addToGroup(ids);
|
||||
}
|
||||
await ea.addElementsToView(true,true,false);
|
||||
const api = ea.getExcalidrawAPI() as ExcalidrawImperativeAPI;
|
||||
const ids = ea.getElements().map(el => el.id);
|
||||
const viewElements = ea.getViewElements().filter(el => ids.includes(el.id));
|
||||
await ea.addElementsToView(true, true, false);
|
||||
const api = ea.getExcalidrawAPI();
|
||||
const ids = ea.getElements().map((el) => el.id);
|
||||
const viewElements = ea
|
||||
.getViewElements()
|
||||
.filter((el) => ids.includes(el.id));
|
||||
api.selectElements(viewElements);
|
||||
api.zoomToFit(viewElements);
|
||||
ea.destroy();
|
||||
this.close();
|
||||
})
|
||||
});
|
||||
importButton = button;
|
||||
importButton.buttonEl.style.display = "none";
|
||||
});
|
||||
importMessage = actionButton.descEl;
|
||||
const importMessage = actionButton.descEl;
|
||||
importMessage.addClass("mod-warning");
|
||||
if(this.pdfFile) {
|
||||
if (this.pdfFile) {
|
||||
search.setValue(this.pdfFile.path);
|
||||
await setFile(this.pdfFile); //on drop if opened with a file
|
||||
suggester.close();
|
||||
@@ -540,4 +585,3 @@ export class InsertPDFModal extends Modal {
|
||||
importButtonMessages();
|
||||
}
|
||||
}
|
||||
|
||||
+229
-373
@@ -1,36 +1,236 @@
|
||||
export const FIRST_RUN = `
|
||||
The Excalidraw Obsidian plugin is much more than "just" a drawing tool. To help you get started here's a showcase of the key Excalidraw plugin features.
|
||||
|
||||
If you'd like to learn more, please subscribe to my YouTube channel: [Visual PKM](https://www.youtube.com/channel/UCC0gns4a9fhVkGkngvSumAQ) where I regularly share videos about Obsidian-Excalidraw and about tools and techniques for Visual Personal Knowledge Management.
|
||||
|
||||
Thank you & Enjoy!
|
||||
|
||||
<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 } = {
|
||||
Intro: `After each update, you'll see these release notes (you can turn this off in the plugin settings).
|
||||
|
||||
I build this plugin in my free time, as a labor of love. Curious about the philosophy behind it? Check out [📕 Sketch Your Mind](https://sketch-your-mind.com). If you find it valuable, say THANK YOU or…
|
||||
I build this plugin as a labor of love. Curious about the philosophy behind it? Check out [📕 Sketch Your Mind](https://sketch-your-mind.com). Want to master Excalidraw? Join [Excalidraw Mastery](https://community.sketch-your-mind.com/em). If you find it valuable, say THANK YOU or…
|
||||
|
||||
<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.21.0":`
|
||||
## Fixed
|
||||
- Sizing of embedded images in Markdown when image type is set to SVG. [#2685](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2685)
|
||||
- Fixed Enter, Up/Down arrows, and TAB keys stop working in text element after deleting the \`#\` character [#2704](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2704)
|
||||
"2.23.0": `
|
||||
<div class="excalidraw-videoWrapper">
|
||||
<a href="https://www.youtube.com/watch?v=EiT56z3KPjI" target="_blank"><img src ="https://i.ytimg.com/vi/EiT56z3KPjI/maxresdefault.jpg" style="width:100%;"></a>
|
||||
</div>
|
||||
|
||||
## New
|
||||
- LaTeX editor is now floating [#2684](https://github.com/zsviczian/obsidian-excalidraw-plugin/pull/2684) 🙏[@TravisLEBLANC1](https://github.com/TravisLEBLANC1)
|
||||
- Inline link suggester now supports triggers \`
|
||||
- New Context Menu options to disable arrow binding and midpoint snapping. [#10906](https://github.com/excalidraw/excalidraw/pull/10906)
|
||||
- Icons aligned with Obsidian style [#2703](https://github.com/zsviczian/obsidian-excalidraw-plugin/pull/2703) 🙏[@heinrich26](https://github.com/heinrich26)
|
||||
- Added a new setting under *Excalidraw Automate* to opt-in to \`excalidraw-onload-scripts\`.
|
||||
- Added image cache for nested images, including nested Excalidraw drawings and PDF page renders.
|
||||
- When a scene is opened again on the same device, cached images are shown immediately while validation of nested changes continues in the background. This should **noticeably improve loading times** for scenes you access regularly.
|
||||
- A new setting under plugin settings in **Image caching and rendering optimization** lets you control cache retention in days, so you can balance disk usage against how long these cached images are kept available.
|
||||
- The cache is local to each device. It is **not synced** through Obsidian Sync or your vault, so each device builds and maintains its own cache independently.
|
||||
- Placeholder image for empty drawings.
|
||||
- AI support is now **provider-aware across the plugin**. You can choose between OpenAI, Anthropic/Claude, Google/Gemini, xAI/Grok, or an OpenAI-compatible/local endpoint.
|
||||
- AI settings now use shared provider profiles plus text/multimodal model lists, image model lists, default model selection, token budgets, and an optional verbose developer-console logging toggle for troubleshooting.
|
||||
- The shared AI configuration is now used by ExcalidrawAutomate, Mermaid chat, diagram-to-code, ExcaliAI, and related AI features.
|
||||
- Older OpenAI-specific AI settings are migrated automatically into the new shared AI settings on first run.
|
||||
- New and updated ExcaliAI script.
|
||||
- API key obfuscation for plugin settings. This helps prevent your API keys from leaking via Excalidraw plugin settings in case you open your vault to LLMs.
|
||||
|
||||
## Fixed
|
||||
- **Findings listed on [Obsidian Community Plugin Info](https://community.obsidian.md/plugins/obsidian-excalidraw-plugin)**
|
||||
- Error when saving pasted images from Excalidraw.com.
|
||||
- Fixed Mermaid chat / text-to-diagram and diagram-to-code to use the shared AI layer and honor the configured provider, model, API key, and endpoint settings.
|
||||
- Fixed the ExcaliAI script to work with the new shared AI settings, including provider-aware text and image model selection, prompt transforms vs. mask edits, and OpenAI image responses that return \`b64_json\` instead of a hosted URL.
|
||||
|
||||
## New in ExcalidrawAutomate
|
||||
- Added new provider-aware AI helper functions for scripts while retaining backward compatibility for existing \`postOpenAI()\` integrations.
|
||||
- Added \`getAISettings()\` to inspect the shared AI settings from scripts.
|
||||
- Added \`analyzeAIImage()\`, \`generateAIImage()\`, \`transformAIImage()\`, and \`maskEditAIImage()\` for shared text/image workflows.
|
||||
- Added \`createAIChatSession()\` to preserve chat history between calls without manually maintaining the \`messages\` array.
|
||||
- Added \`extractCodeBlocks()\` to simplify parsing model responses that return fenced code blocks.
|
||||
- Updated \`addImage()\` to accept \`data:image/...\` data URLs directly, in addition to files, hyperlinks, vault paths, and PDF++ references.
|
||||
|
||||
\`\`\`ts
|
||||
/**
|
||||
* Posts an AI request to the currently configured provider and returns the response.
|
||||
* @param {AIRequest} request - The AI request configuration.
|
||||
* @returns {Promise<RequestUrlResponse>} Promise resolving to the provider-normalized API response.
|
||||
*/
|
||||
public async postAI(request: AIRequest): Promise<RequestUrlResponse>;
|
||||
|
||||
/**
|
||||
* Backwards-compatible alias for \`postAI()\`.
|
||||
* Existing scripts can keep calling \`postOpenAI()\` while using the shared provider, model, API key, and endpoint settings.
|
||||
* @param {AIRequest} request - The AI request configuration.
|
||||
* @returns {Promise<RequestUrlResponse>} Promise resolving to the provider-normalized API response.
|
||||
*/
|
||||
public async postOpenAI(request: AIRequest): Promise<RequestUrlResponse>;
|
||||
|
||||
/**
|
||||
* Returns the shared AI settings exposed to scripts.
|
||||
* @returns {ExcalidrawAISettings | null} Shared AI settings or null if AI is unavailable.
|
||||
*/
|
||||
public getAISettings(): ExcalidrawAISettings | null;
|
||||
|
||||
/**
|
||||
* Sends an image-aware text request using the shared multimodal routing.
|
||||
* @param {AIRequest} request - The AI request configuration.
|
||||
* @returns {Promise<GenerateAITextResult>} Promise resolving to normalized text output.
|
||||
*/
|
||||
public async analyzeAIImage(request: AIRequest): Promise<GenerateAITextResult>;
|
||||
|
||||
/**
|
||||
* Generates a new image using the configured image model.
|
||||
* @param {AIRequest} request - The AI request configuration.
|
||||
* @returns {Promise<GenerateAIImageResult>} Promise resolving to normalized image output.
|
||||
*/
|
||||
public async generateAIImage(request: AIRequest): Promise<GenerateAIImageResult>;
|
||||
|
||||
/**
|
||||
* Applies a prompt-based transform to an input image.
|
||||
* @param {AIRequest} request - The AI request configuration.
|
||||
* @returns {Promise<GenerateAIImageResult>} Promise resolving to normalized image output.
|
||||
*/
|
||||
public async transformAIImage(request: AIRequest): Promise<GenerateAIImageResult>;
|
||||
|
||||
/**
|
||||
* Applies a mask-based edit to an input image.
|
||||
* @param {AIRequest} request - The AI request configuration.
|
||||
* @returns {Promise<GenerateAIImageResult>} Promise resolving to normalized image output.
|
||||
*/
|
||||
public async maskEditAIImage(request: AIRequest): Promise<GenerateAIImageResult>;
|
||||
|
||||
/**
|
||||
* Creates a lightweight chat session helper that preserves prior conversation turns between calls.
|
||||
* @param {Omit<AIRequest, "messages">} initialRequest - Default request fields applied to every send.
|
||||
* @returns {AIChatSession} Chat session helper with \`getMessages()\`, \`reset()\`, and \`send()\`.
|
||||
*/
|
||||
public createAIChatSession(initialRequest?: Omit<AIRequest, "messages">): AIChatSession;
|
||||
|
||||
/**
|
||||
* Extracts code blocks from markdown text.
|
||||
* @param {string} markdown - The markdown string to parse.
|
||||
* @returns {Array<{ data: string, type: string }>} Array of objects containing code block contents and types.
|
||||
*/
|
||||
public extractCodeBlocks(markdown: string): { data: string, type: string }[];
|
||||
|
||||
/**
|
||||
* Adds an image element to the ExcalidrawAutomate instance.
|
||||
* @param {number | AddImageOptions} topXOrOpts - The x-coordinate of the top-left corner or an options object.
|
||||
* @param {number} topY - The y-coordinate of the top-left corner.
|
||||
* @param {TFile | string} imageFile - The image file, hyperlink, vault path, PDF++ reference, or data URL.
|
||||
* @param {boolean} [scale=true] - Whether to scale the image to MAX_IMAGE_SIZE.
|
||||
* @param {boolean} [anchor=true] - Whether to anchor the image at 100% size.
|
||||
* @returns {Promise<string>} Promise resolving to the ID of the added image element.
|
||||
*/
|
||||
async addImage(
|
||||
topXOrOpts: number | AddImageOptions,
|
||||
topY: number,
|
||||
imageFile: TFile | string,
|
||||
scale: boolean = true,
|
||||
anchor: boolean = true,
|
||||
): Promise<string>;
|
||||
\`\`\`
|
||||
`,
|
||||
"2.22.3": `
|
||||
|
||||
Feeling overwhelmed by Excalidraw's endless features?
|
||||
|
||||
It's not just a drawing tool. Inside Obsidian, it becomes a thinking tool.
|
||||
To unlock linking, embedding, and referencing, you need a mindset shift.
|
||||
|
||||
**Join Excalidraw Mastery** to make that shift.
|
||||
Courses, live Q&As, and deep dives to help you move into true 4D Visual PKM. 👉 https://community.sketch-your-mind.com/em
|
||||
|
||||
<div style="text-align:center;margin-top:10px;">
|
||||
<a href="https://community.sketch-your-mind.com/em" target="_blank"><img src="https://sketch-your-mind.com/images/logo-EM.png" style="width:50%"></a>
|
||||
</div>
|
||||
|
||||
Excalidraw Mastery is part of the **Sketch Your Mind Community**—a space for visual thinkers.
|
||||
Share your work. Ask questions. Learn from others. 👉 https://community.sketch-your-mind.com
|
||||
|
||||
Curious about the philosophy behind it?
|
||||
|
||||
<div class="excalidraw-videoWrapper">
|
||||
<a href="https://www.youtube.com/watch?v=TnwRlaIdhSU" target="_blank"><img src ="https://sketch-your-mind.com/images/Thumbnail-podcast.jpg" style="width:100%;"></a>
|
||||
</div>
|
||||
|
||||
`,
|
||||
"2.20.6":`
|
||||
"2.22.1": `
|
||||
## New
|
||||
- Added a command palette action to switch all currently open Excalidraw drawings to view mode.
|
||||
- While this temporary mode is enabled, any Excalidraw drawing opened afterward will also open in view mode.
|
||||
- This is useful when presenting multiple drawings and you want to avoid accidentally moving elements, and when you don't want the tools to be in the way.
|
||||
- Added an optional phone-only layout setting to push Excalidraw's footer controls above the system navigation bar on some Android devices [#2688](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2688), [#2652](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2652), [#798](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/798)
|
||||
- Look for ""Extra bottom padding for phone controls" in the plugin settings.
|
||||
|
||||
## Fixed
|
||||
- invisible cursor color in color picker, mermaid chat, in text elements in dark mode [#2739](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2739)
|
||||
- image sizing issue when embedding image type "SVG Image" to markdown
|
||||
- copying a nested image fragment in Excalidraw and pasting to markdown lost the image block reference
|
||||
- modifier keys conflicted with Excalidraw alt-select (lasso) behavior
|
||||
`,
|
||||
"2.22.0": `
|
||||
## Fixed
|
||||
- Fixed misaligned panel buttons in tray mode [#2718](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2718) 🙏[@heinrich26](https://github.com/heinrich26)
|
||||
- Improved loading of nested Excalidraw files within a scene, with some additional performance gains.
|
||||
- Fixed an issue where the caret color did not match the text color [#11018](https://github.com/excalidraw/excalidraw/issues/11018)
|
||||
|
||||
## New from Excalidraw.com
|
||||
- Added several text editing improvements, including a right-side handle on wrapped text for easier auto-resizing without opening the context menu [#10979](https://github.com/excalidraw/excalidraw/pull/10979)
|
||||
- Added support for Mermaid state diagrams [#11031](https://github.com/excalidraw/excalidraw/pull/11031)
|
||||
- There is a new Preferences menu above the Dark/Light mode switch in the main menu [#10760](https://github.com/excalidraw/excalidraw/pull/10760)
|
||||
- Added a new Preferences option to switch between Wrap and Overlap selection modes. Overlap mode behaves similarly to the lasso selection tool available under More Tools [#11053](https://github.com/excalidraw/excalidraw/pull/11053)
|
||||
|
||||
## New
|
||||
- Added support for embedding the [Sheet Plus](obsidian://show-plugin?id=sheet-plus) plugin as an active embeddable element in Excalidraw. At the moment, changing the canvas theme between dark and light mode does not automatically re-render embedded sheets. To apply the theme change, close and reopen the drawing. This will likely be improved in a future update.
|
||||
`,
|
||||
"2.21.3": `
|
||||
## Fixed
|
||||
- Caret color for link editor, text elemnts in dark mode, color picker input element.
|
||||
- Link click behavior modifier keys setting in plugin settings now enforces CTRL/CMD for link clicks and improves on clarity of setting UI by adding a header row
|
||||
- Link click conbinations that included ALT/OPT did not work because they trigger lasso selection in Excalidraw. This is now fixed, if you CTRL+ALT click a link it will navigate while retaining the lasso select feature when pressing ALT/OPT.
|
||||
- Copying an image block embed (e.g. \`![[drawing#^frame=my_frame]]\`) from the excalidraw scene and pasting it to markdown no longer loses the frame reference
|
||||
- Embed "SVG Image" to markdown should size correctly now when setting a percentage \`![[drawing|50%]]\` where 50% is relative to the width of the markdown note.
|
||||
|
||||
`,
|
||||
"2.21.2": `
|
||||
## Fixed
|
||||
- The new ExcalidrawAutomate function \`parseText()\` broke if the text was a transcluded image or PDF document, causing downstream paste issues in MindMap Builder.
|
||||
- Custom pen sloppiness not being saved to a template drawing [#2715](https://github.com/zsviczian/obsidian-excalidraw-plugin/pull/2715) 🙏[@sreedharsreeram](https://github.com/sreedharsreeram)
|
||||
|
||||
`,
|
||||
"2.21.1": `
|
||||
## Fixed
|
||||
- Drawing and editor fails to initialize in a new window [#2713](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2713)
|
||||
- Duplicate selected image with a different image ID command palette action did not duplicate cropped PDF images.
|
||||
- Memory leak issue with PDF import as images.
|
||||
|
||||
## New
|
||||
- Put caret at pointer position when clicking on selected text element [#10970](https://github.com/excalidraw/excalidraw/pull/10970)
|
||||
|
||||
`,
|
||||
"2.21.0": `
|
||||
## New
|
||||
- LaTeX editor is now floating [#2684](https://github.com/zsviczian/obsidian-excalidraw-plugin/pull/2684) 🙏[@TravisLEBLANC1](https://github.com/TravisLEBLANC1), [#2698](https://github.com/zsviczian/obsidian-excalidraw-plugin/pull/2698) 🙏[@heinrich26](https://github.com/heinrich26)
|
||||
- Inline link suggester supports new triggers \`
|
||||
- New Context Menu options to disable arrow binding and midpoint snapping [#10906](https://github.com/excalidraw/excalidraw/pull/10906)
|
||||
- Improved UI styling and icons are better aligned with Obsidian [#2703](https://github.com/zsviczian/obsidian-excalidraw-plugin/pull/2703), [#2687](https://github.com/zsviczian/obsidian-excalidraw-plugin/pull/2687), [#2697](https://github.com/zsviczian/obsidian-excalidraw-plugin/pull/2697) 🙏[@heinrich26](https://github.com/heinrich26)
|
||||
|
||||
## Fixed
|
||||
- Sizing of embedded images in Markdown when image type is set to SVG [#2685](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2685)
|
||||
- Fixed Enter, Up/Down arrows, and TAB keys stopped working in text elements after deleting the \`#\` character [#2704](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2704)
|
||||
|
||||
## MindMap Builder
|
||||
- Fixed navigation (arrow keys) scoping and recognition
|
||||
- Added new feature to paste images and single Excalidraw elements like container with text, text element, or image element directly as a map leaf (using the MindMap Builder default paste shortcut: ALT/OPT+V)
|
||||
- Added new action to toggle a markdown link between markdown embeddable and link as text. Default shortcut is ALT/OPT+E.
|
||||
|
||||
## New in ExcalidrawAutomate
|
||||
\`\`\`ts
|
||||
/**
|
||||
* Parses text using the target view's ExcalidrawData parser.
|
||||
*
|
||||
* This reuses ExcalidrawData parsing logic directly, including transclusion
|
||||
* resolution, link bracket rendering, and link/url prefixes based on the
|
||||
* target file's frontmatter.
|
||||
*
|
||||
* @param {string} text - Raw text to parse.
|
||||
* @returns {Promise<string | undefined>} Parsed text, or undefined when input/view is unavailable.
|
||||
*/
|
||||
public async parseText (text: string): Promise<string | undefined>;
|
||||
\`\`\`
|
||||
`,
|
||||
"2.20.6": `
|
||||
<div class="excalidraw-videoWrapper">
|
||||
<a href="https://www.youtube.com/watch?v=g-BiyQ7TJTM" target="_blank"><img src ="https://i.ytimg.com/vi/g-BiyQ7TJTM/maxresdefault.jpg" style="width:100%;"></a>
|
||||
</div>
|
||||
@@ -62,7 +262,7 @@ stakeholder_mgmt, 1, 6, 10
|
||||
- Multiple arrow related updates and fixes from Excalidraw.com [#10832](https://github.com/excalidraw/excalidraw/pull/10832) [#10831](https://github.com/excalidraw/excalidraw/pull/10831) [#10816](https://github.com/excalidraw/excalidraw/pull/10816)
|
||||
- Hide MindMap Builder and other floating tools when creating a screenshot
|
||||
`,
|
||||
"2.20.5":`
|
||||
"2.20.5": `
|
||||
## Fixed
|
||||
- Obsidian Mobile: The floating navigation bar got stuck at the bottom after closing Excalidraw or switching to a markdown note. [#2673](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2673)
|
||||
- "Toggle UI Mode" now includes a preference setting for Obsidian Phone as well. You can now set different default layouts for phone, tablet, and desktop. [#2670](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2670)
|
||||
@@ -70,7 +270,7 @@ stakeholder_mgmt, 1, 6, 10
|
||||
## New
|
||||
- Added "Toggle Full Screen" button to toolbar right next to the "Obsidian menu", and the "Insert Any File" button.
|
||||
`,
|
||||
"2.20.4":`
|
||||
"2.20.4": `
|
||||
## Fixed
|
||||
- Fix NativeSVG embed mode into Markdown documents, ahead of the Obsidian 1.12.1 release. [#2665](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2665)
|
||||
- Color picker once again supports 8-digit hex codes (Hex color string with an opacity). [#10772](https://github.com/excalidraw/excalidraw/issues/10772)
|
||||
@@ -84,7 +284,7 @@ stakeholder_mgmt, 1, 6, 10
|
||||
- Arrow binding midpoints. When the projected point is close to center, snap it to the exact center. This way it's easier to create neat(er) simple arrow connections. [#10611](https://github.com/excalidraw/excalidraw/pull/10611)
|
||||
|
||||
`,
|
||||
"2.20.3":`
|
||||
"2.20.3": `
|
||||
## Fixed
|
||||
- Hover preview when hovering an element with a link in the scene was unreliable
|
||||
- If a text element had a link in the text body, in some situations, the link became unresponsive to clicks. [#2660](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2660)
|
||||
@@ -92,7 +292,7 @@ stakeholder_mgmt, 1, 6, 10
|
||||
## New
|
||||
- Added default keymap to latex editor [#2655](https://github.com/zsviczian/obsidian-excalidraw-plugin/pull/2655) 🙏[superle3](https://github.com/superle3)
|
||||
`,
|
||||
"2.20.2":`
|
||||
"2.20.2": `
|
||||
## New from Excalidraw.com
|
||||
- Arrow focus indicator [#10613](https://github.com/excalidraw/excalidraw/pull/10613)
|
||||
|
||||
@@ -121,7 +321,7 @@ stakeholder_mgmt, 1, 6, 10
|
||||
): Promise<boolean>
|
||||
\`\`\`
|
||||
`,
|
||||
"2.20.1":`
|
||||
"2.20.1": `
|
||||
## Fixed
|
||||
- Fixed Experimental file type display, available under miscellaneous settings. (Reported on Discord)
|
||||
- Fixed image inversion in dark mode on iOS devices. [#2636](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2636)
|
||||
@@ -146,7 +346,7 @@ stakeholder_mgmt, 1, 6, 10
|
||||
> - Sun Feb 1 @ 09:00 CET ([local time](https://www.timeanddate.com/worldclock/fixedtime.html?msg=MindMap+Builder+Launch+Party&iso=20260201T08&p1=%3A&ah=1))
|
||||
|
||||
`,
|
||||
"2.20.0":`
|
||||
"2.20.0": `
|
||||
<div class="excalidraw-videoWrapper">
|
||||
<a href="https://www.youtube.com/watch?v=5G9QF-u9w0Q" target="_blank"><img src ="https://i.ytimg.com/vi/5G9QF-u9w0Q/maxresdefault.jpg" style="width:100%;"></a>
|
||||
</div>
|
||||
@@ -174,348 +374,4 @@ stakeholder_mgmt, 1, 6, 10
|
||||
- Some PDFs failed to load when importing PDFs as images (notably documents using JPEG2000-compressed images). Also improved handling of certain color profiles and cases where text rendered with missing/incorrect glyphs.
|
||||
- A long-standing export issue: when exporting in a theme different from the current view (e.g., viewing in dark mode but exporting in light mode), nested Excalidraw images containing bitmap images could export with inverted colors.
|
||||
`,
|
||||
"2.19.2":`
|
||||
## Fixed
|
||||
- Minor fixes to the link autocomplete functionality:
|
||||
- Link suggester "eats up text" [#2603](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2603)
|
||||
- "!" triggers the link suggester prematurely
|
||||
- "\[\[" will now be auto-completed to "\[\[]]". Note, this is not available in MindMap Builder currently.
|
||||
|
||||
## New
|
||||
- When a persistent Excalidraw script is updated via the script store, it will now automatically reload so the new script takes effect immediately.
|
||||
|
||||
`,
|
||||
"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">
|
||||
<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)
|
||||
- You can rename library items by selecting them, then choosing "Rename or publish" from the ... menu.
|
||||
- New compact mode for tablets [#9910](https://github.com/excalidraw/excalidraw/pull/9910)
|
||||
- New setting in plugin setting \`Compact-mode on Tablets\` to override tray-mode on tablets in favor of the new compact mode.
|
||||
|
||||
## New
|
||||
- Embedding PDF as images, frames are now marker frames instead of regular frames. You can reference pages, including their markup in markdown notes, using this syntax: \`![[drawing#^frame=12]]\` (page 12)
|
||||
- Pinned scripts toolbar is now on the right side in all modes: tray-, normal-, and compact. The toolbar moves into view when the side panel is opened for the stencil library or for search.
|
||||
- Better RTL support, pinned scripts are rendered on the left side in RTL mode.
|
||||
|
||||
## Fixed
|
||||
- Critical fix: When clicking to follow a link in a markdown embeddable in preview mode to open an Excalidraw drawing in the same tab, the back of the newly opened drawing was overwritten with the content of the source drawing.
|
||||
- PDF++ Links from document to Excalidraw select everything in the scene instead of the linked element. [#2503](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2503)
|
||||
|
||||
`,
|
||||
"2.15.3":`
|
||||
## Fixed
|
||||
- New back of the note cards are not visible until the drawing is saved. When adding a back-of-the-note card using the context menu, the card got placed at the absolute 0,0 position in the scene instead of the current pointer position. [#9949](https://github.com/excalidraw/excalidraw/issues/9949)
|
||||
- Drawings created 4 years ago don't open [#2479](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2479)
|
||||
- On Obsidian Mobile, when an element has multiple links, clicking the link icon, the link selector pops up and immediately closes
|
||||
- Improved handling of importing external images and drag and drop of images from inside Obsidian. Features like (Convert SVG to Strokes) and (Flip the card) now work immediately, you don't need to force save, or wait for autosave to kick in.
|
||||
|
||||
## New
|
||||
- Added startup check that detects when Obsidian's recorded plugin version differs from the installed Excalidraw code (e.g. after partial sync of large files) and offers to update or ignore, with a setting to disable the check.
|
||||
- When Excalidraw is open in two or more tabs—either as Markdown or Excalidraw—auto-zoom is disabled. This allows you to work in multiple tabs on the same drawing at once: focusing on different areas of the same drawing, or editing the Markdown and Excalidraw views in parallel.
|
||||
`,
|
||||
"2.15.2":`
|
||||
## Fixed:
|
||||
- Pressing enter on a text element erroneously activated all markdown embeddables in the scene. [discord](https://discord.com/channels/1026825302900494357/1412683408424833045)
|
||||
- After updating to PDF++ 0.40.31, touch scrolling of embedded PDF documents stopped working on mobile devices, and the PDF document appeared with the wrong themes in some cases.
|
||||
- Issue with the Kanban board as an active embeddable on mobile phones is fixed.
|
||||
|
||||
## Fixed in ExcalidrawAutomate
|
||||
- \`getActiveEmbeddableViewOrEditor (view?:ExcalidrawView): {view:any}|{file:TFile, editor:Editor}|{node: ObsidianCanvasNode}|null;\` no returns the node, instead of the empty view from the leaf.
|
||||
`,
|
||||
"2.15.1":`
|
||||
## Fixed
|
||||
- PDF improvements
|
||||
- It was not possible to scroll the embedded PDF. [#9891](https://github.com/excalidraw/excalidraw/pull/9891)
|
||||
- Embedded PDF pages were blurred (pixelated).
|
||||
- Embedded PDF now accurately follows \`excalidraw-embeddable-theme\` document property.
|
||||
- auto: follows Excalidraw theme (regardless of Obsidian theme)
|
||||
- default: follows Obsidian theme (regardless of Excalidraw theme)
|
||||
- dark: always displays the PDF in dark mode (regardless of Excalidraw and Obsidian themes)
|
||||
- light: always displays the PDF in light mode (regardless of Excalidraw and Obsidian themes)
|
||||
- New embeddable-menu buttons:
|
||||
- Snapshot: inserts an image of the current active page to the scene
|
||||
- Bookmark: updates the embed link to the current page
|
||||
- Pasting an oversized image triggered an error and caused Excalidraw to discard the scene. [#2453](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2453), [#9878](https://github.com/excalidraw/excalidraw/issues/9878)
|
||||
- Video with local URI will no longer autoplay when the scene loads
|
||||
- Error creating link to element when element is a sticky note
|
||||
- Area link embeds hide the content of the objects within the area [#2461](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2461)
|
||||
- On Obsidian Mobile 1.9.10, embeddables could cause a black/white screen (no active view) until reselecting the Excalidraw page; [#2460](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2460)
|
||||
- Scrolling of embedded web pages on mobile devices is working again.
|
||||
|
||||
## New
|
||||
- Insert Any File now supports adding Audio files.
|
||||
- New option in settings under "Zoom and Pan". Pan with right mouse button (Miro-style): right-click and drag to pan the canvas. Press 'm' for the context menu (disabled while editing text). 🙏 [@mfuria](https://github.com/mfuria) for making this happen! [#2450](https://github.com/zsviczian/obsidian-excalidraw-plugin/pull/2450), [#329](https://github.com/zsviczian/excalidraw/pull/329)
|
||||
- Insert image in the main toolbar now opens a dropdown menu of options: Insert from system, insert from Vault, insert Card, and insert LaTeX. [#2448](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2448)
|
||||
|
||||
## Deprecated
|
||||
- Removed "Toggle RAW mode" from the Command Palette and the Obsidian Tools menu due to low usage. RAW mode remains available by adding \`excalidraw-plugin: raw\` to the note's YAML frontmatter/document properties.
|
||||
|
||||
## New in ExcalidrawAutomate
|
||||
\`\`\`ts
|
||||
/**
|
||||
* Returns the center position of the current view in Excalidraw coordinates.
|
||||
* @returns {{x:number, y:number}} The center position of the view.
|
||||
*/
|
||||
public getViewCenterPosition(): {x:number, y:number};
|
||||
\`\`\`
|
||||
`,
|
||||
"2.15.0":`
|
||||
<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.
|
||||
To create a marker frame, create a frame and toggle the marker frame in the elements properties panel.
|
||||
- Markers are not included in exports such as images or PDFs.
|
||||
- Markers do not contain elements
|
||||
- Markers can be hidden/shown from the canvas context menu
|
||||
- Updated the "Printable Layout Wizard" script
|
||||
- Now works with marker frames
|
||||
- Supports different page sizes and orientations within a single PDF document
|
||||
- The printout may include non-marker frames (e.g., PDF image embeds in frames)
|
||||
- Pro-tip: You can also use marker frames...
|
||||
- with the Slideshow plugin
|
||||
- to create image-area references such that the frames do not get rendered in exported images, and you can reference areas by frame name
|
||||
- Performance improvement of Image-area references
|
||||
|
||||
# New in ExcalidrawAutomate
|
||||
- \`createPDF()\` now supports \`SVG[]\` array of SVGs with different sizes.
|
||||
- New function:
|
||||
\`\`\`ts
|
||||
/**
|
||||
* Gets the elements within a specific area.
|
||||
* @param elements - The elements to check.
|
||||
* @param param1 - The area to check against.
|
||||
* @returns The elements within the area.
|
||||
*/
|
||||
elementsInArea(
|
||||
elements: NonDeletedExcalidrawElement[],
|
||||
{x, y, width, height}:{
|
||||
x:number; y:number; width:number; height:number;
|
||||
}
|
||||
):ExcalidrawElement[]
|
||||
\`\`\`
|
||||
`,
|
||||
};
|
||||
@@ -1,7 +1,11 @@
|
||||
import { Setting } from "obsidian";
|
||||
import { DEVICE } from "src/constants/constants";
|
||||
import { t } from "src/lang/helpers";
|
||||
import { ModifierKeySet, ModifierSetType, modifierKeyTooltipMessages } from "src/utils/modifierkeyHelper";
|
||||
import {
|
||||
ModifierKeySet,
|
||||
ModifierSetType,
|
||||
modifierKeyTooltipMessages,
|
||||
} from "src/utils/modifierkeyHelper";
|
||||
|
||||
type ModifierKeyCategories = Partial<{
|
||||
[modifierSetType in ModifierSetType]: string;
|
||||
@@ -23,33 +27,69 @@ export class ModifierKeySettingsComponent {
|
||||
Mac: Record<string, ModifierKeySet>;
|
||||
Win: Record<string, ModifierKeySet>;
|
||||
},
|
||||
private update?: Function,
|
||||
private update?: () => void,
|
||||
) {
|
||||
this.isMacOS = (DEVICE.isMacOS || DEVICE.isIOS);
|
||||
this.isMacOS = DEVICE.isMacOS || DEVICE.isIOS;
|
||||
}
|
||||
|
||||
render() {
|
||||
const platform = this.isMacOS ? "Mac" : "Win";
|
||||
const modifierKeysConfig = this.modifierKeyConfig[platform];
|
||||
const tooltipMessages = modifierKeyTooltipMessages() as Record<
|
||||
string,
|
||||
Record<string, string>
|
||||
>;
|
||||
|
||||
Object.entries(CATEGORIES).forEach(([modifierSetType, label]) => {
|
||||
const detailsEl = this.contentEl.createEl("details");
|
||||
detailsEl.createEl("summary", {
|
||||
detailsEl.createEl("summary", {
|
||||
text: label,
|
||||
cls: "excalidraw-setting-h4",
|
||||
});
|
||||
|
||||
|
||||
const modifierKeys = modifierKeysConfig[modifierSetType];
|
||||
detailsEl.createDiv({
|
||||
//@ts-ignore
|
||||
text: t("DEFAULT_ACTION_DESC") + modifierKeyTooltipMessages()[modifierSetType][modifierKeys.defaultAction],
|
||||
cls: "setting-item-description"
|
||||
text:
|
||||
t("DEFAULT_ACTION_DESC") +
|
||||
(tooltipMessages[modifierSetType]?.[modifierKeys.defaultAction] ??
|
||||
""),
|
||||
cls: "setting-item-description",
|
||||
});
|
||||
Object.entries(modifierKeys.rules).forEach(([action, rule]) => {
|
||||
const setting = new Setting(detailsEl)
|
||||
//@ts-ignore
|
||||
.setName(modifierKeyTooltipMessages()[modifierSetType][rule.result]);
|
||||
|
||||
// Ensure all LinkClickAction rules have ctrl_cmd enabled
|
||||
if (modifierSetType === "LinkClickAction") {
|
||||
let dirty = false;
|
||||
modifierKeys.rules.forEach((rule) => {
|
||||
if (!rule.ctrl_cmd) {
|
||||
rule.ctrl_cmd = true;
|
||||
dirty = true;
|
||||
}
|
||||
});
|
||||
if (dirty) {
|
||||
this.update?.();
|
||||
}
|
||||
}
|
||||
|
||||
// Column header row
|
||||
const headerSetting = new Setting(detailsEl);
|
||||
headerSetting.settingEl.addClass("modifier-key-header-row");
|
||||
headerSetting.infoEl.remove();
|
||||
[
|
||||
"SHIFT",
|
||||
this.isMacOS ? "CMD" : "CTRL",
|
||||
this.isMacOS ? "OPT" : "ALT",
|
||||
this.isMacOS ? "CTRL" : "META",
|
||||
].forEach((key) => {
|
||||
headerSetting.controlEl.createEl("span", {
|
||||
text: key,
|
||||
cls: "modifier-key-col-header",
|
||||
});
|
||||
});
|
||||
|
||||
Object.entries(modifierKeys.rules).forEach(([_, rule]) => {
|
||||
const setting = new Setting(detailsEl).setName(
|
||||
tooltipMessages[modifierSetType]?.[rule.result],
|
||||
);
|
||||
|
||||
setting.addToggle((toggle) =>
|
||||
toggle
|
||||
.setValue(rule.shift)
|
||||
@@ -57,22 +97,26 @@ export class ModifierKeySettingsComponent {
|
||||
.onChange((value) => {
|
||||
rule.shift = value;
|
||||
this.update();
|
||||
})
|
||||
);
|
||||
}),
|
||||
);
|
||||
setting.addToggle((toggle) => {
|
||||
const isLinkClick = modifierSetType === "LinkClickAction";
|
||||
toggle
|
||||
.setValue(rule.ctrl_cmd)
|
||||
.setValue(isLinkClick ? true : rule.ctrl_cmd)
|
||||
.setTooltip(this.isMacOS ? "CMD" : "CTRL")
|
||||
.onChange((value) => {
|
||||
rule.ctrl_cmd = value;
|
||||
this.update();
|
||||
})
|
||||
if(this.isMacOS && modifierSetType !== "LinkClickAction") {
|
||||
});
|
||||
if (isLinkClick || this.isMacOS) {
|
||||
// CMD is always required for link-click actions (Excalidraw detects
|
||||
// the click via CMD being held). On macOS, CMD is also reserved for
|
||||
// non-link-click actions.
|
||||
toggle.setDisabled(true);
|
||||
toggle.toggleEl.style.opacity = "0.5";
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
setting.addToggle((toggle) =>
|
||||
toggle
|
||||
.setValue(rule.alt_opt)
|
||||
@@ -80,8 +124,8 @@ export class ModifierKeySettingsComponent {
|
||||
.onChange((value) => {
|
||||
rule.alt_opt = value;
|
||||
this.update();
|
||||
})
|
||||
);
|
||||
}),
|
||||
);
|
||||
setting.addToggle((toggle) =>
|
||||
toggle
|
||||
.setValue(rule.meta_ctrl)
|
||||
@@ -89,8 +133,8 @@ export class ModifierKeySettingsComponent {
|
||||
.onChange((value) => {
|
||||
rule.meta_ctrl = value;
|
||||
this.update();
|
||||
})
|
||||
);
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@@ -37,9 +37,9 @@ export class OpenFileDialog extends FuzzySuggestModal<TFile> {
|
||||
this.inputEl.onkeyup = (e) => {
|
||||
if (e.key == "Enter" && this.action == openDialogAction.openFile) {
|
||||
if (this.containerEl.innerText.includes(EMPTY_MESSAGE)) {
|
||||
this.plugin.createAndOpenDrawing(
|
||||
void this.plugin.createAndOpenDrawing(
|
||||
`${this.plugin.settings.folder}/${this.inputEl.value}.excalidraw.md`,
|
||||
this.onNewPane?"new-pane":"active-pane",
|
||||
this.onNewPane ? "new-pane" : "active-pane",
|
||||
);
|
||||
this.close();
|
||||
}
|
||||
@@ -61,10 +61,14 @@ export class OpenFileDialog extends FuzzySuggestModal<TFile> {
|
||||
onChooseItem(item: TFile): void {
|
||||
switch (this.action) {
|
||||
case openDialogAction.openFile:
|
||||
this.plugin.openDrawing(item, this.onNewPane?"new-pane":"active-pane",true);
|
||||
this.plugin.openDrawing(
|
||||
item,
|
||||
this.onNewPane ? "new-pane" : "active-pane",
|
||||
true,
|
||||
);
|
||||
break;
|
||||
case openDialogAction.insertLinkToDrawing:
|
||||
this.plugin.embedDrawing(item);
|
||||
void this.plugin.embedDrawing(item);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,11 @@
|
||||
import { Setting } from "obsidian";
|
||||
import { PageOrientation, PageSize, PDFPageAlignment, PDFPageMarginString, STANDARD_PAGE_SIZES } from "src/types/exportUtilTypes";
|
||||
import {
|
||||
PageOrientation,
|
||||
PageSize,
|
||||
PDFPageAlignment,
|
||||
PDFPageMarginString,
|
||||
STANDARD_PAGE_SIZES,
|
||||
} from "src/types/exportUtilTypes";
|
||||
import { t } from "src/lang/helpers";
|
||||
|
||||
export interface PDFExportSettings {
|
||||
@@ -16,118 +22,137 @@ export class PDFExportSettingsComponent {
|
||||
constructor(
|
||||
private contentEl: HTMLElement,
|
||||
private settings: PDFExportSettings,
|
||||
private update?: Function,
|
||||
private update?: () => void,
|
||||
) {
|
||||
if (!update) this.update = () => {};
|
||||
if (!update) {
|
||||
this.update = () => {};
|
||||
}
|
||||
}
|
||||
|
||||
isOrientationAndTilingVisible() {
|
||||
return !(this.settings.pageSize === "HD Screen" || this.settings.pageSize === "MATCH IMAGE");
|
||||
return !(
|
||||
this.settings.pageSize === "HD Screen" ||
|
||||
this.settings.pageSize === "MATCH IMAGE"
|
||||
);
|
||||
}
|
||||
|
||||
render() {
|
||||
const pageSizeOptions: Record<string, string> = Object.keys(STANDARD_PAGE_SIZES)
|
||||
.reduce((acc, key) => ({
|
||||
const pageSizeOptions: Record<string, string> = Object.keys(
|
||||
STANDARD_PAGE_SIZES,
|
||||
).reduce(
|
||||
(acc, key) => ({
|
||||
...acc,
|
||||
[key]: key
|
||||
}), {});
|
||||
|
||||
let div: HTMLDivElement;
|
||||
[key]: key,
|
||||
}),
|
||||
{},
|
||||
);
|
||||
|
||||
new Setting(this.contentEl)
|
||||
.setName(t("EXPORTDIALOG_PAGE_SIZE"))
|
||||
.addDropdown(dropdown =>
|
||||
.addDropdown((dropdown) =>
|
||||
dropdown
|
||||
.addOptions(pageSizeOptions)
|
||||
.setValue(this.settings.pageSize)
|
||||
.onChange(value => {
|
||||
.onChange((value) => {
|
||||
this.settings.pageSize = value as PageSize;
|
||||
div.style.display = this.isOrientationAndTilingVisible() ? "block" : "none";
|
||||
div.style.display = this.isOrientationAndTilingVisible()
|
||||
? "block"
|
||||
: "none";
|
||||
this.update();
|
||||
})
|
||||
}),
|
||||
);
|
||||
|
||||
div = this.contentEl.createDiv();
|
||||
const div = this.contentEl.createDiv();
|
||||
div.style.display = this.isOrientationAndTilingVisible() ? "block" : "none";
|
||||
|
||||
|
||||
new Setting(div)
|
||||
.setName(t("EXPORTDIALOG_PAGE_ORIENTATION"))
|
||||
.addDropdown(dropdown =>
|
||||
.addDropdown((dropdown) =>
|
||||
dropdown
|
||||
.addOptions({
|
||||
"portrait": t("EXPORTDIALOG_ORIENTATION_PORTRAIT"),
|
||||
"landscape": t("EXPORTDIALOG_ORIENTATION_LANDSCAPE")
|
||||
portrait: t("EXPORTDIALOG_ORIENTATION_PORTRAIT"),
|
||||
landscape: t("EXPORTDIALOG_ORIENTATION_LANDSCAPE"),
|
||||
})
|
||||
.setValue(this.settings.pageOrientation)
|
||||
.onChange(value => {
|
||||
.onChange((value) => {
|
||||
this.settings.pageOrientation = value as PageOrientation;
|
||||
this.update();
|
||||
})
|
||||
}),
|
||||
);
|
||||
|
||||
|
||||
new Setting(div)
|
||||
.setName(t("EXPORTDIALOG_PDF_FIT_TO_PAGE"))
|
||||
.addDropdown(dropdown =>
|
||||
.addDropdown((dropdown) =>
|
||||
dropdown
|
||||
.addOptions({
|
||||
"scale": t("EXPORTDIALOG_PDF_SCALE_OPTION"),
|
||||
"fit": t("EXPORTDIALOG_PDF_FIT_OPTION"),
|
||||
scale: t("EXPORTDIALOG_PDF_SCALE_OPTION"),
|
||||
fit: t("EXPORTDIALOG_PDF_FIT_OPTION"),
|
||||
"fit-2": t("EXPORTDIALOG_PDF_FIT_2_OPTION"),
|
||||
"fit-4": t("EXPORTDIALOG_PDF_FIT_4_OPTION"),
|
||||
"fit-6": t("EXPORTDIALOG_PDF_FIT_6_OPTION"),
|
||||
"fit-8": t("EXPORTDIALOG_PDF_FIT_8_OPTION"),
|
||||
"fit-12": t("EXPORTDIALOG_PDF_FIT_12_OPTION"),
|
||||
"fit-16": t("EXPORTDIALOG_PDF_FIT_16_OPTION")
|
||||
"fit-16": t("EXPORTDIALOG_PDF_FIT_16_OPTION"),
|
||||
})
|
||||
.setValue(this.settings.fitToPage === 1 ? "fit" :
|
||||
(typeof this.settings.fitToPage === "number" ? `fit-${this.settings.fitToPage}` : "scale"))
|
||||
.onChange(value => {
|
||||
this.settings.fitToPage = value === "scale" ? 0 :
|
||||
(value === "fit" ? 1 : parseInt(value.split("-")[1]));
|
||||
.setValue(
|
||||
this.settings.fitToPage === 1
|
||||
? "fit"
|
||||
: typeof this.settings.fitToPage === "number"
|
||||
? `fit-${this.settings.fitToPage}`
|
||||
: "scale",
|
||||
)
|
||||
.onChange((value) => {
|
||||
this.settings.fitToPage =
|
||||
value === "scale"
|
||||
? 0
|
||||
: value === "fit"
|
||||
? 1
|
||||
: parseInt(value.split("-")[1]);
|
||||
this.update();
|
||||
})
|
||||
}),
|
||||
);
|
||||
|
||||
new Setting(this.contentEl)
|
||||
.setName(t("EXPORTDIALOG_PDF_MARGIN"))
|
||||
.addDropdown(dropdown =>
|
||||
.addDropdown((dropdown) =>
|
||||
dropdown
|
||||
.addOptions({
|
||||
"none": t("EXPORTDIALOG_PDF_MARGIN_NONE"),
|
||||
"tiny": t("EXPORTDIALOG_PDF_MARGIN_TINY"),
|
||||
"normal": t("EXPORTDIALOG_PDF_MARGIN_NORMAL")
|
||||
none: t("EXPORTDIALOG_PDF_MARGIN_NONE"),
|
||||
tiny: t("EXPORTDIALOG_PDF_MARGIN_TINY"),
|
||||
normal: t("EXPORTDIALOG_PDF_MARGIN_NORMAL"),
|
||||
})
|
||||
.setValue(this.settings.margin)
|
||||
.onChange(value => {
|
||||
.onChange((value) => {
|
||||
this.settings.margin = value as PDFPageMarginString;
|
||||
this.update();
|
||||
})
|
||||
}),
|
||||
);
|
||||
|
||||
const paperColorSetting = new Setting(this.contentEl)
|
||||
.setName(t("EXPORTDIALOG_PDF_PAPER_COLOR"))
|
||||
.addDropdown(dropdown =>
|
||||
.addDropdown((dropdown) =>
|
||||
dropdown
|
||||
.addOptions({
|
||||
"white": t("EXPORTDIALOG_PDF_PAPER_WHITE"),
|
||||
"scene": t("EXPORTDIALOG_PDF_PAPER_SCENE"),
|
||||
"custom": t("EXPORTDIALOG_PDF_PAPER_CUSTOM")
|
||||
white: t("EXPORTDIALOG_PDF_PAPER_WHITE"),
|
||||
scene: t("EXPORTDIALOG_PDF_PAPER_SCENE"),
|
||||
custom: t("EXPORTDIALOG_PDF_PAPER_CUSTOM"),
|
||||
})
|
||||
.setValue(this.settings.paperColor)
|
||||
.onChange(value => {
|
||||
.onChange((value) => {
|
||||
this.settings.paperColor = value as typeof this.settings.paperColor;
|
||||
colorInput.style.display = (value === "custom") ? "block" : "none";
|
||||
colorInput.style.display = value === "custom" ? "block" : "none";
|
||||
this.update();
|
||||
})
|
||||
}),
|
||||
);
|
||||
|
||||
const colorInput = paperColorSetting.controlEl.createEl("input", {
|
||||
type: "color",
|
||||
value: this.settings.customPaperColor
|
||||
value: this.settings.customPaperColor,
|
||||
});
|
||||
colorInput.style.width = "50px";
|
||||
colorInput.style.marginLeft = "10px";
|
||||
colorInput.style.display = this.settings.paperColor === "custom" ? "block" : "none";
|
||||
colorInput.style.display =
|
||||
this.settings.paperColor === "custom" ? "block" : "none";
|
||||
colorInput.addEventListener("change", (e) => {
|
||||
this.settings.customPaperColor = (e.target as HTMLInputElement).value;
|
||||
this.update();
|
||||
@@ -135,10 +160,10 @@ export class PDFExportSettingsComponent {
|
||||
|
||||
new Setting(this.contentEl)
|
||||
.setName(t("EXPORTDIALOG_PDF_ALIGNMENT"))
|
||||
.addDropdown(dropdown =>
|
||||
.addDropdown((dropdown) =>
|
||||
dropdown
|
||||
.addOptions({
|
||||
"center": t("EXPORTDIALOG_PDF_ALIGN_CENTER"),
|
||||
center: t("EXPORTDIALOG_PDF_ALIGN_CENTER"),
|
||||
"center-left": t("EXPORTDIALOG_PDF_ALIGN_CENTER_LEFT"),
|
||||
"center-right": t("EXPORTDIALOG_PDF_ALIGN_CENTER_RIGHT"),
|
||||
"top-left": t("EXPORTDIALOG_PDF_ALIGN_TOP_LEFT"),
|
||||
@@ -146,13 +171,13 @@ export class PDFExportSettingsComponent {
|
||||
"top-right": t("EXPORTDIALOG_PDF_ALIGN_TOP_RIGHT"),
|
||||
"bottom-left": t("EXPORTDIALOG_PDF_ALIGN_BOTTOM_LEFT"),
|
||||
"bottom-center": t("EXPORTDIALOG_PDF_ALIGN_BOTTOM_CENTER"),
|
||||
"bottom-right": t("EXPORTDIALOG_PDF_ALIGN_BOTTOM_RIGHT")
|
||||
"bottom-right": t("EXPORTDIALOG_PDF_ALIGN_BOTTOM_RIGHT"),
|
||||
})
|
||||
.setValue(this.settings.alignment)
|
||||
.onChange(value => {
|
||||
.onChange((value) => {
|
||||
this.settings.alignment = value as PDFPageAlignment;
|
||||
this.update();
|
||||
})
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
+480
-287
File diff suppressed because it is too large.
Load diff
@@ -1,55 +1,107 @@
|
||||
import { Modal, Setting, TFile } from "obsidian";
|
||||
import ExcalidrawPlugin from "src/core/main";
|
||||
import { getIMGFilename } from "src/utils/fileUtils";
|
||||
import { setElementDisplay } from "src/utils/htmlUtils";
|
||||
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;
|
||||
const haveLinkedFilesChanged = (
|
||||
depth: number,
|
||||
mtime: number,
|
||||
path: string,
|
||||
sourceList: Set<string>,
|
||||
plugin: ExcalidrawPlugin,
|
||||
): boolean => {
|
||||
if (depth++ > 5) {
|
||||
return false;
|
||||
}
|
||||
sourceList.add(path);
|
||||
const links = plugin.app.metadataCache.resolvedLinks[path];
|
||||
if(!links) return false;
|
||||
for(const link of Object.keys(links)) {
|
||||
if(sourceList.has(link)) continue;
|
||||
if (!links) {
|
||||
return false;
|
||||
}
|
||||
for (const link of Object.keys(links)) {
|
||||
if (sourceList.has(link)) {
|
||||
continue;
|
||||
}
|
||||
const file = plugin.app.vault.getAbstractFileByPath(link);
|
||||
if(!file || !(file instanceof TFile)) continue;
|
||||
console.log(path, {mtimeLinked: file.stat.mtime, mtimeSource: mtime, path: file.path});
|
||||
if(file.stat.mtime > mtime) return true;
|
||||
if(plugin.isExcalidrawFile(file)) {
|
||||
if(haveLinkedFilesChanged(depth, mtime, file.path, sourceList, plugin)) return true;
|
||||
if (!file || !(file instanceof TFile)) {
|
||||
continue;
|
||||
}
|
||||
console.log(path, {
|
||||
mtimeLinked: file.stat.mtime,
|
||||
mtimeSource: mtime,
|
||||
path: file.path,
|
||||
});
|
||||
if (file.stat.mtime > mtime) {
|
||||
return true;
|
||||
}
|
||||
if (plugin.isExcalidrawFile(file)) {
|
||||
if (haveLinkedFilesChanged(depth, mtime, file.path, sourceList, plugin)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
const listOfOutOfSyncImgExports = async(plugin: ExcalidrawPlugin, recursive: boolean, statusEl: HTMLParagraphElement):Promise<TFile[]> => {
|
||||
const listOfOutOfSyncImgExports = async (
|
||||
plugin: ExcalidrawPlugin,
|
||||
recursive: boolean,
|
||||
statusEl: HTMLParagraphElement,
|
||||
): Promise<TFile[]> => {
|
||||
const app = plugin.app;
|
||||
|
||||
const publish = app.internalPlugins.plugins["publish"].instance;
|
||||
if(!publish) return;
|
||||
const list = await app.internalPlugins.plugins["publish"].instance.apiList();
|
||||
if(!list || !list.files) return;
|
||||
const publish = app.internalPlugins.plugins.publish?.instance;
|
||||
if (!publish) {
|
||||
return;
|
||||
}
|
||||
const list = await publish.apiList();
|
||||
if (!list || !list.files) {
|
||||
return;
|
||||
}
|
||||
const outOfSyncFiles = new Set<TFile>();
|
||||
const allFiles = list.files.filter((f:any)=>(f.path.endsWith(".svg") || f.path.endsWith(".png")))
|
||||
const allFiles = list.files.filter(
|
||||
(f: any) => f.path.endsWith(".svg") || f.path.endsWith(".png"),
|
||||
);
|
||||
const totalCount = allFiles.length;
|
||||
allFiles.forEach((f:any, idx:number)=>{
|
||||
const maybeExcalidraFilePath = getIMGFilename(f.path,"md");
|
||||
allFiles.forEach((f: any, idx: number) => {
|
||||
const maybeExcalidraFilePath = getIMGFilename(f.path, "md");
|
||||
const imgFile = app.vault.getAbstractFileByPath(f.path);
|
||||
const excalidrawFile = app.vault.getAbstractFileByPath(maybeExcalidraFilePath);
|
||||
statusEl.innerText = `Status: ${idx+1}/${totalCount} ${imgFile ? imgFile.name : f.path}`;
|
||||
if(!excalidrawFile || !imgFile || !(excalidrawFile instanceof TFile) || !(imgFile instanceof TFile)) return;
|
||||
if(excalidrawFile.stat.mtime <= imgFile.stat.mtime) {
|
||||
if(!recursive) return;
|
||||
if(!haveLinkedFilesChanged(0, excalidrawFile.stat.mtime, excalidrawFile.path, new Set<string>(), plugin)) return;
|
||||
const excalidrawFile = app.vault.getAbstractFileByPath(
|
||||
maybeExcalidraFilePath,
|
||||
);
|
||||
statusEl.innerText = `Status: ${idx + 1}/${totalCount} ${imgFile ? imgFile.name : f.path}`;
|
||||
if (
|
||||
!excalidrawFile ||
|
||||
!imgFile ||
|
||||
!(excalidrawFile instanceof TFile) ||
|
||||
!(imgFile instanceof TFile)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
if (excalidrawFile.stat.mtime <= imgFile.stat.mtime) {
|
||||
if (!recursive) {
|
||||
return;
|
||||
}
|
||||
if (
|
||||
!haveLinkedFilesChanged(
|
||||
0,
|
||||
excalidrawFile.stat.mtime,
|
||||
excalidrawFile.path,
|
||||
new Set<string>(),
|
||||
plugin,
|
||||
)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
outOfSyncFiles.add(excalidrawFile);
|
||||
});
|
||||
return Array.from(outOfSyncFiles);
|
||||
}
|
||||
};
|
||||
|
||||
export class PublishOutOfDateFilesDialog extends Modal {
|
||||
constructor(
|
||||
private plugin: ExcalidrawPlugin,
|
||||
) {
|
||||
constructor(private plugin: ExcalidrawPlugin) {
|
||||
super(plugin.app);
|
||||
}
|
||||
|
||||
@@ -57,70 +109,90 @@ export class PublishOutOfDateFilesDialog extends Modal {
|
||||
|
||||
onOpen() {
|
||||
this.containerEl.classList.add("excalidraw-release");
|
||||
this.titleEl.setText(`Out of Date SVG Files`);
|
||||
this.createForm(false);
|
||||
this.titleEl.setText(`Out of Date SVG Files`);
|
||||
void this.createForm(false);
|
||||
}
|
||||
|
||||
async createForm(recursive: boolean) {
|
||||
const detailsEl = this.contentEl.createEl("details");
|
||||
detailsEl.createEl("summary", {
|
||||
detailsEl.createEl("summary", {
|
||||
text: "Video about Obsidian Publish support",
|
||||
});
|
||||
detailsEl.createEl("br");
|
||||
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);
|
||||
statusEl.style.display = "none";
|
||||
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,
|
||||
);
|
||||
setElementDisplay(statusEl, "none");
|
||||
|
||||
if(!files || files.length === 0) {
|
||||
if (!files || files.length === 0) {
|
||||
p.innerText = "No out of date files found.";
|
||||
const div = this.contentEl.createDiv({cls: "excalidraw-prompt-buttons-div"});
|
||||
const bClose = div.createEl("button", { text: "Close", cls: "excalidraw-prompt-button"});
|
||||
const div = this.contentEl.createDiv({
|
||||
cls: "excalidraw-prompt-buttons-div",
|
||||
});
|
||||
const bClose = div.createEl("button", {
|
||||
text: "Close",
|
||||
cls: "excalidraw-prompt-button",
|
||||
});
|
||||
bClose.onclick = () => {
|
||||
this.close();
|
||||
};
|
||||
if(!recursive) {
|
||||
const bRecursive = div.createEl("button", { text: "Check Recursive", cls: "excalidraw-prompt-button"});
|
||||
if (!recursive) {
|
||||
const bRecursive = div.createEl("button", {
|
||||
text: "Check Recursive",
|
||||
cls: "excalidraw-prompt-button",
|
||||
});
|
||||
bRecursive.onclick = () => {
|
||||
this.contentEl.empty();
|
||||
this.createForm(true);
|
||||
void this.createForm(true);
|
||||
};
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const filesMap = new Map<TFile,boolean>();
|
||||
const filesMap = new Map<TFile, boolean>();
|
||||
p.innerText = "Select files to open.";
|
||||
files.forEach((f:TFile) => {
|
||||
filesMap.set(f,true);
|
||||
new Setting(this.contentEl)
|
||||
.setName(f.path)
|
||||
.addToggle(toggle => toggle
|
||||
.setValue(true)
|
||||
.onChange(value => {
|
||||
filesMap.set(f,value);
|
||||
})
|
||||
)
|
||||
files.forEach((f: TFile) => {
|
||||
filesMap.set(f, true);
|
||||
new Setting(this.contentEl).setName(f.path).addToggle((toggle) =>
|
||||
toggle.setValue(true).onChange((value) => {
|
||||
filesMap.set(f, value);
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
const div = this.contentEl.createDiv({cls: "excalidraw-prompt-buttons-div"});
|
||||
const bClose = div.createEl("button", { text: "Close", cls: "excalidraw-prompt-button"});
|
||||
const div = this.contentEl.createDiv({
|
||||
cls: "excalidraw-prompt-buttons-div",
|
||||
});
|
||||
const bClose = div.createEl("button", {
|
||||
text: "Close",
|
||||
cls: "excalidraw-prompt-button",
|
||||
});
|
||||
bClose.onclick = () => {
|
||||
this.close();
|
||||
};
|
||||
if(!recursive) {
|
||||
const bRecursive = div.createEl("button", { text: "Check Recursive", cls: "excalidraw-prompt-button"});
|
||||
if (!recursive) {
|
||||
const bRecursive = div.createEl("button", {
|
||||
text: "Check Recursive",
|
||||
cls: "excalidraw-prompt-button",
|
||||
});
|
||||
bRecursive.onclick = () => {
|
||||
this.contentEl.empty();
|
||||
this.createForm(true);
|
||||
void this.createForm(true);
|
||||
};
|
||||
}
|
||||
const bOpen = div.createEl("button", { text: "Open Selected", cls: "excalidraw-prompt-button" });
|
||||
const bOpen = div.createEl("button", {
|
||||
text: "Open Selected",
|
||||
cls: "excalidraw-prompt-button",
|
||||
});
|
||||
bOpen.onclick = () => {
|
||||
filesMap.forEach((value:boolean,key:TFile) => {
|
||||
if(value) {
|
||||
this.plugin.openDrawing(key,"new-tab",true);
|
||||
filesMap.forEach((value: boolean, key: TFile) => {
|
||||
if (value) {
|
||||
this.plugin.openDrawing(key, "new-tab", true);
|
||||
}
|
||||
});
|
||||
this.close();
|
||||
|
||||
@@ -1,10 +1,18 @@
|
||||
import { App, MarkdownRenderer, Modal } from "obsidian";
|
||||
import ExcalidrawPlugin from "../../core/main";
|
||||
import { Rank, SwordColors } from "src/constants/actionIcons";
|
||||
import { convertSVGStringToElement } from "src/utils/utils";
|
||||
|
||||
export class RankMessage extends Modal {
|
||||
|
||||
constructor(app: App, private plugin: ExcalidrawPlugin, private filecount: number, private rank: Rank, private color: string, private shield: string, private dark: string) {
|
||||
constructor(
|
||||
app: App,
|
||||
private plugin: ExcalidrawPlugin,
|
||||
private filecount: number,
|
||||
private rank: Rank,
|
||||
private color: string,
|
||||
private shield: string,
|
||||
private dark: string,
|
||||
) {
|
||||
super(app);
|
||||
}
|
||||
|
||||
@@ -12,7 +20,7 @@ export class RankMessage extends Modal {
|
||||
//this.contentEl.classList.add("excalidraw-release");
|
||||
this.containerEl.classList.add("excalidraw-release");
|
||||
this.titleEl.setText("Congratulations, glorious knight!");
|
||||
this.createForm();
|
||||
void this.createForm();
|
||||
}
|
||||
|
||||
async onClose() {
|
||||
@@ -21,9 +29,13 @@ export class RankMessage extends Modal {
|
||||
}
|
||||
|
||||
async createForm() {
|
||||
const { title} = SwordColors[this.rank];
|
||||
const { title } = SwordColors[this.rank];
|
||||
this.contentEl.createDiv({ cls: "excalidraw-rank" }, (el) => {
|
||||
el.innerHTML = `<svg xmlns="http://www.w3.org/2000/svg" xml:space="preserve" style="enable-background:new 0 0 512 512" viewBox="0 0 511 512"><path fill="${this.color}" d="m389 495 36 7c6 1 11-4 10-10l-6-36a22 22 0 0 0-9-14l-61-46-29 28 45 62a22 22 0 0 0 14 9zm0 0" data-original="#97a7a7"/><path fill="#ffd3bc" d="m333 361-33 4-27 29 1 5 15 13c11 10 27 12 39 3 7-4 12-11 13-20 1-11-3-23-8-34zm0 0" data-original="#ffd3bc"/><path fill="#a5b0bc" d="m288 450-3-50-88-15-87 15-3 50 27 16 28-16v-8c0-6 4-11 10-11h51c6 0 10 5 10 11v8l28 16 27-16zm28-114a332 332 0 0 0-4-6c-14-17-32-30-55-29l16 93 60-33c-5-9-11-18-17-25zm0 0" data-original="#a5b0bc"/><path fill="${this.shield}" d="M281 371c-9-54-24-70-24-70H138s-15 16-24 70l-4 29h175l-4-29zm0 0" data-original="${this.shield}"/><path fill="${this.color}" d="M383 160a30 30 0 1 1-59 0 30 30 0 0 1 59 0zm-312 0a30 30 0 1 1-59 0 30 30 0 0 1 59 0zm0 0" data-original="#97a7a7"/><path fill="#a5b0bc" d="M44 160a153 153 0 1 1 306 0 153 153 0 0 1-306 0zm0 0" data-original="#a5b0bc"/><path fill="#748A8A" d="M107 450v13s-12 10-17 27c-2 7 4 14 11 14h49c7 1 12-5 12-11v-43zm181 0v13s12 10 17 27c2 7-4 14-11 14h-49c-7 1-12-5-12-11v-43zm0 0" data-original="#748A8A"/><path fill="#ffd3bc" d="M44 160s44 76 153 76c110 0 153-76 153-76l-17-30-136-27-127 24zm0 0" data-original="#ffd3bc"/><path fill="#ffbe9c" d="M197 103 70 127l-26 33s5 9 16 20c6-4 50-29 137-29s131 25 138 29c11-11 15-20 15-20l-17-30zm0 0" data-original="#ffbe9c"/><path fill="${this.color}" d="M271 59c-47-18-100-18-147 0-39 15-80 45-80 101 0 0 48-34 153-34s153 34 153 34c0-56-40-86-79-101zm0 0" data-original="#97a7a7"/><path fill="#ff889e" d="M274 201h-18a7 7 0 1 1 0-15h18a7 7 0 1 1 0 15zm-135 0h-18a7 7 0 1 1 0-15h18a7 7 0 1 1 0 15zm0 0" data-original="#ff889e"/><path fill="#748A8A" d="m185 387-75 13-2 47a39 39 0 0 0 2 0c31-10 57-30 75-60zm0 0" data-original="#748A8A"/><path fill="#00000060" d="M186 386c15-24 22-50 25-67a43 43 0 0 0 0-18h-73s-15 16-24 70l-4 29h67a160 160 0 0 0 9-14zm0 0" data-original="#00000060"/><path fill="#748A8A" d="M174 268c-29-4-46-12-54-17a43 43 0 0 0-45 0h-1a153 153 0 0 0 138 62 43 43 0 0 0-38-45zm0 0" data-original="#748A8A"/><path fill="${this.dark}" d="M171 293c-32-4-53-14-64-21a18 18 0 0 0-19 0c-11 7-32 17-64 21-10 1-18 11-16 21 6 31 25 90 84 109a18 18 0 0 0 11 0c58-19 77-78 83-109 2-10-5-20-15-21zm0 0" data-original="${this.dark}"/><path fill="${this.shield}" d="M97 387c-29-11-43-39-50-62 22-5 38-12 50-18 12 6 29 13 50 18-7 23-21 51-50 62zm0 0" data-original="${this.shield}"/><path fill="${this.dark}" d="m327 444 52-51a6 6 0 0 0 0-9c-9-9-24-9-33 0l-28 27c-9 9-9 24 0 33a6 6 0 0 0 9 0zm0 0" data-original="${this.dark}"/><path d="M100 88a8 8 0 0 0-7 8v18a8 8 0 1 0 15 0V96c0-4-3-8-8-8zm49-20a7 7 0 0 0-8 8v36a8 8 0 1 0 15 0V76a8 8 0 0 0-7-8zm145 20a7 7 0 0 0-7 8v18c0 4 3 8 7 8a8 8 0 0 0 8-8V96a8 8 0 0 0-8-8zm-48-20a8 8 0 0 0-8 8v36a8 8 0 1 0 15 0V76c0-4-3-8-7-8zm-49-6c-4 0-7 3-7 7v36a8 8 0 0 0 15 0V69c0-4-3-7-8-7zm68 120c4 0 8-3 8-8v-13a8 8 0 1 0-15 0v13a8 8 0 0 0 7 8zm-135 0c4 0 7-3 7-8v-13a8 8 0 1 0-15 0v13a8 8 0 0 0 8 8zm85 0a8 8 0 0 0-11 1l-7 2-6-2a7 7 0 0 0-11-1c-3 3-3 7 0 11 4 5 11 7 17 7 7 0 14-2 18-7a8 8 0 0 0 0-11zM95 394a8 8 0 0 0 5 0c32-13 47-44 55-67 1-4-2-9-6-10-18-3-34-9-48-17a7 7 0 0 0-7 0c-14 8-30 14-48 17-4 1-7 6-6 10 7 23 22 54 55 67zm2-78c13 6 26 10 41 14-7 18-19 39-41 49a83 83 0 0 1-40-49c15-4 28-8 40-14zm0 0" data-original="#000000"/><path d="M436 455a29 29 0 0 0-11-19l-45-34 4-4c5-5 5-14 0-19-6-6-13-9-22-9a30 30 0 0 0-16 4l-6-16c-5-9-10-17-18-27a375 375 0 0 0-4-6 86 86 0 0 0-37-27c36-22 63-58 73-101a37 37 0 0 0 0-74 161 161 0 0 0-313 0 37 37 0 0 0 0 74c6 27 19 51 38 71-12 7-30 14-56 17-14 2-25 16-22 30 4 19 12 47 29 71a8 8 0 1 0 12-9c-16-22-23-47-26-64-1-6 3-12 9-13 33-4 54-14 67-22 3-2 8-2 11 0 20 13 43 19 67 22 8 1 10 8 8 15-3 18-12 46-31 69-12 15-28 26-47 32h-6c-12-4-23-10-33-18a8 8 0 1 0-9 11c11 10 24 16 38 21l11 1a694 694 0 0 0-1 19v10c-4 4-13 14-17 28-3 12 6 24 18 24h49c11 0 19-8 19-19v-51c0-2 1-3 3-3h51a3 3 0 0 1 3 3v51c0 11 8 19 19 19h49c12 0 21-12 18-24-4-14-13-24-17-28v-10a699 699 0 0 0-1-25 41 41 0 0 0 10 3c0 8 3 15 9 21a14 14 0 0 0 9 4c4 0 7-1 10-4l4-4 33 46a29 29 0 0 0 19 11s36 7 36 7c10 2 20-8 18-18zm-272-68c16-22 24-45 28-65l1-1 21-1a159 159 0 0 0 40-9c4 6 12 22 18 52l4 29H160l4-5zm142-52 17 23-33 18a473 473 0 0 0-19-66c16 4 27 15 35 25zm32-190c-23-11-48-17-73-21a426 426 0 0 0-136 0 267 267 0 0 0-76 23c5-37 29-64 74-81a195 195 0 0 1 141 0c44 17 69 44 74 81a173 173 0 0 0-4-2zm18-6a22 22 0 0 1 0 43h1a162 162 0 0 0 0-43h-1zM197 15c49 0 91 23 118 60-12-9-26-17-41-23A210 210 0 0 0 80 75c27-37 69-60 117-60zM19 160c0-11 9-20 19-21a163 163 0 0 0 0 43c-10-1-19-10-19-22zm130 121c-14-3-27-8-38-16a25 25 0 0 0-14-3 26 26 0 0 0-4 0c-20-21-33-46-38-73a8 8 0 0 0 0-1l-1-3 21 19a196 196 0 0 0 150 38 7 7 0 1 0-1-15 217 217 0 0 1-27 2c-43 0-81-12-112-36-15-12-25-23-30-30l30-13c36-12 74-16 112-16a320 320 0 0 1 143 29c-10 13-38 45-88 59a8 8 0 0 0-5 9 7 7 0 0 0 9 5c42-12 69-34 85-51a138
Line truncated
|
||||
const svgString = `<svg xmlns="http://www.w3.org/2000/svg" xml:space="preserve" style="enable-background:new 0 0 512 512" viewBox="0 0 511 512"><path fill="${this.color}" d="m389 495 36 7c6 1 11-4 10-10l-6-36a22 22 0 0 0-9-14l-61-46-29 28 45 62a22 22 0 0 0 14 9zm0 0" data-original="#97a7a7"/><path fill="#ffd3bc" d="m333 361-33 4-27 29 1 5 15 13c11 10 27 12 39 3 7-4 12-11 13-20 1-11-3-23-8-34zm0 0" data-original="#ffd3bc"/><path fill="#a5b0bc" d="m288 450-3-50-88-15-87 15-3 50 27 16 28-16v-8c0-6 4-11 10-11h51c6 0 10 5 10 11v8l28 16 27-16zm28-114a332 332 0 0 0-4-6c-14-17-32-30-55-29l16 93 60-33c-5-9-11-18-17-25zm0 0" data-original="#a5b0bc"/><path fill="${this.shield}" d="M281 371c-9-54-24-70-24-70H138s-15 16-24 70l-4 29h175l-4-29zm0 0" data-original="${this.shield}"/><path fill="${this.color}" d="M383 160a30 30 0 1 1-59 0 30 30 0 0 1 59 0zm-312 0a30 30 0 1 1-59 0 30 30 0 0 1 59 0zm0 0" data-original="#97a7a7"/><path fill="#a5b0bc" d="M44 160a153 153 0 1 1 306 0 153 153 0 0 1-306 0zm0 0" data-original="#a5b0bc"/><path fill="#748A8A" d="M107 450v13s-12 10-17 27c-2 7 4 14 11 14h49c7 1 12-5 12-11v-43zm181 0v13s12 10 17 27c2 7-4 14-11 14h-49c-7 1-12-5-12-11v-43zm0 0" data-original="#748A8A"/><path fill="#ffd3bc" d="M44 160s44 76 153 76c110 0 153-76 153-76l-17-30-136-27-127 24zm0 0" data-original="#ffd3bc"/><path fill="#ffbe9c" d="M197 103 70 127l-26 33s5 9 16 20c6-4 50-29 137-29s131 25 138 29c11-11 15-20 15-20l-17-30zm0 0" data-original="#ffbe9c"/><path fill="${this.color}" d="M271 59c-47-18-100-18-147 0-39 15-80 45-80 101 0 0 48-34 153-34s153 34 153 34c0-56-40-86-79-101zm0 0" data-original="#97a7a7"/><path fill="#ff889e" d="M274 201h-18a7 7 0 1 1 0-15h18a7 7 0 1 1 0 15zm-135 0h-18a7 7 0 1 1 0-15h18a7 7 0 1 1 0 15zm0 0" data-original="#ff889e"/><path fill="#748A8A" d="m185 387-75 13-2 47a39 39 0 0 0 2 0c31-10 57-30 75-60zm0 0" data-original="#748A8A"/><path fill="#00000060" d="M186 386c15-24 22-50 25-67a43 43 0 0 0 0-18h-73s-15 16-24 70l-4 29h67a160 160 0 0 0 9-14zm0 0" data-original="#00000060"/><path fill="#748A8A" d="M174 268c-29-4-46-12-54-17a43 43 0 0 0-45 0h-1a153 153 0 0 0 138 62 43 43 0 0 0-38-45zm0 0" data-original="#748A8A"/><path fill="${this.dark}" d="M171 293c-32-4-53-14-64-21a18 18 0 0 0-19 0c-11 7-32 17-64 21-10 1-18 11-16 21 6 31 25 90 84 109a18 18 0 0 0 11 0c58-19 77-78 83-109 2-10-5-20-15-21zm0 0" data-original="${this.dark}"/><path fill="${this.shield}" d="M97 387c-29-11-43-39-50-62 22-5 38-12 50-18 12 6 29 13 50 18-7 23-21 51-50 62zm0 0" data-original="${this.shield}"/><path fill="${this.dark}" d="m327 444 52-51a6 6 0 0 0 0-9c-9-9-24-9-33 0l-28 27c-9 9-9 24 0 33a6 6 0 0 0 9 0zm0 0" data-original="${this.dark}"/><path d="M100 88a8 8 0 0 0-7 8v18a8 8 0 1 0 15 0V96c0-4-3-8-8-8zm49-20a7 7 0 0 0-8 8v36a8 8 0 1 0 15 0V76a8 8 0 0 0-7-8zm145 20a7 7 0 0 0-7 8v18c0 4 3 8 7 8a8 8 0 0 0 8-8V96a8 8 0 0 0-8-8zm-48-20a8 8 0 0 0-8 8v36a8 8 0 1 0 15 0V76c0-4-3-8-7-8zm-49-6c-4 0-7 3-7 7v36a8 8 0 0 0 15 0V69c0-4-3-7-8-7zm68 120c4 0 8-3 8-8v-13a8 8 0 1 0-15 0v13a8 8 0 0 0 7 8zm-135 0c4 0 7-3 7-8v-13a8 8 0 1 0-15 0v13a8 8 0 0 0 8 8zm85 0a8 8 0 0 0-11 1l-7 2-6-2a7 7 0 0 0-11-1c-3 3-3 7 0 11 4 5 11 7 17 7 7 0 14-2 18-7a8 8 0 0 0 0-11zM95 394a8 8 0 0 0 5 0c32-13 47-44 55-67 1-4-2-9-6-10-18-3-34-9-48-17a7 7 0 0 0-7 0c-14 8-30 14-48 17-4 1-7 6-6 10 7 23 22 54 55 67zm2-78c13 6 26 10 41 14-7 18-19 39-41 49a83 83 0 0 1-40-49c15-4 28-8 40-14zm0 0" data-original="#000000"/><path d="M436 455a29 29 0 0 0-11-19l-45-34 4-4c5-5 5-14 0-19-6-6-13-9-22-9a30 30 0 0 0-16 4l-6-16c-5-9-10-17-18-27a375 375 0 0 0-4-6 86 86 0 0 0-37-27c36-22 63-58 73-101a37 37 0 0 0 0-74 161 161 0 0 0-313 0 37 37 0 0 0 0 74c6 27 19 51 38 71-12 7-30 14-56 17-14 2-25 16-22 30 4 19 12 47 29 71a8 8 0 1 0 12-9c-16-22-23-47-26-64-1-6 3-12 9-13 33-4 54-14 67-22 3-2 8-2 11 0 20 13 43 19 67 22 8 1 10 8 8 15-3 18-12 46-31 69-12 15-28 26-47 32h-6c-12-4-23-10-33-18a8 8 0 1 0-9 11c11 10 24 16 38 21l11 1a694 694 0 0 0-1 19v10c-4 4-13 14-17 28-3 12 6 24 18 24h49c11 0 19-8 19-19v-51c0-2 1-3 3-3h51a3 3 0 0 1 3 3v51c0 11 8 19 19 19h49c12 0 21-12 18-24-4-14-13-24-17-28v-10a699 699 0 0 0-1-25 41 41 0 0 0 10 3c0 8 3 15 9 21a14 14 0 0 0 9 4c4 0 7-1 10-4l4-4 33 46a29 29 0 0 0 19 11s36 7 36 7c10 2 20-8 18-18zm-272-68c16-22 24-45 28-65l1-1 21-1a159 159 0 0 0 40-9c4 6 12 22 18 52l4 29H160l4-5zm142-52 17 23-33 18a473 473 0 0 0-19-66c16 4 27 15 35 25zm32-190c-23-11-48-17-73-21a426 426 0 0 0-136 0 267 267 0 0 0-76 23c5-37 29-64 74-81a195 195 0 0 1 141 0c44 17 69 44 74 81a173 173 0 0 0-4-2zm18-6a22 22 0 0 1 0 43h1a162 162 0 0 0 0-43h-1zM197 15c49 0 91 23 118 60-12-9-26-17-41-23A210 210 0 0 0 80 75c27-37 69-60 117-60zM19 160c0-11 9-20 19-21a163 163 0 0 0 0 43c-10-1-19-10-19-22zm130 121c-14-3-27-8-38-16a25 25 0 0 0-14-3 26 26 0 0 0-4 0c-20-21-33-46-38-73a8 8 0 0 0 0-1l-1-3 21 19a196 196 0 0 0 150 38 7 7 0 1 0-1-15 217 217 0 0 1-27 2c-43 0-81-12-112-36-15-12-25-23-30-30l30-13c36-12 74-16 112-16a320 320 0 0 1 143 29c-10 13-38 45-88 59a8 8 0 0 0-5 9 7 7 0 0 0 9 5c42-12 69-34 85-51a1
Line truncated
|
||||
const svg = convertSVGStringToElement(svgString);
|
||||
if (svg) {
|
||||
el.appendChild(svg);
|
||||
}
|
||||
});
|
||||
|
||||
await MarkdownRenderer.render(
|
||||
|
||||
@@ -1,36 +1,55 @@
|
||||
import { App, MarkdownRenderer, Modal } from "obsidian";
|
||||
import { isVersionNewerThanOther } from "src/utils/utils";
|
||||
import ExcalidrawPlugin from "../../core/main";
|
||||
import { FIRST_RUN, RELEASE_NOTES } from "./Messages";
|
||||
import { RELEASE_NOTES } from "./Messages";
|
||||
import { t } from "src/lang/helpers";
|
||||
|
||||
declare const PLUGIN_VERSION:string;
|
||||
declare const PLUGIN_VERSION: string;
|
||||
|
||||
type ReleaseNotesOptions = {
|
||||
message?: string;
|
||||
persistVersion?: boolean;
|
||||
title?: string;
|
||||
};
|
||||
|
||||
export class ReleaseNotes extends Modal {
|
||||
private plugin: ExcalidrawPlugin;
|
||||
private options: ReleaseNotesOptions;
|
||||
private version: string;
|
||||
|
||||
constructor(app: App, plugin: ExcalidrawPlugin, version: string) {
|
||||
constructor(
|
||||
app: App,
|
||||
plugin: ExcalidrawPlugin,
|
||||
version: string,
|
||||
options: ReleaseNotesOptions = {},
|
||||
) {
|
||||
super(app);
|
||||
this.plugin = plugin;
|
||||
this.options = options;
|
||||
this.version = version;
|
||||
}
|
||||
|
||||
onOpen(): void {
|
||||
//@ts-ignore
|
||||
const { containerEl, contentEl, titleEl, headerEl } = this;
|
||||
const { containerEl, titleEl, headerEl } = this;
|
||||
//this.contentEl.classList.add("excalidraw-release");
|
||||
containerEl.classList.add("excalidraw-release");
|
||||
titleEl.setText(`${t("RN_WELCOME")} ${this.version ?? ""}`);
|
||||
this.createForm();
|
||||
titleEl.setText(
|
||||
this.options.title ?? `${t("RN_WELCOME")} ${this.version ?? ""}`.trim(),
|
||||
);
|
||||
void this.createForm();
|
||||
|
||||
if(headerEl) headerEl.style.pointerEvents = "none"; // Disable pointer events on header to allow clicks through
|
||||
if (headerEl) {
|
||||
headerEl.style.pointerEvents = "none";
|
||||
} // Disable pointer events on header to allow clicks through
|
||||
}
|
||||
|
||||
async onClose() {
|
||||
this.contentEl.empty();
|
||||
if (this.options.persistVersion === false) {
|
||||
return;
|
||||
}
|
||||
await this.plugin.loadSettings();
|
||||
if(this.plugin.settings.previousRelease !== PLUGIN_VERSION) {
|
||||
if (this.plugin.settings.previousRelease !== PLUGIN_VERSION) {
|
||||
this.plugin.settings.previousRelease = PLUGIN_VERSION;
|
||||
await this.plugin.saveSettings();
|
||||
}
|
||||
@@ -39,13 +58,21 @@ export class ReleaseNotes extends Modal {
|
||||
async createForm() {
|
||||
let prevRelease = this.plugin.settings.previousRelease;
|
||||
prevRelease = this.version === prevRelease ? "0.0.0" : prevRelease;
|
||||
const message = this.version
|
||||
? Object.keys(RELEASE_NOTES)
|
||||
.filter((key) => key === "Intro" || isVersionNewerThanOther(key,prevRelease))
|
||||
.map((key: string) => `${key==="Intro" ? "" : `# ${key}\n`}${RELEASE_NOTES[key]}`)
|
||||
.slice(0, 10)
|
||||
.join("\n\n---\n")
|
||||
: FIRST_RUN;
|
||||
const message =
|
||||
this.options.message ??
|
||||
(this.version
|
||||
? Object.keys(RELEASE_NOTES)
|
||||
.filter(
|
||||
(key) =>
|
||||
key === "Intro" || isVersionNewerThanOther(key, prevRelease),
|
||||
)
|
||||
.map(
|
||||
(key: string) =>
|
||||
`${key === "Intro" ? "" : `# ${key}\n`}${RELEASE_NOTES[key]}`,
|
||||
)
|
||||
.slice(0, 10)
|
||||
.join("\n\n---\n")
|
||||
: t("FIRST_RUN"));
|
||||
await MarkdownRenderer.render(
|
||||
this.app,
|
||||
message,
|
||||
|
||||
@@ -3,7 +3,11 @@ import { t } from "../../lang/helpers";
|
||||
import ExcalidrawView from "src/view/ExcalidrawView";
|
||||
import { getEA } from "src/core";
|
||||
import { ExcalidrawAutomate } from "src/shared/ExcalidrawAutomate";
|
||||
import { CARD_HEIGHT, CARD_WIDTH, MD_EX_SECTIONS } from "src/constants/constants";
|
||||
import {
|
||||
CARD_HEIGHT,
|
||||
CARD_WIDTH,
|
||||
MD_EX_SECTIONS,
|
||||
} from "src/constants/constants";
|
||||
import { addBackOfTheNoteCard } from "src/utils/excalidrawViewUtils";
|
||||
|
||||
export class SelectCard extends FuzzySuggestModal<string> {
|
||||
@@ -14,7 +18,7 @@ export class SelectCard extends FuzzySuggestModal<string> {
|
||||
constructor(
|
||||
public app: App,
|
||||
private view: ExcalidrawView,
|
||||
private sections: string[]
|
||||
private sections: string[],
|
||||
) {
|
||||
super(app);
|
||||
this.limit = 20;
|
||||
@@ -29,12 +33,20 @@ export class SelectCard extends FuzzySuggestModal<string> {
|
||||
if (e.key == "Enter") {
|
||||
if (this.containerEl.innerText.includes(t("EMPTY_SECTION_MESSAGE"))) {
|
||||
const item = this.inputEl.value;
|
||||
if(item === "" || MD_EX_SECTIONS.includes(item)) {
|
||||
if (item === "" || MD_EX_SECTIONS.includes(item)) {
|
||||
new Notice(t("INVALID_SECTION_NAME"));
|
||||
this.close();
|
||||
return;
|
||||
}
|
||||
addBackOfTheNoteCard(this.view, item, true, undefined, undefined, this.center, {x: this.x, y: this.y});
|
||||
void addBackOfTheNoteCard(
|
||||
this.view,
|
||||
item,
|
||||
true,
|
||||
undefined,
|
||||
undefined,
|
||||
this.center,
|
||||
{ x: this.x, y: this.y },
|
||||
);
|
||||
this.close();
|
||||
}
|
||||
}
|
||||
@@ -50,20 +62,23 @@ export class SelectCard extends FuzzySuggestModal<string> {
|
||||
}
|
||||
|
||||
onChooseItem(item: string): void {
|
||||
const ea = getEA(this.view) as ExcalidrawAutomate;
|
||||
if(this.center) {
|
||||
const ea = getEA(this.view);
|
||||
if (this.center) {
|
||||
const centerPos = ea.getViewCenterPosition();
|
||||
if(centerPos) {
|
||||
this.x = centerPos.x - (CARD_WIDTH / 2);
|
||||
this.y = centerPos.y - (CARD_HEIGHT / 2);
|
||||
if (centerPos) {
|
||||
this.x = centerPos.x - CARD_WIDTH / 2;
|
||||
this.y = centerPos.y - CARD_HEIGHT / 2;
|
||||
}
|
||||
}
|
||||
|
||||
const id = ea.addEmbeddable(
|
||||
this.x,this.y,CARD_WIDTH,CARD_HEIGHT,
|
||||
`[[${this.view.file.path}#${item}]]`
|
||||
this.x,
|
||||
this.y,
|
||||
CARD_WIDTH,
|
||||
CARD_HEIGHT,
|
||||
`[[${this.view.file.path}#${item}]]`,
|
||||
);
|
||||
(async () => {
|
||||
void (async () => {
|
||||
await ea.addElementsToView(!this.center, false, true);
|
||||
ea.selectElementsInView([id]);
|
||||
ea.destroy();
|
||||
|
||||
+324
-190
@@ -7,11 +7,10 @@ type SuggesterInfo = {
|
||||
|
||||
const hyperlink = (url: string, text: string) => {
|
||||
return `<a onclick='window.open("${url}")'>${text}</a>`;
|
||||
}
|
||||
};
|
||||
|
||||
const EMBEDDABLE_MDCUSTOMPROPS = `type EmbeddableMDCustomProps = {<br>useObsidianDefaults: boolean;<br>backgroundMatchCanvas: boolean;<br>backgroundMatchElement: boolean;<br>backgroundColor: string;<br>backgroundOpacity: number;<br>borderMatchElement: boolean;<br>borderColor: string;<br>borderOpacity: number;<br>filenameVisible: boolean;<br>};<br>`;
|
||||
|
||||
|
||||
export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
|
||||
{
|
||||
field: "help",
|
||||
@@ -20,10 +19,10 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
|
||||
after: "",
|
||||
},
|
||||
{
|
||||
field:"isExcalidrawMaskFile",
|
||||
code:"isExcalidrawMaskFile(file?:TFile): boolean;",
|
||||
desc:"Returns true if the file is an Excalidraw Mask file. If file is not provided, the function will use ea.targetView.file",
|
||||
after:"",
|
||||
field: "isExcalidrawMaskFile",
|
||||
code: "isExcalidrawMaskFile(file?:TFile): boolean;",
|
||||
desc: "Returns true if the file is an Excalidraw Mask file. If file is not provided, the function will use ea.targetView.file",
|
||||
after: "",
|
||||
},
|
||||
{
|
||||
field: "plugin",
|
||||
@@ -58,7 +57,7 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
|
||||
{
|
||||
field: "style.backgroundColor",
|
||||
code: "[string]",
|
||||
desc: `A valid css color. See ${hyperlink("https://www.w3schools.com/colors/default.asp","W3 School Colors")} for more.`,
|
||||
desc: `A valid css color. See ${hyperlink("https://www.w3schools.com/colors/default.asp", "W3 School Colors")} for more.`,
|
||||
after: "",
|
||||
},
|
||||
{
|
||||
@@ -148,7 +147,7 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
|
||||
{
|
||||
field: "canvas.viewBackgroundColor",
|
||||
code: "[string]",
|
||||
desc: `A valid css color.\nSee ${hyperlink("https://www.w3schools.com/colors/default.asp","W3 School Colors")} for more.`,
|
||||
desc: `A valid css color.\nSee ${hyperlink("https://www.w3schools.com/colors/default.asp", "W3 School Colors")} for more.`,
|
||||
after: "",
|
||||
},
|
||||
{
|
||||
@@ -166,7 +165,8 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
|
||||
{
|
||||
field: "addAppendUpdateCustomData",
|
||||
code: "addAppendUpdateCustomData(id: string, newData: Partial<Record<string, unknown>>)",
|
||||
desc: "Add, modify keys in element customData and preserve existing keys.\n" +
|
||||
desc:
|
||||
"Add, modify keys in element customData and preserve existing keys.\n" +
|
||||
"Creates customData={} if it does not exist.\n" +
|
||||
"Takes the element ID for an element in the elementsDict and the new data to add or modify.\n" +
|
||||
"To delete keys set key value in newData to undefined. so {keyToBeDeleted:undefined} will be deleted.",
|
||||
@@ -204,8 +204,7 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
|
||||
},
|
||||
{
|
||||
field: "getBoundTextElement",
|
||||
code:
|
||||
"getBoundTextElement(element: ExcalidrawElement, searchInView?: boolean): { eaElement?: Mutable<ExcalidrawTextElement>; sceneElement?: ExcalidrawTextElement; };",
|
||||
code: "getBoundTextElement(element: ExcalidrawElement, searchInView?: boolean): { eaElement?: Mutable<ExcalidrawTextElement>; sceneElement?: ExcalidrawTextElement; };",
|
||||
desc:
|
||||
"Returns an object describing the bound text element.\n" +
|
||||
"@param element: ExcalidrawElement | ExcalidrawElement[] - The selected container with text (an array of 2 elements) to check.\n" +
|
||||
@@ -221,25 +220,26 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
|
||||
},
|
||||
{
|
||||
field: "create",
|
||||
code: 'async create(params?: {filename?: string, foldername?: string, templatePath?: string, onNewPane?: boolean, silent?: boolean, frontmatterKeys?: {},}): Promise<string>;',
|
||||
desc: "Create a drawing and save it to filename.\nIf filename is null: default filename as defined in Excalidraw settings.\nIf folder is null: default folder as defined in Excalidraw settings\nReturns the path to the created file.\n" +
|
||||
'frontmatterKeys: {\n' +
|
||||
' "excalidraw-plugin"?: "raw" | "parsed";\n' +
|
||||
' "excalidraw-link-prefix"?: string;\n' +
|
||||
' "excalidraw-link-brackets"?: boolean;\n' +
|
||||
' "excalidraw-url-prefix"?: string;\n' +
|
||||
' "excalidraw-export-transparent"?: boolean;\n' +
|
||||
' "excalidraw-export-dark"?: boolean;\n' +
|
||||
' "excalidraw-export-padding"?: number;\n' +
|
||||
' "excalidraw-export-pngscale"?: number;\n' +
|
||||
' "excalidraw-export-embed-scene"?: boolean;\n' +
|
||||
' "excalidraw-default-mode"?: "view" | "zen";\n' +
|
||||
' "excalidraw-onload-script"?: string;\n' +
|
||||
' "excalidraw-linkbutton-opacity"?: number;\n' +
|
||||
' "excalidraw-autoexport"?: boolean;\n' +
|
||||
' "excalidraw-mask"?: boolean;\n' +
|
||||
' "excalidraw-export-internal-links"?: boolean;\n' +
|
||||
' "cssclasses"?: string;\n}',
|
||||
code: "async create(params?: {filename?: string, foldername?: string, templatePath?: string, onNewPane?: boolean, silent?: boolean, frontmatterKeys?: {},}): Promise<string>;",
|
||||
desc:
|
||||
"Create a drawing and save it to filename.\nIf filename is null: default filename as defined in Excalidraw settings.\nIf folder is null: default folder as defined in Excalidraw settings\nReturns the path to the created file.\n" +
|
||||
"frontmatterKeys: {\n" +
|
||||
' "excalidraw-plugin"?: "raw" | "parsed";\n' +
|
||||
' "excalidraw-link-prefix"?: string;\n' +
|
||||
' "excalidraw-link-brackets"?: boolean;\n' +
|
||||
' "excalidraw-url-prefix"?: string;\n' +
|
||||
' "excalidraw-export-transparent"?: boolean;\n' +
|
||||
' "excalidraw-export-dark"?: boolean;\n' +
|
||||
' "excalidraw-export-padding"?: number;\n' +
|
||||
' "excalidraw-export-pngscale"?: number;\n' +
|
||||
' "excalidraw-export-embed-scene"?: boolean;\n' +
|
||||
' "excalidraw-default-mode"?: "view" | "zen";\n' +
|
||||
' "excalidraw-onload-script"?: string;\n' +
|
||||
' "excalidraw-linkbutton-opacity"?: number;\n' +
|
||||
' "excalidraw-autoexport"?: boolean;\n' +
|
||||
' "excalidraw-mask"?: boolean;\n' +
|
||||
' "excalidraw-export-internal-links"?: boolean;\n' +
|
||||
' "cssclasses"?: string;\n}',
|
||||
after: "",
|
||||
},
|
||||
{
|
||||
@@ -251,83 +251,88 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
|
||||
{
|
||||
field: "createPDF",
|
||||
code: "async createPDF({SVG: SVGSVGElement[], scale?: PDFExportScale, pageProps?: PDFPageProperties, filename: string}): Promise<void>",
|
||||
desc: "Creates a PDF from the provided SVG elements with specified scaling and page properties.\n" +
|
||||
"\n" +
|
||||
"@param {Object} params - The parameters for creating the PDF.\n" +
|
||||
"@param {SVGSVGElement[]} params.SVG - An array of SVG elements to be included in the PDF. If multiple SVGs are provided, each will be added to a new page.\n" +
|
||||
"@param {PDFExportScale} [params.scale={ fitToPage: true, zoom: 1 }] - The scaling options for the SVG elements.\n" +
|
||||
"@param {PDFPageProperties} [params.pageProps] - The properties for the PDF pages.\n" +
|
||||
"@param {string} params.filename - The name of the PDF file to be created.\n" +
|
||||
"@returns {Promise<ArrayBuffer>} - A promise that resolves to an ArrayBuffer containing the PDF data.\n" +
|
||||
"\n" +
|
||||
"@typedef {Object} PDFExportScale\n" +
|
||||
"@property {boolean} fitToPage - Whether to fit the SVG to the page.\n" +
|
||||
"@property {number} [zoom=1] - The zoom level for the SVG. Used only if fitToPage is false. If the SVG does not fit the page, it will be tiled over multiple pages.\n" +
|
||||
"\n" +
|
||||
"@typedef {Object} PDFPageProperties\n" +
|
||||
"@property {{width: number, height: number}} [dimensions] - The dimensions of the PDF pages in pixels. Use getPageDimensions to get standard page sizes.\n" +
|
||||
"@property {string} [backgroundColor] - The background color of the PDF pages.\n" +
|
||||
"@property {PDFMargin} margin - The margins of the PDF pages in pixels.\n" +
|
||||
"@property {PDFPageAlignment} alignment - The alignment of the SVG on the PDF pages.",
|
||||
after: "({\n" +
|
||||
" SVG: [svgElement1, svgElement2],\n" +
|
||||
" scale: { fitToPage: true },\n" +
|
||||
" pageProps: {\n" +
|
||||
" dimensions: { width: 595.28, height: 841.89 },\n" +
|
||||
" backgroundColor: \"#ffffff\",\n" +
|
||||
" margin: { left: 20, right: 20, top: 20, bottom: 20 },\n" +
|
||||
" alignment: \"center\"\n" +
|
||||
" filename: \"myPDF.pdf\"\n" +
|
||||
" }\n" +
|
||||
"});",
|
||||
desc:
|
||||
"Creates a PDF from the provided SVG elements with specified scaling and page properties.\n" +
|
||||
"\n" +
|
||||
"@param {Object} params - The parameters for creating the PDF.\n" +
|
||||
"@param {SVGSVGElement[]} params.SVG - An array of SVG elements to be included in the PDF. If multiple SVGs are provided, each will be added to a new page.\n" +
|
||||
"@param {PDFExportScale} [params.scale={ fitToPage: true, zoom: 1 }] - The scaling options for the SVG elements.\n" +
|
||||
"@param {PDFPageProperties} [params.pageProps] - The properties for the PDF pages.\n" +
|
||||
"@param {string} params.filename - The name of the PDF file to be created.\n" +
|
||||
"@returns {Promise<ArrayBuffer>} - A promise that resolves to an ArrayBuffer containing the PDF data.\n" +
|
||||
"\n" +
|
||||
"@typedef {Object} PDFExportScale\n" +
|
||||
"@property {boolean} fitToPage - Whether to fit the SVG to the page.\n" +
|
||||
"@property {number} [zoom=1] - The zoom level for the SVG. Used only if fitToPage is false. If the SVG does not fit the page, it will be tiled over multiple pages.\n" +
|
||||
"\n" +
|
||||
"@typedef {Object} PDFPageProperties\n" +
|
||||
"@property {{width: number, height: number}} [dimensions] - The dimensions of the PDF pages in pixels. Use getPageDimensions to get standard page sizes.\n" +
|
||||
"@property {string} [backgroundColor] - The background color of the PDF pages.\n" +
|
||||
"@property {PDFMargin} margin - The margins of the PDF pages in pixels.\n" +
|
||||
"@property {PDFPageAlignment} alignment - The alignment of the SVG on the PDF pages.",
|
||||
after:
|
||||
"({\n" +
|
||||
" SVG: [svgElement1, svgElement2],\n" +
|
||||
" scale: { fitToPage: true },\n" +
|
||||
" pageProps: {\n" +
|
||||
" dimensions: { width: 595.28, height: 841.89 },\n" +
|
||||
' backgroundColor: "#ffffff",\n' +
|
||||
" margin: { left: 20, right: 20, top: 20, bottom: 20 },\n" +
|
||||
' alignment: "center"\n' +
|
||||
' filename: "myPDF.pdf"\n' +
|
||||
" }\n" +
|
||||
"});",
|
||||
},
|
||||
{
|
||||
field: "createViewSVG",
|
||||
code: "async createViewSVG({withBackground?: boolean, theme?: 'light' | 'dark', frameRendering?: FrameRenderingOptions, padding?: number, selectedOnly?: boolean, skipInliningFonts?: boolean, embedScene?: boolean}): Promise<SVGSVGElement>",
|
||||
desc: "Creates an SVG representation of the current view with specified options.\n" +
|
||||
"\n" +
|
||||
"@param {Object} options - The options for creating the SVG.\n" +
|
||||
"@param {boolean} [options.withBackground=true] - Whether to include the background in the SVG.\n" +
|
||||
"@param {\"light\" | \"dark\"} [options.theme] - The theme to use for the SVG.\n" +
|
||||
"@param {FrameRenderingOptions} [options.frameRendering={enabled: true, name: true, outline: true, clip: true}] - The frame rendering options.\n" +
|
||||
"@param {number} [options.padding] - The padding to apply around the SVG.\n" +
|
||||
"@param {boolean} [options.selectedOnly=false] - Whether to include only the selected elements in the SVG.\n" +
|
||||
"@param {boolean} [options.skipInliningFonts=false] - Whether to skip inlining fonts in the SVG.\n" +
|
||||
"@param {boolean} [options.embedScene=false] - Whether to embed the scene in the SVG.\n" +
|
||||
"@returns {Promise<SVGSVGElement>} A promise that resolves to the SVG element.\n" +
|
||||
"\n" +
|
||||
"@typedef {Object} FrameRenderingOptions\n" +
|
||||
"@property {boolean} enabled - Whether frame rendering is enabled.\n" +
|
||||
"@property {boolean} name - Whether to include the name in the frame rendering.\n" +
|
||||
"@property {boolean} outline - Whether to include the outline in the frame rendering.\n" +
|
||||
"@property {boolean} clip - Whether to clip the frame rendering.\n",
|
||||
after: "({\n" +
|
||||
" withBackground: true,\n" +
|
||||
" theme: 'light',\n" +
|
||||
" frameRendering: { enabled: true, name: true, outline: true, clip: true },\n" +
|
||||
" padding: 10,\n" +
|
||||
" selectedOnly: false,\n" +
|
||||
" skipInliningFonts: false,\n" +
|
||||
" embedScene: false,\n" +
|
||||
"});",
|
||||
},
|
||||
desc:
|
||||
"Creates an SVG representation of the current view with specified options.\n" +
|
||||
"\n" +
|
||||
"@param {Object} options - The options for creating the SVG.\n" +
|
||||
"@param {boolean} [options.withBackground=true] - Whether to include the background in the SVG.\n" +
|
||||
'@param {"light" | "dark"} [options.theme] - The theme to use for the SVG.\n' +
|
||||
"@param {FrameRenderingOptions} [options.frameRendering={enabled: true, name: true, outline: true, clip: true}] - The frame rendering options.\n" +
|
||||
"@param {number} [options.padding] - The padding to apply around the SVG.\n" +
|
||||
"@param {boolean} [options.selectedOnly=false] - Whether to include only the selected elements in the SVG.\n" +
|
||||
"@param {boolean} [options.skipInliningFonts=false] - Whether to skip inlining fonts in the SVG.\n" +
|
||||
"@param {boolean} [options.embedScene=false] - Whether to embed the scene in the SVG.\n" +
|
||||
"@returns {Promise<SVGSVGElement>} A promise that resolves to the SVG element.\n" +
|
||||
"\n" +
|
||||
"@typedef {Object} FrameRenderingOptions\n" +
|
||||
"@property {boolean} enabled - Whether frame rendering is enabled.\n" +
|
||||
"@property {boolean} name - Whether to include the name in the frame rendering.\n" +
|
||||
"@property {boolean} outline - Whether to include the outline in the frame rendering.\n" +
|
||||
"@property {boolean} clip - Whether to clip the frame rendering.\n",
|
||||
after:
|
||||
"({\n" +
|
||||
" withBackground: true,\n" +
|
||||
" theme: 'light',\n" +
|
||||
" frameRendering: { enabled: true, name: true, outline: true, clip: true },\n" +
|
||||
" padding: 10,\n" +
|
||||
" selectedOnly: false,\n" +
|
||||
" skipInliningFonts: false,\n" +
|
||||
" embedScene: false,\n" +
|
||||
"});",
|
||||
},
|
||||
{
|
||||
field: "getPagePDFDimensions",
|
||||
code: "getPagePDFDimensions(pageSize: PageSize, orientation: PageOrientation): PageDimensions",
|
||||
desc: "Returns the dimensions of a standard page size in pixels.\n" +
|
||||
"\n" +
|
||||
"@param {PageSize} pageSize - The standard page size. Possible values are \"A0\", \"A1\", \"A2\", \"A3\", \"A4\", \"A5\", \"Letter\", \"Legal\", \"Tabloid\".\n" +
|
||||
"@param {PageOrientation} orientation - The orientation of the page. Possible values are \"portrait\" and \"landscape\".\n" +
|
||||
"@returns {PageDimensions} - An object containing the width and height of the page in pixels.\n" +
|
||||
"\n" +
|
||||
"@typedef {Object} PageDimensions\n" +
|
||||
"@property {number} width - The width of the page in pixels.\n" +
|
||||
"@property {number} height - The height of the page in pixels.\n" +
|
||||
"\n" +
|
||||
"@typedef {\"A0\" | \"A1\" | \"A2\" | \"A3\" | \"A4\" | \"A5\" | \"Letter\" | \"Legal\" | \"Tabloid\"} PageSize\n" +
|
||||
"\n" +
|
||||
"@typedef {\"portrait\" | \"landscape\"} PageOrientation",
|
||||
after: "(\"A4\", \"portrait\");",
|
||||
desc:
|
||||
"Returns the dimensions of a standard page size in pixels.\n" +
|
||||
"\n" +
|
||||
'@param {PageSize} pageSize - The standard page size. Possible values are "A0", "A1", "A2", "A3", "A4", "A5", "Letter", "Legal", "Tabloid".\n' +
|
||||
'@param {PageOrientation} orientation - The orientation of the page. Possible values are "portrait" and "landscape".\n' +
|
||||
"@returns {PageDimensions} - An object containing the width and height of the page in pixels.\n" +
|
||||
"\n" +
|
||||
"@typedef {Object} PageDimensions\n" +
|
||||
"@property {number} width - The width of the page in pixels.\n" +
|
||||
"@property {number} height - The height of the page in pixels.\n" +
|
||||
"\n" +
|
||||
'@typedef {"A0" | "A1" | "A2" | "A3" | "A4" | "A5" | "Letter" | "Legal" | "Tabloid"} PageSize\n' +
|
||||
"\n" +
|
||||
'@typedef {"portrait" | "landscape"} PageOrientation',
|
||||
after: '("A4", "portrait");',
|
||||
},
|
||||
{
|
||||
field: "createPNG",
|
||||
@@ -385,14 +390,15 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
|
||||
},
|
||||
{
|
||||
field: "refreshTextElementSize",
|
||||
code: 'refreshTextElementSize(id: string);',
|
||||
code: "refreshTextElementSize(id: string);",
|
||||
desc: "Refreshes the size of the text element. Intended to be used when you copyViewElementsToEAforEditing() and then change the text in a text element and want to update the size of the text element to fit the modifid contents.",
|
||||
after: "",
|
||||
},
|
||||
{
|
||||
field: "addText",
|
||||
code: 'addText(topX: number, topY: number, text: string, formatting?: {autoResize?: boolean; wrapAt?: number; width?: number; height?: number; textAlign?: "left" | "center" | "right"; textVerticalAlign: "top" | "middle" | "bottom"; box?: boolean | "box" | "blob" | "ellipse" | "diamond"; boxPadding?: number; boxStrokeColor?: string;}, id?: string,): string;',
|
||||
desc: "If box is !null, then text will be boxed\nThe function returns the id of the TextElement. If the text element is boxed i.e. it is a sticky note, then the id of the container object.\n"+
|
||||
desc:
|
||||
"If box is !null, then text will be boxed\nThe function returns the id of the TextElement. If the text element is boxed i.e. it is a sticky note, then the id of the container object.\n" +
|
||||
"Default value for autoResize is true. Setting autoResize to false will wrap the text in the text element without the need for the container. If set to false, you must provide a width value as well.\n" +
|
||||
"wrapAt will be ignored if autoResize is set to false (and a width is also provided)",
|
||||
after: "",
|
||||
@@ -405,8 +411,7 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
|
||||
},
|
||||
{
|
||||
field: "addArrow",
|
||||
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;',
|
||||
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' +
|
||||
@@ -418,7 +423,8 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
|
||||
{
|
||||
field: "addImage",
|
||||
code: "async addImage(opts: {topX: number, topY: number, imageFile: TFile|string, scale?: boolean, anchor?: boolean, colorMap?: ColorMap}): Promise<string>;",
|
||||
desc: "imageFile may be a TFile or a string that contains a hyperlink.\n" +
|
||||
desc:
|
||||
"imageFile may be a TFile or a string containing an http(s)/ftp/file hyperlink, a vault path, or a data URL such as 'data:image/png;base64,...'.\n" +
|
||||
"imageFile may also be an obsidian filepath including a reference eg.: 'path/my.pdf#page=3'\n" +
|
||||
"Set scale to false if you want to embed the image at 100% of its original size. Default is true which will insert a scaled image.\n" +
|
||||
"anchor will only be evaluated if scale is false. anchor true will add |100% to the end of the filename, resulting in an image that will always pop back to 100% when the source file is updated or when the Excalidraw file is reopened.\n" +
|
||||
@@ -429,21 +435,26 @@ 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 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,
|
||||
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" +
|
||||
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: "",
|
||||
},
|
||||
{
|
||||
field: "addMermaid",
|
||||
code: "async addMermaid(diagram: string, groupElements: boolean = true,): Promise<string[]|string>;",
|
||||
desc: "Creates a mermaid diagram and returns the ids of the created elements as a string[]. " +
|
||||
desc:
|
||||
"Creates a mermaid diagram and returns the ids of the created elements as a string[]. " +
|
||||
"The elements will be added to ea. To add them to the canvas you'll need to use addElementsToView. " +
|
||||
"Depending on the diagram type the result will be either a single SVG image, or a number of excalidraw elements.<br>" +
|
||||
"If there is an error, the function returns a string with the error message.",
|
||||
@@ -470,9 +481,9 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
|
||||
{
|
||||
field: "addLabelToLine",
|
||||
code: "addLabelToLine(lineId: string, label: string): string;",
|
||||
desc: 'Adds a text label to a line or arrow. Currently only works with a simple straight 2-point (start & end) line',
|
||||
desc: "Adds a text label to a line or arrow. Currently only works with a simple straight 2-point (start & end) line",
|
||||
after: "",
|
||||
},
|
||||
},
|
||||
{
|
||||
field: "clear",
|
||||
code: "clear(): void;",
|
||||
@@ -500,7 +511,8 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
|
||||
{
|
||||
field: "setView",
|
||||
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. " +
|
||||
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' +
|
||||
@@ -515,7 +527,7 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
|
||||
{
|
||||
field: "getExcalidrawAPI",
|
||||
code: "getExcalidrawAPI(): any;",
|
||||
desc: `${hyperlink("https://github.com/excalidraw/excalidraw/tree/master/src/packages/excalidraw#ref","Excalidraw API")}`,
|
||||
desc: `${hyperlink("https://github.com/excalidraw/excalidraw/tree/master/src/packages/excalidraw#ref", "Excalidraw API")}`,
|
||||
after: "",
|
||||
},
|
||||
{
|
||||
@@ -533,9 +545,12 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
|
||||
{
|
||||
field: "addBackOfTheCardNoteToView",
|
||||
code: "async addBackOfTheCardNoteToView(sectionTitle: string, activate: boolean = false, sectionBody?: string, embeddableCustomData?: EmbeddableMDCustomProps): Promise<string>",
|
||||
desc: "Adds a back of the note card to the current active view. If <b>body</b> is provided the note will be created with the body text, otherwise the note will be created with the title only.<br>Returns the id of the created element.<br>" +
|
||||
"If <b>activate</b> is true, the embedded note will be activated for editing.<br>" +
|
||||
"This is an async function, if you need the element ID of the created element, the function should be awaited.<br>" + EMBEDDABLE_MDCUSTOMPROPS,
|
||||
desc:
|
||||
`Adds a back of the note card to the current active view. If <b>body</b> is provided the note will be created with the body text, otherwise the note will be created with the title only.<br>Returns the id of the created element.<br>` +
|
||||
`If <b>activate</b> is true, the embedded note will be activated for editing.<br>` +
|
||||
`This is an async function, if you need the element ID of the created element, the function should be awaited.<br>${
|
||||
EMBEDDABLE_MDCUSTOMPROPS
|
||||
}`,
|
||||
after: "",
|
||||
},
|
||||
{
|
||||
@@ -559,42 +574,47 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
|
||||
{
|
||||
field: "updateViewSVGImageColorMap",
|
||||
code: "async updateViewSVGImageColorMap(elements: ExcalidrawImageElement | ExcalidrawImageElement[], colors: ColorMap | SVGColorInfo | ColorMap[] | SVGColorInfo[]): Promise<void>;",
|
||||
desc: 'Updates the color map of an SVG image element in the view. If a ColorMap is provided, it will be used directly. If an SVGColorInfo is provided, it will be converted to a ColorMap. The view will be marked as dirty (i.e. will be saved at next scheduled time) and the image will be reset using the color map.\n'+
|
||||
'See "Shade Master" scritp in Script Library for an example of using this function.\n\n' +
|
||||
'type SVGColorInfo = Map<string, { mappedTo: string; fill: boolean; stroke: boolean; }>\n' +
|
||||
'type ColorMap = { [color: string]: string; invertInDarkMode?: boolean; }',
|
||||
desc:
|
||||
"Updates the color map of an SVG image element in the view. If a ColorMap is provided, it will be used directly. If an SVGColorInfo is provided, it will be converted to a ColorMap. The view will be marked as dirty (i.e. will be saved at next scheduled time) and the image will be reset using the color map.\n" +
|
||||
'See "Shade Master" scritp in Script Library for an example of using this function.\n\n' +
|
||||
"type SVGColorInfo = Map<string, { mappedTo: string; fill: boolean; stroke: boolean; }>\n" +
|
||||
"type ColorMap = { [color: string]: string; invertInDarkMode?: boolean; }",
|
||||
after: "",
|
||||
},
|
||||
{
|
||||
field: "getColorMapForImageElement",
|
||||
code: "getColorMapForImageElement(el: ExcalidrawElement): ColorMap",
|
||||
desc: 'Retrieves the color map for an image element. The color map contains information about the mapping of colors used in the image. If the element already has a color map, it will be returned. The colorMap does not include all colors in the image, only those that have been mapped.\n' +
|
||||
'See "Shade Master" scritp in Script Library for an example of using this function.\n\n' +
|
||||
'type ColorMap = { [color: string]: string; invertInDarkMode?: boolean; }',
|
||||
desc:
|
||||
"Retrieves the color map for an image element. The color map contains information about the mapping of colors used in the image. If the element already has a color map, it will be returned. The colorMap does not include all colors in the image, only those that have been mapped.\n" +
|
||||
'See "Shade Master" scritp in Script Library for an example of using this function.\n\n' +
|
||||
"type ColorMap = { [color: string]: string; invertInDarkMode?: boolean; }",
|
||||
after: "",
|
||||
},
|
||||
{
|
||||
field: "getSVGColorInfoForImgElement",
|
||||
code: "async getColorMapForImgElement(el: ExcalidrawElement): Promise<SVGColorInfo>",
|
||||
desc: 'This function must be awaited. Retrieves the color map for an SVG image element. The color map contains information about the fill and stroke colors used in the SVG. If the element already has a color map, it will be merged with the colors extracted from the SVG.\n' +
|
||||
'See "Shade Master" scritp in Script Library for an example of using this function.\n\n' +
|
||||
'type SVGColorInfo = Map<string, { mappedTo: string; fill: boolean; stroke: boolean; }>',
|
||||
desc:
|
||||
"This function must be awaited. Retrieves the color map for an SVG image element. The color map contains information about the fill and stroke colors used in the SVG. If the element already has a color map, it will be merged with the colors extracted from the SVG.\n" +
|
||||
'See "Shade Master" scritp in Script Library for an example of using this function.\n\n' +
|
||||
"type SVGColorInfo = Map<string, { mappedTo: string; fill: boolean; stroke: boolean; }>",
|
||||
after: "",
|
||||
},
|
||||
{
|
||||
field: "getColosFromExcalidrawFile",
|
||||
code: "async getColosFromExcalidrawFile(file:TFile, img: ExcalidrawImageElement): Promise<SVGColorInfo>",
|
||||
desc: 'Must be awaited. Extracts the fill (background) and stroke colors from an excalidraw file and returns them as an SVGColorInfo. The SVGColorInfo is a map where the keys are the colors used in the SVG and the values contain information about whether the color is used for fill, stroke, or both.\n' +
|
||||
'See "Shade Master" scritp in Script Library for an example of using this function.\n\n' +
|
||||
'type SVGColorInfo = Map<string, { mappedTo: string; fill: boolean; stroke: boolean; }>',
|
||||
desc:
|
||||
"Must be awaited. Extracts the fill (background) and stroke colors from an excalidraw file and returns them as an SVGColorInfo. The SVGColorInfo is a map where the keys are the colors used in the SVG and the values contain information about whether the color is used for fill, stroke, or both.\n" +
|
||||
'See "Shade Master" scritp in Script Library for an example of using this function.\n\n' +
|
||||
"type SVGColorInfo = Map<string, { mappedTo: string; fill: boolean; stroke: boolean; }>",
|
||||
after: "",
|
||||
},
|
||||
{
|
||||
field: "getColorsFromSVGString",
|
||||
code: "getColorsFromSVGString(svgString: string): SVGColorInfo",
|
||||
desc: 'Extracts the fill and stroke colors from an SVG string and returns them as an SVGColorInfo. The SVGColorInfo is a map where the keys are the colors used in the SVG and the values contain information about whether the color is used for fill, stroke, or both.\n' +
|
||||
'See "Shade Master" scritp in Script Library for an example of using this function.\n\n' +
|
||||
'type SVGColorInfo = Map<string, { mappedTo: string; fill: boolean; stroke: boolean; }>',
|
||||
desc:
|
||||
"Extracts the fill and stroke colors from an SVG string and returns them as an SVGColorInfo. The SVGColorInfo is a map where the keys are the colors used in the SVG and the values contain information about whether the color is used for fill, stroke, or both.\n" +
|
||||
'See "Shade Master" scritp in Script Library for an example of using this function.\n\n' +
|
||||
"type SVGColorInfo = Map<string, { mappedTo: string; fill: boolean; stroke: boolean; }>",
|
||||
after: "",
|
||||
},
|
||||
{
|
||||
@@ -618,7 +638,8 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
|
||||
{
|
||||
field: "addElementsToView",
|
||||
code: "async addElementsToView(repositionToCursor?: boolean, save?: boolean, newElementsOnTop?: boolean,shouldRestoreElements?: boolean,captureUpdate?: CaptureUpdateActionType): Promise<boolean>;",
|
||||
desc: "Adds elements from elementsDict to the current view\nrepositionToCursor: default is false\n" +
|
||||
desc:
|
||||
"Adds elements from elementsDict to the current view\nrepositionToCursor: default is false\n" +
|
||||
"save: default is true\n" +
|
||||
"newElementsOnTop: default is false, i.e. the new elements get to the bottom of the stack\n" +
|
||||
"newElementsOnTop controls whether elements created with ExcalidrawAutomate are added at the bottom of the stack or the top of the stack of elements already in the view\nNote that elements copied to the view with copyViewElementsToEAforEditing retain their position in the stack of elements in the view even if modified using EA\n" +
|
||||
@@ -640,7 +661,8 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
|
||||
{
|
||||
field: "getExportSettings",
|
||||
code: "getExportSettings(withBackground: boolean, withTheme: boolean,): ExportSettings;",
|
||||
desc: "Utility function to generate ExportSettings object\n" +
|
||||
desc:
|
||||
"Utility function to generate ExportSettings object\n" +
|
||||
"export interface ExportSettings {\n" +
|
||||
" withBackground: boolean;\n" +
|
||||
" withTheme: boolean;\n" +
|
||||
@@ -694,9 +716,10 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
|
||||
{
|
||||
field: "getElementsInTheSameGroupWithElement",
|
||||
code: "getElementsInTheSameGroupWithElement(element: ExcalidrawElement, elements: ExcalidrawElement[], includeFrameElements: boolean = false): ExcalidrawElement[];",
|
||||
desc: "Gets all the elements from elements[] that share one or more groupIds with element.<br>" +
|
||||
desc:
|
||||
"Gets all the elements from elements[] that share one or more groupIds with element.<br>" +
|
||||
"If includeFrameElements is true, then if the frame is part of the group all the elements that are in the frame will also be included in the result set",
|
||||
after: ""
|
||||
after: "",
|
||||
},
|
||||
{
|
||||
field: "getElementsInFrame",
|
||||
@@ -707,19 +730,19 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
|
||||
{
|
||||
field: "activeScript",
|
||||
code: "activeScript: string;",
|
||||
desc: `Mandatory to set before calling the get and set ScriptSettings functions. Set automatically by the ScriptEngine\nSee for more details: ${hyperlink("https://zsviczian.github.io/obsidian-excalidraw-plugin/ExcalidrawScriptsEngine.html","Script Engine Help")}`,
|
||||
desc: `Mandatory to set before calling the get and set ScriptSettings functions. Set automatically by the ScriptEngine\nSee for more details: ${hyperlink("https://zsviczian.github.io/obsidian-excalidraw-plugin/ExcalidrawScriptsEngine.html", "Script Engine Help")}`,
|
||||
after: "",
|
||||
},
|
||||
{
|
||||
field: "getScriptSettings",
|
||||
code: "getScriptSettings(): {};",
|
||||
desc: `Returns script settings. Saves settings in plugin settings, under the activeScript key. See for more details: ${hyperlink("https://zsviczian.github.io/obsidian-excalidraw-plugin/ExcalidrawScriptsEngine.html","Script Engine Help")}`,
|
||||
desc: `Returns script settings. Saves settings in plugin settings, under the activeScript key. See for more details: ${hyperlink("https://zsviczian.github.io/obsidian-excalidraw-plugin/ExcalidrawScriptsEngine.html", "Script Engine Help")}`,
|
||||
after: "",
|
||||
},
|
||||
{
|
||||
field: "setScriptSettings",
|
||||
code: "async setScriptSettings(settings: any): Promise<void>;",
|
||||
desc: `Sets script settings.\nSee for more details: ${hyperlink("https://zsviczian.github.io/obsidian-excalidraw-plugin/ExcalidrawScriptsEngine.html","Script Engine Help")}`,
|
||||
desc: `Sets script settings.\nSee for more details: ${hyperlink("https://zsviczian.github.io/obsidian-excalidraw-plugin/ExcalidrawScriptsEngine.html", "Script Engine Help")}`,
|
||||
after: "",
|
||||
},
|
||||
{
|
||||
@@ -729,7 +752,7 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
|
||||
`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` +
|
||||
`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: "" });`,
|
||||
},
|
||||
@@ -740,7 +763,7 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
|
||||
`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` +
|
||||
`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: "" });`,
|
||||
},
|
||||
@@ -750,7 +773,7 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
|
||||
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")}`,
|
||||
`See for more details: ${hyperlink("https://zsviczian.github.io/obsidian-excalidraw-plugin/ExcalidrawScriptsEngine.html", "Script Engine Help")}`,
|
||||
after: "()",
|
||||
},
|
||||
{
|
||||
@@ -768,18 +791,20 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
|
||||
{
|
||||
field: "getOriginalImageSize",
|
||||
code: "async getOriginalImageSize(imageElement: ExcalidrawImageElement, shouldWaitForImage: boolean=false): Promise<{width: number; height: number}>",
|
||||
desc: "Returns the size of the image element at 100% (i.e. the original size) or undefined if the data URL is not available.\n"+
|
||||
"If shouldWaitForImage is true, the function will wait for the view to load the image before returning the size.\n"+
|
||||
desc:
|
||||
"Returns the size of the image element at 100% (i.e. the original size) or undefined if the data URL is not available.\n" +
|
||||
"If shouldWaitForImage is true, the function will wait for the view to load the image before returning the size.\n" +
|
||||
"This is an async function, you need to await the result.",
|
||||
after: "",
|
||||
},
|
||||
{
|
||||
field: "resetImageAspectRatio",
|
||||
code: "async resetImageAspectRatio(imgEl: ExcalidrawImageElement): Promise<boolean>",
|
||||
desc: "Resets the image to its original aspect ratio.\n" +
|
||||
"If the image is resized then the function returns true.\n" +
|
||||
"If the image element is not in EA (only in the view), then if the image is resized, the element is copied to EA for Editing using copyViewElementsToEAforEditing([imgEl]).\n" +
|
||||
"Note you need to run await ea.addElementsToView(false); to add the modified image to the view.",
|
||||
desc:
|
||||
"Resets the image to its original aspect ratio.\n" +
|
||||
"If the image is resized then the function returns true.\n" +
|
||||
"If the image element is not in EA (only in the view), then if the image is resized, the element is copied to EA for Editing using copyViewElementsToEAforEditing([imgEl]).\n" +
|
||||
"Note you need to run await ea.addElementsToView(false); to add the modified image to the view.",
|
||||
after: "",
|
||||
},
|
||||
{
|
||||
@@ -845,21 +870,23 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
|
||||
{
|
||||
field: "getCM",
|
||||
code: "getCM(color:TInput): ColorMaster;",
|
||||
desc: `Returns a ${hyperlink("https://github.com/lbragile/ColorMaster", "ColorMaster")} object. ` +
|
||||
desc:
|
||||
`Returns a ${hyperlink("https://github.com/lbragile/ColorMaster", "ColorMaster")} object. ` +
|
||||
"The function also accepts css color names. Under the hood, before calling ColorMaster it uses " +
|
||||
"colorNameToHex to convert the color name to a HEX color.",
|
||||
after: "",
|
||||
},
|
||||
{
|
||||
field: "getViewColorPalette",
|
||||
code: "getViewColorPalette(palette: \"canvasBackground\"|\"elementBackground\"|\"elementStroke\"): (string[] | string)[];",
|
||||
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\");",
|
||||
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" +
|
||||
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) {" +
|
||||
@@ -867,26 +894,28 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
|
||||
"} else {" +
|
||||
'console.log("User cancelled color selection");' +
|
||||
"}",
|
||||
after: "(buttonEl, \"elementStroke\");",
|
||||
after: '(buttonEl, "elementStroke");',
|
||||
},
|
||||
{
|
||||
field: "obsidian",
|
||||
code: "obsidian",
|
||||
desc: `Access functions and objects available on the ${hyperlink("https://github.com/obsidianmd/obsidian-api/blob/master/obsidian.d.ts","Obsidian Module")}`,
|
||||
desc: `Access functions and objects available on the ${hyperlink("https://github.com/obsidianmd/obsidian-api/blob/master/obsidian.d.ts", "Obsidian Module")}`,
|
||||
after: "",
|
||||
},
|
||||
{
|
||||
field: "getListOfTemplateFiles",
|
||||
code: "getListOfTemplateFiles(): TFile[] | null",
|
||||
desc: "Returns a list of files in the template folder. " +
|
||||
desc:
|
||||
"Returns a list of files in the template folder. " +
|
||||
"If the Excalidraw Template is set as a single file, it returns a single element in the list. " +
|
||||
"If no template is set, it returns null.",
|
||||
after: "",
|
||||
},
|
||||
{
|
||||
{
|
||||
field: "getEmbeddedImagesFiletree",
|
||||
code: "getEmbeddedImagesFiletree(excalidrawFile?: TFile): TFile[]",
|
||||
desc: "Retruns the embedded images in the scene recursively. If excalidrawFile is not provided, " +
|
||||
desc:
|
||||
"Retruns the embedded images in the scene recursively. If excalidrawFile is not provided, " +
|
||||
"the function will use ea.targetView.file",
|
||||
after: "",
|
||||
},
|
||||
@@ -899,7 +928,8 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
|
||||
{
|
||||
field: "getAttachmentFilepath",
|
||||
code: "async getAttachmentFilepath(filename: string): Promise<string>",
|
||||
desc: "This asynchronous function should be awaited. It retrieves the filepath to a new file, taking into account the attachments preference settings in Obsidian. If the attachment folder doesn't exist, it creates it. The function returns the complete path to the file. If the provided filename already exists, the function will append '_[number]' before the extension to generate a unique filename." +
|
||||
desc:
|
||||
"This asynchronous function should be awaited. It retrieves the filepath to a new file, taking into account the attachments preference settings in Obsidian. If the attachment folder doesn't exist, it creates it. The function returns the complete path to the file. If the provided filename already exists, the function will append '_[number]' before the extension to generate a unique filename." +
|
||||
"Prompts the user with a dialog to select new file action.<br>" +
|
||||
" - create markdown file<br>" +
|
||||
" - create excalidraw file<br>" +
|
||||
@@ -907,17 +937,18 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
|
||||
"The new file will be relative to this.targetView.file.path, unless parentFile is provided. " +
|
||||
"If shouldOpenNewFile is true, the new file will be opened in a workspace leaf. " +
|
||||
"targetPane controls which leaf will be used for the new file.<br>" +
|
||||
"Returns the TFile for the new file or null if the user cancelled the action.<br>" +
|
||||
"Returns the TFile for the new file or null if the user cancelled the action.<br>" +
|
||||
'<code>type PaneTarget = "active-pane"|"new-pane"|"popout-window"|"new-tab"|"md-properties";</code>',
|
||||
after: "",
|
||||
},
|
||||
{
|
||||
field: "getActiveEmbeddableViewOrEditor",
|
||||
code: "getActiveEmbeddableViewOrEditor (view?:ExcalidrawView): {view:any}|{file:TFile, editor:Editor}|{node: ObsidianCanvasNode}|null;",
|
||||
desc: "Returns the editor or leaf.view of the currently active embedded obsidian file.<br>" +
|
||||
"If view is not provided, ea.targetView is used.<br>" +
|
||||
"If the embedded file is an eligible Obsidian canvas node document the function will return<br>" +
|
||||
"<code>{file:TFile, editor:Editor}</code> of {node: ObsidianCanvasNode}, otherwise it will return {view:any}. You can check view type with view.getViewType();",
|
||||
desc:
|
||||
"Returns the editor or leaf.view of the currently active embedded obsidian file.<br>" +
|
||||
"If view is not provided, ea.targetView is used.<br>" +
|
||||
"If the embedded file is an eligible Obsidian canvas node document the function will return<br>" +
|
||||
"<code>{file:TFile, editor:Editor}</code> of {node: ObsidianCanvasNode}, otherwise it will return {view:any}. You can check view type with view.getViewType();",
|
||||
after: "",
|
||||
},
|
||||
{
|
||||
@@ -935,17 +966,19 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
|
||||
{
|
||||
field: "checkForActiveSidepanelTabForScript",
|
||||
code: "checkForActiveSidepanelTabForScript(scriptName?: string): ExcalidrawSidepanelTab | null;",
|
||||
desc: "Returns the active sidepanel tab for the given script, or null if none exists. " +
|
||||
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");'
|
||||
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"+
|
||||
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: "",
|
||||
},
|
||||
@@ -953,22 +986,23 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
|
||||
field: "getSidepanelLeaf",
|
||||
code: "getSidepanelLeaf(): WorkspaceLeaf | null;",
|
||||
desc: "Returns the WorkspaceLeaf hosting the Excalidraw sidepanel view, or null if the sidepanel is not present.",
|
||||
after: "();"
|
||||
after: "();",
|
||||
},
|
||||
{
|
||||
field: "skipSidepanelScriptRestore",
|
||||
code: "skipSidepanelScriptRestore(scriptName?: string): boolean;",
|
||||
desc: "Queues a one-time skip marker so sidepanel persisted restoration will not re-run the script. " +
|
||||
desc:
|
||||
"Queues a one-time skip marker so sidepanel persisted restoration will not re-run the script. " +
|
||||
"Intended for startup race conditions where a script is started from Command Palette/hotkey before the sidepanel has opened. " +
|
||||
"If scriptName is omitted the function uses ea.activeScript. " +
|
||||
"The marker is queued only when getSidepanelLeaf() is null; returns true when queued, otherwise false.",
|
||||
after: "();"
|
||||
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: "();"
|
||||
after: "();",
|
||||
},
|
||||
{
|
||||
field: "persistSidepanelTab",
|
||||
@@ -982,11 +1016,18 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
|
||||
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: "parseText",
|
||||
code: "async parseText(text: string): Promise<string | undefined>;",
|
||||
desc: "Parses raw text through targetView.excalidrawData using the same parsing pipeline as ExcalidrawData (including transclusion resolution, link brackets, and link/url prefixes from frontmatter). Works only when ea.targetView is set and loaded.",
|
||||
after: "",
|
||||
},
|
||||
{
|
||||
field: "getleaf",
|
||||
code: "getLeaf(origo: WorkspaceLeaf, targetPane?: PaneTarget): WorkspaceLeaf;",
|
||||
desc: "Generates a new Obsidian Leaf following Excalidraw plugin settings such as open in Main Workspace or not, open in adjacent pane if available, etc.<br>" +
|
||||
"@param origo: the currently active leaf, the origin of the new leaf<br>" +
|
||||
desc:
|
||||
"Generates a new Obsidian Leaf following Excalidraw plugin settings such as open in Main Workspace or not, open in adjacent pane if available, etc.<br>" +
|
||||
"@param origo: the currently active leaf, the origin of the new leaf<br>" +
|
||||
'@param targetPane: <code>type PaneTarget = "active-pane"|"new-pane"|"popout-window"|"new-tab"|"md-properties";',
|
||||
after: "",
|
||||
},
|
||||
@@ -999,7 +1040,8 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
|
||||
{
|
||||
field: "DEVICE",
|
||||
code: "get DEVICE(): DeviceType;",
|
||||
desc: "Returns the current device type. Possible values are: <br>" +
|
||||
desc:
|
||||
"Returns the current device type. Possible values are: <br>" +
|
||||
"<code>type DeviceType = {<br>" +
|
||||
" isDesktop: boolean,<br>" +
|
||||
" isPhone: boolean,<br>" +
|
||||
@@ -1025,6 +1067,103 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
|
||||
desc: "Checks if the filepath already exists, if so, returns a new filepath with a number appended to the filename else returns the filepath as provided.",
|
||||
after: "",
|
||||
},
|
||||
{
|
||||
field: "postAI",
|
||||
code: "async postAI(request: AIRequest): Promise<RequestUrlResponse>",
|
||||
desc:
|
||||
"This asynchronous function should be awaited. It posts the supplied request to the currently configured AI provider and returns a normalized OpenAI-compatible response payload for backwards compatibility.<br>" +
|
||||
"<b>AIRequest</b> supports these fields:<br>" +
|
||||
"<code>{ provider?, baseURL?, apiKey?, model?, image?, text?, instruction?, systemPrompt?, messages?, temperature?, maxOutgoingTokens?, maxTokens?, imageGenerationProperties? }</code><br>" +
|
||||
"<b>provider</b>: optional override for the configured provider. Supported values are openai, anthropic, google, xai, and openai-compatible.<br>" +
|
||||
"<b>baseURL</b>: optional request-level provider base URL override. Use this for local models, custom gateways, or temporary endpoint switching.<br>" +
|
||||
"<b>apiKey</b>: optional request-level API key override.<br>" +
|
||||
"<b>model</b>: optional request-level model override. This applies to text, vision, and image-generation requests.<br>" +
|
||||
"<b>image</b>: either a data URL string or <code>{url:string}|{dataURL:string}</code>. Use this with vision requests or image edits.<br>" +
|
||||
"<b>text</b>: the main user prompt.<br>" +
|
||||
"<b>instruction</b>: optional extra user instruction appended after the main prompt.<br>" +
|
||||
"<b>systemPrompt</b>: optional system message.<br>" +
|
||||
"<b>messages</b>: optional chat history in the form <code>{role:" +
|
||||
'"system"|"user"|"assistant"' +
|
||||
", content:string | [{type:" +
|
||||
'"text"' +
|
||||
", text:string} | {type:" +
|
||||
'"image"' +
|
||||
", image:string | {url:string}|{dataURL:string}} | {type:" +
|
||||
'"file"' +
|
||||
", file:string | {url:string}|{dataURL:string}} | {type:" +
|
||||
'"audio"' +
|
||||
", audio:string | {url:string}|{dataURL:string}}]}</code>.<br>" +
|
||||
"This enables chat-style interfaces by preserving prior turns in <code>messages</code>, similar to Mermaid chat.<br>" +
|
||||
"<b>temperature</b>: optional generation control.<br>" +
|
||||
"<b>maxOutgoingTokens</b>: optional approximate budget for outgoing text content. Excalidraw trims older text content first while keeping the latest messages and attached files.<br>" +
|
||||
"<b>maxTokens</b>: optional response-size limit.<br>" +
|
||||
"<b>imageGenerationProperties</b>: <code>{ size?, quality?, n?, mask? }</code>. If present, Excalidraw uses the image generation/edit pipeline. <code>mask</code> accepts the same format as <code>image</code>.<br>" +
|
||||
"<b>File support by provider</b>: Google accepts inline file/audio parts such as PDFs and voice clips. Anthropic currently accepts PDF document parts. OpenAI/OpenAI-compatible/xAI remain limited to text plus images in the current chat-completions pipeline.<br>" +
|
||||
"<b>RequestUrlResponse</b> returns:<br>" +
|
||||
"<code>{ status:number, headers:Record<string,string>, text:string, json:any, arrayBuffer:ArrayBuffer }</code><br>" +
|
||||
"For text models, <code>json</code> is normalized to an OpenAI-style chat completion object, so existing scripts can continue reading <code>json.choices[0].message.content</code>. For image models, <code>json</code> preserves the image endpoint response such as <code>json.data[0].url</code>.",
|
||||
after: "",
|
||||
},
|
||||
{
|
||||
field: "getAISettings",
|
||||
code: "getAISettings(): ExcalidrawAISettings | null",
|
||||
desc:
|
||||
"Returns the sanitized AI configuration currently available to ExcalidrawAutomate scripts.<br>" +
|
||||
"The returned object includes enabled state, provider profiles with <code>provider</code>, <code>baseURL</code>, and <code>hasApiKey</code>, the configured text/image model maps, the default text/image model IDs, and the default outgoing/response token budgets.<br>" +
|
||||
"Use this instead of reading <code>ea.plugin.settings</code> directly when building AI-driven scripts.",
|
||||
after: "",
|
||||
},
|
||||
{
|
||||
field: "generateAIText",
|
||||
code: "async generateAIText(request: AIRequest)",
|
||||
desc:
|
||||
"High-level wrapper around <code>postAI()</code> for text and multimodal chat requests.<br>" +
|
||||
"Returns an object with <code>response</code>, <code>json</code>, <code>content</code>, <code>rateLimit</code>, and <code>rateLimitRemaining</code>.<br>" +
|
||||
"Use this when you want the assistant text directly instead of manually reading <code>json.choices[0].message.content</code>.",
|
||||
after: "",
|
||||
},
|
||||
{
|
||||
field: "analyzeAIImage",
|
||||
code: "async analyzeAIImage(request: AIRequest)",
|
||||
desc:
|
||||
"High-level wrapper for multimodal image-analysis requests.<br>" +
|
||||
"Supply an image in <code>request.image</code> or in message parts and optionally add <code>text</code>, <code>instruction</code>, or <code>messages</code>.<br>" +
|
||||
"The configured text model must have multimodal support enabled.",
|
||||
after: "",
|
||||
},
|
||||
{
|
||||
field: "generateAIImage",
|
||||
code: "async generateAIImage(request: AIRequest)",
|
||||
desc:
|
||||
"Generates a new image using the configured image model.<br>" +
|
||||
"Returns <code>{ response, json, images, firstImage, revisedPrompt }</code> where <code>images</code> contains normalized image results with <code>url</code>, <code>b64_json</code>, <code>dataURL</code>, <code>mimeType</code>, and optional <code>revisedPrompt</code>.",
|
||||
after: "",
|
||||
},
|
||||
{
|
||||
field: "transformAIImage",
|
||||
code: "async transformAIImage(request: AIRequest)",
|
||||
desc:
|
||||
"Applies a prompt-based transform to an input image using the configured image model.<br>" +
|
||||
"Requires <code>request.image</code>. This is intended for providers/models that support image plus prompt edits without a mask.",
|
||||
after: "",
|
||||
},
|
||||
{
|
||||
field: "maskEditAIImage",
|
||||
code: "async maskEditAIImage(request: AIRequest)",
|
||||
desc:
|
||||
"Applies a mask-based edit to an input image using the configured image model.<br>" +
|
||||
"Requires both <code>request.image</code> and <code>request.imageGenerationProperties.mask</code>.",
|
||||
after: "",
|
||||
},
|
||||
{
|
||||
field: "createAIChatSession",
|
||||
code: 'createAIChatSession(initialRequest?: Omit<AIRequest, "messages">)',
|
||||
desc:
|
||||
"Creates a lightweight AI chat session helper that preserves prior conversation turns between calls.<br>" +
|
||||
"The returned object exposes <code>getMessages()</code>, <code>reset()</code>, and <code>send(message, requestOverrides?)</code>.<br>" +
|
||||
"Use this when a script needs Mermaid-style iterative prompting without manually maintaining the message array.",
|
||||
after: "",
|
||||
},
|
||||
{
|
||||
field: "extractCodeBlocks",
|
||||
code: "extractCodeBlocks(markdown: string): { data: string, type: string }[]",
|
||||
@@ -1034,16 +1173,7 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
|
||||
{
|
||||
field: "postOpenAI",
|
||||
code: "async postOpenAI(request: AIRequest): Promise<RequestUrlResponse>",
|
||||
desc:
|
||||
"This asynchronous function should be awaited. It posts the supplied request to the OpenAI API and returns the response.<br>" +
|
||||
"The response is a dictionary with the following keys:<br><code>{image, text, instruction, systemPrompt, responseType}</code><br>"+
|
||||
"<b>image</b> should be a dataURL - use ea.createPNGBase64()<br>"+
|
||||
"<b>systemPrompt</b>: if <code>undefined</code> the message to OpenAI will not include a system prompt<br>"+
|
||||
"<b>text</b> is the actual user prompt, a request must have either an image or a text<br>"+
|
||||
"<b>instruction</b> is a user prompt sent as a separate element in the message - I use it to reinforce the type of response I am seeing (e.g. mermaid in a codeblock)<br>"+
|
||||
`<b>imageGenerationProperties</b> if provided then the dall-e model will be used. <code> imageGenerationProperties?: {size?: string, quality?: "standard" | "hd"; n?: number; mask?: string; }</code><br>` +
|
||||
"Different openAI models accept different parameters fr size, quality, n and mask. Consult the API documenation for more information.<br>" +
|
||||
`RequestUrlResponse is defined in the ${hyperlink("https://github.com/obsidianmd/obsidian-api/blob/master/obsidian.d.ts","Obsidian API")}`,
|
||||
desc: "Backwards-compatible alias for <code>postAI()</code>. Existing scripts can keep calling this function without changes. The request object and response object are the same as documented for <code>postAI()</code>, but the function name is preserved for compatibility with older ExcalidrawAutomate scripts.",
|
||||
after: "",
|
||||
},
|
||||
{
|
||||
@@ -1067,7 +1197,8 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
|
||||
{
|
||||
field: "viewUpdateScene",
|
||||
code: "viewUpdateScene(scene:{elements?:ExcalidrawElement[],appState?: AppState,files?: BinaryFileData,captureUpdate?: 'IMMEDIATELY' | 'NEVER' | 'EVENTUALLY'},restore:boolean=false):void",
|
||||
desc: "Calls the ExcalidrawAPI updateScene function for the targetView. When restore=true, excalidraw will try to correct errors in the scene such as setting default values to missing element properties. " +
|
||||
desc:
|
||||
"Calls the ExcalidrawAPI updateScene function for the targetView. When restore=true, excalidraw will try to correct errors in the scene such as setting default values to missing element properties. " +
|
||||
`Use captureUpdate to control undo/redo behavior: 'IMMEDIATELY' for immediate undoable updates (most local changes), 'NEVER' for updates that should never be undoable, or 'EVENTUALLY' for updates that should be undoable as part of an async multi-step process. See the ExcalidrawAPI documentation for more information.`,
|
||||
after: "",
|
||||
},
|
||||
@@ -1100,9 +1231,9 @@ export const EXCALIDRAW_SCRIPTENGINE_INFO: SuggesterInfo[] = [
|
||||
"Editor buttons are text editing buttons like delete, enter, allcaps - these are only displayed if lines is greater than 1 \n" +
|
||||
"Custom components are components that you can add to the prompt. These will be displayed between the text input area and the buttons.\n" +
|
||||
"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"+
|
||||
"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" +
|
||||
'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});`,
|
||||
},
|
||||
@@ -1154,7 +1285,8 @@ export const FRONTMATTER_KEYS_INFO: SuggesterInfo[] = [
|
||||
{
|
||||
field: "linkbutton-opacity",
|
||||
code: null,
|
||||
desc: "The opacity of the blue link button in the top right of the element overriding the respective setting in plugin settings. "+
|
||||
desc:
|
||||
"The opacity of the blue link button in the top right of the element overriding the respective setting in plugin settings. " +
|
||||
"Valid values are between 0 and 1, where 0 means the button is transparent.",
|
||||
after: ": 0.5",
|
||||
},
|
||||
@@ -1162,7 +1294,8 @@ export const FRONTMATTER_KEYS_INFO: SuggesterInfo[] = [
|
||||
field: "onload-script",
|
||||
code: null,
|
||||
desc: "The value of this field will be executed as javascript code using the Script Engine environment. Use this to initiate custom actions or logic when loading your drawing.",
|
||||
after: ': "new Notice(`Hello World!\\n\\nFile: ${ea.targetView.file.basename}`);"',
|
||||
after:
|
||||
': "new Notice(`Hello World!\\n\\nFile: ${ea.targetView.file.basename}`);"',
|
||||
},
|
||||
{
|
||||
field: "font",
|
||||
@@ -1233,7 +1366,8 @@ export const FRONTMATTER_KEYS_INFO: SuggesterInfo[] = [
|
||||
{
|
||||
field: "embed-md",
|
||||
code: null,
|
||||
desc: "If this key is present, when embedding the ![[image]] into a markdown document, it will be embedded as markdown, not as an image.\n" +
|
||||
desc:
|
||||
"If this key is present, when embedding the ![[image]] into a markdown document, it will be embedded as markdown, not as an image.\n" +
|
||||
"If however you embed ![[image#^as-image]], i.e. you reference the 'as-image' block, then the image will be embedded as an image.",
|
||||
after: ": true",
|
||||
},
|
||||
|
||||
@@ -8,20 +8,19 @@ export type UIMode = "full" | "compact" | "tray" | "mobile";
|
||||
|
||||
//setDesktopUIMode(this.app, this.plugin.settings);
|
||||
|
||||
|
||||
export class UIModeSettingsComponent {
|
||||
private containerEl: HTMLElement;
|
||||
private settings: ExcalidrawSettings;
|
||||
private app: App;
|
||||
private onChange: () => void;
|
||||
private reapplyButtonAction: ()=>void = null;
|
||||
private reapplyButtonAction: () => void = null;
|
||||
|
||||
constructor(
|
||||
containerEl: HTMLElement,
|
||||
settings: ExcalidrawSettings,
|
||||
app: App,
|
||||
onChange: () => void,
|
||||
reapplyButtonAction: ()=>void = null,
|
||||
reapplyButtonAction: () => void = null,
|
||||
) {
|
||||
this.containerEl = containerEl;
|
||||
this.settings = settings;
|
||||
@@ -92,30 +91,23 @@ export class UIModeSettingsComponent {
|
||||
.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();
|
||||
}),
|
||||
toggle.setValue(this.settings.isLeftHanded).onChange(async (value) => {
|
||||
this.settings.isLeftHanded = value;
|
||||
setLeftHandedMode(value);
|
||||
this.onChange();
|
||||
}),
|
||||
);
|
||||
|
||||
if (this.reapplyButtonAction) {
|
||||
new Setting(containerEl)
|
||||
.addButton((button) =>
|
||||
button
|
||||
.setButtonText(t("REAPPLY_UI_MODE_BUTTON"))
|
||||
.setCta()
|
||||
.onClick(() => {
|
||||
setUIMode(this.app, this.settings);
|
||||
this.reapplyButtonAction();
|
||||
}),
|
||||
);
|
||||
new Setting(containerEl).addButton((button) =>
|
||||
button
|
||||
.setButtonText(t("REAPPLY_UI_MODE_BUTTON"))
|
||||
.setCta()
|
||||
.onClick(() => {
|
||||
setUIMode(this.app, this.settings);
|
||||
this.reapplyButtonAction();
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -5,15 +5,13 @@ import { Modal } from "obsidian";
|
||||
|
||||
export class UIModeSettings extends Modal {
|
||||
private isDirty = false;
|
||||
constructor(
|
||||
private plugin: ExcalidrawPlugin,
|
||||
) {
|
||||
constructor(private plugin: ExcalidrawPlugin) {
|
||||
super(plugin.app);
|
||||
}
|
||||
|
||||
onOpen(): void {
|
||||
this.containerEl.classList.add("excalidraw-release");
|
||||
this.createForm();
|
||||
void this.createForm();
|
||||
}
|
||||
|
||||
async onClose() {
|
||||
@@ -24,18 +22,17 @@ export class UIModeSettings extends Modal {
|
||||
}
|
||||
|
||||
async createForm() {
|
||||
this.contentEl.createEl("h1",{text: t("MODES_HEAD")});
|
||||
this.contentEl.createEl("h1", { text: t("MODES_HEAD") });
|
||||
new UIModeSettingsComponent(
|
||||
this.contentEl,
|
||||
this.plugin.settings,
|
||||
this.app,
|
||||
()=>this.applySettingsUpdate(),
|
||||
()=>this.close(),
|
||||
() => this.applySettingsUpdate(),
|
||||
() => this.close(),
|
||||
).render();
|
||||
}
|
||||
|
||||
private async applySettingsUpdate() {
|
||||
this.isDirty = true;
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,19 +1,28 @@
|
||||
import { ButtonComponent, DropdownComponent, TFile } from "obsidian";
|
||||
import ExcalidrawView from "../../view/ExcalidrawView";
|
||||
import ExcalidrawPlugin from "../../core/main";
|
||||
import { Modal, Setting, TextComponent } from "obsidian";
|
||||
import { Modal, Setting, TextComponent } from "obsidian";
|
||||
import { FileSuggestionModal } from "../Suggesters/FileSuggestionModal";
|
||||
import { IMAGE_TYPES, sceneCoordsToViewportCoords, viewportCoordsToSceneCoords, MAX_IMAGE_SIZE, ANIMATED_IMAGE_TYPES, MD_EX_SECTIONS } from "src/constants/constants";
|
||||
import { insertEmbeddableToView, insertImageToView } from "src/utils/excalidrawViewUtils";
|
||||
import {
|
||||
IMAGE_TYPES,
|
||||
sceneCoordsToViewportCoords,
|
||||
viewportCoordsToSceneCoords,
|
||||
MAX_IMAGE_SIZE,
|
||||
ANIMATED_IMAGE_TYPES,
|
||||
MD_EX_SECTIONS,
|
||||
} from "src/constants/constants";
|
||||
import {
|
||||
insertEmbeddableToView,
|
||||
insertImageToView,
|
||||
} from "src/utils/excalidrawViewUtils";
|
||||
import { getEA } from "src/core";
|
||||
import { InsertPDFModal } from "./InsertPDFModal";
|
||||
import { ExcalidrawImperativeAPI } from "@zsviczian/excalidraw/types/excalidraw/types";
|
||||
import { ExcalidrawAutomate } from "src/shared/ExcalidrawAutomate";
|
||||
import { cleanSectionHeading } from "src/utils/obsidianUtils";
|
||||
import { cleanSectionHeading } from "src/utils/pathUtils";
|
||||
import { t } from "src/lang/helpers";
|
||||
|
||||
export class UniversalInsertFileModal extends Modal {
|
||||
private center: { x: number, y: number } = { x: 0, y: 0 };
|
||||
private center: { x: number; y: number } = { x: 0, y: 0 };
|
||||
private file: TFile;
|
||||
|
||||
constructor(
|
||||
@@ -21,15 +30,20 @@ export class UniversalInsertFileModal extends Modal {
|
||||
private view: ExcalidrawView,
|
||||
) {
|
||||
super(plugin.app);
|
||||
const appState = (view.excalidrawAPI as ExcalidrawImperativeAPI).getAppState();
|
||||
const appState = view.excalidrawAPI.getAppState();
|
||||
const containerRect = view.containerEl.getBoundingClientRect();
|
||||
const viewportWidth = window.innerWidth || document.documentElement.clientWidth;
|
||||
const viewportHeight = window.innerHeight || document.documentElement.clientHeight;
|
||||
const viewportWidth =
|
||||
window.innerWidth || document.documentElement.clientWidth;
|
||||
const viewportHeight =
|
||||
window.innerHeight || document.documentElement.clientHeight;
|
||||
|
||||
const curViewport = sceneCoordsToViewportCoords({
|
||||
sceneX: view.currentPosition.x,
|
||||
sceneY: view.currentPosition.y,},
|
||||
appState);
|
||||
const curViewport = sceneCoordsToViewportCoords(
|
||||
{
|
||||
sceneX: view.currentPosition.x,
|
||||
sceneY: view.currentPosition.y,
|
||||
},
|
||||
appState,
|
||||
);
|
||||
|
||||
if (
|
||||
curViewport.x >= containerRect.left + 150 &&
|
||||
@@ -39,75 +53,91 @@ export class UniversalInsertFileModal extends Modal {
|
||||
) {
|
||||
const sceneX = view.currentPosition.x - MAX_IMAGE_SIZE / 2;
|
||||
const sceneY = view.currentPosition.y - MAX_IMAGE_SIZE / 2;
|
||||
this.center = {x: sceneX, y: sceneY};
|
||||
this.center = { x: sceneX, y: sceneY };
|
||||
} else {
|
||||
const centerX = containerRect.left + containerRect.width / 2;
|
||||
const centerY = containerRect.top + containerRect.height / 2;
|
||||
|
||||
|
||||
const clientX = Math.max(0, Math.min(viewportWidth, centerX));
|
||||
const clientY = Math.max(0, Math.min(viewportHeight, centerY));
|
||||
|
||||
this.center = viewportCoordsToSceneCoords ({clientX, clientY}, appState);
|
||||
this.center = {x: this.center.x - MAX_IMAGE_SIZE / 2, y: this.center.y - MAX_IMAGE_SIZE / 2};
|
||||
|
||||
this.center = viewportCoordsToSceneCoords({ clientX, clientY }, appState);
|
||||
this.center = {
|
||||
x: this.center.x - MAX_IMAGE_SIZE / 2,
|
||||
y: this.center.y - MAX_IMAGE_SIZE / 2,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
private onKeyDown: (evt: KeyboardEvent) => void;
|
||||
|
||||
open(file?: TFile, center?: { x: number, y: number }) {
|
||||
open(file?: TFile, center?: { x: number; y: number }) {
|
||||
this.file = file;
|
||||
this.center = center ?? this.center;
|
||||
super.open();
|
||||
}
|
||||
|
||||
onOpen(): void {
|
||||
const modalEl = this.modalEl;
|
||||
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();
|
||||
void this.createForm();
|
||||
}
|
||||
|
||||
async createForm() {
|
||||
const ce = this.contentEl;
|
||||
let sectionPicker: DropdownComponent;
|
||||
let sectionPickerSetting: Setting;
|
||||
let actionIFrame: ButtonComponent;
|
||||
let actionImage: ButtonComponent;
|
||||
let actionPDF: ButtonComponent;
|
||||
let sizeToggleSetting: Setting
|
||||
let anchorTo100: boolean = false;
|
||||
let file = this.file;
|
||||
|
||||
const updateForm = async () => {
|
||||
const ea = this.plugin.ea;
|
||||
const isSelf = file === this.view.file;
|
||||
const isMarkdown = file && file.extension === "md" && !ea.isExcalidrawFile(file);
|
||||
const isImage = file && (IMAGE_TYPES.contains(file.extension) || ea.isExcalidrawFile(file));
|
||||
const isAnimatedImage = file && ANIMATED_IMAGE_TYPES.contains(file.extension);
|
||||
const isMarkdown =
|
||||
file && file.extension === "md" && !ea.isExcalidrawFile(file);
|
||||
const isImage =
|
||||
file &&
|
||||
(IMAGE_TYPES.contains(file.extension) || ea.isExcalidrawFile(file));
|
||||
const isAnimatedImage =
|
||||
file && ANIMATED_IMAGE_TYPES.contains(file.extension);
|
||||
const isIFrame = file && !isImage;
|
||||
const isPDF = file && file.extension === "pdf";
|
||||
const isExcalidraw = file && ea.isExcalidrawFile(file);
|
||||
|
||||
const sections = (file && file.extension === "md")
|
||||
? (await this.plugin.app.metadataCache.blockCache
|
||||
.getForFile({ isCancelled: () => false },file))
|
||||
.blocks.filter((b: any) => b.display && b.node?.type === "heading")
|
||||
.filter((b: any) => !isExcalidraw || !MD_EX_SECTIONS.includes(b.display))
|
||||
: null;
|
||||
const sections =
|
||||
file && file.extension === "md"
|
||||
? (
|
||||
await this.plugin.app.metadataCache.blockCache.getForFile(
|
||||
{ isCancelled: () => false },
|
||||
file,
|
||||
)
|
||||
).blocks
|
||||
.filter((b: any) => b.display && b.node?.type === "heading")
|
||||
.filter(
|
||||
(b: any) =>
|
||||
!isExcalidraw || !MD_EX_SECTIONS.includes(b.display),
|
||||
)
|
||||
: null;
|
||||
|
||||
if (isMarkdown || (isExcalidraw && sections?.length > 0)) {
|
||||
sectionPickerSetting.settingEl.style.display = "";
|
||||
sectionPicker.selectEl.style.display = "block";
|
||||
while(sectionPicker.selectEl.options.length > 0) {
|
||||
while (sectionPicker.selectEl.options.length > 0) {
|
||||
sectionPicker.selectEl.remove(0);
|
||||
}
|
||||
if(!isExcalidraw) sectionPicker.addOption("","");
|
||||
if (!isExcalidraw) {
|
||||
sectionPicker.addOption("", "");
|
||||
}
|
||||
sections.forEach((b: any) => {
|
||||
sectionPicker.addOption(
|
||||
`#${cleanSectionHeading(b.display)}`,
|
||||
b.display)
|
||||
b.display,
|
||||
);
|
||||
});
|
||||
} else {
|
||||
sectionPickerSetting.settingEl.style.display = "none";
|
||||
@@ -120,13 +150,17 @@ export class UniversalInsertFileModal extends Modal {
|
||||
sizeToggleSetting.settingEl.style.display = "none";
|
||||
}
|
||||
|
||||
if (!isSelf && (isImage || (file?.extension === "md"))) {
|
||||
if (!isSelf && (isImage || file?.extension === "md")) {
|
||||
actionImage.buttonEl.style.display = "block";
|
||||
} else {
|
||||
actionImage.buttonEl.style.display = "none";
|
||||
}
|
||||
|
||||
if (isIFrame || isAnimatedImage || (isExcalidraw && sections?.length > 0)) {
|
||||
if (
|
||||
isIFrame ||
|
||||
isAnimatedImage ||
|
||||
(isExcalidraw && sections?.length > 0)
|
||||
) {
|
||||
actionIFrame.buttonEl.style.display = "block";
|
||||
} else {
|
||||
actionIFrame.buttonEl.style.display = "none";
|
||||
@@ -137,12 +171,15 @@ export class UniversalInsertFileModal extends Modal {
|
||||
} else {
|
||||
actionPDF.buttonEl.style.display = "none";
|
||||
}
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
const sections = (await this.plugin.app.metadataCache.blockCache
|
||||
.getForFile({ isCancelled: () => false },this.view.file))
|
||||
.blocks.filter((b: any) => b.display && b.node?.type === "heading")
|
||||
const sections = (
|
||||
await this.plugin.app.metadataCache.blockCache.getForFile(
|
||||
{ isCancelled: () => false },
|
||||
this.view.file,
|
||||
)
|
||||
).blocks
|
||||
.filter((b: any) => b.display && b.node?.type === "heading")
|
||||
.filter((b: any) => !MD_EX_SECTIONS.includes(b.display));
|
||||
|
||||
const search = new TextComponent(ce);
|
||||
@@ -150,131 +187,146 @@ export class UniversalInsertFileModal extends Modal {
|
||||
const suggester = new FileSuggestionModal(
|
||||
this.app,
|
||||
search,
|
||||
this.app.vault.getFiles().filter((f: TFile) => sections?.length > 0 || f!==this.view.file),
|
||||
this.plugin
|
||||
this.app.vault
|
||||
.getFiles()
|
||||
.filter((f: TFile) => sections?.length > 0 || f !== this.view.file),
|
||||
this.plugin,
|
||||
);
|
||||
search.onChange(() => {
|
||||
file = suggester.getSelectedItem();
|
||||
updateForm();
|
||||
void updateForm();
|
||||
});
|
||||
|
||||
sectionPickerSetting = new Setting(ce)
|
||||
const sectionPickerSetting = new Setting(ce)
|
||||
.setName(t("UIFM_SECTION_HEAD"))
|
||||
.addDropdown(dropdown => {
|
||||
.addDropdown((dropdown) => {
|
||||
sectionPicker = dropdown;
|
||||
sectionPicker.selectEl.style.width = "100%";
|
||||
})
|
||||
});
|
||||
|
||||
sizeToggleSetting = new Setting(ce)
|
||||
const sizeToggleSetting = new Setting(ce)
|
||||
.setName(t("UIFM_ANCHOR"))
|
||||
.setDesc(t("UIFM_ANCHOR_DESC"))
|
||||
.addToggle(toggle => {
|
||||
toggle.setValue(anchorTo100)
|
||||
.onChange((value) => {
|
||||
.addToggle((toggle) => {
|
||||
toggle.setValue(anchorTo100).onChange((value) => {
|
||||
anchorTo100 = value;
|
||||
})
|
||||
})
|
||||
|
||||
});
|
||||
});
|
||||
|
||||
new Setting(ce)
|
||||
.addButton(button => {
|
||||
button
|
||||
.setButtonText(t("UIFM_BTN_EMBEDDABLE"))
|
||||
.onClick(async () => {
|
||||
const path = this.app.metadataCache.fileToLinktext(
|
||||
file,
|
||||
this.view.file.path,
|
||||
file.extension === "md",
|
||||
)
|
||||
const ea:ExcalidrawAutomate = getEA(this.view);
|
||||
ea.selectElementsInView(
|
||||
[await insertEmbeddableToView (
|
||||
ea,
|
||||
this.center,
|
||||
//this.view.currentPosition,
|
||||
undefined,
|
||||
`[[${path}${sectionPicker.selectEl.value}]]`,
|
||||
)]
|
||||
);
|
||||
ea.destroy();
|
||||
this.close();
|
||||
})
|
||||
.addButton((button) => {
|
||||
button.setButtonText(t("UIFM_BTN_EMBEDDABLE")).onClick(async () => {
|
||||
const path = this.app.metadataCache.fileToLinktext(
|
||||
file,
|
||||
this.view.file.path,
|
||||
file.extension === "md",
|
||||
);
|
||||
const ea: ExcalidrawAutomate = getEA(this.view);
|
||||
ea.selectElementsInView([
|
||||
await insertEmbeddableToView(
|
||||
ea,
|
||||
this.center,
|
||||
//this.view.currentPosition,
|
||||
undefined,
|
||||
`[[${path}${sectionPicker.selectEl.value}]]`,
|
||||
),
|
||||
]);
|
||||
ea.destroy();
|
||||
this.close();
|
||||
});
|
||||
actionIFrame = button;
|
||||
})
|
||||
.addButton(button => {
|
||||
button
|
||||
.setButtonText(t("UIFM_BTN_PDF"))
|
||||
.onClick(() => {
|
||||
const insertPDFModal = new InsertPDFModal(this.plugin, this.view);
|
||||
insertPDFModal.open(file);
|
||||
this.close();
|
||||
})
|
||||
.addButton((button) => {
|
||||
button.setButtonText(t("UIFM_BTN_PDF")).onClick(() => {
|
||||
const insertPDFModal = new InsertPDFModal(this.plugin, this.view);
|
||||
insertPDFModal.open(file);
|
||||
this.close();
|
||||
});
|
||||
actionPDF = button;
|
||||
})
|
||||
.addButton(button => {
|
||||
button
|
||||
.setButtonText(t("UIFM_BTN_IMAGE"))
|
||||
.onClick(async () => {
|
||||
const ea:ExcalidrawAutomate = getEA(this.view);
|
||||
const isMarkdown = file && file.extension === "md" && !ea.isExcalidrawFile(file);
|
||||
ea.selectElementsInView(
|
||||
[await insertImageToView (
|
||||
ea,
|
||||
this.center,
|
||||
//this.view.currentPosition,
|
||||
isMarkdown && sectionPicker.selectEl.value && sectionPicker.selectEl.value !== ""
|
||||
.addButton((button) => {
|
||||
button.setButtonText(t("UIFM_BTN_IMAGE")).onClick(async () => {
|
||||
const ea: ExcalidrawAutomate = getEA(this.view);
|
||||
const isMarkdown =
|
||||
file && file.extension === "md" && !ea.isExcalidrawFile(file);
|
||||
ea.selectElementsInView([
|
||||
await insertImageToView(
|
||||
ea,
|
||||
this.center,
|
||||
//this.view.currentPosition,
|
||||
isMarkdown &&
|
||||
sectionPicker.selectEl.value &&
|
||||
sectionPicker.selectEl.value !== ""
|
||||
? `${file.path}${sectionPicker.selectEl.value}`
|
||||
: file,
|
||||
ea.isExcalidrawFile(file) ? !anchorTo100 : undefined,
|
||||
)]
|
||||
);
|
||||
ea.destroy();
|
||||
this.close();
|
||||
})
|
||||
ea.isExcalidrawFile(file) ? !anchorTo100 : undefined,
|
||||
),
|
||||
]);
|
||||
ea.destroy();
|
||||
this.close();
|
||||
});
|
||||
actionImage = button;
|
||||
})
|
||||
|
||||
this.view.ownerWindow.addEventListener("keydown", this.onKeyDown = (evt: KeyboardEvent) => {
|
||||
const isVisible = (b: ButtonComponent) => b.buttonEl.style.display !== "none";
|
||||
switch (evt.key) {
|
||||
case "Escape": this.close(); return;
|
||||
case "Enter":
|
||||
if (isVisible(actionIFrame) && !isVisible(actionImage) && !isVisible(actionPDF)) {
|
||||
actionIFrame.buttonEl.click();
|
||||
});
|
||||
|
||||
this.view.ownerWindow.addEventListener(
|
||||
"keydown",
|
||||
(this.onKeyDown = (evt: KeyboardEvent) => {
|
||||
const isVisible = (b: ButtonComponent) =>
|
||||
b.buttonEl.style.display !== "none";
|
||||
switch (evt.key) {
|
||||
case "Escape":
|
||||
this.close();
|
||||
return;
|
||||
}
|
||||
if (isVisible(actionImage) && !isVisible(actionIFrame) && !isVisible(actionPDF)) {
|
||||
actionImage.buttonEl.click();
|
||||
case "Enter":
|
||||
if (
|
||||
isVisible(actionIFrame) &&
|
||||
!isVisible(actionImage) &&
|
||||
!isVisible(actionPDF)
|
||||
) {
|
||||
actionIFrame.buttonEl.click();
|
||||
return;
|
||||
}
|
||||
if (
|
||||
isVisible(actionImage) &&
|
||||
!isVisible(actionIFrame) &&
|
||||
!isVisible(actionPDF)
|
||||
) {
|
||||
actionImage.buttonEl.click();
|
||||
return;
|
||||
}
|
||||
if (
|
||||
isVisible(actionPDF) &&
|
||||
!isVisible(actionIFrame) &&
|
||||
!isVisible(actionImage)
|
||||
) {
|
||||
actionPDF.buttonEl.click();
|
||||
return;
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (isVisible(actionPDF) && !isVisible(actionIFrame) && !isVisible(actionImage)) {
|
||||
actionPDF.buttonEl.click();
|
||||
case "i":
|
||||
if (isVisible(actionImage)) {
|
||||
actionImage.buttonEl.click();
|
||||
}
|
||||
return;
|
||||
}
|
||||
return;
|
||||
case "i":
|
||||
if (isVisible(actionImage)) {
|
||||
actionImage.buttonEl.click();
|
||||
}
|
||||
return;
|
||||
case "p":
|
||||
if (isVisible(actionPDF)) {
|
||||
actionPDF.buttonEl.click();
|
||||
}
|
||||
return
|
||||
case "f":
|
||||
if (isVisible(actionIFrame)) {
|
||||
actionIFrame.buttonEl.click();
|
||||
}
|
||||
return;
|
||||
}
|
||||
});
|
||||
case "p":
|
||||
if (isVisible(actionPDF)) {
|
||||
actionPDF.buttonEl.click();
|
||||
}
|
||||
return;
|
||||
case "f":
|
||||
if (isVisible(actionIFrame)) {
|
||||
actionIFrame.buttonEl.click();
|
||||
}
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
search.inputEl.focus();
|
||||
if(file) {
|
||||
if (file) {
|
||||
search.setValue(file.path);
|
||||
suggester.close();
|
||||
}
|
||||
updateForm();
|
||||
void updateForm();
|
||||
}
|
||||
|
||||
onClose(): void {
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
import { Modal, Setting } from "obsidian";
|
||||
import ExcalidrawPlugin from "src/core/main";
|
||||
import { t } from "src/lang/helpers";
|
||||
import { setElementDisplay, setSanitizedHtml } from "src/utils/htmlUtils";
|
||||
|
||||
declare const PLUGIN_VERSION: string;
|
||||
|
||||
/**
|
||||
* A modal dialog that informs the user about a version mismatch between the version recorded by Obsidian and the actual version of the plugin executable.
|
||||
* Explain that this can be the result of a partial sync, such as an Obsidian Sync Standard plan, which does not syncronize files larger than 5MB, and the plugin executable is larger.
|
||||
* Explain that changing the plugin version information in Obsidian can lead to unexpected behavior in plugins suchs as the Plugin Update Tracker plugin or the BRAT plugin.
|
||||
* Explain that changing the plugin version information in Obsidian can lead to unexpected behavior in plugins suchs as the Plugin Update Tracker plugin or the BRAT plugin.
|
||||
* The user has a toggle button to disable this check in the future. There is additional information that this can be reenabled in plugin settings.
|
||||
* The user can click update obsidian version info to match the plugin version, and open Obsidian settings to redownload the plugin.
|
||||
* The user can click ignore to dismiss the dialog.
|
||||
@@ -18,9 +19,7 @@ export class VersionMismatchPrompt extends Modal {
|
||||
private resolved: boolean;
|
||||
private isDirty: boolean = false;
|
||||
|
||||
public constructor(
|
||||
private plugin: ExcalidrawPlugin,
|
||||
) {
|
||||
public constructor(private plugin: ExcalidrawPlugin) {
|
||||
super(plugin.app);
|
||||
}
|
||||
|
||||
@@ -42,24 +41,28 @@ export class VersionMismatchPrompt extends Modal {
|
||||
|
||||
contentEl.createEl("h2", { text: t("VERSION_MISMATCH_HEADING") });
|
||||
const p1 = contentEl.createEl("p");
|
||||
p1.innerHTML = t("VERSION_MISMATCH_NOTICE")
|
||||
.replace("{VAL_RECORDED}", recorded)
|
||||
.replace("{VAL_ACTUAL}", actual);
|
||||
setSanitizedHtml(
|
||||
p1,
|
||||
t("VERSION_MISMATCH_NOTICE")
|
||||
.replace("{VAL_RECORDED}", recorded)
|
||||
.replace("{VAL_ACTUAL}", actual),
|
||||
);
|
||||
|
||||
const p2 = contentEl.createEl("p");
|
||||
p2.innerHTML = t("VERSION_MISMATCH_CAUSE");
|
||||
setSanitizedHtml(p2, t("VERSION_MISMATCH_CAUSE"));
|
||||
|
||||
const p3 = contentEl.createEl("p");
|
||||
p3.innerHTML = t("VERSION_MISMATCH_OPTIONS");
|
||||
setSanitizedHtml(p3, t("VERSION_MISMATCH_OPTIONS"));
|
||||
|
||||
const p4 = contentEl.createEl("p");
|
||||
p4.innerHTML = t("VERSION_MISMATCH_NOTE");
|
||||
setSanitizedHtml(p4, t("VERSION_MISMATCH_NOTE"));
|
||||
|
||||
new Setting(contentEl)
|
||||
.setName(t("VERSION_MISMATCH_DISABLE_NAME"))
|
||||
.setDesc(t("VERSION_MISMATCH_DISABLE_DESC"))
|
||||
.addToggle(tg =>
|
||||
tg.setValue(!this.plugin.settings.compareManifestToPluginVersion ? true : false)
|
||||
.addToggle((tg) =>
|
||||
tg
|
||||
.setValue(!this.plugin.settings.compareManifestToPluginVersion)
|
||||
.onChange(async (value) => {
|
||||
this.plugin.settings.compareManifestToPluginVersion = !value; // invert because label is Disable ...
|
||||
this.isDirty = true;
|
||||
@@ -67,21 +70,27 @@ export class VersionMismatchPrompt extends Modal {
|
||||
);
|
||||
|
||||
// Buttons row
|
||||
const buttonBar = contentEl.createDiv({ cls: "ex-version-mismatch-buttons" });
|
||||
const buttonBar = contentEl.createDiv({
|
||||
cls: "ex-version-mismatch-buttons",
|
||||
});
|
||||
|
||||
const redownloadBtn = buttonBar.createEl("button", { text: t("VERSION_MISMATCH_REDOWNLOAD") });
|
||||
const redownloadBtn = buttonBar.createEl("button", {
|
||||
text: t("VERSION_MISMATCH_REDOWNLOAD"),
|
||||
});
|
||||
redownloadBtn.addEventListener("click", () => {
|
||||
this.resolved = true; // triggers opening settings in caller
|
||||
this.close();
|
||||
});
|
||||
|
||||
const ignoreBtn = buttonBar.createEl("button", { text: t("VERSION_MISMATCH_IGNORE") });
|
||||
const ignoreBtn = buttonBar.createEl("button", {
|
||||
text: t("VERSION_MISMATCH_IGNORE"),
|
||||
});
|
||||
ignoreBtn.addEventListener("click", () => {
|
||||
this.resolved = false;
|
||||
this.close();
|
||||
});
|
||||
|
||||
buttonBar.style.display = "flex";
|
||||
setElementDisplay(buttonBar, "flex");
|
||||
buttonBar.style.gap = "0.5rem";
|
||||
buttonBar.style.marginTop = "1rem";
|
||||
redownloadBtn.style.backgroundColor = "var(--interactive-accent)";
|
||||
@@ -90,7 +99,7 @@ export class VersionMismatchPrompt extends Modal {
|
||||
|
||||
async onClose() {
|
||||
super.onClose();
|
||||
if(this.isDirty) {
|
||||
if (this.isDirty) {
|
||||
await this.plugin.saveSettings();
|
||||
}
|
||||
if (!this.resolved) {
|
||||
@@ -99,4 +108,4 @@ export class VersionMismatchPrompt extends Modal {
|
||||
this.resolvePromise && this.resolvePromise(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -5,12 +5,15 @@ 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) {
|
||||
*
|
||||
* @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"));
|
||||
@@ -21,9 +24,13 @@ export async function copyLinkToSelectedElementToClipboard(view: ExcalidrawView,
|
||||
|
||||
if (elements.length === 2) {
|
||||
const textEl = elements.filter((el) => el.type === "text");
|
||||
if (textEl.length === 1 && (textEl[0] as ExcalidrawTextElement).containerId) {
|
||||
if (
|
||||
textEl.length === 1 &&
|
||||
(textEl[0] as ExcalidrawTextElement).containerId
|
||||
) {
|
||||
const container = elements.filter(
|
||||
(el) => el.boundElements && el.boundElements.some((be) => be.type === "text"),
|
||||
(el) =>
|
||||
el.boundElements && el.boundElements.some((be) => be.type === "text"),
|
||||
);
|
||||
if (container.length === 1) {
|
||||
elementId = textEl[0].id;
|
||||
@@ -65,23 +72,21 @@ export async function copyLinkToSelectedElementToClipboard(view: ExcalidrawView,
|
||||
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",
|
||||
@@ -89,7 +94,6 @@ export async function copyLinkToSelectedElementToClipboard(view: ExcalidrawView,
|
||||
cancelled = false;
|
||||
prefix = "frame=";
|
||||
elementId = getFrameTarget();
|
||||
return;
|
||||
},
|
||||
},
|
||||
clippedframe: {
|
||||
@@ -98,7 +102,6 @@ export async function copyLinkToSelectedElementToClipboard(view: ExcalidrawView,
|
||||
cancelled = false;
|
||||
prefix = "clippedframe=";
|
||||
elementId = getFrameTarget();
|
||||
return;
|
||||
},
|
||||
},
|
||||
};
|
||||
@@ -164,7 +167,8 @@ export async function copyLinkToSelectedElementToClipboard(view: ExcalidrawView,
|
||||
undefined,
|
||||
undefined,
|
||||
(container: HTMLElement) => {
|
||||
const wrapper = container.createDiv?.("excalidraw-prompt-checkboxes") ?? container;
|
||||
const wrapper =
|
||||
container.createDiv?.("excalidraw-prompt-checkboxes") ?? container;
|
||||
const ownerDoc = wrapper.ownerDocument ?? document;
|
||||
|
||||
const anchorRow = ownerDoc.createElement("label");
|
||||
@@ -233,8 +237,8 @@ export async function copyLinkToSelectedElementToClipboard(view: ExcalidrawView,
|
||||
alias = "100%";
|
||||
}
|
||||
|
||||
navigator.clipboard.writeText(
|
||||
await navigator.clipboard.writeText(
|
||||
`${prefix.length > 0 ? "!" : ""}[[${view.file.path}#^${prefix}${elementId}${alias ? `|${alias}` : ``}]]`,
|
||||
);
|
||||
new Notice(t("INSERT_LINK_TO_ELEMENT_READY"));
|
||||
}
|
||||
}
|
||||
@@ -14,18 +14,19 @@ Formatting_formatting-math_formatting-math-end_keyword_math_math- { "" }
|
||||
any { _ }
|
||||
}
|
||||
*/
|
||||
import {LRParser} from "@lezer/lr"
|
||||
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-",
|
||||
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
|
||||
})
|
||||
topRules: { Document: [0, 1] },
|
||||
tokenPrec: 0,
|
||||
});
|
||||
+941
-500
File diff suppressed because it is too large.
Load diff
+1318
-731
File diff suppressed because it is too large.
Load diff
@@ -10,8 +10,10 @@ export class ExcalidrawConfig {
|
||||
}
|
||||
|
||||
updateValues(plugin: ExcalidrawPlugin) {
|
||||
if(DEVICE.isIOS) return;
|
||||
this.areaLimit = 16777216*plugin.settings.areaZoomLimit; //this.plugin.settings.areaLimit;
|
||||
this.widthHeightLimit = 32767*plugin.settings.areaZoomLimit; //his.plugin.settings.widthHeightLimit;
|
||||
if (DEVICE.isIOS) {
|
||||
return;
|
||||
}
|
||||
this.areaLimit = 16777216 * plugin.settings.areaZoomLimit; //this.plugin.settings.areaLimit;
|
||||
this.widthHeightLimit = 32767 * plugin.settings.areaZoomLimit; //his.plugin.settings.widthHeightLimit;
|
||||
}
|
||||
}
|
||||
}
|
||||
+599
-416
File diff suppressed because it is too large.
Load diff
+38
-21
@@ -1,42 +1,59 @@
|
||||
// alternative https://github.com/OPD-libs/OPD-libs
|
||||
|
||||
export default class FrontmatterEditor {
|
||||
private frontmatterStr:string;
|
||||
private frontmatterStr: string;
|
||||
private dataWOfrontmatter: string;
|
||||
private initialized:boolean = false;
|
||||
private initialized: boolean = false;
|
||||
|
||||
constructor (data:string) {
|
||||
constructor(data: string) {
|
||||
this.dataWOfrontmatter = data;
|
||||
|
||||
data = data.replaceAll("\r\n", "\n").replaceAll("\r", "\n");
|
||||
const tmp = data.split(/^---(?:.|\n)*(?:^---\n)/gm);
|
||||
if(tmp.length!==2) return;
|
||||
if (tmp.length !== 2) {
|
||||
return;
|
||||
}
|
||||
this.dataWOfrontmatter = tmp[1];
|
||||
this.frontmatterStr = data.match(/^---((?:.|\n)*)(?:^---\n)/gm)[0].replaceAll(/(^---\n|^\n)/gm,"").trim()+"\n";
|
||||
this.frontmatterStr = `${data
|
||||
.match(/^---((?:.|\n)*)(?:^---\n)/gm)[0]
|
||||
.replaceAll(/(^---\n|^\n)/gm, "")
|
||||
.trim()}\n`;
|
||||
this.initialized = true;
|
||||
}
|
||||
|
||||
public hasKey(key:string):boolean {
|
||||
if(!this.initialized) return false;
|
||||
const reg = new RegExp(`^${key}:`,"gm");
|
||||
|
||||
public hasKey(key: string): boolean {
|
||||
if (!this.initialized) {
|
||||
return false;
|
||||
}
|
||||
const reg = new RegExp(`^${key}:`, "gm");
|
||||
return Boolean(this.frontmatterStr.match(reg));
|
||||
}
|
||||
|
||||
public setKey(key:string, value:string) {
|
||||
if(!this.initialized) return;
|
||||
value = value.replaceAll("\r\n", "\n").replaceAll("\r", "\n").replaceAll(":",";").trim().split("\n").join(" ");
|
||||
if(this.hasKey(key)) {
|
||||
const reg = new RegExp(`^${key}:.*\\n(?:\\s\\s.*\\n)*`,"gm");
|
||||
this.frontmatterStr =
|
||||
this.frontmatterStr.split(reg).join("\n").trim() +
|
||||
`\n${key}: ${value}`;
|
||||
public setKey(key: string, value: string) {
|
||||
if (!this.initialized) {
|
||||
return;
|
||||
}
|
||||
this.frontmatterStr = this.frontmatterStr.trim()+`\n${key}: ${value}`;
|
||||
value = value
|
||||
.replaceAll("\r\n", "\n")
|
||||
.replaceAll("\r", "\n")
|
||||
.replaceAll(":", ";")
|
||||
.trim()
|
||||
.split("\n")
|
||||
.join(" ");
|
||||
if (this.hasKey(key)) {
|
||||
const reg = new RegExp(`^${key}:.*\\n(?:\\s\\s.*\\n)*`, "gm");
|
||||
this.frontmatterStr = `${this.frontmatterStr.split(reg).join("\n").trim()}\n${key}: ${value}`;
|
||||
return;
|
||||
}
|
||||
this.frontmatterStr = `${this.frontmatterStr.trim()}\n${key}: ${value}`;
|
||||
}
|
||||
|
||||
get data() {
|
||||
if(!this.initialized) return this.dataWOfrontmatter;
|
||||
return ["---",this.frontmatterStr,"---",this.dataWOfrontmatter].join("\n");
|
||||
if (!this.initialized) {
|
||||
return this.dataWOfrontmatter;
|
||||
}
|
||||
return ["---", this.frontmatterStr, "---", this.dataWOfrontmatter].join(
|
||||
"\n",
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
+318
-83
@@ -1,20 +1,28 @@
|
||||
import { App, Notice, TFile } from "obsidian";
|
||||
import ExcalidrawPlugin from "src/core/main";
|
||||
import { PDFPageViewProps, Size } from "src/types/embeddedFileLoaderTypes";
|
||||
import { convertSVGStringToElement } from "../utils/utils";
|
||||
import { FILENAMEPARTS, PreviewImageType } from "../types/utilTypes";
|
||||
import { hasExcalidrawEmbeddedImagesTreeChanged } from "../utils/fileUtils";
|
||||
|
||||
//@ts-ignore
|
||||
const DB_NAME = "Excalidraw " + app.appId;
|
||||
const DB_NAME = `Excalidraw ${(app as unknown as { appId: string }).appId}`;
|
||||
const CACHE_STORE = "imageCache";
|
||||
const BACKUP_STORE = "drawingBAK";
|
||||
|
||||
type FileCacheData = { mtime: number; blob?: Blob; svg?: string};
|
||||
type FileCacheData = {
|
||||
mtime: number;
|
||||
lastAccessed?: number;
|
||||
blob?: Blob;
|
||||
svg?: string;
|
||||
renderScale?: number;
|
||||
size?: Size;
|
||||
pdfPageViewProps?: PDFPageViewProps;
|
||||
};
|
||||
type BackupData = string;
|
||||
type BackupKey = string;
|
||||
|
||||
export type ImageKey = {
|
||||
filepath: string;
|
||||
cacheId?: string;
|
||||
blockref: string;
|
||||
sectionref: string;
|
||||
isDark: boolean;
|
||||
@@ -24,16 +32,23 @@ export type ImageKey = {
|
||||
inlineFonts: boolean;
|
||||
} & FILENAMEPARTS;
|
||||
|
||||
type GetImageFromCacheOptions = {
|
||||
skipDependencyCheck?: boolean;
|
||||
minRenderScale?: number;
|
||||
};
|
||||
|
||||
const getKey = (key: ImageKey): string =>
|
||||
`${key.filepath}#${key.blockref??""}#${key.sectionref??""}#${key.isDark ? 1 : 0}#${
|
||||
key.hasGroupref}#${key.hasArearef}#${key.hasFrameref}#${key.hasClippedFrameref}#${
|
||||
key.hasSectionref}#${key.inlineFonts}#${
|
||||
`${key.filepath}#${key.cacheId ?? ""}#${key.blockref ?? ""}#${key.sectionref ?? ""}#${key.isDark ? 1 : 0}#${
|
||||
key.hasGroupref
|
||||
}#${key.hasArearef}#${key.hasFrameref}#${key.hasClippedFrameref}#${
|
||||
key.hasSectionref
|
||||
}#${key.inlineFonts}#${
|
||||
key.previewImageType === PreviewImageType.SVGIMG
|
||||
? 1
|
||||
: key.previewImageType === PreviewImageType.PNG
|
||||
? 0
|
||||
: 2
|
||||
}#${key.scale}${key.isTransparent?"#t":""}`; //key.isSVG ? 1 : 0
|
||||
: 2
|
||||
}#${key.scale}${key.isTransparent ? "#t" : ""}`; //key.isSVG ? 1 : 0
|
||||
|
||||
class ImageCache {
|
||||
private dbName: string;
|
||||
@@ -48,10 +63,47 @@ class ImageCache {
|
||||
private purgeInvalidCacheTimer: number = null;
|
||||
private purgeInvalidBackupTimer: number = null;
|
||||
|
||||
private getCacheRetentionCutoff(): number {
|
||||
const retentionDays = Math.max(
|
||||
1,
|
||||
this.plugin?.settings?.imageCacheRetentionDays ?? 30,
|
||||
);
|
||||
return Date.now() - retentionDays * 24 * 60 * 60 * 1000;
|
||||
}
|
||||
|
||||
private touchCacheData(key: string, cacheData: FileCacheData): void {
|
||||
if (!this.db) {
|
||||
return;
|
||||
}
|
||||
const nextLastAccessed = Date.now();
|
||||
// Avoid rewriting IndexedDB on every cache hit while still keeping actively used
|
||||
// entries alive for retention-based purging.
|
||||
if (
|
||||
cacheData.lastAccessed &&
|
||||
nextLastAccessed - cacheData.lastAccessed < 60 * 1000
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
const transaction = this.db.transaction(this.cacheStoreName, "readwrite");
|
||||
const store = transaction.objectStore(this.cacheStoreName);
|
||||
store.put(
|
||||
{
|
||||
...cacheData,
|
||||
lastAccessed: nextLastAccessed,
|
||||
},
|
||||
key,
|
||||
);
|
||||
}
|
||||
|
||||
public destroy(): void {
|
||||
this.isInitializing = true;
|
||||
if(this.purgeInvalidCacheTimer) clearTimeout(this.purgeInvalidCacheTimer);
|
||||
if(this.purgeInvalidBackupTimer) clearTimeout(this.purgeInvalidBackupTimer);
|
||||
if (this.purgeInvalidCacheTimer) {
|
||||
window.clearTimeout(this.purgeInvalidCacheTimer);
|
||||
}
|
||||
if (this.purgeInvalidBackupTimer) {
|
||||
window.clearTimeout(this.purgeInvalidBackupTimer);
|
||||
}
|
||||
this.db = null;
|
||||
this.plugin = null;
|
||||
this.app = null;
|
||||
@@ -98,7 +150,11 @@ class ImageCache {
|
||||
};
|
||||
|
||||
request.onerror = () => {
|
||||
reject(new Error(`Failed to open or create IndexedDB database: ${this.dbName}`));
|
||||
reject(
|
||||
new Error(
|
||||
`Failed to open or create IndexedDB database: ${this.dbName}`,
|
||||
),
|
||||
);
|
||||
};
|
||||
});
|
||||
|
||||
@@ -129,7 +185,9 @@ class ImageCache {
|
||||
};
|
||||
|
||||
upgradeRequest.onerror = () => {
|
||||
reject(new Error(`Failed to upgrade IndexedDB database: ${this.dbName}`));
|
||||
reject(
|
||||
new Error(`Failed to upgrade IndexedDB database: ${this.dbName}`),
|
||||
);
|
||||
};
|
||||
});
|
||||
|
||||
@@ -140,24 +198,28 @@ class ImageCache {
|
||||
resolve(db);
|
||||
};
|
||||
openRequest.onerror = () => {
|
||||
reject(new Error(`Failed to open IndexedDB database: ${this.dbName}`));
|
||||
reject(
|
||||
new Error(`Failed to open IndexedDB database: ${this.dbName}`),
|
||||
);
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
this.purgeInvalidCacheTimer = window.setTimeout(async ()=>{
|
||||
this.purgeInvalidCacheTimer = window.setTimeout(() => {
|
||||
this.purgeInvalidCacheTimer = null;
|
||||
this.purgeInvalidCacheFiles();
|
||||
void this.purgeInvalidCacheFiles();
|
||||
}, 60000);
|
||||
|
||||
this.purgeInvalidBackupTimer = window.setTimeout(async ()=>{
|
||||
this.purgeInvalidBackupTimer = window.setTimeout(() => {
|
||||
this.purgeInvalidBackupTimer = null;
|
||||
this.purgeInvalidBackupFiles();
|
||||
void this.purgeInvalidBackupFiles();
|
||||
}, 120000);
|
||||
} finally {
|
||||
this.isInitializing = false;
|
||||
if(this.initializationNotice) {
|
||||
new Notice("Excalidraw Image Cache is Initialized - You may now retry opening your damaged drawing.");
|
||||
if (this.initializationNotice) {
|
||||
new Notice(
|
||||
"Excalidraw Image Cache is Initialized - You may now retry opening your damaged drawing.",
|
||||
);
|
||||
this.initializationNotice = false;
|
||||
}
|
||||
console.log("Initialized Excalidraw Image Cache");
|
||||
@@ -166,21 +228,35 @@ class ImageCache {
|
||||
|
||||
private async purgeInvalidCacheFiles(): Promise<void> {
|
||||
return new Promise<void>((resolve, reject) => {
|
||||
const transaction = this.db!.transaction(this.cacheStoreName, "readwrite");
|
||||
const transaction = this.db!.transaction(
|
||||
this.cacheStoreName,
|
||||
"readwrite",
|
||||
);
|
||||
const store = transaction.objectStore(this.cacheStoreName);
|
||||
const files = this.app.vault.getFiles();
|
||||
const deletePromises: Promise<void>[] = [];
|
||||
const request = store.openCursor();
|
||||
request.onsuccess = (event: Event) => {
|
||||
const cursor = (event.target as IDBRequest<IDBCursorWithValue | null>).result;
|
||||
if(cursor) {
|
||||
const cursor = (event.target as IDBRequest<IDBCursorWithValue | null>)
|
||||
.result;
|
||||
if (cursor) {
|
||||
const key = cursor.key as string;
|
||||
const isLegacyKey = key.split("#").length-1 < 12; // introduced hasGroupref, etc. in 1.9.28 // introduced hasClippedFrameref in 2.2.10 //introduced inlineFonts 2.2.11
|
||||
const isLegacyKey = key.split("#").length - 1 < 13; // introduced hasGroupref, etc. in 1.9.28 // introduced hasClippedFrameref in 2.2.10 //introduced inlineFonts 2.2.11 //introduced cacheId in 2.23.x
|
||||
const filepath = key.split("#")[0];
|
||||
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)) {
|
||||
const file = fileExists
|
||||
? files.find((f: TFile) => f.path === filepath)
|
||||
: null;
|
||||
const lastAccessed = cursor.value.lastAccessed ?? cursor.value.mtime;
|
||||
const isExpired = lastAccessed < this.getCacheRetentionCutoff();
|
||||
if (
|
||||
isLegacyKey ||
|
||||
!file ||
|
||||
(file && file.stat.mtime > cursor.value.mtime) ||
|
||||
(!cursor.value.blob && !cursor.value.svg) ||
|
||||
isExpired
|
||||
) {
|
||||
if (this.obsidanURLCache.has(key)) {
|
||||
URL.revokeObjectURL(this.obsidanURLCache.get(key));
|
||||
this.obsidanURLCache.delete(key);
|
||||
}
|
||||
@@ -188,12 +264,12 @@ class ImageCache {
|
||||
new Promise<void>((innerResolve, innerReject) => {
|
||||
const deleteRequest = store.delete(cursor.primaryKey);
|
||||
deleteRequest.onsuccess = () => innerResolve();
|
||||
deleteRequest.onerror = (ev: Event) => {
|
||||
deleteRequest.onerror = () => {
|
||||
const error = deleteRequest.error;
|
||||
const errorMsg = `Failed to delete file with key: ${key}. Error: ${error.message}`
|
||||
const errorMsg = `Failed to delete file with key: ${key}. Error: ${error.message}`;
|
||||
innerReject(new Error(errorMsg));
|
||||
}
|
||||
})
|
||||
};
|
||||
}),
|
||||
);
|
||||
}
|
||||
cursor.continue();
|
||||
@@ -210,7 +286,7 @@ class ImageCache {
|
||||
request.onerror = () => {
|
||||
const error = request.error;
|
||||
console.log(error);
|
||||
const errorMsg = `Failed to purge invalid files from IndexedDB. Error: ${error.message}`
|
||||
const errorMsg = `Failed to purge invalid files from IndexedDB. Error: ${error.message}`;
|
||||
reject(new Error(errorMsg));
|
||||
};
|
||||
});
|
||||
@@ -224,7 +300,8 @@ class ImageCache {
|
||||
const request = store.openCursor();
|
||||
return await new Promise<void>((resolve, reject) => {
|
||||
request.onsuccess = (event: Event) => {
|
||||
const cursor = (event.target as IDBRequest<IDBCursorWithValue | null>).result;
|
||||
const cursor = (event.target as IDBRequest<IDBCursorWithValue | null>)
|
||||
.result;
|
||||
if (cursor) {
|
||||
const key = cursor.key as BackupKey;
|
||||
const fileExists = files.some((f: TFile) => f.path === key);
|
||||
@@ -234,8 +311,10 @@ class ImageCache {
|
||||
const deleteRequest = store.delete(cursor.primaryKey);
|
||||
deleteRequest.onsuccess = () => resolve();
|
||||
deleteRequest.onerror = () =>
|
||||
reject(new Error(`Failed to delete backup file with key: ${key}`));
|
||||
})
|
||||
reject(
|
||||
new Error(`Failed to delete backup file with key: ${key}`),
|
||||
);
|
||||
}),
|
||||
);
|
||||
}
|
||||
cursor.continue();
|
||||
@@ -248,17 +327,20 @@ class ImageCache {
|
||||
.catch((error) => reject(error));
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
request.onerror = () => {
|
||||
const error = request.error;
|
||||
const errorMsg = `Failed to purge invalid backup files from IndexedDB. Error: ${error.message}`
|
||||
const errorMsg = `Failed to purge invalid backup files from IndexedDB. Error: ${error.message}`;
|
||||
console.log(error);
|
||||
reject(new Error(errorMsg));
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
private getObjectStore(mode: IDBTransactionMode, storeName: string): IDBObjectStore {
|
||||
private getObjectStore(
|
||||
mode: IDBTransactionMode,
|
||||
storeName: string,
|
||||
): IDBObjectStore {
|
||||
const transaction = this.db!.transaction(storeName, mode);
|
||||
return transaction.objectStore(storeName);
|
||||
}
|
||||
@@ -296,52 +378,105 @@ class ImageCache {
|
||||
}
|
||||
|
||||
public isReady(): boolean {
|
||||
return !!this.db && !this.isInitializing && !!this.plugin && this.plugin.settings.allowImageCache;
|
||||
return (
|
||||
!!this.db &&
|
||||
!this.isInitializing &&
|
||||
!!this.plugin &&
|
||||
this.plugin.settings.allowImageCache
|
||||
);
|
||||
}
|
||||
|
||||
private fullyInitialized = false;
|
||||
|
||||
public async getImageFromCache(key_: ImageKey): Promise<string | SVGSVGElement | undefined> {
|
||||
private async getResolvedCacheData(
|
||||
key_: ImageKey,
|
||||
options?: GetImageFromCacheOptions,
|
||||
): Promise<{ cacheData: FileCacheData; key: string } | undefined> {
|
||||
if (!this.isReady()) {
|
||||
return null; // Database not initialized yet
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const key = getKey(key_);
|
||||
|
||||
try {
|
||||
const cachedData = this.fullyInitialized
|
||||
? await this.getCacheData(key)
|
||||
: await Promise.race([
|
||||
this.getCacheData(key),
|
||||
new Promise<undefined>((_,reject) => setTimeout(() => {
|
||||
reject(undefined);
|
||||
}, 100))
|
||||
]);
|
||||
? await this.getCacheData(key)
|
||||
: await Promise.race([
|
||||
this.getCacheData(key),
|
||||
new Promise<undefined>((_, reject) =>
|
||||
window.setTimeout(() => {
|
||||
reject(undefined);
|
||||
}, 100),
|
||||
),
|
||||
]);
|
||||
this.fullyInitialized = true;
|
||||
if(!cachedData) return undefined;
|
||||
|
||||
const file = this.app.vault.getAbstractFileByPath(key_.filepath.split("#")[0]);
|
||||
if (!file || !(file instanceof TFile)) return undefined;
|
||||
if (cachedData && (cachedData.mtime >= file.stat.mtime)) {
|
||||
if(hasExcalidrawEmbeddedImagesTreeChanged(file, cachedData.mtime, this.plugin)) {
|
||||
return undefined;
|
||||
}
|
||||
if(cachedData.svg) {
|
||||
return convertSVGStringToElement(cachedData.svg);
|
||||
}
|
||||
if(this.obsidanURLCache.has(key)) {
|
||||
return this.obsidanURLCache.get(key);
|
||||
}
|
||||
const obsidianURL = URL.createObjectURL(cachedData.blob);
|
||||
this.obsidanURLCache.set(key, obsidianURL);
|
||||
return obsidianURL;
|
||||
if (!cachedData) {
|
||||
return undefined;
|
||||
}
|
||||
return undefined;
|
||||
} catch(e) {
|
||||
|
||||
const file = this.app.vault.getAbstractFileByPath(
|
||||
key_.filepath.split("#")[0],
|
||||
);
|
||||
if (!file || !(file instanceof TFile)) {
|
||||
return undefined;
|
||||
}
|
||||
if (cachedData.mtime < file.stat.mtime) {
|
||||
return undefined;
|
||||
}
|
||||
if (
|
||||
!options?.skipDependencyCheck &&
|
||||
hasExcalidrawEmbeddedImagesTreeChanged(
|
||||
file,
|
||||
cachedData.mtime,
|
||||
this.plugin,
|
||||
)
|
||||
) {
|
||||
return undefined;
|
||||
}
|
||||
// Validated reads can require a minimum render scale so lower-resolution PDF
|
||||
// snapshots are upgraded in the background without blocking the first paint.
|
||||
const cachedRenderScale = cachedData.renderScale ?? key_.scale;
|
||||
if (
|
||||
options?.minRenderScale &&
|
||||
cachedRenderScale < options.minRenderScale
|
||||
) {
|
||||
return undefined;
|
||||
}
|
||||
this.touchCacheData(key, cachedData);
|
||||
return { cacheData: cachedData, key };
|
||||
} catch (_) {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
public async getImageCacheData(
|
||||
key_: ImageKey,
|
||||
options?: GetImageFromCacheOptions,
|
||||
): Promise<FileCacheData | undefined> {
|
||||
return (await this.getResolvedCacheData(key_, options))?.cacheData;
|
||||
}
|
||||
|
||||
public async getImageFromCache(
|
||||
key_: ImageKey,
|
||||
options?: GetImageFromCacheOptions,
|
||||
): Promise<string | SVGSVGElement | undefined> {
|
||||
const resolved = await this.getResolvedCacheData(key_, options);
|
||||
if (!resolved) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const { cacheData, key } = resolved;
|
||||
if (cacheData.svg) {
|
||||
return convertSVGStringToElement(cacheData.svg);
|
||||
}
|
||||
if (this.obsidanURLCache.has(key)) {
|
||||
return this.obsidanURLCache.get(key);
|
||||
}
|
||||
const obsidianURL = URL.createObjectURL(cacheData.blob);
|
||||
this.obsidanURLCache.set(key, obsidianURL);
|
||||
return obsidianURL;
|
||||
}
|
||||
|
||||
public async getBAKFromCache(filepath: string): Promise<BackupData | null> {
|
||||
if (!this.isReady()) {
|
||||
return null; // Database not initialized yet
|
||||
@@ -351,36 +486,57 @@ class ImageCache {
|
||||
}
|
||||
|
||||
//cache SVG should have the width and height parameters and not the embedded font
|
||||
public addImageToCache(key_: ImageKey, obsidianURL: string, image: Blob|SVGSVGElement): void {
|
||||
public addImageToCache(
|
||||
key_: ImageKey,
|
||||
obsidianURL: string,
|
||||
image: Blob | SVGSVGElement,
|
||||
metadata?: Partial<FileCacheData>,
|
||||
): void {
|
||||
if (!this.isReady()) {
|
||||
return; // Database not initialized yet
|
||||
}
|
||||
|
||||
const file = this.app.vault.getAbstractFileByPath(key_.filepath.split("#")[0]);
|
||||
if (!file || !(file instanceof TFile)) return;
|
||||
|
||||
const file = this.app.vault.getAbstractFileByPath(
|
||||
key_.filepath.split("#")[0],
|
||||
);
|
||||
if (!file || !(file instanceof TFile)) {
|
||||
return;
|
||||
}
|
||||
|
||||
let svg: string = null;
|
||||
let blob: Blob = null;
|
||||
if(image instanceof SVGSVGElement) {
|
||||
if (image instanceof SVGSVGElement) {
|
||||
svg = image.outerHTML;
|
||||
} else {
|
||||
blob = image as Blob;
|
||||
blob = image as Blob;
|
||||
}
|
||||
const data: FileCacheData = { mtime: Date.now(), blob, svg};
|
||||
const now = Date.now();
|
||||
const data: FileCacheData = {
|
||||
mtime: now,
|
||||
lastAccessed: now,
|
||||
blob,
|
||||
svg,
|
||||
...metadata,
|
||||
};
|
||||
const transaction = this.db.transaction(this.cacheStoreName, "readwrite");
|
||||
const store = transaction.objectStore(this.cacheStoreName);
|
||||
const key = getKey(key_);
|
||||
store.put(data, key);
|
||||
if(!Boolean(svg)) {
|
||||
if(this.obsidanURLCache.has(key) && this.obsidanURLCache.get(key) !== obsidianURL) {
|
||||
if (!Boolean(svg) && obsidianURL) {
|
||||
if (
|
||||
this.obsidanURLCache.has(key) &&
|
||||
this.obsidanURLCache.get(key) !== obsidianURL
|
||||
) {
|
||||
URL.revokeObjectURL(this.obsidanURLCache.get(key));
|
||||
}
|
||||
this.obsidanURLCache.set(key, obsidianURL);
|
||||
}
|
||||
}
|
||||
|
||||
public async addBAKToCache(filepath: string, data: BackupData): Promise<void> {
|
||||
public async addBAKToCache(
|
||||
filepath: string,
|
||||
data: BackupData,
|
||||
): Promise<void> {
|
||||
if (!this.isReady()) {
|
||||
return; // Database not initialized yet
|
||||
}
|
||||
@@ -397,7 +553,7 @@ class ImageCache {
|
||||
|
||||
const transaction = this.db.transaction(this.backupStoreName, "readwrite");
|
||||
const store = transaction.objectStore(this.backupStoreName);
|
||||
|
||||
|
||||
return new Promise<void>((resolve, reject) => {
|
||||
const request = store.delete(filepath);
|
||||
request.onsuccess = () => {
|
||||
@@ -432,20 +588,99 @@ class ImageCache {
|
||||
if (!this.isReady()) {
|
||||
return; // Database not initialized yet
|
||||
}
|
||||
|
||||
|
||||
const transaction = this.db.transaction([storeName], "readwrite");
|
||||
const store = transaction.objectStore(storeName);
|
||||
|
||||
|
||||
return new Promise<void>((resolve, reject) => {
|
||||
const request = store.clear();
|
||||
request.onsuccess = () => {
|
||||
new Notice(message);
|
||||
resolve();
|
||||
};
|
||||
request.onerror = () => reject(new Error(`Failed to clear ${storeName}.`));
|
||||
request.onerror = () =>
|
||||
reject(new Error(`Failed to clear ${storeName}.`));
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
export const imageCache = new ImageCache(DB_NAME, CACHE_STORE, BACKUP_STORE);
|
||||
export const imageCache = new ImageCache(DB_NAME, CACHE_STORE, BACKUP_STORE);
|
||||
|
||||
/* -------------------------------------------------------- */
|
||||
/* Legacy cleanup */
|
||||
// early implementation used localStorage as the image cache,
|
||||
// which if not cleaned can cause Obsidian performance issues
|
||||
/* -------------------------------------------------------- */
|
||||
const LEGACY_LS_PURGE_MARKER = "excalidraw-legacy-ls-purge-v1";
|
||||
|
||||
type LegacyKeyShape = {
|
||||
filepath: unknown;
|
||||
blockref: unknown;
|
||||
isDark: unknown;
|
||||
isSVG: unknown;
|
||||
scale: unknown;
|
||||
};
|
||||
|
||||
const isObject = (value: unknown): value is Record<string, unknown> =>
|
||||
typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
|
||||
const hasLegacyShape = (value: unknown): value is LegacyKeyShape => {
|
||||
if (!isObject(value)) {
|
||||
return false;
|
||||
}
|
||||
return (
|
||||
"filepath" in value &&
|
||||
"blockref" in value &&
|
||||
"isDark" in value &&
|
||||
"isSVG" in value &&
|
||||
"scale" in value
|
||||
);
|
||||
};
|
||||
|
||||
export const purgeLegacyLocalStorageImageCache = (): string | null => {
|
||||
try {
|
||||
if (typeof window === "undefined" || !window.localStorage) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (localStorage.getItem(LEGACY_LS_PURGE_MARKER) === "1") {
|
||||
return null;
|
||||
}
|
||||
|
||||
const keys = Object.keys(localStorage);
|
||||
let deleted = 0;
|
||||
|
||||
for (const key of keys) {
|
||||
let parsed: unknown;
|
||||
try {
|
||||
parsed = JSON.parse(key);
|
||||
} catch {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!hasLegacyShape(parsed)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
localStorage.removeItem(key);
|
||||
deleted += 1;
|
||||
}
|
||||
|
||||
localStorage.setItem(LEGACY_LS_PURGE_MARKER, "1");
|
||||
|
||||
if (deleted === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return `Purged ${deleted} legacy localStorage image cache entr${
|
||||
deleted === 1 ? "y." : "ies."
|
||||
}`;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
const report = purgeLegacyLocalStorageImageCache();
|
||||
if (report) {
|
||||
console.info(report);
|
||||
}
|
||||
Loaded 100 of 183 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user