mirror of
https://github.com/zsviczian/obsidian-excalidraw-plugin.git
synced 2026-12-03 06:43:35 +00:00
Compare commits
49
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
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 |
No files matched your search
@@ -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/>.
|
||||
+24
-14
@@ -1,17 +1,30 @@
|
||||
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 } from "obsidian";
|
||||
|
||||
type DataURL = string & { _brand: "DataURL" };
|
||||
type FileId = string & { _brand: "FileId" };
|
||||
const fileid = customAlphabet("1234567890abcdef", 40);
|
||||
|
||||
type LatexPluginLike = {
|
||||
app: {
|
||||
vault: {
|
||||
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 +51,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,8 +59,8 @@ 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) {
|
||||
@@ -76,10 +89,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
+5
-4
@@ -20,7 +20,7 @@
|
||||
"rollup": "^2.70.1",
|
||||
"rollup-plugin-terser": "^7.0.2",
|
||||
"tslib": "^2.8.1",
|
||||
"typescript": "^5.7.3"
|
||||
"typescript": "5.9.3"
|
||||
}
|
||||
},
|
||||
"node_modules/@babel/code-frame": {
|
||||
@@ -1180,10 +1180,11 @@
|
||||
"license": "0BSD"
|
||||
},
|
||||
"node_modules/typescript": {
|
||||
"version": "5.7.3",
|
||||
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.7.3.tgz",
|
||||
"integrity": "sha512-84MVSjMEHP+FQRPy3pX9sTVV/INIex71s9TL2Gm5FG/WG1SqXeKyZ0k7/blY/4FdOzI12CBy1vGc4og/eus0fw==",
|
||||
"version": "5.9.3",
|
||||
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",
|
||||
"integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"bin": {
|
||||
"tsc": "bin/tsc",
|
||||
"tsserver": "bin/tsserver"
|
||||
|
||||
@@ -19,6 +19,6 @@
|
||||
"rollup": "^2.70.1",
|
||||
"rollup-plugin-terser": "^7.0.2",
|
||||
"tslib": "^2.8.1",
|
||||
"typescript": "^5.7.3"
|
||||
"typescript": "5.9.3"
|
||||
}
|
||||
}
|
||||
@@ -2380,6 +2380,7 @@ export type ObservedElementsAppState = {
|
||||
lockedMultiSelections: AppState["lockedMultiSelections"];
|
||||
activeLockedId: AppState["activeLockedId"];
|
||||
};
|
||||
export type BoxSelectionMode = "contain" | "overlap";
|
||||
export interface AppState {
|
||||
contextMenu: {
|
||||
items: ContextMenuItems;
|
||||
@@ -2418,6 +2419,8 @@ export interface AppState {
|
||||
* `bindingPreference` and keyboard modifiers (ctrl/alt)
|
||||
*/
|
||||
isBindingEnabled: boolean;
|
||||
/** 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 */
|
||||
@@ -2441,7 +2444,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
|
||||
@@ -3114,7 +3117,7 @@ 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 */
|
||||
@@ -3153,7 +3156,9 @@ 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;
|
||||
|
||||
/* ************************************** */
|
||||
@@ -3262,6 +3267,7 @@ declare class App extends React.Component<AppProps, AppState> {
|
||||
x: number;
|
||||
y: number;
|
||||
} | null;
|
||||
private lastCompletedCanvasClicks;
|
||||
/** previous frame pointer coords */
|
||||
previousPointerMoveCoords: {
|
||||
x: number;
|
||||
@@ -3422,6 +3428,7 @@ 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 */
|
||||
@@ -3642,6 +3649,8 @@ declare class App extends React.Component<AppProps, AppState> {
|
||||
private getSelectedTextElement;
|
||||
private getSelectedTextEditingContainerAtPosition;
|
||||
private getTextElementAtPosition;
|
||||
private isHittingTextAutoResizeHandle;
|
||||
private handleTextAutoResizeHandlePointerDown;
|
||||
private getElementAtPosition;
|
||||
private getElementsAtPosition;
|
||||
getElementHitThreshold(element: ExcalidrawElement): number;
|
||||
@@ -3651,7 +3660,9 @@ declare class App extends React.Component<AppProps, AppState> {
|
||||
private debounceDoubleClickTimestamp;
|
||||
private startImageCropping;
|
||||
private finishImageCropping;
|
||||
private shouldHandleBrowserCanvasDoubleClick;
|
||||
private handleCanvasDoubleClick;
|
||||
private handleCanvasClick;
|
||||
private getElementLinkAtPosition;
|
||||
private handleElementLinkClick;
|
||||
private getTopLayerFrameAtSceneCoords;
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
Vendored
+9
-9
@@ -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,7 @@ 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";
|
||||
/**
|
||||
* 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.
|
||||
@@ -247,7 +247,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 +986,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.
|
||||
|
||||
+9
-9
@@ -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,7 @@ 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";
|
||||
/**
|
||||
* 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.
|
||||
@@ -247,7 +247,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 +986,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
+2298
-325
File diff suppressed because it is too large.
Load diff
+121
-23
@@ -1245,6 +1245,44 @@ const parseText = async (text) => {
|
||||
|
||||
const parseImageInput = (input) => {
|
||||
const trimmed = trimText(input);
|
||||
|
||||
// Check for external/local markdown image link:  or 
|
||||
const externalMatch = trimmed.match(/^!\[(.*?)\]\(((?:https?|file):\/\/[^)]+)\)$/i);
|
||||
if (externalMatch) {
|
||||
const altText = externalMatch[1];
|
||||
const url = externalMatch[2];
|
||||
|
||||
let width = null;
|
||||
if (altText) {
|
||||
const parts = altText.split("|");
|
||||
const last = parts[parts.length - 1];
|
||||
if (/^\d+$/.test(last)) {
|
||||
width = parseInt(last);
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
const urlObj = new URL(url);
|
||||
const pathname = urlObj.pathname.toLowerCase();
|
||||
// Heuristic: check if the URL points to a standard image file extension
|
||||
const isImageUrl = IMAGE_TYPES.some(ext => pathname.endsWith("." + ext));
|
||||
|
||||
if (isImageUrl) {
|
||||
return {
|
||||
path: url,
|
||||
width,
|
||||
imageFile: null,
|
||||
isImagePath: true, // This triggers image addition in addNode
|
||||
file: null,
|
||||
isExternalImage: true // Flag to help direct link assignments later
|
||||
};
|
||||
}
|
||||
} catch (e) {}
|
||||
|
||||
// If not matching an image extension, return null so parseEmbeddableInput takes over
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!trimmed.startsWith("![[") || !trimmed.endsWith("]]")) return null;
|
||||
|
||||
const content = trimmed.slice(3, -2);
|
||||
@@ -1285,8 +1323,13 @@ const parseImageInput = (input) => {
|
||||
|
||||
const parseEmbeddableInput = (input, imageInfo) => {
|
||||
const trimmed = input.trim();
|
||||
const match = trimmed.match(/^!\[\]\((https?:\/\/[^)]+)\)$/);
|
||||
if (match) return match[1];
|
||||
// Ensure we capture potential alt-text formatting so we gracefully match the pattern
|
||||
const match = trimmed.match(/^!\[(.*?)\]\(((?:https?|file):\/\/[^)]+)\)$/i);
|
||||
if (match) {
|
||||
// If parseImageInput already claimed this as an external image, do not override
|
||||
if (imageInfo && imageInfo.isExternalImage) return null;
|
||||
return match[2];
|
||||
}
|
||||
const pathSplit = imageInfo?.path?.split("#");
|
||||
if (imageInfo && imageInfo.file && imageInfo.file.extension === "md" &&
|
||||
// Not an Excalidraw File or maybe an Excalidraw file with a back-of-the-card note reference
|
||||
@@ -4802,16 +4845,30 @@ const triggerGlobalLayout = async (rootId, forceUngroup = false, mustHonorMindma
|
||||
|
||||
await run(allElements, mindmapIds, root, false, sharedSets, mustHonorMindmapOrder);
|
||||
|
||||
if (structuralGroupId) {
|
||||
ea.addToGroup(groupedElementIds);
|
||||
if (structuralGroupId && !forceUngroup) {
|
||||
// Restore the exact same group ID instead of creating a new one
|
||||
// This prevents Excalidraw's editingGroupId from pointing to a deleted group,
|
||||
// which causes the 0x0 rendering artifact at the origin.
|
||||
groupedElementIds.forEach(id => {
|
||||
const el = ea.getElement(id);
|
||||
if (el && (!el.groupIds || !el.groupIds.includes(structuralGroupId))) {
|
||||
el.groupIds = [...(el.groupIds || []), structuralGroupId];
|
||||
}
|
||||
});
|
||||
}
|
||||
await addElementsToView({ captureUpdate: "IMMEDIATELY" });
|
||||
|
||||
} else {
|
||||
// If only visual change (no struct change, no boundary move), commit Run 1
|
||||
if (result1.visualChange) {
|
||||
if (structuralGroupId) {
|
||||
ea.addToGroup(groupedElementIds);
|
||||
if (structuralGroupId && !forceUngroup) {
|
||||
// Restore the exact same group ID instead of creating a new one
|
||||
groupedElementIds.forEach(id => {
|
||||
const el = ea.getElement(id);
|
||||
if (el && (!el.groupIds || !el.groupIds.includes(structuralGroupId))) {
|
||||
el.groupIds = [...(el.groupIds || []), structuralGroupId];
|
||||
}
|
||||
});
|
||||
}
|
||||
await addElementsToView({ captureUpdate: "IMMEDIATELY" });
|
||||
} else {
|
||||
@@ -4990,6 +5047,11 @@ const addNode = async (text, follow = false, skipFinalLayout = false, batchModeA
|
||||
width: imageInfo.width,
|
||||
depth
|
||||
});
|
||||
// Attach the URL to the element's link so we can trace it back
|
||||
if (imageInfo.isExternalImage && newNodeId) {
|
||||
const el = ea.getElement(newNodeId);
|
||||
if (el && !el.link) el.link = imageInfo.path;
|
||||
}
|
||||
} else if (imageInfo?.imageFile) {
|
||||
newNodeId = await addImage({
|
||||
pathOrFile: imageInfo.imageFile,
|
||||
@@ -5144,6 +5206,11 @@ const addNode = async (text, follow = false, skipFinalLayout = false, batchModeA
|
||||
y: py,
|
||||
depth
|
||||
});
|
||||
// Attach the URL to the element's link so we can trace it back
|
||||
if (imageInfo.isExternalImage && newNodeId) {
|
||||
const el = ea.getElement(newNodeId);
|
||||
if (el && !el.link) el.link = imageInfo.path;
|
||||
}
|
||||
} else if (imageInfo?.imageFile) {
|
||||
newNodeId = await addImage({
|
||||
pathOrFile: imageInfo.imageFile,
|
||||
@@ -5410,16 +5477,24 @@ const getTextFromNode = (all, node, getRaw = false, shortPath = false) => {
|
||||
if (node.type === "image") {
|
||||
const embeddedFile = ea.targetView?.excalidrawData?.getFile(node.fileId);
|
||||
if (!embeddedFile) return "";
|
||||
|
||||
const file = ea.getViewFileForImageElement(node);
|
||||
|
||||
// Handle external image URLs or local file URIs saved in node.link
|
||||
if (!file && node.link && node.link.match(/^(https?|file):\/\//i)) {
|
||||
return ``;
|
||||
}
|
||||
|
||||
if (shortPath) {
|
||||
const originalPath = embeddedFile.linkParts?.original;
|
||||
return `![[${originalPath}|${Math.round(node.width)}]]`;
|
||||
}
|
||||
const file = ea.getViewFileForImageElement(node);
|
||||
|
||||
if (file) {
|
||||
if (file.extension === "pdf" && node.link?.startsWith("[[")) {
|
||||
return `!${node.link.match(/^(.*?)\]\]/)[1]}|${Math.round(node.width)}]]`;
|
||||
}
|
||||
return `![[${file.path}${embeddedFile.filenameparts?.linkpartReference}|${Math.round(node.width)}]]`;
|
||||
return `![[${file.path}${embeddedFile.filenameparts?.linkpartReference || ""}|${Math.round(node.width)}]]`;
|
||||
}
|
||||
return "";
|
||||
}
|
||||
@@ -6735,18 +6810,21 @@ const changeNodeOrder = async (key) => {
|
||||
|
||||
// Gather all elements in branch + decorations
|
||||
const branchIds = getBranchElementIds(current.id, allElements);
|
||||
|
||||
// Use the specialized function to get decorations and crosslinks
|
||||
// to safely ignore structural groups that might encompass the entire map
|
||||
const decorationAndCrossLinkIds = getDecorationAndCrossLinkIdsForBranches(branchIds, allElements, info.rootId);
|
||||
|
||||
const elementsToMove = new Set();
|
||||
|
||||
branchIds.forEach(id => {
|
||||
const el = allElements.find(x => x.id === id);
|
||||
if (el) {
|
||||
elementsToMove.add(el);
|
||||
// Include attached decorations (grouped elements)
|
||||
if (el.groupIds && el.groupIds.length > 0) {
|
||||
const groupEls = ea.getElementsInTheSameGroupWithElement(el, allElements);
|
||||
groupEls.forEach(gEl => elementsToMove.add(gEl));
|
||||
}
|
||||
}
|
||||
if (el) elementsToMove.add(el);
|
||||
});
|
||||
|
||||
decorationAndCrossLinkIds.forEach(id => {
|
||||
const el = allElements.find(x => x.id === id);
|
||||
if (el) elementsToMove.add(el);
|
||||
});
|
||||
|
||||
const arr = Array.from(elementsToMove);
|
||||
@@ -7627,7 +7705,11 @@ const toggleBox = async (shape = "rectangle") => {
|
||||
const container = allElements.find((el) => el.id === containerId);
|
||||
ea.copyViewElementsToEAforEditing(arrowsToUpdate.concat(sel, container));
|
||||
const textEl = ea.getElement(sel.id);
|
||||
ea.addAppendUpdateCustomData(textEl.id, { isPinned: !!container.customData?.isPinned, mindmapOrder: container.customData?.mindmapOrder });
|
||||
|
||||
// Transfer all custom data from the container back to the text element
|
||||
const dataToCopy = { ...(container.customData || {}) };
|
||||
ea.addAppendUpdateCustomData(textEl.id, dataToCopy);
|
||||
|
||||
textEl.containerId = null;
|
||||
textEl.boundElements =[]; //not null because I will add bound arrows a bit further down
|
||||
ea.getElement(containerId).isDeleted = true;
|
||||
@@ -7648,7 +7730,11 @@ const toggleBox = async (shape = "rectangle") => {
|
||||
|
||||
finalElId = newBindId = rectId;
|
||||
const rect = ea.getElement(rectId);
|
||||
ea.addAppendUpdateCustomData(rectId, { isPinned: !!sel.customData?.isPinned, mindmapOrder: sel.customData?.mindmapOrder });
|
||||
|
||||
// Transfer all custom data from the text element to the new container
|
||||
const dataToCopy = { ...(sel.customData || {}) };
|
||||
ea.addAppendUpdateCustomData(rectId, dataToCopy);
|
||||
|
||||
rect.strokeColor = ea.getCM(sel.strokeColor).stringRGB();
|
||||
rect.strokeWidth = getStrokeWidthForDepth(depth);
|
||||
rect.roughness = getAppState().currentItemRoughness;
|
||||
@@ -8252,6 +8338,11 @@ const commitEdit = async () => {
|
||||
width: imageInfo.width,
|
||||
depth,
|
||||
});
|
||||
// Check for external image flag and append to link to preserve routing
|
||||
if (imageInfo.isExternalImage && newNodeId) {
|
||||
const el = ea.getElement(newNodeId);
|
||||
if (el && !el.link) el.link = imageInfo.path;
|
||||
}
|
||||
} else {
|
||||
newNodeId = await addImage({
|
||||
pathOrFile: imageInfo.imageFile,
|
||||
@@ -8968,7 +9059,7 @@ const renderInput = (container, isFloating = false) => {
|
||||
inputRow.controlEl.style.width = "100%";
|
||||
inputRow.controlEl.style.marginTop = "8px";
|
||||
} else {
|
||||
container.style.width = "70vw";
|
||||
container.style.width = "85vw";
|
||||
container.style.maxWidth = "calc((var(--icon-size) + 2 * var(--size-2-3)) * 17)";
|
||||
inputRow.settingEl.style.border = "none";
|
||||
inputRow.settingEl.style.padding = "0";
|
||||
@@ -9892,6 +9983,7 @@ const registerStyles = () => {
|
||||
" overflow: hidden;",
|
||||
" scrollbar-width: none;",
|
||||
"}",
|
||||
".excalidraw-mindmap-ui .modal-header-button {display: none;}",
|
||||
// Focus styles
|
||||
".excalidraw-mindmap-ui button:focus,",
|
||||
".excalidraw-mindmap-ui .clickable-icon:focus,",
|
||||
@@ -9988,9 +10080,11 @@ const toggleDock = async ({silent=false, forceDock=false, saveSetting=false} = {
|
||||
if (isUndocked) {
|
||||
// UNDOCK: Initialize floating modal
|
||||
floatingInputModal = new ea.FloatingModal(ea.plugin.app);
|
||||
const { contentEl, titleEl, modalEl, headerEl } = floatingInputModal;
|
||||
const { contentEl, titleEl, modalEl, headerEl, bgEl } = floatingInputModal;
|
||||
modalEl.classList.add("excalidraw-mindmap-ui");
|
||||
|
||||
if (bgEl) {
|
||||
bgEl.style.display="none";
|
||||
}
|
||||
floatingInputModal.onOpen = () => {
|
||||
// Reparent modal to target view window
|
||||
if (ea.targetView && modalEl.ownerDocument !== ea.targetView.ownerDocument) {
|
||||
@@ -10017,9 +10111,13 @@ const toggleDock = async ({silent=false, forceDock=false, saveSetting=false} = {
|
||||
//otherwise the event handlers in FloatingModal would override the move
|
||||
//leaving modalEl in the center of the view
|
||||
//modalEl.style.top and left must stay in the timeout call
|
||||
modalEl.style.top = `${ y + FLOAT_MODAL_OFFSET }px`;
|
||||
const {x, y} = ea.targetView.contentEl.getBoundingClientRect();
|
||||
const desktopShift = !!ea.targetView.contentEl.querySelector(".App-bottom-bar .App-toolbar")
|
||||
? 0
|
||||
: (ea.targetView.contentEl.clientWidth < 1200 ? 36 : 0);
|
||||
modalEl.style.top = `${ y + FLOAT_MODAL_OFFSET + desktopShift}px`;
|
||||
modalEl.style.left = `${ x + FLOAT_MODAL_OFFSET }px`;
|
||||
}, 100);
|
||||
}, ea.DEVICE.isMobile ? 400:150);
|
||||
};
|
||||
|
||||
floatingInputModal.onClose = () => {
|
||||
|
||||
+363
-357
File diff suppressed because it is too large.
Load diff
+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
|
||||
|
||||
+3
-3
@@ -1,9 +1,9 @@
|
||||
{
|
||||
"id": "obsidian-excalidraw-plugin",
|
||||
"name": "Excalidraw",
|
||||
"version": "2.22.0-beta-1",
|
||||
"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-beta-4",
|
||||
"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.21.2",
|
||||
"version": "2.22.3",
|
||||
"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
+7
-6
@@ -11,7 +11,7 @@
|
||||
"dependencies": {
|
||||
"@popperjs/core": "^2.11.8",
|
||||
"@zsviczian/colormaster": "^1.2.2",
|
||||
"@zsviczian/excalidraw": "0.18.0-87",
|
||||
"@zsviczian/excalidraw": "0.18.0-90",
|
||||
"chroma-js": "^3.1.2",
|
||||
"clsx": "^2.0.0",
|
||||
"es6-promise-pool": "2.5.0",
|
||||
@@ -47,7 +47,7 @@
|
||||
"@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": "20.19.37",
|
||||
"@types/opentype.js": "^1.3.8",
|
||||
"@types/react": "^18.2.45",
|
||||
"@types/react-dom": "^18.2.18",
|
||||
@@ -70,7 +70,7 @@
|
||||
"rollup-plugin-typescript2": "^0.36.0",
|
||||
"tslib": "^2.8.1",
|
||||
"ttypescript": "^1.5.15",
|
||||
"typescript": "^5.7.3",
|
||||
"typescript": "5.9.3",
|
||||
"uglify-js": "^3.19.3"
|
||||
},
|
||||
"engines": {
|
||||
@@ -4769,9 +4769,10 @@
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@zsviczian/excalidraw": {
|
||||
"version": "0.18.0-87",
|
||||
"resolved": "https://registry.npmjs.org/@zsviczian/excalidraw/-/excalidraw-0.18.0-87.tgz",
|
||||
"integrity": "sha512-ljjsp6KJtsKz5tZs3IbXb0mI4b0fvPfLwjaXBP8HAH+qRKkarL7fDxloKAsdoIHEbtyhUGOjfaMN1OaxiSyVQQ==",
|
||||
"version": "0.18.0-90",
|
||||
"resolved": "https://registry.npmjs.org/@zsviczian/excalidraw/-/excalidraw-0.18.0-90.tgz",
|
||||
"integrity": "sha512-3AX0J4wk3b0LiXjd6k6TQha/wibsDkEKoqRJfX06Itz6WQY9jlBg1q7tHnpF5VmdbcrP7SlRZRuk21sdpqhVMA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@braintree/sanitize-url": "6.0.2",
|
||||
"@codemirror/commands": "^6.0.0",
|
||||
|
||||
+3
-3
@@ -25,7 +25,7 @@
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@popperjs/core": "^2.11.8",
|
||||
"@zsviczian/excalidraw": "0.18.0-87",
|
||||
"@zsviczian/excalidraw": "0.18.0-91",
|
||||
"chroma-js": "^3.1.2",
|
||||
"clsx": "^2.0.0",
|
||||
"@zsviczian/colormaster": "^1.2.2",
|
||||
@@ -63,7 +63,7 @@
|
||||
"@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": "20.19.37",
|
||||
"@types/opentype.js": "^1.3.8",
|
||||
"@types/react": "^18.2.45",
|
||||
"@types/react-dom": "^18.2.18",
|
||||
@@ -84,7 +84,7 @@
|
||||
"rollup-plugin-typescript2": "^0.36.0",
|
||||
"tslib": "^2.8.1",
|
||||
"ttypescript": "^1.5.15",
|
||||
"typescript": "^5.7.3",
|
||||
"typescript": "5.9.3",
|
||||
"fs-extra": "^11.2.0",
|
||||
"uglify-js": "^3.19.3"
|
||||
},
|
||||
|
||||
+139
-2
@@ -49,7 +49,12 @@ const jsxRuntimeShim = `
|
||||
|
||||
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
|
||||
// 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(";")) {
|
||||
@@ -77,12 +82,144 @@ function minifyCode(code) {
|
||||
return minified.code;
|
||||
}
|
||||
|
||||
// Build-time placeholders that are resolved at runtime in src/lang/helpers.ts.
|
||||
// Keep names stable and keep this map 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__",
|
||||
DEVTOOLS_SHORTCUT: "__EXD_DEVTOOLS_SHORTCUT__",
|
||||
};
|
||||
|
||||
function replaceDesktopConditionalBlocks(input, deviceTokens) {
|
||||
// Preserve desktop-only message fragments for runtime decision.
|
||||
const start = "${DEVICE.isDesktop ? `";
|
||||
const end = "` : \"\"}";
|
||||
let output = "";
|
||||
let cursor = 0;
|
||||
|
||||
while (true) {
|
||||
const startIndex = input.indexOf(start, cursor);
|
||||
if (startIndex === -1) {
|
||||
output += input.slice(cursor);
|
||||
break;
|
||||
}
|
||||
|
||||
const contentStart = startIndex + start.length;
|
||||
const endIndex = input.indexOf(end, contentStart);
|
||||
if (endIndex === -1) {
|
||||
output += input.slice(cursor);
|
||||
break;
|
||||
}
|
||||
|
||||
output += input.slice(cursor, startIndex);
|
||||
output += `${deviceTokens.IF_DESKTOP_START}${input.slice(contentStart, endIndex)}${deviceTokens.IF_DESKTOP_END}`;
|
||||
cursor = endIndex + end.length;
|
||||
}
|
||||
|
||||
return output;
|
||||
}
|
||||
|
||||
function replaceAppleTernaryBlocks(input, deviceTokens) {
|
||||
// Preserve Apple vs non-Apple branch text for runtime decision.
|
||||
const start = "(DEVICE.isIOS || DEVICE.isMacOS ? \"";
|
||||
const separator = "\" : \"";
|
||||
const end = "\")";
|
||||
let output = "";
|
||||
let cursor = 0;
|
||||
|
||||
while (true) {
|
||||
const startIndex = input.indexOf(start, cursor);
|
||||
if (startIndex === -1) {
|
||||
output += input.slice(cursor);
|
||||
break;
|
||||
}
|
||||
|
||||
const trueStart = startIndex + start.length;
|
||||
const separatorIndex = input.indexOf(separator, trueStart);
|
||||
if (separatorIndex === -1) {
|
||||
output += input.slice(cursor);
|
||||
break;
|
||||
}
|
||||
|
||||
const falseStart = separatorIndex + separator.length;
|
||||
const endIndex = input.indexOf(end, falseStart);
|
||||
if (endIndex === -1) {
|
||||
output += input.slice(cursor);
|
||||
break;
|
||||
}
|
||||
|
||||
const trueValue = input.slice(trueStart, separatorIndex);
|
||||
const falseValue = input.slice(falseStart, endIndex);
|
||||
|
||||
output += input.slice(cursor, startIndex);
|
||||
output += `"${deviceTokens.IF_APPLE_START}${trueValue}${deviceTokens.IF_APPLE_ELSE}${falseValue}${deviceTokens.IF_APPLE_END}"`;
|
||||
cursor = endIndex + end.length;
|
||||
}
|
||||
|
||||
return output;
|
||||
}
|
||||
|
||||
function tokenizeLocaleContent(content, deviceTokens = DEVICE_TOKEN_VALUES) {
|
||||
let tokenized = content;
|
||||
|
||||
tokenized = replaceDesktopConditionalBlocks(tokenized, deviceTokens);
|
||||
tokenized = replaceAppleTernaryBlocks(tokenized, deviceTokens);
|
||||
|
||||
// Add new replacements here when locale files introduce new dynamic snippets.
|
||||
// Any new token emitted here must be handled in src/lang/helpers.ts.
|
||||
const replacements = [
|
||||
[/\$\{\s*labelALT\(\)\s*\}/g, "__EXD_LABEL_ALT__"],
|
||||
[/\$\{\s*labelCTRL\(\)\s*\}/g, "__EXD_LABEL_CTRL__"],
|
||||
[/\$\{\s*labelMETA\(\)\s*\}/g, "__EXD_LABEL_META__"],
|
||||
[/\$\{\s*labelSHIFT\(\)\s*\}/g, "__EXD_LABEL_SHIFT__"],
|
||||
[/\blabelALT\(\)/g, '"__EXD_LABEL_ALT__"'],
|
||||
[/\blabelCTRL\(\)/g, '"__EXD_LABEL_CTRL__"'],
|
||||
[/\blabelMETA\(\)/g, '"__EXD_LABEL_META__"'],
|
||||
[/\blabelSHIFT\(\)/g, '"__EXD_LABEL_SHIFT__"'],
|
||||
[/\$\{\s*FRONTMATTER_KEYS\["link-brackets"\]\.name\s*\}/g, "__EXD_FRONTMATTER_LINK_BRACKETS__"],
|
||||
[/\$\{\s*FRONTMATTER_KEYS\["link-prefix"\]\.name\s*\}/g, "__EXD_FRONTMATTER_LINK_PREFIX__"],
|
||||
[/\$\{\s*FRONTMATTER_KEYS\["url-prefix"\]\.name\s*\}/g, "__EXD_FRONTMATTER_URL_PREFIX__"],
|
||||
[/\$\{\s*CJK_FONTS\s*\}/g, "__EXD_CJK_FONTS__"],
|
||||
[/\$\{\s*PLUGIN_VERSION\s*\}/g, "__EXD_PLUGIN_VERSION__"],
|
||||
["${DEVICE.isIOS || DEVICE.isMacOS ? \"CMD+OPT+i\" : \"CTRL+SHIFT+i\"}", deviceTokens.DEVTOOLS_SHORTCUT],
|
||||
["${DEVICE.isMacOS ? \"CMD+OPT+i\" : \"CTRL+SHIFT+i\"}", deviceTokens.DEVTOOLS_SHORTCUT],
|
||||
];
|
||||
|
||||
for (const [pattern, replacement] of replacements) {
|
||||
if (typeof pattern === "string") {
|
||||
tokenized = tokenized.split(pattern).join(replacement);
|
||||
} else {
|
||||
tokenized = tokenized.replace(pattern, replacement);
|
||||
}
|
||||
}
|
||||
|
||||
return tokenized;
|
||||
}
|
||||
|
||||
function serializeLocaleToJson(content) {
|
||||
const assignmentCode = minifyCode(`x = ${content};`);
|
||||
const locale = new Function(`
|
||||
const TAG_AUTOEXPORT = "Autoexport";
|
||||
const TAG_MDREADINGMODE = "MDReadingMode";
|
||||
const TAG_PDFEXPORT = "PDFExport";
|
||||
let x = {};
|
||||
${assignmentCode};
|
||||
return x;
|
||||
`)();
|
||||
return JSON.stringify(locale);
|
||||
}
|
||||
|
||||
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 tokenizedContent = tokenizeLocaleContent(content);
|
||||
const localeJson = serializeLocaleToJson(tokenizedContent);
|
||||
return LZString.compressToBase64(localeJson);
|
||||
}
|
||||
|
||||
const excalidraw_pkg = isLib ? "" : minifyCode(isProd
|
||||
|
||||
@@ -31,6 +31,7 @@ export const getIconAsJSX = (iconId: string) => {
|
||||
|
||||
export const ICONS = {
|
||||
ExportImage: getIconAsJSX("image-down"),
|
||||
Info: getIconAsJSX("info"),
|
||||
BackOfNote: getIconAsJSX("text-select"),
|
||||
Reload: getIconAsJSX("rotate-ccw"),
|
||||
Copy: getIconAsJSX("copy"),
|
||||
@@ -55,21 +56,6 @@ export const ICONS = {
|
||||
</svg>
|
||||
),
|
||||
Learn: getIconAsJSX("graduation-cap"),
|
||||
Discord: (
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
fill="var(--icon-fill-color)"
|
||||
stroke="none"
|
||||
strokeWidth="2"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
viewBox="0 0 640 512"
|
||||
>
|
||||
<path
|
||||
d="M524.531,69.836a1.5,1.5,0,0,0-.764-.7A485.065,485.065,0,0,0,404.081,32.03a1.816,1.816,0,0,0-1.923.91,337.461,337.461,0,0,0-14.9,30.6,447.848,447.848,0,0,0-134.426,0,309.541,309.541,0,0,0-15.135-30.6,1.89,1.89,0,0,0-1.924-.91A483.689,483.689,0,0,0,116.085,69.137a1.712,1.712,0,0,0-.788.676C39.068,183.651,18.186,294.69,28.43,404.354a2.016,2.016,0,0,0,.765,1.375A487.666,487.666,0,0,0,176.02,479.918a1.9,1.9,0,0,0,2.063-.676A348.2,348.2,0,0,0,208.12,430.4a1.86,1.86,0,0,0-1.019-2.588,321.173,321.173,0,0,1-45.868-21.853,1.885,1.885,0,0,1-.185-3.126c3.082-2.309,6.166-4.711,9.109-7.137a1.819,1.819,0,0,1,1.9-.256c96.229,43.917,200.41,43.917,295.5,0a1.812,1.812,0,0,1,1.924.233c2.944,2.426,6.027,4.851,9.132,7.16a1.884,1.884,0,0,1-.162,3.126,301.407,301.407,0,0,1-45.89,21.83,1.875,1.875,0,0,0-1,2.611,391.055,391.055,0,0,0,30.014,48.815,1.864,1.864,0,0,0,2.063.7A486.048,486.048,0,0,0,610.7,405.729a1.882,1.882,0,0,0,.765-1.352C623.729,277.594,590.933,167.465,524.531,69.836ZM222.491,337.58c-28.972,0-52.844-26.587-52.844-59.239S193.056,219.1,222.491,219.1c29.665,0,53.306,26.82,52.843,59.239C275.334,310.993,251.924,337.58,222.491,337.58Zm195.38,0c-28.971,0-52.843-26.587-52.843-59.239S388.437,219.1,417.871,219.1c29.667,0,53.307,26.82,52.844,59.239C470.715,310.993,447.538,337.58,417.871,337.58Z"
|
||||
/>
|
||||
</svg>
|
||||
),
|
||||
Github: getIconAsJSX("github"),
|
||||
YouTube: getIconAsJSX("youtube"),
|
||||
heart: getIconAsJSX("heart"),
|
||||
|
||||
@@ -169,8 +169,8 @@ 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);
|
||||
|
||||
@@ -194,7 +194,7 @@ export function setRootElementSize(size?:number) {
|
||||
}
|
||||
const tempElement = document.createElement('div');
|
||||
tempElement.style.fontSize = '1rem';
|
||||
tempElement.style.display = 'none'; // Hide the element
|
||||
tempElement.hidden = true;
|
||||
document.body.appendChild(tempElement);
|
||||
const computedStyle = getComputedStyle(tempElement);
|
||||
const pixelSize = parseFloat(computedStyle.fontSize);
|
||||
@@ -515,3 +515,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
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,7 +1,6 @@
|
||||
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}= {
|
||||
@@ -12,7 +11,6 @@ export class EditorHandler {
|
||||
private activeEditorExtensions: Extension[] = [];
|
||||
|
||||
constructor(private plugin: ExcalidrawPlugin) {
|
||||
(process.env.NODE_ENV === 'development') && DEBUGGING && debug(EditorHandler, `ExcalidrawPlugin.construct EditorHandler`);
|
||||
}
|
||||
|
||||
destroy(): void {
|
||||
@@ -20,7 +18,6 @@ export class EditorHandler {
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
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"} });
|
||||
|
||||
+3
-1
@@ -1,10 +1,12 @@
|
||||
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 { 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) {
|
||||
|
||||
+398
-84
@@ -1,88 +1,94 @@
|
||||
import {
|
||||
TFile,
|
||||
Plugin,
|
||||
WorkspaceLeaf,
|
||||
addIcon,
|
||||
App,
|
||||
PluginManifest,
|
||||
MarkdownView,
|
||||
normalizePath,
|
||||
ViewState,
|
||||
Notice,
|
||||
request,
|
||||
MetadataCache,
|
||||
Workspace,
|
||||
TAbstractFile,
|
||||
FrontMatterCache,
|
||||
TFile,
|
||||
Plugin,
|
||||
WorkspaceLeaf,
|
||||
addIcon,
|
||||
App,
|
||||
PluginManifest,
|
||||
MarkdownView,
|
||||
normalizePath,
|
||||
ViewState,
|
||||
Notice,
|
||||
request,
|
||||
MetadataCache,
|
||||
Workspace,
|
||||
TAbstractFile,
|
||||
FrontMatterCache,
|
||||
} from "obsidian";
|
||||
import {
|
||||
VIEW_TYPE_EXCALIDRAW,
|
||||
VIEW_TYPE_SIDEPANEL,
|
||||
EXCALIDRAW_ICON,
|
||||
ICON_NAME,
|
||||
SCRIPTENGINE_ICON,
|
||||
SCRIPTENGINE_ICON_NAME,
|
||||
RERENDER_EVENT,
|
||||
FRONTMATTER_KEYS,
|
||||
FRONTMATTER,
|
||||
JSON_parse,
|
||||
SCRIPT_INSTALL_CODEBLOCK,
|
||||
SCRIPT_INSTALL_FOLDER,
|
||||
EXPORT_TYPES,
|
||||
EXPORT_IMG_ICON_NAME,
|
||||
EXPORT_IMG_ICON,
|
||||
LOCALE,
|
||||
setExcalidrawPlugin,
|
||||
DEVICE,
|
||||
FONTS_STYLE_ID,
|
||||
CJK_STYLE_ID,
|
||||
loadMermaid,
|
||||
setRootElementSize,
|
||||
VIEW_TYPE_EXCALIDRAW,
|
||||
VIEW_TYPE_SIDEPANEL,
|
||||
EXCALIDRAW_ICON,
|
||||
ICON_NAME,
|
||||
SCRIPTENGINE_ICON,
|
||||
SCRIPTENGINE_ICON_NAME,
|
||||
RERENDER_EVENT,
|
||||
FRONTMATTER_KEYS,
|
||||
FRONTMATTER,
|
||||
JSON_parse,
|
||||
SCRIPT_INSTALL_CODEBLOCK,
|
||||
SCRIPT_INSTALL_FOLDER,
|
||||
EXPORT_TYPES,
|
||||
EXPORT_IMG_ICON_NAME,
|
||||
EXPORT_IMG_ICON,
|
||||
LOCALE,
|
||||
setExcalidrawPlugin,
|
||||
DEVICE,
|
||||
FONTS_STYLE_ID,
|
||||
CJK_STYLE_ID,
|
||||
loadMermaid,
|
||||
setRootElementSize,
|
||||
} from "../constants/constants";
|
||||
import { ExcalidrawSettings, DEFAULT_SETTINGS, ExcalidrawSettingTab } from "./settings";
|
||||
import {
|
||||
ExcalidrawSettings,
|
||||
DEFAULT_SETTINGS,
|
||||
ExcalidrawSettingTab,
|
||||
cloneKnownAIProviderProfiles,
|
||||
cloneModelConfigs,
|
||||
KNOWN_AI_TEXT_MODEL_CONFIGS,
|
||||
KNOWN_AI_IMAGE_MODEL_CONFIGS,
|
||||
} from "./settings";
|
||||
import { ExcalidrawAutomate } from "../shared/ExcalidrawAutomate";
|
||||
import { initExcalidrawAutomate, insertLaTeXToView } from "src/utils/excalidrawAutomateUtils";
|
||||
import { around, dedupe } from "monkey-around";
|
||||
import { initExcalidrawAutomate,insertLaTeXToView } from "src/utils/excalidrawAutomateUtils";
|
||||
import { around,dedupe } from "monkey-around";
|
||||
import { t } from "../lang/helpers";
|
||||
import {
|
||||
createOrOverwriteFile,
|
||||
fileShouldDefaultAsExcalidraw,
|
||||
getDrawingFilename,
|
||||
getIMGFilename,
|
||||
getNewUniqueFilepath,
|
||||
createOrOverwriteFile,
|
||||
fileShouldDefaultAsExcalidraw,
|
||||
getDrawingFilename,
|
||||
getIMGFilename,
|
||||
getNewUniqueFilepath,
|
||||
} from "../utils/fileUtils";
|
||||
import {
|
||||
getFontDataURL,
|
||||
errorlog,
|
||||
setLeftHandedMode,
|
||||
sleep,
|
||||
isVersionNewerThanOther,
|
||||
isCallerFromTemplaterPlugin,
|
||||
versionUpdateCheckTimer,
|
||||
getFontMetrics,
|
||||
calculateUIModeValue,
|
||||
getFontDataURL,
|
||||
errorlog,sleep,
|
||||
isVersionNewerThanOther,
|
||||
isCallerFromTemplaterPlugin,
|
||||
versionUpdateCheckTimer,
|
||||
getFontMetrics,
|
||||
calculateUIModeValue
|
||||
} from "../utils/utils";
|
||||
import { foldExcalidrawSection, getExcalidrawViews, setExcalidrawView } from "../utils/obsidianUtils";
|
||||
import { foldExcalidrawSection,getExcalidrawViews,setExcalidrawView } from "../utils/obsidianUtils";
|
||||
import { FileId } from "@zsviczian/excalidraw/types/element/src/types";
|
||||
import { ScriptEngine } from "../shared/Scripts";
|
||||
import { hoverEvent, initializeMarkdownPostProcessor, markdownPostProcessor, legacyExcalidrawPopoverObserver } from "./managers/MarkdownPostProcessor";
|
||||
import { hoverEvent,initializeMarkdownPostProcessor,markdownPostProcessor,legacyExcalidrawPopoverObserver } from "./managers/MarkdownPostProcessor";
|
||||
import { FieldSuggester } from "../shared/Suggesters/FieldSuggester";
|
||||
import { ReleaseNotes } from "../shared/Dialogs/ReleaseNotes";
|
||||
import { DeviceType, Packages } from "../types/types";
|
||||
import { DeviceType,Packages } from "../types/types";
|
||||
import { PreviewImageType } from "../types/utilTypes";
|
||||
import { emulateCTRLClickForLinks, linkClickModifierType, PaneTarget } from "../utils/modifierkeyHelper";
|
||||
import { emulateCTRLClickForLinks,linkClickModifierType,PaneTarget } from "../utils/modifierkeyHelper";
|
||||
import { imageCache } from "../shared/ImageCache";
|
||||
import { StylesManager } from "./managers/StylesManager";
|
||||
import { CustomMutationObserver, debug, log, DEBUGGING, setDebugging, ts } from "../utils/debugHelper";
|
||||
import { CustomMutationObserver,log,setDebugging } from "../utils/debugHelper";
|
||||
import { ExcalidrawConfig } from "../shared/ExcalidrawConfig";
|
||||
import { EditorHandler } from "./editor/EditorHandler";
|
||||
import { ExcalidrawLib } from "../types/excalidrawLib";
|
||||
import { Rank, SwordColors } from "../constants/actionIcons";
|
||||
import { Rank,SwordColors } from "../constants/actionIcons";
|
||||
import { RankMessage } from "../shared/Dialogs/RankMessage";
|
||||
import { initCompressionWorker, terminateCompressionWorker } from "../shared/Workers/compression-worker";
|
||||
import { initCompressionWorker,terminateCompressionWorker } from "../shared/Workers/compression-worker";
|
||||
import { WeakArray } from "../shared/WeakArray";
|
||||
import { getCJKDataURLs } from "../utils/CJKLoader";
|
||||
import { ExcalidrawLoading, switchToExcalidraw } from "../view/ExcalidrawLoading";
|
||||
import { ExcalidrawLoading,switchToExcalidraw } from "../view/ExcalidrawLoading";
|
||||
import { clearMathJaxVariables } from "../shared/LaTeX";
|
||||
import { PluginFileManager } from "./managers/FileManager";
|
||||
import { ObserverManager } from "./managers/ObserverManager";
|
||||
@@ -93,11 +99,11 @@ import { CommandManager } from "./managers/CommandManager";
|
||||
import { EventManager } from "./managers/EventManager";
|
||||
import { UniversalInsertFileModal } from "src/shared/Dialogs/UniversalInsertFileModal";
|
||||
import en from "src/lang/locale/en";
|
||||
import { get } from "http";
|
||||
import { getHighlightColor } from "src/utils/dynamicStyling";
|
||||
import { InlineLinkSuggester } from "src/shared/Suggesters/InlineLinkSuggester";
|
||||
import { KeyBlocker } from "src/types/excalidrawAutomateTypes";
|
||||
import { UIMode } from "src/shared/Dialogs/UIModeSettingComponent";
|
||||
import { decryptPersistedAPIKeys,encryptPersistedAPIKeys } from "src/utils/settingsKeyObfuscation";
|
||||
|
||||
declare const PLUGIN_VERSION:string;
|
||||
declare const INITIAL_TIMESTAMP: number;
|
||||
@@ -111,6 +117,280 @@ type FileMasterInfo = {
|
||||
colorMapJSON?: string
|
||||
}
|
||||
|
||||
const PHONE_FOOTER_SAFE_AREA_STYLE_ID = "excalidraw-phone-footer-safe-area";
|
||||
const PHONE_FOOTER_SAFE_AREA_CSS = `
|
||||
.excalidraw .App-bottom-bar {
|
||||
padding-bottom: 50px;
|
||||
}
|
||||
`;
|
||||
|
||||
type PersistedExcalidrawSettings = Partial<ExcalidrawSettings> & Record<string, unknown>;
|
||||
|
||||
const LEGACY_AI_SETTING_KEYS: (keyof ExcalidrawSettings)[] = [
|
||||
"aiDefaultMaxTokens",
|
||||
"aiDefaultMultimodalModel",
|
||||
"aiDefaultVisionModel",
|
||||
"aiProvider",
|
||||
"aiAPIKey",
|
||||
"aiBaseURL",
|
||||
"aiTextEndpoint",
|
||||
"aiImageGenerationEndpoint",
|
||||
"aiImageEditsEndpoint",
|
||||
"aiImageVariationsEndpoint",
|
||||
"aiImageModelCapabilities",
|
||||
"aiVisionModelConfigs",
|
||||
"openAIAPIToken",
|
||||
"openAIDefaultTextModel",
|
||||
"openAIDefaultTextModelMaxTokens",
|
||||
"openAIDefaultVisionModel",
|
||||
"openAIDefaultImageGenerationModel",
|
||||
"openAIURL",
|
||||
"openAIImageGenerationURL",
|
||||
"openAIImageEditsURL",
|
||||
"openAIImageVariationURL",
|
||||
];
|
||||
|
||||
const AI_TEXT_SUFFIX = "/chat/completions";
|
||||
|
||||
const normalizeAISettingURL = (value: unknown): string => {
|
||||
return typeof value === "string"
|
||||
? value.trim().replace(/\/+$/, "")
|
||||
: "";
|
||||
};
|
||||
|
||||
const joinAISettingURL = (baseURL: string, path: string): string => {
|
||||
if (!baseURL) return "";
|
||||
return `${baseURL.replace(/\/+$/, "")}/${path.replace(/^\/+/, "")}`;
|
||||
};
|
||||
|
||||
const hasNonEmptyString = (value: unknown): value is string => {
|
||||
return typeof value === "string" && value.trim() !== "";
|
||||
};
|
||||
|
||||
const hasPositiveNumber = (value: unknown): value is number => {
|
||||
return typeof value === "number" && value > 0;
|
||||
};
|
||||
|
||||
const LEGACY_PROVIDER_LABELS: Record<string, string> = {
|
||||
openai: "OpenAI",
|
||||
anthropic: "Anthropic",
|
||||
google: "Google Gemini",
|
||||
xai: "xAI",
|
||||
"openai-compatible": "OpenAI-compatible",
|
||||
};
|
||||
|
||||
const stripLegacyAISettings = <T extends PersistedExcalidrawSettings>(settings: T): T => {
|
||||
const sanitized = { ...settings };
|
||||
LEGACY_AI_SETTING_KEYS.forEach((key) => {
|
||||
delete sanitized[key];
|
||||
});
|
||||
return sanitized;
|
||||
};
|
||||
|
||||
const migrateLegacyAISettings = (
|
||||
settings: PersistedExcalidrawSettings,
|
||||
): { settings: PersistedExcalidrawSettings; didMigrate: boolean } => {
|
||||
const migrated = { ...settings };
|
||||
const migratedRecord = migrated as Record<string, unknown>;
|
||||
let didMigrate = false;
|
||||
|
||||
const assignStringIfMissing = (key: keyof ExcalidrawSettings, value: unknown) => {
|
||||
if (!hasNonEmptyString(value) || hasNonEmptyString(migrated[key])) return;
|
||||
migratedRecord[key] = value.trim();
|
||||
didMigrate = true;
|
||||
};
|
||||
|
||||
const assignPositiveNumberIfMissing = (key: keyof ExcalidrawSettings, value: unknown) => {
|
||||
if (!hasPositiveNumber(value) || hasPositiveNumber(migrated[key])) return;
|
||||
migratedRecord[key] = value;
|
||||
didMigrate = true;
|
||||
};
|
||||
|
||||
assignStringIfMissing("aiAPIKey", settings.openAIAPIToken);
|
||||
assignStringIfMissing("aiDefaultMultimodalModel", settings.aiDefaultVisionModel);
|
||||
assignStringIfMissing("aiDefaultMultimodalModel", settings.openAIDefaultVisionModel);
|
||||
assignStringIfMissing("aiDefaultTextModel", settings.openAIDefaultTextModel);
|
||||
assignStringIfMissing("aiDefaultTextModel", settings.aiDefaultVisionModel);
|
||||
assignStringIfMissing("aiDefaultTextModel", settings.openAIDefaultVisionModel);
|
||||
assignStringIfMissing("aiDefaultImageGenerationModel", settings.openAIDefaultImageGenerationModel);
|
||||
assignPositiveNumberIfMissing("aiDefaultMaxResponseTokens", settings.aiDefaultMaxTokens);
|
||||
assignPositiveNumberIfMissing("aiDefaultMaxResponseTokens", settings.openAIDefaultTextModelMaxTokens);
|
||||
|
||||
const legacyTextEndpoint = normalizeAISettingURL(settings.openAIURL);
|
||||
const inferredLegacyBaseURL = legacyTextEndpoint.endsWith(AI_TEXT_SUFFIX)
|
||||
? legacyTextEndpoint.slice(0, -AI_TEXT_SUFFIX.length)
|
||||
: legacyTextEndpoint;
|
||||
|
||||
assignStringIfMissing("aiBaseURL", inferredLegacyBaseURL);
|
||||
|
||||
const effectiveBaseURL = normalizeAISettingURL(migrated.aiBaseURL) || inferredLegacyBaseURL;
|
||||
const derivedTextEndpoint = joinAISettingURL(effectiveBaseURL, AI_TEXT_SUFFIX);
|
||||
|
||||
if (
|
||||
hasNonEmptyString(legacyTextEndpoint)
|
||||
&& !hasNonEmptyString(migrated.aiTextEndpoint)
|
||||
&& legacyTextEndpoint !== derivedTextEndpoint
|
||||
) {
|
||||
migrated.aiTextEndpoint = legacyTextEndpoint;
|
||||
didMigrate = true;
|
||||
}
|
||||
|
||||
const assignEndpointOverrideIfNeeded = (
|
||||
key: keyof ExcalidrawSettings,
|
||||
legacyValue: unknown,
|
||||
suffix: string,
|
||||
) => {
|
||||
const normalizedLegacyValue = normalizeAISettingURL(legacyValue);
|
||||
if (!normalizedLegacyValue || hasNonEmptyString(migrated[key])) return;
|
||||
|
||||
const derivedEndpoint = joinAISettingURL(effectiveBaseURL, suffix);
|
||||
if (!derivedEndpoint || normalizedLegacyValue !== derivedEndpoint) {
|
||||
migratedRecord[key] = normalizedLegacyValue;
|
||||
didMigrate = true;
|
||||
}
|
||||
};
|
||||
|
||||
assignEndpointOverrideIfNeeded("aiImageGenerationEndpoint", settings.openAIImageGenerationURL, "/images/generations");
|
||||
assignEndpointOverrideIfNeeded("aiImageEditsEndpoint", settings.openAIImageEditsURL, "/images/edits");
|
||||
assignEndpointOverrideIfNeeded("aiImageVariationsEndpoint", settings.openAIImageVariationURL, "/images/variations");
|
||||
|
||||
const hadProviderProfiles = Boolean(migrated.aiProviderProfiles && Object.keys(migrated.aiProviderProfiles).length > 0);
|
||||
const hadTextModelConfigs = Boolean(migrated.aiTextModelConfigs && Object.keys(migrated.aiTextModelConfigs).length > 0);
|
||||
const hadVisionModelConfigs = Boolean(migrated.aiVisionModelConfigs && Object.keys(migrated.aiVisionModelConfigs).length > 0);
|
||||
const hadImageModelConfigs = Boolean(migrated.aiImageModelConfigs && Object.keys(migrated.aiImageModelConfigs).length > 0);
|
||||
|
||||
const ensureProviderProfiles = () => {
|
||||
if (migrated.aiProviderProfiles && Object.keys(migrated.aiProviderProfiles).length > 0) {
|
||||
return migrated.aiProviderProfiles;
|
||||
}
|
||||
migrated.aiProviderProfiles = cloneKnownAIProviderProfiles();
|
||||
didMigrate = true;
|
||||
return migrated.aiProviderProfiles;
|
||||
};
|
||||
|
||||
const ensureModelConfigs = (kind: "text" | "vision" | "image") => {
|
||||
if (kind === "text" && migrated.aiTextModelConfigs && Object.keys(migrated.aiTextModelConfigs).length > 0) return migrated.aiTextModelConfigs;
|
||||
if (kind === "image" && migrated.aiImageModelConfigs && Object.keys(migrated.aiImageModelConfigs).length > 0) return migrated.aiImageModelConfigs;
|
||||
|
||||
const defaults = kind === "text"
|
||||
? cloneModelConfigs(KNOWN_AI_TEXT_MODEL_CONFIGS)
|
||||
: cloneModelConfigs(KNOWN_AI_IMAGE_MODEL_CONFIGS);
|
||||
|
||||
if (kind === "text") migrated.aiTextModelConfigs = defaults;
|
||||
if (kind === "image") migrated.aiImageModelConfigs = defaults as typeof migrated.aiImageModelConfigs;
|
||||
didMigrate = true;
|
||||
return defaults;
|
||||
};
|
||||
|
||||
const providerProfiles = ensureProviderProfiles();
|
||||
const legacyProviderType = (migrated.aiProvider ?? "openai") as ExcalidrawSettings["aiProvider"];
|
||||
const providerProfileId = LEGACY_PROVIDER_LABELS[legacyProviderType] ?? "OpenAI";
|
||||
if (!hadProviderProfiles) {
|
||||
providerProfiles[providerProfileId] = {
|
||||
provider: legacyProviderType,
|
||||
apiKey: migrated.aiAPIKey ?? "",
|
||||
baseURL: normalizeAISettingURL(migrated.aiBaseURL) || providerProfiles[providerProfileId]?.baseURL || "",
|
||||
};
|
||||
didMigrate = true;
|
||||
}
|
||||
|
||||
const textModelId = (migrated.aiDefaultTextModel || settings.aiDefaultVisionModel || settings.openAIDefaultTextModel || settings.openAIDefaultVisionModel || "gpt-5-mini").trim();
|
||||
const multimodalTextModelId = (migrated.aiDefaultMultimodalModel || settings.aiDefaultVisionModel || settings.openAIDefaultVisionModel || textModelId).trim();
|
||||
const imageModelId = (migrated.aiDefaultImageGenerationModel || settings.openAIDefaultImageGenerationModel || "gpt-image-1").trim();
|
||||
const legacyCapabilities = settings.aiImageModelCapabilities as Record<string, {
|
||||
supportedSizes?: string[];
|
||||
supportsPromptImageTransforms?: boolean;
|
||||
supportsMaskImageEdits?: boolean;
|
||||
supportsImageEdits?: boolean;
|
||||
}> | undefined;
|
||||
|
||||
const textModels = ensureModelConfigs("text");
|
||||
if (!hadTextModelConfigs) {
|
||||
textModels[textModelId] = {
|
||||
providerId: providerProfileId,
|
||||
model: textModelId,
|
||||
endpoint: migrated.aiTextEndpoint ?? "",
|
||||
multimodalSupport: true,
|
||||
};
|
||||
}
|
||||
|
||||
if (hadVisionModelConfigs && migrated.aiVisionModelConfigs) {
|
||||
Object.entries(migrated.aiVisionModelConfigs).forEach(([modelId, config]) => {
|
||||
const existingConfig = textModels[modelId];
|
||||
if (!existingConfig) {
|
||||
textModels[modelId] = {
|
||||
...config,
|
||||
multimodalSupport: config.multimodalSupport ?? true,
|
||||
};
|
||||
didMigrate = true;
|
||||
return;
|
||||
}
|
||||
|
||||
if (existingConfig.multimodalSupport === undefined) {
|
||||
existingConfig.multimodalSupport = config.multimodalSupport ?? true;
|
||||
didMigrate = true;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
Object.values(textModels).forEach((config) => {
|
||||
if (config.multimodalSupport === undefined) {
|
||||
config.multimodalSupport = true;
|
||||
didMigrate = true;
|
||||
}
|
||||
});
|
||||
|
||||
const imageModels = ensureModelConfigs("image") as Record<string, typeof KNOWN_AI_IMAGE_MODEL_CONFIGS[string]>;
|
||||
if (!hadImageModelConfigs) {
|
||||
const legacySupportsImageEdits = legacyCapabilities?.[imageModelId]?.supportsImageEdits;
|
||||
imageModels[imageModelId] = {
|
||||
providerId: providerProfileId,
|
||||
model: imageModelId,
|
||||
supportedSizes: [...(legacyCapabilities?.[imageModelId]?.supportedSizes?.length
|
||||
? legacyCapabilities[imageModelId].supportedSizes
|
||||
: imageModels[imageModelId]?.supportedSizes ?? ["1024x1024"])],
|
||||
supportsPromptImageTransforms: legacyCapabilities?.[imageModelId]?.supportsPromptImageTransforms ?? imageModels[imageModelId]?.supportsPromptImageTransforms ?? legacySupportsImageEdits ?? true,
|
||||
supportsMaskImageEdits: legacyCapabilities?.[imageModelId]?.supportsMaskImageEdits ?? imageModels[imageModelId]?.supportsMaskImageEdits ?? legacySupportsImageEdits ?? true,
|
||||
};
|
||||
}
|
||||
|
||||
Object.entries(imageModels).forEach(([modelId, config]) => {
|
||||
const legacyConfig = config as typeof config & { supportsImageEdits?: boolean };
|
||||
const legacySupportsImageEdits = legacyCapabilities?.[modelId]?.supportsImageEdits ?? legacyConfig.supportsImageEdits;
|
||||
const nextConfig = {
|
||||
...config,
|
||||
supportsPromptImageTransforms: config.supportsPromptImageTransforms ?? legacyCapabilities?.[modelId]?.supportsPromptImageTransforms ?? legacySupportsImageEdits ?? true,
|
||||
supportsMaskImageEdits: config.supportsMaskImageEdits ?? legacyCapabilities?.[modelId]?.supportsMaskImageEdits ?? legacySupportsImageEdits ?? true,
|
||||
};
|
||||
|
||||
if (
|
||||
nextConfig.supportsPromptImageTransforms !== config.supportsPromptImageTransforms
|
||||
|| nextConfig.supportsMaskImageEdits !== config.supportsMaskImageEdits
|
||||
|| legacyConfig.supportsImageEdits !== undefined
|
||||
) {
|
||||
imageModels[modelId] = nextConfig;
|
||||
delete (imageModels[modelId] as typeof nextConfig & { supportsImageEdits?: boolean }).supportsImageEdits;
|
||||
didMigrate = true;
|
||||
}
|
||||
});
|
||||
|
||||
if (!migrated.aiDefaultTextModel) migrated.aiDefaultTextModel = textModelId;
|
||||
if (!migrated.aiDefaultMultimodalModel) migrated.aiDefaultMultimodalModel = multimodalTextModelId;
|
||||
if (!migrated.aiDefaultImageGenerationModel) migrated.aiDefaultImageGenerationModel = imageModelId;
|
||||
|
||||
if (migrated.aiDefaultVisionModel !== undefined) {
|
||||
delete migratedRecord.aiDefaultVisionModel;
|
||||
didMigrate = true;
|
||||
}
|
||||
|
||||
if (migrated.aiVisionModelConfigs !== undefined) {
|
||||
delete migratedRecord.aiVisionModelConfigs;
|
||||
didMigrate = true;
|
||||
}
|
||||
|
||||
return { settings: migrated, didMigrate };
|
||||
};
|
||||
|
||||
export default class ExcalidrawPlugin extends Plugin {
|
||||
private fileManager: PluginFileManager;
|
||||
private observerManager: ObserverManager;
|
||||
@@ -153,6 +433,7 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
public wasPenModeActivePreviously: boolean = false;
|
||||
public popScope: Function = null;
|
||||
public lastPDFLeafID: string = null;
|
||||
public forceExcalidrawViewMode: boolean = false;
|
||||
|
||||
constructor(app: App, manifest: PluginManifest) {
|
||||
super(app, manifest);
|
||||
@@ -401,6 +682,8 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
}
|
||||
this.logStartupEvent("Styles manager initialized");
|
||||
|
||||
this.updatePhoneFooterSafeAreaPadding();
|
||||
|
||||
try {
|
||||
this.scriptEngine = new ScriptEngine(this);
|
||||
} catch (e) {
|
||||
@@ -527,7 +810,6 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
private async setPropertyTypes() {
|
||||
if(!this.settings.loadPropertySuggestions) return;
|
||||
const app = this.app;
|
||||
(process.env.NODE_ENV === 'development') && DEBUGGING && debug(this.setPropertyTypes, `ExcalidrawPlugin.setPropertyTypes`);
|
||||
Object.keys(FRONTMATTER_KEYS).forEach((key) => {
|
||||
if(FRONTMATTER_KEYS[key].depricated === true) return;
|
||||
const {name, type} = FRONTMATTER_KEYS[key];
|
||||
@@ -536,7 +818,6 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
}
|
||||
|
||||
public async initializeFonts() {
|
||||
(process.env.NODE_ENV === 'development') && DEBUGGING && debug(this.initializeFonts, `ExcalidrawPlugin.initializeFonts`);
|
||||
const cjkFontDataURLs = await getCJKDataURLs(this);
|
||||
if(typeof cjkFontDataURLs === "boolean" && !cjkFontDataURLs) {
|
||||
new Notice(t("FONTS_LOAD_ERROR") + this.settings.fontAssetsPath,6000);
|
||||
@@ -589,7 +870,7 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
`@font-face{font-family:'Local Font';src:url("${fourthFontDataURL}");font-display: swap;font-weight: 400;`,
|
||||
], ownerDocument);
|
||||
};
|
||||
if(!this.fourthFontLoaded) setTimeout(()=>{this.fourthFontLoaded = true},100);
|
||||
if(!this.fourthFontLoaded) window.setTimeout(()=>{this.fourthFontLoaded = true},100);
|
||||
}
|
||||
|
||||
public async addFonts(declarations: string[],ownerDocument:Document = document, styleId:string = FONTS_STYLE_ID) {
|
||||
@@ -617,9 +898,43 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public updatePhoneFooterSafeAreaPadding() {
|
||||
const documents = new Set<Document>([document, ...this.getOpenObsidianDocuments()]);
|
||||
const shouldEnable = DEVICE.isPhone && this.settings?.phoneFooterSafeAreaPadding;
|
||||
|
||||
documents.forEach((ownerDocument) => {
|
||||
const existingStylesheet = ownerDocument.getElementById(PHONE_FOOTER_SAFE_AREA_STYLE_ID);
|
||||
if (!shouldEnable) {
|
||||
if (existingStylesheet) {
|
||||
ownerDocument.head.removeChild(existingStylesheet);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (existingStylesheet instanceof HTMLStyleElement) {
|
||||
existingStylesheet.textContent = PHONE_FOOTER_SAFE_AREA_CSS;
|
||||
return;
|
||||
}
|
||||
|
||||
const stylesheet = ownerDocument.createElement("style");
|
||||
stylesheet.id = PHONE_FOOTER_SAFE_AREA_STYLE_ID;
|
||||
stylesheet.textContent = PHONE_FOOTER_SAFE_AREA_CSS;
|
||||
ownerDocument.head.appendChild(stylesheet);
|
||||
});
|
||||
}
|
||||
|
||||
private removePhoneFooterSafeAreaPadding() {
|
||||
const documents = new Set<Document>([document, ...this.getOpenObsidianDocuments()]);
|
||||
documents.forEach((ownerDocument) => {
|
||||
const existingStylesheet = ownerDocument.getElementById(PHONE_FOOTER_SAFE_AREA_STYLE_ID);
|
||||
if (existingStylesheet) {
|
||||
ownerDocument.head.removeChild(existingStylesheet);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private getOpenObsidianDocuments(): Document[] {
|
||||
(process.env.NODE_ENV === 'development') && DEBUGGING && debug(this.getOpenObsidianDocuments,`ExcalidrawPlugin.getOpenObsidianDocuments`);
|
||||
const visitedDocs = new Set<Document>();
|
||||
this.app.workspace.iterateAllLeaves((leaf)=>{
|
||||
const ownerDocument = DEVICE.isMobile?document:leaf.view.containerEl.ownerDocument;
|
||||
@@ -634,7 +949,6 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
* Must be called after the workspace is ready
|
||||
*/
|
||||
private switchToExcalidrawAfterLoad() {
|
||||
(process.env.NODE_ENV === 'development') && DEBUGGING && debug(this.switchToExcalidrawAfterLoad, `ExcalidrawPlugin.switchToExcalidrawAfterLoad`);
|
||||
let leaf: WorkspaceLeaf;
|
||||
for (leaf of this.app.workspace.getLeavesOfType("markdown")) {
|
||||
if ( leaf.view instanceof MarkdownView && this.isExcalidrawFile(leaf.view.file)) {
|
||||
@@ -880,7 +1194,6 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
this.registerMarkdownPostProcessor(markdownPostProcessor);
|
||||
|
||||
this.app.workspace.onLayoutReady(async () => {
|
||||
(process.env.NODE_ENV === 'development') && DEBUGGING && debug(this.addMarkdownPostProcessor, `ExcalidrawPlugin.addMarkdownPostProcessor > app.workspace.onLayoutReady`);
|
||||
await this.awaitInit();
|
||||
// internal-link quick preview
|
||||
this.registerEvent(this.app.workspace.on("hover-link", hoverEvent));
|
||||
@@ -894,7 +1207,6 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
|
||||
public enableLegacyFilePopoverObserver() {
|
||||
if(!this.legacyExcalidrawPopoverObserver) {
|
||||
(process.env.NODE_ENV === 'development') && DEBUGGING && debug(this.enableLegacyFilePopoverObserver, `ExcalidrawPlugin.enableLegacyFilePopoverObserver > enabling`)
|
||||
//monitoring for div.popover.hover-popover.file-embed.is-loaded to be added to the DOM tree
|
||||
this.legacyExcalidrawPopoverObserver = legacyExcalidrawPopoverObserver;
|
||||
this.legacyExcalidrawPopoverObserver.observe(document.body, { childList: true, subtree: false });
|
||||
@@ -967,7 +1279,6 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
around(Workspace.prototype, {
|
||||
getActiveViewOfType(old) {
|
||||
return dedupe(key, old, function(...args) {
|
||||
(process.env.NODE_ENV === 'development') && DEBUGGING && debug(this.registerMonkeyPatches, `ExcalidrawPlugin.MonkeyPatch >getActiveViewOfType`, key, old, ...args);
|
||||
const result = old && old.apply(this, args);
|
||||
const maybeEAView = self.app?.workspace?.activeLeaf?.view;
|
||||
if(!maybeEAView || !(maybeEAView instanceof ExcalidrawView)) return result;
|
||||
@@ -1020,7 +1331,6 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
|
||||
setViewState(next) {
|
||||
return function (state: ViewState, ...rest: any[]) {
|
||||
(process.env.NODE_ENV === 'development') && DEBUGGING && debug(this.registerMonkeyPatches, `ExcalidrawPlugin.MonkeyPatch > setViewState`, next);
|
||||
const markdownViewLoaded =
|
||||
self._loaded && // Don't force excalidraw mode during shutdown
|
||||
state.type === "markdown" && // If we have a markdown file
|
||||
@@ -1047,7 +1357,7 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
|
||||
if(markdownViewLoaded) {
|
||||
const leaf = this;
|
||||
setTimeout(async ()=> {
|
||||
window.setTimeout(async ()=> {
|
||||
if(!leaf || !leaf.view || !(leaf.view instanceof MarkdownView) ||
|
||||
!leaf.view.file || !self.isExcalidrawFile(leaf.view.file)
|
||||
) return;
|
||||
@@ -1068,7 +1378,6 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
* @returns
|
||||
*/
|
||||
private async runStartupScript() {
|
||||
(process.env.NODE_ENV === 'development') && DEBUGGING && debug(this.runStartupScript, `ExcalidrawPlugin.runStartupScript`);
|
||||
if(!this.settings.startupScriptPath || this.settings.startupScriptPath === "") {
|
||||
return;
|
||||
}
|
||||
@@ -1167,7 +1476,6 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
* Intended to be called from onLayoutReady in onload()
|
||||
*/
|
||||
private async registerEventListeners() {
|
||||
(process.env.NODE_ENV === 'development') && DEBUGGING && debug(this.registerEventListeners,`ExcalidrawPlugin.registerEventListeners`);
|
||||
await this.awaitInit();
|
||||
|
||||
const metaCache: MetadataCache = this.app.metadataCache;
|
||||
@@ -1209,6 +1517,7 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
this.stylesManager = null;
|
||||
|
||||
this.removeFonts();
|
||||
this.removePhoneFooterSafeAreaPadding();
|
||||
|
||||
this.eaInstances.forEach((ea) => ea?.destroy());
|
||||
this.eaInstances.clear();
|
||||
@@ -1262,9 +1571,12 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
|
||||
public async loadSettings(opts: { reEnableAutosave?: boolean } = { reEnableAutosave: false }
|
||||
) {
|
||||
(process.env.NODE_ENV === 'development') && DEBUGGING && debug(this.loadSettings,`ExcalidrawPlugin.loadSettings`, opts);
|
||||
if(typeof opts.reEnableAutosave === "undefined") opts.reEnableAutosave = false;
|
||||
this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData());
|
||||
const rawSettings = ((await this.loadData()) ?? {}) as PersistedExcalidrawSettings;
|
||||
const { settings: migratedSettings, didMigrate } = migrateLegacyAISettings(rawSettings);
|
||||
const persistedSettings = stripLegacyAISettings(migratedSettings);
|
||||
const decryptedSettings = decryptPersistedAPIKeys(persistedSettings);
|
||||
this.settings = Object.assign({}, DEFAULT_SETTINGS, decryptedSettings);
|
||||
if(!this.settings.previewImageType) { //migration 1.9.13
|
||||
if(typeof this.settings.displaySVGInPreview === "undefined") {
|
||||
this.settings.previewImageType = PreviewImageType.SVGIMG;
|
||||
@@ -1274,21 +1586,25 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
: PreviewImageType.PNG;
|
||||
}
|
||||
}
|
||||
const encryptedPersistedSettings = encryptPersistedAPIKeys(stripLegacyAISettings(this.settings as PersistedExcalidrawSettings));
|
||||
const shouldPersistEncryptedSettings = JSON.stringify(encryptedPersistedSettings) !== JSON.stringify(persistedSettings);
|
||||
if (didMigrate || shouldPersistEncryptedSettings) {
|
||||
await this.saveData(encryptedPersistedSettings);
|
||||
}
|
||||
if(opts.reEnableAutosave) this.settings.autosave = true;
|
||||
setDebugging(this.settings.isDebugMode);
|
||||
}
|
||||
|
||||
async saveSettings() {
|
||||
(process.env.NODE_ENV === 'development') && DEBUGGING && debug(this.saveSettings,`ExcalidrawPlugin.saveSettings`);
|
||||
await this.saveData(this.settings);
|
||||
const persistedSettings = stripLegacyAISettings(this.settings as PersistedExcalidrawSettings);
|
||||
await this.saveData(encryptPersistedAPIKeys(persistedSettings));
|
||||
}
|
||||
|
||||
public async openSidepanel(reveal: boolean = true): Promise<ExcalidrawSidepanelView | null> {
|
||||
return ExcalidrawSidepanelView.getOrCreate(this, reveal);
|
||||
}
|
||||
|
||||
public getStencilLibrary(): {} {
|
||||
(process.env.NODE_ENV === 'development') && DEBUGGING && debug(this.getStencilLibrary,`ExcalidrawPlugin.getStencilLibrary`);
|
||||
public getStencilLibrary(): object {
|
||||
if (
|
||||
this.settings.library === "" ||
|
||||
this.settings.library === "deprecated"
|
||||
@@ -1298,8 +1614,7 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
return JSON_parse(this.settings.library);
|
||||
}
|
||||
|
||||
public async setStencilLibrary(library: {}) {
|
||||
(process.env.NODE_ENV === 'development') && DEBUGGING && debug(this.setStencilLibrary,`ExcalidrawPlugin.setStencilLibrary`, library);
|
||||
public async setStencilLibrary(library: object) {
|
||||
this.settings.library = "deprecated";
|
||||
if(JSON.stringify(this.settings.library2) === JSON.stringify(library)) {
|
||||
return;
|
||||
@@ -1309,7 +1624,6 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
}
|
||||
|
||||
public triggerEmbedUpdates(filepath?: string) {
|
||||
(process.env.NODE_ENV === 'development') && DEBUGGING && debug(this.triggerEmbedUpdates,`ExcalidrawPlugin.triggerEmbedUpdates`, filepath);
|
||||
const visitedDocs = new Set<Document>();
|
||||
this.app.workspace.getLeavesOfType("markdown").forEach((leaf) => {
|
||||
// this.app.workspace.iterateAllLeaves((leaf)=>{
|
||||
|
||||
@@ -1,64 +1,65 @@
|
||||
import {
|
||||
TFile,
|
||||
App,
|
||||
MarkdownView,
|
||||
normalizePath,
|
||||
Menu,
|
||||
MenuItem,
|
||||
Notice,
|
||||
Command,
|
||||
EventRef,
|
||||
FileView,
|
||||
TFile,
|
||||
App,
|
||||
MarkdownView,
|
||||
normalizePath,
|
||||
Menu,
|
||||
MenuItem,
|
||||
Notice,
|
||||
Command,
|
||||
EventRef,
|
||||
FileView,
|
||||
} from "obsidian";
|
||||
import {
|
||||
VIEW_TYPE_EXCALIDRAW,
|
||||
ICON_NAME,
|
||||
IMAGE_TYPES,
|
||||
DEVICE,
|
||||
sceneCoordsToViewportCoords,
|
||||
fileid,
|
||||
VIEW_TYPE_EXCALIDRAW,
|
||||
ICON_NAME,
|
||||
IMAGE_TYPES,
|
||||
DEVICE,
|
||||
CaptureUpdateAction,
|
||||
sceneCoordsToViewportCoords,
|
||||
fileid,
|
||||
} from "../../constants/constants";
|
||||
import ExcalidrawView from "../../view/ExcalidrawView";
|
||||
import { TextMode } from "../../shared/TextMode";
|
||||
import {
|
||||
REGEX_LINK,
|
||||
REGEX_LINK,
|
||||
} from "../../shared/ExcalidrawData";
|
||||
import { ExcalidrawSettings } from "../settings";
|
||||
import { openDialogAction, OpenFileDialog } from "../../shared/Dialogs/OpenDrawing";
|
||||
import { openDialogAction,OpenFileDialog } from "../../shared/Dialogs/OpenDrawing";
|
||||
import { InsertLinkDialog } from "../../shared/Dialogs/InsertLinkDialog";
|
||||
import { InsertCommandDialog } from "../../shared/Dialogs/InsertCommandDialog";
|
||||
import { InsertImageDialog } from "../../shared/Dialogs/InsertImageDialog";
|
||||
import { ImportSVGDialog } from "../../shared/Dialogs/ImportSVGDialog";
|
||||
import { InsertMDDialog } from "../../shared/Dialogs/InsertMDDialog";
|
||||
import { ExcalidrawAutomate } from "../../shared/ExcalidrawAutomate";
|
||||
import { insertLaTeXToView, search } from "src/utils/excalidrawAutomateUtils";
|
||||
import { insertLaTeXToView,search } from "src/utils/excalidrawAutomateUtils";
|
||||
import { templatePromt } from "../../shared/Dialogs/Prompt";
|
||||
import { t } from "../../lang/helpers";
|
||||
import {
|
||||
createOrOverwriteFile,
|
||||
getAliasWithSize,
|
||||
getAnnotationFileNameAndFolder,
|
||||
getCropFileNameAndFolder,
|
||||
getDrawingFilename,
|
||||
getEmbedFilename,
|
||||
getIMGFilename,
|
||||
getLink,
|
||||
getListOfTemplateFiles,
|
||||
getURLImageExtension,
|
||||
createOrOverwriteFile,
|
||||
getAliasWithSize,
|
||||
getAnnotationFileNameAndFolder,
|
||||
getCropFileNameAndFolder,
|
||||
getDrawingFilename,
|
||||
getEmbedFilename,
|
||||
getIMGFilename,
|
||||
getLink,
|
||||
getListOfTemplateFiles,
|
||||
getURLImageExtension,
|
||||
} from "../../utils/fileUtils";
|
||||
import {
|
||||
setLeftHandedMode,
|
||||
sleep,
|
||||
decompress,
|
||||
getImageSize,
|
||||
setLeftHandedMode,
|
||||
sleep,
|
||||
decompress,
|
||||
getImageSize,
|
||||
} from "../../utils/utils";
|
||||
import { extractSVGPNGFileName, getActivePDFPageNumberFromPDFView, isObsidianThemeDark, mergeMarkdownFiles, setExcalidrawView } from "../../utils/obsidianUtils";
|
||||
import { extractSVGPNGFileName,getActivePDFPageNumberFromPDFView,getExcalidrawViews,isObsidianThemeDark,mergeMarkdownFiles,setExcalidrawView } from "../../utils/obsidianUtils";
|
||||
import { getAttachmentsFolderAndFilePath } from "../../utils/pathUtils";
|
||||
import { ExcalidrawElement, ExcalidrawEmbeddableElement, ExcalidrawImageElement, ExcalidrawTextElement, FileId } from "@zsviczian/excalidraw/types/element/src/types";
|
||||
import { ExcalidrawElement,ExcalidrawEmbeddableElement,ExcalidrawImageElement,ExcalidrawTextElement,FileId } from "@zsviczian/excalidraw/types/element/src/types";
|
||||
import { ReleaseNotes } from "../../shared/Dialogs/ReleaseNotes";
|
||||
import { ScriptInstallPrompt } from "../../shared/Dialogs/ScriptInstallPrompt";
|
||||
import Taskbone from "../../shared/OCR/Taskbone";
|
||||
import { emulateCTRLClickForLinks, linkClickModifierType, PaneTarget } from "../../utils/modifierkeyHelper";
|
||||
import { emulateCTRLClickForLinks,linkClickModifierType,PaneTarget } from "../../utils/modifierkeyHelper";
|
||||
import { InsertPDFModal } from "../../shared/Dialogs/InsertPDFModal";
|
||||
import { ExportDialog } from "../../shared/Dialogs/ExportDialog";
|
||||
import { UniversalInsertFileModal } from "../../shared/Dialogs/UniversalInsertFileModal";
|
||||
@@ -68,7 +69,7 @@ import { processLinkText } from "../../utils/customEmbeddableUtils";
|
||||
import { getEA } from "src/core";
|
||||
import { ExcalidrawImperativeAPI } from "@zsviczian/excalidraw/types/excalidraw/types";
|
||||
import { Mutable } from "@zsviczian/excalidraw/types/common/src/utility-types";
|
||||
import { carveOutImage, carveOutPDF, createImageCropperFile } from "../../utils/carveout";
|
||||
import { carveOutImage,carveOutPDF,createImageCropperFile } from "../../utils/carveout";
|
||||
import { showFrameSettings } from "../../shared/Dialogs/FrameSettings";
|
||||
import { insertImageToView } from "../../utils/excalidrawViewUtils";
|
||||
import ExcalidrawPlugin from "src/core/main";
|
||||
@@ -105,6 +106,19 @@ export class CommandManager {
|
||||
this.plugin = plugin;
|
||||
}
|
||||
|
||||
private setAllExcalidrawViewsToViewMode(enabled: boolean) {
|
||||
getExcalidrawViews(this.app, true).forEach((view) => {
|
||||
view.updateScene({
|
||||
appState: {
|
||||
viewModeEnabled: enabled,
|
||||
zenModeEnabled: enabled ? false : view.excalidrawAPI?.getAppState()?.zenModeEnabled,
|
||||
},
|
||||
captureUpdate: CaptureUpdateAction.NEVER,
|
||||
});
|
||||
view.toolsPanelRef?.current?.setExcalidrawViewMode(enabled);
|
||||
});
|
||||
}
|
||||
|
||||
public initialize() {
|
||||
try {
|
||||
this.taskbone = new Taskbone(this.plugin);
|
||||
@@ -324,7 +338,7 @@ export class CommandManager {
|
||||
}
|
||||
if(checking) return true;
|
||||
const ea = getEA(view) as ExcalidrawAutomate;
|
||||
const api = ea.getExcalidrawAPI() as ExcalidrawImperativeAPI;
|
||||
const api = ea.getExcalidrawAPI();
|
||||
ea.copyViewElementsToEAforEditing(els);
|
||||
const scale = 1/api.getAppState().zoom.value;
|
||||
ea.getElements().forEach((el: Mutable<ExcalidrawEmbeddableElement>)=>{
|
||||
@@ -396,6 +410,17 @@ export class CommandManager {
|
||||
}
|
||||
})
|
||||
|
||||
this.addCommand({
|
||||
id: "excalidraw-toggle-session-view-mode",
|
||||
name: t("TEMPORARY_TOGGLE_VIEW_MODE_FOR_ALL_DRAWINGS"),
|
||||
checkCallback: (checking) => {
|
||||
if (checking) return true;
|
||||
this.plugin.forceExcalidrawViewMode = !this.plugin.forceExcalidrawViewMode;
|
||||
this.setAllExcalidrawViewsToViewMode(this.plugin.forceExcalidrawViewMode);
|
||||
return true;
|
||||
}
|
||||
})
|
||||
|
||||
this.addCommand({
|
||||
id: "excalidraw-download-lib",
|
||||
name: t("DOWNLOAD_LIBRARY"),
|
||||
@@ -1001,7 +1026,7 @@ export class CommandManager {
|
||||
if(DEVICE.isMobile) return false;
|
||||
if(this.app.workspace.getActiveViewOfType(ExcalidrawView)) {
|
||||
const view = this.app.workspace.getActiveViewOfType(ExcalidrawView);
|
||||
const api = view?.excalidrawAPI as ExcalidrawImperativeAPI;
|
||||
const api = view?.excalidrawAPI;
|
||||
if(!api || !api.isTrayModeEnabled()) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -1,11 +1,10 @@
|
||||
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";
|
||||
@@ -120,7 +119,7 @@ export class EventManager {
|
||||
|
||||
private onLayoutChangeHandler() {
|
||||
if (this.app.workspace.layoutReady) {
|
||||
getExcalidrawViews(this.app).forEach(excalidrawView=>!!excalidrawView?.refresh && excalidrawView.refresh());
|
||||
getExcalidrawViews(this.app, true).forEach(excalidrawView=>!!excalidrawView?.refresh && excalidrawView.refresh());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -142,12 +141,15 @@ export class EventManager {
|
||||
if (element.type === "image") {
|
||||
const fileinfo = this.plugin.filesMaster.get(element.fileId);
|
||||
if(fileinfo && fileinfo.path) {
|
||||
let path = 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 (fileinfo.blockrefData) {
|
||||
path = `${path}#${fileinfo.blockrefData.split("|")[0]}`; // strip size anchoring (e.g. |100%)
|
||||
}
|
||||
editorInsertText(editor, getLink(this.plugin, {path}));
|
||||
}
|
||||
return;
|
||||
@@ -178,7 +180,6 @@ export class EventManager {
|
||||
}
|
||||
|
||||
public async onActiveLeafChangeHandler (leaf: WorkspaceLeaf) {
|
||||
(process.env.NODE_ENV === 'development') && DEBUGGING && debug(this.onActiveLeafChangeHandler,`onActiveLeafChangeEventHandler`, leaf);
|
||||
//https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/723
|
||||
|
||||
if(this.debunceActiveLeafChangeHandlerTimer) {
|
||||
@@ -262,7 +263,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;
|
||||
}
|
||||
@@ -314,7 +315,6 @@ export class EventManager {
|
||||
}
|
||||
|
||||
private onFileMenuSaveActiveDrawing () {
|
||||
(process.env.NODE_ENV === 'development') && DEBUGGING && debug(this.onFileMenuSaveActiveDrawing,`onFileMenuSaveActiveDrawing`);
|
||||
if (
|
||||
!this.activeExcalidrawView ||
|
||||
!this.activeExcalidrawView?.isDirty()
|
||||
@@ -325,7 +325,6 @@ export class EventManager {
|
||||
};
|
||||
|
||||
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;
|
||||
|
||||
@@ -1,16 +1,14 @@
|
||||
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 { Prompt, templatePromt } from "src/shared/Dialogs/Prompt";
|
||||
import { changeThemeOfExcalidrawMD, ExcalidrawData, getMarkdownDrawingSection } from "../../shared/ExcalidrawData";
|
||||
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 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 { errorlog, getExportTheme } from "src/utils/utils";
|
||||
import { getExcalidrawViews,getNewOrAdjacentLeaf,isObsidianThemeDark,openLeaf } from "src/utils/obsidianUtils";
|
||||
import { errorlog,getExportTheme } from "src/utils/utils";
|
||||
import { imageCache } from "src/shared/ImageCache";
|
||||
|
||||
export class PluginFileManager {
|
||||
@@ -365,9 +363,19 @@ export class PluginFileManager {
|
||||
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;
|
||||
@@ -405,13 +413,17 @@ export class PluginFileManager {
|
||||
* @returns
|
||||
*/
|
||||
public async renameEventHandler (file: TAbstractFile, oldPath: string) {
|
||||
(process.env.NODE_ENV === 'development') && DEBUGGING && debug(this.renameEventHandler, `ExcalidrawPlugin.renameEventHandler`, file, oldPath);
|
||||
if (!(file instanceof TFile)) {
|
||||
return;
|
||||
}
|
||||
if (!this.isExcalidrawFile(file)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.app.workspace.activeLeaf?.view instanceof ExcalidrawView && this.app.workspace.activeLeaf.view.file === file) {
|
||||
this.plugin.lastActiveExcalidrawFilePath = file.path;
|
||||
}
|
||||
|
||||
this.moveBAKFile(oldPath, file.path);
|
||||
|
||||
if (!this.settings.keepInSync) {
|
||||
@@ -454,7 +466,6 @@ export class PluginFileManager {
|
||||
}
|
||||
|
||||
public async modifyEventHandler (file: TFile) {
|
||||
(process.env.NODE_ENV === 'development') && DEBUGGING && debug(this.modifyEventHandler,`FileManager.modifyEventHandler`, file);
|
||||
const excalidrawViews = getExcalidrawViews(this.app);
|
||||
excalidrawViews.forEach(async (excalidrawView) => {
|
||||
if(excalidrawView.semaphores?.viewunload) {
|
||||
@@ -558,7 +569,6 @@ export class PluginFileManager {
|
||||
* @returns
|
||||
*/
|
||||
public async deleteEventHandler (file: TFile) {
|
||||
(process.env.NODE_ENV === 'development') && DEBUGGING && debug(this.deleteEventHandler,`ExcalidrawPlugin.deleteEventHandler`, file);
|
||||
if (!(file instanceof TFile)) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1,35 +1,36 @@
|
||||
import {
|
||||
App,
|
||||
MarkdownPostProcessorContext,
|
||||
MetadataCache,
|
||||
PaneType,
|
||||
TFile,
|
||||
Vault,
|
||||
App,
|
||||
MarkdownPostProcessorContext,
|
||||
MetadataCache,
|
||||
PaneType,
|
||||
TFile,
|
||||
Vault,
|
||||
} from "obsidian";
|
||||
import { DEVICE, RERENDER_EVENT } from "../../constants/constants";
|
||||
import { DEVICE,RERENDER_EVENT } from "../../constants/constants";
|
||||
import { EmbeddedFilesLoader } from "../../shared/EmbeddedFileLoader";
|
||||
import { createPNG, createSVG } from "../../utils/excalidrawAutomateUtils";
|
||||
import { createPNG,createSVG } from "../../utils/excalidrawAutomateUtils";
|
||||
import ExcalidrawPlugin from "../main";
|
||||
import {getIMGFilename,} from "../../utils/fileUtils";
|
||||
import { getIMGFilename,} from "../../utils/fileUtils";
|
||||
import {
|
||||
getEmbeddedFilenameParts,
|
||||
getExportTheme,
|
||||
getQuickImagePreview,
|
||||
getExportPadding,
|
||||
getWithBackground,
|
||||
hasExportTheme,
|
||||
convertSVGStringToElement,
|
||||
isMaskFile,
|
||||
getEmbeddedFilenameParts,
|
||||
getExportTheme,
|
||||
getQuickImagePreview,
|
||||
getExportPadding,
|
||||
getWithBackground,
|
||||
hasExportTheme,
|
||||
convertSVGStringToElement,
|
||||
isMaskFile,
|
||||
} from "../../utils/utils";
|
||||
import { getParentOfClass, isObsidianThemeDark, getFileCSSClasses } from "../../utils/obsidianUtils";
|
||||
import { getParentOfClass,isObsidianThemeDark,getFileCSSClasses } from "../../utils/obsidianUtils";
|
||||
import { linkClickModifierType } from "../../utils/modifierkeyHelper";
|
||||
import { ImageKey, imageCache } from "../../shared/ImageCache";
|
||||
import { FILENAMEPARTS, PreviewImageType } from "../../types/utilTypes";
|
||||
import { CustomMutationObserver, debug, DEBUGGING } from "../../utils/debugHelper";
|
||||
import { ImageKey,imageCache } from "../../shared/ImageCache";
|
||||
import { FILENAMEPARTS,PreviewImageType } from "../../types/utilTypes";
|
||||
import { CustomMutationObserver,DEBUGGING } from "../../utils/debugHelper";
|
||||
import { getExcalidrawFileForwardLinks } from "../../utils/excalidrawViewUtils";
|
||||
import { linkPrompt } from "../../shared/Dialogs/Prompt";
|
||||
import { isHTMLElement } from "../../utils/typechecks";
|
||||
import { ExportSettings } from "src/types/exportUtilTypes";
|
||||
import { setElementDisplay } from "src/utils/htmlUtils";
|
||||
|
||||
interface imgElementAttributes {
|
||||
file?: TFile;
|
||||
@@ -80,7 +81,6 @@ const _getPNG = async ({imgAttributes,filenameParts,theme,cacheReady,img,file,ex
|
||||
exportSettings: ExportSettings,
|
||||
loader: EmbeddedFilesLoader,
|
||||
}):Promise<HTMLImageElement> => {
|
||||
(process.env.NODE_ENV === 'development') && DEBUGGING && debug(_getPNG, `MarkdownPostProcessor.ts > _getPNG`);
|
||||
const width = parseInt(imgAttributes.fwidth);
|
||||
const scale = width >= 2400
|
||||
? 5
|
||||
@@ -157,7 +157,6 @@ const setStyle = ({element,imgAttributes,onCanvas, isNativeSVG}:{
|
||||
isNativeSVG: boolean,
|
||||
}
|
||||
) => {
|
||||
(process.env.NODE_ENV === 'development') && DEBUGGING && debug(setStyle, `MarkdownPostProcessor.ts > setStyle`);
|
||||
let style = "";
|
||||
if(imgAttributes.fwidth) {
|
||||
style = `${isNativeSVG ? "max-width:" : "max-width:100%; width:"}${imgAttributes.fwidth}${imgAttributes.fwidth.match(/\d$/) ? "px":""}; `; //width:100%;`; //removed !important https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/886
|
||||
@@ -189,7 +188,6 @@ const _getSVGIMG = async ({filenameParts,theme,cacheReady,img,file,exportSetting
|
||||
exportSettings: ExportSettings,
|
||||
loader: EmbeddedFilesLoader,
|
||||
}):Promise<HTMLImageElement> => {
|
||||
(process.env.NODE_ENV === 'development') && DEBUGGING && debug(_getSVGIMG, `MarkdownPostProcessor.ts > _getSVGIMG`);
|
||||
exportSettings.skipInliningFonts = false;
|
||||
const cacheKey = {
|
||||
...filenameParts,
|
||||
@@ -243,7 +241,8 @@ const _getSVGIMG = async ({filenameParts,theme,cacheReady,img,file,exportSetting
|
||||
}
|
||||
|
||||
//need to remove width and height attributes to support area= embeds
|
||||
svg.removeAttribute("width");
|
||||
//svg.removeAttribute("width");
|
||||
svg.setAttribute("width", "6000");
|
||||
svg.removeAttribute("height");
|
||||
return addSVGToImgSrc(img, svg, cacheReady, cacheKey);
|
||||
}
|
||||
@@ -258,7 +257,6 @@ const _getSVGNative = async ({filenameParts,theme,cacheReady,containerElement,fi
|
||||
loader: EmbeddedFilesLoader,
|
||||
width?: number,
|
||||
}):Promise<HTMLDivElement> => {
|
||||
(process.env.NODE_ENV === 'development') && DEBUGGING && debug(_getSVGNative, `MarkdownPostProcessor.ts > _getSVGNative`);
|
||||
exportSettings.skipInliningFonts = false;
|
||||
const cacheKey = {
|
||||
...filenameParts,
|
||||
@@ -325,7 +323,6 @@ const getIMG = async (
|
||||
imgAttributes: imgElementAttributes,
|
||||
onCanvas: boolean = false,
|
||||
): Promise<HTMLImageElement | HTMLDivElement> => {
|
||||
(process.env.NODE_ENV === 'development') && DEBUGGING && debug(getIMG, `MarkdownPostProcessor.ts > getIMG`, imgAttributes);
|
||||
let file = imgAttributes.file;
|
||||
if (!imgAttributes.file) {
|
||||
const f = vault.getAbstractFileByPath(imgAttributes.fname?.split("#")[0]);
|
||||
@@ -392,7 +389,7 @@ const getIMG = async (
|
||||
exportSettings,
|
||||
loader,
|
||||
width: imgAttributes.fwidth
|
||||
? (!imgAttributes.fwidth.endsWith("%") ? parseInt(imgAttributes.fwidth) : 1000)
|
||||
? (!imgAttributes.fwidth.endsWith("%") ? parseInt(imgAttributes.fwidth) : 6000)
|
||||
: undefined,
|
||||
});
|
||||
}
|
||||
@@ -400,7 +397,6 @@ const getIMG = async (
|
||||
};
|
||||
|
||||
const addSVGToImgSrc = (img: HTMLImageElement, svg: SVGSVGElement, cacheReady: boolean, cacheKey: ImageKey):HTMLImageElement => {
|
||||
(process.env.NODE_ENV === 'development') && DEBUGGING && debug(addSVGToImgSrc, `MarkdownPostProcessor.ts > addSVGToImgSrc`);
|
||||
//https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2026
|
||||
//const svgString = new XMLSerializer().serializeToString(svg);
|
||||
const svgString = svg.outerHTML;
|
||||
@@ -423,7 +419,6 @@ const createImgElement = async (
|
||||
attr: imgElementAttributes,
|
||||
onCanvas: boolean = false,
|
||||
) :Promise<HTMLElement> => {
|
||||
(process.env.NODE_ENV === 'development') && DEBUGGING && debug(createImgElement, `MarkdownPostProcessor.ts > createImgElement`);
|
||||
const imgOrDiv = await getIMG(attr,onCanvas);
|
||||
if(!imgOrDiv) {
|
||||
return null;
|
||||
@@ -552,7 +547,6 @@ const createImageDiv = async (
|
||||
attr: imgElementAttributes,
|
||||
onCanvas: boolean = false
|
||||
): Promise<HTMLDivElement> => {
|
||||
(process.env.NODE_ENV === 'development') && DEBUGGING && debug(createImageDiv, `MarkdownPostProcessor.ts > createImageDiv`);
|
||||
const img = await createImgElement(attr, onCanvas);
|
||||
return createDiv(attr.style.join(" "), (el) => el.append(img));
|
||||
};
|
||||
@@ -561,7 +555,6 @@ const processReadingMode = async (
|
||||
embeddedItems: NodeListOf<Element> | [HTMLElement],
|
||||
ctx: MarkdownPostProcessorContext,
|
||||
) => {
|
||||
(process.env.NODE_ENV === 'development') && DEBUGGING_MPP && debug(processReadingMode, `MarkdownPostProcessor.ts > processReadingMode`);
|
||||
//We are processing a non-excalidraw file in reading mode
|
||||
//Embedded files will be displayed in an .internal-embed container
|
||||
|
||||
@@ -593,7 +586,6 @@ const processReadingMode = async (
|
||||
};
|
||||
|
||||
const processInternalEmbed = async (internalEmbedEl: Element, file: TFile ):Promise<HTMLDivElement> => {
|
||||
(process.env.NODE_ENV === 'development') && DEBUGGING_MPP && debug(processInternalEmbed, `MarkdownPostProcessor.ts > processInternalEmbed`, internalEmbedEl);
|
||||
const attr: imgElementAttributes = {
|
||||
fname: "",
|
||||
fheight: "",
|
||||
@@ -726,7 +718,6 @@ const processAltText = (
|
||||
alt:string,
|
||||
attr: imgElementAttributes
|
||||
) => {
|
||||
(process.env.NODE_ENV === 'development') && DEBUGGING && debug(processAltText, `MarkdownPostProcessor.ts > processAltText`);
|
||||
if (alt && !alt.startsWith(fname)) {
|
||||
const aliasParts = parseAlias(alt);
|
||||
attr.fwidth = aliasParts.width ?? attr.fwidth;
|
||||
@@ -738,7 +729,6 @@ const processAltText = (
|
||||
}
|
||||
|
||||
const isTextOnlyEmbed = (internalEmbedEl: Element):boolean => {
|
||||
(process.env.NODE_ENV === 'development') && DEBUGGING && debug(isTextOnlyEmbed, `MarkdownPostProcessor.ts > isTextOnlyEmbed`);
|
||||
const src = internalEmbedEl.getAttribute("src");
|
||||
if(!src) return true; //technically this does not mean this is a text only embed, but still should abort further processing
|
||||
const fnameParts = getEmbeddedFilenameParts(src);
|
||||
@@ -753,7 +743,6 @@ const tmpObsidianWYSIWYG = async (
|
||||
isMarkdownReadingMode: boolean,
|
||||
isHoverPopover: boolean,
|
||||
) => {
|
||||
(process.env.NODE_ENV === 'development') && DEBUGGING_MPP && debug(tmpObsidianWYSIWYG, `MarkdownPostProcessor.ts > tmpObsidianWYSIWYG`);
|
||||
const file = app.vault.getAbstractFileByPath(ctx.sourcePath);
|
||||
if(!(file instanceof TFile)) return;
|
||||
if(!plugin.isExcalidrawFile(file)) return;
|
||||
@@ -955,7 +944,6 @@ export const markdownPostProcessor = async (
|
||||
//@ts-ignore
|
||||
const containerEl = ctx.containerEl;
|
||||
|
||||
(process.env.NODE_ENV === 'development') && DEBUGGING_MPP && debug(markdownPostProcessor, `MarkdownPostProcessor.ts > markdownPostProcessor`, ctx, el);
|
||||
|
||||
//check to see if we are rendering in editing mode or live preview
|
||||
//if yes, then there should be no .internal-embed containers
|
||||
@@ -991,7 +979,7 @@ export const markdownPostProcessor = async (
|
||||
//in reading mode these elements should be hidden
|
||||
const excalidrawFile = Boolean(ctx.frontmatter?.hasOwnProperty("excalidraw-plugin"));
|
||||
if (!(isPreview || isMarkdownReadingMode || isPrinting) && excalidrawFile) {
|
||||
el.style.display = "none";
|
||||
setElementDisplay(el, "none");
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
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 { App, Notice, TFile } from "obsidian";
|
||||
import { getExcalidrawViews,isObsidianThemeDark } from "src/utils/obsidianUtils";
|
||||
import { App,Notice,TFile } from "obsidian";
|
||||
import { ExcalidrawImperativeAPI } from "@zsviczian/excalidraw/types/excalidraw/types";
|
||||
|
||||
export class ObserverManager {
|
||||
@@ -67,7 +67,6 @@ export class ObserverManager {
|
||||
if (!matchThemeTrigger) return;
|
||||
|
||||
const themeObserverFn:MutationCallback = async (mutations: MutationRecord[]) => {
|
||||
(process.env.NODE_ENV === 'development') && DEBUGGING && debug(themeObserverFn, `ExcalidrawPlugin.addThemeObserver`, mutations);
|
||||
const { matchThemeTrigger } = this.settings;
|
||||
if (!matchThemeTrigger) return;
|
||||
|
||||
@@ -78,11 +77,11 @@ export class ObserverManager {
|
||||
const darkClass = bodyClassList.contains('theme-dark');
|
||||
if (mutation?.oldValue?.includes('theme-dark') === darkClass) return;
|
||||
|
||||
setTimeout(()=>{ //run async to avoid blocking the UI
|
||||
window.setTimeout(()=>{ //run async to avoid blocking the UI
|
||||
const theme = isObsidianThemeDark() ? "dark" : "light";
|
||||
const excalidrawViews = getExcalidrawViews(this.app);
|
||||
const excalidrawViews = getExcalidrawViews(this.app, true);
|
||||
excalidrawViews.forEach(excalidrawView => {
|
||||
if (excalidrawView.file && excalidrawView.excalidrawAPI) {
|
||||
if (excalidrawView.file) {
|
||||
excalidrawView.setTheme(theme);
|
||||
}
|
||||
});
|
||||
@@ -122,7 +121,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}`)) {
|
||||
@@ -148,7 +146,6 @@ export class ObserverManager {
|
||||
};
|
||||
|
||||
const fileExplorerObserverFn:MutationCallback = (mutationsList) => {
|
||||
(process.env.NODE_ENV === 'development') && DEBUGGING && debug(fileExplorerObserverFn, `ExcalidrawPlugin.experimentalFileTypeDisplay > fileExplorerObserverFn`, mutationsList);
|
||||
const ensureFiletypes = (target: Element | DocumentFragment) => {
|
||||
target.querySelectorAll?.(".nav-file-title").forEach(insertFiletype);
|
||||
};
|
||||
@@ -235,7 +232,6 @@ export class ObserverManager {
|
||||
}
|
||||
//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 view = this.plugin.activeExcalidrawView;
|
||||
if (
|
||||
(m.length !== 1) ||
|
||||
@@ -248,7 +244,7 @@ export class ObserverManager {
|
||||
return;
|
||||
}
|
||||
|
||||
const { errorMessage } = (view.excalidrawAPI as ExcalidrawImperativeAPI).getAppState();
|
||||
const { errorMessage } = (view.excalidrawAPI).getAppState();
|
||||
if (!errorMessage) this.plugin.activeExcalidrawView.save();
|
||||
};
|
||||
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
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";
|
||||
@@ -109,10 +108,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);
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -40,7 +40,6 @@ 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));
|
||||
@@ -87,7 +86,7 @@ export class StylesManager {
|
||||
|
||||
const body = document.body;
|
||||
const iframe:HTMLIFrameElement = document.createElement("iframe");
|
||||
iframe.style.display = "none";
|
||||
iframe.hidden = true;
|
||||
body.appendChild(iframe);
|
||||
|
||||
const iframeLoadedPromise = new Promise<void>((resolve) => {
|
||||
@@ -136,19 +135,19 @@ 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});
|
||||
|
||||
+953
-180
File diff suppressed because it is too large.
Load diff
+95
-8
@@ -1,21 +1,108 @@
|
||||
//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 (!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;
|
||||
}
|
||||
}
|
||||
|
||||
+199
-38
@@ -1,10 +1,10 @@
|
||||
import {
|
||||
DEVICE,
|
||||
FRONTMATTER_KEYS,
|
||||
CJK_FONTS,
|
||||
DEVICE,
|
||||
FRONTMATTER_KEYS,
|
||||
CJK_FONTS,
|
||||
} from "src/constants/constants";
|
||||
import { TAG_AUTOEXPORT, TAG_MDREADINGMODE, TAG_PDFEXPORT } from "src/constants/constSettingsTags";
|
||||
import { labelALT, labelCTRL, labelMETA, labelSHIFT } from "src/utils/modifierKeyLabels";
|
||||
import { TAG_AUTOEXPORT,TAG_MDREADINGMODE,TAG_PDFEXPORT } from "src/constants/constSettingsTags";
|
||||
import { labelALT,labelCTRL,labelMETA,labelSHIFT } from "src/utils/modifierKeyLabels";
|
||||
|
||||
declare const PLUGIN_VERSION:string;
|
||||
|
||||
@@ -97,6 +97,7 @@ export default {
|
||||
ENTER_LATEX: "Enter a valid LaTeX expression",
|
||||
EDIT_LATEX: "Edit LaTeX formula",
|
||||
READ_RELEASE_NOTES: "Read latest release notes",
|
||||
ABOUT_EXCALIDRAW: "About Excalidraw",
|
||||
RUN_OCR: "OCR full drawing: Grab text from freedraw + images to clipboard and doc.props",
|
||||
RERUN_OCR: "OCR full drawing re-run: Grab text from freedraw + images to clipboard and doc.props",
|
||||
RUN_OCR_ELEMENTS: "OCR selected elements: Grab text from freedraw + images to clipboard",
|
||||
@@ -110,6 +111,7 @@ export default {
|
||||
RESET_IMG_ASPECT_RATIO: "Reset selected image element aspect ratio",
|
||||
TEMPORARY_DISABLE_AUTOSAVE: "Disable autosave until next time Obsidian starts (only set this if you know what you are doing)",
|
||||
TEMPORARY_ENABLE_AUTOSAVE: "Enable autosave",
|
||||
TEMPORARY_TOGGLE_VIEW_MODE_FOR_ALL_DRAWINGS: "Toggle view mode for all Excalidraw drawings until Obsidian restarts",
|
||||
FONTS_LOADED: "Excalidraw: CJK Fonts loaded",
|
||||
FONTS_LOAD_ERROR: "Excalidraw: Could not find CJK Fonts in the assets folder\n",
|
||||
TOGGLE_ENABLE_CONTEXT_MENU: "Toggle enable context menu (helpful on Mobile devices)",
|
||||
@@ -196,8 +198,8 @@ export default {
|
||||
WELCOME_HELP_MENU: "Find help in the hamburger-menu",
|
||||
WELCOME_YOUTUBE_ARIA: "Visual PKM YouTube Channel",
|
||||
WELCOME_YOUTUBE_LINK: "Check out the Visual PKM YouTube channel.",
|
||||
WELCOME_DISCORD_ARIA: "Join the Discord Server",
|
||||
WELCOME_DISCORD_LINK: "Join the Discord Server",
|
||||
WELCOME_SYM_ARIA: "Learn Excalidraw, Master PKM, Join the Community",
|
||||
WELCOME_SYM_LINK: "Learn Excalidraw, Master PKM, Join the Community",
|
||||
WELCOME_TWITTER_ARIA: "Follow me on Twitter",
|
||||
WELCOME_TWITTER_LINK: "Follow me on Twitter",
|
||||
WELCOME_LEARN_ARIA: "Learn Visual PKM",
|
||||
@@ -221,12 +223,16 @@ export default {
|
||||
DISABLE_CONTEXT_MENU_DESC: "Disables the Excalidraw context menu. This can be useful on Mobile devices where the context menu pops up in unwanted moments.",
|
||||
NOTEBOOKLM_LINK_ARIA: "Ask NotebookLM for help about the plugin. This model is pre-loaded with all my video transcripts, release notes and other helpful content. Chat with NotebookLM to explore my 250+ videos and the Excalidraw documentation.",
|
||||
NOTEBOOKLM_LINK_TEXT: "Learn the Plugin. Access the NotebookLM knowledgebase.",
|
||||
EXCALIDRAW_MASTERY_PROMO_ARIA: "Open Excalidraw Mastery",
|
||||
EXCALIDRAW_MASTERY_PROMO_HTML: `<p><b>Feeling lost in the toggles and menus?</b></p><p>Excalidraw is a Visual PKM powerhouse built for heavy-duty workflows like <b>Visual-First Daily Notes</b>, deep <b>PDF research</b>, <b>automation</b>, <b>AI integration</b>, and <b>Visual Zettelkasten</b>. But all this power comes with complexity.</p><p>Skip the trial and error. <a href="https://community.sketch-your-mind.com/em" target="_blank">👉 Join Excalidraw Mastery</a> to learn these exact setups step-by-step. Overcome tool friction and master your knowledge alongside a supportive community of visual thinkers!</p>`,
|
||||
EXCALIDRAW_MASTERY_PROMO_SHOW: "Show",
|
||||
EXCALIDRAW_MASTERY_PROMO_HIDE: "Hide",
|
||||
LINKS_BUGS_ARIA: "Report bugs and raise feature requsts on the plugin's GitHub page",
|
||||
LINKS_BUGS: "Report Bugs",
|
||||
LINKS_YT_ARIA: "Check out my YouTube channel to learn about Visual Thinking and Excalidraw",
|
||||
LINKS_YT: "Learn on YouTube",
|
||||
LINKS_DISCORD_ARIA: "Join the Visual Thinking Workshop Discord Server",
|
||||
LINKS_DISCORD: "Join the Community",
|
||||
LINKS_JOIN_SYM_ARIA: "Learn Excalidraw, Master Visual Thinking, Join the Community",
|
||||
LINKS_JOIN_SYM: "Learn Excalidraw",
|
||||
LINKS_TWITTER: "Follow me",
|
||||
LINKS_VTW_ARIA: "Learn about Visual PKM, Excalidraw, Obsidian, ExcaliBrain and more",
|
||||
LINKS_VTW: "Join a Workshop",
|
||||
@@ -302,37 +308,155 @@ export default {
|
||||
AI_DESC: `In the "AI" settings, you can configure options for using OpenAI's GPT API. ` +
|
||||
`While the OpenAI API is in beta, its use is strictly limited — as such we require you use your own API key. ` +
|
||||
`You can create an OpenAI account, add a small credit (5 USD minimum), and generate your own API key. ` +
|
||||
`Once API key is set, you can use the AI tools in Excalidraw.`,
|
||||
`Once API key is set, you can use the AI tools in Excalidraw. ` +
|
||||
`These settings are used by ExcalidrawAutomate, Mermaid chat, diagram-to-code, and related AI features. Configure one or more provider profiles, then assign your text, vision, and image models to those providers. Older OpenAI-specific AI settings are migrated here automatically on first run.`,
|
||||
AI_ENABLED_NAME: "Enable AI features",
|
||||
AI_ENABLED_DESC: "You need to reopen Excalidraw for the changes to take effect.",
|
||||
AI_OPENAI_TOKEN_NAME: "OpenAI API key",
|
||||
AI_OPENAI_TOKEN_DESC:
|
||||
"You can get your OpenAI API key from your <a href='https://platform.openai.com/api-keys'>OpenAI account</a>.",
|
||||
AI_OPENAI_TOKEN_PLACEHOLDER: "Enter your OpenAI API key here",
|
||||
AI_OPENAI_DEFAULT_MODEL_NAME: "Default AI model",
|
||||
AI_OPENAI_DEFAULT_MODEL_DESC:
|
||||
"The default AI model to use when generating text. This is a freetext field, so you can enter any valid OpenAI model name. " +
|
||||
"Find out more about the available models on the <a href='https://platform.openai.com/docs/models'>OpenAI website</a>.",
|
||||
AI_OPENAI_DEFAULT_MODEL_PLACEHOLDER: "Enter your default AI model here. e.g.: gpt-5-mini",
|
||||
AI_OPENAI_DEFAULT_MAX_TOKENS_NAME: "Max tokens",
|
||||
AI_OPENAI_DEFAULT_MAX_TOKENS_DESC:
|
||||
"Maximum number of tokens to generate in the API response. Set to 0 to omit the max_tokens field (useful for models that don't support this parameter, such as GPT-5).",
|
||||
AI_OPENAI_DEFAULT_IMAGE_MODEL_NAME: "Default Image Generation AI model",
|
||||
AI_OPENAI_DEFAULT_IMAGE_MODEL_DESC:
|
||||
"The default AI model to use when generating images. Image editing and variations are only supported by dall-e-2 and gpt-image-1 at this time by OpenAI.<br>" +
|
||||
"This is a freetext field, so you can enter any valid OpenAI model name. " +
|
||||
"Find out more about the available models on the <a href='https://platform.openai.com/docs/models'>OpenAI website</a>.",
|
||||
AI_OPENAI_DEFAULT_IMAGE_MODEL_PLACEHOLDER: "Enter your default Image Generation AI model here e.g.: gpt-image-1",
|
||||
AI_OPENAI_DEFAULT_VISION_MODEL_NAME: "Default AI vision model",
|
||||
AI_OPENAI_DEFAULT_VISION_MODEL_DESC:
|
||||
"The default AI vision model to use when generating text from images. This is a freetext field, so you can enter any valid OpenAI model name. " +
|
||||
"Find out more about the available models on the <a href='https://platform.openai.com/docs/models'>OpenAI website</a>.",
|
||||
AI_OPENAI_DEFAULT_API_URL_NAME: "OpenAI API URL",
|
||||
AI_OPENAI_DEFAULT_API_URL_DESC:
|
||||
"The default OpenAI API URL. This is a freetext field, so you can enter any valid OpenAI API compatible URL. " +
|
||||
"Excalidraw will use this URL when posting API requests to OpenAI. I am not doing any error handling on this field, so make sure you enter a valid URL and only change this if you know what you are doing. ",
|
||||
AI_OPENAI_DEFAULT_IMAGE_API_URL_NAME: "OpenAI Image Generation API URL",
|
||||
AI_OPENAI_DEFAULT_VISION_MODEL_PLACEHOLDER: "Enter your default AI vision model here. e.g.: gpt-5-mini",
|
||||
AI_VERBOSE_LOGGING_NAME: "Enable verbose AI logging",
|
||||
AI_VERBOSE_LOGGING_DESC: "Write detailed AI request and response diagnostics to the developer console. Leave this off unless you are troubleshooting.",
|
||||
AI_PROVIDER_NAME: "Define available providers",
|
||||
AI_PROVIDER_DESC:
|
||||
"Define the provider profiles available to the model lists below. Text, Vision, and Image each select their provider separately.",
|
||||
AI_PROVIDER_PROFILE_ROW_DESC:
|
||||
"Type: {{providerType}}<br>API: {{apiKey}}",
|
||||
AI_PROVIDER_OPTION_OPENAI: "OpenAI",
|
||||
AI_PROVIDER_OPTION_ANTHROPIC: "Anthropic / Claude",
|
||||
AI_PROVIDER_OPTION_GOOGLE: "Google / Gemini",
|
||||
AI_PROVIDER_OPTION_XAI: "xAI / Grok",
|
||||
AI_PROVIDER_OPTION_OPENAI_COMPATIBLE: "OpenAI-compatible / local",
|
||||
AI_PROVIDER_BASE_URL_EMPTY: "Derived from the provider type",
|
||||
AI_PROVIDER_API_KEY_SET: "Configured",
|
||||
AI_PROVIDER_API_KEY_NOT_SET: "Not set",
|
||||
AI_PROVIDER_EDIT: "Edit provider",
|
||||
AI_PROVIDER_ADD: "Add provider",
|
||||
AI_PROVIDER_REMOVE: "Remove provider",
|
||||
AI_PROVIDER_RESTORE_DEFAULTS: "Restore provider defaults",
|
||||
AI_PROVIDER_API_KEY_NAME: "AI API key",
|
||||
AI_PROVIDER_API_KEY_DESC:
|
||||
"Primary API key used by the shared AI layer. The value is masked unless the field is focused.",
|
||||
AI_PROVIDER_API_KEY_PLACEHOLDER: "Provider API key",
|
||||
AI_PROVIDER_BASE_URL_NAME: "AI base URL",
|
||||
AI_PROVIDER_BASE_URL_DESC:
|
||||
"Optional provider base URL. Use this for local OpenAI-compatible servers or self-hosted gateways. You can enter either a base URL such as https://api.openai.com/v1 or a full chat endpoint such as https://api.openai.com/v1/chat/completions; Excalidraw will normalize known OpenAI-style endpoints automatically.",
|
||||
AI_PROVIDER_BASE_URL_PLACEHOLDER: "e.g.: https://api.openai.com/v1",
|
||||
AI_PROVIDER_TEXT_ENDPOINT_NAME: "AI text endpoint override",
|
||||
AI_PROVIDER_TEXT_ENDPOINT_DESC:
|
||||
"Optional full endpoint override for text and multimodal requests. Leave blank to derive it from the base URL and provider. Most users should keep this empty.",
|
||||
AI_PROVIDER_TEXT_ENDPOINT_PLACEHOLDER: "Optional full text endpoint",
|
||||
AI_PROVIDER_IMAGE_GENERATION_ENDPOINT_NAME: "AI image generation endpoint override",
|
||||
AI_PROVIDER_IMAGE_GENERATION_ENDPOINT_DESC:
|
||||
"Optional full endpoint override for image generation requests. Leave blank unless your provider exposes image generation on a non-standard path.",
|
||||
AI_PROVIDER_IMAGE_GENERATION_ENDPOINT_PLACEHOLDER: "Optional full image generation endpoint",
|
||||
AI_PROVIDER_IMAGE_EDITS_ENDPOINT_NAME: "AI image edits endpoint override",
|
||||
AI_PROVIDER_IMAGE_EDITS_ENDPOINT_DESC:
|
||||
"Optional full endpoint override for image edit requests. Leave blank unless your provider exposes image edits on a non-standard path.",
|
||||
AI_PROVIDER_IMAGE_EDITS_ENDPOINT_PLACEHOLDER: "Optional full image edits endpoint",
|
||||
AI_PROVIDER_IMAGE_VARIATIONS_ENDPOINT_NAME: "AI image variations endpoint override",
|
||||
AI_PROVIDER_IMAGE_VARIATIONS_ENDPOINT_DESC:
|
||||
"Optional full endpoint override for image variation requests. Leave blank unless your provider exposes image variations on a non-standard path.",
|
||||
AI_PROVIDER_IMAGE_VARIATIONS_ENDPOINT_PLACEHOLDER: "Optional full image variations endpoint",
|
||||
AI_PROVIDER_DEFAULT_TEXT_MODEL_NAME: "Text and multimodal model",
|
||||
AI_PROVIDER_DEFAULT_TEXT_MODEL_DESC:
|
||||
"Model used for text chat and image-aware requests such as Mermaid chat, diagram-to-code, and wireframe analysis.<br>Provider: {{provider}} ({{providerType}})<br>API key: {{apiKey}}<br>Model name: {{model}}<br>Endpoint: {{endpoint}}<br>Multimodal support: {{multimodalSupport}}",
|
||||
AI_PROVIDER_DEFAULT_TEXT_MODEL_PLACEHOLDER: "e.g.: gpt-5-mini, claude-sonnet, gemini-2.5-pro",
|
||||
AI_PROVIDER_DEFAULT_VISION_MODEL_NAME: "Vision model",
|
||||
AI_PROVIDER_DEFAULT_VISION_MODEL_DESC:
|
||||
"Model used for image understanding tasks such as diagram-to-code or image-plus-text prompts.<br>Provider: {{provider}} ({{providerType}})<br>API key: {{apiKey}}<br>Model name: {{model}}<br>Endpoint: {{endpoint}}",
|
||||
AI_PROVIDER_DEFAULT_VISION_MODEL_PLACEHOLDER: "e.g.: gpt-5-mini, claude-sonnet, gemini-2.5-flash",
|
||||
AI_PROVIDER_DEFAULT_IMAGE_MODEL_NAME: "Image model",
|
||||
AI_PROVIDER_DEFAULT_IMAGE_MODEL_DESC:
|
||||
"Model used for image generation, prompt-based transforms, and mask edits. Use the Edit, Add, and Remove buttons to modify the list.<br>Provider: {{provider}} ({{providerType}})<br>API key: {{apiKey}}<br>Model name: {{model}}<br>Supported resolutions: {{sizes}}<br>Prompt transforms: {{supportsPromptImageTransforms}}<br>Mask edits: {{supportsMaskImageEdits}}",
|
||||
AI_PROVIDER_DEFAULT_IMAGE_MODEL_PLACEHOLDER: "e.g.: gpt-image-1",
|
||||
AI_MODEL_CONFIG_DERIVED_ENDPOINT: "Derived from the selected provider",
|
||||
AI_MODEL_EDIT: "Edit model",
|
||||
AI_MODEL_ADD: "Add model",
|
||||
AI_MODEL_REMOVE: "Remove model",
|
||||
AI_MODEL_RESTORE_DEFAULTS: "Restore model defaults",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_NAME: "Image model capabilities",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_DESC:
|
||||
"Manage stored image model metadata such as supported resolutions, prompt-transform support, and mask-edit support. Example: see the <a href=\"https://platform.openai.com/docs/guides/image-generation\" target=\"_blank\" rel=\"noopener noreferrer\">OpenAI image generation docs</a> to look up supported sizes.",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_LOAD_DEFAULTS: "Restore known defaults",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_ADD_MODEL: "Add",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_EDIT_MODEL: "Edit",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_REMOVE_MODEL: "Remove entry",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_CURRENT_ENTRY_NAME: "Selected model entry",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_CURRENT_ENTRY_DESC:
|
||||
"<b>{{model}}</b><br>Supported resolutions: {{sizes}}<br>Prompt transforms: {{supportsPromptImageTransforms}}<br>Mask edits: {{supportsMaskImageEdits}}",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_SIZES_NAME: "Supported resolutions",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_SIZES_PLACEHOLDER: "1024x1024, 1536x1024, 1024x1536",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_EDITS_NAME: "Supports image edits",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_EDITS_DESC:
|
||||
"Disable this when the model can generate images but does not support image edits or masks.",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_TRANSFORMS_NAME: "Prompt image transforms",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_TRANSFORMS_DESC:
|
||||
"Enable this when the model accepts an input image plus a text prompt for non-masked edits.",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_MASK_EDITS_NAME: "Mask image edits",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_MASK_EDITS_DESC:
|
||||
"Enable this when the model supports replacing selected regions of an input image with a mask.",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_EDITS_YES: "Yes",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_EDITS_NO: "No",
|
||||
AI_IMAGE_MODEL_CAPABILITY_MODAL_ADD_TITLE: "Add image model entry",
|
||||
AI_IMAGE_MODEL_CAPABILITY_MODAL_EDIT_TITLE: "Edit image model entry",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_MODAL_MODEL_NAME: "Model ID",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_MODAL_MODEL_DESC:
|
||||
"Use the exact model name exposed by your provider.",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_MODAL_MODEL_PLACEHOLDER: "e.g.: gpt-image-2",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_MODAL_SIZES_DESC:
|
||||
"Add one supported resolution per row.",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_MODAL_SIZE_LABEL: "Resolution",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_MODAL_ADD_SIZE: "Add resolution",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_MODAL_REMOVE_SIZE: "Remove",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_MODAL_MODEL_REQUIRED: "Model ID is required.",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_MODAL_SIZE_REQUIRED: "Add at least one supported resolution.",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_MODAL_DUPLICATE_MODEL: "A model entry with this ID already exists.",
|
||||
AI_PROVIDER_PROFILE_MODAL_ADD_TITLE: "Add provider profile",
|
||||
AI_PROVIDER_PROFILE_MODAL_EDIT_TITLE: "Edit provider profile",
|
||||
AI_PROVIDER_PROFILE_MODAL_NAME_NAME: "Profile name",
|
||||
AI_PROVIDER_PROFILE_MODAL_NAME_DESC: "This label appears in the model dropdowns.",
|
||||
AI_PROVIDER_PROFILE_MODAL_NAME_PLACEHOLDER: "e.g.: OpenAI",
|
||||
AI_PROVIDER_PROFILE_MODAL_TYPE_NAME: "Provider type",
|
||||
AI_PROVIDER_PROFILE_MODAL_TYPE_DESC: "Select the API family used by this provider profile.",
|
||||
AI_PROVIDER_PROFILE_MODAL_API_KEY_NAME: "API key",
|
||||
AI_PROVIDER_PROFILE_MODAL_API_KEY_DESC: "Stored with this provider profile and used by any model assigned to it.",
|
||||
AI_PROVIDER_PROFILE_MODAL_API_KEY_PLACEHOLDER: "Provider API key",
|
||||
AI_PROVIDER_PROFILE_MODAL_BASE_URL_NAME: "Base URL",
|
||||
AI_PROVIDER_PROFILE_MODAL_BASE_URL_DESC: "Base URL used to derive the provider endpoints.",
|
||||
AI_PROVIDER_PROFILE_MODAL_BASE_URL_PLACEHOLDER: "e.g.: https://api.openai.com/v1",
|
||||
AI_PROVIDER_PROFILE_MODAL_OPENAI_COMPATIBLE_HINT:
|
||||
"For local OpenAI-compatible LLMs, enter a dummy API key if no real key is required so Excalidraw recognizes the profile as configured.",
|
||||
AI_PROVIDER_PROFILE_MODAL_NAME_REQUIRED: "Provider profile name is required.",
|
||||
AI_PROVIDER_PROFILE_MODAL_DUPLICATE_NAME: "A provider profile with this name already exists.",
|
||||
AI_MODEL_CONFIG_MODAL_NAME_NAME: "Entry name",
|
||||
AI_MODEL_CONFIG_MODAL_NAME_DESC: "This label appears in the dropdown.",
|
||||
AI_MODEL_CONFIG_MODAL_NAME_PLACEHOLDER: "e.g.: gpt-5-mini",
|
||||
AI_MODEL_CONFIG_MODAL_PROVIDER_NAME: "Provider",
|
||||
AI_MODEL_CONFIG_MODAL_PROVIDER_DESC: "Choose which provider profile this model should use.",
|
||||
AI_MODEL_CONFIG_MODAL_MODEL_NAME: "Model name",
|
||||
AI_MODEL_CONFIG_MODAL_MODEL_DESC: "Exact model name sent to the API.",
|
||||
AI_MODEL_CONFIG_MODAL_MODEL_PLACEHOLDER: "e.g.: gpt-5-mini",
|
||||
AI_MODEL_CONFIG_MODAL_ENDPOINT_NAME: "Endpoint override",
|
||||
AI_MODEL_CONFIG_MODAL_ENDPOINT_DESC: "Optional full endpoint override for this model. Leave blank to derive it from the provider profile.",
|
||||
AI_MODEL_CONFIG_MODAL_ENDPOINT_PLACEHOLDER: "Optional full endpoint",
|
||||
AI_MODEL_CONFIG_MODAL_MULTIMODAL_NAME: "Multimodal support",
|
||||
AI_MODEL_CONFIG_MODAL_MULTIMODAL_DESC: "Allow this text model to accept image inputs for analysis and diagram-to-code style tasks.",
|
||||
AI_MODEL_CONFIG_MODAL_NAME_REQUIRED: "Entry name is required.",
|
||||
AI_MODEL_CONFIG_MODAL_PROVIDER_REQUIRED: "Select a provider profile.",
|
||||
AI_MODEL_CONFIG_MODAL_MODEL_REQUIRED: "Model name is required.",
|
||||
AI_MODEL_CONFIG_MODAL_DUPLICATE_NAME: "A model entry with this name already exists.",
|
||||
AI_TEXT_MODEL_MODAL_ADD_TITLE: "Add text model",
|
||||
AI_TEXT_MODEL_MODAL_EDIT_TITLE: "Edit text model",
|
||||
AI_VISION_MODEL_MODAL_ADD_TITLE: "Add vision model",
|
||||
AI_VISION_MODEL_MODAL_EDIT_TITLE: "Edit vision model",
|
||||
AI_IMAGE_MODEL_MODAL_ADD_TITLE: "Add image model",
|
||||
AI_IMAGE_MODEL_MODAL_EDIT_TITLE: "Edit image model",
|
||||
AI_PROVIDER_DEFAULT_MAX_OUTGOING_TOKENS_NAME: "AI default outgoing token budget",
|
||||
AI_PROVIDER_DEFAULT_MAX_OUTGOING_TOKENS_DESC:
|
||||
"Default value for AIRequest.maxOutgoingTokens. Excalidraw uses this as an approximate budget for outgoing text content and trims long prompts or older chat history first. This can also affect text sent with image requests.",
|
||||
AI_PROVIDER_DEFAULT_MAX_OUTGOING_TOKENS_PLACEHOLDER: "e.g.: 8000",
|
||||
AI_PROVIDER_DEFAULT_MAX_RESPONSE_TOKENS_NAME: "AI default response token limit",
|
||||
AI_PROVIDER_DEFAULT_MAX_RESPONSE_TOKENS_DESC:
|
||||
"Default value for AIRequest.maxTokens. This limits text or multimodal responses returned by the model. It does not affect direct image generation or image edit endpoints.",
|
||||
AI_PROVIDER_DEFAULT_MAX_RESPONSE_TOKENS_PLACEHOLDER: "e.g.: 4096",
|
||||
SAVING_HEAD: "Saving",
|
||||
SAVING_DESC: "In the 'Saving' section of Excalidraw Settings, you can configure how your drawings are saved. This includes options for compressing Excalidraw JSON in Markdown, setting autosave intervals for both desktop and mobile, defining filename formats, and choosing whether to use the .excalidraw.md or .md file extension. ",
|
||||
COMPRESS_NAME: "Compress Excalidraw JSON in Markdown",
|
||||
@@ -426,6 +550,8 @@ export default {
|
||||
DEFAULT_OPEN_MODE_DESC:
|
||||
"Specifies the mode how Excalidraw opens: Normal, Zen, or View mode. You may also set this behavior on a file level by " +
|
||||
"adding the excalidraw-default-mode frontmatter key with a value of: normal, view, or zen to your document.",
|
||||
PHONE_FOOTER_SAFE_AREA_PADDING_NAME: "Extra bottom padding for phone controls",
|
||||
PHONE_FOOTER_SAFE_AREA_PADDING_DESC: "Adds extra bottom padding to the Excalidraw footer controls so zoom and undo buttons stay above the system navigation bar on phones. This setting only applies on phones.",
|
||||
DEFAULT_PEN_MODE_NAME: "Pen mode",
|
||||
DEFAULT_PEN_MODE_DESC:
|
||||
"Should pen mode be automatically enabled when opening Excalidraw?",
|
||||
@@ -684,6 +810,13 @@ export default {
|
||||
RENDERING_CONCURRENCY_DESC:
|
||||
"Number of parallel workers to use for image rendering. Increasing this number will speed up the rendering process, but may slow down the rest of the system. " +
|
||||
"The default value is 3. You can increase this number if you have a powerful system.",
|
||||
IMAGE_CACHE_RETENTION_DAYS_NAME: "Local image cache retention",
|
||||
IMAGE_CACHE_RETENTION_DAYS_DESC:
|
||||
"How many days Excalidraw should keep locally cached rendered assets such as nested Excalidraw images and PDF pages before unused cache entries are purged. " +
|
||||
"Cached items remain available while they are being used, and their timer is refreshed when they are read from cache.<br><br>" +
|
||||
"This only affects Excalidraw's local cache on the current device. It does <b>not</b> change your vault size, your attachments, or your sync payload. " +
|
||||
"The practical impact is local disk or browser-storage usage inside Obsidian. This can matter on phones and on desktops with tighter browser storage quotas or limited free disk space.<br><br>" +
|
||||
"Lower values reclaim local cache space sooner but may force more rerendering of PDFs and embedded drawings. Higher values keep repeat loads faster at the cost of more local cache storage.",
|
||||
EXPORT_SUBHEAD: "Export Settings",
|
||||
EMBED_SIZING: "Image sizing",
|
||||
EMBED_THEME_BACKGROUND: "Image theme and background color",
|
||||
@@ -846,6 +979,15 @@ export default {
|
||||
FIELD_SUGGESTER_DESC:
|
||||
"Field Suggester borrowed from Breadcrumbs and Templater plugins. The Field Suggester will show an autocomplete menu " +
|
||||
"when you type <code>excalidraw-</code> or <code>ea.</code> with function description as hints on the individual items in the list.",
|
||||
ENABLE_ONLOAD_SCRIPTS_NAME: "Enable onload scripts",
|
||||
ENABLE_ONLOAD_SCRIPTS_CONFIRMATION:
|
||||
"This file includes an <code>excalidraw-onload-script</code>. Do you want to enable onload scripts?",
|
||||
ENABLE_ONLOAD_SCRIPTS_CONFIRM_ENABLE: "Enable scripts",
|
||||
ENABLE_ONLOAD_SCRIPTS_CONFIRM_DENY: "Do not allow",
|
||||
ENABLE_ONLOAD_SCRIPTS_DESC:
|
||||
"If enabled, Excalidraw will execute file-level <code>excalidraw-onload-script</code> code in all drawings you open from now on, until you disable this setting. " +
|
||||
"This creates a risk if you download markdown files from unknown sources: a malicious actor can use <code>excalidraw-onload-script</code> " +
|
||||
"to run any command in Obsidian and potentially transfer data to the internet. Only enable this if you trust the file and its source.",
|
||||
STARTUP_SCRIPT_NAME: "Startup script",
|
||||
STARTUP_SCRIPT_DESC:
|
||||
"If set, excalidraw will execute the script at plugin startup. This is useful if you want to set any of the Excalidraw Automate hooks. The startup script is a markdown file " +
|
||||
@@ -1226,6 +1368,25 @@ export default {
|
||||
|
||||
//ReleaseNotes.ts
|
||||
RN_WELCOME: "Welcome to Excalidraw",
|
||||
FIRST_RUN: `
|
||||
The Excalidraw Obsidian plugin is much more than "just" a drawing tool. Because it integrates deeply with Obsidian, it opens up a whole new paradigm for Visual Personal Knowledge Management.
|
||||
|
||||
<div style="text-align:center;margin-top:10px;">
|
||||
<a href="https://community.sketch-your-mind.com/ee" target="_blank"><img src="https://sketch-your-mind.com/images/logo-EE.png" style="width:50%;"></a>
|
||||
</div>
|
||||
|
||||
To help you get started without the overwhelm, I highly recommend taking the free **[Excalidraw Essentials](https://community.sketch-your-mind.com/ee)** mini-course. It cuts through the noise and teaches you the fundamentals in a fast, structured way.
|
||||
|
||||
You also don't have to figure it all out alone! Come join the **[Sketch Your Mind Community](https://community.sketch-your-mind.com)** to connect with fellow visual thinkers, share your workflows, and build a frictionless PKM system together.
|
||||
|
||||
If you'd like to see what's possible right now, here is a showcase of the key features. To keep abreast of the latest updates and to explore visual PKM, please subscribe to my YouTube channel: [Visual PKM](https://www.youtube.com/@visualPKM).
|
||||
|
||||
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>
|
||||
`,
|
||||
|
||||
//Excalidraw component
|
||||
COMP_IMG: "Image & Files",
|
||||
|
||||
+125
-35
@@ -1,10 +1,10 @@
|
||||
import {
|
||||
DEVICE,
|
||||
FRONTMATTER_KEYS,
|
||||
CJK_FONTS,
|
||||
DEVICE,
|
||||
FRONTMATTER_KEYS,
|
||||
CJK_FONTS,
|
||||
} from "src/constants/constants";
|
||||
import { TAG_AUTOEXPORT, TAG_MDREADINGMODE, TAG_PDFEXPORT } from "src/constants/constSettingsTags";
|
||||
import { labelALT, labelCTRL, labelMETA, labelSHIFT } from "src/utils/modifierKeyLabels";
|
||||
import { TAG_AUTOEXPORT,TAG_MDREADINGMODE,TAG_PDFEXPORT } from "src/constants/constSettingsTags";
|
||||
import { labelALT,labelCTRL,labelMETA,labelSHIFT } from "src/utils/modifierKeyLabels";
|
||||
|
||||
declare const PLUGIN_VERSION:string;
|
||||
|
||||
@@ -294,38 +294,119 @@ export default {
|
||||
AI_DESC: `En la configuración de "IA", puedes configurar opciones para usar la API GPT de OpenAI. ` +
|
||||
`Aunque la API de OpenAI está en fase beta, su uso es estrictamente limitado; por lo tanto, requerimos que uses tu propia API KEY (clave de API). ` +
|
||||
`Puedes crear una cuenta de OpenAI, agregar un pequeño crédito (mínimo 5 USD) y generar tu propia API KEY (clave de API) ` +
|
||||
`Una vez que la API KEY (clave de API) esté configurada, podrás usar las herramientas de IA en Excalidraw.`,
|
||||
`Una vez que la API KEY (clave de API) esté configurada, podrás usar las herramientas de IA en Excalidraw. ` +
|
||||
`Estos ajustes se usan en ExcalidrawAutomate, Mermaid chat y diagram-to-code. En la mayoría de los casos solo necesitas configurar el proveedor, la clave API y los modelos predeterminados. Deja vacías las anulaciones de endpoints salvo que tu proveedor requiera URL personalizadas. Las configuraciones antiguas de IA específicas de OpenAI se migrarán aquí automáticamente en el primer inicio.`,
|
||||
AI_ENABLED_NAME: "Habilitar funcionalidades de IA",
|
||||
AI_ENABLED_DESC: "Necesitas reabrir Excalidraw para que los cambios surtan efecto.",
|
||||
AI_OPENAI_TOKEN_NAME: "OpenAI API key (Clave de API de OpenAI)",
|
||||
AI_OPENAI_TOKEN_DESC:
|
||||
"Puedes obtener tu API KEY (clave de API) de OpenAI desde tu <a href='https://platform.openai.com/api-keys'></a>.",
|
||||
AI_OPENAI_TOKEN_PLACEHOLDER: "Ingresa tu API Key (clave de API) de OpenAI aquí",
|
||||
AI_OPENAI_DEFAULT_MODEL_NAME: "Modelo de IA predeterminado",
|
||||
AI_OPENAI_DEFAULT_MODEL_DESC:
|
||||
"El modelo de IA predeterminado para usar al generar texto. Este es un campo de texto libre, así que puedes ingresar cualquier nombre de modelo de OpenAI válido. " +
|
||||
"Encuentra más información sobre los modelos disponibles en el sitio web de OpenAI: <a href='https://platform.openai.com/docs/models'></a>.",
|
||||
AI_OPENAI_DEFAULT_MODEL_PLACEHOLDER: "Ingresa aquí tu modelo de IA predeterminado. Ej.: gpt-3.5-turbo-1106",
|
||||
AI_OPENAI_DEFAULT_MAX_TOKENS_NAME: "Tokens máximos",
|
||||
AI_OPENAI_DEFAULT_MAX_TOKENS_DESC:
|
||||
"Número máximo de tokens a generar en la respuesta de la API. Establece en 0 para omitir el campo max_tokens (útil para modelos que no admiten este parámetro, como GPT-5).",
|
||||
AI_OPENAI_DEFAULT_IMAGE_MODEL_NAME: "Modelo de IA predeterminado para generación de imágenes",
|
||||
AI_OPENAI_DEFAULT_IMAGE_MODEL_DESC:
|
||||
"El modelo de IA predeterminado para usar al generar imágenes. La edición y variaciones de imágenes solo son compatibles con Dall-E 2 en este momento por parte de OpenAI, " +
|
||||
"por esta razón, Dall-E 2 se usará automáticamente en tales casos, independientemente de esta configuración.<br>" +
|
||||
"Este es un campo de texto libre, así que puedes ingresar cualquier nombre de modelo de OpenAI válido. " +
|
||||
"Encuentra más información sobre los modelos disponibles en el sitio web de OpenAI: <a href='https://platform.openai.com/docs/models'></a>.",
|
||||
AI_OPENAI_DEFAULT_IMAGE_MODEL_PLACEHOLDER: "Ingresa aquí tu modelo de IA predeterminado para generación de imágenes. Ej.: Dall-E 3",
|
||||
AI_OPENAI_DEFAULT_VISION_MODEL_NAME: "Modelo de visión de IA predeterminado",
|
||||
AI_OPENAI_DEFAULT_VISION_MODEL_DESC:
|
||||
"El modelo de visión de IA predeterminado para usar al generar texto a partir de imágenes. Este es un campo de texto libre, así que puedes ingresar cualquier nombre de modelo de OpenAI válido. " +
|
||||
"Find out more about the available models on the <a href='https://platform.openai.com/docs/models'>OpenAI website</a>.",
|
||||
AI_OPENAI_DEFAULT_API_URL_NAME: "URL de la API de OpenAI",
|
||||
AI_OPENAI_DEFAULT_API_URL_DESC:
|
||||
"La URL predeterminada de la API de OpenAI. Este es un campo de texto libre, así que puedes ingresar cualquier URL compatible con la API de OpenAI válida. " +
|
||||
"Excalidraw usará esta URL al enviar solicitudes a la API de OpenAI. No realizo manejo de errores en este campo, así que asegúrate de ingresar una URL válida y solo cámbiala si sabes lo que estás haciendo. ",
|
||||
AI_OPENAI_DEFAULT_IMAGE_API_URL_NAME: "URL de la API de Generación de Imágenes de OpenAI",
|
||||
AI_OPENAI_DEFAULT_VISION_MODEL_PLACEHOLDER: "Ingresa aquí tu modelo de visión de IA predeterminado. Ej.: gpt-4o",
|
||||
AI_VERBOSE_LOGGING_NAME: "Habilitar registro detallado de IA",
|
||||
AI_VERBOSE_LOGGING_DESC: "Escribe diagnósticos detallados de solicitudes y respuestas de IA en la consola de desarrollador. Déjalo desactivado salvo que estés solucionando un problema.",
|
||||
AI_PROVIDER_NAME: "Definir proveedores disponibles",
|
||||
AI_PROVIDER_DESC:
|
||||
"Define los perfiles de proveedor disponibles para las listas de modelos de abajo. Texto, Visión e Imagen seleccionan su proveedor por separado.",
|
||||
AI_PROVIDER_PROFILE_ROW_DESC:
|
||||
"Tipo: {{providerType}}<br>API: {{apiKey}}",
|
||||
AI_PROVIDER_OPTION_OPENAI: "OpenAI",
|
||||
AI_PROVIDER_OPTION_ANTHROPIC: "Anthropic / Claude",
|
||||
AI_PROVIDER_OPTION_GOOGLE: "Google / Gemini",
|
||||
AI_PROVIDER_OPTION_XAI: "xAI / Grok",
|
||||
AI_PROVIDER_OPTION_OPENAI_COMPATIBLE: "Compatible con OpenAI / local",
|
||||
AI_PROVIDER_PROFILE_MODAL_OPENAI_COMPATIBLE_HINT:
|
||||
"Para LLM locales compatibles con OpenAI, usa una API key ficticia si no hace falta una real, para que Excalidraw marque el perfil como configurado.",
|
||||
AI_PROVIDER_BASE_URL_EMPTY: "Derivada del tipo de proveedor",
|
||||
AI_PROVIDER_API_KEY_SET: "Configurada",
|
||||
AI_PROVIDER_API_KEY_NOT_SET: "Sin configurar",
|
||||
AI_PROVIDER_EDIT: "Editar proveedor",
|
||||
AI_PROVIDER_ADD: "Agregar proveedor",
|
||||
AI_PROVIDER_REMOVE: "Eliminar proveedor",
|
||||
AI_PROVIDER_RESTORE_DEFAULTS: "Restaurar proveedores predeterminados",
|
||||
AI_PROVIDER_API_KEY_NAME: "Clave API de IA",
|
||||
AI_PROVIDER_API_KEY_DESC:
|
||||
"Clave API principal usada por la capa compartida de IA. El valor permanece oculto salvo cuando el campo tiene el foco.",
|
||||
AI_PROVIDER_API_KEY_PLACEHOLDER: "Clave API del proveedor",
|
||||
AI_PROVIDER_BASE_URL_NAME: "URL base de IA",
|
||||
AI_PROVIDER_BASE_URL_DESC:
|
||||
"URL base opcional del proveedor. Úsala para servidores locales compatibles con OpenAI o pasarelas autoalojadas. Puedes introducir una URL base como https://api.openai.com/v1 o un endpoint completo de chat como https://api.openai.com/v1/chat/completions; Excalidraw normalizará automáticamente los endpoints conocidos con formato OpenAI.",
|
||||
AI_PROVIDER_BASE_URL_PLACEHOLDER: "p. ej.: https://api.openai.com/v1",
|
||||
AI_PROVIDER_TEXT_ENDPOINT_NAME: "Anulación del endpoint de texto de IA",
|
||||
AI_PROVIDER_TEXT_ENDPOINT_DESC:
|
||||
"Anulación opcional del endpoint completo para solicitudes de texto y multimodales. Déjalo vacío para derivarlo de la URL base y el proveedor. La mayoría de usuarios no necesita rellenarlo.",
|
||||
AI_PROVIDER_TEXT_ENDPOINT_PLACEHOLDER: "Endpoint completo opcional de texto",
|
||||
AI_PROVIDER_IMAGE_GENERATION_ENDPOINT_NAME: "Anulación del endpoint de generación de imágenes de IA",
|
||||
AI_PROVIDER_IMAGE_GENERATION_ENDPOINT_DESC:
|
||||
"Anulación opcional del endpoint completo para solicitudes de generación de imágenes. Déjalo vacío salvo que tu proveedor exponga esta función en una ruta no estándar.",
|
||||
AI_PROVIDER_IMAGE_GENERATION_ENDPOINT_PLACEHOLDER: "Endpoint completo opcional de generación de imágenes",
|
||||
AI_PROVIDER_IMAGE_EDITS_ENDPOINT_NAME: "Anulación del endpoint de edición de imágenes de IA",
|
||||
AI_PROVIDER_IMAGE_EDITS_ENDPOINT_DESC:
|
||||
"Anulación opcional del endpoint completo para solicitudes de edición de imágenes. Déjalo vacío salvo que tu proveedor exponga esta función en una ruta no estándar.",
|
||||
AI_PROVIDER_IMAGE_EDITS_ENDPOINT_PLACEHOLDER: "Endpoint completo opcional de edición de imágenes",
|
||||
AI_PROVIDER_IMAGE_VARIATIONS_ENDPOINT_NAME: "Anulación del endpoint de variaciones de imágenes de IA",
|
||||
AI_PROVIDER_IMAGE_VARIATIONS_ENDPOINT_DESC:
|
||||
"Anulación opcional del endpoint completo para solicitudes de variaciones de imágenes. Déjalo vacío salvo que tu proveedor exponga esta función en una ruta no estándar.",
|
||||
AI_PROVIDER_IMAGE_VARIATIONS_ENDPOINT_PLACEHOLDER: "Endpoint completo opcional de variaciones de imágenes",
|
||||
AI_PROVIDER_DEFAULT_TEXT_MODEL_NAME: "Modelo de texto y multimodal",
|
||||
AI_PROVIDER_DEFAULT_TEXT_MODEL_DESC:
|
||||
"Modelo usado para chat de texto y solicitudes con imágenes, como Mermaid chat, diagram-to-code y análisis de wireframes.<br>Proveedor: {{provider}} ({{providerType}})<br>Clave API: {{apiKey}}<br>Nombre del modelo: {{model}}<br>Endpoint: {{endpoint}}<br>Compatibilidad multimodal: {{multimodalSupport}}",
|
||||
AI_PROVIDER_DEFAULT_TEXT_MODEL_PLACEHOLDER: "p. ej.: gpt-5-mini, claude-sonnet, gemini-2.5-pro",
|
||||
AI_PROVIDER_DEFAULT_VISION_MODEL_NAME: "Modelo de visión",
|
||||
AI_PROVIDER_DEFAULT_VISION_MODEL_DESC:
|
||||
"Modelo usado para tareas de comprensión de imágenes, como diagram-to-code o solicitudes con imagen y texto.<br>Proveedor: {{provider}} ({{providerType}})<br>Clave API: {{apiKey}}<br>Nombre del modelo: {{model}}<br>Endpoint: {{endpoint}}",
|
||||
AI_PROVIDER_DEFAULT_VISION_MODEL_PLACEHOLDER: "p. ej.: gpt-5-mini, claude-sonnet, gemini-2.5-flash",
|
||||
AI_PROVIDER_DEFAULT_IMAGE_MODEL_NAME: "Modelo de imagen",
|
||||
AI_PROVIDER_DEFAULT_IMAGE_MODEL_DESC:
|
||||
"Modelo usado para generación de imágenes, transformaciones guiadas por prompt y ediciones con máscara. Usa los botones Editar, Agregar y Eliminar para modificar la lista.<br>Proveedor: {{provider}} ({{providerType}})<br>Clave API: {{apiKey}}<br>Nombre del modelo: {{model}}<br>Resoluciones compatibles: {{sizes}}<br>Transformaciones por prompt: {{supportsPromptImageTransforms}}<br>Ediciones con máscara: {{supportsMaskImageEdits}}",
|
||||
AI_PROVIDER_DEFAULT_IMAGE_MODEL_PLACEHOLDER: "p. ej.: gpt-image-1",
|
||||
AI_MODEL_CONFIG_DERIVED_ENDPOINT: "Derivado del proveedor seleccionado",
|
||||
AI_MODEL_EDIT: "Editar modelo",
|
||||
AI_MODEL_ADD: "Agregar modelo",
|
||||
AI_MODEL_REMOVE: "Eliminar modelo",
|
||||
AI_MODEL_RESTORE_DEFAULTS: "Restaurar modelos predeterminados",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_NAME: "Capacidades del modelo de imagen",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_DESC:
|
||||
"Administra aquí los metadatos de los modelos de imagen, como resoluciones compatibles, soporte para transformaciones por prompt y soporte para ediciones con máscara. Por ejemplo, puedes consultar los tamaños compatibles en la <a href=\"https://platform.openai.com/docs/guides/image-generation\" target=\"_blank\" rel=\"noopener noreferrer\">documentación de generación de imágenes de OpenAI</a>.",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_LOAD_DEFAULTS: "Restaurar valores conocidos",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_ADD_MODEL: "Agregar",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_EDIT_MODEL: "Editar",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_REMOVE_MODEL: "Eliminar entrada",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_CURRENT_ENTRY_NAME: "Entrada de modelo seleccionada",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_CURRENT_ENTRY_DESC:
|
||||
"<b>{{model}}</b><br>Resoluciones compatibles: {{sizes}}<br>Transformaciones por prompt: {{supportsPromptImageTransforms}}<br>Ediciones con máscara: {{supportsMaskImageEdits}}",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_SIZES_NAME: "Resoluciones compatibles",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_SIZES_PLACEHOLDER: "1024x1024, 1536x1024, 1024x1536",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_EDITS_NAME: "Admite edición de imágenes",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_EDITS_DESC:
|
||||
"Desactiva esta opción si el modelo puede generar imágenes pero no admite edición de imágenes ni máscaras.",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_TRANSFORMS_NAME: "Transformaciones de imagen por prompt",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_TRANSFORMS_DESC:
|
||||
"Actívalo cuando el modelo acepte una imagen de entrada más un prompt de texto para ediciones sin máscara.",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_MASK_EDITS_NAME: "Ediciones de imagen con máscara",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_MASK_EDITS_DESC:
|
||||
"Actívalo cuando el modelo admita reemplazar regiones concretas de una imagen de entrada mediante una máscara.",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_EDITS_YES: "Sí",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_EDITS_NO: "No",
|
||||
AI_IMAGE_MODEL_CAPABILITY_MODAL_ADD_TITLE: "Agregar entrada de modelo de imagen",
|
||||
AI_IMAGE_MODEL_CAPABILITY_MODAL_EDIT_TITLE: "Editar entrada de modelo de imagen",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_MODAL_MODEL_NAME: "ID del modelo",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_MODAL_MODEL_DESC:
|
||||
"Usa el nombre exacto del modelo expuesto por tu proveedor.",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_MODAL_MODEL_PLACEHOLDER: "p. ej.: gpt-image-2",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_MODAL_SIZES_DESC:
|
||||
"Agrega una resolución compatible por fila.",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_MODAL_SIZE_LABEL: "Resolución",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_MODAL_ADD_SIZE: "Agregar resolución",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_MODAL_REMOVE_SIZE: "Eliminar",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_MODAL_MODEL_REQUIRED: "El ID del modelo es obligatorio.",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_MODAL_SIZE_REQUIRED: "Agrega al menos una resolución compatible.",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_MODAL_DUPLICATE_MODEL: "Ya existe una entrada con este ID de modelo.",
|
||||
AI_MODEL_CONFIG_MODAL_MULTIMODAL_NAME: "Compatibilidad multimodal",
|
||||
AI_MODEL_CONFIG_MODAL_MULTIMODAL_DESC: "Permite que este modelo de texto acepte imágenes para análisis y tareas tipo diagram-to-code.",
|
||||
AI_PROVIDER_DEFAULT_MAX_OUTGOING_TOKENS_NAME: "Presupuesto predeterminado de tokens salientes de IA",
|
||||
AI_PROVIDER_DEFAULT_MAX_OUTGOING_TOKENS_DESC:
|
||||
"Valor predeterminado para AIRequest.maxOutgoingTokens. Excalidraw lo usa como presupuesto aproximado para el texto saliente y recorta primero los prompts largos o el historial de chat antiguo. También puede afectar al texto enviado con solicitudes de imagen.",
|
||||
AI_PROVIDER_DEFAULT_MAX_OUTGOING_TOKENS_PLACEHOLDER: "p. ej.: 8000",
|
||||
AI_PROVIDER_DEFAULT_MAX_RESPONSE_TOKENS_NAME: "Límite predeterminado de tokens de respuesta de IA",
|
||||
AI_PROVIDER_DEFAULT_MAX_RESPONSE_TOKENS_DESC:
|
||||
"Valor predeterminado para AIRequest.maxTokens. Limita las respuestas de texto o multimodales devueltas por el modelo. No afecta a los endpoints directos de generación o edición de imágenes.",
|
||||
AI_PROVIDER_DEFAULT_MAX_RESPONSE_TOKENS_PLACEHOLDER: "p. ej.: 4096",
|
||||
SAVING_HEAD: "Guardar",
|
||||
SAVING_DESC: "En la sección 'Guardar' de la Configuración de Excalidraw, puedes configurar cómo se guardan tus bosquejos. Esto incluye opciones para comprimir el JSON de Excalidraw en Markdown, establecer intervalos de autoguardado para escritorio y móvil, definir formatos de nombre de archivo y elegir si usar la extensión de archivo .excalidraw.md o .md. ",
|
||||
COMPRESS_NAME: "Comprimir JSON de Excalidraw en Markdown",
|
||||
@@ -819,6 +900,15 @@ FILENAME_HEAD: "Nombre de archivo",
|
||||
FIELD_SUGGESTER_DESC:
|
||||
"El sugeridor de campos, tomado de los complementos Breadcrumbs y Templater, mostrará un menú de autocompletar " +
|
||||
"cuando escribas <code>excalidraw-</code> o <code>ea.</code> , con descripciones de las funciones como pistas para cada elemento en la lista.",
|
||||
ENABLE_ONLOAD_SCRIPTS_NAME: "Habilitar scripts de carga",
|
||||
ENABLE_ONLOAD_SCRIPTS_CONFIRMATION:
|
||||
"Este archivo incluye un <code>excalidraw-onload-script</code>. ¿Quieres habilitar los scripts de carga?",
|
||||
ENABLE_ONLOAD_SCRIPTS_CONFIRM_ENABLE: "Habilitar scripts",
|
||||
ENABLE_ONLOAD_SCRIPTS_CONFIRM_DENY: "No permitir",
|
||||
ENABLE_ONLOAD_SCRIPTS_DESC:
|
||||
"Si está habilitado, Excalidraw ejecutará el <code>excalidraw-onload-script</code> a nivel de archivo en todos los dibujos que abras a partir de ahora, hasta que desactives esta opción. " +
|
||||
"Esto crea un riesgo si descargas archivos Markdown de fuentes desconocidas: un actor malicioso puede usar <code>excalidraw-onload-script</code> " +
|
||||
"para ejecutar cualquier comando en Obsidian y potencialmente transferir datos a internet. Actívalo solo si confías en el archivo y en su origen.",
|
||||
STARTUP_SCRIPT_NAME: "Script de inicio",
|
||||
STARTUP_SCRIPT_DESC:
|
||||
"Si está configurado, Excalidraw ejecutará el script al iniciar el complemento. Esto es útil si quieres establecer cualquiera de los hooks de Excalidraw Automate. El script de inicio es un archivo Markdown " +
|
||||
|
||||
+159
-32
@@ -1,6 +1,6 @@
|
||||
import { DEVICE, FRONTMATTER_KEYS, CJK_FONTS } from "src/constants/constants";
|
||||
import { TAG_AUTOEXPORT, TAG_MDREADINGMODE, TAG_PDFEXPORT } from "src/constants/constSettingsTags";
|
||||
import { labelALT, labelCTRL, labelMETA, labelSHIFT } from "src/utils/modifierKeyLabels";
|
||||
import { DEVICE,FRONTMATTER_KEYS } from "src/constants/constants";
|
||||
import { TAG_AUTOEXPORT } from "src/constants/constSettingsTags";
|
||||
import { labelALT,labelCTRL,labelMETA,labelSHIFT } from "src/utils/modifierKeyLabels";
|
||||
|
||||
// русский
|
||||
export default {
|
||||
@@ -67,6 +67,7 @@ export default {
|
||||
INSERT_LATEX: `Вставьте формулу LaTeX (например, \\\binom{n}{k} = \\\frac{n!}{k!(n-k)!}).`,
|
||||
ENTER_LATEX: "Введите правильное выражение LaTeX",
|
||||
READ_RELEASE_NOTES: "Прочитать последние заметки о выпуске",
|
||||
ABOUT_EXCALIDRAW: "О Excalidraw",
|
||||
RUN_OCR: "OCR полного чертежа: Захват текста из freedraw + изображения в буфер обмена и doc.props",
|
||||
RERUN_OCR: "Повторный запуск полного чертежа OCR: Захват текста из freedraw + изображения в буфер обмена и doc.props",
|
||||
RUN_OCR_ELEMENTS: "OCR выделенных элементов: Захват текста из freedraw + изображения в буфер обмена",
|
||||
@@ -81,6 +82,28 @@ export default {
|
||||
TEMPORARY_DISABLE_AUTOSAVE: "Отключить автосохранение до следующего запуска Obsidian (устанавливайте этот параметр, только если вы знаете, что делаете)",
|
||||
TEMPORARY_ENABLE_AUTOSAVE: "Включить автосохранение",
|
||||
|
||||
//ReleaseNotes.ts
|
||||
RN_WELCOME: "Добро пожаловать в Excalidraw",
|
||||
FIRST_RUN: `
|
||||
Плагин Excalidraw для Obsidian - это гораздо больше, чем «просто» инструмент для рисования. Благодаря глубокой интеграции с Obsidian он открывает совершенно новый подход к визуальному управлению личными знаниями.
|
||||
|
||||
<div style="text-align:center;margin-top:10px;">
|
||||
<a href="https://community.sketch-your-mind.com/ee" target="_blank"><img src="https://sketch-your-mind.com/images/logo-EE.png" style="width:50%;"></a>
|
||||
</div>
|
||||
|
||||
Чтобы начать без перегруза, очень рекомендую бесплатный мини-курс **[Excalidraw Essentials](https://community.sketch-your-mind.com/ee)**. Он помогает быстро разобраться в главном и освоить базовые принципы в структурированном формате.
|
||||
|
||||
Вам не обязательно разбираться во всем в одиночку. Присоединяйтесь к **[сообществу Sketch Your Mind](https://community.sketch-your-mind.com)**, чтобы общаться с другими визуально мыслящими людьми, делиться своими рабочими процессами и выстраивать более плавную систему PKM.
|
||||
|
||||
Если хотите увидеть, что уже возможно прямо сейчас, ниже есть обзор ключевых возможностей. А чтобы следить за новыми обновлениями и идеями по Visual PKM, подписывайтесь на мой YouTube-канал: [Visual PKM](https://www.youtube.com/@visualPKM).
|
||||
|
||||
Спасибо и приятной работы!
|
||||
|
||||
<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>
|
||||
`,
|
||||
|
||||
//ExcalidrawView.ts
|
||||
NO_SEARCH_RESULT: "Не удалось найти подходящий элемент на чертеже",
|
||||
FORCE_SAVE_ABORTED: "Принудительное сохранение прервано, поскольку идет процесс сохранения",
|
||||
@@ -156,6 +179,10 @@ export default {
|
||||
RELEASE_NOTES_DESC:
|
||||
"<b><u>Переключатель ВКЛ:</u></b> Отображение информации о выпуске при каждом обновлении Excalidraw до новой версии.<br>" +
|
||||
"<b><u>Переключатель ВЫКЛ:</u></b> Тихий режим. Вы все еще можете прочитать заметки о выпуске на <a href='https://github.com/zsviczian/obsidian-excalidraw-plugin/releases'>GitHub</a>.",
|
||||
EXCALIDRAW_MASTERY_PROMO_ARIA: "Открыть Excalidraw Mastery",
|
||||
EXCALIDRAW_MASTERY_PROMO_HTML: `<p><b>Потерялись в переключателях и меню?</b></p><p>Excalidraw - мощный инструмент Visual PKM, созданный для сложных рабочих процессов: <b>Visual-First Daily Notes</b>, глубокое <b>PDF-исследование</b>, <b>автоматизация</b>, <b>интеграция ИИ</b> и <b>визуальный Zettelkasten</b>. Но такая мощность неизбежно приносит и сложность.</p><p>Пропустите этап проб и ошибок. <a href="https://community.sketch-your-mind.com/em" target="_blank">👉 Присоединяйтесь к Excalidraw Mastery</a>, чтобы шаг за шагом освоить именно эти настройки. Уберите трение инструмента и развивайте свои знания вместе с поддерживающим сообществом визуально мыслящих людей!</p>`,
|
||||
EXCALIDRAW_MASTERY_PROMO_SHOW: "Показать",
|
||||
EXCALIDRAW_MASTERY_PROMO_HIDE: "Скрыть",
|
||||
NEWVERSION_NOTIFICATION_NAME: "Уведомление об обновлении плагина",
|
||||
NEWVERSION_NOTIFICATION_DESC:
|
||||
"<b><u>Переключатель ВКЛ:</u></b> Показывайте уведомление о появлении новой версии плагина.<br>" +
|
||||
@@ -204,35 +231,119 @@ export default {
|
||||
AI_DESC: `В настройках "ИИ" вы можете настроить параметры использования GPT API OpenAI. ` +
|
||||
`Пока API OpenAI находится в бета-версии, его использование строго ограничено - поэтому мы требуем, чтобы вы использовали свой собственный ключ API. ` +
|
||||
`Вы можете создать аккаунт OpenAI, добавить небольшой кредит (минимум 5 долларов) и сгенерировать свой собственный ключ API. ` +
|
||||
`После установки API-ключа вы сможете использовать инструменты искусственного интеллекта в Excalidraw.`,
|
||||
AI_OPENAI_TOKEN_NAME: "Ключ API OpenAI",
|
||||
AI_OPENAI_TOKEN_DESC: "Вы можете получить свой ключ API OpenAI из вашего <a href='https://platform.openai.com/api-keys'>OpenAI аккаунта</a>.",
|
||||
AI_OPENAI_TOKEN_PLACEHOLDER: "Введите свой ключ API OpenAI здесь",
|
||||
AI_OPENAI_DEFAULT_MODEL_NAME: "Модель ИИ по умолчанию",
|
||||
AI_OPENAI_DEFAULT_MODEL_DESC:
|
||||
"Модель ИИ по умолчанию, используемая при генерации текста. Это поле свободного текста, поэтому вы можете ввести любое действительное имя модели OpenAI. " +
|
||||
"Узнайте больше о доступных моделях на <a href='https://platform.openai.com/docs/models'>OpenAI сайте</a>.",
|
||||
AI_OPENAI_DEFAULT_MODEL_PLACEHOLDER: "Введите здесь модель искусственного интеллекта по умолчанию, например: gpt-3.5-turbo-1106.",
|
||||
AI_OPENAI_DEFAULT_MAX_TOKENS_NAME: "Максимальное количество токенов",
|
||||
AI_OPENAI_DEFAULT_MAX_TOKENS_DESC:
|
||||
"Максимальное количество токенов для генерации в ответе API. Установите значение 0, чтобы пропустить поле max_tokens (полезно для моделей, которые не поддерживают этот параметр, таких как GPT-5).",
|
||||
AI_OPENAI_DEFAULT_IMAGE_MODEL_NAME: "Модель ИИ для генерации изображений по умолчанию",
|
||||
AI_OPENAI_DEFAULT_IMAGE_MODEL_DESC:
|
||||
"Модель ИИ по умолчанию, используемая при генерации изображений. Редактирование и изменение изображений поддерживается OpenAI только в dall-e-2, " +
|
||||
"поэтому dall-e-2 будет автоматически использоваться в таких случаях независимо от этой настройки.<br>" +
|
||||
"Это поле свободного текста, поэтому вы можете ввести любое действительное имя модели OpenAI. " +
|
||||
"Узнайте больше о доступных моделях на <a href='https://platform.openai.com/docs/models'>OpenAI сайте</a>.",
|
||||
AI_OPENAI_DEFAULT_IMAGE_MODEL_PLACEHOLDER: "Введите здесь модель ИИ Image Generation по умолчанию, например: dall-e-3.",
|
||||
AI_OPENAI_DEFAULT_VISION_MODEL_NAME: "Модель видения ИИ по умолчанию",
|
||||
AI_OPENAI_DEFAULT_VISION_MODEL_DESC:
|
||||
"Модель зрения ИИ по умолчанию, используемая при генерации текста из изображений. Это поле свободного текста, поэтому вы можете ввести любое действительное имя модели OpenAI. " +
|
||||
"Узнайте больше о доступных моделях на <a href='https://platform.openai.com/docs/models'>OpenAI сайте</a>.",
|
||||
AI_OPENAI_DEFAULT_API_URL_NAME: "URL-адрес API OpenAI",
|
||||
AI_OPENAI_DEFAULT_API_URL_DESC:
|
||||
"URL-адрес OpenAI API по умолчанию. Это поле свободного текста, поэтому вы можете ввести любой действительный URL, совместимый с OpenAI API. " +
|
||||
"Excalidraw будет использовать этот URL при отправке API-запросов в OpenAI. Я не делаю никакой обработки ошибок в этом поле, поэтому убедитесь, что вы вводите правильный URL и изменяйте его только в том случае, если вы знаете, что делаете. ",
|
||||
AI_OPENAI_DEFAULT_IMAGE_API_URL_NAME: "URL-адрес API генерации изображений OpenAI",
|
||||
AI_OPENAI_DEFAULT_VISION_MODEL_PLACEHOLDER: "Введите здесь модель зрения ИИ по умолчанию. Например: gpt-4o",
|
||||
`После установки API-ключа вы сможете использовать инструменты искусственного интеллекта в Excalidraw. ` +
|
||||
`Эти параметры используются ExcalidrawAutomate, Mermaid chat и diagram-to-code. В большинстве случаев достаточно указать провайдера, API-ключ и модели по умолчанию. Переопределения конечных точек оставляйте пустыми, если ваш провайдер не требует собственных URL. Старые настройки ИИ, привязанные только к OpenAI, будут автоматически перенесены сюда при первом запуске.`,
|
||||
AI_ENABLED_NAME: "Включить функции ИИ",
|
||||
AI_ENABLED_DESC: "Чтобы изменения вступили в силу, необходимо заново открыть Excalidraw.",
|
||||
AI_VERBOSE_LOGGING_NAME: "Включить подробное логирование ИИ",
|
||||
AI_VERBOSE_LOGGING_DESC: "Выводит подробную диагностику AI-запросов и ответов в консоль разработчика. Оставляйте выключенным, если не занимаетесь отладкой.",
|
||||
AI_PROVIDER_NAME: "Определить доступных провайдеров",
|
||||
AI_PROVIDER_DESC:
|
||||
"Определите профили провайдеров, доступные для списков моделей ниже. Текст, Vision и Image выбирают своего провайдера отдельно.",
|
||||
AI_PROVIDER_PROFILE_ROW_DESC:
|
||||
"Тип: {{providerType}}<br>API: {{apiKey}}",
|
||||
AI_PROVIDER_OPTION_OPENAI: "OpenAI",
|
||||
AI_PROVIDER_OPTION_ANTHROPIC: "Anthropic / Claude",
|
||||
AI_PROVIDER_OPTION_GOOGLE: "Google / Gemini",
|
||||
AI_PROVIDER_OPTION_XAI: "xAI / Grok",
|
||||
AI_PROVIDER_OPTION_OPENAI_COMPATIBLE: "Совместимый с OpenAI / локальный",
|
||||
AI_PROVIDER_PROFILE_MODAL_OPENAI_COMPATIBLE_HINT:
|
||||
"Для локальных LLM, совместимых с OpenAI, укажите фиктивный API key, если реальный не нужен, чтобы Excalidraw считал профиль настроенным.",
|
||||
AI_PROVIDER_BASE_URL_EMPTY: "Определяется типом провайдера",
|
||||
AI_PROVIDER_API_KEY_SET: "Настроено",
|
||||
AI_PROVIDER_API_KEY_NOT_SET: "Не настроено",
|
||||
AI_PROVIDER_EDIT: "Изменить провайдера",
|
||||
AI_PROVIDER_ADD: "Добавить провайдера",
|
||||
AI_PROVIDER_REMOVE: "Удалить провайдера",
|
||||
AI_PROVIDER_RESTORE_DEFAULTS: "Восстановить провайдеров по умолчанию",
|
||||
AI_PROVIDER_API_KEY_NAME: "API-ключ ИИ",
|
||||
AI_PROVIDER_API_KEY_DESC:
|
||||
"Основной API-ключ, используемый общим слоем ИИ. Значение скрыто, пока поле не находится в фокусе.",
|
||||
AI_PROVIDER_API_KEY_PLACEHOLDER: "API-ключ провайдера",
|
||||
AI_PROVIDER_BASE_URL_NAME: "Базовый URL ИИ",
|
||||
AI_PROVIDER_BASE_URL_DESC:
|
||||
"Необязательный базовый URL провайдера. Используйте его для локальных OpenAI-совместимых серверов или собственных шлюзов. Можно указать как базовый URL, например https://api.openai.com/v1, так и полный endpoint чата, например https://api.openai.com/v1/chat/completions; Excalidraw автоматически нормализует известные OpenAI-подобные endpoints.",
|
||||
AI_PROVIDER_BASE_URL_PLACEHOLDER: "например: https://api.openai.com/v1",
|
||||
AI_PROVIDER_TEXT_ENDPOINT_NAME: "Переопределение endpoint текста ИИ",
|
||||
AI_PROVIDER_TEXT_ENDPOINT_DESC:
|
||||
"Необязательное полное переопределение endpoint для текстовых и мультимодальных запросов. Оставьте пустым, чтобы он вычислялся из базового URL и провайдера. Большинству пользователей это поле не нужно.",
|
||||
AI_PROVIDER_TEXT_ENDPOINT_PLACEHOLDER: "Необязательный полный endpoint текста",
|
||||
AI_PROVIDER_IMAGE_GENERATION_ENDPOINT_NAME: "Переопределение endpoint генерации изображений ИИ",
|
||||
AI_PROVIDER_IMAGE_GENERATION_ENDPOINT_DESC:
|
||||
"Необязательное полное переопределение endpoint для запросов генерации изображений. Оставьте пустым, если только ваш провайдер не использует нестандартный путь.",
|
||||
AI_PROVIDER_IMAGE_GENERATION_ENDPOINT_PLACEHOLDER: "Необязательный полный endpoint генерации изображений",
|
||||
AI_PROVIDER_IMAGE_EDITS_ENDPOINT_NAME: "Переопределение endpoint редактирования изображений ИИ",
|
||||
AI_PROVIDER_IMAGE_EDITS_ENDPOINT_DESC:
|
||||
"Необязательное полное переопределение endpoint для запросов редактирования изображений. Оставьте пустым, если только ваш провайдер не использует нестандартный путь.",
|
||||
AI_PROVIDER_IMAGE_EDITS_ENDPOINT_PLACEHOLDER: "Необязательный полный endpoint редактирования изображений",
|
||||
AI_PROVIDER_IMAGE_VARIATIONS_ENDPOINT_NAME: "Переопределение endpoint вариаций изображений ИИ",
|
||||
AI_PROVIDER_IMAGE_VARIATIONS_ENDPOINT_DESC:
|
||||
"Необязательное полное переопределение endpoint для запросов вариаций изображений. Оставьте пустым, если только ваш провайдер не использует нестандартный путь.",
|
||||
AI_PROVIDER_IMAGE_VARIATIONS_ENDPOINT_PLACEHOLDER: "Необязательный полный endpoint вариаций изображений",
|
||||
AI_PROVIDER_DEFAULT_TEXT_MODEL_NAME: "Текстовая и мультимодальная модель",
|
||||
AI_PROVIDER_DEFAULT_TEXT_MODEL_DESC:
|
||||
"Модель для текстового чата и запросов с изображениями, например Mermaid chat, diagram-to-code и анализа вайрфреймов.<br>Провайдер: {{provider}} ({{providerType}})<br>API key: {{apiKey}}<br>Имя модели: {{model}}<br>Endpoint: {{endpoint}}<br>Мультимодальная поддержка: {{multimodalSupport}}",
|
||||
AI_PROVIDER_DEFAULT_TEXT_MODEL_PLACEHOLDER: "например: gpt-5-mini, claude-sonnet, gemini-2.5-pro",
|
||||
AI_PROVIDER_DEFAULT_VISION_MODEL_NAME: "Vision-модель",
|
||||
AI_PROVIDER_DEFAULT_VISION_MODEL_DESC:
|
||||
"Модель для понимания изображений, например diagram-to-code или запросов с изображением и текстом.<br>Провайдер: {{provider}} ({{providerType}})<br>API key: {{apiKey}}<br>Имя модели: {{model}}<br>Endpoint: {{endpoint}}",
|
||||
AI_PROVIDER_DEFAULT_VISION_MODEL_PLACEHOLDER: "например: gpt-5-mini, claude-sonnet, gemini-2.5-flash",
|
||||
AI_PROVIDER_DEFAULT_IMAGE_MODEL_NAME: "Модель изображений",
|
||||
AI_PROVIDER_DEFAULT_IMAGE_MODEL_DESC:
|
||||
"Модель для генерации изображений, prompt-редактирования и редактирования с маской. Используйте кнопки редактирования, добавления и удаления, чтобы менять список.<br>Провайдер: {{provider}} ({{providerType}})<br>API key: {{apiKey}}<br>Имя модели: {{model}}<br>Поддерживаемые разрешения: {{sizes}}<br>Prompt-редактирование: {{supportsPromptImageTransforms}}<br>Редактирование с маской: {{supportsMaskImageEdits}}",
|
||||
AI_PROVIDER_DEFAULT_IMAGE_MODEL_PLACEHOLDER: "например: gpt-image-1",
|
||||
AI_MODEL_CONFIG_DERIVED_ENDPOINT: "Определяется выбранным провайдером",
|
||||
AI_MODEL_EDIT: "Изменить модель",
|
||||
AI_MODEL_ADD: "Добавить модель",
|
||||
AI_MODEL_REMOVE: "Удалить модель",
|
||||
AI_MODEL_RESTORE_DEFAULTS: "Восстановить модели по умолчанию",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_NAME: "Возможности моделей изображений",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_DESC:
|
||||
"Здесь настраиваются метаданные моделей изображений: поддерживаемые разрешения, поддержка prompt-редактирования и поддержка масок. Например, поддерживаемые размеры можно посмотреть в <a href=\"https://platform.openai.com/docs/guides/image-generation\" target=\"_blank\" rel=\"noopener noreferrer\">документации OpenAI по генерации изображений</a>.",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_LOAD_DEFAULTS: "Восстановить известные значения",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_ADD_MODEL: "Добавить",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_EDIT_MODEL: "Изменить",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_REMOVE_MODEL: "Удалить запись",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_CURRENT_ENTRY_NAME: "Выбранная запись модели",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_CURRENT_ENTRY_DESC:
|
||||
"<b>{{model}}</b><br>Поддерживаемые разрешения: {{sizes}}<br>Prompt-редактирование: {{supportsPromptImageTransforms}}<br>Редактирование с маской: {{supportsMaskImageEdits}}",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_SIZES_NAME: "Поддерживаемые разрешения",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_SIZES_PLACEHOLDER: "1024x1024, 1536x1024, 1024x1536",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_EDITS_NAME: "Поддерживает редактирование изображений",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_EDITS_DESC:
|
||||
"Отключите, если модель умеет только генерировать изображения, но не поддерживает редактирование или маски.",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_TRANSFORMS_NAME: "Prompt-редактирование изображений",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_TRANSFORMS_DESC:
|
||||
"Включите, если модель принимает входное изображение и текстовый prompt для редактирования без маски.",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_MASK_EDITS_NAME: "Редактирование изображений с маской",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_MASK_EDITS_DESC:
|
||||
"Включите, если модель умеет заменять выбранные области входного изображения с помощью маски.",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_EDITS_YES: "Да",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_EDITS_NO: "Нет",
|
||||
AI_IMAGE_MODEL_CAPABILITY_MODAL_ADD_TITLE: "Добавить запись модели изображений",
|
||||
AI_IMAGE_MODEL_CAPABILITY_MODAL_EDIT_TITLE: "Изменить запись модели изображений",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_MODAL_MODEL_NAME: "ID модели",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_MODAL_MODEL_DESC:
|
||||
"Используйте точное имя модели, которое дает ваш провайдер.",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_MODAL_MODEL_PLACEHOLDER: "например: gpt-image-2",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_MODAL_SIZES_DESC:
|
||||
"Добавляйте по одному поддерживаемому разрешению в строку.",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_MODAL_SIZE_LABEL: "Разрешение",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_MODAL_ADD_SIZE: "Добавить разрешение",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_MODAL_REMOVE_SIZE: "Удалить",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_MODAL_MODEL_REQUIRED: "Требуется ID модели.",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_MODAL_SIZE_REQUIRED: "Добавьте хотя бы одно поддерживаемое разрешение.",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_MODAL_DUPLICATE_MODEL: "Запись модели с таким ID уже существует.",
|
||||
AI_MODEL_CONFIG_MODAL_MULTIMODAL_NAME: "Мультимодальная поддержка",
|
||||
AI_MODEL_CONFIG_MODAL_MULTIMODAL_DESC: "Разрешает этой текстовой модели принимать изображения для анализа и задач в стиле diagram-to-code.",
|
||||
AI_PROVIDER_DEFAULT_MAX_OUTGOING_TOKENS_NAME: "Бюджет исходящих токенов ИИ по умолчанию",
|
||||
AI_PROVIDER_DEFAULT_MAX_OUTGOING_TOKENS_DESC:
|
||||
"Значение по умолчанию для AIRequest.maxOutgoingTokens. Это приблизительный бюджет для исходящего текста; Excalidraw сначала сокращает длинные подсказки и старую историю чата. Также влияет на текст, отправляемый вместе с image-запросами.",
|
||||
AI_PROVIDER_DEFAULT_MAX_OUTGOING_TOKENS_PLACEHOLDER: "например: 8000",
|
||||
AI_PROVIDER_DEFAULT_MAX_RESPONSE_TOKENS_NAME: "Лимит токенов ответа ИИ по умолчанию",
|
||||
AI_PROVIDER_DEFAULT_MAX_RESPONSE_TOKENS_DESC:
|
||||
"Значение по умолчанию для AIRequest.maxTokens. Ограничивает текстовые и мультимодальные ответы модели. Не влияет на прямые endpoint'ы генерации и редактирования изображений.",
|
||||
AI_PROVIDER_DEFAULT_MAX_RESPONSE_TOKENS_PLACEHOLDER: "например: 4096",
|
||||
SAVING_HEAD: "Сохранение",
|
||||
SAVING_DESC: "В разделе 'Сохранение' раздела Настройки Excalidraw вы можете настроить способ сохранения ваших чертежей. Сюда входят опции сжатия Excalidraw JSON в Markdown, установки интервалов автосохранения для настольных и мобильных компьютеров, определения форматов имен файлов, а также выбора расширения файла .excalidraw.md или .md. ",
|
||||
COMPRESS_NAME: "Сжатие Excalidraw JSON в формате Markdown",
|
||||
@@ -521,6 +632,13 @@ FILENAME_HEAD: "Имя файла",
|
||||
"Скрывайте границы и фон узлов холста при встраивании чертежа Excalidraw в холст. " +
|
||||
"Обратите внимание, что для создания полностью прозрачного фона изображения вам все равно придется настроить Excalidraw на экспорт изображений с прозрачным фоном.",
|
||||
EMBED_CACHING: "Кэширование изображений",
|
||||
IMAGE_CACHE_RETENTION_DAYS_NAME: "Срок хранения локального кэша изображений",
|
||||
IMAGE_CACHE_RETENTION_DAYS_DESC:
|
||||
"Определяет, сколько дней Excalidraw должен хранить локально закэшированные отрендеренные ресурсы, такие как вложенные изображения Excalidraw и страницы PDF, прежде чем неиспользуемые записи кэша будут удалены. " +
|
||||
"При чтении из кэша срок хранения элемента обновляется.<br><br>" +
|
||||
"Это влияет только на локальный кэш Excalidraw на текущем устройстве. Это <b>не</b> меняет размер вашего Vault, вложений или объём синхронизации. " +
|
||||
"Практически это влияет только на локальное использование диска или браузерного хранилища внутри Obsidian. Это может быть особенно заметно на телефонах и на настольных системах с более жёсткими лимитами браузерного хранилища или ограниченным свободным местом на диске.<br><br>" +
|
||||
"Меньшие значения быстрее освобождают локальное место, но могут приводить к более частому повторному рендерингу PDF и встроенных рисунков. Большие значения ускоряют повторные загрузки ценой большего локального кэша.",
|
||||
EXPORT_SUBHEAD: "Настройки экспорта",
|
||||
EMBED_SIZING: "Размер изображения",
|
||||
EMBED_THEME_BACKGROUND: "Тема изображения и цвет фона",
|
||||
@@ -675,6 +793,15 @@ FILENAME_HEAD: "Имя файла",
|
||||
FIELD_SUGGESTER_DESC:
|
||||
"Предложение полей (Suggester) позаимствован у плагинов Breadcrumbs и Templater. Предложение полей (Suggester) полей будет показывать " +
|
||||
"меню автозаполнения при вводе текста с описанием функций <code>excalidraw-</code> или <code>ea.</code> в качестве подсказок для отдельных элементов в списке.",
|
||||
ENABLE_ONLOAD_SCRIPTS_NAME: "Включить onload-скрипты",
|
||||
ENABLE_ONLOAD_SCRIPTS_CONFIRMATION:
|
||||
"Этот файл содержит <code>excalidraw-onload-script</code>. Включить onload-скрипты?",
|
||||
ENABLE_ONLOAD_SCRIPTS_CONFIRM_ENABLE: "Включить скрипты",
|
||||
ENABLE_ONLOAD_SCRIPTS_CONFIRM_DENY: "Не разрешать",
|
||||
ENABLE_ONLOAD_SCRIPTS_DESC:
|
||||
"Если эта настройка включена, Excalidraw будет выполнять <code>excalidraw-onload-script</code> на уровне файла во всех рисунках, которые вы откроете далее, пока вы не отключите эту настройку. " +
|
||||
"Это создаёт риск, если вы загружаете Markdown-файлы из неизвестных источников: злоумышленник может использовать <code>excalidraw-onload-script</code> " +
|
||||
"для запуска любой команды в Obsidian и потенциальной передачи данных в интернет. Включайте это только если доверяете файлу и его источнику.",
|
||||
STARTUP_SCRIPT_NAME: "Сценарий запуска",
|
||||
STARTUP_SCRIPT_DESC:
|
||||
"Если этот параметр установлен, excalidraw будет выполнять скрипт при запуске плагина. Это полезно, если вы хотите установить какой-либо из крючков Excalidraw Automate. " +
|
||||
|
||||
+159
-34
@@ -1,10 +1,10 @@
|
||||
import {
|
||||
DEVICE,
|
||||
FRONTMATTER_KEYS,
|
||||
CJK_FONTS,
|
||||
DEVICE,
|
||||
FRONTMATTER_KEYS,
|
||||
CJK_FONTS,
|
||||
} from "src/constants/constants";
|
||||
import { TAG_AUTOEXPORT, TAG_MDREADINGMODE, TAG_PDFEXPORT } from "src/constants/constSettingsTags";
|
||||
import { labelALT, labelCTRL, labelMETA, labelSHIFT } from "src/utils/modifierKeyLabels";
|
||||
import { TAG_AUTOEXPORT,TAG_MDREADINGMODE,TAG_PDFEXPORT } from "src/constants/constSettingsTags";
|
||||
import { labelCTRL,labelMETA,labelSHIFT } from "src/utils/modifierKeyLabels";
|
||||
|
||||
declare const PLUGIN_VERSION:string;
|
||||
|
||||
@@ -97,6 +97,7 @@ export default {
|
||||
ENTER_LATEX: "输入 LaTeX 公式",
|
||||
EDIT_LATEX: "编辑 LaTeX 公式",
|
||||
READ_RELEASE_NOTES: "阅读本插件的更新说明",
|
||||
ABOUT_EXCALIDRAW: "关于 Excalidraw",
|
||||
RUN_OCR: "OCR 整个绘图:识别涂鸦和图片里的文本并复制到剪贴板和笔记属性中",
|
||||
RERUN_OCR: "重新 OCR 整个绘图:识别涂鸦和图片里的文本并复制到剪贴板和笔记属性中",
|
||||
RUN_OCR_ELEMENTS: "OCR 选中的元素:识别涂鸦和图片里的文本并复制到剪贴板",
|
||||
@@ -110,6 +111,7 @@ export default {
|
||||
RESET_IMG_ASPECT_RATIO: "重置所选图像的纵横比",
|
||||
TEMPORARY_DISABLE_AUTOSAVE: "临时禁用自动保存功能,直到本次 Obsidian 退出(小白慎用!)",
|
||||
TEMPORARY_ENABLE_AUTOSAVE: "启用自动保存功能",
|
||||
TEMPORARY_TOGGLE_VIEW_MODE_FOR_ALL_DRAWINGS: "切换所有 Excalidraw 绘图的查看模式,直到本次 Obsidian 退出",
|
||||
FONTS_LOADED: "Excalidraw: CJK 字体已加载",
|
||||
FONTS_LOAD_ERROR: "Excalidraw: 在资源文件夹下找不到 CJK 字体\n",
|
||||
TOGGLE_ENABLE_CONTEXT_MENU: "切换是否启用上下文菜单(在移动设备上很有用)",
|
||||
@@ -221,6 +223,10 @@ export default {
|
||||
DISABLE_CONTEXT_MENU_DESC: "禁用 Excalidraw 的上下文菜单。这在移动设备上很有用,因为上下文菜单有时会在不需要的时候弹出。",
|
||||
NOTEBOOKLM_LINK_ARIA: "向 NotebookLM 咨询有关插件的帮助。此模型已预加载了我所有的视频转录稿、发布说明和其他帮助内容。与 NotebookLM 聊天,浏览我的 250+ 视频和 Excalidraw 文件。",
|
||||
NOTEBOOKLM_LINK_TEXT: "学习插件。访问 NotebookLM 知识库。",
|
||||
EXCALIDRAW_MASTERY_PROMO_ARIA: "打开 Excalidraw Mastery",
|
||||
EXCALIDRAW_MASTERY_PROMO_HTML: `<p><b>在各种开关和菜单里有点迷路吗?</b></p><p>Excalidraw 是一款为高强度工作流打造的 Visual PKM 强力工具,适合 <b>Visual-First Daily Notes</b>、深入的 <b>PDF 研究</b>、<b>自动化</b>、<b>AI 集成</b> 和 <b>Visual Zettelkasten</b>。但强大能力也意味着更高的复杂度。</p><p>跳过反复试错。<a href="https://community.sketch-your-mind.com/em" target="_blank">👉 加入 Excalidraw Mastery</a>,一步一步学会这些具体配置。减少工具摩擦,与一群善于视觉思考的支持型社群一起掌握你的知识体系。</p>`,
|
||||
EXCALIDRAW_MASTERY_PROMO_SHOW: "显示",
|
||||
EXCALIDRAW_MASTERY_PROMO_HIDE: "隐藏",
|
||||
LINKS_BUGS_ARIA: "在插件的 GitHub 页面报告错误和提交功能请求",
|
||||
LINKS_BUGS: "报告错误",
|
||||
LINKS_YT_ARIA: "访问我的 YouTube 频道学习视觉思维和 Excalidraw",
|
||||
@@ -302,37 +308,119 @@ export default {
|
||||
AI_DESC: `OpenAI GPT API 的设置。` +
|
||||
`目前 OpenAI API 还处于测试阶段,您需要使用自己的 API key。` +
|
||||
`创建 OpenAI 账户,充值至少 5 美元,生成 API key,` +
|
||||
`然后就可以在 Excalidraw 中配置并使用 AI。`,
|
||||
`然后就可以在 Excalidraw 中配置并使用 AI。` +
|
||||
`这些设置会被 ExcalidrawAutomate、Mermaid chat 和 diagram-to-code 共用。大多数情况下,您只需要设置提供商、API key 和默认模型。除非您的提供商要求自定义 URL,否则请将各 endpoint 覆盖项留空。旧的 OpenAI 专用 AI 设置会在首次运行时自动迁移到这里。`,
|
||||
AI_ENABLED_NAME: "启用 AI 功能",
|
||||
AI_ENABLED_DESC: "您需要重新打开 Excalidraw 才能使更改生效。",
|
||||
AI_OPENAI_TOKEN_NAME: "OpenAI API key",
|
||||
AI_OPENAI_TOKEN_DESC:
|
||||
"您可以访问您的 <a href='https://platform.openai.com/api-keys'>OpenAI 账户</a> 来获取自己的 OpenAI API key。",
|
||||
AI_OPENAI_TOKEN_PLACEHOLDER: "OpenAI API key",
|
||||
AI_OPENAI_DEFAULT_MODEL_NAME: "默认的文本 AI 模型",
|
||||
AI_OPENAI_DEFAULT_MODEL_DESC:
|
||||
"使用哪个 AI 模型来生成文本。请填写有效的 OpenAI 模型名称。" +
|
||||
"您可访问 <a href='https://platform.openai.com/docs/models'>OpenAI 网站</a> 了解更多模型信息。",
|
||||
AI_OPENAI_DEFAULT_MODEL_PLACEHOLDER: "gpt-5-mini",
|
||||
AI_OPENAI_DEFAULT_MAX_TOKENS_NAME: "最大 token 数",
|
||||
AI_OPENAI_DEFAULT_MAX_TOKENS_DESC:
|
||||
"API 响应中生成的最大 token 数。设置为 0 以忽略 max_tokens 字段(适用于不支持该参数的模型,如 GPT-5)。",
|
||||
AI_OPENAI_DEFAULT_IMAGE_MODEL_NAME: "默认的图片 AI 模型",
|
||||
AI_OPENAI_DEFAULT_IMAGE_MODEL_DESC:
|
||||
"使用哪个 AI 模型来生成图片。图生图目前只有 dall-e-2 和 gpt-image-1 模型支持 Image editing and variations。" +
|
||||
"请填写有效的 OpenAI 模型名称。" +
|
||||
"您可访问 <a href='https://platform.openai.com/docs/models'>OpenAI 网站</a> 了解更多模型信息。",
|
||||
AI_OPENAI_DEFAULT_IMAGE_MODEL_PLACEHOLDER: "gpt-image-1",
|
||||
AI_OPENAI_DEFAULT_VISION_MODEL_NAME: "默认的 AI 视觉模型",
|
||||
AI_OPENAI_DEFAULT_VISION_MODEL_DESC:
|
||||
"根据文本生成图片时,使用哪个 AI 视觉模型。请填写有效的 OpenAI 模型名称。" +
|
||||
"您可访问 <a href='https://platform.openai.com/docs/models'>OpenAI 网站</a> 了解更多模型信息。",
|
||||
AI_OPENAI_DEFAULT_API_URL_NAME: "OpenAI API URL",
|
||||
AI_OPENAI_DEFAULT_API_URL_DESC:
|
||||
"默认的 OpenAI API URL。请填写有效的 OpenAI API URL。" +
|
||||
"Excalidraw 会通过该 URL 发送 API 请求给 OpenAI。我没有对该项做任何错误处理,请谨慎修改。",
|
||||
AI_OPENAI_DEFAULT_IMAGE_API_URL_NAME: "OpenAI 图片生成 API URL",
|
||||
AI_OPENAI_DEFAULT_VISION_MODEL_PLACEHOLDER: "输入默认 AI 模型名称,如 gpt-5-mini",
|
||||
AI_VERBOSE_LOGGING_NAME: "启用详细 AI 日志",
|
||||
AI_VERBOSE_LOGGING_DESC: "将详细的 AI 请求和响应诊断信息写入开发者控制台。除非您正在排查问题,否则请保持关闭。",
|
||||
AI_PROVIDER_NAME: "定义可用提供商",
|
||||
AI_PROVIDER_DESC:
|
||||
"定义下方模型列表可用的提供商配置。文本、视觉和图像模型各自独立选择提供商。",
|
||||
AI_PROVIDER_PROFILE_ROW_DESC:
|
||||
"类型:{{providerType}}<br>API:{{apiKey}}",
|
||||
AI_PROVIDER_OPTION_OPENAI: "OpenAI",
|
||||
AI_PROVIDER_OPTION_ANTHROPIC: "Anthropic / Claude",
|
||||
AI_PROVIDER_OPTION_GOOGLE: "Google / Gemini",
|
||||
AI_PROVIDER_OPTION_XAI: "xAI / Grok",
|
||||
AI_PROVIDER_OPTION_OPENAI_COMPATIBLE: "OpenAI 兼容 / 本地",
|
||||
AI_PROVIDER_PROFILE_MODAL_OPENAI_COMPATIBLE_HINT:
|
||||
"对于本地的 OpenAI 兼容 LLM,如果不需要真实 API key,请填写一个虚拟 key,否则 Excalidraw 不会把该配置识别为已配置。",
|
||||
AI_PROVIDER_BASE_URL_EMPTY: "由提供商类型推导",
|
||||
AI_PROVIDER_API_KEY_SET: "已配置",
|
||||
AI_PROVIDER_API_KEY_NOT_SET: "未配置",
|
||||
AI_PROVIDER_EDIT: "编辑提供商",
|
||||
AI_PROVIDER_ADD: "添加提供商",
|
||||
AI_PROVIDER_REMOVE: "删除提供商",
|
||||
AI_PROVIDER_RESTORE_DEFAULTS: "恢复默认提供商",
|
||||
AI_PROVIDER_API_KEY_NAME: "AI API key",
|
||||
AI_PROVIDER_API_KEY_DESC:
|
||||
"共享 AI 层使用的主 API key。除非输入框获得焦点,否则该值会被隐藏。",
|
||||
AI_PROVIDER_API_KEY_PLACEHOLDER: "提供商 API key",
|
||||
AI_PROVIDER_BASE_URL_NAME: "AI 基础 URL",
|
||||
AI_PROVIDER_BASE_URL_DESC:
|
||||
"可选的提供商基础 URL。可用于本地 OpenAI 兼容服务器或自托管网关。您既可以填写类似 https://api.openai.com/v1 的基础 URL,也可以填写类似 https://api.openai.com/v1/chat/completions 的完整聊天 endpoint;Excalidraw 会自动规范化已知的 OpenAI 风格 endpoint。",
|
||||
AI_PROVIDER_BASE_URL_PLACEHOLDER: "例如:https://api.openai.com/v1",
|
||||
AI_PROVIDER_TEXT_ENDPOINT_NAME: "AI 文本 endpoint 覆盖",
|
||||
AI_PROVIDER_TEXT_ENDPOINT_DESC:
|
||||
"可选的完整 endpoint 覆盖,用于文本和多模态请求。留空时会根据基础 URL 和提供商自动推导。大多数用户无需填写。",
|
||||
AI_PROVIDER_TEXT_ENDPOINT_PLACEHOLDER: "可选的完整文本 endpoint",
|
||||
AI_PROVIDER_IMAGE_GENERATION_ENDPOINT_NAME: "AI 图像生成 endpoint 覆盖",
|
||||
AI_PROVIDER_IMAGE_GENERATION_ENDPOINT_DESC:
|
||||
"可选的完整 endpoint 覆盖,用于图像生成请求。除非您的提供商使用非标准路径,否则请留空。",
|
||||
AI_PROVIDER_IMAGE_GENERATION_ENDPOINT_PLACEHOLDER: "可选的完整图像生成 endpoint",
|
||||
AI_PROVIDER_IMAGE_EDITS_ENDPOINT_NAME: "AI 图像编辑 endpoint 覆盖",
|
||||
AI_PROVIDER_IMAGE_EDITS_ENDPOINT_DESC:
|
||||
"可选的完整 endpoint 覆盖,用于图像编辑请求。除非您的提供商使用非标准路径,否则请留空。",
|
||||
AI_PROVIDER_IMAGE_EDITS_ENDPOINT_PLACEHOLDER: "可选的完整图像编辑 endpoint",
|
||||
AI_PROVIDER_IMAGE_VARIATIONS_ENDPOINT_NAME: "AI 图像变体 endpoint 覆盖",
|
||||
AI_PROVIDER_IMAGE_VARIATIONS_ENDPOINT_DESC:
|
||||
"可选的完整 endpoint 覆盖,用于图像变体请求。除非您的提供商使用非标准路径,否则请留空。",
|
||||
AI_PROVIDER_IMAGE_VARIATIONS_ENDPOINT_PLACEHOLDER: "可选的完整图像变体 endpoint",
|
||||
AI_PROVIDER_DEFAULT_TEXT_MODEL_NAME: "文本与多模态模型",
|
||||
AI_PROVIDER_DEFAULT_TEXT_MODEL_DESC:
|
||||
"用于文本聊天和图像理解请求的模型,例如 Mermaid chat、diagram-to-code 和线框图分析。<br>提供商:{{provider}}({{providerType}})<br>API key:{{apiKey}}<br>模型名称:{{model}}<br>Endpoint:{{endpoint}}<br>多模态支持:{{multimodalSupport}}",
|
||||
AI_PROVIDER_DEFAULT_TEXT_MODEL_PLACEHOLDER: "例如:gpt-5-mini、claude-sonnet、gemini-2.5-pro",
|
||||
AI_PROVIDER_DEFAULT_VISION_MODEL_NAME: "视觉模型",
|
||||
AI_PROVIDER_DEFAULT_VISION_MODEL_DESC:
|
||||
"用于 diagram-to-code 或图文混合提示等图像理解任务的模型。<br>提供商:{{provider}}({{providerType}})<br>API key:{{apiKey}}<br>模型名称:{{model}}<br>Endpoint:{{endpoint}}",
|
||||
AI_PROVIDER_DEFAULT_VISION_MODEL_PLACEHOLDER: "例如:gpt-5-mini、claude-sonnet、gemini-2.5-flash",
|
||||
AI_PROVIDER_DEFAULT_IMAGE_MODEL_NAME: "图像模型",
|
||||
AI_PROVIDER_DEFAULT_IMAGE_MODEL_DESC:
|
||||
"用于图像生成、基于提示词的图像变换和蒙版编辑的模型。使用“编辑”“添加”“删除”按钮修改列表。<br>提供商:{{provider}}({{providerType}})<br>API key:{{apiKey}}<br>模型名称:{{model}}<br>支持的分辨率:{{sizes}}<br>提示词图像变换:{{supportsPromptImageTransforms}}<br>蒙版编辑:{{supportsMaskImageEdits}}",
|
||||
AI_PROVIDER_DEFAULT_IMAGE_MODEL_PLACEHOLDER: "例如:gpt-image-1",
|
||||
AI_MODEL_CONFIG_DERIVED_ENDPOINT: "由所选提供商推导",
|
||||
AI_MODEL_EDIT: "编辑模型",
|
||||
AI_MODEL_ADD: "添加模型",
|
||||
AI_MODEL_REMOVE: "删除模型",
|
||||
AI_MODEL_RESTORE_DEFAULTS: "恢复默认模型",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_NAME: "图像模型能力",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_DESC:
|
||||
"在这里管理图像模型元数据,例如支持的分辨率、是否支持提示词图像变换以及是否支持蒙版编辑。例如,你可以在 <a href=\"https://platform.openai.com/docs/guides/image-generation\" target=\"_blank\" rel=\"noopener noreferrer\">OpenAI 图像生成文档</a> 中查询支持的尺寸。",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_LOAD_DEFAULTS: "恢复已知默认值",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_ADD_MODEL: "添加",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_EDIT_MODEL: "编辑",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_REMOVE_MODEL: "删除条目",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_CURRENT_ENTRY_NAME: "当前选中的模型条目",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_CURRENT_ENTRY_DESC:
|
||||
"<b>{{model}}</b><br>支持的分辨率:{{sizes}}<br>提示词图像变换:{{supportsPromptImageTransforms}}<br>蒙版编辑:{{supportsMaskImageEdits}}",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_SIZES_NAME: "支持的分辨率",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_SIZES_PLACEHOLDER: "1024x1024, 1536x1024, 1024x1536",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_EDITS_NAME: "支持图像编辑",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_EDITS_DESC:
|
||||
"如果该模型只能生成图像但不支持图像编辑或蒙版,请关闭此项。",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_TRANSFORMS_NAME: "提示词图像变换",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_TRANSFORMS_DESC:
|
||||
"当模型支持使用输入图像加文本提示词进行无蒙版编辑时,请启用此项。",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_MASK_EDITS_NAME: "蒙版图像编辑",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_MASK_EDITS_DESC:
|
||||
"当模型支持使用蒙版替换输入图像的局部区域时,请启用此项。",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_EDITS_YES: "是",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_EDITS_NO: "否",
|
||||
AI_IMAGE_MODEL_CAPABILITY_MODAL_ADD_TITLE: "添加图像模型条目",
|
||||
AI_IMAGE_MODEL_CAPABILITY_MODAL_EDIT_TITLE: "编辑图像模型条目",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_MODAL_MODEL_NAME: "模型 ID",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_MODAL_MODEL_DESC:
|
||||
"使用提供商暴露的精确模型名称。",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_MODAL_MODEL_PLACEHOLDER: "例如:gpt-image-2",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_MODAL_SIZES_DESC:
|
||||
"每行添加一个支持的分辨率。",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_MODAL_SIZE_LABEL: "分辨率",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_MODAL_ADD_SIZE: "添加分辨率",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_MODAL_REMOVE_SIZE: "删除",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_MODAL_MODEL_REQUIRED: "必须填写模型 ID。",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_MODAL_SIZE_REQUIRED: "至少添加一个支持的分辨率。",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_MODAL_DUPLICATE_MODEL: "该模型 ID 已存在条目。",
|
||||
AI_MODEL_CONFIG_MODAL_MULTIMODAL_NAME: "多模态支持",
|
||||
AI_MODEL_CONFIG_MODAL_MULTIMODAL_DESC: "允许该文本模型接收图像输入,用于分析和 diagram-to-code 类任务。",
|
||||
AI_PROVIDER_DEFAULT_MAX_OUTGOING_TOKENS_NAME: "AI 默认输出 token 预算",
|
||||
AI_PROVIDER_DEFAULT_MAX_OUTGOING_TOKENS_DESC:
|
||||
"AIRequest.maxOutgoingTokens 的默认值。Excalidraw 会将其作为发送文本的近似预算,并优先裁剪较长的提示词或较早的聊天历史。它也可能影响图像请求中附带发送的文本。",
|
||||
AI_PROVIDER_DEFAULT_MAX_OUTGOING_TOKENS_PLACEHOLDER: "例如:8000",
|
||||
AI_PROVIDER_DEFAULT_MAX_RESPONSE_TOKENS_NAME: "AI 默认响应 token 上限",
|
||||
AI_PROVIDER_DEFAULT_MAX_RESPONSE_TOKENS_DESC:
|
||||
"AIRequest.maxTokens 的默认值。它限制模型返回的文本或多模态响应,不影响直接图像生成或图像编辑 endpoint。",
|
||||
AI_PROVIDER_DEFAULT_MAX_RESPONSE_TOKENS_PLACEHOLDER: "例如:4096",
|
||||
SAVING_HEAD: "保存",
|
||||
SAVING_DESC: "包括:压缩,自动保存的时间间隔,文件的命名格式和扩展名等。",
|
||||
COMPRESS_NAME: "压缩 Excalidraw JSON",
|
||||
@@ -426,6 +514,8 @@ export default {
|
||||
DEFAULT_OPEN_MODE_DESC:
|
||||
"设置 Excalidraw 的运行模式:普通模式(Normal)/禅模式(Zen)/查看模式(View)。<br>" +
|
||||
"可为某个绘图单独设置,方法是在其 frontmatter 中添加如 <code>excalidraw-default-mode: normal/zen/view</code> 的键值对。",
|
||||
PHONE_FOOTER_SAFE_AREA_PADDING_NAME: "为手机端底部控件增加额外留白",
|
||||
PHONE_FOOTER_SAFE_AREA_PADDING_DESC: "为 Excalidraw 底部控件增加额外底部留白,让缩放和撤销按钮在手机上保持位于系统导航栏之上。该设置仅在手机上生效。",
|
||||
DEFAULT_PEN_MODE_NAME: "触控笔模式(Pen mode)",
|
||||
DEFAULT_PEN_MODE_DESC:
|
||||
"打开绘图时,是否自动开启触控笔模式?",
|
||||
@@ -684,6 +774,13 @@ export default {
|
||||
RENDERING_CONCURRENCY_DESC:
|
||||
"用于图像渲染的并行工作线程数。增加该值可以加快渲染速度,但可能会减慢系统其他部分的运行速度。" +
|
||||
"默认值为 3。如果您的系统性能强大,可以增加该值。",
|
||||
IMAGE_CACHE_RETENTION_DAYS_NAME: "本地图像缓存保留时间",
|
||||
IMAGE_CACHE_RETENTION_DAYS_DESC:
|
||||
"设置 Excalidraw 在清理未使用缓存前,保留本地已渲染资源(如嵌套 Excalidraw 图像和 PDF 页面)的天数。" +
|
||||
"缓存项在被读取时会刷新其保留时间。<br><br>" +
|
||||
"这只影响当前设备上 Excalidraw 的本地 缓存。它<b>不会</b>改变您的库体积、附件文件或同步数据量。" +
|
||||
"实际影响的是 Obsidian 内部本地磁盘或浏览器存储占用。在手机以及浏览器存储配额较紧或剩余磁盘空间有限的桌面设备上,这一点可能尤其重要。<br><br>" +
|
||||
"较小的值会更快回收本地缓存空间,但可能导致 PDF 和嵌入绘图需要更频繁地重新渲染。较大的值会保留更久的缓存,以换取更快的加载速度。",
|
||||
EXPORT_SUBHEAD: "导出",
|
||||
EMBED_SIZING: "图像尺寸",
|
||||
EMBED_THEME_BACKGROUND: "图像的主题和背景色",
|
||||
@@ -846,6 +943,15 @@ export default {
|
||||
FIELD_SUGGESTER_DESC:
|
||||
"开启后,当您在编辑器中输入 <code>excalidraw-</code> 或者 <code>ea.</code> 时,会弹出一个带有函数说明的自动补全提示菜单。<br>" +
|
||||
"该功能借鉴了 Breadcrumbs 和 Templater 插件。",
|
||||
ENABLE_ONLOAD_SCRIPTS_NAME: "启用 onload 脚本",
|
||||
ENABLE_ONLOAD_SCRIPTS_CONFIRMATION:
|
||||
"此文件包含 <code>excalidraw-onload-script</code>。是否启用 onload 脚本?",
|
||||
ENABLE_ONLOAD_SCRIPTS_CONFIRM_ENABLE: "启用脚本",
|
||||
ENABLE_ONLOAD_SCRIPTS_CONFIRM_DENY: "不允许",
|
||||
ENABLE_ONLOAD_SCRIPTS_DESC:
|
||||
"启用后,Excalidraw 会在你之后打开的所有绘图中执行文件级别的 <code>excalidraw-onload-script</code>,直到你关闭此设置。 " +
|
||||
"如果你从未知来源下载 Markdown 文件,这会带来风险:恶意行为者可以利用 <code>excalidraw-onload-script</code> " +
|
||||
"在 Obsidian 中运行任意命令,并且有可能将数据传输到互联网。只有在你信任该文件及其来源时才启用此功能。",
|
||||
STARTUP_SCRIPT_NAME: "起动脚本",
|
||||
STARTUP_SCRIPT_DESC:
|
||||
"插件启动时将自动执行该脚本。可用于为您的 Excalidraw 自动化脚本设置钩子。" +
|
||||
@@ -1226,6 +1332,25 @@ export default {
|
||||
|
||||
//ReleaseNotes.ts
|
||||
RN_WELCOME: "欢迎使用 Excalidraw",
|
||||
FIRST_RUN: `
|
||||
Obsidian 的 Excalidraw 插件远不只是一个“画图工具”。由于它与 Obsidian 深度集成,它为可视化个人知识管理带来了全新的工作范式。
|
||||
|
||||
<div style="text-align:center;margin-top:10px;">
|
||||
<a href="https://community.sketch-your-mind.com/ee" target="_blank"><img src="https://sketch-your-mind.com/images/logo-EE.png" style="width:50%;"></a>
|
||||
</div>
|
||||
|
||||
如果你想顺利入门、避免一开始就被大量功能淹没,我非常推荐免费的 **[Excalidraw Essentials](https://community.sketch-your-mind.com/ee)** 微课程。它能帮你快速抓住重点,用清晰的结构掌握核心基础。
|
||||
|
||||
你也不必独自摸索。欢迎加入 **[Sketch Your Mind 社区](https://community.sketch-your-mind.com)**,与其他视觉思考者交流、分享工作流,一起构建更顺滑的 PKM 系统。
|
||||
|
||||
如果你想先看看它现在都能做到什么,下面有一个核心功能展示。想持续了解最新更新,并进一步探索 Visual PKM,也欢迎订阅我的 YouTube 频道:[Visual PKM](https://www.youtube.com/@visualPKM)。
|
||||
|
||||
感谢使用,祝你玩得开心!
|
||||
|
||||
<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>
|
||||
`,
|
||||
|
||||
//Excalidraw component
|
||||
COMP_IMG: "图片 & 文件",
|
||||
|
||||
+159
-34
@@ -1,10 +1,10 @@
|
||||
import {
|
||||
DEVICE,
|
||||
FRONTMATTER_KEYS,
|
||||
CJK_FONTS,
|
||||
DEVICE,
|
||||
FRONTMATTER_KEYS,
|
||||
CJK_FONTS,
|
||||
} from "src/constants/constants";
|
||||
import { TAG_AUTOEXPORT, TAG_MDREADINGMODE, TAG_PDFEXPORT } from "src/constants/constSettingsTags";
|
||||
import { labelALT, labelCTRL, labelMETA, labelSHIFT } from "src/utils/modifierKeyLabels";
|
||||
import { TAG_AUTOEXPORT,TAG_MDREADINGMODE,TAG_PDFEXPORT } from "src/constants/constSettingsTags";
|
||||
import { labelCTRL,labelMETA,labelSHIFT } from "src/utils/modifierKeyLabels";
|
||||
|
||||
declare const PLUGIN_VERSION:string;
|
||||
|
||||
@@ -97,6 +97,7 @@ export default {
|
||||
ENTER_LATEX: "輸入 LaTeX 公式",
|
||||
EDIT_LATEX: "編輯 LaTeX 公式",
|
||||
READ_RELEASE_NOTES: "閱讀本外掛的更新說明",
|
||||
ABOUT_EXCALIDRAW: "關於 Excalidraw",
|
||||
RUN_OCR: "OCR 整個繪圖:識別塗鴉和圖片裡的文字並複製到剪貼簿和筆記屬性中",
|
||||
RERUN_OCR: "重新 OCR 整個繪圖:識別塗鴉和圖片裡的文字並複製到剪貼簿和筆記屬性中",
|
||||
RUN_OCR_ELEMENTS: "OCR 選中的元素:識別塗鴉和圖片裡的文字並複製到剪貼簿",
|
||||
@@ -110,6 +111,7 @@ export default {
|
||||
RESET_IMG_ASPECT_RATIO: "重置所選影像的縱橫比",
|
||||
TEMPORARY_DISABLE_AUTOSAVE: "臨時停用自動儲存功能,直到本次 Obsidian 退出(小白慎用!)",
|
||||
TEMPORARY_ENABLE_AUTOSAVE: "啟用自動儲存功能",
|
||||
TEMPORARY_TOGGLE_VIEW_MODE_FOR_ALL_DRAWINGS: "切換所有 Excalidraw 繪圖的檢視模式,直到本次 Obsidian 退出",
|
||||
FONTS_LOADED: "Excalidraw: CJK 字型已載入",
|
||||
FONTS_LOAD_ERROR: "Excalidraw: 在資原始檔夾下找不到 CJK 字型\n",
|
||||
TOGGLE_ENABLE_CONTEXT_MENU: "切換是否啟用上下文選單(在移動裝置上很有用)",
|
||||
@@ -221,6 +223,10 @@ export default {
|
||||
DISABLE_CONTEXT_MENU_DESC: "停用 Excalidraw 的上下文選單。這在移動裝置上很有用,因為上下文選單有時會在不需要的時候彈出。",
|
||||
NOTEBOOKLM_LINK_ARIA: "向 NotebookLM 諮詢有關外掛的幫助。此模型已預載入了我所有的影片轉錄稿、釋出說明和其他幫助內容。與 NotebookLM 聊天,瀏覽我的 250+ 影片和 Excalidraw 檔案。",
|
||||
NOTEBOOKLM_LINK_TEXT: "學習外掛。訪問 NotebookLM 知識庫。",
|
||||
EXCALIDRAW_MASTERY_PROMO_ARIA: "開啟 Excalidraw Mastery",
|
||||
EXCALIDRAW_MASTERY_PROMO_HTML: `<p><b>在各種切換與選單中感到迷失嗎?</b></p><p>Excalidraw 是為高強度工作流程打造的 Visual PKM 強大工具,適合 <b>Visual-First Daily Notes</b>、深入的 <b>PDF 研究</b>、<b>自動化</b>、<b>AI 整合</b> 與 <b>Visual Zettelkasten</b>。但這些強大功能也伴隨著複雜度。</p><p>跳過反覆試錯。<a href="https://community.sketch-your-mind.com/em" target="_blank">👉 加入 Excalidraw Mastery</a>,一步一步學會這些具體設定。降低工具摩擦,並與一群擅長視覺思考的支持型社群一起掌握你的知識系統。</p>`,
|
||||
EXCALIDRAW_MASTERY_PROMO_SHOW: "顯示",
|
||||
EXCALIDRAW_MASTERY_PROMO_HIDE: "隱藏",
|
||||
LINKS_BUGS_ARIA: "在外掛的 GitHub 頁面報告錯誤和提交功能請求",
|
||||
LINKS_BUGS: "報告錯誤",
|
||||
LINKS_YT_ARIA: "訪問我的 YouTube 頻道學習視覺思維和 Excalidraw",
|
||||
@@ -302,37 +308,119 @@ export default {
|
||||
AI_DESC: `OpenAI GPT API 的設定。` +
|
||||
`目前 OpenAI API 還處於測試階段,您需要使用自己的 API key。` +
|
||||
`建立 OpenAI 賬戶,充值至少 5 美元,生成 API key,` +
|
||||
`然後就可以在 Excalidraw 中配置並使用 AI。`,
|
||||
`然後就可以在 Excalidraw 中配置並使用 AI。` +
|
||||
`這些設定會被 ExcalidrawAutomate、Mermaid chat 和 diagram-to-code 共用。大多數情況下,您只需要設定供應商、API key 和預設模型。除非您的供應商要求自訂 URL,否則請將各 endpoint 覆寫欄位留空。舊的 OpenAI 專用 AI 設定會在首次執行時自動遷移到這裡。`,
|
||||
AI_ENABLED_NAME: "啟用 AI 功能",
|
||||
AI_ENABLED_DESC: "您需要重新開啟 Excalidraw 才能使更改生效。",
|
||||
AI_OPENAI_TOKEN_NAME: "OpenAI API key",
|
||||
AI_OPENAI_TOKEN_DESC:
|
||||
"您可以訪問您的 <a href='https://platform.openai.com/api-keys'>OpenAI 賬戶</a> 來獲取自己的 OpenAI API key。",
|
||||
AI_OPENAI_TOKEN_PLACEHOLDER: "OpenAI API key",
|
||||
AI_OPENAI_DEFAULT_MODEL_NAME: "預設的文字 AI 模型",
|
||||
AI_OPENAI_DEFAULT_MODEL_DESC:
|
||||
"使用哪個 AI 模型來生成文字。請填寫有效的 OpenAI 模型名稱。" +
|
||||
"您可訪問 <a href='https://platform.openai.com/docs/models'>OpenAI 網站</a> 瞭解更多模型資訊。",
|
||||
AI_OPENAI_DEFAULT_MODEL_PLACEHOLDER: "gpt-5-mini",
|
||||
AI_OPENAI_DEFAULT_MAX_TOKENS_NAME: "最大 token 數",
|
||||
AI_OPENAI_DEFAULT_MAX_TOKENS_DESC:
|
||||
"API 響應中生成的最大 token 數。設定為 0 以忽略 max_tokens 欄位(適用於不支援該引數的模型,如 GPT-5)。",
|
||||
AI_OPENAI_DEFAULT_IMAGE_MODEL_NAME: "預設的圖片 AI 模型",
|
||||
AI_OPENAI_DEFAULT_IMAGE_MODEL_DESC:
|
||||
"使用哪個 AI 模型來生成圖片。圖生圖目前只有 dall-e-2 和 gpt-image-1 模型支援 Image editing and variations。" +
|
||||
"請填寫有效的 OpenAI 模型名稱。" +
|
||||
"您可訪問 <a href='https://platform.openai.com/docs/models'>OpenAI 網站</a> 瞭解更多模型資訊。",
|
||||
AI_OPENAI_DEFAULT_IMAGE_MODEL_PLACEHOLDER: "gpt-image-1",
|
||||
AI_OPENAI_DEFAULT_VISION_MODEL_NAME: "預設的 AI 視覺模型",
|
||||
AI_OPENAI_DEFAULT_VISION_MODEL_DESC:
|
||||
"根據文字生成圖片時,使用哪個 AI 視覺模型。請填寫有效的 OpenAI 模型名稱。" +
|
||||
"您可訪問 <a href='https://platform.openai.com/docs/models'>OpenAI 網站</a> 瞭解更多模型資訊。",
|
||||
AI_OPENAI_DEFAULT_API_URL_NAME: "OpenAI API URL",
|
||||
AI_OPENAI_DEFAULT_API_URL_DESC:
|
||||
"預設的 OpenAI API URL。請填寫有效的 OpenAI API URL。" +
|
||||
"Excalidraw 會透過該 URL 傳送 API 請求給 OpenAI。我沒有對該項做任何錯誤處理,請謹慎修改。",
|
||||
AI_OPENAI_DEFAULT_IMAGE_API_URL_NAME: "OpenAI 圖片生成 API URL",
|
||||
AI_OPENAI_DEFAULT_VISION_MODEL_PLACEHOLDER: "輸入預設 AI 模型名稱,如 gpt-5-mini",
|
||||
AI_VERBOSE_LOGGING_NAME: "啟用詳細 AI 日誌",
|
||||
AI_VERBOSE_LOGGING_DESC: "將詳細的 AI 請求與回應診斷資訊寫入開發者主控台。除非您正在排查問題,否則請保持關閉。",
|
||||
AI_PROVIDER_NAME: "定義可用供應商",
|
||||
AI_PROVIDER_DESC:
|
||||
"定義下方模型清單可用的供應商設定。文字、視覺與圖像模型各自獨立選擇供應商。",
|
||||
AI_PROVIDER_PROFILE_ROW_DESC:
|
||||
"類型:{{providerType}}<br>API:{{apiKey}}",
|
||||
AI_PROVIDER_OPTION_OPENAI: "OpenAI",
|
||||
AI_PROVIDER_OPTION_ANTHROPIC: "Anthropic / Claude",
|
||||
AI_PROVIDER_OPTION_GOOGLE: "Google / Gemini",
|
||||
AI_PROVIDER_OPTION_XAI: "xAI / Grok",
|
||||
AI_PROVIDER_OPTION_OPENAI_COMPATIBLE: "OpenAI 相容 / 本地",
|
||||
AI_PROVIDER_PROFILE_MODAL_OPENAI_COMPATIBLE_HINT:
|
||||
"對於本機的 OpenAI 相容 LLM,如果不需要真正的 API key,請填入一個虛擬 key,否則 Excalidraw 不會將此設定識別為已設定。",
|
||||
AI_PROVIDER_BASE_URL_EMPTY: "由供應商類型推導",
|
||||
AI_PROVIDER_API_KEY_SET: "已設定",
|
||||
AI_PROVIDER_API_KEY_NOT_SET: "未設定",
|
||||
AI_PROVIDER_EDIT: "編輯供應商",
|
||||
AI_PROVIDER_ADD: "新增供應商",
|
||||
AI_PROVIDER_REMOVE: "刪除供應商",
|
||||
AI_PROVIDER_RESTORE_DEFAULTS: "還原預設供應商",
|
||||
AI_PROVIDER_API_KEY_NAME: "AI API key",
|
||||
AI_PROVIDER_API_KEY_DESC:
|
||||
"共享 AI 層使用的主要 API key。除非輸入欄位取得焦點,否則該值會被隱藏。",
|
||||
AI_PROVIDER_API_KEY_PLACEHOLDER: "供應商 API key",
|
||||
AI_PROVIDER_BASE_URL_NAME: "AI 基礎 URL",
|
||||
AI_PROVIDER_BASE_URL_DESC:
|
||||
"可選的供應商基礎 URL。可用於本地 OpenAI 相容伺服器或自架閘道。您可以填入像 https://api.openai.com/v1 這樣的基礎 URL,也可以填入像 https://api.openai.com/v1/chat/completions 這樣的完整聊天 endpoint;Excalidraw 會自動正規化已知的 OpenAI 風格 endpoint。",
|
||||
AI_PROVIDER_BASE_URL_PLACEHOLDER: "例如:https://api.openai.com/v1",
|
||||
AI_PROVIDER_TEXT_ENDPOINT_NAME: "AI 文字 endpoint 覆寫",
|
||||
AI_PROVIDER_TEXT_ENDPOINT_DESC:
|
||||
"可選的完整 endpoint 覆寫,用於文字與多模態請求。留空時會根據基礎 URL 和供應商自動推導。大多數使用者不需要填寫。",
|
||||
AI_PROVIDER_TEXT_ENDPOINT_PLACEHOLDER: "可選的完整文字 endpoint",
|
||||
AI_PROVIDER_IMAGE_GENERATION_ENDPOINT_NAME: "AI 圖像生成 endpoint 覆寫",
|
||||
AI_PROVIDER_IMAGE_GENERATION_ENDPOINT_DESC:
|
||||
"可選的完整 endpoint 覆寫,用於圖像生成請求。除非您的供應商使用非標準路徑,否則請留空。",
|
||||
AI_PROVIDER_IMAGE_GENERATION_ENDPOINT_PLACEHOLDER: "可選的完整圖像生成 endpoint",
|
||||
AI_PROVIDER_IMAGE_EDITS_ENDPOINT_NAME: "AI 圖像編輯 endpoint 覆寫",
|
||||
AI_PROVIDER_IMAGE_EDITS_ENDPOINT_DESC:
|
||||
"可選的完整 endpoint 覆寫,用於圖像編輯請求。除非您的供應商使用非標準路徑,否則請留空。",
|
||||
AI_PROVIDER_IMAGE_EDITS_ENDPOINT_PLACEHOLDER: "可選的完整圖像編輯 endpoint",
|
||||
AI_PROVIDER_IMAGE_VARIATIONS_ENDPOINT_NAME: "AI 圖像變體 endpoint 覆寫",
|
||||
AI_PROVIDER_IMAGE_VARIATIONS_ENDPOINT_DESC:
|
||||
"可選的完整 endpoint 覆寫,用於圖像變體請求。除非您的供應商使用非標準路徑,否則請留空。",
|
||||
AI_PROVIDER_IMAGE_VARIATIONS_ENDPOINT_PLACEHOLDER: "可選的完整圖像變體 endpoint",
|
||||
AI_PROVIDER_DEFAULT_TEXT_MODEL_NAME: "文字與多模態模型",
|
||||
AI_PROVIDER_DEFAULT_TEXT_MODEL_DESC:
|
||||
"用於文字聊天與圖像理解請求的模型,例如 Mermaid chat、diagram-to-code 與線框圖分析。<br>供應商:{{provider}}({{providerType}})<br>API key:{{apiKey}}<br>模型名稱:{{model}}<br>Endpoint:{{endpoint}}<br>多模態支援:{{multimodalSupport}}",
|
||||
AI_PROVIDER_DEFAULT_TEXT_MODEL_PLACEHOLDER: "例如:gpt-5-mini、claude-sonnet、gemini-2.5-pro",
|
||||
AI_PROVIDER_DEFAULT_VISION_MODEL_NAME: "視覺模型",
|
||||
AI_PROVIDER_DEFAULT_VISION_MODEL_DESC:
|
||||
"用於 diagram-to-code 或圖文混合提示等圖像理解任務的模型。<br>供應商:{{provider}}({{providerType}})<br>API key:{{apiKey}}<br>模型名稱:{{model}}<br>Endpoint:{{endpoint}}",
|
||||
AI_PROVIDER_DEFAULT_VISION_MODEL_PLACEHOLDER: "例如:gpt-5-mini、claude-sonnet、gemini-2.5-flash",
|
||||
AI_PROVIDER_DEFAULT_IMAGE_MODEL_NAME: "圖像模型",
|
||||
AI_PROVIDER_DEFAULT_IMAGE_MODEL_DESC:
|
||||
"用於圖像生成、提示詞驅動的圖像轉換與遮罩編輯的模型。使用「編輯」、「新增」、「刪除」按鈕修改列表。<br>供應商:{{provider}}({{providerType}})<br>API key:{{apiKey}}<br>模型名稱:{{model}}<br>支援的解析度:{{sizes}}<br>提示詞圖像轉換:{{supportsPromptImageTransforms}}<br>遮罩編輯:{{supportsMaskImageEdits}}",
|
||||
AI_PROVIDER_DEFAULT_IMAGE_MODEL_PLACEHOLDER: "例如:gpt-image-1",
|
||||
AI_MODEL_CONFIG_DERIVED_ENDPOINT: "由所選供應商推導",
|
||||
AI_MODEL_EDIT: "編輯模型",
|
||||
AI_MODEL_ADD: "新增模型",
|
||||
AI_MODEL_REMOVE: "刪除模型",
|
||||
AI_MODEL_RESTORE_DEFAULTS: "還原預設模型",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_NAME: "圖像模型能力",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_DESC:
|
||||
"在這裡管理圖像模型中繼資料,例如支援的解析度、是否支援提示詞圖像轉換,以及是否支援遮罩編輯。舉例來說,你可以在 <a href=\"https://platform.openai.com/docs/guides/image-generation\" target=\"_blank\" rel=\"noopener noreferrer\">OpenAI 圖像生成文件</a> 中查詢支援的尺寸。",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_LOAD_DEFAULTS: "還原已知預設值",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_ADD_MODEL: "新增",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_EDIT_MODEL: "編輯",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_REMOVE_MODEL: "刪除項目",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_CURRENT_ENTRY_NAME: "目前選取的模型項目",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_CURRENT_ENTRY_DESC:
|
||||
"<b>{{model}}</b><br>支援的解析度:{{sizes}}<br>提示詞圖像轉換:{{supportsPromptImageTransforms}}<br>遮罩編輯:{{supportsMaskImageEdits}}",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_SIZES_NAME: "支援的解析度",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_SIZES_PLACEHOLDER: "1024x1024, 1536x1024, 1024x1536",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_EDITS_NAME: "支援圖像編輯",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_EDITS_DESC:
|
||||
"如果模型只能生成圖像但不支援圖像編輯或遮罩,請關閉此項。",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_TRANSFORMS_NAME: "提示詞圖像轉換",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_TRANSFORMS_DESC:
|
||||
"當模型支援使用輸入圖像與文字提示詞進行無遮罩編輯時,請啟用此項。",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_MASK_EDITS_NAME: "遮罩圖像編輯",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_MASK_EDITS_DESC:
|
||||
"當模型支援使用遮罩替換輸入圖像的局部區域時,請啟用此項。",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_EDITS_YES: "是",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_EDITS_NO: "否",
|
||||
AI_IMAGE_MODEL_CAPABILITY_MODAL_ADD_TITLE: "新增圖像模型項目",
|
||||
AI_IMAGE_MODEL_CAPABILITY_MODAL_EDIT_TITLE: "編輯圖像模型項目",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_MODAL_MODEL_NAME: "模型 ID",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_MODAL_MODEL_DESC:
|
||||
"使用供應商提供的精確模型名稱。",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_MODAL_MODEL_PLACEHOLDER: "例如:gpt-image-2",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_MODAL_SIZES_DESC:
|
||||
"每列新增一個支援的解析度。",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_MODAL_SIZE_LABEL: "解析度",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_MODAL_ADD_SIZE: "新增解析度",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_MODAL_REMOVE_SIZE: "刪除",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_MODAL_MODEL_REQUIRED: "必須填寫模型 ID。",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_MODAL_SIZE_REQUIRED: "至少新增一個支援的解析度。",
|
||||
AI_IMAGE_MODEL_CAPABILITIES_MODAL_DUPLICATE_MODEL: "此模型 ID 已存在項目。",
|
||||
AI_MODEL_CONFIG_MODAL_MULTIMODAL_NAME: "多模態支援",
|
||||
AI_MODEL_CONFIG_MODAL_MULTIMODAL_DESC: "允許此文字模型接收圖像輸入,用於分析與 diagram-to-code 類型任務。",
|
||||
AI_PROVIDER_DEFAULT_MAX_OUTGOING_TOKENS_NAME: "AI 預設輸出 token 預算",
|
||||
AI_PROVIDER_DEFAULT_MAX_OUTGOING_TOKENS_DESC:
|
||||
"AIRequest.maxOutgoingTokens 的預設值。Excalidraw 會將其作為送出文字的近似預算,並優先裁切較長提示詞或較舊的聊天記錄。它也可能影響圖像請求中附帶送出的文字。",
|
||||
AI_PROVIDER_DEFAULT_MAX_OUTGOING_TOKENS_PLACEHOLDER: "例如:8000",
|
||||
AI_PROVIDER_DEFAULT_MAX_RESPONSE_TOKENS_NAME: "AI 預設回應 token 上限",
|
||||
AI_PROVIDER_DEFAULT_MAX_RESPONSE_TOKENS_DESC:
|
||||
"AIRequest.maxTokens 的預設值。它限制模型回傳的文字或多模態回應,不影響直接圖像生成或圖像編輯 endpoint。",
|
||||
AI_PROVIDER_DEFAULT_MAX_RESPONSE_TOKENS_PLACEHOLDER: "例如:4096",
|
||||
SAVING_HEAD: "儲存",
|
||||
SAVING_DESC: "包括:壓縮,自動儲存的時間間隔,檔案的命名格式和副檔名等。",
|
||||
COMPRESS_NAME: "壓縮 Excalidraw JSON",
|
||||
@@ -426,6 +514,8 @@ export default {
|
||||
DEFAULT_OPEN_MODE_DESC:
|
||||
"設定 Excalidraw 的執行模式:普通模式(Normal)/禪模式(Zen)/檢視模式(View)。<br>" +
|
||||
"可為某個繪圖單獨設定,方法是在其 frontmatter 中新增如 <code>excalidraw-default-mode: normal/zen/view</code> 的鍵值對。",
|
||||
PHONE_FOOTER_SAFE_AREA_PADDING_NAME: "為手機端底部控制項增加額外留白",
|
||||
PHONE_FOOTER_SAFE_AREA_PADDING_DESC: "為 Excalidraw 底部控制項增加額外底部留白,讓縮放與復原按鈕在手機上保持位於系統導覽列之上。該設定僅在手機上生效。",
|
||||
DEFAULT_PEN_MODE_NAME: "觸控筆模式(Pen mode)",
|
||||
DEFAULT_PEN_MODE_DESC:
|
||||
"開啟繪圖時,是否自動開啟觸控筆模式?",
|
||||
@@ -684,6 +774,13 @@ export default {
|
||||
RENDERING_CONCURRENCY_DESC:
|
||||
"用於影像渲染的並行工作執行緒數。增加該值可以加快渲染速度,但可能會減慢系統其他部分的執行速度。" +
|
||||
"預設值為 3。如果您的系統性能強大,可以增加該值。",
|
||||
IMAGE_CACHE_RETENTION_DAYS_NAME: "本地影像快取保留時間",
|
||||
IMAGE_CACHE_RETENTION_DAYS_DESC:
|
||||
"設定 Excalidraw 在清理未使用快取之前,保留本地已渲染資源(例如巢狀 Excalidraw 影像與 PDF 頁面)的天數。" +
|
||||
"快取項目在被讀取時會更新其保留時間。<br><br>" +
|
||||
"這只影響目前裝置上的 Excalidraw 本地 快取。它<b>不會</b>改變您的 Vault 大小、附件檔案或同步資料量。" +
|
||||
"實際影響的是 Obsidian 內部使用的本機磁碟或瀏覽器儲存空間。在手機,以及瀏覽器儲存配額較緊或可用磁碟空間有限的桌面裝置上,這點可能特別重要。<br><br>" +
|
||||
"較小的值會更快回收本地快取空間,但可能讓 PDF 與嵌入繪圖更常重新渲染。較大的值則會保留較久的快取,以換取更快的載入速度。",
|
||||
EXPORT_SUBHEAD: "匯出",
|
||||
EMBED_SIZING: "影像尺寸",
|
||||
EMBED_THEME_BACKGROUND: "影像的主題和背景色",
|
||||
@@ -846,6 +943,15 @@ export default {
|
||||
FIELD_SUGGESTER_DESC:
|
||||
"開啟後,當您在編輯器中輸入 <code>excalidraw-</code> 或者 <code>ea.</code> 時,會彈出一個帶有函式說明的自動補全提示選單。<br>" +
|
||||
"該功能借鑑了 Breadcrumbs 和 Templater 外掛。",
|
||||
ENABLE_ONLOAD_SCRIPTS_NAME: "啟用 onload 腳本",
|
||||
ENABLE_ONLOAD_SCRIPTS_CONFIRMATION:
|
||||
"此檔案包含 <code>excalidraw-onload-script</code>。是否啟用 onload 腳本?",
|
||||
ENABLE_ONLOAD_SCRIPTS_CONFIRM_ENABLE: "啟用腳本",
|
||||
ENABLE_ONLOAD_SCRIPTS_CONFIRM_DENY: "不允許",
|
||||
ENABLE_ONLOAD_SCRIPTS_DESC:
|
||||
"啟用後,Excalidraw 會在你之後開啟的所有繪圖中執行檔案層級的 <code>excalidraw-onload-script</code>,直到你關閉此設定。 " +
|
||||
"如果你從未知來源下載 Markdown 檔案,這會帶來風險:惡意人士可以使用 <code>excalidraw-onload-script</code> " +
|
||||
"在 Obsidian 中執行任何命令,並且有可能將資料傳送到網際網路。只有在你信任該檔案及其來源時才啟用此功能。",
|
||||
STARTUP_SCRIPT_NAME: "起動指令碼",
|
||||
STARTUP_SCRIPT_DESC:
|
||||
"外掛啟動時將自動執行該指令碼。可用於為您的 Excalidraw 自動化指令碼設定鉤子。" +
|
||||
@@ -1226,6 +1332,25 @@ export default {
|
||||
|
||||
//ReleaseNotes.ts
|
||||
RN_WELCOME: "歡迎使用 Excalidraw",
|
||||
FIRST_RUN: `
|
||||
Obsidian 的 Excalidraw 外掛遠不只是「畫圖工具」。由於它與 Obsidian 深度整合,它為視覺化個人知識管理帶來了全新的工作方式。
|
||||
|
||||
<div style="text-align:center;margin-top:10px;">
|
||||
<a href="https://community.sketch-your-mind.com/ee" target="_blank"><img src="https://sketch-your-mind.com/images/logo-EE.png" style="width:50%;"></a>
|
||||
</div>
|
||||
|
||||
如果你想順利上手、避免一開始就被大量功能淹沒,我非常推薦免費的 **[Excalidraw Essentials](https://community.sketch-your-mind.com/ee)** 微課程。它能幫你快速抓住重點,用清楚的結構掌握核心基礎。
|
||||
|
||||
你也不必自己摸索。歡迎加入 **[Sketch Your Mind 社群](https://community.sketch-your-mind.com)**,與其他視覺思考者交流、分享工作流程,一起打造更順暢的 PKM 系統。
|
||||
|
||||
如果你想先看看它現在能做到什麼,下面有一段核心功能展示。若想持續了解最新更新,並進一步探索 Visual PKM,也歡迎訂閱我的 YouTube 頻道:[Visual PKM](https://www.youtube.com/@visualPKM)。
|
||||
|
||||
感謝使用,祝你玩得愉快!
|
||||
|
||||
<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>
|
||||
`,
|
||||
|
||||
//Excalidraw component
|
||||
COMP_IMG: "圖片 & 檔案",
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
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";
|
||||
@@ -166,8 +166,6 @@ export class CropImage {
|
||||
}
|
||||
|
||||
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
|
||||
|
||||
@@ -0,0 +1,189 @@
|
||||
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,295 @@
|
||||
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,202 @@
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -13,7 +13,7 @@ const getColors = (palette: PaletteName, view?: ExcalidrawView, includeSceneColo
|
||||
const raw = getViewColorPalette(palette, view, includeSceneColors) ?? [];
|
||||
const flattened: string[] = [];
|
||||
|
||||
raw.forEach((entry: any) => {
|
||||
raw.forEach((entry: string[] | string) => {
|
||||
if (Array.isArray(entry)) {
|
||||
entry.forEach((color) => {
|
||||
if (typeof color === "string" && color) {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Setting, ToggleComponent } from "obsidian";
|
||||
import { Setting,ToggleComponent } from "obsidian";
|
||||
import { EmbeddableMDCustomProps } from "./EmbeddableSettings";
|
||||
import { fragWithHTML } from "src/utils/utils";
|
||||
import { t } from "src/lang/helpers";
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
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 { addAppendUpdateCustomData, fragWithHTML } from "src/utils/utils";
|
||||
import { getYouTubeStartAt, isValidYouTubeStart, isYouTube, updateYouTubeStartTime } from "src/utils/YoutTubeUtils";
|
||||
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 { EmbeddalbeMDFileCustomDataSettingsComponent } from "./EmbeddableMDFileCustomDataSettingsComponent";
|
||||
import { isWinCTRLorMacCMD } from "src/utils/modifierkeyHelper";
|
||||
import { ExcalidrawImperativeAPI } from "@zsviczian/excalidraw/types/excalidraw/types";
|
||||
@@ -114,7 +114,7 @@ export class EmbeddableSettings extends Modal {
|
||||
button
|
||||
.setButtonText(t("ES_ZOOM_100"))
|
||||
.onClick(() => {
|
||||
const api = this.view.excalidrawAPI as ExcalidrawImperativeAPI;
|
||||
const api = this.view.excalidrawAPI;
|
||||
this.zoomValue = 1/api.getAppState().zoom.value;
|
||||
zoomSetting.setDesc(zoomValue());
|
||||
})
|
||||
|
||||
@@ -1,17 +1,17 @@
|
||||
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";
|
||||
import { exportImageToFile,getIMGFilename } from "src/utils/fileUtils";
|
||||
|
||||
|
||||
|
||||
@@ -25,7 +25,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 +39,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,7 +56,7 @@ export class ExportDialog extends Modal {
|
||||
) {
|
||||
super(plugin.app);
|
||||
this.ea = getEA(this.view);
|
||||
this.api = this.ea.getExcalidrawAPI() as ExcalidrawImperativeAPI;
|
||||
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)
|
||||
@@ -386,7 +386,7 @@ export class ExportDialog extends Modal {
|
||||
bPNG.onclick = () => {
|
||||
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,
|
||||
@@ -411,7 +411,7 @@ export class ExportDialog extends Modal {
|
||||
bPNGVault.onclick = () => {
|
||||
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,
|
||||
@@ -435,7 +435,7 @@ export class ExportDialog extends Modal {
|
||||
bPNGClipboard.onclick = async () => {
|
||||
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,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { App, Modal } from "obsidian";
|
||||
import { App,Modal } from "obsidian";
|
||||
import { clamp } from "@radix-ui/number";
|
||||
|
||||
function getClientPoint(e: PointerEvent | TouchEvent) {
|
||||
@@ -194,7 +194,7 @@ export class FloatingModal extends Modal {
|
||||
// prevent automatic selection / focus restoration
|
||||
this.shouldRestoreSelection = false;
|
||||
}
|
||||
setTimeout(() => {
|
||||
window.setTimeout(() => {
|
||||
// @ts-ignore
|
||||
const { containerEl, modalEl, bgEl } = this;
|
||||
containerEl.addClass("mod-excalidraw-draggable")
|
||||
|
||||
@@ -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";
|
||||
@@ -79,6 +78,6 @@ export const showFrameSettings = (view: ExcalidrawView) => {
|
||||
};
|
||||
|
||||
// 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,4 +1,4 @@
|
||||
import { BaseComponent, Setting, Modifier } from 'obsidian';
|
||||
import { BaseComponent,Setting,Modifier } from 'obsidian';
|
||||
import { DEVICE } from 'src/constants/constants';
|
||||
import { t } from 'src/lang/helpers';
|
||||
import { ExcalidrawSettings } from 'src/core/settings';
|
||||
|
||||
@@ -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";
|
||||
|
||||
@@ -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,22 +24,20 @@ 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();
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { FuzzySuggestModal, TFile } from "obsidian";
|
||||
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";
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import { FuzzyMatch, FuzzySuggestModal } from "obsidian";
|
||||
import { FuzzyMatch,FuzzySuggestModal } from "obsidian";
|
||||
import { t } from "../../lang/helpers";
|
||||
import ExcalidrawPlugin from "src/core/main";
|
||||
import { getLink } from "src/utils/fileUtils";
|
||||
import { LinkSuggestion } from "src/types/types";
|
||||
import { getLinkSuggestionsFiltered, getSortedLinkMatches, renderLinkSuggestion } from "src/shared/Suggesters/LinkSuggesterUtils";
|
||||
import { getLinkSuggestionsFiltered,getSortedLinkMatches,renderLinkSuggestion } from "src/shared/Suggesters/LinkSuggesterUtils";
|
||||
|
||||
|
||||
export class InsertLinkDialog extends FuzzySuggestModal<LinkSuggestion> {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { FuzzySuggestModal, TFile } from "obsidian";
|
||||
import { FuzzySuggestModal,TFile } from "obsidian";
|
||||
import ExcalidrawView from "../../view/ExcalidrawView";
|
||||
import { t } from "../../lang/helpers";
|
||||
import ExcalidrawPlugin from "../../core/main";
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
import { ButtonComponent, TFile, ToggleComponent } from "obsidian";
|
||||
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;
|
||||
@@ -195,7 +196,7 @@ export class InsertPDFModal extends Modal {
|
||||
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
|
||||
@@ -211,9 +212,9 @@ export class InsertPDFModal extends Modal {
|
||||
this.setImageSizeMessage();
|
||||
}
|
||||
if(pages.length > 15) {
|
||||
importPagesMessage.innerHTML = `You are importing <b>${pages.length}</b> pages. ⚠️ This may take a while. ⚠️`;
|
||||
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();
|
||||
}
|
||||
@@ -515,7 +516,7 @@ export class InsertPDFModal extends Modal {
|
||||
ea.addToGroup(ids);
|
||||
}
|
||||
await ea.addElementsToView(true,true,false);
|
||||
const api = ea.getExcalidrawAPI() as ExcalidrawImperativeAPI;
|
||||
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);
|
||||
|
||||
+166
-18
@@ -1,33 +1,181 @@
|
||||
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.23.0":`
|
||||
## New
|
||||
- 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.
|
||||
- API key obfuscuation for plugin settings. This prevents your API keys to leak via Excalidraw plugin settings in case you open up 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.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
|
||||
- Tray-mode panel buttons get misaligned [#2718](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2718) 🙏[@heinrich26](https://github.com/heinrich26)
|
||||
- Improved loading of nested Excalidraw files in the Excalidraw scene, plus some limited performance improvement.
|
||||
- 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
|
||||
- Various text element editing improvements, including handle on the right side of wrapped text to enable text auto-resizing (instead of having to open the context menu for this) [#10979](https://github.com/excalidraw/excalidraw/pull/10979)
|
||||
- Support for Mermaid state diagrams [#11031](https://github.com/excalidraw/excalidraw/pull/11031)
|
||||
- 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
|
||||
- (partial) support for embedding the [Sheet Plus](obsidian://show-plugin?id=sheet-plus) plugin as an active embedded element in Excalidraw.
|
||||
- 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
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
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;
|
||||
@@ -45,6 +45,31 @@ export class ModifierKeySettingsComponent {
|
||||
text: t("DEFAULT_ACTION_DESC") + modifierKeyTooltipMessages()[modifierSetType][modifierKeys.defaultAction],
|
||||
cls: "setting-item-description"
|
||||
});
|
||||
// Ensure all LinkClickAction rules have ctrl_cmd enabled
|
||||
if (modifierSetType === "LinkClickAction") {
|
||||
let dirty = false;
|
||||
modifierKeys.rules.forEach((rule) => {
|
||||
if (!rule.ctrl_cmd) { rule.ctrl_cmd = true; dirty = true; }
|
||||
});
|
||||
if (dirty) this.update?.();
|
||||
}
|
||||
|
||||
// Column header row
|
||||
const headerSetting = new Setting(detailsEl);
|
||||
headerSetting.settingEl.addClass("modifier-key-header-row");
|
||||
headerSetting.infoEl.remove();
|
||||
[
|
||||
"SHIFT",
|
||||
this.isMacOS ? "CMD" : "CTRL",
|
||||
this.isMacOS ? "OPT" : "ALT",
|
||||
this.isMacOS ? "CTRL" : "META",
|
||||
].forEach((key) => {
|
||||
headerSetting.controlEl.createEl("span", {
|
||||
text: key,
|
||||
cls: "modifier-key-col-header",
|
||||
});
|
||||
});
|
||||
|
||||
Object.entries(modifierKeys.rules).forEach(([action, rule]) => {
|
||||
const setting = new Setting(detailsEl)
|
||||
//@ts-ignore
|
||||
@@ -60,14 +85,18 @@ export class ModifierKeySettingsComponent {
|
||||
})
|
||||
);
|
||||
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";
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { App, FuzzySuggestModal, TFile } from "obsidian";
|
||||
import { App,FuzzySuggestModal,TFile } from "obsidian";
|
||||
import ExcalidrawPlugin from "../../core/main";
|
||||
import { EMPTY_MESSAGE } from "../../constants/constants";
|
||||
import { t } from "../../lang/helpers";
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
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 {
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
import { ExcalidrawImperativeAPI } from "@zsviczian/excalidraw/types/excalidraw/types";
|
||||
import { ColorComponent, Modal, Setting, TextComponent, ToggleComponent } from "obsidian";
|
||||
import { ColorComponent,Modal,Setting,TextComponent,ToggleComponent } from "obsidian";
|
||||
import { COLOR_NAMES } from "src/constants/constants";
|
||||
import ExcalidrawView from "src/view/ExcalidrawView";
|
||||
import ExcalidrawPlugin from "src/core/main";
|
||||
import { setPen } from "src/view/components/menu/ObsidianMenu";
|
||||
import { ExtendedFillStyle, PenType } from "src/types/penTypes";
|
||||
import { ExtendedFillStyle,PenType } from "src/types/penTypes";
|
||||
import { getExcalidrawViews } from "src/utils/obsidianUtils";
|
||||
import { PENS } from "src/utils/pens";
|
||||
import { fragWithHTML } from "src/utils/utils";
|
||||
import { __values } from "tslib";
|
||||
import { setSanitizedHtml } from "src/utils/htmlUtils";
|
||||
import { showColorPicker } from "./ColorPicker";
|
||||
|
||||
const EASINGFUNCTIONS: Record<string,string> = {
|
||||
@@ -67,7 +67,7 @@ export class PenSettingsModal extends Modal {
|
||||
async onClose() {
|
||||
if(this.dirty) {
|
||||
await this.plugin.saveSettings();
|
||||
getExcalidrawViews(this.app).forEach(excalidrawView=>excalidrawView.updatePinnedCustomPens());
|
||||
getExcalidrawViews(this.app, true).forEach(excalidrawView=>excalidrawView.updatePinnedCustomPens());
|
||||
const pen = this.plugin.settings.customPens[this.pen]
|
||||
const api = this.view.excalidrawAPI;
|
||||
setPen(pen,api);
|
||||
@@ -467,7 +467,7 @@ export class PenSettingsModal extends Modal {
|
||||
|
||||
ce.createEl("h2",{text: "Perfect Freehand settings"});
|
||||
const p = ce.createEl("p");
|
||||
p.innerHTML = `Read the Perfect Freehand documentation following <a href="https://github.com/steveruizok/perfect-freehand#documentation" target="_blank">this link</a>.`;
|
||||
setSanitizedHtml(p, `Read the Perfect Freehand documentation following <a href="https://github.com/steveruizok/perfect-freehand#documentation" target="_blank">this link</a>.`);
|
||||
|
||||
let tSetting: Setting;
|
||||
tSetting = new Setting(ce)
|
||||
|
||||
@@ -1,35 +1,36 @@
|
||||
import {
|
||||
App,
|
||||
ButtonComponent,
|
||||
Modal,
|
||||
FuzzyMatch,
|
||||
FuzzySuggestModal,
|
||||
Instruction,
|
||||
TFile,
|
||||
Notice,
|
||||
TextAreaComponent
|
||||
App,
|
||||
ButtonComponent,
|
||||
Modal,
|
||||
FuzzyMatch,
|
||||
FuzzySuggestModal,
|
||||
Instruction,
|
||||
TFile,
|
||||
Notice,
|
||||
TextAreaComponent
|
||||
} from "obsidian";
|
||||
import ExcalidrawView from "../../view/ExcalidrawView";
|
||||
import ExcalidrawPlugin from "../../core/main";
|
||||
import { escapeRegExp, getLinkParts, sleep } from "../../utils/utils";
|
||||
import { getLeaf, openLeaf } from "../../utils/obsidianUtils";
|
||||
import { escapeRegExp,getLinkParts,sleep } from "../../utils/utils";
|
||||
import { getLeaf,openLeaf } from "../../utils/obsidianUtils";
|
||||
import { createOrOverwriteFile } from "src/utils/fileUtils";
|
||||
import { KeyEvent, isWinCTRLorMacCMD } from "src/utils/modifierkeyHelper";
|
||||
import { KeyEvent,isWinCTRLorMacCMD } from "src/utils/modifierkeyHelper";
|
||||
import { t } from "src/lang/helpers";
|
||||
import { ExcalidrawElement, getEA } from "src/core";
|
||||
import { ExcalidrawElement,getEA } from "src/core";
|
||||
import { ExcalidrawAutomate } from "src/shared/ExcalidrawAutomate";
|
||||
import { MAX_IMAGE_SIZE, REG_LINKINDEX_INVALIDCHARS } from "src/constants/constants";
|
||||
import { REGEX_LINK, REGEX_TAGS } from "../ExcalidrawData";
|
||||
import { MAX_IMAGE_SIZE,REG_LINKINDEX_INVALIDCHARS } from "src/constants/constants";
|
||||
import { REGEX_LINK,REGEX_TAGS } from "../ExcalidrawData";
|
||||
import { ScriptEngine } from "../Scripts";
|
||||
import { openExternalLink, openTagSearch, parseObsidianLink } from "src/utils/excalidrawViewUtils";
|
||||
import { openExternalLink,openTagSearch,parseObsidianLink } from "src/utils/excalidrawViewUtils";
|
||||
import { ButtonDefinition } from "src/types/promptTypes";
|
||||
import { EditorView, keymap } from "@codemirror/view";
|
||||
import { defaultKeymap, history, historyKeymap } from "@codemirror/commands";
|
||||
import { EditorView,keymap } from "@codemirror/view";
|
||||
import { defaultKeymap,history,historyKeymap } from "@codemirror/commands";
|
||||
import { parser } from "./math-only";
|
||||
import { LRLanguage } from "@codemirror/language";
|
||||
import { editorLivePreviewField } from "obsidian";
|
||||
import { Extension } from "@codemirror/state";
|
||||
import { FloatingModal } from "./FloatingModal";
|
||||
import { setSanitizedHtml } from "src/utils/htmlUtils";
|
||||
|
||||
export class Prompt extends Modal {
|
||||
private promptEl: HTMLInputElement;
|
||||
@@ -61,7 +62,7 @@ export class Prompt extends Modal {
|
||||
div = div.createDiv();
|
||||
div.style.width = "100%";
|
||||
const p = div.createEl("p");
|
||||
p.innerHTML = this.prompt_desc;
|
||||
setSanitizedHtml(p, this.prompt_desc);
|
||||
}
|
||||
const form = div.createEl("form");
|
||||
form.addClass("excalidraw-prompt-form");
|
||||
@@ -656,7 +657,7 @@ export class GenericInputPrompt extends Modal {
|
||||
|
||||
// Add to document and set up listeners
|
||||
document.body.appendChild(popup);
|
||||
setTimeout(() => {
|
||||
window.setTimeout(() => {
|
||||
document.addEventListener('click', closePopupListener);
|
||||
}, 10);
|
||||
}
|
||||
@@ -752,7 +753,7 @@ export class GenericInputPrompt extends Modal {
|
||||
// Restore focus and cursor position
|
||||
if (activeElement && activeElement.isConnected) {
|
||||
// Use setTimeout to ensure the pointer event is fully processed
|
||||
setTimeout(() => {
|
||||
window.setTimeout(() => {
|
||||
activeElement.focus();
|
||||
|
||||
// Restore cursor position for input/textarea elements (but not for number inputs)
|
||||
@@ -1050,6 +1051,7 @@ export class MultiOptionConfirmationPrompt extends Modal {
|
||||
private readonly message: string;
|
||||
private readonly buttons: Map<string, any>;
|
||||
private ctaButtonLabel: string = null;
|
||||
private ctaButtonEl: HTMLButtonElement | null = null;
|
||||
|
||||
constructor(private plugin: ExcalidrawPlugin, message: string, buttons?: Map<string, any>, ctaButtonLabel?: string) {
|
||||
super(plugin.app);
|
||||
@@ -1060,7 +1062,7 @@ export class MultiOptionConfirmationPrompt extends Modal {
|
||||
[t("PROMPT_BUTTON_OK"), true],
|
||||
]);
|
||||
if( !ctaButtonLabel) {
|
||||
ctaButtonLabel = t("PROMPT_BUTTON_OK");
|
||||
ctaButtonLabel = t("PROMPT_BUTTON_CANCEL");
|
||||
}
|
||||
}
|
||||
this.ctaButtonLabel = ctaButtonLabel;
|
||||
@@ -1080,7 +1082,7 @@ export class MultiOptionConfirmationPrompt extends Modal {
|
||||
|
||||
const messageEl = this.contentEl.createDiv();
|
||||
messageEl.style.marginBottom = "1rem";
|
||||
messageEl.innerHTML = this.message;
|
||||
setSanitizedHtml(messageEl, this.message);
|
||||
|
||||
const buttonContainer = this.contentEl.createDiv();
|
||||
buttonContainer.style.display = "flex";
|
||||
@@ -1090,16 +1092,16 @@ export class MultiOptionConfirmationPrompt extends Modal {
|
||||
// Convert Map to Array for easier iteration
|
||||
const buttonEntries = Array.from(this.buttons.entries());
|
||||
|
||||
// Add buttons in reverse order (last button will be on the right)
|
||||
let ctaButton: HTMLButtonElement = null;
|
||||
buttonEntries.reverse().forEach(([buttonText, value], index) => {
|
||||
// Preserve caller-provided button order so fallback focus semantics are predictable.
|
||||
this.ctaButtonEl = null;
|
||||
buttonEntries.forEach(([buttonText, value], index) => {
|
||||
const button = this.createButton(buttonContainer, buttonText, () => {
|
||||
this.selectedValue = value;
|
||||
this.close();
|
||||
});
|
||||
|
||||
if (buttonText === this.ctaButtonLabel) {
|
||||
ctaButton = button.buttonEl;
|
||||
this.ctaButtonEl = button.buttonEl;
|
||||
button.setCta();
|
||||
}
|
||||
|
||||
@@ -1109,10 +1111,8 @@ export class MultiOptionConfirmationPrompt extends Modal {
|
||||
});
|
||||
|
||||
// Set focus on the first button (visually last)
|
||||
if(this.ctaButtonLabel) {
|
||||
if (ctaButton) {
|
||||
ctaButton.focus();
|
||||
}
|
||||
if(this.ctaButtonLabel && this.ctaButtonEl) {
|
||||
this.ctaButtonEl.focus();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1124,7 +1124,10 @@ export class MultiOptionConfirmationPrompt extends Modal {
|
||||
|
||||
onOpen() {
|
||||
super.onOpen();
|
||||
this.contentEl.querySelector("button")?.focus();
|
||||
const defaultButton = this.ctaButtonEl ?? this.contentEl.querySelector("button");
|
||||
// Obsidian modal open may apply its own autofocus after onOpen; defer to enforce default keyboard action.
|
||||
window.setTimeout(() => defaultButton?.focus(), 0);
|
||||
window.setTimeout(() => defaultButton?.focus(), 50);
|
||||
}
|
||||
|
||||
onClose() {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { Modal, Setting, TFile } from "obsidian";
|
||||
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 => {
|
||||
@@ -71,7 +72,7 @@ export class PublishOutOfDateFilesDialog extends Modal {
|
||||
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";
|
||||
setElementDisplay(statusEl, "none");
|
||||
|
||||
if(!files || files.length === 0) {
|
||||
p.innerText = "No out of date files found.";
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { App, MarkdownRenderer, Modal } from "obsidian";
|
||||
import { App,MarkdownRenderer,Modal } from "obsidian";
|
||||
import ExcalidrawPlugin from "../../core/main";
|
||||
import { Rank, SwordColors } from "src/constants/actionIcons";
|
||||
import { Rank,SwordColors } from "src/constants/actionIcons";
|
||||
import { convertSVGStringToElement } from "src/utils/utils";
|
||||
|
||||
export class RankMessage extends Modal {
|
||||
|
||||
@@ -23,7 +24,11 @@ export class RankMessage extends Modal {
|
||||
async createForm() {
|
||||
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,18 +1,26 @@
|
||||
import { App, MarkdownRenderer, Modal } from "obsidian";
|
||||
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;
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -21,7 +29,7 @@ export class ReleaseNotes extends Modal {
|
||||
const { containerEl, contentEl, titleEl, headerEl } = this;
|
||||
//this.contentEl.classList.add("excalidraw-release");
|
||||
containerEl.classList.add("excalidraw-release");
|
||||
titleEl.setText(`${t("RN_WELCOME")} ${this.version ?? ""}`);
|
||||
titleEl.setText(this.options.title ?? `${t("RN_WELCOME")} ${this.version ?? ""}`.trim());
|
||||
this.createForm();
|
||||
|
||||
if(headerEl) headerEl.style.pointerEvents = "none"; // Disable pointer events on header to allow clicks through
|
||||
@@ -29,6 +37,9 @@ export class ReleaseNotes extends Modal {
|
||||
|
||||
async onClose() {
|
||||
this.contentEl.empty();
|
||||
if (this.options.persistVersion === false) {
|
||||
return;
|
||||
}
|
||||
await this.plugin.loadSettings();
|
||||
if(this.plugin.settings.previousRelease !== PLUGIN_VERSION) {
|
||||
this.plugin.settings.previousRelease = PLUGIN_VERSION;
|
||||
@@ -39,13 +50,13 @@ 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
|
||||
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")
|
||||
: FIRST_RUN;
|
||||
: t("FIRST_RUN"));
|
||||
await MarkdownRenderer.render(
|
||||
this.app,
|
||||
message,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { MarkdownRenderer, Modal, Notice, request } from "obsidian";
|
||||
import { MarkdownRenderer,Modal,Notice,request } from "obsidian";
|
||||
import ExcalidrawPlugin from "../../core/main";
|
||||
import { errorlog } from "../../utils/utils";
|
||||
import { log } from "src/utils/debugHelper";
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import { App, FuzzySuggestModal, Notice } from "obsidian";
|
||||
import { App,FuzzySuggestModal,Notice } from "obsidian";
|
||||
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> {
|
||||
|
||||
@@ -418,7 +418,7 @@ 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" +
|
||||
@@ -1031,6 +1031,93 @@ 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 }[]",
|
||||
@@ -1041,15 +1128,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")}`,
|
||||
"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: "",
|
||||
},
|
||||
{
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { Setting, DropdownComponent, App } from "obsidian";
|
||||
import { Setting,DropdownComponent,App } from "obsidian";
|
||||
import { t } from "src/lang/helpers";
|
||||
import { ExcalidrawSettings } from "src/core/settings";
|
||||
import { fragWithHTML, setLeftHandedMode, setUIMode } from "src/utils/utils";
|
||||
import { fragWithHTML,setLeftHandedMode,setUIMode } from "src/utils/utils";
|
||||
import { DEVICE } from "src/constants/constants";
|
||||
|
||||
export type UIMode = "full" | "compact" | "tray" | "mobile";
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
import { ButtonComponent, DropdownComponent, TFile } from "obsidian";
|
||||
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 { ExcalidrawImperativeAPI } from "@zsviczian/excalidraw/types/excalidraw/types";
|
||||
import { ExcalidrawAutomate } from "src/shared/ExcalidrawAutomate";
|
||||
import { cleanSectionHeading } from "src/utils/pathUtils";
|
||||
import { t } from "src/lang/helpers";
|
||||
@@ -21,7 +21,7 @@ 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;
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { Modal, Setting } from "obsidian";
|
||||
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;
|
||||
|
||||
@@ -42,18 +43,21 @@ 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"))
|
||||
@@ -81,7 +85,7 @@ export class VersionMismatchPrompt extends Modal {
|
||||
this.close();
|
||||
});
|
||||
|
||||
buttonBar.style.display = "flex";
|
||||
setElementDisplay(buttonBar, "flex");
|
||||
buttonBar.style.gap = "0.5rem";
|
||||
buttonBar.style.marginTop = "1rem";
|
||||
redownloadBtn.style.backgroundColor = "var(--interactive-accent)";
|
||||
|
||||
@@ -14,7 +14,7 @@ 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",
|
||||
|
||||
@@ -1,45 +1,46 @@
|
||||
//https://stackoverflow.com/questions/2068344/how-do-i-get-a-youtube-video-thumbnail-from-the-youtube-api
|
||||
//https://img.youtube.com/vi/uZz5MgzWXiM/maxresdefault.jpg
|
||||
|
||||
import { ExcalidrawElement, FileId } from "@zsviczian/excalidraw/types/element/src/types";
|
||||
import { ExcalidrawElement,FileId } from "@zsviczian/excalidraw/types/element/src/types";
|
||||
import { DataURL } from "@zsviczian/excalidraw/types/excalidraw/types";
|
||||
import { App, MarkdownRenderer, Notice, TFile } from "obsidian";
|
||||
import {
|
||||
DEFAULT_MD_EMBED_CSS,
|
||||
fileid,
|
||||
IMAGE_TYPES,
|
||||
nanoid,
|
||||
THEME_FILTER,
|
||||
FRONTMATTER_KEYS,
|
||||
getCSSFontDefinition,
|
||||
import { App,MarkdownRenderer,Notice,TFile } from "obsidian";
|
||||
import {
|
||||
DEFAULT_MD_EMBED_CSS,
|
||||
fileid,
|
||||
IMAGE_TYPES,
|
||||
nanoid,
|
||||
THEME_FILTER,
|
||||
FRONTMATTER_KEYS,
|
||||
getCSSFontDefinition,
|
||||
} from "../constants/constants";
|
||||
import { createSVG } from "src/utils/excalidrawAutomateUtils";
|
||||
import { ExcalidrawData, getTransclusion } from "./ExcalidrawData";
|
||||
import { ExcalidrawData,getTransclusion } from "./ExcalidrawData";
|
||||
import { t } from "../lang/helpers";
|
||||
import { tex2dataURL } from "./LaTeX";
|
||||
import ExcalidrawPlugin from "../core/main";
|
||||
import { blobToBase64, getDataURLFromURL, getMimeType, getPDFDoc, getURLImageExtension, readLocalFileBinary } from "../utils/fileUtils";
|
||||
import { errorlog, getDataURL } from "../utils/coreUtils";
|
||||
import { getExportTheme, getLinkParts, hasExportTheme, LinkParts } from "../utils/sceneDataUtils";
|
||||
import { blobToBase64,getDataURLFromURL,getMimeType,getPDFDoc,getURLImageExtension,readLocalFileBinary } from "../utils/fileUtils";
|
||||
import { errorlog,getDataURL } from "../utils/coreUtils";
|
||||
import { getExportTheme,getLinkParts,hasExportTheme,LinkParts } from "../utils/sceneDataUtils";
|
||||
import {
|
||||
cropCanvas,
|
||||
getEmbeddedFilenameParts,
|
||||
getExportPadding,
|
||||
getFontDataURL,
|
||||
getImageSize,
|
||||
getWithBackground,
|
||||
hasExportBackground,
|
||||
isMaskFile,
|
||||
promiseTry,
|
||||
PromisePool,
|
||||
svgToBase64,
|
||||
cropCanvas,
|
||||
getEmbeddedFilenameParts,
|
||||
getExportPadding,
|
||||
getFontDataURL,
|
||||
getImageSize,
|
||||
getWithBackground,
|
||||
hasExportBackground,
|
||||
isMaskFile,
|
||||
promiseTry,
|
||||
PromisePool,
|
||||
svgToBase64,
|
||||
} from "../utils/embeddedAssetUtils";
|
||||
import { getMermaidImageElements, getMermaidText, shouldRenderMermaid } from "../utils/mermaidUtils";
|
||||
import { getMermaidImageElements,getMermaidText,shouldRenderMermaid } from "../utils/mermaidUtils";
|
||||
import { mermaidToExcalidraw } from "src/constants/constants";
|
||||
import { ImageKey, imageCache } from "./ImageCache";
|
||||
import { FILENAMEPARTS, PreviewImageType } from "../types/utilTypes";
|
||||
import { ColorMap, ImgData, PDFPageViewProps, Size, MimeType, FileData } from "src/types/embeddedFileLoaderTypes";
|
||||
import { ImageKey,imageCache } from "./ImageCache";
|
||||
import { FILENAMEPARTS,PreviewImageType } from "../types/utilTypes";
|
||||
import { ColorMap,ImgData,PDFPageViewProps,Size,MimeType,FileData } from "src/types/embeddedFileLoaderTypes";
|
||||
import { ExportSettings } from "src/types/exportUtilTypes";
|
||||
import { setStyleText } from "src/utils/htmlUtils";
|
||||
|
||||
//An ugly workaround for the following situation.
|
||||
//File A is a markdown file that has an embedded Excalidraw file B
|
||||
@@ -50,6 +51,22 @@ import { ExportSettings } from "src/types/exportUtilTypes";
|
||||
//and getObsidianImage is aborted if the file is already in the Watchdog stack
|
||||
const markdownRendererRecursionWatcthdog = new Set<TFile>();
|
||||
|
||||
type CacheValidationMode = "validated" | "stale-first";
|
||||
|
||||
type LoadImageOptions = {
|
||||
cacheValidation?: CacheValidationMode;
|
||||
onStaleCacheHit?: () => void;
|
||||
};
|
||||
|
||||
type LoadSceneEmitPolicy = "all" | "changed-only";
|
||||
|
||||
const getPDFCacheId = (linkParts: LinkParts, pageNum: number): string => {
|
||||
// Different crops of the same PDF page must not overwrite each other in cache,
|
||||
// so the cache key uses the full PDF page/reference fragment when present.
|
||||
const pdfRef = linkParts.original?.match(/#([^|]*)/)?.[1];
|
||||
return pdfRef && pdfRef !== "" ? pdfRef : `page=${pageNum}`;
|
||||
};
|
||||
|
||||
|
||||
|
||||
/**
|
||||
@@ -137,6 +154,7 @@ export class EmbeddedFile {
|
||||
public hyperlink:DataURL;
|
||||
public colorMap: ColorMap | null = null;
|
||||
public pdfPageViewProps: PDFPageViewProps;
|
||||
public renderScale: number = 0;
|
||||
|
||||
constructor(plugin: ExcalidrawPlugin, hostPath: string, imgPath: string, colorMapJSON?: string) {
|
||||
this.plugin = plugin;
|
||||
@@ -151,12 +169,13 @@ export class EmbeddedFile {
|
||||
}
|
||||
|
||||
get hasSeparateDarkAndLightVersion(): boolean {
|
||||
return this.isSVGwithBitmap;
|
||||
return this.isSVGwithBitmap || this.file?.extension?.toLowerCase?.() === "pdf";
|
||||
}
|
||||
|
||||
public resetImage(hostPath: string, imgPath: string) {
|
||||
this.imgInverted = this.img = "";
|
||||
this.mtime = 0;
|
||||
this.renderScale = 0;
|
||||
|
||||
if(imgPath.startsWith("https://") || imgPath.startsWith("http://") || imgPath.startsWith("ftp://") || imgPath.startsWith("ftps://")) {
|
||||
this.isHyperLink = true;
|
||||
@@ -216,13 +235,14 @@ export class EmbeddedFile {
|
||||
return this.mtime !== this.file.stat.mtime;
|
||||
}
|
||||
|
||||
public setImage({ imgBase64, mimeType, size, isDark, isSVGwithBitmap, pdfPageViewProps } : {
|
||||
public setImage({ imgBase64, mimeType, size, isDark, isSVGwithBitmap, pdfPageViewProps, renderScale } : {
|
||||
imgBase64: string;
|
||||
mimeType: MimeType;
|
||||
size: Size;
|
||||
isDark: boolean;
|
||||
isSVGwithBitmap: boolean;
|
||||
pdfPageViewProps?: PDFPageViewProps;
|
||||
renderScale?: number;
|
||||
}
|
||||
) {
|
||||
if (!this.file && !this.isHyperLink && !this.isLocalLink) {
|
||||
@@ -234,6 +254,7 @@ export class EmbeddedFile {
|
||||
this.isSVGwithBitmap = isSVGwithBitmap;
|
||||
this.mtime = this.isHyperLink || this.isLocalLink ? 0 : this.file.stat.mtime;
|
||||
this.pdfPageViewProps = pdfPageViewProps;
|
||||
this.renderScale = renderScale ?? 0;
|
||||
this.size = size;
|
||||
this.mimeType = mimeType;
|
||||
switch (isDark && this.hasSeparateDarkAndLightVersion) {
|
||||
@@ -261,6 +282,12 @@ export class EmbeddedFile {
|
||||
if (this.fileChanged()) {
|
||||
return false;
|
||||
}
|
||||
if (this.file.extension?.toLowerCase?.() === "pdf" && this.renderScale > 0) {
|
||||
const hasImageForTheme = this.hasSeparateDarkAndLightVersion && isDark
|
||||
? this.imgInverted !== ""
|
||||
: this.img !== "";
|
||||
return hasImageForTheme && this.renderScale >= this.plugin.settings.pdfScale;
|
||||
}
|
||||
}
|
||||
if (this.hasSeparateDarkAndLightVersion && isDark) {
|
||||
return this.imgInverted !== "";
|
||||
@@ -336,6 +363,8 @@ export class EmbeddedFilesLoader {
|
||||
inFile,
|
||||
hasSVGwithBitmap,
|
||||
elements = [],
|
||||
cacheValidation = "validated",
|
||||
onStaleCacheHit,
|
||||
}: {
|
||||
isDark: boolean;
|
||||
file: TFile;
|
||||
@@ -343,7 +372,9 @@ export class EmbeddedFilesLoader {
|
||||
inFile: TFile | EmbeddedFile;
|
||||
hasSVGwithBitmap: boolean;
|
||||
elements?: ExcalidrawElement[];
|
||||
}) : Promise<{dataURL: DataURL, hasSVGwithBitmap:boolean}> {
|
||||
cacheValidation?: CacheValidationMode;
|
||||
onStaleCacheHit?: () => void;
|
||||
}) : Promise<{dataURL: DataURL, hasSVGwithBitmap:boolean, loadedFromCache?: boolean}> {
|
||||
//debug({where:"EmbeddedFileLoader.getExcalidrawSVG",uid:this.uid,file:file.name});
|
||||
const isMask = isMaskFile(this.plugin, file);
|
||||
const forceTheme = hasExportTheme(this.plugin, file)
|
||||
@@ -388,9 +419,15 @@ export class EmbeddedFilesLoader {
|
||||
}
|
||||
|
||||
const maybeSVG = shouldUseCache
|
||||
? await imageCache.getImageFromCache(cacheKey)
|
||||
? await imageCache.getImageFromCache(cacheKey, {
|
||||
skipDependencyCheck: cacheValidation === "stale-first",
|
||||
})
|
||||
: undefined;
|
||||
|
||||
if (maybeSVG && cacheValidation === "stale-first") {
|
||||
onStaleCacheHit?.();
|
||||
}
|
||||
|
||||
const svg = (maybeSVG && (maybeSVG instanceof SVGSVGElement))
|
||||
? maybeSVG
|
||||
: replaceSVGColors(
|
||||
@@ -469,7 +506,7 @@ export class EmbeddedFilesLoader {
|
||||
Boolean(vb[3]) && svg.setAttribute("height", vb[3]);
|
||||
}
|
||||
const dURL = svgToBase64(svg.outerHTML) as DataURL;
|
||||
return {dataURL: dURL as DataURL, hasSVGwithBitmap};
|
||||
return {dataURL: dURL as DataURL, hasSVGwithBitmap, loadedFromCache: Boolean(maybeSVG)};
|
||||
};
|
||||
|
||||
//this is a fix for backward compatibility - I messed up with generating the local link
|
||||
@@ -481,7 +518,11 @@ export class EmbeddedFilesLoader {
|
||||
return localPath;
|
||||
}
|
||||
|
||||
private async _getObsidianImage(inFile: TFile | EmbeddedFile, depth: number): Promise<ImgData> {
|
||||
private async _getObsidianImage(
|
||||
inFile: TFile | EmbeddedFile,
|
||||
depth: number,
|
||||
options?: LoadImageOptions,
|
||||
): Promise<ImgData> {
|
||||
if (!this.plugin || !inFile) {
|
||||
return null;
|
||||
}
|
||||
@@ -534,6 +575,7 @@ export class EmbeddedFilesLoader {
|
||||
: await app.vault.readBinary(file);
|
||||
|
||||
let dURL: DataURL = null;
|
||||
let excalidrawLoadedFromCache = false;
|
||||
if (isExcalidrawFile) {
|
||||
const res = await this.getExcalidrawSVG({
|
||||
isDark: this.isDark,
|
||||
@@ -541,16 +583,19 @@ export class EmbeddedFilesLoader {
|
||||
depth,
|
||||
inFile,
|
||||
hasSVGwithBitmap,
|
||||
cacheValidation: options?.cacheValidation,
|
||||
onStaleCacheHit: options?.onStaleCacheHit,
|
||||
});
|
||||
dURL = res.dataURL;
|
||||
hasSVGwithBitmap = res.hasSVGwithBitmap;
|
||||
excalidrawLoadedFromCache = !!res.loadedFromCache;
|
||||
}
|
||||
|
||||
const excalidrawSVG = isExcalidrawFile ? dURL : null;
|
||||
|
||||
const [pdfDataURL, pdfSize, pdfPageViewProps] = isPDF
|
||||
? await this.pdfToDataURL(file,linkParts)
|
||||
: [null, null, null];
|
||||
const [pdfDataURL, pdfSize, pdfPageViewProps, pdfRenderScale, pdfLoadedFromCache] = isPDF
|
||||
? await this.pdfToDataURL(file, linkParts, options)
|
||||
: [null, null, null, null, false];
|
||||
|
||||
let mimeType: MimeType = isPDF
|
||||
? "image/png"
|
||||
@@ -597,9 +642,11 @@ export class EmbeddedFilesLoader {
|
||||
),
|
||||
dataURL,
|
||||
created: isHyperLink || isLocalLink ? 0 : file.stat.mtime,
|
||||
loadedFromCache: isExcalidrawFile ? excalidrawLoadedFromCache : pdfLoadedFromCache,
|
||||
hasSVGwithBitmap,
|
||||
size,
|
||||
pdfPageViewProps,
|
||||
renderScale: pdfRenderScale,
|
||||
};
|
||||
} catch (error) {
|
||||
errorlog({
|
||||
@@ -619,12 +666,22 @@ export class EmbeddedFilesLoader {
|
||||
depth,
|
||||
isThemeChange = false,
|
||||
fileIDWhiteList,
|
||||
forceReloadFileIDs,
|
||||
cacheValidation = "validated",
|
||||
validationConcurrency,
|
||||
emitPolicy = "all",
|
||||
onDeferredValidationCandidates,
|
||||
}: {
|
||||
excalidrawData: ExcalidrawData;
|
||||
addFiles: (files: FileData[], isDark: boolean, final?: boolean) => void;
|
||||
depth: number;
|
||||
isThemeChange?: boolean;
|
||||
fileIDWhiteList?: Set<FileId>;
|
||||
forceReloadFileIDs?: Set<FileId>;
|
||||
cacheValidation?: CacheValidationMode;
|
||||
validationConcurrency?: number;
|
||||
emitPolicy?: LoadSceneEmitPolicy;
|
||||
onDeferredValidationCandidates?: (fileIds: Set<FileId>) => void;
|
||||
}) {
|
||||
|
||||
if(depth > 7) {
|
||||
@@ -655,6 +712,8 @@ export class EmbeddedFilesLoader {
|
||||
const files: FileData[][] = [];
|
||||
files.push([]);
|
||||
let batch = 0;
|
||||
// Only stale-first cache hits are queued for the cheap second pass.
|
||||
const deferredValidationFileIds = new Set<FileId>();
|
||||
|
||||
function* loadIterator(this: EmbeddedFilesLoader):Generator<Promise<void>> {
|
||||
while (!(entry = entries.next()).done) {
|
||||
@@ -665,19 +724,27 @@ export class EmbeddedFilesLoader {
|
||||
if(this.terminate) {
|
||||
return;
|
||||
}
|
||||
if (!embeddedFile.isLoaded(this.isDark)) {
|
||||
const shouldForceReload = forceReloadFileIDs?.has(id);
|
||||
if (shouldForceReload || !embeddedFile.isLoaded(this.isDark)) {
|
||||
//debug({where:"EmbeddedFileLoader.loadSceneFiles",uid:this.uid,status:"embedded Files are not loaded"});
|
||||
const data = await this._getObsidianImage(embeddedFile, depth);
|
||||
const data = await this._getObsidianImage(embeddedFile, depth, {
|
||||
cacheValidation,
|
||||
onStaleCacheHit: cacheValidation === "stale-first"
|
||||
? () => deferredValidationFileIds.add(id)
|
||||
: undefined,
|
||||
});
|
||||
if (data) {
|
||||
const fileData: FileData = {
|
||||
mimeType: data.mimeType,
|
||||
id: id,
|
||||
dataURL: data.dataURL,
|
||||
created: data.created,
|
||||
loadedFromCache: data.loadedFromCache,
|
||||
size: data.size,
|
||||
hasSVGwithBitmap: data.hasSVGwithBitmap,
|
||||
shouldScale: embeddedFile.shouldScale(),
|
||||
pdfPageViewProps: data.pdfPageViewProps,
|
||||
renderScale: data.renderScale,
|
||||
};
|
||||
files[batch].push(fileData);
|
||||
}
|
||||
@@ -692,6 +759,7 @@ export class EmbeddedFilesLoader {
|
||||
hasSVGwithBitmap: embeddedFile.isSVGwithBitmap,
|
||||
shouldScale: embeddedFile.shouldScale(),
|
||||
pdfPageViewProps: embeddedFile.pdfPageViewProps,
|
||||
renderScale: embeddedFile.renderScale,
|
||||
};
|
||||
files[batch].push(fileData);
|
||||
}
|
||||
@@ -802,16 +870,18 @@ export class EmbeddedFilesLoader {
|
||||
};
|
||||
}
|
||||
|
||||
const addFilesTimer = setInterval(() => {
|
||||
const addFilesTimer = window.setInterval(() => {
|
||||
if (this.terminate) {
|
||||
clearInterval(addFilesTimer);
|
||||
window.clearInterval(addFilesTimer);
|
||||
return;
|
||||
}
|
||||
if(files[batch].length === 0) {
|
||||
return;
|
||||
}
|
||||
// During deferred validation, only regenerated results should reach addFiles.
|
||||
const batchFiles = files[batch].filter(f=>emitPolicy === "all" || !f.loadedFromCache);
|
||||
try {
|
||||
addFiles(files[batch], this.isDark, false);
|
||||
addFiles(batchFiles, this.isDark, false);
|
||||
}
|
||||
catch(e) {
|
||||
errorlog({ where: "EmbeddedFileLoader.loadSceneFiles", error: e });
|
||||
@@ -822,7 +892,7 @@ export class EmbeddedFilesLoader {
|
||||
|
||||
try {
|
||||
const iterator = loadIterator.bind(this)();
|
||||
const concurency = this.plugin.settings.renderingConcurrency;
|
||||
const concurency = validationConcurrency ?? this.plugin.settings.renderingConcurrency;
|
||||
if (!this.terminate) {
|
||||
await new PromisePool(iterator, concurency).all();
|
||||
}
|
||||
@@ -832,9 +902,14 @@ export class EmbeddedFilesLoader {
|
||||
return;
|
||||
}
|
||||
//debug({where:"EmbeddedFileLoader.loadSceneFiles",uid:this.uid,status:"add Files"});
|
||||
if (deferredValidationFileIds.size > 0) {
|
||||
onDeferredValidationCandidates?.(deferredValidationFileIds);
|
||||
}
|
||||
// Same filter for the final flush so validated cache hits remain a no-op.
|
||||
const batchFiles = files[batch].filter(f=>emitPolicy === "all" || !f.loadedFromCache);
|
||||
try {
|
||||
//in try block because by the time files are loaded the user may have closed the view
|
||||
addFiles(files[batch], this.isDark, true);
|
||||
addFiles(batchFiles, this.isDark, true);
|
||||
} catch (e) {
|
||||
errorlog({ where: "EmbeddedFileLoader.loadSceneFiles", error: e });
|
||||
}
|
||||
@@ -847,14 +922,61 @@ export class EmbeddedFilesLoader {
|
||||
private async pdfToDataURL(
|
||||
file: TFile,
|
||||
linkParts: LinkParts,
|
||||
): Promise<[DataURL,Size, PDFPageViewProps]> {
|
||||
options?: LoadImageOptions,
|
||||
): Promise<[DataURL,Size, PDFPageViewProps, number, boolean]> {
|
||||
try {
|
||||
let width = 0, height = 0;
|
||||
const pageNum = isNaN(linkParts.page) ? 1 : (linkParts.page??1);
|
||||
const requestedScale = this.plugin.settings.pdfScale;
|
||||
const shouldUseCache = imageCache.isReady() && (!options || this.plugin.settings.allowImageCacheInScene);
|
||||
const cacheKey: ImageKey = {
|
||||
filepath: file.path,
|
||||
cacheId: getPDFCacheId(linkParts, pageNum),
|
||||
hasBlockref: false,
|
||||
hasGroupref: false,
|
||||
hasTaskbone: false,
|
||||
hasArearef: false,
|
||||
hasFrameref: false,
|
||||
hasClippedFrameref: false,
|
||||
hasSectionref: false,
|
||||
blockref: null,
|
||||
sectionref: null,
|
||||
linkpartReference: null,
|
||||
linkpartAlias: null,
|
||||
isDark: !!this.isDark,
|
||||
previewImageType: PreviewImageType.PNG,
|
||||
scale: 0,
|
||||
isTransparent: false,
|
||||
inlineFonts: false,
|
||||
};
|
||||
const cachedData = shouldUseCache
|
||||
? await imageCache.getImageCacheData(cacheKey, {
|
||||
skipDependencyCheck: options?.cacheValidation === "stale-first",
|
||||
minRenderScale: options?.cacheValidation === "stale-first" ? undefined : requestedScale,
|
||||
})
|
||||
: undefined;
|
||||
|
||||
if (cachedData?.blob) {
|
||||
const cachedScale = cachedData.renderScale ?? requestedScale;
|
||||
// Stale-first accepts an older PDF raster immediately, but still marks it
|
||||
// for deferred validation when the requested scale has increased.
|
||||
if (options?.cacheValidation === "stale-first" && cachedScale < requestedScale) {
|
||||
options?.onStaleCacheHit?.();
|
||||
}
|
||||
return [
|
||||
`data:image/png;base64,${await blobToBase64(cachedData.blob)}` as DataURL,
|
||||
cachedData.size,
|
||||
cachedData.pdfPageViewProps,
|
||||
cachedScale,
|
||||
true,
|
||||
];
|
||||
}
|
||||
|
||||
let pdfDoc = this.pdfDocsMap.get(file.path);
|
||||
if(!pdfDoc) {
|
||||
pdfDoc = await getPDFDoc(file);
|
||||
if(!pdfDoc) {
|
||||
return [null, null, null];
|
||||
return [null, null, null, null, false];
|
||||
}
|
||||
this.pdfDocs.add(pdfDoc);
|
||||
if(!this.pdfDocsMap.has(file.path)) {
|
||||
@@ -863,8 +985,8 @@ export class EmbeddedFilesLoader {
|
||||
} else {
|
||||
this.pdfDocs.add(pdfDoc);
|
||||
}
|
||||
const pageNum = isNaN(linkParts.page) ? 1 : (linkParts.page??1);
|
||||
const scale = this.plugin.settings.pdfScale;
|
||||
|
||||
const scale = requestedScale;
|
||||
const cropRect = linkParts.ref.split("rect=")[1]?.split(",").map(x=>parseInt(x));
|
||||
const validRect = cropRect && cropRect.length === 4 && cropRect.every(x=>!isNaN(x));
|
||||
let viewProps: PDFPageViewProps;
|
||||
@@ -992,19 +1114,35 @@ export class EmbeddedFilesLoader {
|
||||
|
||||
const canvas = await renderPage(pageNum);
|
||||
if(canvas) {
|
||||
const result: [DataURL,Size, PDFPageViewProps] = [`data:image/png;base64,${await new Promise((resolve, reject) => {
|
||||
canvas.toBlob(async (blob) => {
|
||||
const dataURL = await blobToBase64(blob);
|
||||
resolve(dataURL);
|
||||
const blob = await new Promise<Blob>((resolve, reject) => {
|
||||
canvas.toBlob((pngBlob) => {
|
||||
if (!pngBlob) {
|
||||
reject(new Error("Failed to convert PDF canvas to blob."));
|
||||
return;
|
||||
}
|
||||
resolve(pngBlob);
|
||||
});
|
||||
})}` as DataURL, {width, height}, viewProps];
|
||||
});
|
||||
const base64 = await blobToBase64(blob);
|
||||
shouldUseCache && imageCache.addImageToCache(cacheKey, "", blob, {
|
||||
renderScale: requestedScale,
|
||||
size: {width, height},
|
||||
pdfPageViewProps: viewProps,
|
||||
});
|
||||
const result: [DataURL,Size, PDFPageViewProps, number, boolean] = [
|
||||
`data:image/png;base64,${base64}` as DataURL,
|
||||
{width, height},
|
||||
viewProps,
|
||||
requestedScale,
|
||||
false,
|
||||
];
|
||||
canvas.width = 0; //free memory iOS bug
|
||||
canvas.height = 0;
|
||||
return result;
|
||||
}
|
||||
} catch(e) {
|
||||
console.log(e);
|
||||
return [null, null, null];
|
||||
return [null, null, null, null, false];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1179,7 +1317,7 @@ export class EmbeddedFilesLoader {
|
||||
if (style) {
|
||||
const styleEl = iframeDoc.createElement("style");
|
||||
styleEl.type = "text/css";
|
||||
styleEl.innerHTML = style;
|
||||
setStyleText(styleEl, style);
|
||||
iframeDoc.head.appendChild(styleEl);
|
||||
}
|
||||
const stylingDIV = iframeDoc.importNode(mdDIV, true);
|
||||
@@ -1311,4 +1449,4 @@ const replaceBlobWithBase64 = async (divElement: HTMLDivElement): Promise<void>
|
||||
console.error(`Failed to fetch or convert blob: ${blobUrl}`, error);
|
||||
}
|
||||
}
|
||||
};
|
||||
};
|
||||
@@ -1,66 +1,66 @@
|
||||
import ExcalidrawPlugin from "src/core/main";
|
||||
import {
|
||||
FillStyle,
|
||||
StrokeStyle,
|
||||
ExcalidrawElement,
|
||||
ExcalidrawBindableElement,
|
||||
FileId,
|
||||
NonDeletedExcalidrawElement,
|
||||
ExcalidrawImageElement,
|
||||
ExcalidrawTextElement,
|
||||
StrokeRoundness,
|
||||
RoundnessType,
|
||||
ExcalidrawFrameElement,
|
||||
ExcalidrawTextContainer,
|
||||
FillStyle,
|
||||
StrokeStyle,
|
||||
ExcalidrawElement,
|
||||
ExcalidrawBindableElement,
|
||||
FileId,
|
||||
NonDeletedExcalidrawElement,
|
||||
ExcalidrawImageElement,
|
||||
ExcalidrawTextElement,
|
||||
StrokeRoundness,
|
||||
RoundnessType,
|
||||
ExcalidrawFrameElement,
|
||||
ExcalidrawTextContainer,
|
||||
} from "@zsviczian/excalidraw/types/element/src/types";
|
||||
import { ColorMap, MimeType } from "../types/embeddedFileLoaderTypes";
|
||||
import { Editor, Notice, OpenViewState, RequestUrlResponse, TFile, TFolder, WorkspaceLeaf } from "obsidian";
|
||||
import { ColorMap,MimeType } from "../types/embeddedFileLoaderTypes";
|
||||
import { Editor,Notice,OpenViewState,RequestUrlResponse,TFile,TFolder,WorkspaceLeaf } from "obsidian";
|
||||
import * as obsidian_module from "obsidian";
|
||||
import ExcalidrawView from "src/view/ExcalidrawView";
|
||||
import { TextMode } from "src/shared/TextMode";
|
||||
import {
|
||||
ExcalidrawData,
|
||||
getMarkdownDrawingSection,
|
||||
ExcalidrawData,
|
||||
getMarkdownDrawingSection,
|
||||
} from "./ExcalidrawData";
|
||||
import {
|
||||
FRONTMATTER,
|
||||
nanoid,
|
||||
MAX_IMAGE_SIZE,
|
||||
COLOR_NAMES,
|
||||
fileid,
|
||||
GITHUB_RELEASES,
|
||||
getCommonBoundingBox,
|
||||
getLineHeight,
|
||||
getMaximumGroups,
|
||||
intersectElementWithLine,
|
||||
DEVICE,
|
||||
mermaidToExcalidraw,
|
||||
refreshTextDimensions,
|
||||
getFontFamilyString,
|
||||
FRONTMATTER,
|
||||
nanoid,
|
||||
MAX_IMAGE_SIZE,
|
||||
COLOR_NAMES,
|
||||
fileid,
|
||||
GITHUB_RELEASES,
|
||||
getCommonBoundingBox,
|
||||
getLineHeight,
|
||||
getMaximumGroups,
|
||||
intersectElementWithLine,
|
||||
DEVICE,
|
||||
mermaidToExcalidraw,
|
||||
refreshTextDimensions,
|
||||
getFontFamilyString,
|
||||
} from "src/constants/constants";
|
||||
import { blobToBase64, checkAndCreateFolder, getDrawingFilename, getExcalidrawEmbeddedFilesFiletree, getListOfTemplateFiles, getNewUniqueFilepath, splitFolderAndFilename } from "src/utils/fileUtils";
|
||||
import { blobToBase64,checkAndCreateFolder,getDrawingFilename,getExcalidrawEmbeddedFilesFiletree,getListOfTemplateFiles,getNewUniqueFilepath,splitFolderAndFilename } from "src/utils/fileUtils";
|
||||
import {
|
||||
//debug,
|
||||
getImageSize,
|
||||
isMaskFile,
|
||||
wrapTextAtCharLength,
|
||||
arrayToMap,
|
||||
addAppendUpdateCustomData,
|
||||
getSVG,
|
||||
//debug,
|
||||
getImageSize,
|
||||
isMaskFile,
|
||||
wrapTextAtCharLength,
|
||||
arrayToMap,
|
||||
addAppendUpdateCustomData,
|
||||
getSVG,
|
||||
} from "src/utils/utils";
|
||||
import { InlineLinkSuggester } from "./Suggesters/InlineLinkSuggester";
|
||||
import { getExcalidrawViews, getLeaf, getNewOrAdjacentLeaf, isObsidianThemeDark, mergeMarkdownFiles, openLeaf } from "src/utils/obsidianUtils";
|
||||
import { getExcalidrawViews,getLeaf,getNewOrAdjacentLeaf,isObsidianThemeDark,mergeMarkdownFiles,openLeaf } from "src/utils/obsidianUtils";
|
||||
import { getAttachmentsFolderAndFilePath } from "src/utils/pathUtils";
|
||||
import { AppState, BinaryFileData, DataURL, ExcalidrawImperativeAPI, SceneData } from "@zsviczian/excalidraw/types/excalidraw/types";
|
||||
import { EmbeddedFile, EmbeddedFilesLoader } from "./EmbeddedFileLoader";
|
||||
import { AppState,BinaryFileData,DataURL,ExcalidrawImperativeAPI,SceneData } from "@zsviczian/excalidraw/types/excalidraw/types";
|
||||
import { EmbeddedFile,EmbeddedFilesLoader } from "./EmbeddedFileLoader";
|
||||
import { tex2dataURL } from "./LaTeX";
|
||||
import { NewFileActions } from "src/shared/Dialogs/Prompt";
|
||||
import { ConnectionPoint, DeviceType, Point } from "src/types/types";
|
||||
import CM, { ColorMaster, extendPlugins } from "@zsviczian/colormaster";
|
||||
import { ConnectionPoint,DeviceType,Point } from "src/types/types";
|
||||
import CM,{ ColorMaster,extendPlugins } from "@zsviczian/colormaster";
|
||||
import HarmonyPlugin from "@zsviczian/colormaster/plugins/harmony";
|
||||
import MixPlugin from "@zsviczian/colormaster/plugins/mix"
|
||||
import A11yPlugin from "@zsviczian/colormaster/plugins/accessibility"
|
||||
import NamePlugin from "@zsviczian/colormaster/plugins/name"
|
||||
import MixPlugin from "@zsviczian/colormaster/plugins/mix";
|
||||
import A11yPlugin from "@zsviczian/colormaster/plugins/accessibility";
|
||||
import NamePlugin from "@zsviczian/colormaster/plugins/name";
|
||||
import LCHPlugin from "@zsviczian/colormaster/plugins/lch";
|
||||
import LUVPlugin from "@zsviczian/colormaster/plugins/luv";
|
||||
import LABPlugin from "@zsviczian/colormaster/plugins/lab";
|
||||
@@ -71,28 +71,36 @@ import HSVPlugin from "@zsviczian/colormaster/plugins/hsv";
|
||||
import RYBPlugin from "@zsviczian/colormaster/plugins/ryb";
|
||||
import CMYKPlugin from "@zsviczian/colormaster/plugins/cmyk";
|
||||
import { TInput } from "@zsviczian/colormaster/types";
|
||||
import {ConversionResult, svgToExcalidraw} from "src/shared/svgToExcalidraw/parser"
|
||||
import { ConversionResult,svgToExcalidraw } from "src/shared/svgToExcalidraw/parser";
|
||||
import { ROUNDNESS } from "src/constants/constants";
|
||||
import { ClipboardData } from "@zsviczian/excalidraw/types/excalidraw/clipboard";
|
||||
import { emulateKeysForLinkClick, PaneTarget } from "src/utils/modifierkeyHelper";
|
||||
import { emulateKeysForLinkClick,PaneTarget } from "src/utils/modifierkeyHelper";
|
||||
import { Mutable } from "@zsviczian/excalidraw/types/common/src/utility-types";
|
||||
import PolyBool from "polybooljs";
|
||||
import { EmbeddableMDCustomProps } from "./Dialogs/EmbeddableSettings";
|
||||
import {
|
||||
postOpenAI as _postOpenAI,
|
||||
extractCodeBlocks as _extractCodeBlocks,
|
||||
postAI as _postAI,
|
||||
postOpenAI as _postOpenAI,
|
||||
getAISettings as _getAISettings,
|
||||
generateAIText as _generateAIText,
|
||||
analyzeAIImage as _analyzeAIImage,
|
||||
generateAIImage as _generateAIImage,
|
||||
transformAIImage as _transformAIImage,
|
||||
maskEditAIImage as _maskEditAIImage,
|
||||
createAIChatSession as _createAIChatSession,
|
||||
extractCodeBlocks as _extractCodeBlocks,
|
||||
} from "../utils/AIUtils";
|
||||
import { EXCALIDRAW_AUTOMATE_INFO, EXCALIDRAW_SCRIPTENGINE_INFO } from "./Dialogs/SuggesterInfo";
|
||||
import { EXCALIDRAW_AUTOMATE_INFO,EXCALIDRAW_SCRIPTENGINE_INFO } from "./Dialogs/SuggesterInfo";
|
||||
import { showColorPicker } from "./Dialogs/ColorPicker";
|
||||
import { addBackOfTheNoteCard, getViewColorPalette, sceneRemoveInternalLinks } from "../utils/excalidrawViewUtils";
|
||||
import { addBackOfTheNoteCard,getViewColorPalette,sceneRemoveInternalLinks } from "../utils/excalidrawViewUtils";
|
||||
import { log } from "../utils/debugHelper";
|
||||
import { ExcalidrawLib } from "../types/excalidrawLib";
|
||||
import { GlobalPoint } from "@zsviczian/excalidraw/types/math/src/types";
|
||||
import { AddImageOptions, ImageInfo, KeyBlocker, ScriptSettingValue, SVGColorInfo } from "src/types/excalidrawAutomateTypes";
|
||||
import { _measureText, cloneElement, createPNG, createSVG, ensureActiveScriptSettingsObject, errorMessage, filterColorMap, getEmbeddedFileForImageElment, getLineBox, getTemplate, isColorStringTransparent, isImageOrPDFTransclusion, isSVGColorInfo, mergeColorMapIntoSVGColorInfo, normalizeBindMode, normalizeFixedPoint, normalizeLinePoints, repositionElementsToCursor, svgColorInfoToColorMap, updateOrAddSVGColorInfo, verifyMinimumPluginVersion } from "src/utils/excalidrawAutomateUtils";
|
||||
import { AddImageOptions,ImageInfo,KeyBlocker,ScriptSettingValue,SVGColorInfo } from "src/types/excalidrawAutomateTypes";
|
||||
import { _measureText,cloneElement,createPNG,createSVG,ensureActiveScriptSettingsObject,errorMessage,filterColorMap,getEmbeddedFileForImageElment,getLineBox,getTemplate,isColorStringTransparent,isImageOrPDFTransclusion,isSVGColorInfo,mergeColorMapIntoSVGColorInfo,normalizeBindMode,normalizeFixedPoint,normalizeLinePoints,repositionElementsToCursor,svgColorInfoToColorMap,updateOrAddSVGColorInfo,verifyMinimumPluginVersion } from "src/utils/excalidrawAutomateUtils";
|
||||
import { getLastActiveExcalidrawView } from "src/utils/excalidrawViewLookup";
|
||||
import { exportToPDF, getMarginValue, getPageDimensions } from "src/utils/exportUtils";
|
||||
import { PageDimensions, PageOrientation, PageSize, PDFExportScale, PDFPageProperties, ExportSettings} from "src/types/exportUtilTypes";
|
||||
import { exportToPDF,getMarginValue,getPageDimensions } from "src/utils/exportUtils";
|
||||
import { PageDimensions,PageOrientation,PageSize,PDFExportScale,PDFPageProperties,ExportSettings } from "src/types/exportUtilTypes";
|
||||
import { FrameRenderingOptions } from "src/types/utilTypes";
|
||||
import { CaptureUpdateAction } from "src/constants/constants";
|
||||
import { AutoexportConfig } from "src/types/excalidrawViewTypes";
|
||||
@@ -101,7 +109,7 @@ import { ExcalidrawSidepanelView } from "src/view/sidepanel/Sidepanel";
|
||||
import { ExcalidrawSidepanelTab } from "src/view/sidepanel/SidepanelTab";
|
||||
import { patchMobileView } from "src/utils/customEmbeddableUtils";
|
||||
import { ObsidianCanvasNode } from "src/view/managers/CanvasNodeFactory";
|
||||
import { AIRequest } from "src/types/AIUtilTypes";
|
||||
import { AIRequest,ExcalidrawAISettings } from "src/types/AIUtilTypes";
|
||||
import { getAspectRatio } from "src/utils/YoutTubeUtils";
|
||||
import { getPDFCropRect } from "src/utils/PDFUtils";
|
||||
import { CaptureUpdateActionType } from "@zsviczian/excalidraw/types/element/src";
|
||||
@@ -289,15 +297,73 @@ export class ExcalidrawAutomate {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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> {
|
||||
return await _postAI(request, { plugin: this.plugin });
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
public async postOpenAI(request: AIRequest): Promise<RequestUrlResponse> {
|
||||
return await _postOpenAI(request);
|
||||
return await _postOpenAI(request, { plugin: this.plugin });
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the sanitized Excalidraw AI configuration currently available to scripts.
|
||||
*/
|
||||
public getAISettings(): ExcalidrawAISettings | null {
|
||||
return _getAISettings(this.plugin);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends a text or multimodal chat request to the configured AI text model.
|
||||
*/
|
||||
public async generateAIText(request: AIRequest) {
|
||||
return await _generateAIText(request, { plugin: this.plugin });
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends an image-analysis request to the configured multimodal text model.
|
||||
*/
|
||||
public async analyzeAIImage(request: AIRequest) {
|
||||
return await _analyzeAIImage(request, { plugin: this.plugin });
|
||||
}
|
||||
|
||||
/**
|
||||
* Generates a new image using the configured AI image model.
|
||||
*/
|
||||
public async generateAIImage(request: AIRequest) {
|
||||
return await _generateAIImage(request, { plugin: this.plugin });
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies a prompt-driven edit to an input image using the configured AI image model.
|
||||
*/
|
||||
public async transformAIImage(request: AIRequest) {
|
||||
return await _transformAIImage(request, { plugin: this.plugin });
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies a mask-based edit to an input image using the configured AI image model.
|
||||
*/
|
||||
public async maskEditAIImage(request: AIRequest) {
|
||||
return await _maskEditAIImage(request, { plugin: this.plugin });
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a lightweight chat session wrapper that preserves prior messages between calls.
|
||||
*/
|
||||
public createAIChatSession(initialRequest: Omit<AIRequest, "messages"> = {}) {
|
||||
return _createAIChatSession(initialRequest, { plugin: this.plugin });
|
||||
}
|
||||
|
||||
/**
|
||||
* Extracts code blocks from markdown text.
|
||||
* @param {string} markdown - The markdown string to parse.
|
||||
@@ -555,7 +621,7 @@ export class ExcalidrawAutomate {
|
||||
viewBackgroundColor: string;
|
||||
gridSize: number;
|
||||
};
|
||||
colorPalette: {};
|
||||
colorPalette: object;
|
||||
sidepanelTab: ExcalidrawSidepanelTab | null = null;
|
||||
|
||||
constructor(plugin: ExcalidrawPlugin, view?: ExcalidrawView) {
|
||||
@@ -740,7 +806,7 @@ export class ExcalidrawAutomate {
|
||||
errorMessage("targetView not set", "getExcalidrawAPI()");
|
||||
return null;
|
||||
}
|
||||
const st = (this.getExcalidrawAPI() as ExcalidrawImperativeAPI).getAppState();
|
||||
const st = (this.getExcalidrawAPI()).getAppState();
|
||||
if (!st) return null;
|
||||
|
||||
const zoom = st.zoom?.value ?? 1;
|
||||
@@ -2229,7 +2295,7 @@ export 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.
|
||||
@@ -2256,19 +2322,33 @@ export class ExcalidrawAutomate {
|
||||
}
|
||||
|
||||
const pdfLinkRegex = /^[^#]*#page=\d*(&\w*=[^&]+){0,}&rect=\d*,\d*,\d*,\d*/;
|
||||
const isDataURL = typeof imageFile === "string" && imageFile.startsWith("data:image/");
|
||||
const originalLink = typeof imageFile === "string" ? imageFile : null;
|
||||
const imageFileForLoader = originalLink && pdfLinkRegex.test(originalLink)
|
||||
? originalLink.split("&rect=")[0]
|
||||
: imageFile;
|
||||
|
||||
const id = nanoid();
|
||||
const loader = new EmbeddedFilesLoader(
|
||||
this.plugin,
|
||||
this.canvas.theme === "dark",
|
||||
);
|
||||
const image = (typeof imageFileForLoader === "string")
|
||||
? await loader.getObsidianImage(new EmbeddedFile(this.plugin, "", imageFileForLoader),0)
|
||||
: await loader.getObsidianImage(imageFileForLoader,0);
|
||||
const dataURL = isDataURL ? originalLink : null;
|
||||
const image = isDataURL
|
||||
? {
|
||||
mimeType: dataURL.substring(5, dataURL.indexOf(";")) as MimeType,
|
||||
fileId: fileid() as FileId,
|
||||
dataURL: dataURL as DataURL,
|
||||
created: Date.now(),
|
||||
size: await getImageSize(dataURL),
|
||||
hasSVGwithBitmap: false,
|
||||
pdfPageViewProps: null as any,
|
||||
}
|
||||
: await (() => {
|
||||
const loader = new EmbeddedFilesLoader(
|
||||
this.plugin,
|
||||
this.canvas.theme === "dark",
|
||||
);
|
||||
return typeof imageFileForLoader === "string"
|
||||
? loader.getObsidianImage(new EmbeddedFile(this.plugin, "", imageFileForLoader),0)
|
||||
: loader.getObsidianImage(imageFileForLoader,0);
|
||||
})();
|
||||
|
||||
if (!image) {
|
||||
return null;
|
||||
@@ -2281,11 +2361,11 @@ export class ExcalidrawAutomate {
|
||||
id: fileId,
|
||||
dataURL: image.dataURL,
|
||||
created: image.created,
|
||||
isHyperLink: typeof imageFileForLoader === "string",
|
||||
hyperlink: typeof imageFileForLoader === "string"
|
||||
isHyperLink: typeof imageFileForLoader === "string" && !isDataURL,
|
||||
hyperlink: typeof imageFileForLoader === "string" && !isDataURL
|
||||
? imageFileForLoader
|
||||
: null,
|
||||
file: typeof imageFileForLoader === "string"
|
||||
file: typeof imageFileForLoader === "string" || isDataURL
|
||||
? null
|
||||
: imageFileForLoader.path + (scale || !anchor ? "":"|100%"),
|
||||
hasSVGwithBitmap: image.hasSVGwithBitmap,
|
||||
@@ -2640,7 +2720,7 @@ export class ExcalidrawAutomate {
|
||||
return;
|
||||
}
|
||||
view = getLastActiveExcalidrawView(this.plugin);
|
||||
this.targetView = view ?? getExcalidrawViews(this.plugin.app)[0];
|
||||
this.targetView = view ?? getExcalidrawViews(this.plugin.app, true)[0];
|
||||
return;
|
||||
}
|
||||
if (view == "active") {
|
||||
@@ -2653,7 +2733,7 @@ export class ExcalidrawAutomate {
|
||||
return;
|
||||
}
|
||||
if (view == "first") {
|
||||
this.targetView = getExcalidrawViews(this.plugin.app)[0];
|
||||
this.targetView = getExcalidrawViews(this.plugin.app, true)[0];
|
||||
return;
|
||||
}
|
||||
if (view instanceof ExcalidrawView) {
|
||||
@@ -2671,9 +2751,9 @@ export class ExcalidrawAutomate {
|
||||
|
||||
/**
|
||||
* Returns the Excalidraw API for the current view.
|
||||
* @returns {any} The Excalidraw API.
|
||||
* @returns {ExcalidrawImperativeAPI} The Excalidraw API.
|
||||
*/
|
||||
getExcalidrawAPI(): any {
|
||||
getExcalidrawAPI(): ExcalidrawImperativeAPI {
|
||||
if (!this.targetView || !this.targetView?._loaded) {
|
||||
errorMessage("targetView not set", "getExcalidrawAPI()");
|
||||
return null;
|
||||
@@ -2683,9 +2763,9 @@ export class ExcalidrawAutomate {
|
||||
|
||||
/**
|
||||
* 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[] {
|
||||
if (!this.targetView || !this.targetView?._loaded) {
|
||||
errorMessage("targetView not set", "getViewElements()");
|
||||
return [];
|
||||
@@ -2703,7 +2783,7 @@ export class ExcalidrawAutomate {
|
||||
errorMessage("targetView not set", "deleteViewElements()");
|
||||
return false;
|
||||
}
|
||||
const api = this.targetView?.excalidrawAPI as ExcalidrawImperativeAPI;
|
||||
const api = this.targetView?.excalidrawAPI;
|
||||
if (!api) {
|
||||
return false;
|
||||
}
|
||||
@@ -3080,7 +3160,7 @@ export class ExcalidrawAutomate {
|
||||
viewUpdateScene (
|
||||
scene: {
|
||||
elements?: ExcalidrawElement[],
|
||||
appState?: AppState | {},
|
||||
appState?: AppState | object,
|
||||
files?: BinaryFileData,
|
||||
commitToHistory?: boolean,
|
||||
storeAction?: "capture" | "none" | "update",
|
||||
@@ -3515,7 +3595,7 @@ export 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;
|
||||
@@ -3607,7 +3687,7 @@ export class ExcalidrawAutomate {
|
||||
*/
|
||||
getElementsInTheSameGroupWithElement(
|
||||
element: ExcalidrawElement,
|
||||
elements: ExcalidrawElement[],
|
||||
elements: readonly NonDeletedExcalidrawElement[],
|
||||
includeFrameElements: boolean = false,
|
||||
): ExcalidrawElement[] {
|
||||
if(!element || !elements) return [];
|
||||
@@ -3654,7 +3734,7 @@ export class ExcalidrawAutomate {
|
||||
*/
|
||||
getElementsInFrame(
|
||||
frameElement: ExcalidrawElement,
|
||||
elements: ExcalidrawElement[],
|
||||
elements: readonly NonDeletedExcalidrawElement[],
|
||||
shouldIncludeFrame: boolean = false,
|
||||
): ExcalidrawElement[] {
|
||||
if(!frameElement || !elements || frameElement.type !== "frame") return [];
|
||||
@@ -3672,7 +3752,7 @@ export class ExcalidrawAutomate {
|
||||
* Saves settings in plugin settings, under the activeScript key.
|
||||
* @returns {Object} The script settings.
|
||||
*/
|
||||
getScriptSettings(): {} {
|
||||
getScriptSettings(): object {
|
||||
if (!this.activeScript) {
|
||||
return null;
|
||||
}
|
||||
@@ -3896,7 +3976,7 @@ export class ExcalidrawAutomate {
|
||||
return;
|
||||
}
|
||||
const API = this.getExcalidrawAPI();
|
||||
const elements = this.getViewElements();
|
||||
const elements = this.getViewElements() as Mutable<ExcalidrawElement>[];
|
||||
const elementToMove = elements.filter((el: any) => el.id === elementId);
|
||||
if (elementToMove.length === 0) {
|
||||
errorMessage(
|
||||
|
||||
@@ -5,56 +5,53 @@
|
||||
originalText: this is the text without added linebreaks for wrapping. This will be parsed or markup depending on view mode
|
||||
rawText: text with original markdown markup and without the added linebreaks for wrapping
|
||||
*/
|
||||
import { App, Notice, TFile } from "obsidian";
|
||||
import { App,Notice,TFile } from "obsidian";
|
||||
import {
|
||||
nanoid,
|
||||
fileid,
|
||||
DEVICE,
|
||||
EMBEDDABLE_THEME_FRONTMATTER_VALUES,
|
||||
getLineHeight,
|
||||
ERROR_IFRAME_CONVERSION_CANCELED,
|
||||
JSON_parse,
|
||||
FRONTMATTER_KEYS,
|
||||
refreshTextDimensions,
|
||||
getContainerElement,
|
||||
loadSceneFonts,
|
||||
nanoid,
|
||||
fileid,
|
||||
DEVICE,
|
||||
EMBEDDABLE_THEME_FRONTMATTER_VALUES,
|
||||
getLineHeight,
|
||||
ERROR_IFRAME_CONVERSION_CANCELED,
|
||||
JSON_parse,
|
||||
FRONTMATTER_KEYS,
|
||||
refreshTextDimensions,
|
||||
getContainerElement,
|
||||
loadSceneFonts,
|
||||
} from "../constants/constants";
|
||||
import ExcalidrawPlugin from "../core/main";
|
||||
import { TextMode } from "./TextMode";
|
||||
import type ExcalidrawView from "../view/ExcalidrawView";
|
||||
import { addAppendUpdateCustomData } from "../utils/elementCustomDataUtils";
|
||||
import {
|
||||
compress,
|
||||
decompress,
|
||||
getBinaryFileFromDataURL,
|
||||
_getContainerElement,
|
||||
getExportTheme,
|
||||
getLinkParts,
|
||||
hasExportTheme,
|
||||
isVersionNewerThanOther,
|
||||
LinkParts,
|
||||
updateFrontmatterInString,
|
||||
wrapTextAtCharLength,
|
||||
arrayToMap,
|
||||
compressAsync,
|
||||
compress,
|
||||
decompress,
|
||||
getBinaryFileFromDataURL,getExportTheme,
|
||||
getLinkParts,
|
||||
hasExportTheme,
|
||||
isVersionNewerThanOther,
|
||||
LinkParts,
|
||||
updateFrontmatterInString,
|
||||
wrapTextAtCharLength,
|
||||
arrayToMap,
|
||||
compressAsync
|
||||
} from "../utils/sceneDataUtils";
|
||||
import { isObsidianThemeDark } from "../utils/obsidianUtils";
|
||||
import { cleanBlockRef, cleanSectionHeading } from "../utils/pathUtils";
|
||||
import { cleanBlockRef,cleanSectionHeading } from "../utils/pathUtils";
|
||||
import {
|
||||
ExcalidrawElement,
|
||||
ExcalidrawImageElement,
|
||||
ExcalidrawTextElement,
|
||||
FileId,
|
||||
ExcalidrawElement,
|
||||
ExcalidrawImageElement,
|
||||
ExcalidrawTextElement,
|
||||
FileId,
|
||||
} from "@zsviczian/excalidraw/types/element/src/types";
|
||||
import { BinaryFiles, DataURL, SceneData } from "@zsviczian/excalidraw/types/excalidraw/types";
|
||||
import { BinaryFiles,DataURL,SceneData } from "@zsviczian/excalidraw/types/excalidraw/types";
|
||||
import { EmbeddedFile } from "./EmbeddedFileLoader";
|
||||
import { MimeType } from "src/types/embeddedFileLoaderTypes";
|
||||
import { MultiOptionConfirmationPrompt } from "./Dialogs/Prompt";
|
||||
import { getMermaidImageElements, getMermaidText, shouldRenderMermaid } from "../utils/mermaidUtils";
|
||||
import { DEBUGGING, debug } from "../utils/debugHelper";
|
||||
import { getMermaidImageElements,getMermaidText,shouldRenderMermaid } from "../utils/mermaidUtils";
|
||||
import { Mutable } from "@zsviczian/excalidraw/types/common/src/utility-types";
|
||||
import { updateElementIdsInScene } from "../utils/excalidrawSceneUtils";
|
||||
import { importFileToVault } from "../utils/fileUtils";
|
||||
import { importFileToVault } from "../utils/fileUtils";
|
||||
import { t } from "../lang/helpers";
|
||||
import { displayFontMessage } from "../utils/excalidrawViewUtils";
|
||||
import { getPDFRect } from "../utils/PDFUtils";
|
||||
@@ -151,13 +148,13 @@ export const REGEX_LINK = {
|
||||
const DRAWING_REG = /\n##? Drawing\n[^`]*(```json\n)([\s\S]*?)```\n/gm; //https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/182
|
||||
const DRAWING_REG_FALLBACK = /\n##? Drawing\n(```json\n)?(.*)(```)?(%%)?/gm;
|
||||
export const DRAWING_COMPRESSED_REG =
|
||||
/(\n##? Drawing\n[^`]*(?:```compressed\-json\n))([\s\S]*?)(```\n)/gm; //https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/182
|
||||
/(\n##? Drawing\n[^`]*(?:```compressed-json\n))([\s\S]*?)(```\n)/gm; //https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/182
|
||||
const DRAWING_COMPRESSED_REG_FALLBACK =
|
||||
/(\n##? Drawing\n(?:```compressed\-json\n)?)(.*)((```)?(%%)?)/gm;
|
||||
/(\n##? Drawing\n(?:```compressed-json\n)?)(.*)((```)?(%%)?)/gm;
|
||||
export const REG_LINKINDEX_HYPERLINK = /^\w+:\/\//;
|
||||
|
||||
const isCompressedMD = (data: string): boolean => {
|
||||
return data.match(/```compressed\-json\n/gm) !== null;
|
||||
return data.match(/```compressed-json\n/gm) !== null;
|
||||
};
|
||||
|
||||
const getDecompressedScene = (
|
||||
@@ -254,36 +251,6 @@ export function getMarkdownDrawingSection(
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param text - TextElement.text
|
||||
* @param originalText - TextElement.originalText
|
||||
* @returns null if the textElement is not wrapped or the longest line in the text element
|
||||
*/
|
||||
const estimateMaxLineLen = (text: string, originalText: string): number => {
|
||||
if (!originalText || !text) {
|
||||
return null;
|
||||
}
|
||||
if (text === originalText) {
|
||||
return null;
|
||||
} //text will contain extra new line characters if wrapped
|
||||
let maxLineLen = 0; //will be non-null if text is container bound and multi line
|
||||
const splitText = text.split("\n");
|
||||
if (splitText.length === 1) {
|
||||
return null;
|
||||
}
|
||||
for (const line of splitText) {
|
||||
const l = line.trim();
|
||||
if (l.length > maxLineLen) {
|
||||
maxLineLen = l.length;
|
||||
}
|
||||
}
|
||||
return maxLineLen;
|
||||
};
|
||||
|
||||
const wrap = (text: string, lineLen: number) =>
|
||||
lineLen ? wrapTextAtCharLength(text, lineLen, false, 0) : text;
|
||||
|
||||
//WITHSECTION refers to back of the card note (see this.inputEl.onkeyup in SelectCard.ts)
|
||||
const RE_EXCALIDRAWDATA_WITHSECTION_OK = /^(#\n+)%%\n+# Excalidraw Data(?:\n|$)/m;
|
||||
const RE_EXCALIDRAWDATA_WITHSECTION_NOTOK = /#\n+%%\n+# Excalidraw Data(?:\n|$)/m;
|
||||
@@ -794,7 +761,7 @@ export class ExcalidrawData {
|
||||
displayFontMessage(this.app);
|
||||
}
|
||||
},5000);
|
||||
const fontFaces = await loadSceneFonts(this.scene.elements);
|
||||
await loadSceneFonts(this.scene.elements);
|
||||
clearTimeout(timer);
|
||||
|
||||
if (!this.scene.files) {
|
||||
@@ -977,7 +944,7 @@ export class ExcalidrawData {
|
||||
? data.substring(indexOfNewEmbeddedFiles + embeddedFilesNewLength)
|
||||
: data.substring(indexOfOldEmbeddedFiles + embeddedFilesOldLength);
|
||||
//Load Embedded files
|
||||
const REG_FILEID_FILEPATH = /([\w\d]*):\s*\!?\[\[([^\]]*)]]\s*(\{[^}]*})?\n/gm;
|
||||
const REG_FILEID_FILEPATH = /([\w\d]*):\s*!?\[\[([^\]]*)]]\s*(\{[^}]*})?\n/gm;
|
||||
res = data.matchAll(REG_FILEID_FILEPATH);
|
||||
while (!(parts = res.next()).done) {
|
||||
const embeddedFile = new EmbeddedFile(
|
||||
@@ -1101,7 +1068,6 @@ export class ExcalidrawData {
|
||||
te.width = width;
|
||||
te.height = height;
|
||||
} catch(e) {
|
||||
(process.env.NODE_ENV === 'development') && DEBUGGING && debug(this.updateSceneTextElements, `ExcalidrawData.updateSceneTextElements, textElement:${te?.id}`, te, this.updateSceneTextElements);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1512,7 +1478,7 @@ export class ExcalidrawData {
|
||||
}
|
||||
if (this.files.size > 0) {
|
||||
for (const key of this.files.keys()) {
|
||||
const PATHREG = /(^[^#\|]*)/;
|
||||
const PATHREG = /(^[^#|]*)/;
|
||||
const ef = this.files.get(key);
|
||||
if(ef.isHyperLink || ef.isLocalLink) {
|
||||
outString += `${key}: ${ef.hyperlink}\n\n`;
|
||||
@@ -1615,7 +1581,6 @@ export class ExcalidrawData {
|
||||
}
|
||||
|
||||
private syncCroppedPDFs() {
|
||||
let dirty = false;
|
||||
const scene = this.scene as SceneDataWithFiles;
|
||||
const pdfScale = this.plugin.settings.pdfScale;
|
||||
scene.elements
|
||||
@@ -1632,7 +1597,6 @@ export class ExcalidrawData {
|
||||
(restOfLink ? restOfLink : "]]");
|
||||
el.link = `[[${link}`;
|
||||
this.elementLinks.set(el.id, el.link);
|
||||
dirty = true;
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1879,6 +1843,9 @@ export class ExcalidrawData {
|
||||
|
||||
public getOpenMode(): { viewModeEnabled: boolean; zenModeEnabled: boolean } {
|
||||
const fileCache = this.app.metadataCache.getFileCache(this.file);
|
||||
if (this.plugin.forceExcalidrawViewMode) {
|
||||
return { viewModeEnabled: true, zenModeEnabled: false };
|
||||
}
|
||||
let mode = this.plugin.settings.defaultMode === "view-mobile"
|
||||
? (DEVICE.isPhone ? "view" : "normal")
|
||||
: this.plugin.settings.defaultMode;
|
||||
|
||||
+116
-36
@@ -1,7 +1,8 @@
|
||||
import { App, Notice, TFile } from "obsidian";
|
||||
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 { FILENAMEPARTS,PreviewImageType } from "../types/utilTypes";
|
||||
import { hasExcalidrawEmbeddedImagesTreeChanged } from "../utils/fileUtils";
|
||||
|
||||
//@ts-ignore
|
||||
@@ -9,12 +10,21 @@ const DB_NAME = "Excalidraw " + app.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,8 +34,13 @@ 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.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
|
||||
@@ -48,10 +63,34 @@ 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;
|
||||
@@ -175,11 +214,13 @@ class ImageCache {
|
||||
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)) {
|
||||
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);
|
||||
@@ -301,47 +342,80 @@ class ImageCache {
|
||||
|
||||
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;
|
||||
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.mtime < file.stat.mtime) {
|
||||
return undefined;
|
||||
}
|
||||
return undefined;
|
||||
} catch(e) {
|
||||
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 (e) {
|
||||
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,7 +425,12 @@ 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
|
||||
}
|
||||
@@ -367,12 +446,13 @@ class ImageCache {
|
||||
} else {
|
||||
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(!Boolean(svg) && obsidianURL) {
|
||||
if(this.obsidanURLCache.has(key) && this.obsidanURLCache.get(key) !== obsidianURL) {
|
||||
URL.revokeObjectURL(this.obsidanURLCache.get(key));
|
||||
}
|
||||
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
// LaTeX.ts
|
||||
import { DataURL } from "@zsviczian/excalidraw/types/excalidraw/types";
|
||||
import ExcalidrawView from "../view/ExcalidrawView";
|
||||
import { FileData, MimeType } from "src/types/embeddedFileLoaderTypes";
|
||||
import { FileData,MimeType } from "src/types/embeddedFileLoaderTypes";
|
||||
import { FileId } from "@zsviczian/excalidraw/types/element/src/types";
|
||||
import ExcalidrawPlugin from "src/core/main";
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { ExcalidrawAutomate } from "../ExcalidrawAutomate";
|
||||
import {Notice, requestUrl} from "obsidian"
|
||||
import ExcalidrawPlugin from "../../core/main"
|
||||
import { Notice,requestUrl } from "obsidian";
|
||||
import ExcalidrawPlugin from "../../core/main";
|
||||
import FrontmatterEditor from "src/shared/Frontmatter";
|
||||
import { ExcalidrawElement } from "@zsviczian/excalidraw/types/element/src/types";
|
||||
import { EmbeddedFilesLoader } from "../EmbeddedFileLoader";
|
||||
|
||||
@@ -1,21 +1,21 @@
|
||||
import {
|
||||
App,
|
||||
Instruction,
|
||||
normalizePath,
|
||||
TAbstractFile,
|
||||
TFile,
|
||||
App,
|
||||
Instruction,
|
||||
normalizePath,
|
||||
TAbstractFile,
|
||||
TFile,
|
||||
} from "obsidian";
|
||||
import { PLUGIN_ID } from "../constants/constants";
|
||||
import ExcalidrawView from "../view/ExcalidrawView";
|
||||
import ExcalidrawPlugin from "../core/main";
|
||||
import { GenericInputPrompt, GenericSuggester } from "./Dialogs/Prompt";
|
||||
import { GenericInputPrompt,GenericSuggester } from "./Dialogs/Prompt";
|
||||
import { getIMGFilename } from "../utils/fileUtils";
|
||||
import { splitFolderAndFilename } from "../utils/fileUtils";
|
||||
import { getEA } from "src/core";
|
||||
import { ExcalidrawAutomate } from "../shared/ExcalidrawAutomate";
|
||||
import { WeakArray } from "./WeakArray";
|
||||
import { getExcalidrawViews, stripYamlFrontmatter } from "../utils/obsidianUtils";
|
||||
import { ButtonDefinition, InputPromptOptions } from "src/types/promptTypes";
|
||||
import { getExcalidrawViews,stripYamlFrontmatter } from "../utils/obsidianUtils";
|
||||
import { ButtonDefinition,InputPromptOptions } from "src/types/promptTypes";
|
||||
|
||||
export type ScriptIconMap = {
|
||||
[key: string]: { name: string; group: string; svgString: string };
|
||||
@@ -346,7 +346,7 @@ export class ScriptEngine {
|
||||
}
|
||||
|
||||
private updateToolPannels() {
|
||||
const excalidrawViews = getExcalidrawViews(this.app);
|
||||
const excalidrawViews = getExcalidrawViews(this.app, true);
|
||||
excalidrawViews.forEach(excalidrawView => {
|
||||
excalidrawView.toolsPanelRef?.current?.updateScriptIconMap(
|
||||
this.scriptIconMap,
|
||||
|
||||
@@ -1,17 +1,18 @@
|
||||
import {
|
||||
Editor,
|
||||
EditorPosition,
|
||||
EditorSuggest,
|
||||
EditorSuggestContext,
|
||||
EditorSuggestTriggerInfo,
|
||||
TFile,
|
||||
Editor,
|
||||
EditorPosition,
|
||||
EditorSuggest,
|
||||
EditorSuggestContext,
|
||||
EditorSuggestTriggerInfo,
|
||||
TFile,
|
||||
} from "obsidian";
|
||||
import { FRONTMATTER_KEYS_INFO } from "../Dialogs/SuggesterInfo";
|
||||
import {
|
||||
EXCALIDRAW_AUTOMATE_INFO,
|
||||
EXCALIDRAW_SCRIPTENGINE_INFO,
|
||||
EXCALIDRAW_AUTOMATE_INFO,
|
||||
EXCALIDRAW_SCRIPTENGINE_INFO,
|
||||
} from "../Dialogs/SuggesterInfo";
|
||||
import type ExcalidrawPlugin from "../../core/main";
|
||||
import { setSanitizedHtml } from "src/utils/htmlUtils";
|
||||
|
||||
/**
|
||||
* The field suggester recommends document properties in source mode, ea and utils function and attribute names.
|
||||
@@ -92,7 +93,7 @@ export class FieldSuggester extends EditorSuggest<string> {
|
||||
el.createEl("code", { text: value.code });
|
||||
}
|
||||
if (value.desc) {
|
||||
el.createDiv("div", (el) => (el.innerHTML = value.desc));
|
||||
el.createDiv("div", (el) => setSanitizedHtml(el, value.desc));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,16 +1,16 @@
|
||||
import {
|
||||
FuzzyMatch,
|
||||
TFile,
|
||||
CachedMetadata,
|
||||
TextComponent,
|
||||
App,
|
||||
setIcon,
|
||||
FuzzyMatch,
|
||||
TFile,
|
||||
CachedMetadata,
|
||||
TextComponent,
|
||||
App,
|
||||
setIcon,
|
||||
} from "obsidian";
|
||||
import { SuggestionModal } from "./SuggestionModal";
|
||||
import { t } from "src/lang/helpers";
|
||||
import { LinkSuggestion } from "src/types/types";
|
||||
import ExcalidrawPlugin from "src/core/main";
|
||||
import { AUDIO_TYPES, CODE_TYPES, ICON_NAME, IMAGE_TYPES, VIDEO_TYPES } from "src/constants/constants";
|
||||
import { AUDIO_TYPES,CODE_TYPES,ICON_NAME,IMAGE_TYPES,VIDEO_TYPES } from "src/constants/constants";
|
||||
|
||||
export class FileSuggestionModal extends SuggestionModal<LinkSuggestion> {
|
||||
text: TextComponent;
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import {
|
||||
FuzzyMatch,
|
||||
CachedMetadata,
|
||||
TextComponent,
|
||||
App,
|
||||
TFolder,
|
||||
FuzzyMatch,
|
||||
CachedMetadata,
|
||||
TextComponent,
|
||||
App,
|
||||
TFolder,
|
||||
} from "obsidian";
|
||||
import { SuggestionModal } from "./SuggestionModal";
|
||||
|
||||
|
||||
@@ -1,15 +1,15 @@
|
||||
import { App, FuzzyMatch, TFile } from "obsidian";
|
||||
import { App,FuzzyMatch,TFile } from "obsidian";
|
||||
import { SuggestionModal } from "./SuggestionModal";
|
||||
import { LinkSuggestion } from "src/types/types";
|
||||
import ExcalidrawPlugin from "src/core/main";
|
||||
import {
|
||||
getLinkSuggestionsFiltered,
|
||||
getSortedLinkMatches,
|
||||
renderHeadingSuggestionRow,
|
||||
renderLinkSuggestion,
|
||||
renderParagraphSuggestionRow,
|
||||
fuzzyMatchTextItems,
|
||||
fuzzyMatchParagraphsWithId,
|
||||
getLinkSuggestionsFiltered,
|
||||
getSortedLinkMatches,
|
||||
renderHeadingSuggestionRow,
|
||||
renderLinkSuggestion,
|
||||
renderParagraphSuggestionRow,
|
||||
fuzzyMatchTextItems,
|
||||
fuzzyMatchParagraphsWithId,
|
||||
} from "src/shared/Suggesters/LinkSuggesterUtils";
|
||||
import { KeyBlocker } from "src/types/excalidrawAutomateTypes";
|
||||
import { t } from "src/lang/helpers";
|
||||
@@ -703,7 +703,7 @@ export class InlineLinkSuggester extends SuggestionModal<InlineSuggestion> imple
|
||||
}
|
||||
this.suggestEl.detach();
|
||||
this.shouldNotOpen = false;
|
||||
setTimeout(() => {
|
||||
window.setTimeout(() => {
|
||||
this.block = false;
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
import { App, FuzzyMatch, prepareFuzzySearch, setIcon } from "obsidian";
|
||||
import { App,FuzzyMatch,prepareFuzzySearch,setIcon } from "obsidian";
|
||||
import { LinkSuggestion } from "src/types/types";
|
||||
import {
|
||||
AUDIO_TYPES,
|
||||
CODE_TYPES,
|
||||
ICON_NAME,
|
||||
IMAGE_TYPES,
|
||||
REG_LINKINDEX_INVALIDCHARS,
|
||||
VIDEO_TYPES,
|
||||
AUDIO_TYPES,
|
||||
CODE_TYPES,
|
||||
ICON_NAME,
|
||||
IMAGE_TYPES,
|
||||
REG_LINKINDEX_INVALIDCHARS,
|
||||
VIDEO_TYPES,
|
||||
} from "src/constants/constants";
|
||||
import ExcalidrawPlugin from "src/core/main";
|
||||
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
import {
|
||||
FuzzyMatch,
|
||||
TFile,
|
||||
BlockCache,
|
||||
HeadingCache,
|
||||
CachedMetadata,
|
||||
TextComponent,
|
||||
App,
|
||||
FuzzyMatch,
|
||||
TFile,
|
||||
BlockCache,
|
||||
HeadingCache,
|
||||
CachedMetadata,
|
||||
TextComponent,
|
||||
App,
|
||||
} from "obsidian";
|
||||
import { SuggestionModal } from "./SuggestionModal";
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import {
|
||||
SuggestModal,
|
||||
Scope,
|
||||
SuggestModal,
|
||||
Scope,
|
||||
} from "obsidian";
|
||||
|
||||
export class Suggester<T> {
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
import {
|
||||
FuzzyMatch,
|
||||
App,
|
||||
FuzzySuggestModal,
|
||||
Scope,
|
||||
FuzzyMatch,
|
||||
App,
|
||||
FuzzySuggestModal,
|
||||
Scope,
|
||||
} from "obsidian";
|
||||
import { createPopper, Instance as PopperInstance } from "@popperjs/core";
|
||||
import { createPopper,Instance as PopperInstance } from "@popperjs/core";
|
||||
import { Suggester } from "./Suggester";
|
||||
import { t } from "src/lang/helpers";
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { SavedChats, TTDPersistenceAdapter } from "@zsviczian/excalidraw";
|
||||
import type { SavedChats,TTDPersistenceAdapter } from "@zsviczian/excalidraw";
|
||||
|
||||
const TTD_DB_NAME = "excalidraw-ttd";
|
||||
const TTD_DB_VERSION = 1;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { t } from "src/lang/helpers";
|
||||
import { escapeRegExp } from "../../utils/utils";
|
||||
// @ts-ignore
|
||||
import { getIcon, htmlToMarkdown, Notice } from "obsidian";
|
||||
import { htmlToMarkdown,Notice,setIcon } from "obsidian";
|
||||
|
||||
export class ContentSearcher {
|
||||
private contentDiv: HTMLElement;
|
||||
@@ -46,7 +46,7 @@ export class ContentSearcher {
|
||||
},
|
||||
type: "button",
|
||||
});
|
||||
this.prevButton.innerHTML = getIcon("arrow-up").outerHTML;
|
||||
setIcon(this.prevButton, "arrow-up");
|
||||
|
||||
this.nextButton = createEl("button", {
|
||||
cls: ["clickable-icon", "document-search-button"],
|
||||
@@ -56,7 +56,7 @@ export class ContentSearcher {
|
||||
},
|
||||
type: "button",
|
||||
});
|
||||
this.nextButton.innerHTML = getIcon("arrow-down").outerHTML;
|
||||
setIcon(this.nextButton, "arrow-down");
|
||||
|
||||
this.exportMarkdown = createEl("button", {
|
||||
cls: ["clickable-icon", "document-search-button"],
|
||||
@@ -66,7 +66,7 @@ export class ContentSearcher {
|
||||
},
|
||||
type: "button",
|
||||
});
|
||||
this.exportMarkdown.innerHTML = getIcon("clipboard-copy").outerHTML;
|
||||
setIcon(this.exportMarkdown, "clipboard-copy");
|
||||
|
||||
this.showHideButton = createEl("button", {
|
||||
cls: ["clickable-icon", "document-search-button", "search-visible"],
|
||||
@@ -76,7 +76,7 @@ export class ContentSearcher {
|
||||
},
|
||||
type: "button",
|
||||
});
|
||||
this.showHideButton.innerHTML = getIcon("minimize-2").outerHTML;
|
||||
setIcon(this.showHideButton, "minimize-2");
|
||||
|
||||
buttonContainer.appendChild(this.prevButton);
|
||||
buttonContainer.appendChild(this.nextButton);
|
||||
@@ -102,14 +102,21 @@ export class ContentSearcher {
|
||||
this.nextButton.onclick = () => this.navigateSearchResults("next");
|
||||
this.prevButton.onclick = () => this.navigateSearchResults("previous");
|
||||
this.exportMarkdown.onclick = () => {
|
||||
// Get the full HTML content first
|
||||
const fullHtml = this.contentDiv.outerHTML;
|
||||
|
||||
// Find the index of the first <hr> element
|
||||
const startIndex = fullHtml.indexOf('<hr');
|
||||
|
||||
// Extract HTML from the first <hr> element onwards
|
||||
const html = startIndex > -1 ? fullHtml.substring(startIndex) : fullHtml;
|
||||
const exportContent = this.contentDiv.cloneNode(true) as HTMLElement;
|
||||
exportContent.querySelector(".excalidraw-search")?.remove();
|
||||
|
||||
const childNodes = Array.from(exportContent.childNodes);
|
||||
const startIndex = childNodes.findIndex(
|
||||
(node) => node instanceof HTMLElement && node.tagName === "HR",
|
||||
);
|
||||
const nodesToExport = startIndex > -1 ? childNodes.slice(startIndex) : childNodes;
|
||||
const htmlContainer = document.createElement("div");
|
||||
|
||||
nodesToExport.forEach((node) => {
|
||||
htmlContainer.appendChild(node.cloneNode(true));
|
||||
});
|
||||
|
||||
const html = htmlContainer.innerHTML;
|
||||
|
||||
function replaceHeading(html:string,level:number):string {
|
||||
const re = new RegExp(`<summary class="excalidraw-setting-h${level}">([^<]+)<\/summary>`,"g");
|
||||
@@ -139,13 +146,13 @@ export class ContentSearcher {
|
||||
this.showHideButton.addClass("search-hidden");
|
||||
this.searchBarWrapper.style.backgroundColor = "transparent";
|
||||
setOpacity("0");
|
||||
this.showHideButton.innerHTML = getIcon("maximize-2").outerHTML;
|
||||
setIcon(this.showHideButton, "maximize-2");
|
||||
} else {
|
||||
this.showHideButton.removeClass("search-hidden");
|
||||
this.showHideButton.addClass("search-visible");
|
||||
this.searchBarWrapper.style.backgroundColor = null;
|
||||
setOpacity(null);
|
||||
this.showHideButton.innerHTML = getIcon("minimize-2").outerHTML;
|
||||
setIcon(this.showHideButton, "minimize-2");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -157,7 +164,7 @@ export class ContentSearcher {
|
||||
this.highlightSearchTerm(searchTerm);
|
||||
const totalHits = this.contentDiv.querySelectorAll("mark.search-highlight").length;
|
||||
this.hitCount.textContent = totalHits > 0 ? `1 / ${totalHits}` : "";
|
||||
setTimeout(() => this.navigateSearchResults("next"));
|
||||
window.setTimeout(() => this.navigateSearchResults("next"));
|
||||
} else {
|
||||
this.hitCount.textContent = "";
|
||||
}
|
||||
@@ -236,9 +243,17 @@ export class ContentSearcher {
|
||||
* Remove all search highlights
|
||||
*/
|
||||
public clearHighlights(): void {
|
||||
const parentsToNormalize = new Set<Node>();
|
||||
|
||||
this.contentDiv.querySelectorAll("mark.search-highlight").forEach((el) => {
|
||||
el.outerHTML = el.innerHTML;
|
||||
const parent = el.parentNode;
|
||||
if (!parent) return;
|
||||
|
||||
parentsToNormalize.add(parent);
|
||||
el.replaceWith(document.createTextNode(el.textContent ?? ""));
|
||||
});
|
||||
|
||||
parentsToNormalize.forEach((parent) => parent.normalize());
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -280,11 +295,8 @@ export class ContentSearcher {
|
||||
this.expandParentDetails(nextActiveHighlight);
|
||||
|
||||
// Use setTimeout to ensure DOM has time to update after expanding details
|
||||
setTimeout(() => {
|
||||
nextActiveHighlight.scrollIntoView({
|
||||
behavior: "smooth",
|
||||
block: "nearest",
|
||||
});
|
||||
window.setTimeout(() => {
|
||||
this.scrollResultIntoView(nextActiveHighlight);
|
||||
}, 100);
|
||||
|
||||
// Update the hit count
|
||||
@@ -303,4 +315,46 @@ export class ContentSearcher {
|
||||
parent = parent.parentElement;
|
||||
}
|
||||
}
|
||||
|
||||
private scrollResultIntoView(element: HTMLElement): void {
|
||||
const scrollContainer = this.getScrollContainer(element);
|
||||
const targetRatio = 2 / 3;
|
||||
|
||||
if (!scrollContainer) {
|
||||
const targetScrollTop = window.scrollY + element.getBoundingClientRect().top - window.innerHeight * targetRatio;
|
||||
window.scrollTo({
|
||||
top: Math.max(0, targetScrollTop),
|
||||
behavior: "smooth",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const containerRect = scrollContainer.getBoundingClientRect();
|
||||
const elementRect = element.getBoundingClientRect();
|
||||
const targetScrollTop = scrollContainer.scrollTop + (elementRect.top - containerRect.top) - containerRect.height * targetRatio;
|
||||
const maxScrollTop = Math.max(0, scrollContainer.scrollHeight - scrollContainer.clientHeight);
|
||||
|
||||
scrollContainer.scrollTo({
|
||||
top: Math.min(Math.max(0, targetScrollTop), maxScrollTop),
|
||||
behavior: "smooth",
|
||||
});
|
||||
}
|
||||
|
||||
private getScrollContainer(element: HTMLElement): HTMLElement | null {
|
||||
let parent = element.parentElement;
|
||||
|
||||
while (parent && parent !== document.body) {
|
||||
const style = window.getComputedStyle(parent);
|
||||
const overflowY = style.overflowY;
|
||||
const isScrollable = ["auto", "scroll", "overlay"].includes(overflowY);
|
||||
if (isScrollable && parent.scrollHeight > parent.clientHeight) {
|
||||
return parent;
|
||||
}
|
||||
parent = parent.parentElement;
|
||||
}
|
||||
|
||||
return document.scrollingElement instanceof HTMLElement
|
||||
? document.scrollingElement
|
||||
: null;
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import { randomId, randomInteger } from "../utils";
|
||||
import { randomId,randomInteger } from "../utils";
|
||||
|
||||
import { ExcalidrawLinearElement, FillStyle, GroupId, RoundnessType, StrokeStyle } from "@zsviczian/excalidraw/types/element/src/types";
|
||||
import { ExcalidrawLinearElement,FillStyle,GroupId,RoundnessType,StrokeStyle } from "@zsviczian/excalidraw/types/element/src/types";
|
||||
|
||||
export type Point = [number, number];
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { PathCommand } from "../../../types";
|
||||
import { safeNumber } from "../../../utils";
|
||||
import { curveToPoints } from "./bezier";
|
||||
import { findArc, getEllipsePoints, getEllipsesCenter } from "./ellipse";
|
||||
import { findArc,getEllipsePoints,getEllipsesCenter } from "./ellipse";
|
||||
|
||||
const PATH_COMMANDS_REGEX =
|
||||
/(?:([HhVv] *-?\d*(?:\.\d+)?)|([MmLlTt](?: *-?\d*(?:\.\d+)?(?:,| *)?){2})|([Cc](?: *-?\d*(?:\.\d+)?(?:,| *)?){6})|([QqSs](?: *-?\d*(?:\.\d+)?(?:,| *)?){4})|([Aa](?: *-?\d*(?:\.\d+)?(?:,| *)?){7})|(z|Z))/g;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import ExcalidrawScene from "./elements/ExcalidrawScene";
|
||||
import Group from "./elements/Group";
|
||||
import { createTreeWalker, walk } from "./walker";
|
||||
import { createTreeWalker,walk } from "./walker";
|
||||
|
||||
export type ConversionResult = {
|
||||
hasErrors: boolean;
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import Group from "./elements/Group";
|
||||
import { vec3, mat4 } from "gl-matrix";
|
||||
import { vec3,mat4 } from "gl-matrix";
|
||||
|
||||
/*
|
||||
SVG transform attr is a bit strange in that it can accept traditional
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { ExcalidrawElement, ExcalidrawLinearElement, ExcalidrawTextElement, FillStyle, GroupId, RoundnessType, StrokeStyle } from "@zsviczian/excalidraw/types/element/src/types";
|
||||
import { ExcalidrawElement,ExcalidrawLinearElement,ExcalidrawTextElement,FillStyle,GroupId,RoundnessType,StrokeStyle } from "@zsviczian/excalidraw/types/element/src/types";
|
||||
|
||||
export type PathCommand = {
|
||||
type: string;
|
||||
|
||||
@@ -1,30 +1,30 @@
|
||||
import { mat4 } from "gl-matrix";
|
||||
import { dimensionsFromPoints } from "./utils";
|
||||
import ExcalidrawScene from "./elements/ExcalidrawScene";
|
||||
import Group, { getGroupAttrs } from "./elements/Group";
|
||||
import Group,{ getGroupAttrs } from "./elements/Group";
|
||||
import {
|
||||
ExcalidrawElementBase,
|
||||
ExcalidrawRectangle,
|
||||
ExcalidrawEllipse,
|
||||
ExcalidrawLine,
|
||||
ExcalidrawDraw,
|
||||
createExRect,
|
||||
createExEllipse,
|
||||
createExLine,
|
||||
createExDraw,
|
||||
Point,
|
||||
ExcalidrawElementBase,
|
||||
ExcalidrawRectangle,
|
||||
ExcalidrawEllipse,
|
||||
ExcalidrawLine,
|
||||
ExcalidrawDraw,
|
||||
createExRect,
|
||||
createExEllipse,
|
||||
createExLine,
|
||||
createExDraw,
|
||||
Point,
|
||||
} from "./elements/ExcalidrawElement";
|
||||
import {
|
||||
presAttrsToElementValues,
|
||||
filterAttrsToElementValues,
|
||||
pointsAttrToPoints,
|
||||
has,
|
||||
get,
|
||||
getNum,
|
||||
presAttrsToElementValues,
|
||||
filterAttrsToElementValues,
|
||||
pointsAttrToPoints,
|
||||
has,
|
||||
get,
|
||||
getNum,
|
||||
} from "./attributes";
|
||||
import { getTransformMatrix, transformPoints } from "./transform";
|
||||
import { getTransformMatrix,transformPoints } from "./transform";
|
||||
import { pointsOnPath } from "points-on-path";
|
||||
import { randomId, getWindingOrder } from "./utils";
|
||||
import { randomId,getWindingOrder } from "./utils";
|
||||
import { ROUNDNESS } from "../../constants/constants";
|
||||
|
||||
const SUPPORTED_TAGS = [
|
||||
|
||||
@@ -1,6 +1,60 @@
|
||||
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 | { url: string; detail?: "low" | "high" | "auto" };
|
||||
};
|
||||
|
||||
type MessageContent =
|
||||
| string
|
||||
| (string | { type: "image_url"; image_url: string })[];
|
||||
| ({ type: "text"; text: string } | OpenAIImageURLPart)[];
|
||||
|
||||
export type GPTCompletionRequest = {
|
||||
model: string;
|
||||
@@ -15,6 +69,7 @@ export type GPTCompletionRequest = {
|
||||
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;
|
||||
@@ -32,15 +87,36 @@ export type GPTCompletionRequest = {
|
||||
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; //depends on model
|
||||
quality?: "standard" | "hd"; //depends on model
|
||||
n?: number; //dall-e-3 only accepts 1
|
||||
mask?: string; //dall-e-2 only (image editing)
|
||||
mask?: AIImageInput; //dall-e-2 only (image editing)
|
||||
};
|
||||
};
|
||||
@@ -1,5 +1,5 @@
|
||||
import { FileId } from "@zsviczian/excalidraw/types/element/src/types";
|
||||
import { BinaryFileData, DataURL } from "@zsviczian/excalidraw/types/excalidraw/types";
|
||||
import { BinaryFileData,DataURL } from "@zsviczian/excalidraw/types/excalidraw/types";
|
||||
import { ValueOf } from "../types/types";
|
||||
|
||||
export const IMAGE_MIME_TYPES = {
|
||||
@@ -20,18 +20,22 @@ 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; //true if image should maintain its area, false if image should display at 100% its size
|
||||
pdfPageViewProps?: PDFPageViewProps;
|
||||
renderScale?: number;
|
||||
};
|
||||
|
||||
export type PDFPageViewProps = {
|
||||
|
||||
Loaded 100 of 141 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user