Compare commits
16 Commits
alpha-v202
...
alpha-v202
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
764bbf0e4c | ||
|
|
ff05ba0430 | ||
|
|
347df47c62 | ||
|
|
7536169508 | ||
|
|
34de384738 | ||
|
|
954ee42f0b | ||
|
|
f67aafe442 | ||
|
|
b2122ac24c | ||
|
|
6f8810146e | ||
|
|
929ba9241e | ||
|
|
c5e84c8218 | ||
|
|
fb55ed2f6d | ||
|
|
91a0247187 | ||
|
|
ce78abfd57 | ||
|
|
6202892512 | ||
|
|
2eb21356ef |
@@ -1,2 +1,2 @@
|
||||
HOTSPOT_THRESHOLD=9.86
|
||||
AVERAGE_THRESHOLD=9.68
|
||||
AVERAGE_THRESHOLD=9.7
|
||||
|
||||
661
LICENSE
Normal file
661
LICENSE
Normal 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/>.
|
||||
10
README.md
10
README.md
@@ -90,4 +90,12 @@ Husky installs the git hooks from `.husky/` during `pnpm install`. The repo enfo
|
||||
|
||||
## License
|
||||
|
||||
Private repository — not licensed for public use.
|
||||
Tolaria is licensed under the GNU Affero General Public License, version 3 or any later version (AGPL-3.0-or-later).
|
||||
|
||||
See [LICENSE](LICENSE) for the full license text.
|
||||
|
||||
## Trademarks
|
||||
|
||||
The Tolaria name and logo are not licensed under the AGPL.
|
||||
|
||||
See [trademarks.md](trademarks.md) for the trademark policy.
|
||||
|
||||
@@ -436,9 +436,11 @@ Defined in `src/components/editorSchema.tsx` and styled in `src/components/Edito
|
||||
|
||||
Defined in `src/components/tolariaEditorFormatting.tsx` and `src/components/tolariaEditorFormattingConfig.ts`:
|
||||
|
||||
- `SingleEditorView` disables BlockNote's default formatting toolbar and `/` menu, then mounts Tolaria-owned controllers so the visible formatting surface matches Tolaria's markdown round-trip guarantees.
|
||||
- `SingleEditorView` disables BlockNote's default formatting toolbar, `/` menu, and side menu, then mounts Tolaria-owned controllers so the visible formatting surface matches Tolaria's markdown round-trip guarantees.
|
||||
- The formatting toolbar only exposes inline controls that persist through `blocksToMarkdownLossy()` in Tolaria's save pipeline: bold, italic, strike, nesting, and link creation. Controls that BlockNote can render temporarily but Tolaria cannot faithfully persist, such as underline, color, alignment, and the block-type dropdown, are hidden instead of appearing to work and later disappearing.
|
||||
- Tolaria's formatting-toolbar controller also keeps file/image actions mounted across the tiny hover gap between an image block and the floating toolbar, and while the toolbar itself is hovered, so image controls remain usable instead of collapsing mid-interaction.
|
||||
- The `/` slash menu remains the supported path for markdown-safe block transformations such as headings, quotes, and list blocks. Tolaria filters out BlockNote's toggle-heading and toggle-list variants because those do not map cleanly to the markdown note model.
|
||||
- The block-handle side menu keeps only actions that survive Tolaria's markdown round-trip. Delete and table-header toggles remain available; BlockNote's `Colors` submenu is removed because block colors are not part of Tolaria's supported markdown surface.
|
||||
|
||||
### Markdown-to-BlockNote Pipeline
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
{
|
||||
"name": "tolaria",
|
||||
"private": true,
|
||||
"license": "AGPL-3.0-or-later",
|
||||
"version": "0.1.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
|
||||
@@ -2,8 +2,8 @@
|
||||
name = "tolaria"
|
||||
version = "0.1.0"
|
||||
description = "Personal knowledge and life management app"
|
||||
authors = ["you"]
|
||||
license = ""
|
||||
authors = ["Luca Rossi"]
|
||||
license = "AGPL-3.0-or-later"
|
||||
repository = ""
|
||||
edition = "2021"
|
||||
rust-version = "1.77.2"
|
||||
|
||||
@@ -208,107 +208,161 @@ const OUTDATED_AGENTS_MARKERS: [&str; 3] = [
|
||||
"Tolaria still understands legacy aliases such as `Is A`.",
|
||||
];
|
||||
|
||||
pub(super) fn agents_content_can_be_refreshed(content: &str) -> bool {
|
||||
let is_outdated_managed_template = OUTDATED_AGENTS_MARKERS
|
||||
.iter()
|
||||
.all(|marker| content.contains(marker));
|
||||
let is_stale_title_stub = content.contains("Do not add `title:` frontmatter.");
|
||||
const STALE_TITLE_FRONTMATTER_MARKER: &str = "Do not add `title:` frontmatter.";
|
||||
const LEGACY_VIEWS_SECTION_MARKER: &str = "## Views";
|
||||
const LEGACY_VIEW_FILE_MARKERS: [&str; 2] = [".view.json", "```json"];
|
||||
|
||||
content.trim().is_empty()
|
||||
|| content == PRE_TYPE_AGENTS_MD
|
||||
|| content == LEGACY_AGENTS_MD
|
||||
|| content == STALE_AGENTS_MD
|
||||
|| is_stale_title_stub
|
||||
|| is_outdated_managed_template
|
||||
struct AgentsContent<'a>(&'a str);
|
||||
|
||||
impl<'a> AgentsContent<'a> {
|
||||
fn new(content: &'a str) -> Self {
|
||||
Self(content)
|
||||
}
|
||||
|
||||
fn contains(&self, marker: &str) -> bool {
|
||||
self.0.contains(marker)
|
||||
}
|
||||
|
||||
fn contains_all(&self, markers: &[&str]) -> bool {
|
||||
markers.iter().all(|marker| self.contains(marker))
|
||||
}
|
||||
|
||||
fn is_known_legacy_template(&self) -> bool {
|
||||
self.0.trim().is_empty()
|
||||
|| self.0 == PRE_TYPE_AGENTS_MD
|
||||
|| self.0 == LEGACY_AGENTS_MD
|
||||
|| self.0 == STALE_AGENTS_MD
|
||||
}
|
||||
|
||||
fn has_stale_title_stub(&self) -> bool {
|
||||
self.contains(STALE_TITLE_FRONTMATTER_MARKER)
|
||||
}
|
||||
|
||||
fn has_legacy_json_view_guidance(&self) -> bool {
|
||||
self.contains(LEGACY_VIEWS_SECTION_MARKER)
|
||||
&& LEGACY_VIEW_FILE_MARKERS
|
||||
.iter()
|
||||
.any(|marker| self.contains(marker))
|
||||
}
|
||||
|
||||
fn can_be_refreshed(&self) -> bool {
|
||||
self.is_known_legacy_template()
|
||||
|| self.has_stale_title_stub()
|
||||
|| self.has_legacy_json_view_guidance()
|
||||
|| self.contains_all(&OUTDATED_AGENTS_MARKERS)
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn agents_content_can_be_refreshed(content: &str) -> bool {
|
||||
AgentsContent::new(content).can_be_refreshed()
|
||||
}
|
||||
|
||||
/// Default AGENTS.md content — vault instructions for AI agents.
|
||||
/// Describes Tolaria vault mechanics only; no user-specific structure.
|
||||
/// The vault scanner will pick this up as a regular entry.
|
||||
pub(super) const AGENTS_MD: &str = r##"# AGENTS.md — Tolaria Vault
|
||||
pub(super) const AGENTS_MD: &str = r##"---
|
||||
type: Note
|
||||
_organized: true
|
||||
---
|
||||
|
||||
This is a [Tolaria](https://github.com/refactoringhq/tolaria) vault: a folder of Markdown files with YAML frontmatter forming a personal knowledge graph.
|
||||
# AGENTS.md — Tolaria Vault
|
||||
|
||||
Keep edits compatible with Tolaria's current conventions. Prefer small, human-readable changes over heavy restructuring.
|
||||
This is a [Tolaria](https://github.com/refactoringhq/tolaria) vault, a folder of Markdown files with YAML frontmatter forming a personal knowledge graph.
|
||||
|
||||
Keep edits compatible with this starter vault's current conventions. Prefer small, human-readable changes over heavy restructuring.
|
||||
|
||||
## Core conventions
|
||||
|
||||
- One Markdown note per file.
|
||||
- The first H1 in the body is the preferred display title.
|
||||
- Legacy `title:` frontmatter is still read as a fallback when a note has no H1. Do not add it to new notes unless you are maintaining an older file.
|
||||
- The first H1 in the body is the preferred display title. Legacy `title:` frontmatter is still read as a fallback when a note has no H1, but do not add it to new notes.
|
||||
- Store note type in the `type:` frontmatter field.
|
||||
- Most notes live at the vault root as flat `.md` files. Type definitions live in `type/`. Saved views live in `views/`.
|
||||
- Any frontmatter field containing `[[wikilinks]]` is treated as a relationship. Common names include `Belongs to:`, `Related to:`, `Workspace:`, and custom relationship names.
|
||||
- In this starter vault, type definitions currently live at the vault root, for example `project.md`, `person.md`, `note.md`, and `config.md`. Keep new type files at the vault root unless the user explicitly asks to reorganize them.
|
||||
- Saved views live in `views/*.yml`.
|
||||
- Files in `attachments/` are assets, not notes. Reference them from notes, but do not treat them as notes or types.
|
||||
- Frontmatter properties that start with `_` are usually Tolaria-managed state. Leave them alone unless the user explicitly asks for them to change.
|
||||
|
||||
## Notes
|
||||
|
||||
```yaml
|
||||
---
|
||||
type: Project
|
||||
type: Note
|
||||
related_to: "[[tolaria]]"
|
||||
status: Active
|
||||
icon: target
|
||||
Workspace: "[[tolaria]]"
|
||||
Belongs to:
|
||||
- "[[25q2]]"
|
||||
Related to:
|
||||
- "[[person-luca-rossi]]"
|
||||
aliases:
|
||||
- Tolaria work
|
||||
url: https://example.com
|
||||
---
|
||||
|
||||
# Ship Tolaria
|
||||
# Example note
|
||||
|
||||
Body content in Markdown.
|
||||
```
|
||||
|
||||
## Types
|
||||
|
||||
Type definitions are regular notes stored in `type/`. Use `type: Type` for new ones:
|
||||
In this starter vault, types are regular notes stored at the vault root and use `type: Type`.
|
||||
|
||||
```yaml
|
||||
---
|
||||
type: Type
|
||||
icon: shapes
|
||||
color: blue
|
||||
sidebar label: Projects
|
||||
template: |
|
||||
## Outcome
|
||||
|
||||
## Next actions
|
||||
_icon: rocket
|
||||
_color: "#3b82f6"
|
||||
_order: 0
|
||||
_list_properties_display:
|
||||
- related_to
|
||||
_sort: "property:onboarding:asc"
|
||||
---
|
||||
|
||||
# Project
|
||||
```
|
||||
|
||||
Useful type metadata includes `icon`, `color`, `order`, `sidebar label`, `template`, `sort`, `view`, and `visible`.
|
||||
Useful type metadata in this vault includes `icon`/`_icon`, `color`/`_color`, `order`/`_order`, `sidebar label`, `_list_properties_display`, `_sort`, `template`, `view`, and `visible`. When editing an existing file, preserve the key style already used there instead of mass-normalizing underscored keys.
|
||||
|
||||
## Relationships
|
||||
|
||||
Any frontmatter property whose value contains `[[wikilinks]]` is treated as a relationship. In this starter vault, common relationship keys include `related_to` and `belongs_to`, but custom relationship names are valid too.
|
||||
|
||||
Preserve older relationship labels such as `Belongs to:` when editing existing notes that already use them.
|
||||
|
||||
Use quoted wikilinks for scalar frontmatter values and YAML lists for multi-value relationships.
|
||||
|
||||
## Wikilinks
|
||||
|
||||
- `[[filename]]` or `[[Note Title]]` — link by filename or title
|
||||
- `[[filename|display text]]` — with custom display text
|
||||
- `[[filename]]` or `[[Note Title]]` for normal links
|
||||
- `[[filename|display text]]` for custom display text
|
||||
- Works in frontmatter values and Markdown body
|
||||
|
||||
## Views
|
||||
|
||||
Saved views live in `views/*.yml` and are written as YAML:
|
||||
Saved views live in `views/*.yml` and are written as YAML. Tolaria scans every `.yml` file in `views/`, and the filename is the stable view id, so use kebab-case filenames such as `active-projects.yml`.
|
||||
|
||||
A view definition looks like this:
|
||||
|
||||
```yaml
|
||||
name: Active Projects
|
||||
icon: kanban
|
||||
color: blue
|
||||
sort: modified:desc
|
||||
icon: null
|
||||
color: null
|
||||
sort: "property:onboarding:asc"
|
||||
filters:
|
||||
all:
|
||||
any:
|
||||
- field: type
|
||||
op: equals
|
||||
value: Project
|
||||
- field: status
|
||||
op: equals
|
||||
value: Active
|
||||
- field: related_to
|
||||
op: contains
|
||||
value: "[[tolaria]]"
|
||||
```
|
||||
|
||||
View rules that matter when creating or editing files:
|
||||
- `name` is required. `icon`, `color`, and `sort` are optional.
|
||||
- `sort` uses `option:direction`. Built-in options are `modified`, `created`, `title`, and `status`. Custom-property sorts use `property:<Property Name>`, for example `property:onboarding:asc`.
|
||||
- `filters` must be a tree whose root is exactly one `all:` group or one `any:` group.
|
||||
- Each filter condition uses `field`, `op`, and usually `value`.
|
||||
- `field` can target built-ins like `type`, `status`, `title`, `favorite`, and `body`, plus actual frontmatter keys used in this vault such as `related_to`, `belongs_to`, or `url`.
|
||||
- Supported operators are `equals`, `not_equals`, `contains`, `not_contains`, `any_of`, `none_of`, `is_empty`, `is_not_empty`, `before`, and `after`.
|
||||
- `any_of` and `none_of` expect `value` to be a YAML list.
|
||||
- `regex: true` is supported with `equals`, `not_equals`, `contains`, and `not_contains` when pattern matching is needed.
|
||||
- Relationship filters can use wikilinks in `value`, for example `"[[tolaria]]"`.
|
||||
- Do not create JSON view files or `.view.json` filenames.
|
||||
|
||||
## Filenames
|
||||
|
||||
Use kebab-case: `my-note-title.md`. One note per file.
|
||||
@@ -316,16 +370,17 @@ Use kebab-case: `my-note-title.md`. One note per file.
|
||||
## What agents should do
|
||||
|
||||
- Create and edit notes using the frontmatter and H1 conventions above.
|
||||
- Create and edit type documents in `type/`.
|
||||
- Create and edit type documents at the vault root.
|
||||
- Add or modify relationships without breaking existing wikilinks.
|
||||
- Create and edit saved views in `views/`.
|
||||
- Update `AGENTS.md` only when the user asks for vault-level guidance changes.
|
||||
|
||||
## What agents should avoid
|
||||
|
||||
- Do not infer note type from folders other than the dedicated `type/` directory for type definitions.
|
||||
- Do not move existing type files out of the vault root unless the user explicitly asks.
|
||||
- Do not treat files in `attachments/` as notes, types, or view definitions.
|
||||
- Do not silently overwrite an existing custom `AGENTS.md`.
|
||||
- Do not overwrite user-authored config or installation-specific app files unless the user explicitly asks.
|
||||
- Do not rewrite installation-specific app configuration unless the user explicitly asks.
|
||||
"##;
|
||||
|
||||
pub(super) const LEGACY_AGENTS_MD: &str = r##"# AGENTS.md — Tolaria Vault
|
||||
@@ -413,18 +468,23 @@ Do not modify app configuration files — those are local to each installation.
|
||||
|
||||
/// Clone the public starter vault into the requested path.
|
||||
pub fn create_getting_started_vault(target_path: &str) -> Result<String, String> {
|
||||
create_getting_started_vault_from_repo(target_path, &getting_started_repo_url())
|
||||
let vault_path = create_getting_started_vault_from_repo(
|
||||
Path::new(target_path),
|
||||
&getting_started_repo_url(),
|
||||
)?;
|
||||
Ok(vault_path.to_string_lossy().to_string())
|
||||
}
|
||||
|
||||
fn create_getting_started_vault_from_repo(
|
||||
target_path: &str,
|
||||
target_path: &Path,
|
||||
repo_url: &str,
|
||||
) -> Result<String, String> {
|
||||
if target_path.trim().is_empty() {
|
||||
) -> Result<PathBuf, String> {
|
||||
let target_path_str = target_path.to_string_lossy();
|
||||
if target_path_str.trim().is_empty() {
|
||||
return Err("Target path is required".to_string());
|
||||
}
|
||||
|
||||
crate::git::clone_repo(repo_url, target_path)?;
|
||||
crate::git::clone_repo(repo_url, &target_path_str)?;
|
||||
let vault_path = canonical_vault_path(target_path)?;
|
||||
refresh_cloned_vault_config_files(&vault_path)?;
|
||||
Ok(vault_path)
|
||||
@@ -436,16 +496,23 @@ fn getting_started_repo_url() -> String {
|
||||
.unwrap_or_else(|_| GETTING_STARTED_REPO_URL.to_string())
|
||||
}
|
||||
|
||||
fn canonical_vault_path(target_path: &str) -> Result<String, String> {
|
||||
let path = Path::new(target_path);
|
||||
let canonical = path
|
||||
.canonicalize()
|
||||
.map_err(|e| format!("Failed to resolve vault path '{}': {}", target_path, e))?;
|
||||
Ok(canonical.to_string_lossy().to_string())
|
||||
fn canonical_vault_path(target_path: &Path) -> Result<PathBuf, String> {
|
||||
target_path.canonicalize().map_err(|e| {
|
||||
format!(
|
||||
"Failed to resolve vault path '{}': {}",
|
||||
target_path.display(),
|
||||
e
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
fn refresh_cloned_vault_config_files(vault_path: &str) -> Result<(), String> {
|
||||
let agents_path = Path::new(vault_path).join("AGENTS.md");
|
||||
fn path_to_utf8<'a>(path: &'a Path, context: &str) -> Result<&'a str, String> {
|
||||
path.to_str()
|
||||
.ok_or_else(|| format!("{context} '{}' is not valid UTF-8", path.display()))
|
||||
}
|
||||
|
||||
fn refresh_cloned_vault_config_files(vault_path: &Path) -> Result<(), String> {
|
||||
let agents_path = vault_path.join("AGENTS.md");
|
||||
let refresh_agents = if !agents_path.exists() {
|
||||
true
|
||||
} else {
|
||||
@@ -459,18 +526,21 @@ fn refresh_cloned_vault_config_files(vault_path: &str) -> Result<(), String> {
|
||||
.map_err(|e| format!("Failed to write {}: {e}", agents_path.display()))?;
|
||||
}
|
||||
|
||||
crate::vault::repair_config_files(vault_path)?;
|
||||
crate::vault::repair_config_files(path_to_utf8(vault_path, "Vault path")?)?;
|
||||
|
||||
if !vault_has_pending_changes(vault_path)? {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
ensure_commit_identity(vault_path)?;
|
||||
crate::git::git_commit(vault_path, "Initialize Tolaria config files")?;
|
||||
crate::git::git_commit(
|
||||
path_to_utf8(vault_path, "Vault path")?,
|
||||
"Initialize Tolaria config files",
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn vault_has_pending_changes(vault_path: &str) -> Result<bool, String> {
|
||||
fn vault_has_pending_changes(vault_path: &Path) -> Result<bool, String> {
|
||||
let output = Command::new("git")
|
||||
.args(["status", "--porcelain"])
|
||||
.current_dir(vault_path)
|
||||
@@ -487,7 +557,7 @@ fn vault_has_pending_changes(vault_path: &str) -> Result<bool, String> {
|
||||
))
|
||||
}
|
||||
|
||||
fn ensure_commit_identity(vault_path: &str) -> Result<(), String> {
|
||||
fn ensure_commit_identity(vault_path: &Path) -> Result<(), String> {
|
||||
for (key, fallback) in [
|
||||
("user.name", "Tolaria"),
|
||||
("user.email", "vault@tolaria.app"),
|
||||
@@ -575,8 +645,7 @@ mod tests {
|
||||
let dest = dir.path().join("Getting Started");
|
||||
init_source_repo(&source, Some(agents_content));
|
||||
|
||||
create_getting_started_vault_from_repo(dest.to_str().unwrap(), source.to_str().unwrap())
|
||||
.unwrap();
|
||||
create_getting_started_vault_from_repo(dest.as_path(), source.to_str().unwrap()).unwrap();
|
||||
|
||||
let content = fs::read_to_string(dest.join("AGENTS.md")).unwrap();
|
||||
assert_eq!(content, AGENTS_MD);
|
||||
@@ -605,13 +674,11 @@ mod tests {
|
||||
let dest = dir.path().join("Getting Started");
|
||||
init_source_repo(&source, None);
|
||||
|
||||
let result = create_getting_started_vault_from_repo(
|
||||
dest.to_str().unwrap(),
|
||||
source.to_str().unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
let result =
|
||||
create_getting_started_vault_from_repo(dest.as_path(), source.to_str().unwrap())
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(result, dest.canonicalize().unwrap().to_string_lossy());
|
||||
assert_eq!(result, dest.canonicalize().unwrap());
|
||||
assert!(dest.join("welcome.md").exists());
|
||||
assert!(dest.join("views").join("active-projects.yml").exists());
|
||||
assert!(dest.join(".git").exists());
|
||||
@@ -631,11 +698,8 @@ mod tests {
|
||||
fs::create_dir_all(&dest).unwrap();
|
||||
fs::write(dest.join("existing.md"), "# Existing\n").unwrap();
|
||||
|
||||
let err = create_getting_started_vault_from_repo(
|
||||
dest.to_str().unwrap(),
|
||||
source.to_str().unwrap(),
|
||||
)
|
||||
.unwrap_err();
|
||||
let err = create_getting_started_vault_from_repo(dest.as_path(), source.to_str().unwrap())
|
||||
.unwrap_err();
|
||||
|
||||
assert!(err.contains("already exists and is not empty"));
|
||||
}
|
||||
@@ -646,11 +710,9 @@ mod tests {
|
||||
let missing_repo = dir.path().join("missing");
|
||||
let dest = dir.path().join("Getting Started");
|
||||
|
||||
let err = create_getting_started_vault_from_repo(
|
||||
dest.to_str().unwrap(),
|
||||
missing_repo.to_str().unwrap(),
|
||||
)
|
||||
.unwrap_err();
|
||||
let err =
|
||||
create_getting_started_vault_from_repo(dest.as_path(), missing_repo.to_str().unwrap())
|
||||
.unwrap_err();
|
||||
|
||||
assert!(err.contains("git clone failed"));
|
||||
assert!(!dest.exists());
|
||||
@@ -663,8 +725,7 @@ mod tests {
|
||||
let dest = dir.path().join("Getting Started");
|
||||
init_source_repo(&source, None);
|
||||
|
||||
create_getting_started_vault_from_repo(dest.to_str().unwrap(), source.to_str().unwrap())
|
||||
.unwrap();
|
||||
create_getting_started_vault_from_repo(dest.as_path(), source.to_str().unwrap()).unwrap();
|
||||
|
||||
let output = StdCommand::new("git")
|
||||
.args(["status", "--porcelain"])
|
||||
@@ -689,16 +750,35 @@ mod tests {
|
||||
assert!(agents_content_can_be_refreshed(PRE_TYPE_AGENTS_MD));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_agents_refresh_detection_accepts_legacy_json_view_guidance() {
|
||||
let stale = r#"# AGENTS.md — Tolaria Vault
|
||||
|
||||
## Views
|
||||
|
||||
Saved filters live in `views/` as `.view.json` files:
|
||||
|
||||
```json
|
||||
{"title":"Active Notes"}
|
||||
```
|
||||
"#;
|
||||
assert!(agents_content_can_be_refreshed(stale));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_agents_template_matches_current_tolaria_vault_conventions() {
|
||||
assert!(AGENTS_MD.starts_with("---\ntype: Note\n_organized: true\n---\n"));
|
||||
assert!(AGENTS_MD.contains("# AGENTS.md — Tolaria Vault"));
|
||||
assert!(AGENTS_MD.contains("type/"));
|
||||
assert!(AGENTS_MD.contains("views/"));
|
||||
assert!(AGENTS_MD.contains("sidebar label"));
|
||||
assert!(AGENTS_MD.contains("Legacy `title:` frontmatter is still read as a fallback"));
|
||||
assert!(AGENTS_MD.contains("Store note type in the `type:` frontmatter field."));
|
||||
assert!(AGENTS_MD.contains("type definitions currently live at the vault root"));
|
||||
assert!(AGENTS_MD.contains("attachments/"));
|
||||
assert!(AGENTS_MD.contains("views/*.yml"));
|
||||
assert!(AGENTS_MD.contains("option:direction"));
|
||||
assert!(AGENTS_MD.contains("property:<Property Name>"));
|
||||
assert!(AGENTS_MD.contains("actual frontmatter keys used in this vault such as `related_to`, `belongs_to`, or `url`."));
|
||||
assert!(AGENTS_MD.contains("Belongs to:"));
|
||||
assert!(AGENTS_MD.contains("Do not create JSON view files or `.view.json` filenames."));
|
||||
assert!(!AGENTS_MD.contains("Laputa"));
|
||||
assert!(!AGENTS_MD.contains("Is A"));
|
||||
assert!(!AGENTS_MD.contains("is_a"));
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { render, screen, fireEvent, waitFor } from '@testing-library/react'
|
||||
import { render, screen, fireEvent, waitFor, within } from '@testing-library/react'
|
||||
import type { ReactNode } from 'react'
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
|
||||
// Provide a localStorage mock that supports all methods (jsdom's may be incomplete)
|
||||
@@ -75,8 +76,14 @@ const mockAllContent: Record<string, string> = {
|
||||
'/vault/topic/dev.md': '---\ntitle: Software Development\nis_a: Topic\n---\n\n# Software Development\n',
|
||||
}
|
||||
|
||||
const mockVaultList = {
|
||||
vaults: [{ label: 'Test Vault', path: '/vault' }],
|
||||
active_vault: '/vault',
|
||||
hidden_defaults: [],
|
||||
}
|
||||
|
||||
const mockCommandResults: Record<string, unknown> = {
|
||||
load_vault_list: { vaults: [], active_vault: null, hidden_defaults: [] },
|
||||
load_vault_list: mockVaultList,
|
||||
list_vault: mockEntries,
|
||||
list_vault_folders: [],
|
||||
list_views: [],
|
||||
@@ -93,9 +100,42 @@ const mockCommandResults: Record<string, unknown> = {
|
||||
get_vault_settings: { theme: null },
|
||||
}
|
||||
|
||||
function resetMockCommandResults() {
|
||||
Object.assign(mockCommandResults, {
|
||||
load_vault_list: mockVaultList,
|
||||
list_vault: mockEntries,
|
||||
list_vault_folders: [],
|
||||
list_views: [],
|
||||
get_all_content: mockAllContent,
|
||||
get_modified_files: [],
|
||||
get_note_content: mockAllContent['/vault/project/test.md'] || '',
|
||||
get_file_history: [],
|
||||
get_settings: {
|
||||
auto_pull_interval_minutes: null,
|
||||
telemetry_consent: true,
|
||||
crash_reporting_enabled: null,
|
||||
analytics_enabled: null,
|
||||
anonymous_id: null,
|
||||
release_channel: null,
|
||||
},
|
||||
save_settings: null,
|
||||
check_vault_exists: true,
|
||||
get_default_vault_path: '/Users/mock/Documents/Getting Started',
|
||||
list_themes: [],
|
||||
get_vault_settings: { theme: null },
|
||||
})
|
||||
}
|
||||
|
||||
function resolveMockCommandResult(cmd: string, args?: unknown) {
|
||||
const result = mockCommandResults[cmd]
|
||||
return typeof result === 'function'
|
||||
? (result as (input?: unknown) => unknown)(args)
|
||||
: result ?? null
|
||||
}
|
||||
|
||||
vi.mock('./mock-tauri', () => ({
|
||||
isTauri: () => false,
|
||||
mockInvoke: vi.fn(async (cmd: string) => mockCommandResults[cmd] ?? null),
|
||||
mockInvoke: vi.fn(async (cmd: string, args?: unknown) => resolveMockCommandResult(cmd, args)),
|
||||
addMockEntry: vi.fn(),
|
||||
updateMockContent: vi.fn(),
|
||||
}))
|
||||
@@ -125,6 +165,12 @@ vi.mock('@blocknote/core/extensions', () => ({
|
||||
|
||||
vi.mock('@blocknote/react', () => ({
|
||||
createReactInlineContentSpec: () => ({ render: () => null }),
|
||||
BlockNoteViewRaw: ({ children }: { children?: ReactNode }) => (
|
||||
<div data-testid="blocknote-view">{children}</div>
|
||||
),
|
||||
ComponentsContext: {
|
||||
Provider: ({ children }: { children?: ReactNode }) => <>{children}</>,
|
||||
},
|
||||
useCreateBlockNote: () => ({
|
||||
tryParseMarkdownToBlocks: async () => [],
|
||||
replaceBlocks: () => {},
|
||||
@@ -132,6 +178,7 @@ vi.mock('@blocknote/react', () => ({
|
||||
insertInlineContent: () => {},
|
||||
onMount: (cb: () => void) => { cb(); return () => {} },
|
||||
}),
|
||||
SideMenuController: () => null,
|
||||
SuggestionMenuController: () => null,
|
||||
}))
|
||||
|
||||
@@ -148,6 +195,7 @@ const CLAUDE_CODE_ONBOARDING_DISMISSED_KEY = 'tolaria:claude-code-onboarding-dis
|
||||
describe('App', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
resetMockCommandResults()
|
||||
localStorage.clear()
|
||||
localStorage.setItem(CLAUDE_CODE_ONBOARDING_DISMISSED_KEY, '1')
|
||||
})
|
||||
@@ -196,6 +244,32 @@ describe('App', () => {
|
||||
})
|
||||
})
|
||||
|
||||
it('shows onboarding after telemetry consent when no active vault is configured', async () => {
|
||||
mockCommandResults.get_settings = {
|
||||
auto_pull_interval_minutes: null,
|
||||
telemetry_consent: null,
|
||||
crash_reporting_enabled: null,
|
||||
analytics_enabled: null,
|
||||
anonymous_id: null,
|
||||
release_channel: null,
|
||||
}
|
||||
mockCommandResults.load_vault_list = { vaults: [], active_vault: null, hidden_defaults: [] }
|
||||
mockCommandResults.check_vault_exists = (args?: { path?: string }) => args?.path === '/Users/mock/Documents/Getting Started'
|
||||
|
||||
render(<App />)
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('Help improve Tolaria')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
fireEvent.click(screen.getByTestId('telemetry-accept'))
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId('welcome-screen')).toBeInTheDocument()
|
||||
})
|
||||
expect(screen.getByTestId('welcome-open-folder')).toHaveTextContent('Open existing vault')
|
||||
})
|
||||
|
||||
it('renders sidebar with correct default selection (All Notes)', async () => {
|
||||
render(<App />)
|
||||
await waitFor(() => {
|
||||
@@ -221,7 +295,7 @@ describe('App', () => {
|
||||
render(<App />)
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.queryByText('Inbox')).not.toBeInTheDocument()
|
||||
expect(within(screen.getByTestId('sidebar-top-nav')).queryByText('Inbox')).not.toBeInTheDocument()
|
||||
expect(screen.getByText('All Notes')).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
|
||||
98
src/App.tsx
98
src/App.tsx
@@ -37,7 +37,7 @@ import { useEntryActions } from './hooks/useEntryActions'
|
||||
import { useAppCommands } from './hooks/useAppCommands'
|
||||
import { generateCommitMessage } from './utils/commitMessage'
|
||||
import { useDialogs } from './hooks/useDialogs'
|
||||
import { GETTING_STARTED_LABEL, useVaultSwitcher } from './hooks/useVaultSwitcher'
|
||||
import { useVaultSwitcher } from './hooks/useVaultSwitcher'
|
||||
import { useGitHistory } from './hooks/useGitHistory'
|
||||
import { useUpdater, restartApp } from './hooks/useUpdater'
|
||||
import { useAutoSync } from './hooks/useAutoSync'
|
||||
@@ -61,6 +61,7 @@ import { useLayoutPanels } from './hooks/useLayoutPanels'
|
||||
import { useConflictFlow } from './hooks/useConflictFlow'
|
||||
import { useAppSave } from './hooks/useAppSave'
|
||||
import { useVaultBridge } from './hooks/useVaultBridge'
|
||||
import { getAppStorageItem } from './constants/appStorage'
|
||||
import type { CommitDiffRequest } from './hooks/useDiffMode'
|
||||
import { ConflictResolverModal } from './components/ConflictResolverModal'
|
||||
import { ConfirmDeleteDialog } from './components/ConfirmDeleteDialog'
|
||||
@@ -206,22 +207,40 @@ function App() {
|
||||
onSwitch: () => { handleSetSelection(DEFAULT_SELECTION); notes.closeAllTabs() },
|
||||
onToast: (msg) => setToastMessage(msg),
|
||||
})
|
||||
const { handleVaultCloned } = vaultSwitcher
|
||||
const { allVaults, handleVaultCloned, switchVault } = vaultSwitcher
|
||||
|
||||
const handleGettingStartedVaultReady = useCallback((vaultPath: string, label: string) => {
|
||||
const rememberOnboardingVaultChoice = useCallback((vaultPath: string) => {
|
||||
if (!vaultPath) return
|
||||
|
||||
if (allVaults.some((vault) => vault.path === vaultPath)) {
|
||||
switchVault(vaultPath)
|
||||
return
|
||||
}
|
||||
|
||||
const label = vaultPath.split('/').filter(Boolean).pop() || 'Local Vault'
|
||||
handleVaultCloned(vaultPath, label)
|
||||
}, [allVaults, handleVaultCloned, switchVault])
|
||||
|
||||
const handleGettingStartedVaultReady = useCallback((vaultPath: string) => {
|
||||
rememberOnboardingVaultChoice(vaultPath)
|
||||
setToastMessage(`Getting Started vault cloned and opened at ${vaultPath}`)
|
||||
}, [handleVaultCloned])
|
||||
}, [rememberOnboardingVaultChoice])
|
||||
const cloneGettingStartedVault = useGettingStartedClone({
|
||||
onError: (message) => setToastMessage(message),
|
||||
onSuccess: handleGettingStartedVaultReady,
|
||||
})
|
||||
const onboarding = useOnboarding(vaultSwitcher.vaultPath, (vaultPath) => {
|
||||
handleGettingStartedVaultReady(vaultPath, GETTING_STARTED_LABEL)
|
||||
handleGettingStartedVaultReady(vaultPath)
|
||||
})
|
||||
const aiAgentsStatus = useAiAgentsStatus()
|
||||
const aiAgentsOnboarding = useAiAgentsOnboarding(onboarding.state.status === 'ready' && !noteWindowParams)
|
||||
|
||||
useEffect(() => {
|
||||
if (onboarding.state.status !== 'ready') return
|
||||
if (!onboarding.state.vaultPath || onboarding.state.vaultPath === vaultSwitcher.vaultPath) return
|
||||
rememberOnboardingVaultChoice(onboarding.state.vaultPath)
|
||||
}, [onboarding.state, rememberOnboardingVaultChoice, vaultSwitcher.vaultPath])
|
||||
|
||||
// The active vault path can temporarily come from onboarding before the
|
||||
// persisted vault switcher catches up to the newly cloned starter vault.
|
||||
const resolvedPath = noteWindowParams?.vaultPath ?? (onboarding.state.status === 'ready' ? onboarding.state.vaultPath : vaultSwitcher.vaultPath)
|
||||
@@ -899,6 +918,17 @@ function App() {
|
||||
) ?? null
|
||||
}, [notes.activeTabPath, vault.modifiedFiles])
|
||||
|
||||
const activeCommandEntry = useMemo(() => {
|
||||
if (!notes.activeTabPath) return null
|
||||
return notes.tabs.find((tab) => tab.entry.path === notes.activeTabPath)?.entry
|
||||
?? vault.entries.find((entry) => entry.path === notes.activeTabPath)
|
||||
?? null
|
||||
}, [notes.activeTabPath, notes.tabs, vault.entries])
|
||||
|
||||
const canToggleRichEditor = !!activeCommandEntry
|
||||
&& activeCommandEntry.filename.toLowerCase().endsWith('.md')
|
||||
&& !activeDeletedFile
|
||||
|
||||
const commands = useAppCommands({
|
||||
activeTabPath: notes.activeTabPath, activeTabPathRef: notes.activeTabPathRef,
|
||||
entries: vault.entries,
|
||||
@@ -922,7 +952,7 @@ function App() {
|
||||
onSetViewMode: handleSetViewMode,
|
||||
onToggleInspector: handleToggleInspector,
|
||||
onToggleDiff: () => diffToggleRef.current(),
|
||||
onToggleRawEditor: activeDeletedFile ? undefined : () => rawToggleRef.current(),
|
||||
onToggleRawEditor: canToggleRichEditor ? () => rawToggleRef.current() : undefined,
|
||||
onZoomIn: zoom.zoomIn, onZoomOut: zoom.zoomOut, onZoomReset: zoom.zoomReset,
|
||||
zoomLevel: zoom.zoomLevel,
|
||||
onSelect: handleSetSelection,
|
||||
@@ -987,16 +1017,49 @@ function App() {
|
||||
return { type: null, query: '' }
|
||||
}, [effectiveSelection])
|
||||
|
||||
// Show welcome/onboarding screen when vault doesn't exist (skip for note windows — vault path is known)
|
||||
if (!noteWindowParams && (onboarding.state.status === 'welcome' || onboarding.state.status === 'vault-missing')) {
|
||||
return <WelcomeView onboarding={onboarding} isOffline={networkStatus.isOffline} />
|
||||
}
|
||||
const shouldResumeFreshStartOnboarding = useMemo(() => {
|
||||
if (onboarding.state.status !== 'ready' || !vaultSwitcher.loaded) return false
|
||||
|
||||
try {
|
||||
if (getAppStorageItem('welcomeDismissed') === '1') return false
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
|
||||
return vaultSwitcher.allVaults.length === 1
|
||||
&& vaultSwitcher.allVaults[0]?.path === vaultSwitcher.vaultPath
|
||||
&& onboarding.state.vaultPath === vaultSwitcher.vaultPath
|
||||
}, [onboarding.state, vaultSwitcher.allVaults, vaultSwitcher.loaded, vaultSwitcher.vaultPath])
|
||||
|
||||
// Show loading spinner while checking vault (skip for note windows)
|
||||
if (!noteWindowParams && onboarding.state.status === 'loading') {
|
||||
return <LoadingView />
|
||||
}
|
||||
|
||||
// Show telemetry consent dialog on first launch (skip for note windows).
|
||||
// After the user answers, the next render can continue into onboarding.
|
||||
if (!noteWindowParams && settingsLoaded && settings.telemetry_consent === null) {
|
||||
return (
|
||||
<TelemetryConsentDialog
|
||||
onAccept={() => {
|
||||
const id = crypto.randomUUID()
|
||||
saveSettings({ ...settings, telemetry_consent: true, crash_reporting_enabled: true, analytics_enabled: true, anonymous_id: id })
|
||||
}}
|
||||
onDecline={() => {
|
||||
saveSettings({ ...settings, telemetry_consent: false, crash_reporting_enabled: false, analytics_enabled: false, anonymous_id: null })
|
||||
}}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
// Show welcome/onboarding screen when vault doesn't exist (skip for note windows — vault path is known)
|
||||
if (!noteWindowParams && (onboarding.state.status === 'welcome' || onboarding.state.status === 'vault-missing' || shouldResumeFreshStartOnboarding)) {
|
||||
const welcomeOnboarding = shouldResumeFreshStartOnboarding
|
||||
? { ...onboarding, state: { status: 'welcome' as const, defaultPath: vaultSwitcher.vaultPath } }
|
||||
: onboarding
|
||||
return <WelcomeView onboarding={welcomeOnboarding} isOffline={networkStatus.isOffline} />
|
||||
}
|
||||
|
||||
if (!noteWindowParams && onboarding.state.status === 'ready' && aiAgentsOnboarding.showPrompt) {
|
||||
return (
|
||||
<>
|
||||
@@ -1026,21 +1089,6 @@ function App() {
|
||||
return <LoadingView />
|
||||
}
|
||||
|
||||
// Show telemetry consent dialog on first launch (skip for note windows)
|
||||
if (!noteWindowParams && settingsLoaded && settings.telemetry_consent === null) {
|
||||
return (
|
||||
<TelemetryConsentDialog
|
||||
onAccept={() => {
|
||||
const id = crypto.randomUUID()
|
||||
saveSettings({ ...settings, telemetry_consent: true, crash_reporting_enabled: true, analytics_enabled: true, anonymous_id: id })
|
||||
}}
|
||||
onDecline={() => {
|
||||
saveSettings({ ...settings, telemetry_consent: false, crash_reporting_enabled: false, analytics_enabled: false, anonymous_id: null })
|
||||
}}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="app-shell">
|
||||
<div className="app">
|
||||
|
||||
@@ -6,7 +6,6 @@ import { Input } from '@/components/ui/input'
|
||||
import { ActionTooltip, type ActionTooltipCopy } from '@/components/ui/action-tooltip'
|
||||
import { TooltipProvider } from '@/components/ui/tooltip'
|
||||
import {
|
||||
MagnifyingGlass,
|
||||
GitBranch,
|
||||
Code,
|
||||
CursorText,
|
||||
@@ -103,6 +102,7 @@ function IconActionButton({
|
||||
style,
|
||||
children,
|
||||
testId,
|
||||
tooltipAlign,
|
||||
}: {
|
||||
copy: ActionTooltipCopy
|
||||
onClick?: () => void
|
||||
@@ -110,9 +110,10 @@ function IconActionButton({
|
||||
style?: CSSProperties
|
||||
children: ReactNode
|
||||
testId?: string
|
||||
tooltipAlign?: 'start' | 'center' | 'end'
|
||||
}) {
|
||||
return (
|
||||
<ActionTooltip copy={copy} side="bottom">
|
||||
<ActionTooltip copy={copy} side="bottom" align={tooltipAlign}>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
@@ -131,7 +132,10 @@ function IconActionButton({
|
||||
}
|
||||
|
||||
function RawToggleButton({ rawMode, onToggleRaw }: { rawMode?: boolean; onToggleRaw?: () => void }) {
|
||||
const copy: ActionTooltipCopy = { label: rawMode ? 'Return to the editor' : 'Open the raw editor' }
|
||||
const copy: ActionTooltipCopy = {
|
||||
label: rawMode ? 'Return to the editor' : 'Open the raw editor',
|
||||
shortcut: '⌘\\',
|
||||
}
|
||||
return (
|
||||
<IconActionButton
|
||||
copy={copy}
|
||||
@@ -182,14 +186,6 @@ function OrganizedAction({
|
||||
)
|
||||
}
|
||||
|
||||
function SearchAction() {
|
||||
return (
|
||||
<IconActionButton copy={{ label: 'Search within this note' }} className="hover:text-foreground">
|
||||
<MagnifyingGlass size={16} className={BREADCRUMB_ICON_CLASS} />
|
||||
</IconActionButton>
|
||||
)
|
||||
}
|
||||
|
||||
function DiffAction({
|
||||
showDiffToggle,
|
||||
diffMode,
|
||||
@@ -276,7 +272,7 @@ function InspectorAction({
|
||||
}: Pick<BreadcrumbBarProps, 'inspectorCollapsed' | 'onToggleInspector'>) {
|
||||
if (!inspectorCollapsed) return null
|
||||
return (
|
||||
<IconActionButton copy={{ label: 'Open the properties panel', shortcut: '⌘⇧I' }} onClick={onToggleInspector} className="hover:text-foreground">
|
||||
<IconActionButton copy={{ label: 'Open the properties panel', shortcut: '⌘⇧I' }} onClick={onToggleInspector} className="hover:text-foreground" tooltipAlign="end">
|
||||
<SlidersHorizontal size={16} className={BREADCRUMB_ICON_CLASS} />
|
||||
</IconActionButton>
|
||||
)
|
||||
@@ -478,7 +474,6 @@ function BreadcrumbActions({
|
||||
<div className="breadcrumb-bar__actions ml-auto flex items-center" style={{ gap: 12 }}>
|
||||
<FavoriteAction favorite={entry.favorite} onToggleFavorite={onToggleFavorite} />
|
||||
<OrganizedAction organized={entry.organized} onToggleOrganized={onToggleOrganized} />
|
||||
<SearchAction />
|
||||
<DiffAction
|
||||
showDiffToggle={showDiffToggle}
|
||||
diffMode={diffMode}
|
||||
|
||||
@@ -67,7 +67,7 @@ describe('DynamicPropertiesPanel system metadata', () => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('hides underscored and legacy system metadata while keeping user properties visible', () => {
|
||||
it('keeps the icon visible while hiding the other system metadata', () => {
|
||||
render(
|
||||
<DynamicPropertiesPanel
|
||||
entry={makeEntry()}
|
||||
@@ -86,7 +86,9 @@ describe('DynamicPropertiesPanel system metadata', () => {
|
||||
|
||||
expect(screen.getByText('Owner')).toBeInTheDocument()
|
||||
expect(screen.getByText('Luca')).toBeInTheDocument()
|
||||
expect(screen.queryByText('Icon')).not.toBeInTheDocument()
|
||||
expect(screen.getByText('Icon')).toBeInTheDocument()
|
||||
expect(screen.getByTestId('icon-editable-display')).toHaveTextContent('rocket')
|
||||
expect(screen.queryByDisplayValue('legacy')).not.toBeInTheDocument()
|
||||
expect(screen.queryByText('Order')).not.toBeInTheDocument()
|
||||
expect(screen.queryByText('Sort')).not.toBeInTheDocument()
|
||||
expect(screen.queryByText('Sidebar label')).not.toBeInTheDocument()
|
||||
@@ -130,4 +132,18 @@ describe('DynamicPropertiesPanel system metadata', () => {
|
||||
|
||||
expect(onAddProperty).toHaveBeenCalledWith('_icon', 'rocket')
|
||||
})
|
||||
|
||||
it('renders an existing underscored icon property with the icon picker UI', () => {
|
||||
render(
|
||||
<DynamicPropertiesPanel
|
||||
entry={makeEntry()}
|
||||
content=""
|
||||
frontmatter={{ _icon: 'megaphone' }}
|
||||
onAddProperty={onAddProperty}
|
||||
/>,
|
||||
)
|
||||
|
||||
expect(screen.getByText('Icon')).toBeInTheDocument()
|
||||
expect(screen.getByTestId('icon-editable-display')).toHaveTextContent('megaphone')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -342,7 +342,7 @@ describe('DynamicPropertiesPanel', () => {
|
||||
|
||||
fireEvent.focus(warningButton)
|
||||
await waitFor(() => {
|
||||
expect(screen.getByRole('tooltip')).toHaveTextContent('There is no type file for this type')
|
||||
expect(screen.getByRole('tooltip')).toHaveTextContent('Missing type')
|
||||
})
|
||||
|
||||
fireEvent.click(warningButton)
|
||||
@@ -697,21 +697,20 @@ describe('DynamicPropertiesPanel', () => {
|
||||
})
|
||||
|
||||
describe('system property filtering', () => {
|
||||
it('hides archived, archived_at, and legacy icon metadata from the properties panel', () => {
|
||||
it('hides archived metadata but keeps the note icon visible in the properties panel', () => {
|
||||
renderEditablePanel({ archived: false, archived_at: '', icon: '📝', cadence: 'Weekly' })
|
||||
expect(screen.queryByText('Archived')).not.toBeInTheDocument()
|
||||
expect(screen.queryByText('Archived at')).not.toBeInTheDocument()
|
||||
expect(screen.queryByText('Icon')).not.toBeInTheDocument()
|
||||
expect(screen.queryByText('📝')).not.toBeInTheDocument()
|
||||
// Custom property still visible
|
||||
expect(screen.getByText('Icon')).toBeInTheDocument()
|
||||
expect(screen.getByText('📝')).toBeInTheDocument()
|
||||
expect(screen.getByText('Cadence')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('hides legacy icon metadata even when cased differently', () => {
|
||||
it('keeps the note icon visible even when cased differently', () => {
|
||||
renderEditablePanel({ Archived: false, Icon: '🎯', cadence: 'Daily' })
|
||||
expect(screen.queryByText('Archived')).not.toBeInTheDocument()
|
||||
expect(screen.queryByText('Icon')).not.toBeInTheDocument()
|
||||
expect(screen.queryByText('🎯')).not.toBeInTheDocument()
|
||||
expect(screen.getByText('Icon')).toBeInTheDocument()
|
||||
expect(screen.getByText('🎯')).toBeInTheDocument()
|
||||
expect(screen.getByText('Cadence')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
|
||||
@@ -70,6 +70,7 @@ vi.mock('@blocknote/react', () => ({
|
||||
</div>
|
||||
),
|
||||
FormattingToolbarController: () => null,
|
||||
SideMenuController: () => null,
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mock
|
||||
SuggestionMenuController: (props: any) => {
|
||||
capturedGetItemsByTrigger[props.triggerCharacter] = props.getItems
|
||||
@@ -90,7 +91,11 @@ vi.mock('./tolariaEditorFormatting', () => ({
|
||||
}))
|
||||
|
||||
import { Editor } from './Editor'
|
||||
import { applyPendingRawExitContent } from './editorRawModeSync'
|
||||
import {
|
||||
applyPendingRawExitContent,
|
||||
rememberPendingRawExitContent,
|
||||
syncActiveTabIntoRawBuffer,
|
||||
} from './editorRawModeSync'
|
||||
import type { VaultEntry } from '../types'
|
||||
import { bindVaultConfigStore, resetVaultConfigStore } from '../utils/vaultConfigStore'
|
||||
import { TooltipProvider } from '@/components/ui/tooltip'
|
||||
@@ -208,7 +213,8 @@ describe('Editor', () => {
|
||||
activeTabPath: mockEntry.path,
|
||||
})
|
||||
|
||||
expect(screen.getByRole('button', { name: 'Search within this note' })).toBeInTheDocument()
|
||||
expect(screen.getByRole('button', { name: 'Open the raw editor' })).toBeInTheDocument()
|
||||
expect(screen.getByRole('button', { name: 'Delete this note' })).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('hides the legacy title field for untitled draft notes', () => {
|
||||
@@ -415,6 +421,73 @@ describe('applyPendingRawExitContent', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('raw-mode sync content guards', () => {
|
||||
it('does not emit a content change when entering raw mode normalizes markdown', () => {
|
||||
const onContentChange = vi.fn()
|
||||
const rawLatestContentRef = { current: null as string | null }
|
||||
|
||||
const result = syncActiveTabIntoRawBuffer({
|
||||
editor: mockEditor as never,
|
||||
activeTabPath: mockEntry.path,
|
||||
activeTabContent: mockContent,
|
||||
rawLatestContentRef,
|
||||
})
|
||||
|
||||
expect(result).toBe('---\ntitle: Test Project\nis_a: Project\nStatus: Active\n---\n# Test Project\n\nThis is a test note with some words to count.\n')
|
||||
expect(rawLatestContentRef.current).toBe(result)
|
||||
expect(onContentChange).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('captures the latest serialized markdown when entering raw mode', () => {
|
||||
const rawLatestContentRef = { current: null as string | null }
|
||||
|
||||
mockEditor.blocksToMarkdownLossy.mockReturnValueOnce('# Test Project\n\nUpdated body\n')
|
||||
|
||||
const result = syncActiveTabIntoRawBuffer({
|
||||
editor: mockEditor as never,
|
||||
activeTabPath: mockEntry.path,
|
||||
activeTabContent: mockContent,
|
||||
rawLatestContentRef,
|
||||
})
|
||||
|
||||
expect(result).toBe('---\ntitle: Test Project\nis_a: Project\nStatus: Active\n---\n# Test Project\n\nUpdated body\n')
|
||||
expect(rawLatestContentRef.current).toBe(result)
|
||||
})
|
||||
|
||||
it('does not emit a content change when leaving raw mode without user edits', () => {
|
||||
const onContentChange = vi.fn()
|
||||
const normalizedContent = '---\ntitle: Test Project\nis_a: Project\nStatus: Active\n---\n# Test Project\n\nThis is a test note with some words to count.\n'
|
||||
|
||||
const result = rememberPendingRawExitContent({
|
||||
activeTabPath: mockEntry.path,
|
||||
activeTabContent: mockContent,
|
||||
rawInitialContent: normalizedContent,
|
||||
rawLatestContentRef: { current: normalizedContent },
|
||||
onContentChange,
|
||||
})
|
||||
|
||||
expect(result).toBeNull()
|
||||
expect(onContentChange).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('emits a content change when leaving raw mode with edited markdown', () => {
|
||||
const onContentChange = vi.fn()
|
||||
const normalizedContent = '---\ntitle: Test Project\nis_a: Project\nStatus: Active\n---\n# Test Project\n\nThis is a test note with some words to count.\n'
|
||||
const editedContent = `${normalizedContent}\nUpdated in raw mode\n`
|
||||
|
||||
const result = rememberPendingRawExitContent({
|
||||
activeTabPath: mockEntry.path,
|
||||
activeTabContent: mockContent,
|
||||
rawInitialContent: normalizedContent,
|
||||
rawLatestContentRef: { current: editedContent },
|
||||
onContentChange,
|
||||
})
|
||||
|
||||
expect(result).toEqual({ path: mockEntry.path, content: editedContent })
|
||||
expect(onContentChange).toHaveBeenCalledWith(mockEntry.path, editedContent)
|
||||
})
|
||||
})
|
||||
|
||||
describe('click empty editor space', () => {
|
||||
it('focuses editor at end of last block when clicking empty space below content', () => {
|
||||
mockEditor.focus.mockClear()
|
||||
|
||||
@@ -20,6 +20,7 @@ import {
|
||||
resolveRawModeContent,
|
||||
} from './editorRawModeSync'
|
||||
import { useRawModeWithFlush } from './useRawModeWithFlush'
|
||||
import { useFilenameAutolinkGuard } from './useFilenameAutolinkGuard'
|
||||
import './Editor.css'
|
||||
import './EditorTheme.css'
|
||||
|
||||
@@ -167,6 +168,7 @@ function useEditorSetup({
|
||||
schema,
|
||||
uploadFile: (file: File) => uploadImageFile(file, vaultPathRef.current),
|
||||
})
|
||||
useFilenameAutolinkGuard(editor)
|
||||
const activeTab = tabs.find((t) => t.entry.path === activeTabPath) ?? null
|
||||
const {
|
||||
rawMode,
|
||||
|
||||
@@ -22,6 +22,7 @@ import { getTagStyle } from '../utils/tagStyles'
|
||||
import { ColorEditableValue } from './ColorInput'
|
||||
import { IconEditableValue } from './IconEditableValue'
|
||||
import { PROPERTY_CHIP_STYLE } from './propertyChipStyles'
|
||||
import { canonicalSystemMetadataKey } from '../utils/systemMetadata'
|
||||
|
||||
function parseDateValue(value: string): Date | undefined {
|
||||
const iso = toISODate(value)
|
||||
@@ -307,7 +308,7 @@ function toBooleanValue(value: FrontmatterValue): boolean {
|
||||
}
|
||||
|
||||
function autoDetectFromValue(propKey: string, value: FrontmatterValue): PropertyDisplayMode {
|
||||
if (propKey.toLowerCase() === 'icon') return 'text'
|
||||
if (canonicalSystemMetadataKey(propKey) === '_icon') return 'text'
|
||||
if (typeof value === 'boolean') return 'boolean'
|
||||
if (typeof value === 'string' && isUrlValue(value)) return 'url'
|
||||
if (typeof value === 'string' && isValidCssColor(value) && value.startsWith('#')) return 'color'
|
||||
@@ -405,7 +406,7 @@ function ScalarValueCell(props: SmartCellProps) {
|
||||
onSave,
|
||||
})
|
||||
|
||||
if (propKey.toLowerCase() === 'icon') {
|
||||
if (canonicalSystemMetadataKey(propKey) === '_icon') {
|
||||
return <IconEditableValue {...editProps} />
|
||||
}
|
||||
|
||||
|
||||
@@ -48,7 +48,7 @@ describe('SettingsPanel', () => {
|
||||
<SettingsPanel open={true} settings={emptySettings} onSave={onSave} onClose={onClose} />
|
||||
)
|
||||
expect(screen.getByText('Settings')).toBeInTheDocument()
|
||||
expect(screen.getByText('Sync')).toBeInTheDocument()
|
||||
expect(screen.getByText('Sync & Updates')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('calls onSave with stable defaults on save', () => {
|
||||
@@ -127,7 +127,7 @@ describe('SettingsPanel', () => {
|
||||
<SettingsPanel open={true} settings={emptySettings} onSave={onSave} onClose={onClose} />
|
||||
)
|
||||
|
||||
expect(screen.getByRole('switch', { name: 'AutoGit' })).toHaveAttribute('aria-checked', 'false')
|
||||
expect(screen.getByRole('switch', { name: 'Enable AutoGit' })).toHaveAttribute('aria-checked', 'false')
|
||||
expect(screen.getByTestId('settings-autogit-idle-threshold')).toHaveValue(90)
|
||||
expect(screen.getByTestId('settings-autogit-inactive-threshold')).toHaveValue(30)
|
||||
})
|
||||
@@ -137,7 +137,7 @@ describe('SettingsPanel', () => {
|
||||
<SettingsPanel open={true} settings={emptySettings} onSave={onSave} onClose={onClose} />
|
||||
)
|
||||
|
||||
fireEvent.click(screen.getByRole('switch', { name: 'AutoGit' }))
|
||||
fireEvent.click(screen.getByRole('switch', { name: 'Enable AutoGit' }))
|
||||
fireEvent.change(screen.getByTestId('settings-autogit-idle-threshold'), { target: { value: '120' } })
|
||||
fireEvent.change(screen.getByTestId('settings-autogit-inactive-threshold'), { target: { value: '45' } })
|
||||
fireEvent.click(screen.getByTestId('settings-save'))
|
||||
@@ -160,7 +160,7 @@ describe('SettingsPanel', () => {
|
||||
/>
|
||||
)
|
||||
|
||||
expect(screen.getByRole('switch', { name: 'AutoGit' })).toBeDisabled()
|
||||
expect(screen.getByRole('switch', { name: 'Enable AutoGit' })).toBeDisabled()
|
||||
expect(screen.getByTestId('settings-autogit-idle-threshold')).toBeDisabled()
|
||||
expect(screen.getByTestId('settings-autogit-inactive-threshold')).toBeDisabled()
|
||||
})
|
||||
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
useEffect,
|
||||
type KeyboardEvent as ReactKeyboardEvent,
|
||||
type MouseEvent as ReactMouseEvent,
|
||||
type ReactNode,
|
||||
} from 'react'
|
||||
import { X } from '@phosphor-icons/react'
|
||||
import type { Settings } from '../types'
|
||||
@@ -331,74 +332,73 @@ function SettingsBody({
|
||||
setAnalytics,
|
||||
}: SettingsBodyProps) {
|
||||
return (
|
||||
<div style={{ padding: 24, display: 'flex', flexDirection: 'column', gap: 20, overflow: 'auto' }}>
|
||||
<SyncSettingsSection
|
||||
pullInterval={pullInterval}
|
||||
setPullInterval={setPullInterval}
|
||||
/>
|
||||
<div style={{ padding: 24, display: 'flex', flexDirection: 'column', gap: 0, overflow: 'auto' }}>
|
||||
<SettingsSection showDivider={false}>
|
||||
<SyncAndUpdatesSection
|
||||
pullInterval={pullInterval}
|
||||
setPullInterval={setPullInterval}
|
||||
releaseChannel={releaseChannel}
|
||||
setReleaseChannel={setReleaseChannel}
|
||||
/>
|
||||
</SettingsSection>
|
||||
|
||||
<Divider />
|
||||
<SettingsSection>
|
||||
<AutoGitSettingsSection
|
||||
isGitVault={isGitVault}
|
||||
autoGitEnabled={autoGitEnabled}
|
||||
setAutoGitEnabled={setAutoGitEnabled}
|
||||
autoGitIdleThresholdSeconds={autoGitIdleThresholdSeconds}
|
||||
setAutoGitIdleThresholdSeconds={setAutoGitIdleThresholdSeconds}
|
||||
autoGitInactiveThresholdSeconds={autoGitInactiveThresholdSeconds}
|
||||
setAutoGitInactiveThresholdSeconds={setAutoGitInactiveThresholdSeconds}
|
||||
/>
|
||||
</SettingsSection>
|
||||
|
||||
<AutoGitSettingsSection
|
||||
isGitVault={isGitVault}
|
||||
autoGitEnabled={autoGitEnabled}
|
||||
setAutoGitEnabled={setAutoGitEnabled}
|
||||
autoGitIdleThresholdSeconds={autoGitIdleThresholdSeconds}
|
||||
setAutoGitIdleThresholdSeconds={setAutoGitIdleThresholdSeconds}
|
||||
autoGitInactiveThresholdSeconds={autoGitInactiveThresholdSeconds}
|
||||
setAutoGitInactiveThresholdSeconds={setAutoGitInactiveThresholdSeconds}
|
||||
/>
|
||||
<SettingsSection>
|
||||
<TitleSettingsSection
|
||||
initialH1AutoRename={initialH1AutoRename}
|
||||
setInitialH1AutoRename={setInitialH1AutoRename}
|
||||
/>
|
||||
</SettingsSection>
|
||||
|
||||
<Divider />
|
||||
<SettingsSection>
|
||||
<AiAgentSettingsSection
|
||||
aiAgentsStatus={aiAgentsStatus}
|
||||
defaultAiAgent={defaultAiAgent}
|
||||
setDefaultAiAgent={setDefaultAiAgent}
|
||||
/>
|
||||
</SettingsSection>
|
||||
|
||||
<TitleSettingsSection
|
||||
initialH1AutoRename={initialH1AutoRename}
|
||||
setInitialH1AutoRename={setInitialH1AutoRename}
|
||||
/>
|
||||
<SettingsSection>
|
||||
<OrganizationWorkflowSection
|
||||
checked={explicitOrganization}
|
||||
onChange={setExplicitOrganization}
|
||||
/>
|
||||
</SettingsSection>
|
||||
|
||||
<Divider />
|
||||
|
||||
<AiAgentSettingsSection
|
||||
aiAgentsStatus={aiAgentsStatus}
|
||||
defaultAiAgent={defaultAiAgent}
|
||||
setDefaultAiAgent={setDefaultAiAgent}
|
||||
/>
|
||||
|
||||
<Divider />
|
||||
|
||||
<ReleaseChannelSection
|
||||
releaseChannel={releaseChannel}
|
||||
setReleaseChannel={setReleaseChannel}
|
||||
/>
|
||||
|
||||
<Divider />
|
||||
|
||||
<OrganizationWorkflowSection
|
||||
checked={explicitOrganization}
|
||||
onChange={setExplicitOrganization}
|
||||
/>
|
||||
|
||||
<Divider />
|
||||
|
||||
<PrivacySettingsSection
|
||||
crashReporting={crashReporting}
|
||||
setCrashReporting={setCrashReporting}
|
||||
analytics={analytics}
|
||||
setAnalytics={setAnalytics}
|
||||
/>
|
||||
<SettingsSection>
|
||||
<PrivacySettingsSection
|
||||
crashReporting={crashReporting}
|
||||
setCrashReporting={setCrashReporting}
|
||||
analytics={analytics}
|
||||
setAnalytics={setAnalytics}
|
||||
/>
|
||||
</SettingsSection>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function SyncSettingsSection({
|
||||
function SyncAndUpdatesSection({
|
||||
pullInterval,
|
||||
setPullInterval,
|
||||
}: Pick<SettingsBodyProps, 'pullInterval' | 'setPullInterval'>) {
|
||||
releaseChannel,
|
||||
setReleaseChannel,
|
||||
}: Pick<SettingsBodyProps, 'pullInterval' | 'setPullInterval' | 'releaseChannel' | 'setReleaseChannel'>) {
|
||||
return (
|
||||
<>
|
||||
<SectionHeading
|
||||
title="Sync"
|
||||
description="Automatically pull vault changes from Git in the background."
|
||||
title="Sync & Updates"
|
||||
description="Configure background pulling and which update feed Tolaria follows. Stable only receives manually promoted releases, while Alpha follows every push to main."
|
||||
/>
|
||||
|
||||
<LabeledSelect
|
||||
@@ -412,6 +412,17 @@ function SyncSettingsSection({
|
||||
testId="settings-pull-interval"
|
||||
autoFocus={true}
|
||||
/>
|
||||
|
||||
<LabeledSelect
|
||||
label="Release channel"
|
||||
value={releaseChannel}
|
||||
onValueChange={(value) => setReleaseChannel(value as ReleaseChannel)}
|
||||
options={[
|
||||
{ value: 'stable', label: 'Stable' },
|
||||
{ value: 'alpha', label: 'Alpha' },
|
||||
]}
|
||||
testId="settings-release-channel"
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -448,7 +459,7 @@ function AutoGitSettingsSection({
|
||||
/>
|
||||
|
||||
<SettingsSwitchRow
|
||||
label="AutoGit"
|
||||
label="Enable AutoGit"
|
||||
description="When enabled, Tolaria will commit and push saved local changes automatically after an idle pause or after the app becomes inactive."
|
||||
checked={autoGitEnabled}
|
||||
onChange={setAutoGitEnabled}
|
||||
@@ -537,31 +548,6 @@ function AiAgentSettingsSection({
|
||||
)
|
||||
}
|
||||
|
||||
function ReleaseChannelSection({
|
||||
releaseChannel,
|
||||
setReleaseChannel,
|
||||
}: Pick<SettingsBodyProps, 'releaseChannel' | 'setReleaseChannel'>) {
|
||||
return (
|
||||
<>
|
||||
<SectionHeading
|
||||
title="Release Channel"
|
||||
description="Controls which update feed Tolaria polls. Stable only receives manually promoted releases. Alpha follows every push to main."
|
||||
/>
|
||||
|
||||
<LabeledSelect
|
||||
label="Release channel"
|
||||
value={releaseChannel}
|
||||
onValueChange={(value) => setReleaseChannel(value as ReleaseChannel)}
|
||||
options={[
|
||||
{ value: 'stable', label: 'Stable' },
|
||||
{ value: 'alpha', label: 'Alpha' },
|
||||
]}
|
||||
testId="settings-release-channel"
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
function PrivacySettingsSection({
|
||||
crashReporting,
|
||||
setCrashReporting,
|
||||
@@ -593,6 +579,21 @@ function PrivacySettingsSection({
|
||||
)
|
||||
}
|
||||
|
||||
function SettingsSection({
|
||||
children,
|
||||
showDivider = true,
|
||||
}: {
|
||||
children: ReactNode
|
||||
showDivider?: boolean
|
||||
}) {
|
||||
return (
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 14, padding: '18px 0' }}>
|
||||
{showDivider ? <Divider /> : null}
|
||||
{children}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function SectionHeading({
|
||||
title,
|
||||
description,
|
||||
@@ -601,9 +602,19 @@ function SectionHeading({
|
||||
description: string
|
||||
}) {
|
||||
return (
|
||||
<div>
|
||||
<div style={{ fontSize: 13, fontWeight: 600, color: 'var(--foreground)', marginBottom: 4 }}>{title}</div>
|
||||
<div style={{ fontSize: 12, color: 'var(--muted-foreground)', lineHeight: 1.5 }}>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
|
||||
<div
|
||||
style={{
|
||||
fontSize: 11,
|
||||
fontWeight: 700,
|
||||
letterSpacing: '0.08em',
|
||||
textTransform: 'uppercase',
|
||||
color: 'var(--muted-foreground)',
|
||||
}}
|
||||
>
|
||||
{title}
|
||||
</div>
|
||||
<div style={{ fontSize: 12, color: 'var(--muted-foreground)', lineHeight: 1.55, maxWidth: 420 }}>
|
||||
{description}
|
||||
</div>
|
||||
</div>
|
||||
@@ -611,7 +622,7 @@ function SectionHeading({
|
||||
}
|
||||
|
||||
function Divider() {
|
||||
return <div style={{ height: 1, background: 'var(--border)' }} />
|
||||
return <div style={{ height: 1, background: 'color-mix(in srgb, var(--border) 82%, transparent)' }} />
|
||||
}
|
||||
|
||||
function renderDefaultAiAgentSummary(defaultAiAgent: AiAgentId, aiAgentsStatus: AiAgentsStatus): string {
|
||||
|
||||
@@ -5,6 +5,7 @@ import {
|
||||
SuggestionMenuController,
|
||||
BlockNoteViewRaw,
|
||||
ComponentsContext,
|
||||
SideMenuController,
|
||||
} from '@blocknote/react'
|
||||
import { components } from '@blocknote/mantine'
|
||||
import { MantineContext, MantineProvider } from '@mantine/core'
|
||||
@@ -23,6 +24,7 @@ import {
|
||||
TolariaFormattingToolbar,
|
||||
TolariaFormattingToolbarController,
|
||||
} from './tolariaEditorFormatting'
|
||||
import { TolariaSideMenu } from './tolariaBlockNoteSideMenu'
|
||||
import { useEditorLinkActivation } from './useEditorLinkActivation'
|
||||
|
||||
const TEST_TABLE_MARKDOWN = `| Head 1 | Head 2 | Head 3 |
|
||||
@@ -223,7 +225,9 @@ export function SingleEditorView({ editor, entries, onNavigateWikilink, onChange
|
||||
editable={editable}
|
||||
formattingToolbar={false}
|
||||
slashMenu={false}
|
||||
sideMenu={false}
|
||||
>
|
||||
<SideMenuController sideMenu={TolariaSideMenu} />
|
||||
<TolariaFormattingToolbarController
|
||||
formattingToolbar={TolariaFormattingToolbar}
|
||||
floatingUIOptions={{
|
||||
|
||||
@@ -467,7 +467,7 @@ describe('StatusBar', () => {
|
||||
/>,
|
||||
)
|
||||
|
||||
expect(screen.getByTestId('status-ai-agents')).toHaveTextContent('AI: Claude')
|
||||
expect(screen.getByTestId('status-ai-agents')).toHaveTextContent('Claude')
|
||||
})
|
||||
|
||||
it('opens the AI agent switcher from the keyboard and switches agents', () => {
|
||||
|
||||
@@ -27,4 +27,9 @@ describe('TelemetryConsentDialog', () => {
|
||||
render(<TelemetryConsentDialog onAccept={vi.fn()} onDecline={vi.fn()} />)
|
||||
expect(screen.getByText(/no vault content, note titles/i)).toBeDefined()
|
||||
})
|
||||
|
||||
it('focuses the first action for keyboard users', () => {
|
||||
render(<TelemetryConsentDialog onAccept={vi.fn()} onDecline={vi.fn()} />)
|
||||
expect(screen.getByTestId('telemetry-decline')).toHaveFocus()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -46,6 +46,7 @@ export function TelemetryConsentDialog({ onAccept, onDecline }: TelemetryConsent
|
||||
style={{ flex: 1, fontSize: 13, padding: '10px 16px' }}
|
||||
onClick={onDecline}
|
||||
data-testid="telemetry-decline"
|
||||
autoFocus
|
||||
>
|
||||
No thanks
|
||||
</button>
|
||||
|
||||
@@ -19,7 +19,7 @@ import {
|
||||
const TYPE_NONE = '__none__'
|
||||
const MIN_POPOVER_WIDTH = 220
|
||||
const OPEN_COMBOBOX_KEYS = new Set(['ArrowDown', 'ArrowUp', 'Enter', ' '])
|
||||
const MISSING_TYPE_TOOLTIP = 'There is no type file for this type'
|
||||
const MISSING_TYPE_TOOLTIP = 'Missing type'
|
||||
|
||||
interface TypeSelectorItemProps {
|
||||
type: string
|
||||
@@ -130,17 +130,16 @@ function MissingTypeWarning({
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
size="icon-xs"
|
||||
className={cn(
|
||||
'h-auto shrink-0 gap-1 rounded-full border border-amber-300/70 px-2 py-1 text-[11px] font-medium text-amber-900 shadow-none hover:bg-amber-100',
|
||||
'h-6 w-6 shrink-0 rounded-md border border-amber-300/80 bg-amber-50 p-0 text-amber-700 shadow-none hover:bg-amber-100 hover:text-amber-800',
|
||||
!canCreateMissingType && 'cursor-default',
|
||||
)}
|
||||
data-testid="missing-type-warning"
|
||||
aria-label={`Missing type ${missingTypeName}. ${MISSING_TYPE_TOOLTIP}`}
|
||||
aria-label={`Missing type ${missingTypeName}. Click to create this type.`}
|
||||
onClick={canCreateMissingType ? () => setDialogOpen(true) : undefined}
|
||||
>
|
||||
<WarningCircle size={14} aria-hidden="true" />
|
||||
Missing type
|
||||
<WarningCircle size={14} weight="fill" aria-hidden="true" />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>{MISSING_TYPE_TOOLTIP}</TooltipContent>
|
||||
@@ -169,7 +168,7 @@ function TypeRowValue({
|
||||
onCreateMissingType?: (typeName: string) => void | Promise<void>
|
||||
}) {
|
||||
return (
|
||||
<div className="flex min-w-0 items-center justify-end gap-1">
|
||||
<div className="flex min-w-0 items-center justify-start gap-1">
|
||||
<div className="min-w-0">{children}</div>
|
||||
{missingTypeName && (
|
||||
<MissingTypeWarning
|
||||
|
||||
@@ -30,6 +30,11 @@ describe('WelcomeScreen', () => {
|
||||
expect(screen.getByTestId('welcome-create-vault')).toHaveTextContent('Get started with a template')
|
||||
})
|
||||
|
||||
it('focuses the first action for keyboard users', () => {
|
||||
render(<WelcomeScreen {...defaultProps} />)
|
||||
expect(screen.getByTestId('welcome-create-new')).toHaveFocus()
|
||||
})
|
||||
|
||||
it('shows default vault path in template option description', () => {
|
||||
render(<WelcomeScreen {...defaultProps} />)
|
||||
expect(screen.getByText(/~\/Documents\/Laputa/)).toBeInTheDocument()
|
||||
|
||||
@@ -160,6 +160,7 @@ interface OptionButtonProps {
|
||||
disabled: boolean
|
||||
loading?: boolean
|
||||
testId: string
|
||||
autoFocus?: boolean
|
||||
}
|
||||
|
||||
function OptionButton({
|
||||
@@ -173,6 +174,7 @@ function OptionButton({
|
||||
disabled,
|
||||
loading,
|
||||
testId,
|
||||
autoFocus = false,
|
||||
}: OptionButtonProps) {
|
||||
const [hover, setHover] = useState(false)
|
||||
return (
|
||||
@@ -188,6 +190,7 @@ function OptionButton({
|
||||
onMouseEnter={() => setHover(true)}
|
||||
onMouseLeave={() => setHover(false)}
|
||||
data-testid={testId}
|
||||
autoFocus={autoFocus}
|
||||
>
|
||||
<div style={{ ...OPTION_ICON_STYLE, background: iconBg }}>
|
||||
{loading ? <Loader2 size={18} className="animate-spin" style={{ color: 'var(--muted-foreground)' }} /> : icon}
|
||||
@@ -278,6 +281,7 @@ export function WelcomeScreen({
|
||||
disabled={busy}
|
||||
loading={creatingAction === 'empty'}
|
||||
testId="welcome-create-new"
|
||||
autoFocus
|
||||
/>
|
||||
|
||||
<OptionButton
|
||||
|
||||
@@ -54,32 +54,60 @@ export function applyPendingRawExitContent(
|
||||
return changed ? nextTabs : tabs
|
||||
}
|
||||
|
||||
function syncContentIfChanged({
|
||||
currentContent,
|
||||
nextContent,
|
||||
path,
|
||||
onContentChange,
|
||||
}: {
|
||||
currentContent: string | null
|
||||
nextContent: string
|
||||
path: string
|
||||
onContentChange?: (path: string, content: string) => void
|
||||
}) {
|
||||
if (currentContent === nextContent) return
|
||||
onContentChange?.(path, nextContent)
|
||||
}
|
||||
|
||||
export function syncActiveTabIntoRawBuffer(options: {
|
||||
editor: ReturnType<typeof useCreateBlockNote>
|
||||
activeTabPath: string | null
|
||||
activeTabContent: string | null
|
||||
rawLatestContentRef: React.MutableRefObject<string | null>
|
||||
onContentChange?: (path: string, content: string) => void
|
||||
}) {
|
||||
const { editor, activeTabPath, activeTabContent, rawLatestContentRef, onContentChange } = options
|
||||
const { editor, activeTabPath, activeTabContent, rawLatestContentRef } = options
|
||||
if (!activeTabPath || activeTabContent === null) return null
|
||||
|
||||
const syncedContent = serializeEditorDocumentToMarkdown(editor, activeTabContent)
|
||||
rawLatestContentRef.current = syncedContent
|
||||
onContentChange?.(activeTabPath, syncedContent)
|
||||
return syncedContent
|
||||
}
|
||||
|
||||
export function rememberPendingRawExitContent(options: {
|
||||
activeTabPath: string | null
|
||||
activeTabContent: string | null
|
||||
rawInitialContent: string | null
|
||||
rawLatestContentRef: React.MutableRefObject<string | null>
|
||||
onContentChange?: (path: string, content: string) => void
|
||||
}) {
|
||||
const { activeTabPath, rawLatestContentRef, onContentChange } = options
|
||||
const {
|
||||
activeTabPath,
|
||||
activeTabContent,
|
||||
rawInitialContent,
|
||||
rawLatestContentRef,
|
||||
onContentChange,
|
||||
} = options
|
||||
const pendingRawExitContent = buildPendingRawExitContent(activeTabPath, rawLatestContentRef.current)
|
||||
if (!pendingRawExitContent) return null
|
||||
if (pendingRawExitContent.content === rawInitialContent) return null
|
||||
if (pendingRawExitContent.content === activeTabContent) return null
|
||||
|
||||
onContentChange?.(pendingRawExitContent.path, pendingRawExitContent.content)
|
||||
syncContentIfChanged({
|
||||
currentContent: activeTabContent,
|
||||
nextContent: pendingRawExitContent.content,
|
||||
path: pendingRawExitContent.path,
|
||||
onContentChange,
|
||||
})
|
||||
return pendingRawExitContent
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { AlertTriangle, ChevronsUpDown, Terminal } from 'lucide-react'
|
||||
import { AlertTriangle, ChevronsUpDown } from 'lucide-react'
|
||||
import { Sparkle } from '@phosphor-icons/react'
|
||||
import { ActionTooltip } from '@/components/ui/action-tooltip'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import {
|
||||
@@ -72,11 +73,8 @@ function missingAgentDefinitions(statuses: AiAgentsStatus): AiAgentDefinition[]
|
||||
return AI_AGENT_DEFINITIONS.filter((definition) => !isAiAgentInstalled(statuses, definition.id))
|
||||
}
|
||||
|
||||
function triggerLabel(defaultAgent: AiAgentId, selectedAgentReady: boolean): string {
|
||||
const definition = getAiAgentDefinition(defaultAgent)
|
||||
return selectedAgentReady
|
||||
? `AI: ${definition.shortLabel}`
|
||||
: `AI: ${definition.shortLabel} unavailable`
|
||||
function triggerLabel(defaultAgent: AiAgentId): string {
|
||||
return getAiAgentDefinition(defaultAgent).shortLabel
|
||||
}
|
||||
|
||||
function menuHeading(defaultAgent: AiAgentId, selectedAgentReady: boolean): string {
|
||||
@@ -211,8 +209,8 @@ export function AiAgentsBadge({
|
||||
data-testid="status-ai-agents"
|
||||
>
|
||||
<span style={{ ...ICON_STYLE, color: showWarning ? 'var(--accent-orange)' : 'var(--muted-foreground)' }}>
|
||||
<Terminal size={13} />
|
||||
{triggerLabel(defaultAgent, selectedAgentReady)}
|
||||
<Sparkle size={13} weight="fill" />
|
||||
{triggerLabel(defaultAgent)}
|
||||
{showWarning && <AlertTriangle size={10} style={{ marginLeft: 2 }} />}
|
||||
{!showWarning && showSwitcherCue && <ChevronsUpDown size={10} style={{ marginLeft: 2 }} />}
|
||||
</span>
|
||||
|
||||
@@ -210,7 +210,7 @@ export function StatusBarSecondarySection({
|
||||
<Bell size={14} />
|
||||
</span>
|
||||
</ActionTooltip>
|
||||
<ActionTooltip copy={SETTINGS_TOOLTIP} side="top">
|
||||
<ActionTooltip copy={SETTINGS_TOOLTIP} side="top" align="end">
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
|
||||
44
src/components/tolariaBlockNoteSideMenu.test.tsx
Normal file
44
src/components/tolariaBlockNoteSideMenu.test.tsx
Normal file
@@ -0,0 +1,44 @@
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import type { ComponentType, PropsWithChildren } from 'react'
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import { TolariaSideMenu } from './tolariaBlockNoteSideMenu'
|
||||
|
||||
let capturedDragHandleMenu: ComponentType | null = null
|
||||
|
||||
vi.mock('@blocknote/react', () => ({
|
||||
DragHandleMenu: ({ children }: PropsWithChildren) => (
|
||||
<div data-testid="drag-handle-menu">{children}</div>
|
||||
),
|
||||
RemoveBlockItem: ({ children }: PropsWithChildren) => <div>{children}</div>,
|
||||
SideMenu: ({ dragHandleMenu }: { dragHandleMenu?: ComponentType }) => {
|
||||
capturedDragHandleMenu = dragHandleMenu ?? null
|
||||
return <div data-testid="side-menu" />
|
||||
},
|
||||
TableColumnHeaderItem: ({ children }: PropsWithChildren) => <div>{children}</div>,
|
||||
TableRowHeaderItem: ({ children }: PropsWithChildren) => <div>{children}</div>,
|
||||
useDictionary: () => ({
|
||||
drag_handle: {
|
||||
delete_menuitem: 'Delete',
|
||||
header_row_menuitem: 'Header row',
|
||||
header_column_menuitem: 'Header column',
|
||||
colors_menuitem: 'Colors',
|
||||
},
|
||||
}),
|
||||
}))
|
||||
|
||||
describe('TolariaSideMenu', () => {
|
||||
it('replaces BlockNote block colors with markdown-safe drag-handle items', () => {
|
||||
render(<TolariaSideMenu />)
|
||||
|
||||
expect(screen.getByTestId('side-menu')).toBeInTheDocument()
|
||||
expect(capturedDragHandleMenu).not.toBeNull()
|
||||
|
||||
const DragHandleMenuComponent = capturedDragHandleMenu!
|
||||
render(<DragHandleMenuComponent />)
|
||||
|
||||
expect(screen.getByText('Delete')).toBeInTheDocument()
|
||||
expect(screen.getByText('Header row')).toBeInTheDocument()
|
||||
expect(screen.getByText('Header column')).toBeInTheDocument()
|
||||
expect(screen.queryByText('Colors')).not.toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
25
src/components/tolariaBlockNoteSideMenu.tsx
Normal file
25
src/components/tolariaBlockNoteSideMenu.tsx
Normal file
@@ -0,0 +1,25 @@
|
||||
import {
|
||||
DragHandleMenu,
|
||||
RemoveBlockItem,
|
||||
SideMenu,
|
||||
TableColumnHeaderItem,
|
||||
TableRowHeaderItem,
|
||||
type SideMenuProps,
|
||||
useDictionary,
|
||||
} from '@blocknote/react'
|
||||
|
||||
function TolariaDragHandleMenu() {
|
||||
const dict = useDictionary()
|
||||
|
||||
return (
|
||||
<DragHandleMenu>
|
||||
<RemoveBlockItem>{dict.drag_handle.delete_menuitem}</RemoveBlockItem>
|
||||
<TableRowHeaderItem>{dict.drag_handle.header_row_menuitem}</TableRowHeaderItem>
|
||||
<TableColumnHeaderItem>{dict.drag_handle.header_column_menuitem}</TableColumnHeaderItem>
|
||||
</DragHandleMenu>
|
||||
)
|
||||
}
|
||||
|
||||
export function TolariaSideMenu(props: SideMenuProps) {
|
||||
return <SideMenu {...props} dragHandleMenu={TolariaDragHandleMenu} />
|
||||
}
|
||||
@@ -25,7 +25,18 @@ import type {
|
||||
StyleSchema,
|
||||
} from '@blocknote/core'
|
||||
import { FormattingToolbarExtension } from '@blocknote/core/extensions'
|
||||
import { useCallback, useMemo, useState, type FC, type ReactElement } from 'react'
|
||||
import {
|
||||
useCallback,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
type Dispatch,
|
||||
type FC,
|
||||
type MutableRefObject,
|
||||
type ReactElement,
|
||||
type SetStateAction,
|
||||
} from 'react'
|
||||
import {
|
||||
Button as MantineButton,
|
||||
CheckIcon as MantineCheckIcon,
|
||||
@@ -46,6 +57,78 @@ import {
|
||||
|
||||
type TolariaBasicTextStyle = 'bold' | 'italic' | 'strike' | 'code'
|
||||
|
||||
const FORMATTER_CLOSE_GRACE_MS = 160
|
||||
|
||||
function isFocusStillWithinToolbar(
|
||||
currentTarget: EventTarget & Element,
|
||||
nextTarget: EventTarget | null,
|
||||
) {
|
||||
return nextTarget instanceof Node && currentTarget.contains(nextTarget)
|
||||
}
|
||||
|
||||
function clearToolbarCloseGrace(
|
||||
timeoutRef: MutableRefObject<number | null>,
|
||||
setCloseGraceActive: Dispatch<SetStateAction<boolean>>,
|
||||
) {
|
||||
if (timeoutRef.current !== null) {
|
||||
window.clearTimeout(timeoutRef.current)
|
||||
timeoutRef.current = null
|
||||
}
|
||||
setCloseGraceActive(false)
|
||||
}
|
||||
|
||||
function startToolbarCloseGrace(
|
||||
timeoutRef: MutableRefObject<number | null>,
|
||||
setCloseGraceActive: Dispatch<SetStateAction<boolean>>,
|
||||
) {
|
||||
setCloseGraceActive(true)
|
||||
if (timeoutRef.current !== null) {
|
||||
window.clearTimeout(timeoutRef.current)
|
||||
}
|
||||
timeoutRef.current = window.setTimeout(() => {
|
||||
timeoutRef.current = null
|
||||
setCloseGraceActive(false)
|
||||
}, FORMATTER_CLOSE_GRACE_MS)
|
||||
}
|
||||
|
||||
function useFormattingToolbarCloseGrace({
|
||||
show,
|
||||
toolbarHasFocus,
|
||||
toolbarHovered,
|
||||
}: {
|
||||
show: boolean
|
||||
toolbarHasFocus: boolean
|
||||
toolbarHovered: boolean
|
||||
}) {
|
||||
const [closeGraceActive, setCloseGraceActive] = useState(false)
|
||||
const closeGraceTimeoutRef = useRef<number | null>(null)
|
||||
const previousShowRef = useRef(show)
|
||||
|
||||
const clearCloseGrace = useCallback(() => {
|
||||
clearToolbarCloseGrace(closeGraceTimeoutRef, setCloseGraceActive)
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
const toolbarInteractionActive = show || toolbarHasFocus || toolbarHovered
|
||||
|
||||
if (toolbarInteractionActive) {
|
||||
clearCloseGrace()
|
||||
} else if (previousShowRef.current) {
|
||||
startToolbarCloseGrace(closeGraceTimeoutRef, setCloseGraceActive)
|
||||
}
|
||||
|
||||
previousShowRef.current = show
|
||||
}, [clearCloseGrace, show, toolbarHasFocus, toolbarHovered])
|
||||
|
||||
useEffect(() => () => {
|
||||
if (closeGraceTimeoutRef.current !== null) {
|
||||
window.clearTimeout(closeGraceTimeoutRef.current)
|
||||
}
|
||||
}, [])
|
||||
|
||||
return { closeGraceActive, clearCloseGrace }
|
||||
}
|
||||
|
||||
const TOLARIA_BASIC_TEXT_STYLE_TOOLTIPS = {
|
||||
bold: {
|
||||
label: 'Bold',
|
||||
@@ -360,7 +443,14 @@ export function TolariaFormattingToolbarController(props: {
|
||||
editor,
|
||||
})
|
||||
const [toolbarHasFocus, setToolbarHasFocus] = useState(false)
|
||||
const isOpen = show || toolbarHasFocus
|
||||
const [toolbarHovered, setToolbarHovered] = useState(false)
|
||||
const { closeGraceActive, clearCloseGrace } = useFormattingToolbarCloseGrace({
|
||||
show,
|
||||
toolbarHasFocus,
|
||||
toolbarHovered,
|
||||
})
|
||||
|
||||
const isOpen = show || toolbarHasFocus || toolbarHovered || closeGraceActive
|
||||
|
||||
const position = useEditorState({
|
||||
editor,
|
||||
@@ -398,6 +488,8 @@ export function TolariaFormattingToolbarController(props: {
|
||||
formattingToolbar.store.setState(open)
|
||||
if (!open) {
|
||||
setToolbarHasFocus(false)
|
||||
setToolbarHovered(false)
|
||||
clearCloseGrace()
|
||||
}
|
||||
if (reason === 'escape-key') {
|
||||
editor.focus()
|
||||
@@ -413,7 +505,14 @@ export function TolariaFormattingToolbarController(props: {
|
||||
...props.floatingUIOptions?.elementProps,
|
||||
},
|
||||
}),
|
||||
[editor, formattingToolbar.store, isOpen, placement, props.floatingUIOptions],
|
||||
[
|
||||
clearCloseGrace,
|
||||
editor,
|
||||
formattingToolbar.store,
|
||||
isOpen,
|
||||
placement,
|
||||
props.floatingUIOptions,
|
||||
],
|
||||
)
|
||||
|
||||
const Component = props.formattingToolbar || TolariaFormattingToolbar
|
||||
@@ -422,12 +521,21 @@ export function TolariaFormattingToolbarController(props: {
|
||||
<PositionPopover position={position} {...floatingUIOptions}>
|
||||
{isOpen && (
|
||||
<div
|
||||
onPointerEnter={() => {
|
||||
setToolbarHovered(true)
|
||||
}}
|
||||
onPointerLeave={(event) => {
|
||||
if (isFocusStillWithinToolbar(event.currentTarget, event.relatedTarget)) {
|
||||
return
|
||||
}
|
||||
|
||||
setToolbarHovered(false)
|
||||
}}
|
||||
onFocusCapture={() => {
|
||||
setToolbarHasFocus(true)
|
||||
}}
|
||||
onBlurCapture={(event) => {
|
||||
const nextTarget = event.relatedTarget
|
||||
if (nextTarget instanceof Node && event.currentTarget.contains(nextTarget)) {
|
||||
if (isFocusStillWithinToolbar(event.currentTarget, event.relatedTarget)) {
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
@@ -12,6 +12,7 @@ interface ActionTooltipProps {
|
||||
children: ReactNode
|
||||
className?: string
|
||||
side?: ComponentProps<typeof TooltipContent>['side']
|
||||
align?: ComponentProps<typeof TooltipContent>['align']
|
||||
sideOffset?: number
|
||||
}
|
||||
|
||||
@@ -20,12 +21,13 @@ export function ActionTooltip({
|
||||
children,
|
||||
className,
|
||||
side = 'top',
|
||||
align = 'center',
|
||||
sideOffset = 6,
|
||||
}: ActionTooltipProps) {
|
||||
return (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>{children}</TooltipTrigger>
|
||||
<TooltipContent side={side} sideOffset={sideOffset} className={cn('px-2.5 py-2', className)}>
|
||||
<TooltipContent side={side} align={align} sideOffset={sideOffset} className={cn('px-2.5 py-2', className)}>
|
||||
<div className="flex min-w-0 items-center gap-3">
|
||||
<span className="min-w-0 flex-1 text-[11px] font-medium leading-tight">{copy.label}</span>
|
||||
{copy.shortcut && (
|
||||
|
||||
132
src/components/useFilenameAutolinkGuard.ts
Normal file
132
src/components/useFilenameAutolinkGuard.ts
Normal file
@@ -0,0 +1,132 @@
|
||||
import { useEffect } from 'react'
|
||||
import type { useCreateBlockNote } from '@blocknote/react'
|
||||
import { shouldStripAutoLinkedLocalFileMark } from '../utils/editorLinkAutolink'
|
||||
|
||||
const FILENAME_AUTOLINK_GUARD_META = 'tolaria-filename-autolink-guard'
|
||||
|
||||
type TiptapLinkMark = {
|
||||
attrs?: {
|
||||
href?: string
|
||||
}
|
||||
type: unknown
|
||||
}
|
||||
|
||||
type TiptapTextNode = {
|
||||
isText?: boolean
|
||||
marks?: TiptapLinkMark[]
|
||||
nodeSize: number
|
||||
text?: string | null
|
||||
}
|
||||
|
||||
function hasTextContent(node: TiptapTextNode) {
|
||||
return Boolean(node.isText && node.text && node.marks?.length)
|
||||
}
|
||||
|
||||
function isAccidentalFilenameLinkMark(
|
||||
mark: TiptapLinkMark,
|
||||
linkMarkType: unknown,
|
||||
text: string,
|
||||
) {
|
||||
if (mark.type !== linkMarkType) {
|
||||
return false
|
||||
}
|
||||
|
||||
if (typeof mark.attrs?.href !== 'string') {
|
||||
return false
|
||||
}
|
||||
|
||||
return shouldStripAutoLinkedLocalFileMark({
|
||||
href: { raw: mark.attrs.href },
|
||||
text: { raw: text },
|
||||
})
|
||||
}
|
||||
|
||||
function hasEditorEventApi(
|
||||
tiptap: ReturnType<typeof useCreateBlockNote>['_tiptapEditor'] | undefined,
|
||||
) {
|
||||
return Boolean(tiptap && typeof tiptap.on === 'function' && typeof tiptap.off === 'function')
|
||||
}
|
||||
|
||||
function collectAccidentalFilenameLinkRanges(editor: ReturnType<typeof useCreateBlockNote>) {
|
||||
const linkMarkType = editor._tiptapEditor?.schema?.marks?.link
|
||||
if (!linkMarkType) {
|
||||
return []
|
||||
}
|
||||
|
||||
const ranges: Array<{ from: number; to: number }> = []
|
||||
editor._tiptapEditor.state.doc.descendants((node: TiptapTextNode, pos: number) => {
|
||||
if (!hasTextContent(node)) {
|
||||
return
|
||||
}
|
||||
|
||||
const hasAccidentalFilenameLink = node.marks?.some((mark) => (
|
||||
isAccidentalFilenameLinkMark(mark, linkMarkType, node.text ?? '')
|
||||
)) ?? false
|
||||
|
||||
if (hasAccidentalFilenameLink) {
|
||||
ranges.push({ from: pos, to: pos + node.nodeSize })
|
||||
}
|
||||
})
|
||||
|
||||
return ranges
|
||||
}
|
||||
|
||||
function shouldSkipGuardRun(
|
||||
applyingGuard: boolean,
|
||||
transaction: { docChanged?: boolean; getMeta: (key: string) => unknown },
|
||||
) {
|
||||
return (
|
||||
applyingGuard
|
||||
|| !transaction.docChanged
|
||||
|| transaction.getMeta(FILENAME_AUTOLINK_GUARD_META)
|
||||
)
|
||||
}
|
||||
|
||||
function removeLinkRanges(
|
||||
editor: ReturnType<typeof useCreateBlockNote>,
|
||||
ranges: Array<{ from: number; to: number }>,
|
||||
) {
|
||||
const tr = editor._tiptapEditor.state.tr
|
||||
for (const range of ranges) {
|
||||
tr.removeMark(range.from, range.to, editor._tiptapEditor.schema.marks.link)
|
||||
}
|
||||
|
||||
return tr
|
||||
}
|
||||
|
||||
export function useFilenameAutolinkGuard(editor: ReturnType<typeof useCreateBlockNote>) {
|
||||
useEffect(() => {
|
||||
const tiptap = editor._tiptapEditor
|
||||
if (!hasEditorEventApi(tiptap)) {
|
||||
return
|
||||
}
|
||||
|
||||
let applyingGuard = false
|
||||
const stripAccidentalFilenameAutolinks = ({ transaction }: { transaction: { docChanged?: boolean; getMeta: (key: string) => unknown } }) => {
|
||||
if (shouldSkipGuardRun(applyingGuard, transaction)) {
|
||||
return
|
||||
}
|
||||
|
||||
const ranges = collectAccidentalFilenameLinkRanges(editor)
|
||||
if (ranges.length === 0) {
|
||||
return
|
||||
}
|
||||
|
||||
const tr = removeLinkRanges(editor, ranges)
|
||||
if (!tr.docChanged) {
|
||||
return
|
||||
}
|
||||
|
||||
tr.setMeta(FILENAME_AUTOLINK_GUARD_META, true)
|
||||
applyingGuard = true
|
||||
tiptap.view.dispatch(tr)
|
||||
applyingGuard = false
|
||||
}
|
||||
|
||||
tiptap.on('update', stripAccidentalFilenameAutolinks)
|
||||
|
||||
return () => {
|
||||
tiptap.off('update', stripAccidentalFilenameAutolinks)
|
||||
}
|
||||
}, [editor])
|
||||
}
|
||||
@@ -76,17 +76,20 @@ function capturePendingRoundTripRawRestore(activeTabPath: string | null): Pendin
|
||||
function useTrackRawBuffer({
|
||||
activeTabContent,
|
||||
activeTabPath,
|
||||
rawInitialContentRef,
|
||||
rawBufferPathRef,
|
||||
rawLatestContentRef,
|
||||
}: {
|
||||
activeTabContent: string | null
|
||||
activeTabPath: string | null
|
||||
rawInitialContentRef: React.MutableRefObject<string | null>
|
||||
rawBufferPathRef: React.MutableRefObject<string | null>
|
||||
rawLatestContentRef: React.MutableRefObject<string | null>
|
||||
}) {
|
||||
useLayoutEffect(() => {
|
||||
if (!activeTabPath) {
|
||||
rawLatestContentRef.current = null
|
||||
rawInitialContentRef.current = null
|
||||
rawBufferPathRef.current = null
|
||||
return
|
||||
}
|
||||
@@ -96,44 +99,52 @@ function useTrackRawBuffer({
|
||||
}
|
||||
|
||||
rawLatestContentRef.current = activeTabContent
|
||||
rawInitialContentRef.current = activeTabContent
|
||||
rawBufferPathRef.current = activeTabContent === null ? null : activeTabPath
|
||||
}, [activeTabContent, activeTabPath, rawBufferPathRef, rawLatestContentRef])
|
||||
}, [activeTabContent, activeTabPath, rawBufferPathRef, rawInitialContentRef, rawLatestContentRef])
|
||||
}
|
||||
|
||||
function resetRawBufferState({
|
||||
rawInitialContentRef,
|
||||
rawBufferPathRef,
|
||||
rawLatestContentRef,
|
||||
}: {
|
||||
rawInitialContentRef: React.MutableRefObject<string | null>
|
||||
rawBufferPathRef: React.MutableRefObject<string | null>
|
||||
rawLatestContentRef: React.MutableRefObject<string | null>
|
||||
}) {
|
||||
rawInitialContentRef.current = null
|
||||
rawBufferPathRef.current = null
|
||||
rawLatestContentRef.current = null
|
||||
}
|
||||
|
||||
export function useRawModeWithFlush(
|
||||
editor: ReturnType<typeof useCreateBlockNote>,
|
||||
activeTabPath: string | null,
|
||||
activeTabContent: string | null,
|
||||
onContentChange?: (path: string, content: string) => void,
|
||||
) {
|
||||
const rawLatestContentRef = useRef<string | null>(null)
|
||||
const rawBufferPathRef = useRef<string | null>(null)
|
||||
const pendingRawRestoreRef = useRef<CodeMirrorRestoreState | null>(null)
|
||||
const pendingRichRestoreRef = useRef<RawEditorPositionSnapshot | null>(null)
|
||||
const pendingRoundTripRawRestoreRef = useRef<PendingRoundTripRawRestore | null>(null)
|
||||
const [pendingRawExitContent, setPendingRawExitContent] = useState<PendingRawExitContent | null>(null)
|
||||
const [rawModeContentOverride, setRawModeContentOverride] = useState<PendingRawExitContent | null>(null)
|
||||
useTrackRawBuffer({ activeTabContent, activeTabPath, rawBufferPathRef, rawLatestContentRef })
|
||||
|
||||
const handleFlushPending = useCallback(async () => {
|
||||
function useHandleFlushPending({
|
||||
editor,
|
||||
activeTabPath,
|
||||
activeTabContent,
|
||||
rawInitialContentRef,
|
||||
rawLatestContentRef,
|
||||
pendingRawRestoreRef,
|
||||
pendingRoundTripRawRestoreRef,
|
||||
setRawModeContentOverride,
|
||||
}: {
|
||||
editor: ReturnType<typeof useCreateBlockNote>
|
||||
activeTabPath: string | null
|
||||
activeTabContent: string | null
|
||||
rawInitialContentRef: React.MutableRefObject<string | null>
|
||||
rawLatestContentRef: React.MutableRefObject<string | null>
|
||||
pendingRawRestoreRef: React.MutableRefObject<CodeMirrorRestoreState | null>
|
||||
pendingRoundTripRawRestoreRef: React.MutableRefObject<PendingRoundTripRawRestore | null>
|
||||
setRawModeContentOverride: React.Dispatch<React.SetStateAction<PendingRawExitContent | null>>
|
||||
}) {
|
||||
return useCallback(async () => {
|
||||
const syncedContent = syncActiveTabIntoRawBuffer({
|
||||
editor,
|
||||
activeTabPath,
|
||||
activeTabContent,
|
||||
rawLatestContentRef,
|
||||
onContentChange,
|
||||
})
|
||||
rawInitialContentRef.current = syncedContent ?? activeTabContent
|
||||
pendingRawRestoreRef.current = buildPendingRawRestore({
|
||||
activeTabContent,
|
||||
activeTabPath,
|
||||
@@ -145,20 +156,116 @@ export function useRawModeWithFlush(
|
||||
setRawModeContentOverride(buildPendingRawExitContent(activeTabPath, syncedContent))
|
||||
clearTableResizeState(editor)
|
||||
return true
|
||||
}, [activeTabContent, activeTabPath, editor, onContentChange])
|
||||
}, [
|
||||
activeTabContent,
|
||||
activeTabPath,
|
||||
editor,
|
||||
pendingRawRestoreRef,
|
||||
pendingRoundTripRawRestoreRef,
|
||||
rawInitialContentRef,
|
||||
rawLatestContentRef,
|
||||
setRawModeContentOverride,
|
||||
])
|
||||
}
|
||||
|
||||
const handleBeforeRawEnd = useCallback(() => {
|
||||
function useHandleBeforeRawEnd({
|
||||
activeTabPath,
|
||||
activeTabContent,
|
||||
onContentChange,
|
||||
rawInitialContentRef,
|
||||
rawBufferPathRef,
|
||||
rawLatestContentRef,
|
||||
pendingRawRestoreRef,
|
||||
pendingRichRestoreRef,
|
||||
pendingRoundTripRawRestoreRef,
|
||||
setPendingRawExitContent,
|
||||
setRawModeContentOverride,
|
||||
}: {
|
||||
activeTabPath: string | null
|
||||
activeTabContent: string | null
|
||||
onContentChange?: (path: string, content: string) => void
|
||||
rawInitialContentRef: React.MutableRefObject<string | null>
|
||||
rawBufferPathRef: React.MutableRefObject<string | null>
|
||||
rawLatestContentRef: React.MutableRefObject<string | null>
|
||||
pendingRawRestoreRef: React.MutableRefObject<CodeMirrorRestoreState | null>
|
||||
pendingRichRestoreRef: React.MutableRefObject<RawEditorPositionSnapshot | null>
|
||||
pendingRoundTripRawRestoreRef: React.MutableRefObject<PendingRoundTripRawRestore | null>
|
||||
setPendingRawExitContent: React.Dispatch<React.SetStateAction<PendingRawExitContent | null>>
|
||||
setRawModeContentOverride: React.Dispatch<React.SetStateAction<PendingRawExitContent | null>>
|
||||
}) {
|
||||
return useCallback(() => {
|
||||
pendingRoundTripRawRestoreRef.current = capturePendingRoundTripRawRestore(activeTabPath)
|
||||
pendingRichRestoreRef.current = captureRawEditorPositionSnapshot(document)
|
||||
pendingRawRestoreRef.current = null
|
||||
setPendingRawExitContent(rememberPendingRawExitContent({
|
||||
activeTabPath,
|
||||
activeTabContent,
|
||||
rawInitialContent: rawInitialContentRef.current,
|
||||
rawLatestContentRef,
|
||||
onContentChange,
|
||||
}))
|
||||
setRawModeContentOverride(null)
|
||||
resetRawBufferState({ rawBufferPathRef, rawLatestContentRef })
|
||||
}, [activeTabPath, onContentChange])
|
||||
resetRawBufferState({ rawInitialContentRef, rawBufferPathRef, rawLatestContentRef })
|
||||
}, [
|
||||
activeTabContent,
|
||||
activeTabPath,
|
||||
onContentChange,
|
||||
pendingRawRestoreRef,
|
||||
pendingRichRestoreRef,
|
||||
pendingRoundTripRawRestoreRef,
|
||||
rawInitialContentRef,
|
||||
rawBufferPathRef,
|
||||
rawLatestContentRef,
|
||||
setPendingRawExitContent,
|
||||
setRawModeContentOverride,
|
||||
])
|
||||
}
|
||||
|
||||
export function useRawModeWithFlush(
|
||||
editor: ReturnType<typeof useCreateBlockNote>,
|
||||
activeTabPath: string | null,
|
||||
activeTabContent: string | null,
|
||||
onContentChange?: (path: string, content: string) => void,
|
||||
) {
|
||||
const rawLatestContentRef = useRef<string | null>(null)
|
||||
const rawInitialContentRef = useRef<string | null>(null)
|
||||
const rawBufferPathRef = useRef<string | null>(null)
|
||||
const pendingRawRestoreRef = useRef<CodeMirrorRestoreState | null>(null)
|
||||
const pendingRichRestoreRef = useRef<RawEditorPositionSnapshot | null>(null)
|
||||
const pendingRoundTripRawRestoreRef = useRef<PendingRoundTripRawRestore | null>(null)
|
||||
const [pendingRawExitContent, setPendingRawExitContent] = useState<PendingRawExitContent | null>(null)
|
||||
const [rawModeContentOverride, setRawModeContentOverride] = useState<PendingRawExitContent | null>(null)
|
||||
useTrackRawBuffer({
|
||||
activeTabContent,
|
||||
activeTabPath,
|
||||
rawInitialContentRef,
|
||||
rawBufferPathRef,
|
||||
rawLatestContentRef,
|
||||
})
|
||||
|
||||
const handleFlushPending = useHandleFlushPending({
|
||||
editor,
|
||||
activeTabPath,
|
||||
activeTabContent,
|
||||
rawInitialContentRef,
|
||||
rawLatestContentRef,
|
||||
pendingRawRestoreRef,
|
||||
pendingRoundTripRawRestoreRef,
|
||||
setRawModeContentOverride,
|
||||
})
|
||||
const handleBeforeRawEnd = useHandleBeforeRawEnd({
|
||||
activeTabPath,
|
||||
activeTabContent,
|
||||
onContentChange,
|
||||
rawInitialContentRef,
|
||||
rawBufferPathRef,
|
||||
rawLatestContentRef,
|
||||
pendingRawRestoreRef,
|
||||
pendingRichRestoreRef,
|
||||
pendingRoundTripRawRestoreRef,
|
||||
setPendingRawExitContent,
|
||||
setRawModeContentOverride,
|
||||
})
|
||||
|
||||
const { rawMode, handleToggleRaw } = useRawMode({
|
||||
activeTabPath,
|
||||
|
||||
@@ -32,7 +32,7 @@ export function buildViewCommands(config: ViewCommandsConfig): CommandAction[] {
|
||||
{ id: 'view-all', label: 'Full Layout', group: 'View', shortcut: '⌘3', keywords: ['layout', 'sidebar'], enabled: true, execute: () => onSetViewMode('all') },
|
||||
{ id: 'toggle-inspector', label: 'Toggle Properties Panel', group: 'View', shortcut: '⌘⇧I', keywords: ['properties', 'inspector', 'panel', 'right', 'sidebar'], enabled: true, execute: onToggleInspector },
|
||||
{ id: 'toggle-diff', label: 'Toggle Diff Mode', group: 'View', keywords: ['diff', 'changes', 'git', 'compare', 'version'], enabled: hasActiveNote && activeNoteModified, execute: () => onToggleDiff?.() },
|
||||
{ id: 'toggle-raw-editor', label: 'Toggle Raw Editor', group: 'View', keywords: ['raw', 'source', 'markdown', 'frontmatter', 'code', 'textarea'], enabled: hasActiveNote, execute: () => onToggleRawEditor?.() },
|
||||
{ id: 'toggle-raw-editor', label: 'Toggle Raw Editor', group: 'View', keywords: ['raw', 'source', 'markdown', 'frontmatter', 'code', 'textarea'], enabled: hasActiveNote && !!onToggleRawEditor, execute: () => onToggleRawEditor?.() },
|
||||
{ id: 'toggle-ai-panel', label: 'Toggle AI Panel', group: 'View', shortcut: '⇧⌘L', keywords: ['ai', 'agent', 'chat', 'assistant', 'contextual'], enabled: true, execute: () => onToggleAIChat?.() },
|
||||
{ id: 'toggle-backlinks', label: 'Toggle Backlinks', group: 'View', keywords: ['backlinks', 'references', 'links', 'mentions', 'incoming'], enabled: hasActiveNote, execute: onToggleInspector },
|
||||
{ id: 'customize-note-list-columns', label: noteListColumnsLabel, group: 'View', keywords: ['all notes', 'inbox', 'columns', 'chips', 'properties', 'note list'], enabled: !!(canCustomizeNoteListColumns && onCustomizeNoteListColumns), execute: () => onCustomizeNoteListColumns?.() },
|
||||
|
||||
@@ -461,6 +461,33 @@ describe('useAppSave', () => {
|
||||
expect(getTabs()[0].content).toBe('# Fresh Title\n\nBody that keeps changing while rename is pending')
|
||||
})
|
||||
|
||||
it('does not run markdown title-sync renames for non-markdown text files', async () => {
|
||||
vi.mocked(isTauri).mockReturnValue(true)
|
||||
|
||||
const viewPath = '/vault/views/active-projects.yml'
|
||||
const viewContent = 'name: Active Projects\nicon: rocket\ncolor: blue\n'
|
||||
const viewEntry = {
|
||||
...makeEntry(viewPath, 'Active Projects', 'active-projects.yml'),
|
||||
fileKind: 'text' as const,
|
||||
}
|
||||
|
||||
const { result } = renderSave({
|
||||
tabs: [{ entry: viewEntry, content: viewContent }],
|
||||
activeTabPath: viewPath,
|
||||
unsavedPaths: new Set([viewPath]),
|
||||
})
|
||||
|
||||
await act(async () => {
|
||||
await result.current.handleSave()
|
||||
})
|
||||
|
||||
expect(vi.mocked(invoke)).toHaveBeenCalledWith('save_note_content', {
|
||||
path: viewPath,
|
||||
content: viewContent,
|
||||
})
|
||||
expect(deps.handleRenameNote).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('remaps a buffered auto-save to the renamed path when untitled rename lands mid-idle window', async () => {
|
||||
const initialContent = '# Fresh Title\n\nInitial body'
|
||||
const bufferedContent = '# Fresh Title\n\nBody typed right before rename'
|
||||
|
||||
@@ -214,6 +214,12 @@ describe('useCommandRegistry', () => {
|
||||
expect(findCommand(result.current, 'archive-note')?.shortcut).toBeUndefined()
|
||||
})
|
||||
|
||||
it('disables Toggle Raw Editor when the active file cannot switch to rich mode', () => {
|
||||
const config = makeConfig({ onToggleRawEditor: undefined })
|
||||
const { result } = renderHook(() => useCommandRegistry(config))
|
||||
expect(findCommand(result.current, 'toggle-raw-editor')?.enabled).toBe(false)
|
||||
})
|
||||
|
||||
it('omits Inbox navigation when the explicit workflow is disabled', () => {
|
||||
const config = makeConfig({ showInbox: false })
|
||||
const { result } = renderHook(() => useCommandRegistry(config))
|
||||
|
||||
@@ -35,6 +35,7 @@ interface ReloadTabsAfterRenameRequest {
|
||||
|
||||
/** Check if a note's filename doesn't match the slug of its current title. */
|
||||
export function needsRenameOnSave(title: string, filename: string): boolean {
|
||||
if (!filename.toLowerCase().endsWith('.md')) return false
|
||||
return `${slugify(title)}.md` !== filename
|
||||
}
|
||||
|
||||
|
||||
@@ -72,6 +72,22 @@ async function expectStatus(
|
||||
})
|
||||
}
|
||||
|
||||
async function expectCancelledPickerLeavesWelcome(
|
||||
action: (onboarding: ReturnType<typeof useOnboarding>) => Promise<void>,
|
||||
) {
|
||||
mockCommands()
|
||||
vi.mocked(pickFolder).mockResolvedValue(null)
|
||||
|
||||
const { result } = await renderOnboarding()
|
||||
|
||||
await expectStatus(result, 'welcome')
|
||||
await act(async () => {
|
||||
await action(result.current)
|
||||
})
|
||||
|
||||
expect(result.current.state.status).toBe('welcome')
|
||||
}
|
||||
|
||||
describe('useOnboarding', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
@@ -94,9 +110,15 @@ describe('useOnboarding', () => {
|
||||
expect(result.current.state).toEqual({ status: 'welcome', defaultPath: DEFAULT_GETTING_STARTED_PATH })
|
||||
})
|
||||
|
||||
it('shows vault-missing when the welcome screen was previously dismissed', async () => {
|
||||
it('shows vault-missing when a previously configured active vault is missing', async () => {
|
||||
localStorage.setItem(APP_STORAGE_KEYS.welcomeDismissed, '1')
|
||||
mockCommands()
|
||||
mockCommands({
|
||||
load_vault_list: {
|
||||
vaults: [{ label: 'Old Vault', path: '/vault/deleted' }],
|
||||
active_vault: '/vault/deleted',
|
||||
hidden_defaults: [],
|
||||
},
|
||||
})
|
||||
|
||||
const { result } = await renderOnboarding('/vault/deleted')
|
||||
|
||||
@@ -153,17 +175,9 @@ describe('useOnboarding', () => {
|
||||
})
|
||||
|
||||
it('does nothing when the template folder picker is cancelled', async () => {
|
||||
mockCommands()
|
||||
vi.mocked(pickFolder).mockResolvedValue(null)
|
||||
|
||||
const { result } = await renderOnboarding()
|
||||
|
||||
await expectStatus(result, 'welcome')
|
||||
await act(async () => {
|
||||
await result.current.handleCreateVault()
|
||||
await expectCancelledPickerLeavesWelcome(async (onboarding) => {
|
||||
await onboarding.handleCreateVault()
|
||||
})
|
||||
|
||||
expect(result.current.state.status).toBe('welcome')
|
||||
expect(mockInvokeFn).not.toHaveBeenCalledWith('create_getting_started_vault', expect.anything())
|
||||
})
|
||||
|
||||
@@ -233,17 +247,9 @@ describe('useOnboarding', () => {
|
||||
})
|
||||
|
||||
it('does nothing when the empty-vault picker is cancelled', async () => {
|
||||
mockCommands()
|
||||
vi.mocked(pickFolder).mockResolvedValue(null)
|
||||
|
||||
const { result } = await renderOnboarding()
|
||||
|
||||
await expectStatus(result, 'welcome')
|
||||
await act(async () => {
|
||||
await result.current.handleCreateNewVault()
|
||||
await expectCancelledPickerLeavesWelcome(async (onboarding) => {
|
||||
await onboarding.handleCreateNewVault()
|
||||
})
|
||||
|
||||
expect(result.current.state.status).toBe('welcome')
|
||||
})
|
||||
|
||||
it('opens an existing folder and transitions to ready', async () => {
|
||||
@@ -262,17 +268,9 @@ describe('useOnboarding', () => {
|
||||
})
|
||||
|
||||
it('does nothing when the open-folder picker is cancelled', async () => {
|
||||
mockCommands()
|
||||
vi.mocked(pickFolder).mockResolvedValue(null)
|
||||
|
||||
const { result } = await renderOnboarding()
|
||||
|
||||
await expectStatus(result, 'welcome')
|
||||
await act(async () => {
|
||||
await result.current.handleOpenFolder()
|
||||
await expectCancelledPickerLeavesWelcome(async (onboarding) => {
|
||||
await onboarding.handleOpenFolder()
|
||||
})
|
||||
|
||||
expect(result.current.state.status).toBe('welcome')
|
||||
})
|
||||
|
||||
it('marks the welcome screen dismissed and keeps the initial vault path', async () => {
|
||||
|
||||
@@ -9,7 +9,7 @@ import {
|
||||
removeDisplayModeOverride,
|
||||
} from '../utils/propertyTypes'
|
||||
import { containsWikilinks } from '../components/DynamicPropertiesPanel'
|
||||
import { isSystemMetadataKey } from '../utils/systemMetadata'
|
||||
import { canonicalSystemMetadataKey, isSystemMetadataKey } from '../utils/systemMetadata'
|
||||
|
||||
// Keys to skip showing in Properties (handled by dedicated UI or internal)
|
||||
// Compared case-insensitively via isVisibleProperty()
|
||||
@@ -79,6 +79,22 @@ function isVisibleProperty([key, value]: [string, FrontmatterValue]): boolean {
|
||||
return !isHiddenPropertyKey(key) && !containsWikilinks(value)
|
||||
}
|
||||
|
||||
function buildVisiblePropertyEntries(frontmatter: ParsedFrontmatter): [string, FrontmatterValue][] {
|
||||
const result: [string, FrontmatterValue][] = []
|
||||
const seen = new Set<string>()
|
||||
|
||||
for (const [key, value] of Object.entries(frontmatter)) {
|
||||
if (!isVisibleProperty([key, value])) continue
|
||||
|
||||
const canonicalKey = canonicalSystemMetadataKey(key)
|
||||
if (seen.has(canonicalKey)) continue
|
||||
seen.add(canonicalKey)
|
||||
result.push([key, value])
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
function addTagValues(tagsByKey: Map<string, Set<string>>, key: string, value: unknown) {
|
||||
if (!Array.isArray(value)) return
|
||||
|
||||
@@ -102,6 +118,8 @@ function toSortedTagRecord(tagsByKey: Map<string, Set<string>>): Record<string,
|
||||
}
|
||||
|
||||
function isHiddenPropertyKey(key: string): boolean {
|
||||
const canonicalKey = canonicalSystemMetadataKey(key)
|
||||
if (canonicalKey === '_icon') return false
|
||||
return SKIP_KEYS.has(key.toLowerCase()) || isSystemMetadataKey(key)
|
||||
}
|
||||
|
||||
@@ -137,7 +155,7 @@ export function usePropertyPanelState(deps: PropertyPanelDeps) {
|
||||
const { availableTypes, customColorKey, typeColorKeys, typeIconKeys } = useMemo(() => deriveTypeInfo(entries, entryIsA), [entries, entryIsA])
|
||||
const vaultStatuses = useMemo(() => collectVaultStatuses(entries), [entries])
|
||||
const vaultTagsByKey = useMemo(() => collectAllVaultTags(entries), [entries])
|
||||
const propertyEntries = useMemo(() => Object.entries(frontmatter).filter(isVisibleProperty), [frontmatter])
|
||||
const propertyEntries = useMemo(() => buildVisiblePropertyEntries(frontmatter), [frontmatter])
|
||||
|
||||
const handleSaveValue = useCallback((key: string, newValue: string) => {
|
||||
setEditingKey(null)
|
||||
|
||||
@@ -24,11 +24,18 @@ if (typeof window !== 'undefined') {
|
||||
window.__mockHandlers = mockHandlers
|
||||
}
|
||||
|
||||
function resolveMockHandler(command: string) {
|
||||
if (typeof window !== 'undefined' && window.__mockHandlers?.[command]) {
|
||||
return window.__mockHandlers[command]
|
||||
}
|
||||
return mockHandlers[command]
|
||||
}
|
||||
|
||||
export async function mockInvoke<T>(cmd: string, args?: Record<string, unknown>): Promise<T> {
|
||||
const vaultResult = await tryVaultApi<T>(cmd, args)
|
||||
if (vaultResult !== undefined) return vaultResult
|
||||
|
||||
const handler = mockHandlers[cmd]
|
||||
const handler = resolveMockHandler(cmd)
|
||||
if (handler) {
|
||||
await new Promise((r) => setTimeout(r, 100))
|
||||
return handler(args) as T
|
||||
|
||||
@@ -103,11 +103,17 @@ let mockSettings: Settings = {
|
||||
default_ai_agent: 'claude_code',
|
||||
}
|
||||
|
||||
let mockLastVaultPath: string | null = null
|
||||
const DEFAULT_MOCK_VAULT_PATH = '/Users/mock/demo-vault-v2'
|
||||
const DEFAULT_MOCK_VAULT = {
|
||||
label: 'demo-vault-v2',
|
||||
path: DEFAULT_MOCK_VAULT_PATH,
|
||||
}
|
||||
|
||||
let mockLastVaultPath: string | null = DEFAULT_MOCK_VAULT_PATH
|
||||
|
||||
let mockVaultList: { vaults: Array<{ label: string; path: string }>; active_vault: string | null } = {
|
||||
vaults: [],
|
||||
active_vault: null,
|
||||
vaults: [DEFAULT_MOCK_VAULT],
|
||||
active_vault: DEFAULT_MOCK_VAULT_PATH,
|
||||
}
|
||||
|
||||
let mockVaultAiGuidanceStatus = {
|
||||
|
||||
61
src/mock-tauri/vault-api.test.ts
Normal file
61
src/mock-tauri/vault-api.test.ts
Normal file
@@ -0,0 +1,61 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
const originalFetch = globalThis.fetch
|
||||
|
||||
function jsonResponse(body: unknown, status = 200) {
|
||||
return new Response(JSON.stringify(body), {
|
||||
status,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
})
|
||||
}
|
||||
|
||||
describe('tryVaultApi', () => {
|
||||
afterEach(() => {
|
||||
vi.resetModules()
|
||||
vi.restoreAllMocks()
|
||||
globalThis.fetch = originalFetch
|
||||
})
|
||||
|
||||
it('retries vault API discovery after an unavailable response', async () => {
|
||||
let vaultApiOnline = false
|
||||
const fetchMock = vi.fn(async (input: string | URL) => {
|
||||
const url = String(input)
|
||||
if (url === '/api/vault/ping') {
|
||||
return jsonResponse({ ok: vaultApiOnline }, vaultApiOnline ? 200 : 503)
|
||||
}
|
||||
if (url === '/api/vault/list?path=%2Ffixture') {
|
||||
return jsonResponse([{ title: 'Alpha Project' }])
|
||||
}
|
||||
throw new Error(`Unexpected fetch: ${url}`)
|
||||
})
|
||||
globalThis.fetch = fetchMock as typeof fetch
|
||||
|
||||
const { tryVaultApi } = await import('./vault-api')
|
||||
|
||||
await expect(tryVaultApi('list_vault', { path: '/fixture' })).resolves.toBeUndefined()
|
||||
|
||||
vaultApiOnline = true
|
||||
|
||||
await expect(tryVaultApi('list_vault', { path: '/fixture' })).resolves.toEqual([{ title: 'Alpha Project' }])
|
||||
expect(fetchMock.mock.calls.filter(([url]) => String(url) === '/api/vault/ping')).toHaveLength(2)
|
||||
})
|
||||
|
||||
it('unwraps note content responses from the vault API', async () => {
|
||||
const fetchMock = vi.fn(async (input: string | URL) => {
|
||||
const url = String(input)
|
||||
if (url === '/api/vault/ping') {
|
||||
return jsonResponse({ ok: true })
|
||||
}
|
||||
if (url === '/api/vault/content?path=%2Ffixture%2Falpha.md') {
|
||||
return jsonResponse({ content: '# Alpha Project' })
|
||||
}
|
||||
throw new Error(`Unexpected fetch: ${url}`)
|
||||
})
|
||||
globalThis.fetch = fetchMock as typeof fetch
|
||||
|
||||
const { tryVaultApi } = await import('./vault-api')
|
||||
|
||||
await expect(tryVaultApi('get_note_content', { path: '/fixture/alpha.md' })).resolves.toBe('# Alpha Project')
|
||||
expect(fetchMock.mock.calls.filter(([url]) => String(url) === '/api/vault/ping')).toHaveLength(1)
|
||||
})
|
||||
})
|
||||
@@ -6,16 +6,22 @@
|
||||
|
||||
let vaultApiAvailable: boolean | null = null
|
||||
|
||||
async function checkVaultApi(): Promise<boolean> {
|
||||
if (vaultApiAvailable !== null) return vaultApiAvailable
|
||||
async function detectVaultApiAvailability(): Promise<boolean> {
|
||||
try {
|
||||
const res = await fetch('/api/vault/ping', { signal: AbortSignal.timeout(500) })
|
||||
vaultApiAvailable = res.ok
|
||||
return res.ok
|
||||
} catch {
|
||||
vaultApiAvailable = false
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
async function checkVaultApi(): Promise<boolean> {
|
||||
if (vaultApiAvailable === true) return true
|
||||
|
||||
const available = await detectVaultApiAvailability()
|
||||
vaultApiAvailable = available
|
||||
console.info(`[mock-tauri] Vault API available: ${vaultApiAvailable}`)
|
||||
return vaultApiAvailable
|
||||
return available
|
||||
}
|
||||
|
||||
interface VaultApiRequest {
|
||||
@@ -65,25 +71,38 @@ const VAULT_API_COMMANDS: Record<string, (args: Record<string, unknown>) => Vaul
|
||||
},
|
||||
}
|
||||
|
||||
export async function tryVaultApi<T>(cmd: string, args?: Record<string, unknown>): Promise<T | undefined> {
|
||||
const available = await checkVaultApi()
|
||||
if (!available) return undefined
|
||||
|
||||
function buildVaultApiRequest(cmd: string, args?: Record<string, unknown>) {
|
||||
if (!args) return null
|
||||
const requestBuilder = VAULT_API_COMMANDS[cmd]
|
||||
if (!requestBuilder || !args) return undefined
|
||||
return requestBuilder?.(args) ?? null
|
||||
}
|
||||
|
||||
const request = requestBuilder(args)
|
||||
function buildFetchOptions(request: VaultApiRequest): RequestInit {
|
||||
if (!request.body) {
|
||||
return { method: request.method || 'GET' }
|
||||
}
|
||||
|
||||
return {
|
||||
method: request.method || 'GET',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(request.body),
|
||||
}
|
||||
}
|
||||
|
||||
async function fetchVaultApiResponse(request: VaultApiRequest) {
|
||||
const res = await fetch(request.url, buildFetchOptions(request))
|
||||
if (!res.ok) return undefined
|
||||
return res.json()
|
||||
}
|
||||
|
||||
export async function tryVaultApi<T>(cmd: string, args?: Record<string, unknown>): Promise<T | undefined> {
|
||||
const request = buildVaultApiRequest(cmd, args)
|
||||
if (!request) return undefined
|
||||
if (!await checkVaultApi()) return undefined
|
||||
|
||||
try {
|
||||
const fetchOpts: RequestInit = { method: request.method || 'GET' }
|
||||
if (request.body) {
|
||||
fetchOpts.headers = { 'Content-Type': 'application/json' }
|
||||
fetchOpts.body = JSON.stringify(request.body)
|
||||
}
|
||||
const res = await fetch(request.url, fetchOpts)
|
||||
if (!res.ok) return undefined
|
||||
const data = await res.json()
|
||||
const data = await fetchVaultApiResponse(request)
|
||||
if (data === undefined) return undefined
|
||||
return (cmd === 'get_note_content' ? data.content : data) as T
|
||||
} catch (err) {
|
||||
console.warn(`[mock-tauri] Vault API call failed for ${cmd}, falling back to mock:`, err)
|
||||
|
||||
62
src/utils/editorLinkAutolink.test.ts
Normal file
62
src/utils/editorLinkAutolink.test.ts
Normal file
@@ -0,0 +1,62 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
looksLikeLocalFileReference,
|
||||
shouldStripAutoLinkedLocalFileMark,
|
||||
shouldAutoLinkTolariaHref,
|
||||
} from './editorLinkAutolink'
|
||||
|
||||
describe('looksLikeLocalFileReference', () => {
|
||||
it('treats bare filenames with file extensions as local file references', () => {
|
||||
expect(looksLikeLocalFileReference({ raw: 'AGENTS.md' })).toBe(true)
|
||||
expect(looksLikeLocalFileReference({ raw: 'README.txt' })).toBe(true)
|
||||
})
|
||||
|
||||
it('treats local path-like filenames as local file references', () => {
|
||||
expect(looksLikeLocalFileReference({ raw: 'docs/README.md' })).toBe(true)
|
||||
expect(looksLikeLocalFileReference({ raw: './docs/README.md' })).toBe(true)
|
||||
expect(looksLikeLocalFileReference({ raw: '/vault/README.md' })).toBe(true)
|
||||
})
|
||||
|
||||
it('does not classify domain-based urls as local file references', () => {
|
||||
expect(looksLikeLocalFileReference({ raw: 'https://example.com/README.md' })).toBe(false)
|
||||
expect(looksLikeLocalFileReference({ raw: 'example.com/README.md' })).toBe(false)
|
||||
expect(looksLikeLocalFileReference({ raw: 'www.example.com/README.md' })).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('shouldAutoLinkTolariaHref', () => {
|
||||
it('rejects plain filename-like text', () => {
|
||||
expect(shouldAutoLinkTolariaHref({ raw: 'AGENTS.md' })).toBe(false)
|
||||
expect(shouldAutoLinkTolariaHref({ raw: 'docs/README.md' })).toBe(false)
|
||||
})
|
||||
|
||||
it('keeps normal url-like values eligible for autolinking', () => {
|
||||
expect(shouldAutoLinkTolariaHref({ raw: 'https://example.com/docs' })).toBe(true)
|
||||
expect(shouldAutoLinkTolariaHref({ raw: 'example.com' })).toBe(true)
|
||||
expect(shouldAutoLinkTolariaHref({ raw: 'example.com/README.md' })).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('shouldStripAutoLinkedLocalFileMark', () => {
|
||||
it('strips accidental link marks that mirror local file text', () => {
|
||||
expect(shouldStripAutoLinkedLocalFileMark({
|
||||
href: { raw: 'https://AGENTS.md' },
|
||||
text: { raw: 'AGENTS.md' },
|
||||
})).toBe(true)
|
||||
expect(shouldStripAutoLinkedLocalFileMark({
|
||||
href: { raw: 'https://docs/README.md' },
|
||||
text: { raw: 'docs/README.md' },
|
||||
})).toBe(true)
|
||||
})
|
||||
|
||||
it('keeps intentional external links', () => {
|
||||
expect(shouldStripAutoLinkedLocalFileMark({
|
||||
href: { raw: 'https://example.com/docs' },
|
||||
text: { raw: 'Tolaria Docs' },
|
||||
})).toBe(false)
|
||||
expect(shouldStripAutoLinkedLocalFileMark({
|
||||
href: { raw: 'https://example.com/agents' },
|
||||
text: { raw: 'AGENTS.md' },
|
||||
})).toBe(false)
|
||||
})
|
||||
})
|
||||
143
src/utils/editorLinkAutolink.ts
Normal file
143
src/utils/editorLinkAutolink.ts
Normal file
@@ -0,0 +1,143 @@
|
||||
const FILE_LIKE_EXTENSION_PATTERN =
|
||||
/\.(?:md|markdown|txt|ya?ml|json|toml|csv|tsv|pdf|png|jpe?g|gif|svg|webp|avif|mp3|wav|ogg|mp4|mov|zip|tar|gz|tsx?|jsx?|cjs|mjs|rs|py|sh|css|html?)$/i
|
||||
|
||||
const EXPLICIT_PROTOCOL_PATTERN = /^[a-z][a-z0-9+.-]*:\/\//i
|
||||
const MAYBE_PROTOCOL_PATTERN = /^[a-z][a-z0-9+.-]*:/i
|
||||
const LOCAL_PATH_PREFIX_PATTERN = /^(?:\.{1,2}\/|~\/|\/)/
|
||||
const IPV4_HOST_PATTERN = /^\d{1,3}(\.\d{1,3}){3}$/
|
||||
const WINDOWS_PATH_SEPARATOR = '\\'
|
||||
const WWW_PREFIX = 'www.'
|
||||
|
||||
export type LinkValue = {
|
||||
raw: string
|
||||
}
|
||||
|
||||
export type LinkMarkCandidate = {
|
||||
href: LinkValue
|
||||
text: LinkValue
|
||||
}
|
||||
|
||||
function withRaw(raw: string): LinkValue {
|
||||
return { raw }
|
||||
}
|
||||
|
||||
function stripUrlDecorators(value: LinkValue) {
|
||||
return withRaw(value.raw.split(/[?#]/, 1)[0] ?? value.raw)
|
||||
}
|
||||
|
||||
function stripProtocol(value: LinkValue) {
|
||||
return withRaw(value.raw.replace(/^[a-z][a-z0-9+.-]*:\/\//i, ''))
|
||||
}
|
||||
|
||||
function isExplicitProtocolUrl(value: LinkValue) {
|
||||
return EXPLICIT_PROTOCOL_PATTERN.test(value.raw)
|
||||
}
|
||||
|
||||
function isMaybeProtocolUrl(value: LinkValue) {
|
||||
return MAYBE_PROTOCOL_PATTERN.test(value.raw)
|
||||
}
|
||||
|
||||
function hasWindowsPathSeparator(value: LinkValue) {
|
||||
return value.raw.includes(WINDOWS_PATH_SEPARATOR)
|
||||
}
|
||||
|
||||
function hasPathSeparator(value: LinkValue) {
|
||||
return value.raw.includes('/')
|
||||
}
|
||||
|
||||
function startsWithWebHostPrefix(value: LinkValue) {
|
||||
return value.raw.startsWith(WWW_PREFIX)
|
||||
}
|
||||
|
||||
function firstPathSegment(value: LinkValue) {
|
||||
return value.raw.split('/', 1)[0] ?? value.raw
|
||||
}
|
||||
|
||||
function isDomainLikePath(value: LinkValue) {
|
||||
return firstPathSegment(value).includes('.')
|
||||
}
|
||||
|
||||
function hostnameFromUrlLikeValue(value: LinkValue) {
|
||||
const withoutUserinfo = value.raw.includes('@') ? value.raw.split('@').pop() ?? value.raw : value.raw
|
||||
return withoutUserinfo.split(/[/?#:]/, 1)[0] ?? withoutUserinfo
|
||||
}
|
||||
|
||||
function isExplicitWebUrl(value: LinkValue) {
|
||||
return isExplicitProtocolUrl(value) || startsWithWebHostPrefix(value)
|
||||
}
|
||||
|
||||
function isSingleSegmentValue(value: LinkValue) {
|
||||
return !hasPathSeparator(value)
|
||||
}
|
||||
|
||||
function isLocalPathPrefix(value: LinkValue) {
|
||||
return LOCAL_PATH_PREFIX_PATTERN.test(value.raw)
|
||||
}
|
||||
|
||||
function isPathLikeFileReference(value: LinkValue) {
|
||||
return hasPathSeparator(value) && !isDomainLikePath(value)
|
||||
}
|
||||
|
||||
function hasBareProtocolPrefix(value: LinkValue) {
|
||||
return isMaybeProtocolUrl(value) && !value.raw.includes('@')
|
||||
}
|
||||
|
||||
function hostnameHasTld(hostname: string) {
|
||||
return hostname.includes('.')
|
||||
}
|
||||
|
||||
function normalizeInput(value: LinkValue) {
|
||||
return stripUrlDecorators(withRaw(value.raw.trim()))
|
||||
}
|
||||
|
||||
export function looksLikeLocalFileReference(value: LinkValue) {
|
||||
const normalized = normalizeInput(value)
|
||||
if (!normalized.raw) return false
|
||||
|
||||
if (isLocalPathPrefix(normalized) || hasWindowsPathSeparator(normalized)) {
|
||||
return true
|
||||
}
|
||||
|
||||
if (!FILE_LIKE_EXTENSION_PATTERN.test(normalized.raw)) {
|
||||
return false
|
||||
}
|
||||
|
||||
if (isExplicitWebUrl(normalized)) {
|
||||
return false
|
||||
}
|
||||
|
||||
if (isSingleSegmentValue(normalized)) {
|
||||
return true
|
||||
}
|
||||
|
||||
return isPathLikeFileReference(normalized)
|
||||
}
|
||||
|
||||
export function shouldAutoLinkTolariaHref(url: LinkValue) {
|
||||
if (looksLikeLocalFileReference(url)) {
|
||||
return false
|
||||
}
|
||||
|
||||
if (isExplicitProtocolUrl(url) || hasBareProtocolPrefix(url)) {
|
||||
return true
|
||||
}
|
||||
|
||||
const hostname = hostnameFromUrlLikeValue(url)
|
||||
if (IPV4_HOST_PATTERN.test(hostname)) {
|
||||
return false
|
||||
}
|
||||
|
||||
return hostnameHasTld(hostname)
|
||||
}
|
||||
|
||||
export function shouldStripAutoLinkedLocalFileMark(mark: LinkMarkCandidate) {
|
||||
const normalizedText = normalizeInput(mark.text)
|
||||
if (!looksLikeLocalFileReference(normalizedText)) {
|
||||
return false
|
||||
}
|
||||
|
||||
const normalizedHref = stripUrlDecorators(
|
||||
stripProtocol(normalizeInput(mark.href)),
|
||||
)
|
||||
return normalizedHref.raw === normalizedText.raw
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
export function humanizePropertyKey(key: string): string {
|
||||
const spaced = key.replace(/[_-]/g, ' ')
|
||||
const normalized = key.replace(/^_+/, '')
|
||||
const spaced = normalized.replace(/[_-]/g, ' ')
|
||||
if (!spaced) return spaced
|
||||
return spaced.charAt(0).toUpperCase() + spaced.slice(1)
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ import { getAppStorageItem } from '../constants/appStorage'
|
||||
import { isValidCssColor, isColorKeyName } from './colorUtils'
|
||||
import { updateVaultConfigField } from './vaultConfigStore'
|
||||
import { CalendarIcon, Type, ToggleLeft, Circle, Link, Tag, Palette } from 'lucide-react'
|
||||
import { canonicalSystemMetadataKey } from './systemMetadata'
|
||||
|
||||
export type PropertyDisplayMode = 'text' | 'date' | 'boolean' | 'status' | 'url' | 'tags' | 'color'
|
||||
|
||||
@@ -20,7 +21,7 @@ const DATE_KEY_PATTERNS = ['date', 'deadline', 'due', 'start', 'end', 'scheduled
|
||||
const TAGS_KEY_PATTERNS = ['tags', 'keywords', 'categories', 'labels']
|
||||
|
||||
function isIconKey(key: string): boolean {
|
||||
return key.toLowerCase() === 'icon'
|
||||
return canonicalSystemMetadataKey(key) === '_icon'
|
||||
}
|
||||
|
||||
function keyMatchesPatterns(key: string, patterns: string[]): boolean {
|
||||
|
||||
@@ -2,20 +2,40 @@ import { expect, type Page } from '@playwright/test'
|
||||
import fs from 'fs'
|
||||
import os from 'os'
|
||||
import path from 'path'
|
||||
import { installFixtureVaultDesktopBridgeInBrowser } from './fixtureVaultDesktopBridge'
|
||||
|
||||
const FIXTURE_VAULT = path.resolve('tests/fixtures/test-vault')
|
||||
const FIXTURE_VAULT_READY_TIMEOUT = 30_000
|
||||
const FIXTURE_VAULT_REMOVE_RETRIES = 10
|
||||
const FIXTURE_VAULT_REMOVE_RETRY_DELAY_MS = 100
|
||||
const CLAUDE_CODE_ONBOARDING_DISMISSED_KEY = 'tolaria:claude-code-onboarding-dismissed'
|
||||
type FixtureCommandArgs = Record<string, unknown> | undefined
|
||||
|
||||
function copyDirSync(src: string, dest: string): void {
|
||||
interface FixtureVaultPageArgs {
|
||||
page: Page
|
||||
vaultPath: string
|
||||
}
|
||||
|
||||
interface FixturePageArgs {
|
||||
page: Page
|
||||
}
|
||||
|
||||
interface CopyDirArgs {
|
||||
src: string
|
||||
dest: string
|
||||
}
|
||||
|
||||
interface RemoveFixtureVaultArgs {
|
||||
tempVaultDir: string
|
||||
}
|
||||
|
||||
function copyDirSync({ src, dest }: CopyDirArgs): void {
|
||||
fs.mkdirSync(dest, { recursive: true })
|
||||
for (const item of fs.readdirSync(src, { withFileTypes: true })) {
|
||||
const sourcePath = path.join(src, item.name)
|
||||
const destinationPath = path.join(dest, item.name)
|
||||
if (item.isDirectory()) {
|
||||
copyDirSync(sourcePath, destinationPath)
|
||||
copyDirSync({ src: sourcePath, dest: destinationPath })
|
||||
continue
|
||||
}
|
||||
fs.copyFileSync(sourcePath, destinationPath)
|
||||
@@ -24,12 +44,11 @@ function copyDirSync(src: string, dest: string): void {
|
||||
|
||||
export function createFixtureVaultCopy(): string {
|
||||
const tempVaultDir = fs.mkdtempSync(path.join(os.tmpdir(), 'laputa-test-vault-'))
|
||||
copyDirSync(FIXTURE_VAULT, tempVaultDir)
|
||||
copyDirSync({ src: FIXTURE_VAULT, dest: tempVaultDir })
|
||||
return tempVaultDir
|
||||
}
|
||||
|
||||
export function removeFixtureVaultCopy(tempVaultDir: string | null | undefined): void {
|
||||
if (!tempVaultDir) return
|
||||
function removeFixtureVaultDirectory({ tempVaultDir }: RemoveFixtureVaultArgs): void {
|
||||
fs.rmSync(tempVaultDir, {
|
||||
recursive: true,
|
||||
force: true,
|
||||
@@ -38,15 +57,21 @@ export function removeFixtureVaultCopy(tempVaultDir: string | null | undefined):
|
||||
})
|
||||
}
|
||||
|
||||
export async function openFixtureVault(
|
||||
page: Page,
|
||||
vaultPath: string,
|
||||
): Promise<void> {
|
||||
export function removeFixtureVaultCopy(tempVaultDir: string | null | undefined): void {
|
||||
if (!tempVaultDir) return
|
||||
removeFixtureVaultDirectory({ tempVaultDir })
|
||||
}
|
||||
|
||||
async function installFixtureVaultInitScript({ page, vaultPath }: FixtureVaultPageArgs): Promise<void> {
|
||||
await page.addInitScript(({ dismissedKey, resolvedVaultPath }: { dismissedKey: string; resolvedVaultPath: string }) => {
|
||||
localStorage.clear()
|
||||
localStorage.setItem(dismissedKey, '1')
|
||||
|
||||
const jsonHeaders = { 'Content-Type': 'application/json' }
|
||||
const FRONTMATTER_OPEN = '---\n'
|
||||
const FRONTMATTER_CLOSE = '\n---\n'
|
||||
const nativeFetch = window.fetch.bind(window)
|
||||
|
||||
window.fetch = (input: RequestInfo | URL, init?: RequestInit) => {
|
||||
const requestUrl = typeof input === 'string'
|
||||
? input
|
||||
@@ -64,85 +89,21 @@ export async function openFixtureVault(
|
||||
return nativeFetch(input, init)
|
||||
}
|
||||
|
||||
const applyFixtureVaultOverrides = (
|
||||
handlers: Record<string, ((args?: unknown) => unknown)> | null | undefined,
|
||||
) => {
|
||||
if (!handlers) return handlers
|
||||
handlers.load_vault_list = () => ({
|
||||
vaults: [{ label: 'Test Vault', path: resolvedVaultPath }],
|
||||
active_vault: resolvedVaultPath,
|
||||
hidden_defaults: [],
|
||||
})
|
||||
handlers.check_vault_exists = () => true
|
||||
handlers.get_last_vault_path = () => resolvedVaultPath
|
||||
handlers.get_default_vault_path = () => resolvedVaultPath
|
||||
handlers.save_vault_list = () => null
|
||||
return handlers
|
||||
const readJson = async (url: string, init?: RequestInit) => {
|
||||
const response = await nativeFetch(url, init)
|
||||
if (!response.ok) {
|
||||
let message = `HTTP ${response.status}`
|
||||
try {
|
||||
const body = await response.json() as { error?: string }
|
||||
message = body.error ?? message
|
||||
} catch {
|
||||
// Preserve the HTTP status fallback when the body is not JSON.
|
||||
}
|
||||
throw new Error(message)
|
||||
}
|
||||
return response.json()
|
||||
}
|
||||
|
||||
let ref = applyFixtureVaultOverrides(
|
||||
(window.__mockHandlers as Record<string, ((args?: unknown) => unknown)> | undefined),
|
||||
) ?? null
|
||||
|
||||
Object.defineProperty(window, '__mockHandlers', {
|
||||
configurable: true,
|
||||
set(value) {
|
||||
ref = applyFixtureVaultOverrides(
|
||||
value as Record<string, ((args?: unknown) => unknown)> | undefined,
|
||||
) ?? null
|
||||
},
|
||||
get() {
|
||||
return applyFixtureVaultOverrides(ref) ?? ref
|
||||
},
|
||||
})
|
||||
}, { dismissedKey: CLAUDE_CODE_ONBOARDING_DISMISSED_KEY, resolvedVaultPath: vaultPath })
|
||||
|
||||
await page.goto('/', { waitUntil: 'domcontentloaded' })
|
||||
await page.waitForFunction(() => Boolean(window.__mockHandlers))
|
||||
await page.evaluate((resolvedVaultPath: string) => {
|
||||
const handlers = window.__mockHandlers
|
||||
if (!handlers) {
|
||||
throw new Error('Mock handlers unavailable for fixture vault override')
|
||||
}
|
||||
|
||||
handlers.load_vault_list = () => ({
|
||||
vaults: [{ label: 'Test Vault', path: resolvedVaultPath }],
|
||||
active_vault: resolvedVaultPath,
|
||||
hidden_defaults: [],
|
||||
})
|
||||
handlers.check_vault_exists = () => true
|
||||
handlers.get_last_vault_path = () => resolvedVaultPath
|
||||
handlers.get_default_vault_path = () => resolvedVaultPath
|
||||
handlers.save_vault_list = () => null
|
||||
}, vaultPath)
|
||||
await page.reload({ waitUntil: 'domcontentloaded' })
|
||||
await page.locator('[data-testid="note-list-container"]').waitFor({ timeout: FIXTURE_VAULT_READY_TIMEOUT })
|
||||
await expect(page.getByText('Alpha Project', { exact: true }).first()).toBeVisible({
|
||||
timeout: FIXTURE_VAULT_READY_TIMEOUT,
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Browser harness for desktop command-routing tests.
|
||||
*
|
||||
* This stubs the Tauri invoke bridge inside Playwright so tests can exercise
|
||||
* renderer shortcut dispatch and desktop menu-command dispatch without a native
|
||||
* shell. It is deterministic, but it is not a substitute for real native QA.
|
||||
*/
|
||||
export async function openFixtureVaultDesktopHarness(
|
||||
page: Page,
|
||||
vaultPath: string,
|
||||
): Promise<void> {
|
||||
await openFixtureVault(page, vaultPath)
|
||||
await page.evaluate((resolvedVaultPath: string) => {
|
||||
const jsonHeaders = { 'Content-Type': 'application/json' }
|
||||
const nativeFetch = window.fetch.bind(window)
|
||||
|
||||
const FRONTMATTER_OPEN = '---\n'
|
||||
const FRONTMATTER_CLOSE = '\n---\n'
|
||||
|
||||
const escapeRegExp = (value: string) => value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
|
||||
|
||||
const splitFrontmatter = (content: string) => {
|
||||
if (!content.startsWith(FRONTMATTER_OPEN)) {
|
||||
return { frontmatter: null as string | null, body: content }
|
||||
@@ -206,16 +167,12 @@ export async function openFixtureVaultDesktopHarness(
|
||||
return `${FRONTMATTER_OPEN}${nextEntryLines.join('\n')}${FRONTMATTER_CLOSE}${body}`
|
||||
}
|
||||
|
||||
const entries = splitFrontmatterEntries(frontmatter).filter((entry) => entry.key !== '')
|
||||
const keyPattern = new RegExp(`^${escapeRegExp(key)}$`)
|
||||
let replaced = false
|
||||
const nextEntries = entries.map((entry) => {
|
||||
if (!keyPattern.test(entry.key)) return entry
|
||||
replaced = true
|
||||
return { key, lines: nextEntryLines }
|
||||
})
|
||||
const nextEntries = splitFrontmatterEntries(frontmatter)
|
||||
.filter((entry) => entry.key !== '')
|
||||
.map((entry) => (entry.key === key ? { key, lines: nextEntryLines } : entry))
|
||||
|
||||
if (!replaced) {
|
||||
const hasEntry = nextEntries.some((entry) => entry.key === key)
|
||||
if (!hasEntry) {
|
||||
nextEntries.push({ key, lines: nextEntryLines })
|
||||
}
|
||||
|
||||
@@ -226,9 +183,8 @@ export async function openFixtureVaultDesktopHarness(
|
||||
const { frontmatter, body } = splitFrontmatter(content)
|
||||
if (frontmatter === null) return content
|
||||
|
||||
const keyPattern = new RegExp(`^${escapeRegExp(key)}$`)
|
||||
const nextEntries = splitFrontmatterEntries(frontmatter)
|
||||
.filter((entry) => entry.key !== '' && !keyPattern.test(entry.key))
|
||||
.filter((entry) => entry.key !== '' && entry.key !== key)
|
||||
|
||||
if (nextEntries.length === 0) {
|
||||
return body
|
||||
@@ -237,32 +193,19 @@ export async function openFixtureVaultDesktopHarness(
|
||||
return `${FRONTMATTER_OPEN}${nextEntries.flatMap((entry) => entry.lines).join('\n')}${FRONTMATTER_CLOSE}${body}`
|
||||
}
|
||||
|
||||
const persistFrontmatterChange = async (path: string, transform: (content: string) => string) => {
|
||||
const current = await readJson(`/api/vault/content?path=${encodeURIComponent(path)}`) as { content: string }
|
||||
const persistFrontmatterChange = async (notePath: string, transform: (content: string) => string) => {
|
||||
const current = await readJson(
|
||||
`/api/vault/content?path=${encodeURIComponent(notePath)}`,
|
||||
) as { content: string }
|
||||
const updatedContent = transform(current.content)
|
||||
await readJson('/api/vault/save', {
|
||||
method: 'POST',
|
||||
headers: jsonHeaders,
|
||||
body: JSON.stringify({ path, content: updatedContent }),
|
||||
body: JSON.stringify({ path: notePath, content: updatedContent }),
|
||||
})
|
||||
return updatedContent
|
||||
}
|
||||
|
||||
const readJson = async (url: string, init?: RequestInit) => {
|
||||
const response = await nativeFetch(url, init)
|
||||
if (!response.ok) {
|
||||
let message = `HTTP ${response.status}`
|
||||
try {
|
||||
const body = await response.json() as { error?: string }
|
||||
message = body.error ?? message
|
||||
} catch {
|
||||
// Keep the HTTP status fallback when the body is not JSON.
|
||||
}
|
||||
throw new Error(message)
|
||||
}
|
||||
return response.json()
|
||||
}
|
||||
|
||||
const activeVaultList = {
|
||||
vaults: [{ label: 'Test Vault', path: resolvedVaultPath }],
|
||||
active_vault: resolvedVaultPath,
|
||||
@@ -283,16 +226,16 @@ export async function openFixtureVaultDesktopHarness(
|
||||
body: JSON.stringify(payload),
|
||||
})
|
||||
|
||||
const commandHandlers: Record<string, (commandArgs?: Record<string, unknown>) => Promise<unknown> | unknown> = {
|
||||
trigger_menu_command: (commandArgs) => {
|
||||
const commandId = String(commandArgs?.id ?? '')
|
||||
const bridge = window.__laputaTest?.dispatchBrowserMenuCommand
|
||||
if (!bridge) throw new Error('Tolaria test bridge is missing dispatchBrowserMenuCommand')
|
||||
bridge(commandId)
|
||||
return null
|
||||
},
|
||||
const readCommandValue = (commandArgs: FixtureCommandArgs, key: string, fallback?: unknown) =>
|
||||
commandArgs?.[key] ?? fallback
|
||||
|
||||
const readCommandString = (commandArgs: FixtureCommandArgs, key: string, fallback = '') =>
|
||||
String(readCommandValue(commandArgs, key, fallback))
|
||||
|
||||
const buildFixtureStateHandlers = () => ({
|
||||
load_vault_list: () => activeVaultList,
|
||||
check_vault_exists: () => true,
|
||||
check_vault_exists: (commandArgs?: FixtureCommandArgs) =>
|
||||
readCommandString(commandArgs, 'path') === resolvedVaultPath,
|
||||
is_git_repo: () => true,
|
||||
get_last_vault_path: () => resolvedVaultPath,
|
||||
get_default_vault_path: () => resolvedVaultPath,
|
||||
@@ -309,97 +252,164 @@ export async function openFixtureVaultDesktopHarness(
|
||||
anonymous_id: null,
|
||||
release_channel: null,
|
||||
}),
|
||||
list_vault: (commandArgs) => readVaultList(commandArgs),
|
||||
reload_vault: (commandArgs) => readVaultList(commandArgs, true),
|
||||
})
|
||||
|
||||
const buildFixtureReadHandlers = () => ({
|
||||
list_vault: (commandArgs?: FixtureCommandArgs) => readVaultList(commandArgs),
|
||||
reload_vault: (commandArgs?: FixtureCommandArgs) => readVaultList(commandArgs, true),
|
||||
list_vault_folders: () => [],
|
||||
list_views: () => [],
|
||||
get_modified_files: () => [],
|
||||
detect_renames: () => [],
|
||||
reload_vault_entry: (commandArgs) =>
|
||||
readJson(`/api/vault/entry?path=${encodeURIComponent(String(commandArgs?.path ?? ''))}`),
|
||||
get_note_content: async (commandArgs) => {
|
||||
reload_vault_entry: (commandArgs?: FixtureCommandArgs) =>
|
||||
readJson(`/api/vault/entry?path=${encodeURIComponent(readCommandString(commandArgs, 'path'))}`),
|
||||
get_note_content: async (commandArgs?: FixtureCommandArgs) => {
|
||||
const data = await readJson(
|
||||
`/api/vault/content?path=${encodeURIComponent(String(commandArgs?.path ?? ''))}`,
|
||||
`/api/vault/content?path=${encodeURIComponent(readCommandString(commandArgs, 'path'))}`,
|
||||
) as { content: string }
|
||||
return data.content
|
||||
},
|
||||
get_all_content: (commandArgs) =>
|
||||
get_all_content: (commandArgs?: FixtureCommandArgs) =>
|
||||
readJson(
|
||||
`/api/vault/all-content?path=${encodeURIComponent(String(commandArgs?.path ?? resolvedVaultPath))}`,
|
||||
`/api/vault/all-content?path=${encodeURIComponent(readCommandString(commandArgs, 'path', resolvedVaultPath))}`,
|
||||
),
|
||||
save_note_content: (commandArgs) =>
|
||||
readJson('/api/vault/save', {
|
||||
method: 'POST',
|
||||
headers: jsonHeaders,
|
||||
body: JSON.stringify({ path: commandArgs?.path, content: commandArgs?.content }),
|
||||
}),
|
||||
update_frontmatter: (commandArgs) =>
|
||||
persistFrontmatterChange(
|
||||
String(commandArgs?.path ?? ''),
|
||||
(content) => replaceFrontmatterEntry(content, String(commandArgs?.key ?? ''), commandArgs?.value),
|
||||
),
|
||||
delete_frontmatter_property: (commandArgs) =>
|
||||
persistFrontmatterChange(
|
||||
String(commandArgs?.path ?? ''),
|
||||
(content) => removeFrontmatterEntry(content, String(commandArgs?.key ?? '')),
|
||||
),
|
||||
rename_note: (commandArgs) =>
|
||||
renameNoteRequest({
|
||||
vault_path: commandArgs?.vaultPath ?? resolvedVaultPath,
|
||||
old_path: commandArgs?.oldPath,
|
||||
new_title: commandArgs?.newTitle,
|
||||
old_title: commandArgs?.oldTitle ?? null,
|
||||
}),
|
||||
rename_note_filename: (commandArgs) =>
|
||||
readJson('/api/vault/rename-filename', {
|
||||
method: 'POST',
|
||||
headers: jsonHeaders,
|
||||
body: JSON.stringify({
|
||||
vault_path: commandArgs?.vaultPath ?? resolvedVaultPath,
|
||||
old_path: commandArgs?.oldPath,
|
||||
new_filename_stem: commandArgs?.newFilenameStem,
|
||||
}),
|
||||
}),
|
||||
search_vault: (commandArgs) => {
|
||||
const resolvedPath = String(commandArgs?.path ?? commandArgs?.vaultPath ?? resolvedVaultPath)
|
||||
const query = encodeURIComponent(String(commandArgs?.query ?? ''))
|
||||
const mode = encodeURIComponent(String(commandArgs?.mode ?? 'all'))
|
||||
search_vault: (commandArgs?: FixtureCommandArgs) => {
|
||||
const resolvedPath = readCommandString(
|
||||
commandArgs,
|
||||
'path',
|
||||
readCommandValue(commandArgs, 'vaultPath', resolvedVaultPath),
|
||||
)
|
||||
const query = encodeURIComponent(readCommandString(commandArgs, 'query'))
|
||||
const mode = encodeURIComponent(readCommandString(commandArgs, 'mode', 'all'))
|
||||
return readJson(
|
||||
`/api/vault/search?vault_path=${encodeURIComponent(resolvedPath)}&query=${query}&mode=${mode}`,
|
||||
)
|
||||
},
|
||||
auto_rename_untitled: async (commandArgs) => {
|
||||
const notePath = String(commandArgs?.notePath ?? '')
|
||||
})
|
||||
|
||||
const buildFixtureWriteHandlers = () => ({
|
||||
save_note_content: (commandArgs?: FixtureCommandArgs) =>
|
||||
readJson('/api/vault/save', {
|
||||
method: 'POST',
|
||||
headers: jsonHeaders,
|
||||
body: JSON.stringify({
|
||||
path: readCommandValue(commandArgs, 'path'),
|
||||
content: readCommandValue(commandArgs, 'content'),
|
||||
}),
|
||||
}),
|
||||
update_frontmatter: (commandArgs?: FixtureCommandArgs) =>
|
||||
persistFrontmatterChange(
|
||||
readCommandString(commandArgs, 'path'),
|
||||
(content) => replaceFrontmatterEntry(
|
||||
content,
|
||||
readCommandString(commandArgs, 'key'),
|
||||
readCommandValue(commandArgs, 'value'),
|
||||
),
|
||||
),
|
||||
delete_frontmatter_property: (commandArgs?: FixtureCommandArgs) =>
|
||||
persistFrontmatterChange(
|
||||
readCommandString(commandArgs, 'path'),
|
||||
(content) => removeFrontmatterEntry(content, readCommandString(commandArgs, 'key')),
|
||||
),
|
||||
rename_note: (commandArgs?: FixtureCommandArgs) =>
|
||||
renameNoteRequest({
|
||||
vault_path: readCommandValue(commandArgs, 'vaultPath', resolvedVaultPath),
|
||||
old_path: readCommandValue(commandArgs, 'oldPath'),
|
||||
new_title: readCommandValue(commandArgs, 'newTitle'),
|
||||
old_title: readCommandValue(commandArgs, 'oldTitle', null),
|
||||
}),
|
||||
rename_note_filename: (commandArgs?: FixtureCommandArgs) =>
|
||||
readJson('/api/vault/rename-filename', {
|
||||
method: 'POST',
|
||||
headers: jsonHeaders,
|
||||
body: JSON.stringify({
|
||||
vault_path: readCommandValue(commandArgs, 'vaultPath', resolvedVaultPath),
|
||||
old_path: readCommandValue(commandArgs, 'oldPath'),
|
||||
new_filename_stem: readCommandValue(commandArgs, 'newFilenameStem'),
|
||||
}),
|
||||
}),
|
||||
auto_rename_untitled: async (commandArgs?: FixtureCommandArgs) => {
|
||||
const notePath = readCommandString(commandArgs, 'notePath')
|
||||
const contentData = await readJson(
|
||||
`/api/vault/content?path=${encodeURIComponent(notePath)}`,
|
||||
) as { content: string }
|
||||
const match = contentData.content.match(/^#\s+(.+)$/m)
|
||||
if (!match) return null
|
||||
return renameNoteRequest({
|
||||
vault_path: commandArgs?.vaultPath ?? resolvedVaultPath,
|
||||
vault_path: readCommandValue(commandArgs, 'vaultPath', resolvedVaultPath),
|
||||
old_path: notePath,
|
||||
new_title: match[1].trim(),
|
||||
})
|
||||
},
|
||||
})
|
||||
|
||||
const applyFixtureVaultOverrides = (
|
||||
handlers: Record<string, ((args?: unknown) => unknown)> | null | undefined,
|
||||
) => {
|
||||
if (!handlers) return handlers
|
||||
Object.assign(
|
||||
handlers,
|
||||
buildFixtureStateHandlers(),
|
||||
buildFixtureReadHandlers(),
|
||||
buildFixtureWriteHandlers(),
|
||||
)
|
||||
return handlers
|
||||
}
|
||||
|
||||
const invoke = async (command: string, args?: Record<string, unknown>) => {
|
||||
const handler = commandHandlers[command] ?? window.__mockHandlers?.[command]
|
||||
if (!handler) throw new Error(`Unhandled invoke: ${command}`)
|
||||
return handler(args)
|
||||
}
|
||||
let ref = applyFixtureVaultOverrides(
|
||||
(window.__mockHandlers as Record<string, ((args?: unknown) => unknown)> | undefined),
|
||||
) ?? null
|
||||
|
||||
Object.defineProperty(window, '__TAURI__', {
|
||||
Object.defineProperty(window, '__mockHandlers', {
|
||||
configurable: true,
|
||||
value: {},
|
||||
set(value) {
|
||||
ref = applyFixtureVaultOverrides(
|
||||
value as Record<string, ((args?: unknown) => unknown)> | undefined,
|
||||
) ?? null
|
||||
},
|
||||
get() {
|
||||
return applyFixtureVaultOverrides(ref) ?? ref
|
||||
},
|
||||
})
|
||||
Object.defineProperty(window, '__TAURI_INTERNALS__', {
|
||||
configurable: true,
|
||||
value: { invoke },
|
||||
})
|
||||
}, vaultPath)
|
||||
}, { dismissedKey: CLAUDE_CODE_ONBOARDING_DISMISSED_KEY, resolvedVaultPath: vaultPath })
|
||||
}
|
||||
|
||||
async function waitForFixtureVaultReady({ page }: FixturePageArgs): Promise<void> {
|
||||
await page.goto('/', { waitUntil: 'domcontentloaded' })
|
||||
await page.waitForFunction(() => Boolean(window.__mockHandlers?.list_vault))
|
||||
await page.locator('[data-testid="note-list-container"]').waitFor({ timeout: FIXTURE_VAULT_READY_TIMEOUT })
|
||||
await expect(page.getByText('Alpha Project', { exact: true }).first()).toBeVisible({
|
||||
timeout: FIXTURE_VAULT_READY_TIMEOUT,
|
||||
})
|
||||
}
|
||||
|
||||
export async function openFixtureVault(
|
||||
page: Page,
|
||||
vaultPath: string,
|
||||
): Promise<void> {
|
||||
await installFixtureVaultInitScript({ page, vaultPath })
|
||||
await waitForFixtureVaultReady({ page })
|
||||
}
|
||||
|
||||
async function installFixtureVaultDesktopBridge({ page }: FixturePageArgs): Promise<void> {
|
||||
await page.evaluate(installFixtureVaultDesktopBridgeInBrowser)
|
||||
|
||||
await page.waitForFunction(() => Boolean(window.__TAURI_INTERNALS__))
|
||||
}
|
||||
|
||||
/**
|
||||
* Browser harness for desktop command-routing tests.
|
||||
*
|
||||
* This stubs the Tauri invoke bridge inside Playwright so tests can exercise
|
||||
* renderer shortcut dispatch and desktop menu-command dispatch without a native
|
||||
* shell. It is deterministic, but it is not a substitute for real native QA.
|
||||
*/
|
||||
export async function openFixtureVaultDesktopHarness(
|
||||
page: Page,
|
||||
vaultPath: string,
|
||||
): Promise<void> {
|
||||
await openFixtureVault(page, vaultPath)
|
||||
await installFixtureVaultDesktopBridge({ page })
|
||||
}
|
||||
|
||||
export const openFixtureVaultTauri = openFixtureVaultDesktopHarness
|
||||
|
||||
27
tests/helpers/fixtureVaultDesktopBridge.ts
Normal file
27
tests/helpers/fixtureVaultDesktopBridge.ts
Normal file
@@ -0,0 +1,27 @@
|
||||
export function installFixtureVaultDesktopBridgeInBrowser(): void {
|
||||
const dispatchBrowserMenuCommand =
|
||||
window.__laputaTest?.dispatchBrowserMenuCommand
|
||||
?? (() => { throw new Error('Tolaria test bridge is missing dispatchBrowserMenuCommand') })
|
||||
|
||||
const specialHandlers: Record<string, (args?: Record<string, unknown>) => unknown> = {
|
||||
trigger_menu_command: (args) => {
|
||||
dispatchBrowserMenuCommand(String(args?.id ?? ''))
|
||||
return null
|
||||
},
|
||||
}
|
||||
|
||||
const invoke = (command: string, args?: Record<string, unknown>) => {
|
||||
const handler = specialHandlers[command] ?? window.__mockHandlers?.[command]
|
||||
if (!handler) throw new Error(`Unhandled invoke: ${command}`)
|
||||
return handler(args)
|
||||
}
|
||||
|
||||
Object.defineProperty(window, '__TAURI__', {
|
||||
configurable: true,
|
||||
value: {},
|
||||
})
|
||||
Object.defineProperty(window, '__TAURI_INTERNALS__', {
|
||||
configurable: true,
|
||||
value: { invoke },
|
||||
})
|
||||
}
|
||||
@@ -66,6 +66,8 @@ async function expectZoomedHandleClickToWork(
|
||||
|
||||
const menu = page.locator('.mantine-Menu-dropdown').filter({ has: page.locator('.mantine-Menu-item') }).first()
|
||||
await expect(menu).toBeVisible({ timeout: 5_000 })
|
||||
await expect(menu.getByRole('menuitem', { name: 'Delete' })).toBeVisible()
|
||||
await expect(menu.getByRole('menuitem', { name: 'Colors' })).toHaveCount(0)
|
||||
await page.keyboard.press('Escape')
|
||||
await expect(menu).toBeHidden({ timeout: 5_000 })
|
||||
}
|
||||
|
||||
187
tests/smoke/editor-mode-modified-ordering.spec.ts
Normal file
187
tests/smoke/editor-mode-modified-ordering.spec.ts
Normal file
@@ -0,0 +1,187 @@
|
||||
import fs from 'fs'
|
||||
import path from 'path'
|
||||
import { test, expect, type Page } from '@playwright/test'
|
||||
import {
|
||||
createFixtureVaultCopy,
|
||||
openFixtureVaultDesktopHarness,
|
||||
removeFixtureVaultCopy,
|
||||
} from '../helpers/fixtureVault'
|
||||
|
||||
const RAW_EDITOR = '[data-testid="raw-editor-codemirror"]'
|
||||
const LIST_ROWS = '[data-testid="note-list-container"] [data-note-path]'
|
||||
const SORT_BUTTON = '[data-testid="sort-button-__list__"]'
|
||||
const SORT_OPTION_MODIFIED = '[data-testid="sort-option-modified"]'
|
||||
const SORT_DIRECTION_DESC = '[data-testid="sort-dir-desc-modified"]'
|
||||
|
||||
let tempVaultDir: string
|
||||
let alphaPath: string
|
||||
let newerPath: string
|
||||
|
||||
function setAllMarkdownModifiedTimes(rootDir: string, timestamp: Date) {
|
||||
const stack = [rootDir]
|
||||
|
||||
while (stack.length > 0) {
|
||||
const current = stack.pop()
|
||||
if (!current) continue
|
||||
|
||||
for (const entry of fs.readdirSync(current, { withFileTypes: true })) {
|
||||
const nextPath = path.join(current, entry.name)
|
||||
if (entry.isDirectory()) {
|
||||
stack.push(nextPath)
|
||||
continue
|
||||
}
|
||||
if (entry.isFile() && nextPath.endsWith('.md')) {
|
||||
fs.utimesSync(nextPath, timestamp, timestamp)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function sortListByModifiedDesc(page: Page) {
|
||||
await page.locator(SORT_BUTTON).click()
|
||||
await page.locator(SORT_OPTION_MODIFIED).click()
|
||||
await page.locator(SORT_BUTTON).click()
|
||||
await page.locator(SORT_DIRECTION_DESC).click()
|
||||
}
|
||||
|
||||
async function listOrder(page: Page): Promise<string[]> {
|
||||
return page.locator(LIST_ROWS).evaluateAll((rows) =>
|
||||
rows
|
||||
.map((row) => row.getAttribute('data-note-path'))
|
||||
.filter((value): value is string => typeof value === 'string' && value.length > 0),
|
||||
)
|
||||
}
|
||||
|
||||
async function getRawEditorContent(page: Page): Promise<string> {
|
||||
return page.evaluate(() => {
|
||||
const el = document.querySelector('.cm-content')
|
||||
if (!el) return ''
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const view = (el as any).cmTile?.view
|
||||
if (view) return view.state.doc.toString() as string
|
||||
return el.textContent ?? ''
|
||||
})
|
||||
}
|
||||
|
||||
async function setRawEditorContent(page: Page, content: string) {
|
||||
await page.evaluate((nextContent) => {
|
||||
const el = document.querySelector('.cm-content')
|
||||
if (!el) {
|
||||
throw new Error('CodeMirror content element is missing')
|
||||
}
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const view = (el as any).cmTile?.view
|
||||
if (!view) {
|
||||
throw new Error('CodeMirror view is missing')
|
||||
}
|
||||
view.dispatch({
|
||||
changes: { from: 0, to: view.state.doc.length, insert: nextContent },
|
||||
})
|
||||
}, content)
|
||||
}
|
||||
|
||||
async function installSaveTracker(page: Page) {
|
||||
await page.evaluate(() => {
|
||||
const internals = window.__TAURI_INTERNALS__
|
||||
if (!internals || typeof internals.invoke !== 'function') {
|
||||
throw new Error('Tauri invoke bridge is missing')
|
||||
}
|
||||
|
||||
if (window.__laputaTest?.getTrackedSaveCount) {
|
||||
window.__laputaTest.resetTrackedSaveCount?.()
|
||||
return
|
||||
}
|
||||
|
||||
let trackedSaveCount = 0
|
||||
const originalInvoke = internals.invoke.bind(internals)
|
||||
|
||||
internals.invoke = async (command: string, args?: Record<string, unknown>) => {
|
||||
if (command === 'save_note_content') {
|
||||
trackedSaveCount += 1
|
||||
}
|
||||
return originalInvoke(command, args)
|
||||
}
|
||||
|
||||
window.__laputaTest = {
|
||||
...window.__laputaTest,
|
||||
getTrackedSaveCount: () => trackedSaveCount,
|
||||
resetTrackedSaveCount: () => {
|
||||
trackedSaveCount = 0
|
||||
},
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
async function trackedSaveCount(page: Page): Promise<number> {
|
||||
return page.evaluate(() => window.__laputaTest?.getTrackedSaveCount?.() ?? 0)
|
||||
}
|
||||
|
||||
async function resetTrackedSaveCount(page: Page) {
|
||||
await page.evaluate(() => {
|
||||
window.__laputaTest?.resetTrackedSaveCount?.()
|
||||
})
|
||||
}
|
||||
|
||||
test.describe('editor mode modified-date ordering', () => {
|
||||
test.beforeEach(async ({ page }) => {
|
||||
tempVaultDir = createFixtureVaultCopy()
|
||||
alphaPath = path.join(tempVaultDir, 'project/alpha-project.md')
|
||||
newerPath = path.join(tempVaultDir, 'note/note-b.md')
|
||||
|
||||
setAllMarkdownModifiedTimes(tempVaultDir, new Date('2026-01-01T10:00:00Z'))
|
||||
fs.utimesSync(newerPath, new Date('2026-01-01T12:00:00Z'), new Date('2026-01-01T12:00:00Z'))
|
||||
|
||||
await openFixtureVaultDesktopHarness(page, tempVaultDir)
|
||||
await installSaveTracker(page)
|
||||
await sortListByModifiedDesc(page)
|
||||
await expect(page.locator(`[data-note-path="${alphaPath}"]`)).toBeVisible({ timeout: 5_000 })
|
||||
})
|
||||
|
||||
test.afterEach(() => {
|
||||
removeFixtureVaultCopy(tempVaultDir)
|
||||
})
|
||||
|
||||
test('keyboard-only editor toggles do not save or reorder by modified date, but real edits still save', async ({ page }) => {
|
||||
const baselineOrder = await listOrder(page)
|
||||
const baselineIndex = baselineOrder.indexOf(alphaPath)
|
||||
|
||||
expect(baselineOrder[0]).toBe(newerPath)
|
||||
expect(baselineIndex).toBeGreaterThan(0)
|
||||
|
||||
await page.locator(`[data-note-path="${alphaPath}"]`).click()
|
||||
await expect(page.locator('.bn-editor')).toBeVisible({ timeout: 5_000 })
|
||||
await resetTrackedSaveCount(page)
|
||||
|
||||
const modifiedBeforeToggle = fs.statSync(alphaPath).mtimeMs
|
||||
|
||||
await page.keyboard.press('Control+Backslash')
|
||||
await expect(page.locator(RAW_EDITOR)).toBeVisible({ timeout: 5_000 })
|
||||
await page.waitForTimeout(700)
|
||||
expect(fs.statSync(alphaPath).mtimeMs).toBe(modifiedBeforeToggle)
|
||||
|
||||
await page.keyboard.press('Control+Backslash')
|
||||
await expect(page.locator('.bn-editor')).toBeVisible({ timeout: 5_000 })
|
||||
await page.waitForTimeout(700)
|
||||
expect(fs.statSync(alphaPath).mtimeMs).toBe(modifiedBeforeToggle)
|
||||
|
||||
const orderAfterViewToggle = await listOrder(page)
|
||||
expect(orderAfterViewToggle[0]).toBe(newerPath)
|
||||
expect(orderAfterViewToggle.indexOf(alphaPath)).toBe(baselineIndex)
|
||||
expect(await trackedSaveCount(page)).toBe(0)
|
||||
|
||||
await page.keyboard.press('Control+Backslash')
|
||||
await expect(page.locator(RAW_EDITOR)).toBeVisible({ timeout: 5_000 })
|
||||
|
||||
const rawContent = await getRawEditorContent(page)
|
||||
const appendedText = `Actual raw edit ${Date.now()}`
|
||||
await setRawEditorContent(page, `${rawContent}\n\n${appendedText}`)
|
||||
await page.keyboard.press(process.platform === 'darwin' ? 'Meta+s' : 'Control+s')
|
||||
await page.waitForTimeout(300)
|
||||
|
||||
await expect.poll(() => fs.statSync(alphaPath).mtimeMs).toBeGreaterThan(modifiedBeforeToggle)
|
||||
await expect.poll(() => trackedSaveCount(page)).toBeGreaterThan(0)
|
||||
|
||||
await page.keyboard.press('Control+Backslash')
|
||||
await expect(page.locator('.bn-editor')).toContainText(appendedText, { timeout: 5_000 })
|
||||
})
|
||||
})
|
||||
44
tests/smoke/fresh-start-telemetry-onboarding.spec.ts
Normal file
44
tests/smoke/fresh-start-telemetry-onboarding.spec.ts
Normal file
@@ -0,0 +1,44 @@
|
||||
import { test, expect } from '@playwright/test'
|
||||
|
||||
test('accepting telemetry consent on a fresh start opens the vault choice wizard @smoke', async ({ page }) => {
|
||||
await page.addInitScript(() => {
|
||||
localStorage.clear()
|
||||
|
||||
let ref: Record<string, unknown> | null = null
|
||||
|
||||
Object.defineProperty(window, '__mockHandlers', {
|
||||
configurable: true,
|
||||
set(value) {
|
||||
ref = value as Record<string, unknown>
|
||||
|
||||
const originalGetSettings = ref.get_settings as (() => Record<string, unknown>) | undefined
|
||||
ref.get_settings = () => ({
|
||||
...(originalGetSettings ? originalGetSettings() : {}),
|
||||
telemetry_consent: null,
|
||||
crash_reporting_enabled: null,
|
||||
analytics_enabled: null,
|
||||
anonymous_id: null,
|
||||
})
|
||||
ref.load_vault_list = () => ({
|
||||
vaults: [],
|
||||
active_vault: null,
|
||||
hidden_defaults: [],
|
||||
})
|
||||
ref.get_default_vault_path = () => '/Users/mock/Documents/Getting Started'
|
||||
ref.check_vault_exists = (args: { path?: string }) => args?.path === '/Users/mock/Documents/Getting Started'
|
||||
},
|
||||
get() {
|
||||
return ref
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
await page.goto('/', { waitUntil: 'domcontentloaded' })
|
||||
|
||||
await expect(page.getByText('Help improve Tolaria')).toBeVisible()
|
||||
await page.getByTestId('telemetry-accept').click()
|
||||
|
||||
await expect(page.getByTestId('welcome-screen')).toBeVisible()
|
||||
await expect(page.getByTestId('welcome-open-folder')).toBeVisible()
|
||||
await expect(page.getByTestId('welcome-create-new')).toBeFocused()
|
||||
})
|
||||
118
tests/smoke/image-toolbar-hover.spec.ts
Normal file
118
tests/smoke/image-toolbar-hover.spec.ts
Normal file
@@ -0,0 +1,118 @@
|
||||
import { test, expect, type Page } from '@playwright/test'
|
||||
import {
|
||||
createFixtureVaultCopy,
|
||||
openFixtureVault,
|
||||
removeFixtureVaultCopy,
|
||||
} from '../helpers/fixtureVault'
|
||||
import { openCommandPalette, executeCommand } from './helpers'
|
||||
|
||||
const IMAGE_DATA_URL =
|
||||
'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+yK9sAAAAASUVORK5CYII='
|
||||
|
||||
let tempVaultDir: string
|
||||
|
||||
async function openNote(page: Page, title: string) {
|
||||
await page.locator('[data-testid="note-list-container"]').getByText(title, { exact: true }).click()
|
||||
await expect(page.locator('.bn-editor')).toBeVisible({ timeout: 5_000 })
|
||||
}
|
||||
|
||||
async function openRawMode(page: Page) {
|
||||
await openCommandPalette(page)
|
||||
await executeCommand(page, 'Toggle Raw')
|
||||
await expect(page.locator('.cm-content')).toBeVisible({ timeout: 5_000 })
|
||||
}
|
||||
|
||||
async function openBlockNoteMode(page: Page) {
|
||||
await openCommandPalette(page)
|
||||
await executeCommand(page, 'Toggle Raw')
|
||||
await expect(page.locator('.bn-editor')).toBeVisible({ timeout: 5_000 })
|
||||
}
|
||||
|
||||
async function getRawEditorContent(page: Page): Promise<string> {
|
||||
return page.evaluate(() => {
|
||||
const el = document.querySelector('.cm-content')
|
||||
if (!el) return ''
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- CodeMirror view is attached to the DOM node.
|
||||
const view = (el as any).cmTile?.view
|
||||
if (!view) return el.textContent ?? ''
|
||||
|
||||
return view.state.doc.toString() as string
|
||||
})
|
||||
}
|
||||
|
||||
async function setRawEditorContent(page: Page, content: string) {
|
||||
await page.evaluate((nextContent) => {
|
||||
const el = document.querySelector('.cm-content')
|
||||
if (!el) return
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- CodeMirror view is attached to the DOM node.
|
||||
const view = (el as any).cmTile?.view
|
||||
if (!view) return
|
||||
|
||||
const fullDocumentRange = { from: 0, to: view.state.doc.length }
|
||||
view.dispatch({
|
||||
changes: { ...fullDocumentRange, insert: nextContent },
|
||||
})
|
||||
}, content)
|
||||
}
|
||||
|
||||
async function seedImageBlock(page: Page) {
|
||||
await openNote(page, 'Note B')
|
||||
await openRawMode(page)
|
||||
|
||||
const rawContent = await getRawEditorContent(page)
|
||||
const imageMarkdown = `\n\n\n`
|
||||
await setRawEditorContent(page, `${rawContent}${imageMarkdown}`)
|
||||
await page.waitForTimeout(700)
|
||||
|
||||
await openBlockNoteMode(page)
|
||||
|
||||
const image = page.locator('.bn-editor img.bn-visual-media').last()
|
||||
await expect(image).toBeVisible({ timeout: 5_000 })
|
||||
return image
|
||||
}
|
||||
|
||||
test.beforeEach(async ({ page }, testInfo) => {
|
||||
testInfo.setTimeout(90_000)
|
||||
tempVaultDir = createFixtureVaultCopy()
|
||||
await openFixtureVault(page, tempVaultDir)
|
||||
})
|
||||
|
||||
test.afterEach(async () => {
|
||||
removeFixtureVaultCopy(tempVaultDir)
|
||||
})
|
||||
|
||||
test('image toolbar stays usable while the pointer crosses onto its controls', async ({ page }) => {
|
||||
const image = await seedImageBlock(page)
|
||||
|
||||
await image.click()
|
||||
|
||||
const toolbar = page.locator('.bn-formatting-toolbar')
|
||||
const replaceButton = page.getByRole('button', { name: /Replace image/i })
|
||||
|
||||
await expect(toolbar).toBeVisible({ timeout: 5_000 })
|
||||
await expect(replaceButton).toBeVisible()
|
||||
|
||||
const imageBox = await image.boundingBox()
|
||||
const replaceButtonBox = await replaceButton.boundingBox()
|
||||
|
||||
expect(imageBox).not.toBeNull()
|
||||
expect(replaceButtonBox).not.toBeNull()
|
||||
|
||||
await page.mouse.move(
|
||||
imageBox!.x + imageBox!.width / 2,
|
||||
imageBox!.y + imageBox!.height / 2,
|
||||
)
|
||||
await page.mouse.move(
|
||||
replaceButtonBox!.x + replaceButtonBox!.width / 2,
|
||||
replaceButtonBox!.y + replaceButtonBox!.height / 2,
|
||||
{ steps: 16 },
|
||||
)
|
||||
|
||||
await expect(toolbar).toBeVisible()
|
||||
await expect(replaceButton).toBeVisible()
|
||||
|
||||
await replaceButton.click()
|
||||
await expect(page.locator('.bn-panel-popover')).toBeVisible()
|
||||
})
|
||||
108
tests/smoke/plain-filename-autolink.spec.ts
Normal file
108
tests/smoke/plain-filename-autolink.spec.ts
Normal file
@@ -0,0 +1,108 @@
|
||||
import { expect, test, type Page } from '@playwright/test'
|
||||
import {
|
||||
createFixtureVaultCopy,
|
||||
openFixtureVault,
|
||||
removeFixtureVaultCopy,
|
||||
} from '../helpers/fixtureVault'
|
||||
import { executeCommand, openCommandPalette } from './helpers'
|
||||
|
||||
let tempVaultDir: string
|
||||
|
||||
async function openNote(page: Page, title: string) {
|
||||
await page.locator('[data-testid="note-list-container"]').getByText(title, { exact: true }).click()
|
||||
await expect(page.locator('.bn-editor')).toBeVisible({ timeout: 5_000 })
|
||||
}
|
||||
|
||||
async function openRawMode(page: Page) {
|
||||
await openCommandPalette(page)
|
||||
await executeCommand(page, 'Toggle Raw')
|
||||
await expect(page.locator('.cm-content')).toBeVisible({ timeout: 5_000 })
|
||||
}
|
||||
|
||||
async function openBlockNoteMode(page: Page) {
|
||||
await openCommandPalette(page)
|
||||
await executeCommand(page, 'Toggle Raw')
|
||||
await expect(page.locator('.bn-editor')).toBeVisible({ timeout: 5_000 })
|
||||
}
|
||||
|
||||
async function getRawEditorContent(page: Page): Promise<string> {
|
||||
return page.evaluate(() => {
|
||||
const el = document.querySelector('.cm-content')
|
||||
if (!el) return ''
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- CodeMirror view is attached to the DOM node.
|
||||
const view = (el as any).cmTile?.view
|
||||
if (!view) return el.textContent ?? ''
|
||||
|
||||
return view.state.doc.toString() as string
|
||||
})
|
||||
}
|
||||
|
||||
async function setRawEditorContent(page: Page, content: string) {
|
||||
await page.evaluate((nextContent) => {
|
||||
const el = document.querySelector('.cm-content')
|
||||
if (!el) return
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- CodeMirror view is attached to the DOM node.
|
||||
const view = (el as any).cmTile?.view
|
||||
if (!view) return
|
||||
|
||||
view.dispatch({
|
||||
changes: {
|
||||
from: 0,
|
||||
to: view.state.doc.length,
|
||||
insert: nextContent,
|
||||
},
|
||||
})
|
||||
}, content)
|
||||
}
|
||||
|
||||
async function appendPlainFilenameParagraph(page: Page, value: string) {
|
||||
const lastBlock = page.locator('.bn-block-content').last()
|
||||
await expect(lastBlock).toBeVisible({ timeout: 5_000 })
|
||||
await lastBlock.click()
|
||||
await page.keyboard.press('End')
|
||||
await page.keyboard.press('Enter')
|
||||
await page.keyboard.type(`${value} `)
|
||||
await page.waitForTimeout(700)
|
||||
}
|
||||
|
||||
test.beforeEach(async ({ page }, testInfo) => {
|
||||
testInfo.setTimeout(90_000)
|
||||
tempVaultDir = createFixtureVaultCopy()
|
||||
await openFixtureVault(page, tempVaultDir)
|
||||
})
|
||||
|
||||
test.afterEach(async () => {
|
||||
removeFixtureVaultCopy(tempVaultDir)
|
||||
})
|
||||
|
||||
test('plain filename-like text typed in BlockNote stays plain through raw-mode round trips', async ({ page }) => {
|
||||
await openNote(page, 'Note B')
|
||||
await appendPlainFilenameParagraph(page, 'AGENTS.md')
|
||||
await appendPlainFilenameParagraph(page, 'docs/README.md')
|
||||
|
||||
await openRawMode(page)
|
||||
|
||||
const raw = await getRawEditorContent(page)
|
||||
expect(raw).toContain('AGENTS.md')
|
||||
expect(raw).toContain('docs/README.md')
|
||||
expect(raw).not.toMatch(/\[AGENTS\.md\]\(/)
|
||||
expect(raw).not.toMatch(/\[docs\/README\.md\]\(/)
|
||||
})
|
||||
|
||||
test('explicit markdown links still render and round-trip intentionally', async ({ page }) => {
|
||||
await openNote(page, 'Note B')
|
||||
await openRawMode(page)
|
||||
|
||||
const raw = await getRawEditorContent(page)
|
||||
const intentionalLink = '[Tolaria Docs](https://example.com/docs)'
|
||||
await setRawEditorContent(page, `${raw}\n\n${intentionalLink}\n`)
|
||||
await page.waitForTimeout(700)
|
||||
|
||||
await openBlockNoteMode(page)
|
||||
await expect(page.locator('.bn-editor a[href="https://example.com/docs"]').last()).toContainText('Tolaria Docs')
|
||||
|
||||
await openRawMode(page)
|
||||
await expect.poll(() => getRawEditorContent(page)).toContain(intentionalLink)
|
||||
})
|
||||
184
tests/smoke/raw-yml-view-save.spec.ts
Normal file
184
tests/smoke/raw-yml-view-save.spec.ts
Normal file
@@ -0,0 +1,184 @@
|
||||
import { test, expect, type Page } from '@playwright/test'
|
||||
import fs from 'fs'
|
||||
import os from 'os'
|
||||
import path from 'path'
|
||||
import { APP_COMMAND_IDS } from '../../src/hooks/appCommandCatalog'
|
||||
import {
|
||||
createFixtureVaultCopy,
|
||||
openFixtureVaultDesktopHarness,
|
||||
removeFixtureVaultCopy,
|
||||
} from '../helpers/fixtureVault'
|
||||
import { triggerShortcutCommand } from './testBridge'
|
||||
|
||||
const VIEW_RELATIVE_PATH = path.join('views', 'active-projects.yml')
|
||||
const DUPLICATE_RELATIVE_PATH = path.join('views', 'active-projects.md')
|
||||
const VIEW_TITLE = 'Active Projects'
|
||||
const VIEW_CONTENT = `name: Active Projects
|
||||
icon: rocket
|
||||
color: blue
|
||||
sort: "modified:desc"
|
||||
filters:
|
||||
all:
|
||||
- field: type
|
||||
op: equals
|
||||
value: Project
|
||||
`
|
||||
|
||||
let tempVaultDir: string
|
||||
|
||||
function seedViewFile(vaultPath: string): void {
|
||||
const viewPath = path.join(vaultPath, VIEW_RELATIVE_PATH)
|
||||
fs.mkdirSync(path.dirname(viewPath), { recursive: true })
|
||||
fs.writeFileSync(viewPath, VIEW_CONTENT)
|
||||
}
|
||||
|
||||
function buildViewEntry(vaultPath: string) {
|
||||
const viewPath = path.join(vaultPath, VIEW_RELATIVE_PATH)
|
||||
return {
|
||||
path: viewPath,
|
||||
filename: path.basename(viewPath),
|
||||
title: VIEW_TITLE,
|
||||
isA: null,
|
||||
aliases: [],
|
||||
belongsTo: [],
|
||||
relatedTo: [],
|
||||
status: null,
|
||||
archived: false,
|
||||
modifiedAt: Date.now(),
|
||||
createdAt: null,
|
||||
fileSize: Buffer.byteLength(VIEW_CONTENT),
|
||||
snippet: '',
|
||||
wordCount: 0,
|
||||
relationships: {},
|
||||
icon: null,
|
||||
color: null,
|
||||
order: null,
|
||||
sidebarLabel: null,
|
||||
template: null,
|
||||
sort: null,
|
||||
view: null,
|
||||
visible: null,
|
||||
organized: false,
|
||||
favorite: false,
|
||||
favoriteIndex: null,
|
||||
listPropertiesDisplay: [],
|
||||
outgoingLinks: [],
|
||||
properties: {},
|
||||
hasH1: false,
|
||||
fileKind: 'text',
|
||||
}
|
||||
}
|
||||
|
||||
async function injectViewEntryIntoVaultList(page: Page, vaultPath: string): Promise<void> {
|
||||
const viewEntry = buildViewEntry(vaultPath)
|
||||
await page.route('**/api/vault/list*', async (route) => {
|
||||
const response = await route.fetch()
|
||||
const entries = await response.json()
|
||||
if (!Array.isArray(entries)) {
|
||||
await route.fulfill({ response })
|
||||
return
|
||||
}
|
||||
|
||||
const hasViewEntry = entries.some((entry) => entry?.path === viewEntry.path)
|
||||
const nextEntries = hasViewEntry ? entries : [...entries, viewEntry]
|
||||
await route.fulfill({ response, json: nextEntries })
|
||||
})
|
||||
}
|
||||
|
||||
async function openQuickOpenEntry(page: Page, title: string): Promise<void> {
|
||||
await triggerShortcutCommand(page, APP_COMMAND_IDS.fileQuickOpen)
|
||||
const input = page.locator('input[placeholder="Search notes..."]')
|
||||
await expect(input).toBeVisible({ timeout: 5_000 })
|
||||
await input.fill(title)
|
||||
await page.keyboard.press('Enter')
|
||||
}
|
||||
|
||||
async function appendRawEditorLine(page: Page, line: string): Promise<void> {
|
||||
await page.evaluate((nextLine) => {
|
||||
const host = document.querySelector('.cm-content')
|
||||
if (!host) {
|
||||
throw new Error('CodeMirror content element is missing')
|
||||
}
|
||||
|
||||
type CodeMirrorHost = Element & {
|
||||
cmTile?: {
|
||||
view?: {
|
||||
state: { doc: { toString(): string; length: number } }
|
||||
dispatch(transaction: { changes: { from: number; to: number; insert: string } }): void
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const view = (host as CodeMirrorHost).cmTile?.view
|
||||
if (!view) {
|
||||
throw new Error('CodeMirror view is missing')
|
||||
}
|
||||
|
||||
const doc = view.state.doc.toString()
|
||||
view.dispatch({
|
||||
changes: {
|
||||
from: doc.length,
|
||||
to: doc.length,
|
||||
insert: `\n${nextLine}\n`,
|
||||
},
|
||||
})
|
||||
}, line)
|
||||
}
|
||||
|
||||
async function readRawEditorContent(page: Page): Promise<string> {
|
||||
return page.evaluate(() => {
|
||||
const host = document.querySelector('.cm-content')
|
||||
if (!host) return ''
|
||||
|
||||
type CodeMirrorHost = Element & {
|
||||
cmTile?: {
|
||||
view?: {
|
||||
state: { doc: { toString(): string } }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return (host as CodeMirrorHost).cmTile?.view?.state.doc.toString() ?? host.textContent ?? ''
|
||||
})
|
||||
}
|
||||
|
||||
test.describe('raw .yml view save regression', () => {
|
||||
test.beforeEach(() => {
|
||||
tempVaultDir = createFixtureVaultCopy()
|
||||
seedViewFile(tempVaultDir)
|
||||
})
|
||||
|
||||
test.afterEach(() => {
|
||||
removeFixtureVaultCopy(tempVaultDir)
|
||||
})
|
||||
|
||||
test('saving a raw-edited .yml view preserves the .yml file and blocks the raw toggle shortcut @smoke', async ({ page }) => {
|
||||
const viewPath = path.join(tempVaultDir, VIEW_RELATIVE_PATH)
|
||||
const duplicatePath = path.join(tempVaultDir, DUPLICATE_RELATIVE_PATH)
|
||||
const marker = `# raw-yml-save-${Date.now()}-${os.userInfo().username}`
|
||||
|
||||
await injectViewEntryIntoVaultList(page, tempVaultDir)
|
||||
await openFixtureVaultDesktopHarness(page, tempVaultDir)
|
||||
await openQuickOpenEntry(page, VIEW_TITLE)
|
||||
|
||||
await expect(page.getByTestId('raw-editor-codemirror')).toBeVisible({ timeout: 5_000 })
|
||||
await expect(page.locator('.bn-editor')).toHaveCount(0)
|
||||
|
||||
await triggerShortcutCommand(page, APP_COMMAND_IDS.editToggleRawEditor)
|
||||
await expect(page.getByTestId('raw-editor-codemirror')).toBeVisible({ timeout: 5_000 })
|
||||
await expect(page.locator('.bn-editor')).toHaveCount(0)
|
||||
|
||||
await appendRawEditorLine(page, marker)
|
||||
await triggerShortcutCommand(page, APP_COMMAND_IDS.fileSave)
|
||||
|
||||
await expect.poll(() => fs.readFileSync(viewPath, 'utf-8')).toContain(marker)
|
||||
await expect.poll(() => fs.existsSync(duplicatePath)).toBe(false)
|
||||
|
||||
await openQuickOpenEntry(page, 'Alpha Project')
|
||||
await expect(page.locator('.bn-editor')).toBeVisible({ timeout: 5_000 })
|
||||
|
||||
await openQuickOpenEntry(page, VIEW_TITLE)
|
||||
await expect(page.getByTestId('raw-editor-codemirror')).toBeVisible({ timeout: 5_000 })
|
||||
await expect.poll(async () => readRawEditorContent(page)).toContain(marker)
|
||||
})
|
||||
})
|
||||
45
trademarks.md
Normal file
45
trademarks.md
Normal file
@@ -0,0 +1,45 @@
|
||||
# Tolaria Trademark Policy
|
||||
|
||||
This policy covers the **Tolaria** name, the Tolaria logo, and related branding assets.
|
||||
|
||||
## Code license vs. trademarks
|
||||
|
||||
Tolaria's source code is licensed under the GNU Affero General Public License v3.0 or later (AGPL-3.0-or-later).
|
||||
|
||||
That license applies to the code. It does **not** grant any right to use the Tolaria name, logo, or branding.
|
||||
|
||||
## Allowed without asking
|
||||
|
||||
You may, without prior permission:
|
||||
- refer to Tolaria truthfully in commentary, documentation, blog posts, reviews, comparisons, or tutorials
|
||||
- say that your project is based on, compatible with, or derived from Tolaria, as long as that statement is accurate
|
||||
- redistribute unmodified official releases while preserving existing notices
|
||||
- make nominative use of the Tolaria name to explain that you are discussing the original project
|
||||
|
||||
## Not allowed without prior written permission
|
||||
|
||||
You may not, without prior written permission:
|
||||
- use the Tolaria name or logo for a modified fork in a way that suggests it is the official project
|
||||
- rebrand a hosted or commercial offering as "Tolaria" if it is not the official Tolaria service or product
|
||||
- use the Tolaria logo in product branding, app icons, domains, marketing pages, or store listings for a fork or derivative product
|
||||
- imply endorsement, affiliation, sponsorship, or approval by the Tolaria project, Luca Rossi, or Refactoring when none exists
|
||||
|
||||
## Forks and modified versions
|
||||
|
||||
If you fork or modify Tolaria, you are welcome to do so under the AGPL, but you must choose your own name and branding for any redistributed or hosted version unless you have written permission to use the Tolaria marks.
|
||||
|
||||
Good examples:
|
||||
- "Fork of Tolaria"
|
||||
- "Based on Tolaria"
|
||||
- "Internal knowledge app derived from Tolaria"
|
||||
|
||||
Bad examples:
|
||||
- calling your modified product "Tolaria"
|
||||
- using the Tolaria logo for your fork
|
||||
- presenting your hosted fork as the official Tolaria product
|
||||
|
||||
## Reservation of rights
|
||||
|
||||
All trademark rights in the Tolaria name, logo, and branding are reserved.
|
||||
|
||||
Questions or permission requests should be directed to the project maintainer.
|
||||
Reference in New Issue
Block a user