Compare commits

...
Author SHA1 Message Date
zsviczian aaab8fff62 local llm message, remove some unnecessary escape from regexp, and sum unused functions 2026-05-13 20:57:35 +02:00
zsviczian 869ad088a5 KeyObfuscation 2026-05-13 20:14:32 +02:00
zsviczian b9a3b1c71e removed lang pack eval 2026-05-13 19:42:24 +02:00
zsviczian ce2713ecdb fixed any vs. ExcalidrawImperativeAPI 2026-05-13 18:49:38 +02:00
zsviczian 8fefcbcf66 cleanup imports 2026-05-13 13:55:56 +00:00
zsviczian d765e36326 window.setTimeout, window.clearTimeout 2026-05-13 13:41:37 +00:00
zsviczian f6a5236a14 type-only clarity improvements 2026-05-13 13:21:45 +00:00
zsviczian 18c547d0f1 fix icon in rank findings 2026-05-13 12:04:00 +00:00
zsviczian 10f0e26316 removed unsued debugging: (process.env.NODE_ENV === 'development') && DEBUGGING && debug(... 2026-05-13 11:46:42 +00:00
zsviczian a2f277e232 Use object instead of {} 2026-05-13 11:22:05 +00:00
zsviczian 130f518b3b note on style in exportUtils (PDF), contentSearch outerHTML solved, Manifest solved, settings updates views on focus change. 2026-05-13 11:11:44 +00:00
zsviczian b30abb0406 unsafe innerHTML svg assginment convertSVGStringToElement 2026-05-13 08:46:43 +00:00
zsviczian 6a7e3b41e4 css display none 2026-05-13 08:40:01 +00:00
zsviczian 6749c078cc fixing further innerHTMLs 2026-05-13 08:20:35 +00:00
zsviczian 7475a1ad41 addressing InnerHtml 2026-05-13 07:21:09 +00:00
zsviczian 982e9e0848 fix mathjax style issue, add window.setInterwal in Embedded file loader 2026-05-13 06:36:00 +00:00
zsviczian 8df4364bc8 Add GNU AGPL v3 License
Added the GNU Affero General Public License version 3 to the project.
2026-05-13 06:03:31 +02:00
zsviczian 7ca40ceb4f Merge pull request #2757 from zsviczian/excali-ai
Excali ai
2026-05-12 20:53:09 +02:00
zsviczian 3275a7a168 updated package.json with new excalidraw pacakge 2026-05-12 20:51:58 +02:00
zsviczian 41e1a0dd02 ExcaliAI Styling 2026-05-12 18:52:45 +02:00
zsviczian 15c0d34ecc styling 2026-05-12 16:25:30 +00:00
zsviczian 9fe30df73a Refactor ExcaliAI and shared AI settings 2026-05-12 14:01:26 +00:00
zsviczian 1a774d1ed4 opt-in for onload-scripts 2026-05-11 10:28:44 +00:00
zsviczian bf5ea9c27a 2.23.0-beta-2 2026-05-10 17:48:36 +02:00
127 changed files with 9618 additions and 2088 deletions

No files matched your search

+661
View File
@@ -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
View File
@@ -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) {
+9 -9
View File
@@ -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
View File
@@ -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
+2282 -313
View File
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -1 +1 @@
[{"fname":"Mindmap connector.md","mtime":1658686599427},{"fname":"Mindmap connector.svg","mtime":1658686599427},{"fname":"Add Connector Point.md","mtime":1735420748564},{"fname":"Add Connector Point.svg","mtime":1645944722000},{"fname":"Add Link to Existing File and Open.md","mtime":1647807918345},{"fname":"Add Link to Existing File and Open.svg","mtime":1645964261000},{"fname":"Add Link to New Page and Open.md","mtime":1654168862138},{"fname":"Add Link to New Page and Open.svg","mtime":1645960639000},{"fname":"Add Next Step in Process.md","mtime":1688304760357},{"fname":"Add Next Step in Process.svg","mtime":1645960639000},{"fname":"Box Each Selected Groups.md","mtime":1645305706000},{"fname":"Box Each Selected Groups.svg","mtime":1645967510000},{"fname":"Box Selected Elements.md","mtime":1645305706000},{"fname":"Box Selected Elements.svg","mtime":1645960639000},{"fname":"Change shape of selected elements.md","mtime":1652701169236},{"fname":"Change shape of selected elements.svg","mtime":1645960775000},{"fname":"Connect elements.md","mtime":1645305706000},{"fname":"Connect elements.svg","mtime":1645960639000},{"fname":"Convert freedraw to line.md","mtime":1645305706000},{"fname":"Convert freedraw to line.svg","mtime":1645960639000},{"fname":"Convert selected text elements to sticky notes.md","mtime":1670169501383},{"fname":"Convert selected text elements to sticky notes.svg","mtime":1645960639000},{"fname":"Convert text to link with folder and alias.md","mtime":1641639819000},{"fname":"Convert text to link with folder and alias.svg","mtime":1645960639000},{"fname":"Copy Selected Element Styles to Global.md","mtime":1642232088000},{"fname":"Copy Selected Element Styles to Global.svg","mtime":1645960639000},{"fname":"Create new markdown file and embed into active drawing.md","mtime":1640866935000},{"fname":"Create new markdown file and embed into active drawing.svg","mtime":1645960639000},{"fname":"Darken background color.md","mtime":1663059051059},{"fname":"Darken background color.svg","mtime":1645960639000},{"fname":"Elbow connectors.md","mtime":1671126911490},{"fname":"Elbow connectors.svg","mtime":1645960639000},{"fname":"Expand rectangles horizontally keep text centered.md","mtime":1646563692000},{"fname":"Expand rectangles horizontally keep text centered.svg","mtime":1645967510000},{"fname":"Expand rectangles horizontally.md","mtime":1644950235000},{"fname":"Expand rectangles horizontally.svg","mtime":1645967510000},{"fname":"Expand rectangles vertically keep text centered.md","mtime":1646563692000},{"fname":"Expand rectangles vertically keep text centered.svg","mtime":1645967510000},{"fname":"Expand rectangles vertically.md","mtime":1658686599427},{"fname":"Expand rectangles vertically.svg","mtime":1645967510000},{"fname":"Fixed horizontal distance between centers.md","mtime":1646743234000},{"fname":"Fixed horizontal distance between centers.svg","mtime":1645960639000},{"fname":"Fixed inner distance.md","mtime":1646743234000},{"fname":"Fixed inner distance.svg","mtime":1645960639000},{"fname":"Fixed spacing.md","mtime":1646743234000},{"fname":"Fixed spacing.svg","mtime":1645967510000},{"fname":"Fixed vertical distance between centers.md","mtime":1646743234000},{"fname":"Fixed vertical distance between centers.svg","mtime":1645967510000},{"fname":"Fixed vertical distance.md","mtime":1646743234000},{"fname":"Fixed vertical distance.svg","mtime":1645967510000},{"fname":"Lighten background color.md","mtime":1663059051059},{"fname":"Lighten background color.svg","mtime":1645959546000},{"fname":"Modify background color opacity.md","mtime":1644924415000},{"fname":"Modify background color opacity.svg","mtime":1645944722000},{"fname":"Normalize Selected Arrows.md","mtime":1670403743278},{"fname":"Normalize Selected Arrows.svg","mtime":1645960639000},{"fname":"Organic Line.md","mtime":1672920172531},{"fname":"Organic Line.svg","mtime":1645964261000},{"fname":"Organic Line Legacy.md","mtime":1690607372668},{"fname":"Organic Line Legacy.svg","mtime":1690607372668},{"fname":"README.md","mtime":1645175700000},{"fname":"Repeat Elements.md","mtime":1663059051059},{"fname":"Repeat Elements.svg","mtime":1645960639000},{"fname":"Reverse arrows.md","mtime":1645305706000},{"fname":"Reverse arrows.svg","mtime":1645960639000},{"fname":"Scribble Helper.md","mtime":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
+2 -2
View File
@@ -1,9 +1,9 @@
{
"id": "obsidian-excalidraw-plugin",
"name": "Excalidraw",
"version": "2.23.0-beta-1",
"version": "2.23.0-beta-4",
"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",
"isDesktopOnly": false
+1 -1
View File
@@ -3,7 +3,7 @@
"name": "Excalidraw",
"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",
+4 -4
View File
@@ -11,7 +11,7 @@
"dependencies": {
"@popperjs/core": "^2.11.8",
"@zsviczian/colormaster": "^1.2.2",
"@zsviczian/excalidraw": "0.18.0-88",
"@zsviczian/excalidraw": "0.18.0-90",
"chroma-js": "^3.1.2",
"clsx": "^2.0.0",
"es6-promise-pool": "2.5.0",
@@ -4769,9 +4769,9 @@
"license": "MIT"
},
"node_modules/@zsviczian/excalidraw": {
"version": "0.18.0-88",
"resolved": "https://registry.npmjs.org/@zsviczian/excalidraw/-/excalidraw-0.18.0-88.tgz",
"integrity": "sha512-2xEgAxPr8fHZXHYBV9wRe2ltbhuVkimsN0Sm9NKtqNpx5+5J8OUvIK9+h6+zVqAIIZ3pT/qtoIDe18uL8ozpZw==",
"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",
+1 -1
View File
@@ -25,7 +25,7 @@
"license": "MIT",
"dependencies": {
"@popperjs/core": "^2.11.8",
"@zsviczian/excalidraw": "0.18.0-90",
"@zsviczian/excalidraw": "0.18.0-91",
"chroma-js": "^3.1.2",
"clsx": "^2.0.0",
"@zsviczian/colormaster": "^1.2.2",
+139 -2
View File
@@ -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
+3 -3
View File
@@ -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("&#91;", "["));
export function JSON_parse<T>(x: string): T {
return JSON.parse(x.replaceAll("&#91;", "[")) 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);
-3
View File
@@ -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 -1
View File
@@ -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
View File
@@ -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) {
+241 -88
View File
@@ -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;
@@ -121,6 +127,18 @@ const PHONE_FOOTER_SAFE_AREA_CSS = `
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",
@@ -153,6 +171,14 @@ 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) => {
@@ -181,10 +207,14 @@ const migrateLegacyAISettings = (
};
assignStringIfMissing("aiAPIKey", settings.openAIAPIToken);
assignStringIfMissing("aiDefaultMultimodalModel", settings.aiDefaultVisionModel);
assignStringIfMissing("aiDefaultMultimodalModel", settings.openAIDefaultVisionModel);
assignStringIfMissing("aiDefaultTextModel", settings.openAIDefaultTextModel);
assignStringIfMissing("aiDefaultVisionModel", settings.openAIDefaultVisionModel);
assignStringIfMissing("aiDefaultTextModel", settings.aiDefaultVisionModel);
assignStringIfMissing("aiDefaultTextModel", settings.openAIDefaultVisionModel);
assignStringIfMissing("aiDefaultImageGenerationModel", settings.openAIDefaultImageGenerationModel);
assignPositiveNumberIfMissing("aiDefaultMaxTokens", settings.openAIDefaultTextModelMaxTokens);
assignPositiveNumberIfMissing("aiDefaultMaxResponseTokens", settings.aiDefaultMaxTokens);
assignPositiveNumberIfMissing("aiDefaultMaxResponseTokens", settings.openAIDefaultTextModelMaxTokens);
const legacyTextEndpoint = normalizeAISettingURL(settings.openAIURL);
const inferredLegacyBaseURL = legacyTextEndpoint.endsWith(AI_TEXT_SUFFIX)
@@ -224,6 +254,140 @@ const migrateLegacyAISettings = (
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 };
};
@@ -646,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];
@@ -655,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);
@@ -708,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) {
@@ -773,7 +935,6 @@ export default class ExcalidrawPlugin extends Plugin {
}
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;
@@ -788,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)) {
@@ -1034,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));
@@ -1048,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 });
@@ -1121,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;
@@ -1174,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
@@ -1201,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;
@@ -1222,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;
}
@@ -1321,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;
@@ -1417,12 +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;
const rawSettings = ((await this.loadData()) ?? {}) as PersistedExcalidrawSettings;
const { settings: migratedSettings, didMigrate } = migrateLegacyAISettings(rawSettings);
const persistedSettings = stripLegacyAISettings(migratedSettings);
this.settings = Object.assign({}, DEFAULT_SETTINGS, persistedSettings);
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;
@@ -1432,24 +1586,25 @@ export default class ExcalidrawPlugin extends Plugin {
: PreviewImageType.PNG;
}
}
if (didMigrate) {
await this.saveData(persistedSettings);
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(stripLegacyAISettings(this.settings as PersistedExcalidrawSettings));
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"
@@ -1459,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;
@@ -1470,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)=>{
+40 -40
View File
@@ -1,65 +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,
CaptureUpdateAction,
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, getExcalidrawViews, 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";
@@ -69,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";
@@ -338,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>)=>{
@@ -1026,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;
}
+4 -8
View File
@@ -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";
@@ -181,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) {
@@ -265,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;
}
@@ -317,7 +315,6 @@ export class EventManager {
}
private onFileMenuSaveActiveDrawing () {
(process.env.NODE_ENV === 'development') && DEBUGGING && debug(this.onFileMenuSaveActiveDrawing,`onFileMenuSaveActiveDrawing`);
if (
!this.activeExcalidrawView ||
!this.activeExcalidrawView?.isDirty()
@@ -328,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;
+20 -15
View File
@@ -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,7 +413,6 @@ 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;
}
@@ -459,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) {
@@ -563,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;
}
+23 -36
View File
@@ -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,
@@ -259,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,
@@ -326,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]);
@@ -401,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;
@@ -424,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;
@@ -553,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));
};
@@ -562,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
@@ -594,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: "",
@@ -727,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;
@@ -739,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);
@@ -754,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;
@@ -956,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
@@ -992,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;
}
+5 -9
View File
@@ -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,7 +77,7 @@ 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, true);
excalidrawViews.forEach(excalidrawView => {
@@ -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();
};
-5
View File
@@ -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);
+6 -7
View File
@@ -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});
+740 -230
View File
File diff suppressed because it is too large. Load diff
+95 -8
View File
@@ -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;
}
}
+125 -19
View File
@@ -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;
@@ -309,17 +309,28 @@ export default {
`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. ` +
`These settings are used by ExcalidrawAutomate, Mermaid chat, and diagram-to-code. In most cases you only need to set Provider, API key, and the default model fields. Leave endpoint overrides blank unless your provider requires custom URLs. Older OpenAI-specific AI settings are migrated here automatically on first run.`,
`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_PROVIDER_NAME: "AI provider",
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:
"Choose the provider used by the shared AI layer. OpenAI-compatible also covers local endpoints such as LM Studio, vLLM, or OpenWebUI.",
"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.",
@@ -330,7 +341,7 @@ export default {
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 vision requests. Leave blank to derive it from the base URL and provider. Most users should keep this empty.",
"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:
@@ -344,22 +355,108 @@ export default {
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: "AI default text model",
AI_PROVIDER_DEFAULT_TEXT_MODEL_NAME: "Text and multimodal model",
AI_PROVIDER_DEFAULT_TEXT_MODEL_DESC:
"Default model used for text-only requests such as Mermaid chat.",
"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: "AI default vision model",
AI_PROVIDER_DEFAULT_VISION_MODEL_NAME: "Vision model",
AI_PROVIDER_DEFAULT_VISION_MODEL_DESC:
"Default model used for image understanding tasks such as diagram-to-code or image-plus-text prompts.",
"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: "AI default image model",
AI_PROVIDER_DEFAULT_IMAGE_MODEL_NAME: "Image model",
AI_PROVIDER_DEFAULT_IMAGE_MODEL_DESC:
"Default model used for image generation and image edits. Today this is primarily relevant for OpenAI or OpenAI-compatible image endpoints.",
"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_PROVIDER_DEFAULT_MAX_TOKENS_NAME: "AI default max tokens",
AI_PROVIDER_DEFAULT_MAX_TOKENS_DESC:
"Shared max token limit for text responses. This applies to provider-aware text and vision requests. Use 0 to omit the token limit field entirely.",
AI_PROVIDER_DEFAULT_MAX_TOKENS_PLACEHOLDER: "e.g.: 4096",
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",
@@ -882,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 " +
+88 -18
View File
@@ -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;
@@ -298,14 +298,27 @@ export default {
`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_PROVIDER_NAME: "Proveedor de IA",
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:
"Elige el proveedor usado por la capa compartida de IA. OpenAI-compatible también cubre endpoints locales como LM Studio, vLLM u OpenWebUI.",
"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.",
@@ -316,7 +329,7 @@ export default {
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 visión. Déjalo vacío para derivarlo de la URL base y el proveedor. La mayoría de usuarios no necesita rellenarlo.",
"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:
@@ -330,22 +343,70 @@ export default {
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 predeterminado de IA",
AI_PROVIDER_DEFAULT_TEXT_MODEL_NAME: "Modelo de texto y multimodal",
AI_PROVIDER_DEFAULT_TEXT_MODEL_DESC:
"Modelo predeterminado usado para solicitudes solo de texto, como Mermaid chat.",
"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 predeterminado de IA",
AI_PROVIDER_DEFAULT_VISION_MODEL_NAME: "Modelo de visión",
AI_PROVIDER_DEFAULT_VISION_MODEL_DESC:
"Modelo predeterminado usado para tareas de comprensión de imágenes, como diagram-to-code o solicitudes con imagen y texto.",
"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 predeterminado de IA",
AI_PROVIDER_DEFAULT_IMAGE_MODEL_NAME: "Modelo de imagen",
AI_PROVIDER_DEFAULT_IMAGE_MODEL_DESC:
"Modelo predeterminado usado para generación y edición de imágenes. Hoy esto es especialmente relevante para OpenAI o endpoints de imagen compatibles con OpenAI.",
"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_PROVIDER_DEFAULT_MAX_TOKENS_NAME: "Máximo de tokens predeterminado de IA",
AI_PROVIDER_DEFAULT_MAX_TOKENS_DESC:
"Límite compartido de tokens para respuestas de texto. Se aplica a solicitudes de texto y visión conscientes del proveedor. Usa 0 para omitir por completo el campo del límite de tokens.",
AI_PROVIDER_DEFAULT_MAX_TOKENS_PLACEHOLDER: "p. ej.: 4096",
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",
@@ -839,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 " +
+86 -16
View File
@@ -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 {
@@ -235,14 +235,27 @@ export default {
`Эти параметры используются ExcalidrawAutomate, Mermaid chat и diagram-to-code. В большинстве случаев достаточно указать провайдера, API-ключ и модели по умолчанию. Переопределения конечных точек оставляйте пустыми, если ваш провайдер не требует собственных URL. Старые настройки ИИ, привязанные только к OpenAI, будут автоматически перенесены сюда при первом запуске.`,
AI_ENABLED_NAME: "Включить функции ИИ",
AI_ENABLED_DESC: "Чтобы изменения вступили в силу, необходимо заново открыть Excalidraw.",
AI_PROVIDER_NAME: "Провайдер ИИ",
AI_VERBOSE_LOGGING_NAME: "Включить подробное логирование ИИ",
AI_VERBOSE_LOGGING_DESC: "Выводит подробную диагностику AI-запросов и ответов в консоль разработчика. Оставляйте выключенным, если не занимаетесь отладкой.",
AI_PROVIDER_NAME: "Определить доступных провайдеров",
AI_PROVIDER_DESC:
"Выберите провайдера, используемого общим слоем ИИ. Пункт OpenAI-compatible также подходит для локальных конечных точек, таких как LM Studio, vLLM или OpenWebUI.",
"Определите профили провайдеров, доступные для списков моделей ниже. Текст, 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-ключ, используемый общим слоем ИИ. Значение скрыто, пока поле не находится в фокусе.",
@@ -253,7 +266,7 @@ export default {
AI_PROVIDER_BASE_URL_PLACEHOLDER: "например: https://api.openai.com/v1",
AI_PROVIDER_TEXT_ENDPOINT_NAME: "Переопределение endpoint текста ИИ",
AI_PROVIDER_TEXT_ENDPOINT_DESC:
"Необязательное полное переопределение endpoint для текстовых и vision-запросов. Оставьте пустым, чтобы он вычислялся из базового URL и провайдера. Большинству пользователей это поле не нужно.",
"Необязательное полное переопределение endpoint для текстовых и мультимодальных запросов. Оставьте пустым, чтобы он вычислялся из базового URL и провайдера. Большинству пользователей это поле не нужно.",
AI_PROVIDER_TEXT_ENDPOINT_PLACEHOLDER: "Необязательный полный endpoint текста",
AI_PROVIDER_IMAGE_GENERATION_ENDPOINT_NAME: "Переопределение endpoint генерации изображений ИИ",
AI_PROVIDER_IMAGE_GENERATION_ENDPOINT_DESC:
@@ -267,22 +280,70 @@ export default {
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_NAME: "Текстовая и мультимодальная модель",
AI_PROVIDER_DEFAULT_TEXT_MODEL_DESC:
"Модель по умолчанию для текстовых запросов, таких как Mermaid chat.",
"Модель для текстового чата и запросов с изображениями, например 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_NAME: "Vision-модель",
AI_PROVIDER_DEFAULT_VISION_MODEL_DESC:
"Модель по умолчанию для задач понимания изображений, таких как diagram-to-code или запросы с изображением и текстом.",
"Модель для понимания изображений, например 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_NAME: "Модель изображений",
AI_PROVIDER_DEFAULT_IMAGE_MODEL_DESC:
"Модель по умолчанию для генерации и редактирования изображений. Сейчас это в первую очередь актуально для OpenAI или OpenAI-совместимых image endpoints.",
"Модель для генерации изображений, 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_PROVIDER_DEFAULT_MAX_TOKENS_NAME: "Максимум токенов ИИ по умолчанию",
AI_PROVIDER_DEFAULT_MAX_TOKENS_DESC:
"Общий лимит токенов для текстовых ответов. Применяется к provider-aware текстовым и vision-запросам. Используйте 0, чтобы полностью убрать поле лимита токенов.",
AI_PROVIDER_DEFAULT_MAX_TOKENS_PLACEHOLDER: "например: 4096",
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",
@@ -732,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. " +
+88 -18
View File
@@ -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;
@@ -312,14 +312,27 @@ export default {
`这些设置会被 ExcalidrawAutomate、Mermaid chat 和 diagram-to-code 共用。大多数情况下,您只需要设置提供商、API key 和默认模型。除非您的提供商要求自定义 URL,否则请将各 endpoint 覆盖项留空。旧的 OpenAI 专用 AI 设置会在首次运行时自动迁移到这里。`,
AI_ENABLED_NAME: "启用 AI 功能",
AI_ENABLED_DESC: "您需要重新打开 Excalidraw 才能使更改生效。",
AI_PROVIDER_NAME: "AI 提供商",
AI_VERBOSE_LOGGING_NAME: "启用详细 AI 日志",
AI_VERBOSE_LOGGING_DESC: "将详细的 AI 请求和响应诊断信息写入开发者控制台。除非您正在排查问题,否则请保持关闭。",
AI_PROVIDER_NAME: "定义可用提供商",
AI_PROVIDER_DESC:
"选择共享 AI 层使用的提供商。OpenAI-compatible 也包括 LM Studio、vLLM 或 OpenWebUI 等本地 endpoint。",
"定义下方模型列表可用的提供商配置。文本、视觉和图像模型各自独立选择提供商。",
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。除非输入框获得焦点,否则该值会被隐藏。",
@@ -330,7 +343,7 @@ export default {
AI_PROVIDER_BASE_URL_PLACEHOLDER: "例如:https://api.openai.com/v1",
AI_PROVIDER_TEXT_ENDPOINT_NAME: "AI 文本 endpoint 覆盖",
AI_PROVIDER_TEXT_ENDPOINT_DESC:
"可选的完整 endpoint 覆盖,用于文本和视觉请求。留空时会根据基础 URL 和提供商自动推导。大多数用户无需填写。",
"可选的完整 endpoint 覆盖,用于文本和多模态请求。留空时会根据基础 URL 和提供商自动推导。大多数用户无需填写。",
AI_PROVIDER_TEXT_ENDPOINT_PLACEHOLDER: "可选的完整文本 endpoint",
AI_PROVIDER_IMAGE_GENERATION_ENDPOINT_NAME: "AI 图像生成 endpoint 覆盖",
AI_PROVIDER_IMAGE_GENERATION_ENDPOINT_DESC:
@@ -344,22 +357,70 @@ export default {
AI_PROVIDER_IMAGE_VARIATIONS_ENDPOINT_DESC:
"可选的完整 endpoint 覆盖,用于图像变体请求。除非您的提供商使用非标准路径,否则请留空。",
AI_PROVIDER_IMAGE_VARIATIONS_ENDPOINT_PLACEHOLDER: "可选的完整图像变体 endpoint",
AI_PROVIDER_DEFAULT_TEXT_MODEL_NAME: "AI 默认文本模型",
AI_PROVIDER_DEFAULT_TEXT_MODEL_NAME: "文本与多模态模型",
AI_PROVIDER_DEFAULT_TEXT_MODEL_DESC:
"用于 Mermaid chat 等纯文本请求的默认模型。",
"用于文本聊天和图像理解请求的模型,例如 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 默认视觉模型",
AI_PROVIDER_DEFAULT_VISION_MODEL_NAME: "视觉模型",
AI_PROVIDER_DEFAULT_VISION_MODEL_DESC:
"用于 diagram-to-code 或图文混合提示等图像理解任务的默认模型。",
"用于 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 默认图像模型",
AI_PROVIDER_DEFAULT_IMAGE_MODEL_NAME: "图像模型",
AI_PROVIDER_DEFAULT_IMAGE_MODEL_DESC:
"用于图像生成和图像编辑的默认模型。目前这主要适用于 OpenAI 或兼容 OpenAI 的图像 endpoint。",
"用于图像生成、基于提示词的图像变换和蒙版编辑的模型。使用“编辑”“添加”“删除”按钮修改列表。<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_PROVIDER_DEFAULT_MAX_TOKENS_NAME: "AI 默认最大 token 数",
AI_PROVIDER_DEFAULT_MAX_TOKENS_DESC:
"文本响应的共享 token 上限。适用于具备 provider 感知能力的文本和视觉请求。填入 0 可完全省略 token 上限字段。",
AI_PROVIDER_DEFAULT_MAX_TOKENS_PLACEHOLDER: "例如:4096",
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",
@@ -882,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 自动化脚本设置钩子。" +
+88 -18
View File
@@ -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;
@@ -312,14 +312,27 @@ export default {
`這些設定會被 ExcalidrawAutomate、Mermaid chat 和 diagram-to-code 共用。大多數情況下,您只需要設定供應商、API key 和預設模型。除非您的供應商要求自訂 URL,否則請將各 endpoint 覆寫欄位留空。舊的 OpenAI 專用 AI 設定會在首次執行時自動遷移到這裡。`,
AI_ENABLED_NAME: "啟用 AI 功能",
AI_ENABLED_DESC: "您需要重新開啟 Excalidraw 才能使更改生效。",
AI_PROVIDER_NAME: "AI 供應商",
AI_VERBOSE_LOGGING_NAME: "啟用詳細 AI 日誌",
AI_VERBOSE_LOGGING_DESC: "將詳細的 AI 請求與回應診斷資訊寫入開發者主控台。除非您正在排查問題,否則請保持關閉。",
AI_PROVIDER_NAME: "定義可用供應商",
AI_PROVIDER_DESC:
"選擇共享 AI 層使用的供應商。OpenAI-compatible 也包含 LM Studio、vLLM 或 OpenWebUI 等本地 endpoint。",
"定義下方模型清單可用的供應商設定。文字、視覺與圖像模型各自獨立選擇供應商。",
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。除非輸入欄位取得焦點,否則該值會被隱藏。",
@@ -330,7 +343,7 @@ export default {
AI_PROVIDER_BASE_URL_PLACEHOLDER: "例如:https://api.openai.com/v1",
AI_PROVIDER_TEXT_ENDPOINT_NAME: "AI 文字 endpoint 覆寫",
AI_PROVIDER_TEXT_ENDPOINT_DESC:
"可選的完整 endpoint 覆寫,用於文字與視覺請求。留空時會根據基礎 URL 和供應商自動推導。大多數使用者不需要填寫。",
"可選的完整 endpoint 覆寫,用於文字與多模態請求。留空時會根據基礎 URL 和供應商自動推導。大多數使用者不需要填寫。",
AI_PROVIDER_TEXT_ENDPOINT_PLACEHOLDER: "可選的完整文字 endpoint",
AI_PROVIDER_IMAGE_GENERATION_ENDPOINT_NAME: "AI 圖像生成 endpoint 覆寫",
AI_PROVIDER_IMAGE_GENERATION_ENDPOINT_DESC:
@@ -344,22 +357,70 @@ export default {
AI_PROVIDER_IMAGE_VARIATIONS_ENDPOINT_DESC:
"可選的完整 endpoint 覆寫,用於圖像變體請求。除非您的供應商使用非標準路徑,否則請留空。",
AI_PROVIDER_IMAGE_VARIATIONS_ENDPOINT_PLACEHOLDER: "可選的完整圖像變體 endpoint",
AI_PROVIDER_DEFAULT_TEXT_MODEL_NAME: "AI 預設文字模型",
AI_PROVIDER_DEFAULT_TEXT_MODEL_NAME: "文字與多模態模型",
AI_PROVIDER_DEFAULT_TEXT_MODEL_DESC:
"用於 Mermaid chat 等純文字請求的預設模型。",
"用於文字聊天與圖像理解請求的模型,例如 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 預設視覺模型",
AI_PROVIDER_DEFAULT_VISION_MODEL_NAME: "視覺模型",
AI_PROVIDER_DEFAULT_VISION_MODEL_DESC:
"用於 diagram-to-code 或圖文混合提示等圖像理解任務的預設模型。",
"用於 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 預設圖像模型",
AI_PROVIDER_DEFAULT_IMAGE_MODEL_NAME: "圖像模型",
AI_PROVIDER_DEFAULT_IMAGE_MODEL_DESC:
"用於圖像生成與圖像編輯的預設模型。目前這主要適用於 OpenAI 或相容 OpenAI 的圖像 endpoint。",
"用於圖像生成、提示詞驅動的圖像轉換與遮罩編輯的模型。使用「編輯」、「新增」、「刪除」按鈕修改列表。<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_PROVIDER_DEFAULT_MAX_TOKENS_NAME: "AI 預設最大 token 數",
AI_PROVIDER_DEFAULT_MAX_TOKENS_DESC:
"文字回應的共享 token 上限。適用於具備 provider 感知能力的文字與視覺請求。填入 0 可完全省略 token 上限欄位。",
AI_PROVIDER_DEFAULT_MAX_TOKENS_PLACEHOLDER: "例如:4096",
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",
@@ -882,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 自動化指令碼設定鉤子。" +
+1 -3
View File
@@ -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();
}
}
+295
View File
@@ -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();
}
}
+1 -1
View File
@@ -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";
+5 -5
View File
@@ -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());
})
+10 -10
View File
@@ -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";
@@ -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,
+2 -2
View File
@@ -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 -2
View File
@@ -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 -1
View File
@@ -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 -1
View File
@@ -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";
+9 -10
View File
@@ -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();
}
+2 -2
View File
@@ -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";
+2 -2
View File
@@ -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 -1
View File
@@ -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";
+7 -6
View File
@@ -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);
+54 -5
View File
@@ -7,22 +7,29 @@ I build this plugin as a labor of love. Curious about the philosophy behind it?
`,
"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.
- The shared AI configuration is now used by ExcalidrawAutomate, Mermaid chat, diagram-to-code, and related AI features.
- 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 OpenAI image responses that return \`b64_json\` instead of a hosted URL.
- 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 AI helper functions for scripts while retaining backward compatibility for existing \`postOpenAI()\` integrations.
- 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.
@@ -35,12 +42,54 @@ I build this plugin as a labor of love. Curious about the philosophy behind it?
public async postAI(request: AIRequest): Promise<RequestUrlResponse>;
/**
* Posts an AI request to the OpenAI API and returns the response.
* 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 API response.
* @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.
+1 -1
View File
@@ -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;
+1 -1
View File
@@ -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 {
+4 -4
View File
@@ -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> = {
@@ -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)
+35 -32
View File
@@ -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() {
+3 -2
View File
@@ -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.";
+8 -3
View File
@@ -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 -1
View File
@@ -1,4 +1,4 @@
import { App, MarkdownRenderer, Modal } from "obsidian";
import { App,MarkdownRenderer,Modal } from "obsidian";
import { isVersionNewerThanOther } from "src/utils/utils";
import ExcalidrawPlugin from "../../core/main";
import { RELEASE_NOTES } from "./Messages";
+1 -1
View File
@@ -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";
+2 -2
View File
@@ -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> {
+71 -4
View File
@@ -1037,20 +1037,87 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
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?, image?, text?, instruction?, systemPrompt?, messages?, temperature?, maxTokens?, imageGenerationProperties? }</code><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>image</b>: either a data URL string or <code>{url:string}</code>. Use this with vision requests or image edits.<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}}]}</code>.<br>" +
"<b>temperature</b> and <b>maxTokens</b>: optional generation controls.<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 }[]",
+2 -2
View File
@@ -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;
+12 -8
View File
@@ -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)";
+1 -1
View File
@@ -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",
+33 -32
View File
@@ -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
@@ -869,9 +870,9 @@ export class EmbeddedFilesLoader {
};
}
const addFilesTimer = setInterval(() => {
const addFilesTimer = window.setInterval(() => {
if (this.terminate) {
clearInterval(addFilesTimer);
window.clearInterval(addFilesTimer);
return;
}
if(files[batch].length === 0) {
@@ -1316,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);
+129 -73
View File
@@ -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,29 +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 {
postAI as _postAI,
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";
@@ -102,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";
@@ -296,7 +303,7 @@ export class ExcalidrawAutomate {
* @returns {Promise<RequestUrlResponse>} Promise resolving to the provider-normalized API response.
*/
public async postAI(request: AIRequest): Promise<RequestUrlResponse> {
return await _postAI(request);
return await _postAI(request, { plugin: this.plugin });
}
/**
@@ -305,9 +312,58 @@ export class ExcalidrawAutomate {
* @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.
@@ -565,7 +621,7 @@ export class ExcalidrawAutomate {
viewBackgroundColor: string;
gridSize: number;
};
colorPalette: {};
colorPalette: object;
sidepanelTab: ExcalidrawSidepanelTab | null = null;
constructor(plugin: ExcalidrawPlugin, view?: ExcalidrawView) {
@@ -750,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;
@@ -2695,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;
@@ -2707,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 [];
@@ -2727,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;
}
@@ -3104,7 +3160,7 @@ export class ExcalidrawAutomate {
viewUpdateScene (
scene: {
elements?: ExcalidrawElement[],
appState?: AppState | {},
appState?: AppState | object,
files?: BinaryFileData,
commitToHistory?: boolean,
storeAction?: "capture" | "none" | "update",
@@ -3539,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;
@@ -3631,7 +3687,7 @@ export class ExcalidrawAutomate {
*/
getElementsInTheSameGroupWithElement(
element: ExcalidrawElement,
elements: ExcalidrawElement[],
elements: readonly NonDeletedExcalidrawElement[],
includeFrameElements: boolean = false,
): ExcalidrawElement[] {
if(!element || !elements) return [];
@@ -3678,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 [];
@@ -3696,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;
}
@@ -3920,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(
+37 -73
View File
@@ -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;
});
}
+6 -6
View File
@@ -1,8 +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 { 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
@@ -89,8 +89,8 @@ class ImageCache {
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;
@@ -357,7 +357,7 @@ class ImageCache {
? await this.getCacheData(key)
: await Promise.race([
this.getCacheData(key),
new Promise<undefined>((_, reject) => setTimeout(() => {
new Promise<undefined>((_, reject) => window.setTimeout(() => {
reject(undefined);
}, 100))
]);
+1 -1
View File
@@ -1,7 +1,7 @@
// LaTeX.ts
import { DataURL } from "@zsviczian/excalidraw/types/excalidraw/types";
import ExcalidrawView from "../view/ExcalidrawView";
import { FileData, MimeType } from "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";
+2 -2
View File
@@ -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";
+8 -8
View File
@@ -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 };
+10 -9
View File
@@ -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));
}
}
+7 -7
View File
@@ -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";
+9 -9
View File
@@ -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;
});
}
+7 -7
View File
@@ -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";
+7 -7
View File
@@ -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";
+2 -2
View File
@@ -1,6 +1,6 @@
import {
SuggestModal,
Scope,
SuggestModal,
Scope,
} from "obsidian";
export class Suggester<T> {
+5 -5
View File
@@ -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 -1
View File
@@ -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;
+33 -18
View File
@@ -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,7 +295,7 @@ export class ContentSearcher {
this.expandParentDetails(nextActiveHighlight);
// Use setTimeout to ensure DOM has time to update after expanding details
setTimeout(() => {
window.setTimeout(() => {
this.scrollResultIntoView(nextActiveHighlight);
}, 100);
@@ -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 -1
View File
@@ -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 -1
View File
@@ -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 -1
View File
@@ -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;
+19 -19
View File
@@ -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 = [
+55 -2
View File
@@ -1,6 +1,51 @@
export type AIProvider = "openai" | "anthropic" | "google" | "xai" | "openai-compatible";
export type AIImageInput = string | { url: string };
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";
@@ -44,7 +89,9 @@ export type GPTCompletionRequest = {
export type AIRequestMessagePart =
| { type: "text"; text: string }
| { type: "image"; image: AIImageInput };
| { type: "image"; image: AIImageInput }
| { type: "file"; file: AIFileInput }
| { type: "audio"; audio: AIFileInput };
export type AIRequestMessage = {
role: "system" | "user" | "assistant";
@@ -53,12 +100,18 @@ export type AIRequestMessage = {
export type AIRequest = {
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
+1 -1
View File
@@ -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 = {
+1 -1
View File
@@ -1,7 +1,7 @@
import { DataURL } from "@zsviczian/excalidraw/types/excalidraw/types";
import { TFile } from "obsidian";
import { FileId } from "src/core";
import { ColorMap, PDFPageViewProps, Size, MimeType } from "./embeddedFileLoaderTypes";
import { ColorMap,PDFPageViewProps,Size,MimeType } from "./embeddedFileLoaderTypes";
export type SVGColorInfo = Map<string, {
mappedTo: string;
+3 -5
View File
@@ -1,9 +1,7 @@
import { RestoredDataState } from "@zsviczian/excalidraw/types/excalidraw/data/restore";
import { ImportedDataState } from "@zsviczian/excalidraw/types/excalidraw/data/types";
import { BoundingBox } from "@zsviczian/excalidraw/types/element/src";
import { ElementsMap, ElementsMapOrArray, ExcalidrawBindableElement, ExcalidrawElement, ExcalidrawFrameElement, ExcalidrawFrameLikeElement, ExcalidrawTextContainer, ExcalidrawTextElement, FontFamilyValues, FontString, NonDeleted, NonDeletedExcalidrawElement, OrderedExcalidrawElement, Theme } from "@zsviczian/excalidraw/types/element/src/types";
import { CombineBrandsIfNeeded, FontMetadata } from "@zsviczian/excalidraw/types/common/src";
import { AppState, BinaryFiles, DataURL, GenerateDiagramToCode, Zoom } from "@zsviczian/excalidraw/types/excalidraw/types";
import { ElementsMap,ElementsMapOrArray,ExcalidrawBindableElement,ExcalidrawElement,ExcalidrawFrameElement,ExcalidrawFrameLikeElement,ExcalidrawTextContainer,ExcalidrawTextElement,FontFamilyValues,FontString,NonDeleted,NonDeletedExcalidrawElement,OrderedExcalidrawElement,Theme } from "@zsviczian/excalidraw/types/element/src/types";
import { CombineBrandsIfNeeded,FontMetadata } from "@zsviczian/excalidraw/types/common/src";
import { AppState,BinaryFiles,DataURL,GenerateDiagramToCode,Zoom } from "@zsviczian/excalidraw/types/excalidraw/types";
import { Mutable } from "@zsviczian/excalidraw/types/common/src/utility-types";
import { GlobalPoint } from "@zsviczian/excalidraw/types/math/src/types";
+15
View File
@@ -2,6 +2,20 @@ import { TFile } from "obsidian";
import { ExcalidrawAutomate } from "../shared/ExcalidrawAutomate";
import { ExcalidrawLib } from "./excalidrawLib";
export type ObsidianCommand = {
id: string;
name: string;
icon?: string;
mobileOnly?: boolean;
repeatable?: boolean;
};
export type ObsidianCommandManager = {
listCommands(): ObsidianCommand[];
executeCommandById(commandId: string): boolean;
commands: Record<string, ObsidianCommand>;
};
export type ConnectionPoint = "top" | "bottom" | "left" | "right" | null;
export type Packages = {
@@ -59,6 +73,7 @@ declare module "obsidian" {
interface App {
internalPlugins: any;
setting: any;
commands: ObsidianCommandManager;
isMobile(): boolean;
getObsidianUrl(file:TFile): string;
metadataTypeManager: {
+1240 -216
View File
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -1,5 +1,5 @@
import ExcalidrawPlugin from "src/core/main";
import { PromisePool, promiseTry } from "./utils";
import { PromisePool,promiseTry } from "./utils";
import { blobToBase64 } from "./fileUtils";
interface ExcalidrawFontFaceDescriptor {
-5
View File
@@ -1,5 +1,4 @@
import { Notice } from "obsidian";
import { debug, DEBUGGING } from "./debugHelper";
/**
* Centralized error handling for the Excalidraw plugin
@@ -58,10 +57,6 @@ export class ErrorHandler {
new Notice(formattedError, timeout || this.errorNoticeTimeout);
}
// Debug output if debugging is enabled
if ((process.env.NODE_ENV === 'development') && DEBUGGING) {
debug(this.handleError, `ErrorHandler.handleError: ${context}`, errorObj);
}
}
/**
+3 -3
View File
@@ -1,9 +1,9 @@
import { ExcalidrawEmbeddableElement, ExcalidrawFrameElement, ExcalidrawImageElement } from "@zsviczian/excalidraw/types/element/src/types";
import { ExcalidrawEmbeddableElement,ExcalidrawFrameElement,ExcalidrawImageElement } from "@zsviczian/excalidraw/types/element/src/types";
import { Mutable } from "@zsviczian/excalidraw/types/common/src/utility-types";
import { getEA } from "src/core";
import { ExcalidrawAutomate } from "src/shared/ExcalidrawAutomate";
import { getCropFileNameAndFolder, getListOfTemplateFiles } from "./fileUtils";
import { Notice, TFile } from "obsidian";
import { getCropFileNameAndFolder,getListOfTemplateFiles } from "./fileUtils";
import { Notice,TFile } from "obsidian";
import { Radians } from "@zsviczian/excalidraw/types/math/src/types";
export const CROPPED_PREFIX = "cropped_";
+1 -1
View File
@@ -15,6 +15,6 @@ export async function getDataURL(
});
}
export function errorlog(data: {}) {
export function errorlog(data: object) {
console.error({ plugin: "Excalidraw", ...data });
}
+3 -3
View File
@@ -1,7 +1,7 @@
import { NonDeletedExcalidrawElement } from "@zsviczian/excalidraw/types/element/src/types";
import { AUDIO_TYPES, DEVICE, REG_LINKINDEX_INVALIDCHARS, VIDEO_TYPES } from "src/constants/constants";
import { ConstructableWorkspaceSplit, getContainerForDocument, getParentOfClass } from "./obsidianUtils";
import { App, TFile, WorkspaceLeaf, WorkspaceSplit } from "obsidian";
import { AUDIO_TYPES,DEVICE,REG_LINKINDEX_INVALIDCHARS,VIDEO_TYPES } from "src/constants/constants";
import { ConstructableWorkspaceSplit,getContainerForDocument,getParentOfClass } from "./obsidianUtils";
import { App,TFile,WorkspaceLeaf,WorkspaceSplit } from "obsidian";
import { getLinkParts } from "./sceneDataUtils";
import ExcalidrawView from "src/view/ExcalidrawView";
+7 -7
View File
@@ -1,5 +1,5 @@
import { ExcalidrawImperativeAPI } from "@zsviczian/excalidraw/types/excalidraw/types";
import CM, { ColorMaster } from "@zsviczian/colormaster";
import CM,{ ColorMaster } from "@zsviczian/colormaster";
import { ExcalidrawAutomate } from "src/shared/ExcalidrawAutomate";
import ExcalidrawView from "src/view/ExcalidrawView";
import { DynamicStyle } from "src/types/types";
@@ -17,7 +17,7 @@ export const setDynamicStyle = (
) => {
if(dynamicStyle === "none") {
//view.excalidrawContainer?.removeAttribute("style");
setTimeout(()=>
window.setTimeout(()=>
view.updateScene({
appState:{dynamicStyle: {}},
captureUpdate: CaptureUpdateAction.NEVER
@@ -26,7 +26,7 @@ export const setDynamicStyle = (
const toolspanel = view.toolsPanelRef?.current?.containerRef?.current;
if(toolspanel) {
let toolsStyle = toolspanel.getAttribute("style");
toolsStyle = toolsStyle.replace(/\-\-color\-primary.*/,"");
toolsStyle = toolsStyle.replace(/--color-primary.*/,"");
toolspanel.setAttribute("style",toolsStyle);
}
return;
@@ -148,12 +148,12 @@ export const setDynamicStyle = (
const toolspanel = view.toolsPanelRef?.current?.containerRef?.current;
if(toolspanel) {
let toolsStyle = toolspanel.getAttribute("style");
toolsStyle = toolsStyle.replace(/\-\-color\-primary.*/,"");
toolsStyle = toolsStyle.replace(/--color-primary.*/,"");
toolspanel.setAttribute("style",toolsStyle+styleString);
}
setTimeout(()=>{
const api = view.excalidrawAPI as ExcalidrawImperativeAPI;
window.setTimeout(()=>{
const api = view.excalidrawAPI;
if(!api) {
view = null;
ea = null;
@@ -178,7 +178,7 @@ export const setDynamicStyle = (
) {
return;
}
(view.excalidrawAPI as ExcalidrawImperativeAPI).mutateElement(e,{customData: f.customData});
(view.excalidrawAPI).mutateElement(e,{customData: f.customData});
});
view.updateScene({
+3 -3
View File
@@ -1,4 +1,4 @@
import type { TFile, App } from "obsidian";
import type { TFile,App } from "obsidian";
import { FRONTMATTER_KEYS } from "src/constants/constants";
import type ExcalidrawPlugin from "src/core/main";
import type { FILENAMEPARTS } from "src/types/utilTypes";
@@ -136,7 +136,7 @@ export function getExportPadding(plugin: ExcalidrawPlugin, file: TFile): number
}
export function getEmbeddedFilenameParts(fname: string): FILENAMEPARTS {
const parts = fname?.match(/([^#\^]*)((#\^)(group=|area=|frame=|clippedframe=|taskbone)?([^\|]*)|(#)(group=|area=|frame=|clippedframe=|taskbone)?([^\^\|]*))(.*)/);
const parts = fname?.match(/([^#\^]*)((#\^)(group=|area=|frame=|clippedframe=|taskbone)?([^|]*)|(#)(group=|area=|frame=|clippedframe=|taskbone)?([^\^|]*))(.*)/);
if (!parts) {
return {
filepath: fname,
@@ -236,7 +236,7 @@ export class PromisePool<T> {
return Promise.resolve(this.pool.start()).then(
() => {
setTimeout(() => {
window.setTimeout(() => {
this.pool?.removeEventListener("fulfilled", listener);
});
return Object.values(this.entries);
Loaded 100 of 127 files, more files were not shown because too many files have changed in this diff. Show more