v1.0.0 - Initial release

This commit is contained in:
Yuri Karamian
2026-02-09 01:47:56 +01:00
commit 46f4b6e7bc
70 changed files with 26357 additions and 0 deletions
+33
View File
@@ -0,0 +1,33 @@
node_modules
# Output
.output
.vercel
.netlify
.wrangler
/.svelte-kit
/build
# Tauri
/src-tauri/target
/src-tauri/gen
# OS
.DS_Store
Thumbs.db
# Env
.env
.env.*
!.env.example
!.env.test
# Vite
vite.config.js.timestamp-*
vite.config.ts.timestamp-*
# Claude Code
.claude/
# Signing keys
*.key
+1
View File
@@ -0,0 +1 @@
engine-strict=true
+661
View File
@@ -0,0 +1,661 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<https://www.gnu.org/licenses/>.
+62
View File
@@ -0,0 +1,62 @@
# HelixNotes
A local-first markdown note-taking app built with Tauri, SvelteKit, and Rust.
Your notes are stored as standard Markdown files on your local filesystem. No cloud, no lock-in.
## Download
| Platform | Download |
|----------|----------|
| Linux | [HelixNotes_1.0.0_amd64.AppImage](https://codeberg.org/ArkHost/HelixNotes/releases/download/v1.0.0/HelixNotes_1.0.0_amd64.AppImage) |
| Windows | Coming soon |
| macOS | Coming soon |
See all releases: [codeberg.org/ArkHost/HelixNotes/releases](https://codeberg.org/ArkHost/HelixNotes/releases)
## Features
- **Markdown editor** with rich formatting toolbar, slash commands, and source mode
- **Wiki-links** — link notes with `[[Note Title]]` syntax
- **Graph view** — visualize connections between your notes
- **Full-text search** powered by Tantivy
- **AI writing tools** — improve, summarize, translate, and more (Anthropic / OpenAI)
- **Version history** — per-note snapshots with diff view
- **Backups** — automatic zip-based vault backups
- **PDF preview** — inline rendering of embedded PDFs
- **Obsidian import** — convert Obsidian wiki-links to standard markdown
- **Themes** — light/dark mode with customizable accent colors and fonts
- **Focus mode** — distraction-free writing
- **Local-first** — everything stays on your machine
## Tech Stack
- **Frontend**: SvelteKit (Svelte 5) + TailwindCSS v4 + TipTap v3
- **Backend**: Rust (Tauri 2.0) + Tantivy (search) + Notify (file watcher)
- **Platforms**: Linux (AppImage, .deb, .rpm), Windows, macOS
## Building from Source
### Prerequisites
- [Rust](https://rustup.rs/) (1.77+)
- [Node.js](https://nodejs.org/) (18+)
- [pnpm](https://pnpm.io/)
- System dependencies for Tauri: see [Tauri prerequisites](https://v2.tauri.app/start/prerequisites/)
### Development
```bash
pnpm install
pnpm tauri dev
```
### Production Build
```bash
pnpm tauri build
```
## License
[AGPL-3.0](LICENSE)
+68
View File
@@ -0,0 +1,68 @@
{
"name": "helixnotes",
"private": true,
"license": "AGPL-3.0-or-later",
"version": "1.0.0",
"type": "module",
"scripts": {
"dev": "vite dev",
"build": "vite build",
"preview": "vite preview",
"prepare": "svelte-kit sync || echo ''",
"check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json",
"check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch",
"tauri": "tauri",
"tauri:dev": "tauri dev",
"tauri:build": "tauri build"
},
"devDependencies": {
"@sveltejs/adapter-auto": "^7.0.0",
"@sveltejs/adapter-static": "^3.0.10",
"@sveltejs/kit": "^2.50.2",
"@sveltejs/vite-plugin-svelte": "^6.2.4",
"@tailwindcss/postcss": "^4.1.18",
"@tailwindcss/vite": "^4.1.18",
"@tauri-apps/cli": "^2.10.0",
"svelte": "^5.49.2",
"svelte-check": "^4.3.6",
"tailwindcss": "^4.1.18",
"typescript": "^5.9.3",
"vite": "^7.3.1"
},
"dependencies": {
"@tauri-apps/api": "^2.10.1",
"@tauri-apps/plugin-dialog": "^2.6.0",
"@tauri-apps/plugin-fs": "^2.4.5",
"@tauri-apps/plugin-opener": "^2.5.3",
"@tauri-apps/plugin-updater": "^2.10.0",
"@tiptap/core": "^3.19.0",
"@tiptap/extension-code-block-lowlight": "^3.19.0",
"@tiptap/extension-color": "^3.19.0",
"@tiptap/extension-details": "^3.19.0",
"@tiptap/extension-highlight": "^3.19.0",
"@tiptap/extension-image": "^3.19.0",
"@tiptap/extension-link": "^3.19.0",
"@tiptap/extension-placeholder": "^3.19.0",
"@tiptap/extension-subscript": "^3.19.0",
"@tiptap/extension-superscript": "^3.19.0",
"@tiptap/extension-table": "^3.19.0",
"@tiptap/extension-table-cell": "^3.19.0",
"@tiptap/extension-table-header": "^3.19.0",
"@tiptap/extension-table-row": "^3.19.0",
"@tiptap/extension-task-item": "^3.19.0",
"@tiptap/extension-task-list": "^3.19.0",
"@tiptap/extension-text-align": "^3.19.0",
"@tiptap/extension-text-style": "^3.19.0",
"@tiptap/extension-typography": "^3.19.0",
"@tiptap/extension-underline": "^3.19.0",
"@tiptap/pm": "^3.19.0",
"@tiptap/starter-kit": "^3.19.0",
"@types/markdown-it": "^14.1.2",
"lowlight": "^3.3.0",
"markdown-it": "^14.1.0",
"markdown-it-mark": "^4.0.0",
"markdown-it-sub": "^2.0.0",
"markdown-it-sup": "^2.0.0",
"markdown-it-task-lists": "^2.1.1"
}
}
+2403
View File
File diff suppressed because it is too large Load Diff
+4
View File
@@ -0,0 +1,4 @@
# Generated by Cargo
# will have compiled files and executables
/target/
/gen/schemas
+6885
View File
File diff suppressed because it is too large Load Diff
+40
View File
@@ -0,0 +1,40 @@
[package]
name = "helixnotes"
version = "1.0.0"
description = "Local-first markdown note-taking app"
authors = ["HelixNotes"]
license = "AGPL-3.0-or-later"
edition = "2021"
rust-version = "1.77.2"
[lib]
name = "app_lib"
crate-type = ["staticlib", "cdylib", "rlib"]
[build-dependencies]
tauri-build = { version = "2", features = [] }
[dependencies]
tauri = { version = "2", features = ["protocol-asset", "tray-icon", "image-png"] }
tauri-plugin-log = "2"
tauri-plugin-dialog = "2"
tauri-plugin-fs = "2"
tauri-plugin-opener = "2"
tauri-plugin-updater = "2"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
serde_yaml = "0.9"
log = "0.4"
notify = "8"
walkdir = "2"
chrono = { version = "0.4", features = ["serde"] }
uuid = { version = "1", features = ["v4"] }
tantivy = "0.22"
gray_matter = "0.2"
tokio = { version = "1", features = ["full"] }
dirs = "6"
regex = "1"
zip = { version = "2", default-features = false, features = ["deflate"] }
reqwest = { version = "0.12", features = ["json", "stream"] }
futures = "0.3"
rayon = "1"
+3
View File
@@ -0,0 +1,3 @@
fn main() {
tauri_build::build()
}
+50
View File
@@ -0,0 +1,50 @@
{
"$schema": "../gen/schemas/desktop-schema.json",
"identifier": "default",
"description": "HelixNotes default capabilities",
"windows": ["main"],
"permissions": [
"core:default",
"core:window:default",
"core:window:allow-start-dragging",
"core:window:allow-minimize",
"core:window:allow-toggle-maximize",
"core:window:allow-close",
"core:window:allow-is-maximized",
"core:window:allow-set-decorations",
"dialog:default",
"dialog:allow-open",
"dialog:allow-save",
"dialog:allow-message",
"dialog:allow-ask",
"dialog:allow-confirm",
"fs:default",
"fs:allow-read",
"fs:allow-write",
"fs:allow-exists",
"fs:allow-mkdir",
"fs:allow-remove",
"fs:allow-rename",
"fs:allow-copy-file",
"fs:allow-stat",
"fs:allow-read-dir",
"fs:allow-read-file",
"fs:allow-write-file",
"fs:allow-watch",
"opener:default",
{
"identifier": "opener:allow-open-path",
"allow": [{ "path": "/**" }]
},
{
"identifier": "opener:allow-open-url",
"allow": [
{ "url": "https://**" },
{ "url": "http://**" },
{ "url": "mailto:*" }
]
},
"opener:allow-reveal-item-in-dir",
"updater:default"
]
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 4.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 953 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 793 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

+405
View File
@@ -0,0 +1,405 @@
use reqwest::Client;
use serde_json::json;
use tauri::{AppHandle, Emitter};
use crate::types::AiStreamEvent;
const ANTHROPIC_API_URL: &str = "https://api.anthropic.com/v1/messages";
const OPENAI_API_URL: &str = "https://api.openai.com/v1/chat/completions";
pub fn ai_request(
app: AppHandle,
provider: String,
api_key: String,
model: String,
system_prompt: String,
user_message: String,
request_id: String,
) {
std::thread::spawn(move || {
let rt = tokio::runtime::Runtime::new().unwrap();
rt.block_on(async {
let result = match provider.as_str() {
"openai" => {
stream_openai(
&app,
&api_key,
&model,
&system_prompt,
&user_message,
&request_id,
)
.await
}
_ => {
stream_anthropic(
&app,
&api_key,
&model,
&system_prompt,
&user_message,
&request_id,
)
.await
}
};
if let Err(e) = result {
let _ = app.emit(
"ai-stream",
AiStreamEvent {
event_type: "error".to_string(),
text: None,
error: Some(e),
},
);
}
});
});
}
async fn stream_anthropic(
app: &AppHandle,
api_key: &str,
model: &str,
system_prompt: &str,
user_message: &str,
_request_id: &str,
) -> Result<(), String> {
let client = Client::new();
let body = json!({
"model": model,
"max_tokens": 4096,
"stream": true,
"system": system_prompt,
"messages": [
{
"role": "user",
"content": user_message
}
]
});
let response = client
.post(ANTHROPIC_API_URL)
.header("x-api-key", api_key)
.header("anthropic-version", "2023-06-01")
.header("content-type", "application/json")
.json(&body)
.send()
.await
.map_err(|e| format!("Request failed: {}", e))?;
if !response.status().is_success() {
let status = response.status();
let body_text = response.text().await.unwrap_or_default();
return Err(format!("API error {}: {}", status, body_text));
}
// Parse SSE stream
use futures::StreamExt;
let mut stream = response.bytes_stream();
let mut buffer = String::new();
while let Some(chunk) = stream.next().await {
let chunk = chunk.map_err(|e| format!("Stream error: {}", e))?;
buffer.push_str(&String::from_utf8_lossy(&chunk));
// Process complete SSE events from buffer
while let Some(event_end) = buffer.find("\n\n") {
let event_str = buffer[..event_end].to_string();
buffer = buffer[event_end + 2..].to_string();
for line in event_str.lines() {
if let Some(data) = line.strip_prefix("data: ") {
if data == "[DONE]" {
let _ = app.emit(
"ai-stream",
AiStreamEvent {
event_type: "done".to_string(),
text: None,
error: None,
},
);
return Ok(());
}
if let Ok(parsed) = serde_json::from_str::<serde_json::Value>(data) {
let event_type = parsed["type"].as_str().unwrap_or("");
match event_type {
"content_block_delta" => {
if let Some(text) = parsed["delta"]["text"].as_str() {
let _ = app.emit(
"ai-stream",
AiStreamEvent {
event_type: "text".to_string(),
text: Some(text.to_string()),
error: None,
},
);
}
}
"message_stop" => {
let _ = app.emit(
"ai-stream",
AiStreamEvent {
event_type: "done".to_string(),
text: None,
error: None,
},
);
return Ok(());
}
"error" => {
let msg = parsed["error"]["message"]
.as_str()
.unwrap_or("Unknown API error");
let _ = app.emit(
"ai-stream",
AiStreamEvent {
event_type: "error".to_string(),
text: None,
error: Some(msg.to_string()),
},
);
return Err(msg.to_string());
}
_ => {}
}
}
}
}
}
}
// Stream ended — send done
let _ = app.emit(
"ai-stream",
AiStreamEvent {
event_type: "done".to_string(),
text: None,
error: None,
},
);
Ok(())
}
async fn stream_openai(
app: &AppHandle,
api_key: &str,
model: &str,
system_prompt: &str,
user_message: &str,
_request_id: &str,
) -> Result<(), String> {
let client = Client::new();
let is_gpt5 = model.starts_with("gpt-5");
let token_key = if is_gpt5 {
"max_completion_tokens"
} else {
"max_tokens"
};
let mut body = json!({
"model": model,
"stream": true,
token_key: 4096,
"messages": [
{
"role": "system",
"content": system_prompt
},
{
"role": "user",
"content": user_message
}
]
});
// GPT-5 models don't support temperature
if !is_gpt5 {
body["temperature"] = json!(0.7);
}
let response = client
.post(OPENAI_API_URL)
.header("Authorization", format!("Bearer {}", api_key))
.header("content-type", "application/json")
.json(&body)
.send()
.await
.map_err(|e| format!("Request failed: {}", e))?;
if !response.status().is_success() {
let status = response.status();
let body_text = response.text().await.unwrap_or_default();
return Err(format!("API error {}: {}", status, body_text));
}
use futures::StreamExt;
let mut stream = response.bytes_stream();
let mut buffer = String::new();
while let Some(chunk) = stream.next().await {
let chunk = chunk.map_err(|e| format!("Stream error: {}", e))?;
buffer.push_str(&String::from_utf8_lossy(&chunk));
while let Some(event_end) = buffer.find("\n\n") {
let event_str = buffer[..event_end].to_string();
buffer = buffer[event_end + 2..].to_string();
for line in event_str.lines() {
if let Some(data) = line.strip_prefix("data: ") {
if data == "[DONE]" {
let _ = app.emit(
"ai-stream",
AiStreamEvent {
event_type: "done".to_string(),
text: None,
error: None,
},
);
return Ok(());
}
if let Ok(parsed) = serde_json::from_str::<serde_json::Value>(data) {
// OpenAI streaming: choices[0].delta.content
if let Some(content) = parsed["choices"][0]["delta"]["content"].as_str() {
if !content.is_empty() {
let _ = app.emit(
"ai-stream",
AiStreamEvent {
event_type: "text".to_string(),
text: Some(content.to_string()),
error: None,
},
);
}
}
// Check finish_reason
if let Some(reason) = parsed["choices"][0]["finish_reason"].as_str() {
if reason == "stop" || reason == "length" {
let _ = app.emit(
"ai-stream",
AiStreamEvent {
event_type: "done".to_string(),
text: None,
error: None,
},
);
return Ok(());
}
}
// Check for error in stream
if let Some(err) = parsed["error"]["message"].as_str() {
let _ = app.emit(
"ai-stream",
AiStreamEvent {
event_type: "error".to_string(),
text: None,
error: Some(err.to_string()),
},
);
return Err(err.to_string());
}
}
}
}
}
}
let _ = app.emit(
"ai-stream",
AiStreamEvent {
event_type: "done".to_string(),
text: None,
error: None,
},
);
Ok(())
}
pub async fn test_connection(provider: &str, api_key: &str, model: &str) -> Result<String, String> {
match provider {
"openai" => test_openai(api_key, model).await,
_ => test_anthropic(api_key, model).await,
}
}
async fn test_anthropic(api_key: &str, model: &str) -> Result<String, String> {
let client = Client::new();
let body = json!({
"model": model,
"max_tokens": 10,
"messages": [
{
"role": "user",
"content": "Hi"
}
]
});
let response = client
.post(ANTHROPIC_API_URL)
.header("x-api-key", api_key)
.header("anthropic-version", "2023-06-01")
.header("content-type", "application/json")
.json(&body)
.send()
.await
.map_err(|e| format!("Connection failed: {}", e))?;
if response.status().is_success() {
Ok("Connection successful".to_string())
} else {
let status = response.status();
let body_text = response.text().await.unwrap_or_default();
Err(format!("API error {}: {}", status, body_text))
}
}
async fn test_openai(api_key: &str, model: &str) -> Result<String, String> {
let client = Client::new();
let is_gpt5 = model.starts_with("gpt-5");
let token_key = if is_gpt5 {
"max_completion_tokens"
} else {
"max_tokens"
};
let body = json!({
"model": model,
token_key: 10,
"messages": [
{
"role": "user",
"content": "Hi"
}
]
});
let response = client
.post(OPENAI_API_URL)
.header("Authorization", format!("Bearer {}", api_key))
.header("content-type", "application/json")
.json(&body)
.send()
.await
.map_err(|e| format!("Connection failed: {}", e))?;
if response.status().is_success() {
Ok("Connection successful".to_string())
} else {
let status = response.status();
let body_text = response.text().await.unwrap_or_default();
Err(format!("API error {}: {}", status, body_text))
}
}
+269
View File
@@ -0,0 +1,269 @@
use std::fs;
use std::io::{Read, Write};
use std::path::{Path, PathBuf};
use chrono::Utc;
use walkdir::WalkDir;
use zip::write::SimpleFileOptions;
use zip::ZipArchive;
use crate::types::BackupEntry;
/// Returns the default backup directory (~/.config/helixnotes/backups/)
pub fn default_backup_dir() -> Result<PathBuf, String> {
let config_dir = dirs::config_dir().ok_or("Cannot find config directory")?;
let dir = config_dir.join("helixnotes").join("backups");
if !dir.exists() {
fs::create_dir_all(&dir).map_err(|e| e.to_string())?;
}
Ok(dir)
}
/// Returns the effective backup directory (custom or default)
pub fn get_backup_dir(custom: &Option<String>) -> Result<PathBuf, String> {
match custom {
Some(p) if !p.is_empty() => {
let dir = PathBuf::from(p);
if !dir.exists() {
fs::create_dir_all(&dir).map_err(|e| e.to_string())?;
}
Ok(dir)
}
_ => default_backup_dir(),
}
}
/// Create a backup zip of the vault
pub fn create_backup(
vault_path: &str,
backup_dir: &Path,
include_attachments: bool,
) -> Result<BackupEntry, String> {
let vault = Path::new(vault_path);
if !vault.is_dir() {
return Err("Vault directory does not exist".to_string());
}
if !backup_dir.exists() {
fs::create_dir_all(backup_dir).map_err(|e| e.to_string())?;
}
let now = Utc::now();
let timestamp = now.format("%Y-%m-%dT%H-%M-%S").to_string();
let filename = format!("helixnotes-backup-{}.zip", timestamp);
let backup_path = backup_dir.join(&filename);
let file = fs::File::create(&backup_path)
.map_err(|e| format!("Failed to create backup file: {}", e))?;
let mut zip = zip::ZipWriter::new(file);
let options = SimpleFileOptions::default()
.compression_method(zip::CompressionMethod::Deflated)
.compression_level(Some(6));
let helixnotes_dir = vault.join(".helixnotes");
let attachments_dir = helixnotes_dir.join("attachments");
for entry in WalkDir::new(vault).into_iter().filter_map(|e| e.ok()) {
let path = entry.path();
// Handle .helixnotes/ directory
if path.starts_with(&helixnotes_dir) {
if include_attachments {
// Include attachments/ but skip everything else
if !path.starts_with(&attachments_dir) && path != helixnotes_dir {
continue;
}
if path == helixnotes_dir {
continue;
}
} else {
// Skip .helixnotes entirely
continue;
}
}
// Skip hidden files/directories (except .helixnotes which we handle above)
if path != vault {
if let Some(name) = path.file_name() {
let name_str = name.to_string_lossy();
if name_str.starts_with('.') && name_str != ".helixnotes" {
continue;
}
}
}
let relative = path.strip_prefix(vault).map_err(|e| e.to_string())?;
if path.is_dir() {
let dir_name = format!("{}/", relative.to_string_lossy());
if dir_name != "/" {
zip.add_directory(&dir_name, options)
.map_err(|e| e.to_string())?;
}
} else {
let name = relative.to_string_lossy().to_string();
zip.start_file(&name, options).map_err(|e| e.to_string())?;
let mut f = fs::File::open(path).map_err(|e| e.to_string())?;
let mut buffer = Vec::new();
f.read_to_end(&mut buffer).map_err(|e| e.to_string())?;
zip.write_all(&buffer).map_err(|e| e.to_string())?;
}
}
zip.finish().map_err(|e| e.to_string())?;
let meta = fs::metadata(&backup_path).map_err(|e| e.to_string())?;
Ok(BackupEntry {
filename: filename.clone(),
path: backup_path.to_string_lossy().to_string(),
size: meta.len(),
created: now.to_rfc3339(),
})
}
/// List all backups in the backup directory
pub fn list_backups(backup_dir: &Path) -> Result<Vec<BackupEntry>, String> {
if !backup_dir.exists() {
return Ok(Vec::new());
}
let mut entries: Vec<BackupEntry> = Vec::new();
for entry in fs::read_dir(backup_dir).map_err(|e| e.to_string())? {
let entry = entry.map_err(|e| e.to_string())?;
let path = entry.path();
if path.extension().map_or(false, |ext| ext == "zip") {
let filename = path
.file_name()
.unwrap_or_default()
.to_string_lossy()
.to_string();
let meta = fs::metadata(&path).map_err(|e| e.to_string())?;
// Parse timestamp from filename: helixnotes-backup-YYYY-MM-DDTHH-MM-SS.zip
let created = if let Some(ts) = filename
.strip_prefix("helixnotes-backup-")
.and_then(|s| s.strip_suffix(".zip"))
{
// ts = "2026-02-08T18-09-15" → "2026-02-08T18:09:15Z"
if let Some(t_pos) = ts.find('T') {
let date_part = &ts[..t_pos];
let time_part = &ts[t_pos + 1..];
let time_colons = time_part.replace('-', ":");
format!("{}T{}Z", date_part, time_colons)
} else {
meta.modified()
.map(|t| {
let dt: chrono::DateTime<Utc> = t.into();
dt.to_rfc3339()
})
.unwrap_or_default()
}
} else {
meta.modified()
.map(|t| {
let dt: chrono::DateTime<Utc> = t.into();
dt.to_rfc3339()
})
.unwrap_or_default()
};
entries.push(BackupEntry {
filename,
path: path.to_string_lossy().to_string(),
size: meta.len(),
created,
});
}
}
// Sort newest first
entries.sort_by(|a, b| b.created.cmp(&a.created));
Ok(entries)
}
/// Restore a backup by extracting the zip over the vault directory
pub fn restore_backup(vault_path: &str, backup_path: &str) -> Result<(), String> {
let vault = Path::new(vault_path);
let backup = Path::new(backup_path);
if !backup.exists() {
return Err("Backup file does not exist".to_string());
}
let file = fs::File::open(backup).map_err(|e| format!("Failed to open backup: {}", e))?;
let mut archive =
ZipArchive::new(file).map_err(|e| format!("Invalid backup archive: {}", e))?;
// Clear existing notes (but keep .helixnotes/ internals except attachments)
for entry in fs::read_dir(vault).map_err(|e| e.to_string())? {
let entry = entry.map_err(|e| e.to_string())?;
let path = entry.path();
let name = path
.file_name()
.unwrap_or_default()
.to_string_lossy()
.to_string();
// Keep hidden dirs (.helixnotes) — we'll handle attachments separately
if name.starts_with('.') {
continue;
}
if path.is_dir() {
fs::remove_dir_all(&path).map_err(|e| e.to_string())?;
} else {
fs::remove_file(&path).map_err(|e| e.to_string())?;
}
}
// Clear existing attachments so backup's attachments replace them
let attachments_dir = vault.join(".helixnotes").join("attachments");
if attachments_dir.exists() {
fs::remove_dir_all(&attachments_dir).map_err(|e| e.to_string())?;
}
// Extract archive
for i in 0..archive.len() {
let mut file = archive.by_index(i).map_err(|e| e.to_string())?;
let outpath = vault.join(file.mangled_name());
if file.is_dir() {
fs::create_dir_all(&outpath).map_err(|e| e.to_string())?;
} else {
if let Some(parent) = outpath.parent() {
fs::create_dir_all(parent).map_err(|e| e.to_string())?;
}
let mut outfile = fs::File::create(&outpath).map_err(|e| e.to_string())?;
std::io::copy(&mut file, &mut outfile).map_err(|e| e.to_string())?;
}
}
Ok(())
}
/// Delete a single backup file
pub fn delete_backup(backup_path: &str) -> Result<(), String> {
let path = Path::new(backup_path);
if path.exists() {
fs::remove_file(path).map_err(|e| e.to_string())?;
}
Ok(())
}
/// Remove old backups keeping only the newest `max_count`
pub fn cleanup_old_backups(backup_dir: &Path, max_count: u32) -> Result<(), String> {
let mut backups = list_backups(backup_dir)?;
// backups are already sorted newest-first
if backups.len() as u32 > max_count {
let to_remove = backups.split_off(max_count as usize);
for entry in to_remove {
delete_backup(&entry.path)?;
}
}
Ok(())
}
File diff suppressed because it is too large Load Diff
+171
View File
@@ -0,0 +1,171 @@
use std::fs;
use std::path::{Path, PathBuf};
use chrono::{DateTime, Utc};
use crate::types::VersionEntry;
/// Directory: .helixnotes/history/<note-id>/
fn history_dir(vault_path: &str, note_id: &str) -> PathBuf {
Path::new(vault_path)
.join(".helixnotes")
.join("history")
.join(note_id)
}
/// Save a version snapshot if enough time has passed since the last one.
/// Minimum interval: 5 minutes between snapshots.
pub fn maybe_snapshot(vault_path: &str, note_id: &str, raw_content: &str, max_versions: u32) {
let dir = history_dir(vault_path, note_id);
// Check if we should create a snapshot (5 min cooldown)
if let Ok(entries) = fs::read_dir(&dir) {
let mut files: Vec<String> = entries
.filter_map(|e| e.ok())
.filter_map(|e| e.file_name().to_str().map(|s| s.to_string()))
.filter(|n| n.ends_with(".md"))
.collect();
files.sort();
if let Some(last) = files.last() {
if let Some(ts) = last.strip_suffix(".md") {
// Parse timestamp: 2026-02-08T18-30-00.md
if let Some(t_pos) = ts.find('T') {
let date_part = &ts[..t_pos];
let time_part = &ts[t_pos + 1..];
let time_colons = time_part.replace('-', ":");
let iso = format!("{}T{}Z", date_part, time_colons);
if let Ok(last_time) = iso.parse::<DateTime<Utc>>() {
let elapsed = Utc::now() - last_time;
if elapsed.num_minutes() < 5 {
return; // Too soon, skip
}
}
}
}
}
}
// Create snapshot
if let Err(e) = fs::create_dir_all(&dir) {
eprintln!("Failed to create history dir: {}", e);
return;
}
let timestamp = Utc::now().format("%Y-%m-%dT%H-%M-%S").to_string();
let filename = format!("{}.md", timestamp);
let path = dir.join(&filename);
if let Err(e) = fs::write(&path, raw_content) {
eprintln!("Failed to write version snapshot: {}", e);
return;
}
// Prune old versions
if max_versions > 0 {
let _ = prune_versions(&dir, max_versions);
}
}
/// Force-create a version snapshot, bypassing the cooldown.
pub fn force_snapshot(vault_path: &str, note_id: &str, raw_content: &str, max_versions: u32) {
let dir = history_dir(vault_path, note_id);
if let Err(e) = fs::create_dir_all(&dir) {
eprintln!("Failed to create history dir: {}", e);
return;
}
let timestamp = Utc::now().format("%Y-%m-%dT%H-%M-%S").to_string();
let filename = format!("{}.md", timestamp);
let path = dir.join(&filename);
if let Err(e) = fs::write(&path, raw_content) {
eprintln!("Failed to write version snapshot: {}", e);
return;
}
if max_versions > 0 {
let _ = prune_versions(&dir, max_versions);
}
}
/// List all version snapshots for a note, newest first.
pub fn list_versions(vault_path: &str, note_id: &str) -> Result<Vec<VersionEntry>, String> {
let dir = history_dir(vault_path, note_id);
if !dir.exists() {
return Ok(Vec::new());
}
let mut entries: Vec<VersionEntry> = Vec::new();
for entry in fs::read_dir(&dir).map_err(|e| e.to_string())? {
let entry = entry.map_err(|e| e.to_string())?;
let path = entry.path();
if path.extension().map_or(false, |ext| ext == "md") {
let filename = path
.file_stem()
.unwrap_or_default()
.to_string_lossy()
.to_string();
let meta = fs::metadata(&path).map_err(|e| e.to_string())?;
// Parse timestamp from filename
let timestamp = if let Some(t_pos) = filename.find('T') {
let date_part = &filename[..t_pos];
let time_part = &filename[t_pos + 1..];
let time_colons = time_part.replace('-', ":");
format!("{}T{}Z", date_part, time_colons)
} else {
filename.clone()
};
entries.push(VersionEntry {
timestamp,
size: meta.len(),
});
}
}
// Newest first
entries.sort_by(|a, b| b.timestamp.cmp(&a.timestamp));
Ok(entries)
}
/// Get the raw content of a specific version.
pub fn get_version(vault_path: &str, note_id: &str, timestamp: &str) -> Result<String, String> {
// Convert ISO timestamp back to filename: 2026-02-08T18:30:00Z → 2026-02-08T18-30-00.md
let filename = if let Some(t_pos) = timestamp.find('T') {
let date_part = &timestamp[..t_pos];
let time_part = timestamp[t_pos + 1..].trim_end_matches('Z');
let time_dashes = time_part.replace(':', "-");
format!("{}.md", format!("{}T{}", date_part, time_dashes))
} else {
format!("{}.md", timestamp)
};
let path = history_dir(vault_path, note_id).join(&filename);
fs::read_to_string(&path).map_err(|e| format!("Version not found: {}", e))
}
/// Remove old versions keeping only the newest `max` entries.
fn prune_versions(dir: &Path, max: u32) -> Result<(), String> {
let mut files: Vec<PathBuf> = fs::read_dir(dir)
.map_err(|e| e.to_string())?
.filter_map(|e| e.ok())
.map(|e| e.path())
.filter(|p| p.extension().map_or(false, |ext| ext == "md"))
.collect();
// Sort by name (timestamps sort lexicographically) — newest last
files.sort();
if files.len() as u32 > max {
let to_remove = files.len() as u32 - max;
for path in files.iter().take(to_remove as usize) {
let _ = fs::remove_file(path);
}
}
Ok(())
}
+138
View File
@@ -0,0 +1,138 @@
mod ai;
mod backup;
mod commands;
mod history;
mod search;
mod state;
mod types;
mod vault;
use state::AppState;
use tauri::{
image::Image,
menu::{MenuBuilder, MenuItemBuilder},
tray::TrayIconBuilder,
Manager,
};
#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
let config = commands::load_app_config();
let show_tray = config.show_tray_icon;
let app_state = AppState::new(config);
tauri::Builder::default()
.plugin(tauri_plugin_dialog::init())
.plugin(tauri_plugin_fs::init())
.plugin(tauri_plugin_opener::init())
.plugin(tauri_plugin_updater::Builder::new().build())
.setup(move |app| {
if cfg!(debug_assertions) {
app.handle().plugin(
tauri_plugin_log::Builder::default()
.level(log::LevelFilter::Info)
.build(),
)?;
}
if show_tray {
setup_tray(app)?;
}
Ok(())
})
.manage(app_state)
.invoke_handler(tauri::generate_handler![
commands::open_vault,
commands::get_app_config,
commands::set_theme,
commands::set_accent_color,
commands::set_font_size,
commands::set_font_family,
commands::get_notebooks,
commands::create_notebook,
commands::rename_notebook,
commands::delete_notebook,
commands::get_notes,
commands::read_note,
commands::save_note,
commands::create_note,
commands::rename_note,
commands::delete_note,
commands::move_note,
commands::get_all_tags,
commands::get_all_note_titles,
commands::search_notes,
commands::reindex,
commands::get_trash,
commands::restore_note,
commands::permanent_delete,
commands::empty_trash,
commands::load_vault_state,
commands::save_vault_state,
commands::save_image,
commands::save_attachment,
commands::get_notebook_icons,
commands::set_notebook_icon,
commands::set_general_settings,
commands::get_quick_access,
commands::add_quick_access,
commands::remove_quick_access,
commands::get_vault_stats,
commands::import_obsidian,
commands::open_file,
commands::copy_file_to,
commands::create_backup,
commands::list_backups,
commands::restore_backup,
commands::delete_backup,
commands::set_backup_settings,
commands::get_note_versions,
commands::get_note_version_content,
commands::create_version,
commands::set_ai_settings,
commands::test_ai_connection,
commands::ai_ask,
])
.run(tauri::generate_context!())
.expect("error while running tauri application");
}
fn setup_tray(app: &mut tauri::App) -> Result<(), Box<dyn std::error::Error>> {
let show = MenuItemBuilder::with_id("show", "Show HelixNotes").build(app)?;
let quit = MenuItemBuilder::with_id("quit", "Quit").build(app)?;
let menu = MenuBuilder::new(app).items(&[&show, &quit]).build()?;
let _tray = TrayIconBuilder::new()
.icon(
Image::from_path("icons/32x32.png")
.unwrap_or_else(|_| app.default_window_icon().cloned().unwrap()),
)
.menu(&menu)
.tooltip("HelixNotes")
.on_menu_event(|app, event| match event.id().as_ref() {
"show" => {
if let Some(window) = app.get_webview_window("main") {
let _ = window.show();
let _ = window.unminimize();
let _ = window.set_focus();
}
}
"quit" => {
app.exit(0);
}
_ => {}
})
.on_tray_icon_event(|tray, event| {
if let tauri::tray::TrayIconEvent::Click { .. } = event {
if let Some(window) = tray.app_handle().get_webview_window("main") {
let _ = window.show();
let _ = window.unminimize();
let _ = window.set_focus();
}
}
})
.build(app)?;
Ok(())
}
+6
View File
@@ -0,0 +1,6 @@
// Prevents additional console window on Windows in release, DO NOT REMOVE!!
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
fn main() {
app_lib::run();
}
+175
View File
@@ -0,0 +1,175 @@
use crate::types::SearchResult;
use crate::vault::frontmatter;
use crate::vault::operations::helixnotes_dir;
use std::fs;
use std::path::Path;
use std::sync::Mutex;
use tantivy::collector::TopDocs;
use tantivy::directory::MmapDirectory;
use tantivy::query::QueryParser;
use tantivy::schema::*;
use tantivy::{Index, IndexWriter, TantivyDocument};
use walkdir::WalkDir;
pub struct SearchIndex {
index: Index,
writer: Mutex<Option<IndexWriter>>,
#[allow(dead_code)]
schema: Schema,
path_field: Field,
title_field: Field,
body_field: Field,
tags_field: Field,
}
impl SearchIndex {
pub fn new(vault_path: &str) -> Result<Self, String> {
let index_dir = helixnotes_dir(vault_path).join("search_index");
fs::create_dir_all(&index_dir).map_err(|e| e.to_string())?;
let mut schema_builder = Schema::builder();
let path_field = schema_builder.add_text_field("path", STRING | STORED);
let title_field = schema_builder.add_text_field("title", TEXT | STORED);
let body_field = schema_builder.add_text_field("body", TEXT);
let tags_field = schema_builder.add_text_field("tags", TEXT | STORED);
let schema = schema_builder.build();
let dir = MmapDirectory::open(&index_dir).map_err(|e| e.to_string())?;
let index = Index::open_or_create(dir, schema.clone()).map_err(|e| e.to_string())?;
let writer = index
.writer(50_000_000)
.map_err(|e| e.to_string())?;
Ok(Self {
index,
writer: Mutex::new(Some(writer)),
schema,
path_field,
title_field,
body_field,
tags_field,
})
}
pub fn rebuild(&self, vault_path: &str) -> Result<(), String> {
let mut writer_guard = self.writer.lock().map_err(|e| e.to_string())?;
let writer = writer_guard.as_mut().ok_or("Writer not available")?;
writer.delete_all_documents().map_err(|e| e.to_string())?;
let hn_dir = helixnotes_dir(vault_path);
for entry in WalkDir::new(vault_path)
.into_iter()
.filter_map(|e| e.ok())
.filter(|e| {
let p = e.path();
p.is_file()
&& p.extension().and_then(|x| x.to_str()) == Some("md")
&& !p.starts_with(&hn_dir)
&& !p
.file_name()
.and_then(|n| n.to_str())
.map(|n| n.starts_with('.'))
.unwrap_or(false)
})
{
if let Ok(raw) = fs::read_to_string(entry.path()) {
let filename = entry.file_name().to_string_lossy().to_string();
let (meta, content) = frontmatter::parse_note(&raw, &filename);
let path_str = entry.path().to_string_lossy().to_string();
let mut doc = TantivyDocument::new();
doc.add_text(self.path_field, &path_str);
doc.add_text(self.title_field, &meta.title);
doc.add_text(self.body_field, &content);
doc.add_text(self.tags_field, &meta.tags.join(" "));
let _ = writer.add_document(doc);
}
}
writer.commit().map_err(|e| e.to_string())?;
Ok(())
}
pub fn index_note(&self, path: &str) -> Result<(), String> {
let p = Path::new(path);
let raw = fs::read_to_string(p).map_err(|e| e.to_string())?;
let filename = p
.file_name()
.unwrap_or_default()
.to_string_lossy()
.to_string();
let (meta, content) = frontmatter::parse_note(&raw, &filename);
let mut writer_guard = self.writer.lock().map_err(|e| e.to_string())?;
let writer = writer_guard.as_mut().ok_or("Writer not available")?;
// Delete old entry
let term = tantivy::Term::from_field_text(self.path_field, path);
writer.delete_term(term);
// Add updated
let mut doc = TantivyDocument::new();
doc.add_text(self.path_field, path);
doc.add_text(self.title_field, &meta.title);
doc.add_text(self.body_field, &content);
doc.add_text(self.tags_field, &meta.tags.join(" "));
let _ = writer.add_document(doc);
writer.commit().map_err(|e| e.to_string())?;
Ok(())
}
pub fn remove_note(&self, path: &str) -> Result<(), String> {
let mut writer_guard = self.writer.lock().map_err(|e| e.to_string())?;
let writer = writer_guard.as_mut().ok_or("Writer not available")?;
let term = tantivy::Term::from_field_text(self.path_field, path);
writer.delete_term(term);
writer.commit().map_err(|e| e.to_string())?;
Ok(())
}
pub fn search(&self, query_str: &str, limit: usize) -> Result<Vec<SearchResult>, String> {
let reader = self.index.reader().map_err(|e| e.to_string())?;
let searcher = reader.searcher();
let query_parser =
QueryParser::for_index(&self.index, vec![self.title_field, self.body_field, self.tags_field]);
let query = query_parser
.parse_query(query_str)
.map_err(|e| e.to_string())?;
let top_docs = searcher
.search(&query, &TopDocs::with_limit(limit))
.map_err(|e| e.to_string())?;
let mut results = Vec::new();
for (score, doc_address) in top_docs {
let doc: TantivyDocument = searcher.doc(doc_address).map_err(|e| e.to_string())?;
let path = doc
.get_first(self.path_field)
.and_then(|v| v.as_str())
.unwrap_or("")
.to_string();
let title = doc
.get_first(self.title_field)
.and_then(|v| v.as_str())
.unwrap_or("")
.to_string();
results.push(SearchResult {
path,
title,
snippet: String::new(),
score,
});
}
Ok(results)
}
}
+23
View File
@@ -0,0 +1,23 @@
use crate::search::SearchIndex;
use crate::types::AppConfig;
use notify::RecommendedWatcher;
use std::sync::atomic::AtomicBool;
use std::sync::Mutex;
pub struct AppState {
pub config: Mutex<AppConfig>,
pub search_index: Mutex<Option<SearchIndex>>,
pub watcher: Mutex<Option<RecommendedWatcher>>,
pub importing: AtomicBool,
}
impl AppState {
pub fn new(config: AppConfig) -> Self {
Self {
config: Mutex::new(config),
search_index: Mutex::new(None),
watcher: Mutex::new(None),
importing: AtomicBool::new(false),
}
}
}
+244
View File
@@ -0,0 +1,244 @@
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NoteMeta {
pub id: String,
pub title: String,
pub tags: Vec<String>,
pub pinned: bool,
pub created: DateTime<Utc>,
pub modified: DateTime<Utc>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NoteEntry {
pub path: String,
pub relative_path: String,
pub meta: NoteMeta,
pub preview: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NotebookEntry {
pub name: String,
pub path: String,
pub relative_path: String,
pub children: Vec<NotebookEntry>,
pub note_count: usize,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NoteContent {
pub path: String,
pub meta: NoteMeta,
pub content: String,
pub raw: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VaultConfig {
pub path: String,
pub name: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AppConfig {
pub vaults: Vec<VaultConfig>,
pub active_vault: Option<String>,
pub theme: String,
#[serde(default)]
pub accent_color: Option<String>,
#[serde(default)]
pub font_size: Option<u32>,
#[serde(default)]
pub font_family: Option<String>,
#[serde(default)]
pub compact_notes: bool,
#[serde(default)]
pub time_format: String,
#[serde(default)]
pub gpu_acceleration: bool,
#[serde(default)]
pub autostart: bool,
#[serde(default)]
pub pdf_preview: bool,
#[serde(default = "default_pdf_height")]
pub pdf_height: u32,
#[serde(default = "default_title_mode")]
pub title_mode: String,
#[serde(default)]
pub hide_title_in_body: bool,
#[serde(default)]
pub backup_enabled: bool,
#[serde(default = "default_backup_frequency")]
pub backup_frequency: String,
#[serde(default = "default_backup_max")]
pub backup_max_count: u32,
#[serde(default)]
pub backup_location: Option<String>,
#[serde(default)]
pub last_backup_time: Option<String>,
#[serde(default)]
pub backup_include_attachments: bool,
#[serde(default = "default_max_versions")]
pub max_versions_per_note: u32,
#[serde(default)]
pub ai_provider: Option<String>,
#[serde(default)]
pub ai_api_key: Option<String>,
#[serde(default)]
pub openai_api_key: Option<String>,
#[serde(default = "default_ai_model")]
pub ai_model: String,
#[serde(default)]
pub ai_writing_style: Option<String>,
#[serde(default)]
pub default_view_mode: bool,
#[serde(default)]
pub show_tray_icon: bool,
#[serde(default = "default_true")]
pub enable_wiki_links: bool,
}
fn default_true() -> bool {
true
}
fn default_pdf_height() -> u32 {
600
}
fn default_backup_frequency() -> String {
"24h".to_string()
}
fn default_backup_max() -> u32 {
10
}
fn default_title_mode() -> String {
"input".to_string()
}
fn default_max_versions() -> u32 {
20
}
fn default_ai_model() -> String {
"claude-sonnet-4-5-20250929".to_string()
}
impl Default for AppConfig {
fn default() -> Self {
Self {
vaults: Vec::new(),
active_vault: None,
theme: "system".to_string(),
accent_color: None,
font_size: None,
font_family: None,
compact_notes: false,
time_format: "relative".to_string(),
gpu_acceleration: true,
autostart: false,
pdf_preview: false,
pdf_height: 600,
title_mode: "input".to_string(),
hide_title_in_body: false,
backup_enabled: false,
backup_frequency: "24h".to_string(),
backup_max_count: 10,
backup_location: None,
last_backup_time: None,
backup_include_attachments: false,
max_versions_per_note: 20,
ai_provider: None,
ai_api_key: None,
openai_api_key: None,
ai_model: "claude-sonnet-4-5-20250929".to_string(),
ai_writing_style: None,
default_view_mode: false,
show_tray_icon: false,
enable_wiki_links: true,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VaultState {
pub last_open_note: Option<String>,
pub sidebar_width: f64,
pub notelist_width: f64,
pub sidebar_collapsed: bool,
#[serde(default)]
pub collapsed_notebooks: Vec<String>,
}
impl Default for VaultState {
fn default() -> Self {
Self {
last_open_note: None,
sidebar_width: 220.0,
notelist_width: 280.0,
sidebar_collapsed: false,
collapsed_notebooks: Vec::new(),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SearchResult {
pub path: String,
pub title: String,
pub snippet: String,
pub score: f32,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FileEvent {
pub event_type: String,
pub path: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ImportResult {
pub files_converted: u64,
pub links_converted: u64,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VaultStats {
pub total_notes: u64,
pub total_attachments: u64,
pub notes_size: u64,
pub attachments_size: u64,
pub total_size: u64,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BackupEntry {
pub filename: String,
pub path: String,
pub size: u64,
pub created: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VersionEntry {
pub timestamp: String,
pub size: u64,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AiStreamEvent {
pub event_type: String, // "text", "done", "error"
pub text: Option<String>,
pub error: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NoteTitleEntry {
pub title: String,
pub path: String,
}
+315
View File
@@ -0,0 +1,315 @@
use crate::types::NoteMeta;
use chrono::Utc;
use gray_matter::engine::YAML;
use gray_matter::Matter;
use serde::{Deserialize, Serialize};
use uuid::Uuid;
#[derive(Debug, Serialize, Deserialize, Default)]
struct RawFrontmatter {
id: Option<String>,
title: Option<String>,
tags: Option<Vec<String>>,
pinned: Option<bool>,
created: Option<String>,
modified: Option<String>,
}
pub fn parse_note(raw: &str, filename: &str) -> (NoteMeta, String) {
let matter = Matter::<YAML>::new();
let result = matter.parse(raw);
let fm: RawFrontmatter = result
.data
.and_then(|d| d.deserialize().ok())
.unwrap_or_default();
let title = fm.title.unwrap_or_else(|| filename_to_title(filename));
let created = fm
.created
.and_then(|s| s.parse().ok())
.unwrap_or_else(Utc::now);
let modified = fm
.modified
.and_then(|s| s.parse().ok())
.unwrap_or_else(Utc::now);
let id = fm.id.unwrap_or_else(|| Uuid::new_v4().to_string());
let meta = NoteMeta {
id,
title,
tags: fm.tags.unwrap_or_default(),
pinned: fm.pinned.unwrap_or(false),
created,
modified,
};
let content = result.content;
(meta, content)
}
pub fn serialize_frontmatter(meta: &NoteMeta) -> String {
let tags_str = if meta.tags.is_empty() {
"[]".to_string()
} else {
format!(
"[{}]",
meta.tags
.iter()
.map(|t| format!("{}", t))
.collect::<Vec<_>>()
.join(", ")
)
};
format!(
"---\nid: \"{}\"\ntitle: \"{}\"\ntags: {}\npinned: {}\ncreated: {}\nmodified: {}\n---\n",
meta.id,
meta.title.replace('"', "\\\""),
tags_str,
meta.pinned,
meta.created.to_rfc3339(),
meta.modified.to_rfc3339(),
)
}
pub fn update_note_raw(meta: &NoteMeta, body: &str) -> String {
let fm = serialize_frontmatter(meta);
format!("{}{}", fm, body)
}
fn filename_to_title(filename: &str) -> String {
let stem = filename.trim_end_matches(".md");
// Only replace dashes/underscores acting as word separators (between non-space chars).
// Keep dashes that are surrounded by spaces (e.g. "Title - Subtitle").
let mut result = String::with_capacity(stem.len());
let chars: Vec<char> = stem.chars().collect();
for (i, &ch) in chars.iter().enumerate() {
if (ch == '-' || ch == '_')
&& i > 0
&& i < chars.len() - 1
&& chars[i - 1] != ' '
&& chars[i + 1] != ' '
{
result.push(' ');
} else {
result.push(ch);
}
}
result
}
/// Quick title extraction from raw note content (frontmatter only, no full parse)
pub fn extract_title(raw: &str) -> Option<String> {
let matter = Matter::<YAML>::new();
let result = matter.parse(raw);
let fm: RawFrontmatter = result
.data
.and_then(|d| d.deserialize().ok())
.unwrap_or_default();
fm.title
}
pub fn extract_preview(content: &str, max_len: usize) -> String {
// Filter out headings and empty lines BEFORE stripping markdown,
// since strip_html_and_markdown collapses all whitespace into one line.
let filtered: String = content
.lines()
.filter(|l| {
let trimmed = l.trim();
!trimmed.is_empty()
&& !trimmed.starts_with('#')
&& !trimmed.starts_with("---")
&& !trimmed.starts_with("```")
})
.take(5)
.collect::<Vec<_>>()
.join("\n");
let text = strip_html_and_markdown(&filtered);
let trimmed = text.trim().to_string();
if trimmed.len() > max_len {
let mut end = max_len;
while end > 0 && !trimmed.is_char_boundary(end) {
end -= 1;
}
format!("{}...", &trimmed[..end])
} else {
trimmed
}
}
fn strip_html_and_markdown(input: &str) -> String {
let mut result = String::with_capacity(input.len());
let mut chars = input.chars().peekable();
let mut in_tag = false;
while let Some(ch) = chars.next() {
if in_tag {
if ch == '>' {
in_tag = false;
// Add a space after closing tags to separate words
result.push(' ');
}
continue;
}
if ch == '<' {
in_tag = true;
continue;
}
// Skip markdown image syntax: ![alt](url)
if ch == '!' && chars.peek() == Some(&'[') {
// Consume ![...](...) entirely
chars.next(); // skip '['
let mut depth = 1;
// Skip alt text
while let Some(c) = chars.next() {
if c == '[' {
depth += 1;
}
if c == ']' {
depth -= 1;
if depth == 0 {
break;
}
}
}
// Skip (url) if present
if chars.peek() == Some(&'(') {
chars.next();
let mut depth = 1;
while let Some(c) = chars.next() {
if c == '(' {
depth += 1;
}
if c == ')' {
depth -= 1;
if depth == 0 {
break;
}
}
}
}
continue;
}
// Markdown links: [text](url) — keep the text, skip the URL
if ch == '[' {
let mut link_text = String::new();
let mut depth = 1;
while let Some(c) = chars.next() {
if c == '[' {
depth += 1;
}
if c == ']' {
depth -= 1;
if depth == 0 {
break;
}
}
link_text.push(c);
}
// Skip (url) if present
if chars.peek() == Some(&'(') {
chars.next();
let mut depth = 1;
while let Some(c) = chars.next() {
if c == '(' {
depth += 1;
}
if c == ')' {
depth -= 1;
if depth == 0 {
break;
}
}
}
result.push_str(&link_text);
} else {
// Not a link, just brackets
result.push('[');
result.push_str(&link_text);
result.push(']');
}
continue;
}
// Strip bold/italic markers
if ch == '*' || ch == '_' {
// Skip consecutive * or _
while chars.peek() == Some(&ch) {
chars.next();
}
continue;
}
// Strip strikethrough ~~
if ch == '~' && chars.peek() == Some(&'~') {
chars.next();
continue;
}
// Strip inline code backticks
if ch == '`' {
while chars.peek() == Some(&'`') {
chars.next();
}
continue;
}
result.push(ch);
}
// Collapse multiple spaces/newlines into single spaces
let mut collapsed = String::with_capacity(result.len());
let mut last_was_space = false;
for ch in result.chars() {
if ch.is_whitespace() {
if !last_was_space {
collapsed.push(' ');
last_was_space = true;
}
} else {
collapsed.push(ch);
last_was_space = false;
}
}
collapsed
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_extract_preview_basic() {
let content =
"## SIM Kaarten\n\n### Artjom\n\n**Telefoonnummer**\n\n**== 0456 74 49 91 ==**\n";
let preview = extract_preview(content, 120);
eprintln!("Preview: {:?}", preview);
assert!(!preview.is_empty(), "Preview should not be empty");
}
#[test]
fn test_extract_preview_no_frontmatter() {
let content = "# Android flash\n\nAndroid flash\n\n[TWRP](https://twrp.me/)\n\nNotes;\n\n- Samsung S6\n";
let preview = extract_preview(content, 120);
eprintln!("Preview: {:?}", preview);
assert!(!preview.is_empty(), "Preview should not be empty");
}
#[test]
fn test_strip_html_markdown() {
let input = "**Telefoonnummer**\n\n**== 0456 ==**";
let stripped = strip_html_and_markdown(input);
eprintln!("Stripped: {:?}", stripped);
assert!(stripped.contains("Telefoonnummer"));
}
}
+3
View File
@@ -0,0 +1,3 @@
pub mod frontmatter;
pub mod operations;
pub mod watcher;
+677
View File
@@ -0,0 +1,677 @@
use crate::types::{NoteContent, NoteEntry, NoteMeta, NotebookEntry, VaultState};
use crate::vault::frontmatter;
use chrono::Utc;
use rayon::prelude::*;
use std::fs;
use std::io::Read;
use std::path::{Path, PathBuf};
use uuid::Uuid;
use walkdir::WalkDir;
pub fn helixnotes_dir(vault_path: &str) -> PathBuf {
Path::new(vault_path).join(".helixnotes")
}
pub fn ensure_vault_structure(vault_path: &str) -> Result<(), String> {
let hn_dir = helixnotes_dir(vault_path);
fs::create_dir_all(hn_dir.join("trash")).map_err(|e| e.to_string())?;
fs::create_dir_all(hn_dir.join("attachments")).map_err(|e| e.to_string())?;
let config_path = hn_dir.join("config.json");
if !config_path.exists() {
let config = serde_json::json!({
"version": "0.1.0",
"created": Utc::now().to_rfc3339()
});
fs::write(&config_path, serde_json::to_string_pretty(&config).unwrap())
.map_err(|e| e.to_string())?;
}
let state_path = hn_dir.join("state.json");
if !state_path.exists() {
let state = VaultState::default();
fs::write(&state_path, serde_json::to_string_pretty(&state).unwrap())
.map_err(|e| e.to_string())?;
}
let gitignore_path = hn_dir.join(".gitignore");
if !gitignore_path.exists() {
fs::write(&gitignore_path, "trash/\nindex.json\nstate.json\n")
.map_err(|e| e.to_string())?;
}
Ok(())
}
pub fn scan_notebooks(vault_path: &str) -> Result<Vec<NotebookEntry>, String> {
let root = Path::new(vault_path);
if !root.exists() {
return Err("Vault path does not exist".to_string());
}
Ok(scan_dir_recursive(root, vault_path))
}
fn scan_dir_recursive(dir: &Path, vault_root: &str) -> Vec<NotebookEntry> {
let mut entries = Vec::new();
let root = Path::new(vault_root);
let Ok(read_dir) = fs::read_dir(dir) else {
return entries;
};
let mut dirs: Vec<_> = read_dir
.filter_map(|e| e.ok())
.filter(|e| {
let path = e.path();
path.is_dir() && !is_hidden(&path)
})
.collect();
dirs.sort_by(|a, b| {
a.file_name()
.to_string_lossy()
.to_lowercase()
.cmp(&b.file_name().to_string_lossy().to_lowercase())
});
for dir_entry in dirs {
let path = dir_entry.path();
let name = dir_entry.file_name().to_string_lossy().to_string();
let relative = path
.strip_prefix(root)
.unwrap_or(&path)
.to_string_lossy()
.to_string();
let children = scan_dir_recursive(&path, vault_root);
let note_count = count_notes_in_dir(&path);
entries.push(NotebookEntry {
name,
path: path.to_string_lossy().to_string(),
relative_path: relative,
children,
note_count,
});
}
entries
}
fn count_notes_in_dir(dir: &Path) -> usize {
fs::read_dir(dir)
.map(|rd| {
rd.filter_map(|e| e.ok())
.filter(|e| {
let path = e.path();
path.is_file() && path.extension().and_then(|x| x.to_str()) == Some("md")
})
.count()
})
.unwrap_or(0)
}
fn is_hidden(path: &Path) -> bool {
path.file_name()
.and_then(|n| n.to_str())
.map(|n| n.starts_with('.'))
.unwrap_or(false)
}
pub fn scan_notes(vault_path: &str, notebook_path: Option<&str>) -> Result<Vec<NoteEntry>, String> {
let scan_path = notebook_path.unwrap_or(vault_path);
let root = Path::new(scan_path);
let vault_root = Path::new(vault_path);
if !root.exists() {
return Err("Path does not exist".to_string());
}
let md_files: Vec<PathBuf> = if notebook_path.is_some() {
// Only direct children for a specific notebook
fs::read_dir(root)
.map_err(|e| e.to_string())?
.filter_map(|e| e.ok())
.map(|e| e.path())
.filter(|p| p.is_file() && p.extension().and_then(|x| x.to_str()) == Some("md"))
.collect()
} else {
// Recursive for "All Notes"
WalkDir::new(root)
.into_iter()
.filter_map(|e| e.ok())
.filter(|e| !is_hidden(e.path()) && !e.path().starts_with(&helixnotes_dir(vault_path)))
.map(|e| e.path().to_path_buf())
.filter(|p| p.is_file() && p.extension().and_then(|x| x.to_str()) == Some("md"))
.collect()
};
// Process files in parallel with partial reads
let mut notes: Vec<NoteEntry> = md_files
.par_iter()
.filter_map(|path| read_note_entry_fast(path, vault_root).ok())
.collect();
notes.sort_by(|a, b| b.meta.modified.cmp(&a.meta.modified));
Ok(notes)
}
fn read_note_entry(path: &Path, vault_root: &Path) -> Result<NoteEntry, String> {
let raw = fs::read_to_string(path).map_err(|e| e.to_string())?;
read_note_entry_from_str(&raw, path, vault_root)
}
/// Fast version: reads only the first ~2KB of the file (enough for frontmatter + preview).
fn read_note_entry_fast(path: &Path, vault_root: &Path) -> Result<NoteEntry, String> {
let mut file = fs::File::open(path).map_err(|e| e.to_string())?;
let mut buf = vec![0u8; 2048];
let bytes_read = file.read(&mut buf).map_err(|e| e.to_string())?;
buf.truncate(bytes_read);
let raw = String::from_utf8_lossy(&buf);
read_note_entry_from_str(&raw, path, vault_root)
}
fn read_note_entry_from_str(
raw: &str,
path: &Path,
vault_root: &Path,
) -> Result<NoteEntry, String> {
let filename = path
.file_name()
.unwrap_or_default()
.to_string_lossy()
.to_string();
let (mut meta, content) = frontmatter::parse_note(raw, &filename);
// Use filesystem times if frontmatter didn't have them
if let Ok(fs_meta) = fs::metadata(path) {
if let Ok(modified) = fs_meta.modified() {
meta.modified = modified.into();
}
if let Ok(created) = fs_meta.created() {
meta.created = created.into();
}
}
let relative = path
.strip_prefix(vault_root)
.unwrap_or(path)
.to_string_lossy()
.to_string();
let preview = frontmatter::extract_preview(&content, 120);
Ok(NoteEntry {
path: path.to_string_lossy().to_string(),
relative_path: relative,
meta,
preview,
})
}
pub fn read_note(path: &str) -> Result<NoteContent, String> {
let p = Path::new(path);
let raw = fs::read_to_string(p).map_err(|e| e.to_string())?;
let filename = p
.file_name()
.unwrap_or_default()
.to_string_lossy()
.to_string();
let (meta, content) = frontmatter::parse_note(&raw, &filename);
Ok(NoteContent {
path: path.to_string(),
meta,
content,
raw,
})
}
pub fn save_note(path: &str, meta: &NoteMeta, body: &str) -> Result<(), String> {
let mut updated_meta = meta.clone();
updated_meta.modified = Utc::now();
let raw = frontmatter::update_note_raw(&updated_meta, body);
fs::write(path, raw).map_err(|e| e.to_string())?;
Ok(())
}
pub fn create_note(
vault_path: &str,
notebook_relative: Option<&str>,
title: &str,
) -> Result<NoteEntry, String> {
let dir = match notebook_relative {
Some(rel) => Path::new(vault_path).join(rel),
None => PathBuf::from(vault_path),
};
if !dir.exists() {
return Err("Notebook directory does not exist".to_string());
}
let filename = sanitize_filename(title);
let mut file_path = dir.join(format!("{}.md", filename));
// Deduplicate filename
let mut counter = 1;
while file_path.exists() {
file_path = dir.join(format!("{} {}.md", filename, counter));
counter += 1;
}
let now = Utc::now();
let meta = NoteMeta {
id: Uuid::new_v4().to_string(),
title: title.to_string(),
tags: Vec::new(),
pinned: false,
created: now,
modified: now,
};
let raw = frontmatter::update_note_raw(&meta, "\n");
fs::write(&file_path, raw).map_err(|e| e.to_string())?;
let vault_root = Path::new(vault_path);
let relative = file_path
.strip_prefix(vault_root)
.unwrap_or(&file_path)
.to_string_lossy()
.to_string();
Ok(NoteEntry {
path: file_path.to_string_lossy().to_string(),
relative_path: relative,
meta,
preview: String::new(),
})
}
pub fn create_notebook(
vault_path: &str,
parent_relative: Option<&str>,
name: &str,
) -> Result<NotebookEntry, String> {
let parent = match parent_relative {
Some(rel) => Path::new(vault_path).join(rel),
None => PathBuf::from(vault_path),
};
let dir_path = parent.join(name);
if dir_path.exists() {
return Err("Notebook already exists".to_string());
}
fs::create_dir_all(&dir_path).map_err(|e| e.to_string())?;
let vault_root = Path::new(vault_path);
let relative = dir_path
.strip_prefix(vault_root)
.unwrap_or(&dir_path)
.to_string_lossy()
.to_string();
Ok(NotebookEntry {
name: name.to_string(),
path: dir_path.to_string_lossy().to_string(),
relative_path: relative,
children: Vec::new(),
note_count: 0,
})
}
pub fn delete_note(vault_path: &str, note_path: &str) -> Result<(), String> {
let src = Path::new(note_path);
if !src.exists() {
return Err("Note does not exist".to_string());
}
let trash_dir = helixnotes_dir(vault_path).join("trash");
fs::create_dir_all(&trash_dir).map_err(|e| e.to_string())?;
let filename = src
.file_name()
.unwrap_or_default()
.to_string_lossy()
.to_string();
let timestamp = Utc::now().format("%Y%m%d%H%M%S%3f");
let trash_name = format!("{}_{}", timestamp, filename);
let dest = trash_dir.join(&trash_name);
fs::rename(src, dest).map_err(|e| e.to_string())?;
Ok(())
}
pub fn delete_notebook(vault_path: &str, notebook_path: &str) -> Result<(), String> {
let src = Path::new(notebook_path);
if !src.exists() {
return Err("Notebook does not exist".to_string());
}
let trash_dir = helixnotes_dir(vault_path).join("trash");
fs::create_dir_all(&trash_dir).map_err(|e| e.to_string())?;
let dirname = src
.file_name()
.unwrap_or_default()
.to_string_lossy()
.to_string();
let timestamp = Utc::now().format("%Y%m%d%H%M%S%3f");
let trash_name = format!("{}_{}", timestamp, dirname);
let dest = trash_dir.join(&trash_name);
fs::rename(src, dest).map_err(|e| e.to_string())?;
Ok(())
}
pub fn rename_note(path: &str, new_title: &str) -> Result<String, String> {
let src = Path::new(path);
if !src.exists() {
return Err("Note does not exist".to_string());
}
// Update frontmatter
let raw = fs::read_to_string(src).map_err(|e| e.to_string())?;
let filename = src
.file_name()
.unwrap_or_default()
.to_string_lossy()
.to_string();
let (mut meta, content) = frontmatter::parse_note(&raw, &filename);
meta.title = new_title.to_string();
meta.modified = Utc::now();
let updated = frontmatter::update_note_raw(&meta, &content);
// Rename file
let new_filename = sanitize_filename(new_title);
let new_path = src.parent().unwrap().join(format!("{}.md", new_filename));
fs::write(src, &updated).map_err(|e| e.to_string())?;
if new_path != src {
fs::rename(src, &new_path).map_err(|e| e.to_string())?;
}
Ok(new_path.to_string_lossy().to_string())
}
pub fn rename_notebook(path: &str, new_name: &str) -> Result<String, String> {
let src = Path::new(path);
if !src.exists() {
return Err("Notebook does not exist".to_string());
}
let new_path = src.parent().unwrap().join(new_name);
if new_path.exists() {
return Err("A notebook with that name already exists".to_string());
}
fs::rename(src, &new_path).map_err(|e| e.to_string())?;
Ok(new_path.to_string_lossy().to_string())
}
pub fn move_note(note_path: &str, dest_notebook: &str) -> Result<String, String> {
let src = Path::new(note_path);
if !src.exists() {
return Err("Note does not exist".to_string());
}
let dest_dir = Path::new(dest_notebook);
if !dest_dir.is_dir() {
return Err("Destination notebook does not exist".to_string());
}
let filename = src.file_name().unwrap_or_default();
let dest = dest_dir.join(filename);
fs::rename(src, &dest).map_err(|e| e.to_string())?;
Ok(dest.to_string_lossy().to_string())
}
pub fn get_trash_notes(vault_path: &str) -> Result<Vec<NoteEntry>, String> {
let trash_dir = helixnotes_dir(vault_path).join("trash");
if !trash_dir.exists() {
return Ok(Vec::new());
}
let vault_root = Path::new(vault_path);
let mut notes = Vec::new();
for entry in fs::read_dir(&trash_dir).map_err(|e| e.to_string())? {
let entry = entry.map_err(|e| e.to_string())?;
let path = entry.path();
if path.is_file() && path.extension().and_then(|x| x.to_str()) == Some("md") {
if let Ok(note) = read_note_entry(&path, vault_root) {
notes.push(note);
}
}
}
notes.sort_by(|a, b| b.meta.modified.cmp(&a.meta.modified));
Ok(notes)
}
pub fn restore_note(
vault_path: &str,
trash_path: &str,
dest_notebook: Option<&str>,
) -> Result<String, String> {
let src = Path::new(trash_path);
if !src.exists() {
return Err("Trashed note does not exist".to_string());
}
let dest_dir = match dest_notebook {
Some(nb) => PathBuf::from(nb),
None => PathBuf::from(vault_path),
};
// Strip timestamp prefix from trash filename (17-char with millis or 14-char legacy)
let filename = src.file_name().unwrap_or_default().to_string_lossy();
let original_name = if filename.len() > 18 && filename.chars().nth(17) == Some('_') {
&filename[18..]
} else if filename.len() > 15 && filename.chars().nth(14) == Some('_') {
&filename[15..]
} else {
&filename
};
let dest = dest_dir.join(original_name);
fs::rename(src, &dest).map_err(|e| e.to_string())?;
Ok(dest.to_string_lossy().to_string())
}
pub fn permanent_delete(path: &str) -> Result<(), String> {
let p = Path::new(path);
if p.is_dir() {
fs::remove_dir_all(p).map_err(|e| e.to_string())?;
} else {
fs::remove_file(p).map_err(|e| e.to_string())?;
}
Ok(())
}
pub fn empty_trash(vault_path: &str) -> Result<(), String> {
let trash_dir = helixnotes_dir(vault_path).join("trash");
if trash_dir.exists() {
fs::remove_dir_all(&trash_dir).map_err(|e| e.to_string())?;
fs::create_dir_all(&trash_dir).map_err(|e| e.to_string())?;
}
Ok(())
}
pub fn load_vault_state(vault_path: &str) -> Result<VaultState, String> {
let state_path = helixnotes_dir(vault_path).join("state.json");
if state_path.exists() {
let data = fs::read_to_string(&state_path).map_err(|e| e.to_string())?;
serde_json::from_str(&data).map_err(|e| e.to_string())
} else {
Ok(VaultState::default())
}
}
pub fn save_vault_state(vault_path: &str, state: &VaultState) -> Result<(), String> {
let state_path = helixnotes_dir(vault_path).join("state.json");
let data = serde_json::to_string_pretty(state).map_err(|e| e.to_string())?;
fs::write(&state_path, data).map_err(|e| e.to_string())?;
Ok(())
}
pub fn get_all_tags(vault_path: &str) -> Result<Vec<(String, usize)>, String> {
let hn_dir = helixnotes_dir(vault_path);
let md_files: Vec<PathBuf> = WalkDir::new(vault_path)
.into_iter()
.filter_map(|e| e.ok())
.filter(|e| {
let p = e.path();
p.is_file()
&& p.extension().and_then(|x| x.to_str()) == Some("md")
&& !is_hidden(p)
&& !p.starts_with(&hn_dir)
})
.map(|e| e.path().to_path_buf())
.collect();
// Read frontmatter in parallel (only need tags, so partial read is fine)
let all_tags: Vec<Vec<String>> = md_files
.par_iter()
.filter_map(|path| {
let mut file = fs::File::open(path).ok()?;
let mut buf = vec![0u8; 1024]; // Tags are in frontmatter, 1KB is plenty
let n = file.read(&mut buf).ok()?;
buf.truncate(n);
let raw = String::from_utf8_lossy(&buf);
let filename = path.file_name()?.to_string_lossy().to_string();
let (meta, _) = frontmatter::parse_note(&raw, &filename);
Some(meta.tags)
})
.collect();
let mut tag_counts: std::collections::HashMap<String, usize> = std::collections::HashMap::new();
for tags in all_tags {
for tag in tags {
*tag_counts.entry(tag).or_insert(0) += 1;
}
}
let mut tags: Vec<(String, usize)> = tag_counts.into_iter().collect();
tags.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0)));
Ok(tags)
}
pub fn save_image(vault_path: &str, name: &str, data: &[u8]) -> Result<String, String> {
save_attachment(vault_path, name, data)
}
pub fn save_attachment(vault_path: &str, name: &str, data: &[u8]) -> Result<String, String> {
let attachments_dir = helixnotes_dir(vault_path).join("attachments");
fs::create_dir_all(&attachments_dir).map_err(|e| e.to_string())?;
let timestamp = Utc::now().format("%Y%m%d%H%M%S");
let safe_name = sanitize_filename(name);
let filename = format!("{}_{}", timestamp, safe_name);
let dest = attachments_dir.join(&filename);
fs::write(&dest, data).map_err(|e| e.to_string())?;
// Return relative path from vault root
let relative = format!(".helixnotes/attachments/{}", filename);
Ok(relative)
}
pub fn load_notebook_icons(
vault_path: &str,
) -> Result<std::collections::HashMap<String, String>, String> {
let icons_path = helixnotes_dir(vault_path).join("notebook_icons.json");
if icons_path.exists() {
let data = fs::read_to_string(&icons_path).map_err(|e| e.to_string())?;
serde_json::from_str(&data).map_err(|e| e.to_string())
} else {
Ok(std::collections::HashMap::new())
}
}
pub fn set_notebook_icon(
vault_path: &str,
notebook_relative: &str,
icon_relative: Option<&str>,
) -> Result<(), String> {
let mut icons = load_notebook_icons(vault_path)?;
match icon_relative {
Some(icon) => {
icons.insert(notebook_relative.to_string(), icon.to_string());
}
None => {
icons.remove(notebook_relative);
}
}
let icons_path = helixnotes_dir(vault_path).join("notebook_icons.json");
let data = serde_json::to_string_pretty(&icons).map_err(|e| e.to_string())?;
fs::write(&icons_path, data).map_err(|e| e.to_string())?;
Ok(())
}
pub fn load_quick_access(vault_path: &str) -> Result<Vec<String>, String> {
let qa_path = helixnotes_dir(vault_path).join("quick_access.json");
if qa_path.exists() {
let data = fs::read_to_string(&qa_path).map_err(|e| e.to_string())?;
serde_json::from_str(&data).map_err(|e| e.to_string())
} else {
Ok(Vec::new())
}
}
pub fn save_quick_access(vault_path: &str, paths: &[String]) -> Result<(), String> {
let qa_path = helixnotes_dir(vault_path).join("quick_access.json");
let data = serde_json::to_string_pretty(paths).map_err(|e| e.to_string())?;
fs::write(&qa_path, data).map_err(|e| e.to_string())?;
Ok(())
}
pub fn add_quick_access(vault_path: &str, note_relative: &str) -> Result<(), String> {
let mut list = load_quick_access(vault_path)?;
if !list.contains(&note_relative.to_string()) {
list.push(note_relative.to_string());
save_quick_access(vault_path, &list)?;
}
Ok(())
}
pub fn remove_quick_access(vault_path: &str, note_relative: &str) -> Result<(), String> {
let mut list = load_quick_access(vault_path)?;
list.retain(|p| p != note_relative);
save_quick_access(vault_path, &list)?;
Ok(())
}
pub fn get_quick_access_notes(vault_path: &str) -> Result<Vec<NoteEntry>, String> {
let list = load_quick_access(vault_path)?;
let vault_root = Path::new(vault_path);
let mut notes = Vec::new();
for relative in &list {
let full_path = vault_root.join(relative);
if full_path.exists() {
if let Ok(entry) = read_note_entry(&full_path, vault_root) {
notes.push(entry);
}
}
}
Ok(notes)
}
pub fn sanitize_filename(name: &str) -> String {
name.chars()
.map(|c| match c {
'/' | '\\' | ':' | '*' | '?' | '"' | '<' | '>' | '|' => '-',
_ => c,
})
.collect::<String>()
.trim()
.to_string()
}
+73
View File
@@ -0,0 +1,73 @@
use notify::{Config, EventKind, RecommendedWatcher, RecursiveMode, Watcher};
use std::path::Path;
use std::sync::mpsc;
use std::time::Duration;
use tauri::{AppHandle, Emitter, Manager};
use crate::state::AppState;
use crate::types::FileEvent;
use crate::vault::operations::helixnotes_dir;
pub fn start_watcher(app: AppHandle, vault_path: String) -> Result<RecommendedWatcher, String> {
let (tx, rx) = mpsc::channel();
let mut watcher = RecommendedWatcher::new(
tx,
Config::default().with_poll_interval(Duration::from_secs(1)),
)
.map_err(|e| e.to_string())?;
watcher
.watch(Path::new(&vault_path), RecursiveMode::Recursive)
.map_err(|e| e.to_string())?;
let hn_dir = helixnotes_dir(&vault_path);
std::thread::spawn(move || {
while let Ok(result) = rx.recv() {
match result {
Ok(event) => {
// Skip all file events while importing
let state = app.state::<AppState>();
if state.importing.load(std::sync::atomic::Ordering::Relaxed) {
continue;
}
// Skip .helixnotes directory events
let dominated_by_hn = event.paths.iter().all(|p| p.starts_with(&hn_dir));
if dominated_by_hn {
continue;
}
// Only care about .md file events
let has_md = event.paths.iter().any(|p| {
p.extension().and_then(|x| x.to_str()) == Some("md") || p.is_dir()
});
if !has_md {
continue;
}
let event_type = match event.kind {
EventKind::Create(_) => "create",
EventKind::Modify(_) => "modify",
EventKind::Remove(_) => "remove",
_ => continue,
};
for path in &event.paths {
let fe = FileEvent {
event_type: event_type.to_string(),
path: path.to_string_lossy().to_string(),
};
let _ = app.emit("file-changed", &fe);
}
}
Err(e) => {
log::error!("File watcher error: {}", e);
}
}
}
});
Ok(watcher)
}
+60
View File
@@ -0,0 +1,60 @@
{
"$schema": "../node_modules/@tauri-apps/cli/config.schema.json",
"productName": "HelixNotes",
"version": "1.0.0",
"identifier": "com.helixnotes.app",
"build": {
"frontendDist": "../build",
"devUrl": "http://localhost:5173",
"beforeDevCommand": "pnpm dev",
"beforeBuildCommand": "pnpm build"
},
"app": {
"windows": [
{
"title": "HelixNotes",
"label": "main",
"width": 1200,
"height": 800,
"minWidth": 800,
"minHeight": 500,
"resizable": true,
"fullscreen": false,
"decorations": false
}
],
"security": {
"csp": "default-src 'self' 'unsafe-inline' 'unsafe-eval'; img-src 'self' asset: http://asset.localhost blob: data:; font-src 'self' data:; style-src 'self' 'unsafe-inline'",
"assetProtocol": {
"enable": true,
"scope": ["**/*", "/**", "**/.helixnotes/**"]
}
}
},
"plugins": {
"updater": {
"endpoints": ["https://helixnotes.com/latest.json"],
"pubkey": "dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IEFEODY0N0JDRjFEOTVGQTEKUldTaFg5bnh2RWVHclFEcW4wdjB2cWg0TWZNRkRxZThMYnZEV0pKV09YK1ZxcHBYOUJwT1pGT3UK"
}
},
"bundle": {
"active": true,
"targets": "all",
"createUpdaterArtifacts": "v1Compatible",
"icon": [
"icons/32x32.png",
"icons/128x128.png",
"icons/128x128@2x.png",
"icons/icon.icns",
"icons/icon.ico"
],
"linux": {
"deb": {
"depends": []
},
"appimage": {
"bundleMediaFramework": false
}
}
}
}
+151
View File
@@ -0,0 +1,151 @@
@import "tailwindcss";
@font-face {
font-family: "Inter";
src: local("Inter");
}
:root {
/* Light theme */
--bg-primary: #ffffff;
--bg-secondary: #f8f9fa;
--bg-tertiary: #f0f1f3;
--bg-hover: #e9ecef;
--bg-active: #dde1e6;
--bg-editor: #ffffff;
--text-primary: #1a1a2e;
--text-secondary: #495057;
--text-tertiary: #868e96;
--text-accent: #5b6abf;
--border-color: #e2e5e9;
--border-light: #f0f1f3;
--accent: #5b6abf;
--accent-hover: #4a59b0;
--accent-light: #eef0f9;
--danger: #e55353;
--danger-hover: #d43d3d;
--success: #40c057;
--warning: #fab005;
--shadow-sm: 0 1px 2px rgba(0, 0, 0, 0.05);
--shadow-md: 0 4px 12px rgba(0, 0, 0, 0.08);
--shadow-lg: 0 8px 24px rgba(0, 0, 0, 0.12);
--sidebar-width: 220px;
--notelist-width: 280px;
--panel-resize-handle: 4px;
}
:root.dark {
--bg-primary: #1a1b26;
--bg-secondary: #1f2029;
--bg-tertiary: #24253a;
--bg-hover: #2a2b3d;
--bg-active: #33354a;
--bg-editor: #1a1b26;
--text-primary: #cdd6f4;
--text-secondary: #a6adc8;
--text-tertiary: #6c7086;
--text-accent: #89b4fa;
--border-color: #2a2b3d;
--border-light: #24253a;
--accent: #89b4fa;
--accent-hover: #74a8f7;
--accent-light: #1e2640;
--danger: #f38ba8;
--danger-hover: #eba0ac;
--success: #a6e3a1;
--warning: #f9e2af;
--shadow-sm: 0 1px 2px rgba(0, 0, 0, 0.2);
--shadow-md: 0 4px 12px rgba(0, 0, 0, 0.3);
--shadow-lg: 0 8px 24px rgba(0, 0, 0, 0.4);
}
*,
*::before,
*::after {
margin: 0;
padding: 0;
box-sizing: border-box;
-webkit-user-select: none !important;
user-select: none !important;
}
html,
body {
height: 100%;
overflow: hidden;
font-family: var(
--editor-font-family,
"Inter",
-apple-system,
BlinkMacSystemFont,
"Segoe UI",
sans-serif
);
background: var(--bg-primary);
color: var(--text-primary);
font-size: var(--editor-font-size, 14px);
line-height: 1.5;
-webkit-font-smoothing: antialiased;
user-select: none;
}
/* Scrollbar styling */
::-webkit-scrollbar {
width: 6px;
height: 6px;
}
::-webkit-scrollbar-track {
background: transparent;
}
::-webkit-scrollbar-thumb {
background: var(--text-tertiary);
border-radius: 3px;
}
::-webkit-scrollbar-thumb:hover {
background: var(--text-secondary);
}
/* Selection */
::selection {
background: var(--accent);
color: white;
}
/* Focus ring */
:focus-visible {
outline: 2px solid var(--accent);
outline-offset: -2px;
}
/* Allow text selection in editor and source view */
.editor-content,
.editor-content *,
.source-editor {
-webkit-user-select: text !important;
user-select: text !important;
}
/* Transitions */
.transition-colors {
transition:
color 0.15s ease,
background-color 0.15s ease,
border-color 0.15s ease;
}
/* Panel resize handle */
.resize-handle {
width: var(--panel-resize-handle);
cursor: col-resize;
background: var(--border-color);
transition: background 0.15s ease;
flex-shrink: 0;
}
.resize-handle:hover,
.resize-handle.active {
background: var(--accent);
}
+13
View File
@@ -0,0 +1,13 @@
// See https://svelte.dev/docs/kit/types#app.d.ts
// for information about these interfaces
declare global {
namespace App {
// interface Error {}
// interface Locals {}
// interface PageData {}
// interface PageState {}
// interface Platform {}
}
}
export {};
+11
View File
@@ -0,0 +1,11 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
%sveltekit.head%
</head>
<body data-sveltekit-preload-data="hover">
<div style="display: contents">%sveltekit.body%</div>
</body>
</html>
+309
View File
@@ -0,0 +1,309 @@
import { invoke } from "@tauri-apps/api/core";
import type {
AppConfig,
NoteContent,
NoteEntry,
NoteMeta,
NotebookEntry,
NoteTitleEntry,
SearchResult,
VaultState,
VaultStats,
ImportResult,
BackupEntry,
VersionEntry,
} from "./types";
export async function openVault(path: string): Promise<void> {
return invoke("open_vault", { path });
}
export async function getAppConfig(): Promise<AppConfig> {
return invoke("get_app_config");
}
export async function setTheme(theme: string): Promise<void> {
return invoke("set_theme", { theme });
}
export async function setAccentColor(color: string): Promise<void> {
return invoke("set_accent_color", { color });
}
export async function setFontSize(size: number): Promise<void> {
return invoke("set_font_size", { size });
}
export async function setFontFamily(family: string): Promise<void> {
return invoke("set_font_family", { family });
}
export async function getNotebooks(): Promise<NotebookEntry[]> {
return invoke("get_notebooks");
}
export async function createNotebook(
parentRelative: string | null,
name: string,
): Promise<NotebookEntry> {
return invoke("create_notebook", { parentRelative, name });
}
export async function renameNotebook(
path: string,
newName: string,
): Promise<string> {
return invoke("rename_notebook", { path, newName });
}
export async function deleteNotebook(path: string): Promise<void> {
return invoke("delete_notebook", { path });
}
export async function getNotes(
notebookPath: string | null,
): Promise<NoteEntry[]> {
return invoke("get_notes", { notebookPath });
}
export async function readNote(path: string): Promise<NoteContent> {
return invoke("read_note", { path });
}
export async function saveNote(
path: string,
meta: NoteMeta,
body: string,
): Promise<void> {
return invoke("save_note", { path, meta, body });
}
export async function createNote(
notebookRelative: string | null,
title: string,
): Promise<NoteEntry> {
return invoke("create_note", { notebookRelative, title });
}
export async function renameNote(
path: string,
newTitle: string,
): Promise<string> {
return invoke("rename_note", { path, newTitle });
}
export async function deleteNote(path: string): Promise<void> {
return invoke("delete_note", { path });
}
export async function moveNote(
notePath: string,
destNotebook: string,
): Promise<string> {
return invoke("move_note", { notePath, destNotebook });
}
export async function getAllTags(): Promise<[string, number][]> {
return invoke("get_all_tags");
}
export async function getAllNoteTitles(): Promise<NoteTitleEntry[]> {
return invoke("get_all_note_titles");
}
export async function searchNotes(
query: string,
limit?: number,
): Promise<SearchResult[]> {
return invoke("search_notes", { query, limit });
}
export async function reindex(): Promise<void> {
return invoke("reindex");
}
export async function getTrash(): Promise<NoteEntry[]> {
return invoke("get_trash");
}
export async function restoreNote(
trashPath: string,
destNotebook: string | null,
): Promise<string> {
return invoke("restore_note", { trashPath, destNotebook });
}
export async function permanentDelete(path: string): Promise<void> {
return invoke("permanent_delete", { path });
}
export async function emptyTrash(): Promise<void> {
return invoke("empty_trash");
}
export async function loadVaultState(): Promise<VaultState> {
return invoke("load_vault_state");
}
export async function saveVaultState(vaultState: VaultState): Promise<void> {
return invoke("save_vault_state", { vaultState });
}
export async function saveImage(name: string, data: number[]): Promise<string> {
return invoke("save_image", { name, data });
}
export async function saveAttachment(
name: string,
data: number[],
): Promise<string> {
return invoke("save_attachment", { name, data });
}
export async function getNotebookIcons(): Promise<Record<string, string>> {
return invoke("get_notebook_icons");
}
export async function setNotebookIcon(
notebookRelative: string,
iconRelative: string | null,
): Promise<void> {
return invoke("set_notebook_icon", { notebookRelative, iconRelative });
}
export async function setGeneralSettings(
compactNotes: boolean,
timeFormat: string,
gpuAcceleration: boolean,
autostart: boolean,
pdfPreview: boolean,
pdfHeight: number,
titleMode: string,
hideTitleInBody: boolean,
defaultViewMode: boolean,
showTrayIcon: boolean,
enableWikiLinks: boolean,
): Promise<void> {
return invoke("set_general_settings", {
compactNotes,
timeFormat,
gpuAcceleration,
autostart,
pdfPreview,
pdfHeight,
titleMode,
hideTitleInBody,
defaultViewMode,
showTrayIcon,
enableWikiLinks,
});
}
export async function getQuickAccess(): Promise<NoteEntry[]> {
return invoke("get_quick_access");
}
export async function addQuickAccess(noteRelative: string): Promise<void> {
return invoke("add_quick_access", { noteRelative });
}
export async function removeQuickAccess(noteRelative: string): Promise<void> {
return invoke("remove_quick_access", { noteRelative });
}
export async function getVaultStats(): Promise<VaultStats> {
return invoke("get_vault_stats");
}
export async function importObsidian(): Promise<void> {
return invoke("import_obsidian");
}
export async function openFile(path: string): Promise<void> {
return invoke("open_file", { path });
}
export async function copyFileTo(
source: string,
destination: string,
): Promise<void> {
return invoke("copy_file_to", { source, destination });
}
// ── Backup ──
export async function createBackup(): Promise<void> {
return invoke("create_backup");
}
export async function listBackups(): Promise<BackupEntry[]> {
return invoke("list_backups");
}
export async function restoreBackup(backupPath: string): Promise<void> {
return invoke("restore_backup", { backupPath });
}
export async function deleteBackup(backupPath: string): Promise<void> {
return invoke("delete_backup", { backupPath });
}
export async function setBackupSettings(
enabled: boolean,
frequency: string,
maxCount: number,
location: string | null,
includeAttachments: boolean,
): Promise<void> {
return invoke("set_backup_settings", {
enabled,
frequency,
maxCount,
location,
includeAttachments,
});
}
// ── Version History ──
export async function getNoteVersions(noteId: string): Promise<VersionEntry[]> {
return invoke("get_note_versions", { noteId });
}
export async function getNoteVersionContent(
noteId: string,
timestamp: string,
): Promise<string> {
return invoke("get_note_version_content", { noteId, timestamp });
}
export async function createVersion(
path: string,
noteId: string,
): Promise<void> {
return invoke("create_version", { path, noteId });
}
// ── AI ──
export async function setAiSettings(
provider: string | null,
apiKey: string | null,
model: string,
writingStyle: string | null,
): Promise<void> {
return invoke("set_ai_settings", { provider, apiKey, model, writingStyle });
}
export async function testAiConnection(): Promise<void> {
return invoke("test_ai_connection");
}
export async function aiAsk(
action: string,
text: string,
customPrompt: string | null,
requestId: string,
): Promise<void> {
return invoke("ai_ask", { action, text, customPrompt, requestId });
}
+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="107" height="128" viewBox="0 0 107 128"><title>svelte-logo</title><path d="M94.157 22.819c-10.4-14.885-30.94-19.297-45.792-9.835L22.282 29.608A29.92 29.92 0 0 0 8.764 49.65a31.5 31.5 0 0 0 3.108 20.231 30 30 0 0 0-4.477 11.183 31.9 31.9 0 0 0 5.448 24.116c10.402 14.887 30.942 19.297 45.791 9.835l26.083-16.624A29.92 29.92 0 0 0 98.235 78.35a31.53 31.53 0 0 0-3.105-20.232 30 30 0 0 0 4.474-11.182 31.88 31.88 0 0 0-5.447-24.116" style="fill:#ff3e00"/><path d="M45.817 106.582a20.72 20.72 0 0 1-22.237-8.243 19.17 19.17 0 0 1-3.277-14.503 18 18 0 0 1 .624-2.435l.49-1.498 1.337.981a33.6 33.6 0 0 0 10.203 5.098l.97.294-.09.968a5.85 5.85 0 0 0 1.052 3.878 6.24 6.24 0 0 0 6.695 2.485 5.8 5.8 0 0 0 1.603-.704L69.27 76.28a5.43 5.43 0 0 0 2.45-3.631 5.8 5.8 0 0 0-.987-4.371 6.24 6.24 0 0 0-6.698-2.487 5.7 5.7 0 0 0-1.6.704l-9.953 6.345a19 19 0 0 1-5.296 2.326 20.72 20.72 0 0 1-22.237-8.243 19.17 19.17 0 0 1-3.277-14.502 17.99 17.99 0 0 1 8.13-12.052l26.081-16.623a19 19 0 0 1 5.3-2.329 20.72 20.72 0 0 1 22.237 8.243 19.17 19.17 0 0 1 3.277 14.503 18 18 0 0 1-.624 2.435l-.49 1.498-1.337-.98a33.6 33.6 0 0 0-10.203-5.1l-.97-.294.09-.968a5.86 5.86 0 0 0-1.052-3.878 6.24 6.24 0 0 0-6.696-2.485 5.8 5.8 0 0 0-1.602.704L37.73 51.72a5.42 5.42 0 0 0-2.449 3.63 5.79 5.79 0 0 0 .986 4.372 6.24 6.24 0 0 0 6.698 2.486 5.8 5.8 0 0 0 1.602-.704l9.952-6.342a19 19 0 0 1 5.295-2.328 20.72 20.72 0 0 1 22.237 8.242 19.17 19.17 0 0 1 3.277 14.503 18 18 0 0 1-8.13 12.053l-26.081 16.622a19 19 0 0 1-5.3 2.328" style="fill:#fff"/></svg>

After

Width:  |  Height:  |  Size: 1.5 KiB

+288
View File
@@ -0,0 +1,288 @@
<script lang="ts">
import { onMount, onDestroy } from 'svelte';
import { listen } from '@tauri-apps/api/event';
import Sidebar from './Sidebar.svelte';
import NoteList from './NoteList.svelte';
import Editor from './Editor.svelte';
import SearchPanel from './SearchPanel.svelte';
import CommandPalette from './CommandPalette.svelte';
import SettingsPanel from './SettingsPanel.svelte';
import InfoPanel from './InfoPanel.svelte';
import TitleBar from './TitleBar.svelte';
import ResizeHandle from './ResizeHandle.svelte';
import { getCurrentWindow } from '@tauri-apps/api/window';
import {
sidebarWidth,
notelistWidth,
sidebarCollapsed,
collapsedNotebooks,
showSearch,
showCommandPalette,
theme,
focusMode,
activeNote
} from '$lib/stores/app';
const appWindow = getCurrentWindow();
import { loadVaultState, saveVaultState } from '$lib/api';
import { debounce } from '$lib/utils/debounce';
import type { VaultState, FileEvent } from '$lib/types';
let sidebar: Sidebar;
let noteList: NoteList;
let editor: Editor;
let unlistenFileChange: (() => void) | null = null;
const persistState = debounce(async () => {
const state: VaultState = {
last_open_note: null,
sidebar_width: $sidebarWidth,
notelist_width: $notelistWidth,
sidebar_collapsed: $sidebarCollapsed,
collapsed_notebooks: $collapsedNotebooks
};
try {
await saveVaultState(state);
} catch (_) {}
}, 1000);
function handleSidebarResize(delta: number) {
$sidebarWidth = Math.max(160, Math.min(400, $sidebarWidth + delta));
persistState();
}
function handleNotelistResize(delta: number) {
$notelistWidth = Math.max(200, Math.min(500, $notelistWidth + delta));
persistState();
}
function handleNoteSelected(path: string, content: string) {
editor?.loadNote(path, content);
}
function handleViewChanged() {
noteList?.refresh(true);
}
async function createAndFocusNote() {
await noteList?.handleCreateNote();
editor?.focusTitle();
}
function handleKeydown(e: KeyboardEvent) {
if (e.ctrlKey && !e.shiftKey && e.key === 'n') {
e.preventDefault();
createAndFocusNote();
}
if (e.ctrlKey && e.shiftKey && e.key === 'N') {
e.preventDefault();
}
if (e.ctrlKey && e.key === 'f') {
e.preventDefault();
$showSearch = true;
}
if (e.ctrlKey && e.key === 'p') {
e.preventDefault();
$showCommandPalette = true;
}
if (e.ctrlKey && e.key === 's') {
e.preventDefault();
editor?.forceSave();
}
if (e.key === 'Escape') {
if ($focusMode) $focusMode = false;
else if ($showSearch) $showSearch = false;
else if ($showCommandPalette) $showCommandPalette = false;
}
}
function applyTheme(t: string) {
const root = document.documentElement;
root.classList.remove('dark');
if (t === 'dark' || (t === 'system' && window.matchMedia('(prefers-color-scheme: dark)').matches)) {
root.classList.add('dark');
}
}
$effect(() => {
applyTheme($theme);
});
$effect(() => {
$collapsedNotebooks;
persistState();
});
onMount(async () => {
try {
const state = await loadVaultState();
$sidebarWidth = state.sidebar_width;
$notelistWidth = state.notelist_width;
$sidebarCollapsed = state.sidebar_collapsed;
$collapsedNotebooks = state.collapsed_notebooks ?? [];
} catch (_) {}
applyTheme($theme);
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', () => {
if ($theme === 'system') applyTheme('system');
});
await sidebar?.refresh();
await noteList?.refresh();
unlistenFileChange = await listen<FileEvent>('file-changed', async () => {
await sidebar?.refresh();
await noteList?.refresh(true);
});
});
onDestroy(() => {
unlistenFileChange?.();
});
</script>
<svelte:window onkeydown={handleKeydown} />
<div class="app-shell">
{#if $focusMode}
<!-- svelte-ignore a11y_no_static_element_interactions -->
<div class="focus-topbar" onmousedown={(e) => { if (!(e.target as HTMLElement).closest('button')) appWindow.startDragging(); }}>
<span class="focus-title">{$activeNote?.meta.title || 'Untitled'}</span>
<div class="focus-controls">
<button class="focus-btn focus-active" onclick={() => ($focusMode = false)} title="Exit focus mode (Escape)">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="M8 3v3a2 2 0 01-2 2H3m18 0h-3a2 2 0 01-2-2V3m0 18v-3a2 2 0 012-2h3M3 16h3a2 2 0 012 2v3"/>
</svg>
</button>
<button class="focus-btn" onmousedown={(e) => e.stopPropagation()} onclick={() => appWindow.minimize()} title="Minimize">
<svg width="10" height="10" viewBox="0 0 10 10"><line x1="1" y1="5" x2="9" y2="5" stroke="currentColor" stroke-width="1.2" stroke-linecap="round"/></svg>
</button>
<button class="focus-btn" onmousedown={(e) => e.stopPropagation()} onclick={() => appWindow.toggleMaximize()} title="Maximize">
<svg width="10" height="10" viewBox="0 0 10 10"><rect x="1" y="1" width="8" height="8" rx="1" fill="none" stroke="currentColor" stroke-width="1.2"/></svg>
</button>
<button class="focus-btn focus-close" onmousedown={(e) => e.stopPropagation()} onclick={() => appWindow.close()} title="Close">
<svg width="10" height="10" viewBox="0 0 10 10"><line x1="1.5" y1="1.5" x2="8.5" y2="8.5" stroke="currentColor" stroke-width="1.2" stroke-linecap="round"/><line x1="8.5" y1="1.5" x2="1.5" y2="8.5" stroke="currentColor" stroke-width="1.2" stroke-linecap="round"/></svg>
</button>
</div>
</div>
{:else}
<TitleBar onNewNote={createAndFocusNote} />
{/if}
<div class="app-layout">
{#if !$focusMode}
<div class="sidebar-panel" style="width: {$sidebarCollapsed ? 44 : $sidebarWidth}px">
<Sidebar bind:this={sidebar} onViewChanged={handleViewChanged} />
</div>
{#if !$sidebarCollapsed}
<ResizeHandle onResize={handleSidebarResize} />
{/if}
<div class="notelist-panel" style="width: {$notelistWidth}px">
<NoteList bind:this={noteList} onNoteSelected={handleNoteSelected} onNoteMoved={() => sidebar?.refresh()} />
</div>
<ResizeHandle onResize={handleNotelistResize} />
{/if}
<div class="editor-panel">
<Editor bind:this={editor} />
</div>
</div>
</div>
<SearchPanel />
<CommandPalette />
<SettingsPanel />
<InfoPanel />
<style>
.app-shell {
display: flex;
flex-direction: column;
height: 100vh;
overflow: hidden;
}
.app-layout {
display: flex;
flex: 1;
overflow: hidden;
}
.sidebar-panel {
flex-shrink: 0;
height: 100%;
overflow: hidden;
}
.notelist-panel {
flex-shrink: 0;
height: 100%;
overflow: hidden;
}
.editor-panel {
flex: 1;
height: 100%;
overflow: hidden;
min-width: 300px;
}
.focus-topbar {
display: flex;
align-items: center;
height: 34px;
background: var(--bg-secondary);
border-bottom: 1px solid var(--border-light);
user-select: none;
flex-shrink: 0;
padding: 0 8px 0 16px;
}
.focus-title {
flex: 1;
font-size: 12px;
color: var(--text-tertiary);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
pointer-events: none;
}
.focus-controls {
display: flex;
align-items: center;
gap: 2px;
}
.focus-btn {
display: flex;
align-items: center;
justify-content: center;
width: 32px;
height: 26px;
border: none;
background: none;
color: var(--text-tertiary);
cursor: pointer;
border-radius: 4px;
transition: background 0.1s, color 0.1s;
}
.focus-btn.focus-active {
color: var(--text-accent);
background: var(--accent-light);
}
.focus-btn:hover {
background: var(--bg-hover);
color: var(--text-primary);
}
.focus-close:hover {
background: #e81123;
color: white;
}
</style>
+229
View File
@@ -0,0 +1,229 @@
<script lang="ts">
import { showCommandPalette, showSearch, theme, sourceMode } from '$lib/stores/app';
import { setTheme, reindex } from '$lib/api';
interface Command {
id: string;
label: string;
shortcut?: string;
action: () => void;
}
let query = $state('');
let selectedIndex = $state(0);
let inputEl = $state<HTMLInputElement>(null!);
const commands: Command[] = [
{
id: 'search',
label: 'Search Notes',
shortcut: 'Ctrl+F',
action: () => {
$showCommandPalette = false;
$showSearch = true;
}
},
{
id: 'theme-light',
label: 'Switch to Light Theme',
action: () => {
$theme = 'light';
setTheme('light');
applyTheme('light');
$showCommandPalette = false;
}
},
{
id: 'theme-dark',
label: 'Switch to Dark Theme',
action: () => {
$theme = 'dark';
setTheme('dark');
applyTheme('dark');
$showCommandPalette = false;
}
},
{
id: 'theme-system',
label: 'Use System Theme',
action: () => {
$theme = 'system';
setTheme('system');
applyTheme('system');
$showCommandPalette = false;
}
},
{
id: 'toggle-source',
label: 'Toggle Source/WYSIWYG Mode',
action: () => {
$sourceMode = !$sourceMode;
$showCommandPalette = false;
}
},
{
id: 'reindex',
label: 'Rebuild Search Index',
action: async () => {
await reindex();
$showCommandPalette = false;
}
}
];
let filteredCommands = $derived(
query.trim()
? commands.filter((c) => c.label.toLowerCase().includes(query.toLowerCase()))
: commands
);
$effect(() => {
if ($showCommandPalette && inputEl) {
query = '';
selectedIndex = 0;
setTimeout(() => inputEl?.focus(), 50);
}
});
function handleKeydown(e: KeyboardEvent) {
if (e.key === 'Escape') {
$showCommandPalette = false;
} else if (e.key === 'ArrowDown') {
e.preventDefault();
selectedIndex = Math.min(selectedIndex + 1, filteredCommands.length - 1);
} else if (e.key === 'ArrowUp') {
e.preventDefault();
selectedIndex = Math.max(selectedIndex - 1, 0);
} else if (e.key === 'Enter' && filteredCommands.length > 0) {
filteredCommands[selectedIndex].action();
}
}
function applyTheme(t: string) {
const root = document.documentElement;
root.classList.remove('dark');
if (t === 'dark' || (t === 'system' && window.matchMedia('(prefers-color-scheme: dark)').matches)) {
root.classList.add('dark');
}
}
</script>
{#if $showCommandPalette}
<!-- svelte-ignore a11y_no_static_element_interactions -->
<div class="palette-overlay" onclick={() => ($showCommandPalette = false)} onkeydown={handleKeydown}>
<!-- svelte-ignore a11y_no_static_element_interactions -->
<div class="palette-panel" onclick={(e) => e.stopPropagation()} onkeydown={(e) => e.stopPropagation()}>
<div class="palette-input-wrapper">
<svg width="16" height="16" viewBox="0 0 16 16" fill="var(--text-tertiary)">
<path d="M3 2v4.586l7 7L14.586 9l-7-7H3zm2 1a1 1 0 110 2 1 1 0 010-2z" />
</svg>
<input
bind:this={inputEl}
type="text"
placeholder="Type a command..."
bind:value={query}
onkeydown={handleKeydown}
/>
</div>
<div class="palette-results">
{#each filteredCommands as cmd, i (cmd.id)}
<button
class="cmd-item"
class:selected={i === selectedIndex}
onclick={() => cmd.action()}
onmouseenter={() => (selectedIndex = i)}
>
<span class="cmd-label">{cmd.label}</span>
{#if cmd.shortcut}
<span class="cmd-shortcut">{cmd.shortcut}</span>
{/if}
</button>
{/each}
</div>
</div>
</div>
{/if}
<style>
.palette-overlay {
position: fixed;
inset: 0;
background: rgba(0, 0, 0, 0.3);
display: flex;
align-items: flex-start;
justify-content: center;
padding-top: 20vh;
z-index: 2000;
}
.palette-panel {
background: var(--bg-primary);
border: 1px solid var(--border-color);
border-radius: 12px;
box-shadow: var(--shadow-lg);
width: 480px;
max-height: 360px;
overflow: hidden;
display: flex;
flex-direction: column;
}
.palette-input-wrapper {
display: flex;
align-items: center;
gap: 10px;
padding: 14px 16px;
border-bottom: 1px solid var(--border-light);
}
.palette-input-wrapper input {
flex: 1;
border: none;
background: none;
color: var(--text-primary);
font-size: 15px;
outline: none;
}
.palette-input-wrapper input::placeholder {
color: var(--text-tertiary);
}
.palette-results {
overflow-y: auto;
padding: 4px;
}
.cmd-item {
display: flex;
align-items: center;
justify-content: space-between;
width: 100%;
padding: 10px 14px;
border: none;
background: none;
border-radius: 8px;
cursor: pointer;
text-align: left;
transition: background 0.1s;
}
.cmd-item:hover,
.cmd-item.selected {
background: var(--bg-hover);
}
.cmd-label {
font-size: 14px;
color: var(--text-primary);
}
.cmd-shortcut {
font-size: 12px;
color: var(--text-tertiary);
background: var(--bg-tertiary);
padding: 2px 8px;
border-radius: 4px;
}
</style>
File diff suppressed because it is too large Load Diff
+522
View File
@@ -0,0 +1,522 @@
<script lang="ts">
import { onDestroy } from 'svelte';
import { getAllNoteTitles, readNote } from '$lib/api';
import { appConfig, activeNotePath } from '$lib/stores/app';
import type { NoteTitleEntry } from '$lib/types';
let { onclose, onnavigate }: {
onclose: () => void;
onnavigate: (path: string, title: string) => void;
} = $props();
let canvas = $state<HTMLCanvasElement>(null!);
let loading = $state(true);
interface GraphNode {
id: string;
title: string;
path: string;
x: number;
y: number;
vx: number;
vy: number;
links: string[]; // titles this note links to
}
interface GraphEdge {
source: string;
target: string;
}
let nodes: GraphNode[] = [];
let edges: GraphEdge[] = [];
let animFrame = 0;
let pan = { x: 0, y: 0 };
let zoom = 1;
let dragging: GraphNode | null = null;
let dragMoved = false;
let mouseDownPos = { x: 0, y: 0 };
let panning = false;
let panStart = { x: 0, y: 0 };
let hoveredNode: GraphNode | null = null;
const wikiLinkRegex = /\[\[([^\]]+)\]\]/g;
async function buildGraph() {
loading = true;
try {
const titles = await getAllNoteTitles();
const titleMap = new Map<string, NoteTitleEntry>();
for (const t of titles) {
titleMap.set(t.title.toLowerCase(), t);
}
// Create nodes
const w = canvas?.width ?? 800;
const h = canvas?.height ?? 600;
nodes = titles.map((t, i) => ({
id: t.title.toLowerCase(),
title: t.title,
path: t.path,
x: w / 2 + (Math.random() - 0.5) * Math.min(w, h) * 0.6,
y: h / 2 + (Math.random() - 0.5) * Math.min(w, h) * 0.6,
vx: 0,
vy: 0,
links: [],
}));
const nodeMap = new Map<string, GraphNode>();
for (const n of nodes) nodeMap.set(n.id, n);
// Read each note to extract [[wiki-links]]
const edgeSet = new Set<string>();
for (const node of nodes) {
try {
const content = await readNote(node.path);
const body = content.content || '';
let match;
wikiLinkRegex.lastIndex = 0;
while ((match = wikiLinkRegex.exec(body)) !== null) {
const linkTitle = match[1].trim().toLowerCase();
if (linkTitle !== node.id && nodeMap.has(linkTitle)) {
node.links.push(linkTitle);
const edgeKey = [node.id, linkTitle].sort().join('|');
if (!edgeSet.has(edgeKey)) {
edgeSet.add(edgeKey);
edges.push({ source: node.id, target: linkTitle });
}
}
}
} catch {
// Skip notes that can't be read
}
}
} catch (e) {
console.error('Failed to build graph:', e);
}
loading = false;
startSimulation();
}
function fitToView() {
if (!canvas || nodes.length === 0) return;
const w = canvas.width;
const h = canvas.height;
const padding = 60;
// Compute bounding box of all nodes
let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
for (const node of nodes) {
if (node.x < minX) minX = node.x;
if (node.y < minY) minY = node.y;
if (node.x > maxX) maxX = node.x;
if (node.y > maxY) maxY = node.y;
}
const graphW = maxX - minX || 1;
const graphH = maxY - minY || 1;
const centerGraphX = (minX + maxX) / 2;
const centerGraphY = (minY + maxY) / 2;
// Compute zoom to fit
zoom = Math.min(
(w - padding * 2) / graphW,
(h - padding * 2) / graphH,
2 // max zoom
);
zoom = Math.max(zoom, 0.2);
// Center the graph
pan.x = w / 2 - centerGraphX * zoom;
pan.y = h / 2 - centerGraphY * zoom;
}
function startSimulation() {
if (animFrame) cancelAnimationFrame(animFrame);
let iterations = 0;
const maxIterations = 300;
function tick() {
if (iterations >= maxIterations) {
fitToView();
draw();
return;
}
simulate();
draw();
iterations++;
animFrame = requestAnimationFrame(tick);
}
animFrame = requestAnimationFrame(tick);
}
function simulate() {
const nodeCount = nodes.length;
if (nodeCount === 0) return;
const w = canvas?.width ?? 800;
const h = canvas?.height ?? 600;
const centerX = w / 2;
const centerY = h / 2;
// Repulsion between all nodes
for (let i = 0; i < nodeCount; i++) {
for (let j = i + 1; j < nodeCount; j++) {
const a = nodes[i];
const b = nodes[j];
let dx = b.x - a.x;
let dy = b.y - a.y;
let dist = Math.sqrt(dx * dx + dy * dy) || 1;
const force = 800 / (dist * dist);
const fx = (dx / dist) * force;
const fy = (dy / dist) * force;
a.vx -= fx;
a.vy -= fy;
b.vx += fx;
b.vy += fy;
}
}
// Attraction along edges
for (const edge of edges) {
const a = nodes.find(n => n.id === edge.source);
const b = nodes.find(n => n.id === edge.target);
if (!a || !b) continue;
let dx = b.x - a.x;
let dy = b.y - a.y;
let dist = Math.sqrt(dx * dx + dy * dy) || 1;
const force = (dist - 100) * 0.01;
const fx = (dx / dist) * force;
const fy = (dy / dist) * force;
a.vx += fx;
a.vy += fy;
b.vx -= fx;
b.vy -= fy;
}
// Center gravity
for (const node of nodes) {
node.vx += (centerX - node.x) * 0.001;
node.vy += (centerY - node.y) * 0.001;
}
// Apply velocity with damping
for (const node of nodes) {
if (node === dragging) continue;
node.vx *= 0.85;
node.vy *= 0.85;
node.x += node.vx;
node.y += node.vy;
}
}
function draw() {
if (!canvas) return;
const ctx = canvas.getContext('2d');
if (!ctx) return;
const w = canvas.width;
const h = canvas.height;
ctx.clearRect(0, 0, w, h);
ctx.save();
ctx.translate(pan.x, pan.y);
ctx.scale(zoom, zoom);
const style = getComputedStyle(document.documentElement);
const borderColor = style.getPropertyValue('--border-color').trim() || '#444';
const textColor = style.getPropertyValue('--text-primary').trim() || '#eee';
const textSecondary = style.getPropertyValue('--text-tertiary').trim() || '#888';
const accent = style.getPropertyValue('--accent').trim() || '#7b9bd4';
const accentLight = style.getPropertyValue('--accent-light').trim() || 'rgba(123,155,212,0.15)';
// Draw edges
ctx.strokeStyle = borderColor;
ctx.lineWidth = 1;
ctx.globalAlpha = 0.4;
for (const edge of edges) {
const a = nodes.find(n => n.id === edge.source);
const b = nodes.find(n => n.id === edge.target);
if (!a || !b) continue;
ctx.beginPath();
ctx.moveTo(a.x, a.y);
ctx.lineTo(b.x, b.y);
ctx.stroke();
}
ctx.globalAlpha = 1;
// Determine active note
const activePath = $activeNotePath || '';
// Draw nodes
for (const node of nodes) {
const isActive = node.path === activePath;
const isHovered = node === hoveredNode;
const hasLinks = node.links.length > 0 || edges.some(e => e.source === node.id || e.target === node.id);
const radius = isActive ? 7 : hasLinks ? 5 : 3.5;
// Node circle
ctx.beginPath();
ctx.arc(node.x, node.y, radius, 0, Math.PI * 2);
if (isActive) {
ctx.fillStyle = accent;
} else if (isHovered) {
ctx.fillStyle = accent;
} else if (hasLinks) {
ctx.fillStyle = textSecondary;
} else {
ctx.fillStyle = borderColor;
}
ctx.fill();
// Label
if (isActive || isHovered || hasLinks) {
ctx.font = `${isActive || isHovered ? '12' : '10'}px -apple-system, BlinkMacSystemFont, sans-serif`;
ctx.fillStyle = isActive || isHovered ? textColor : textSecondary;
ctx.textAlign = 'center';
ctx.fillText(node.title, node.x, node.y - radius - 5);
}
}
ctx.restore();
}
function getNodeAt(clientX: number, clientY: number): GraphNode | null {
if (!canvas) return null;
const rect = canvas.getBoundingClientRect();
const x = (clientX - rect.left - pan.x) / zoom;
const y = (clientY - rect.top - pan.y) / zoom;
for (let i = nodes.length - 1; i >= 0; i--) {
const n = nodes[i];
const dx = n.x - x;
const dy = n.y - y;
if (dx * dx + dy * dy < 100) return n;
}
return null;
}
function handleMouseDown(e: MouseEvent) {
mouseDownPos = { x: e.clientX, y: e.clientY };
dragMoved = false;
const node = getNodeAt(e.clientX, e.clientY);
if (node) {
dragging = node;
} else {
panning = true;
panStart = { x: e.clientX - pan.x, y: e.clientY - pan.y };
}
}
function handleMouseMove(e: MouseEvent) {
const dx = e.clientX - mouseDownPos.x;
const dy = e.clientY - mouseDownPos.y;
if (Math.abs(dx) > 3 || Math.abs(dy) > 3) {
dragMoved = true;
}
if (dragging && dragMoved) {
const rect = canvas.getBoundingClientRect();
dragging.x = (e.clientX - rect.left - pan.x) / zoom;
dragging.y = (e.clientY - rect.top - pan.y) / zoom;
dragging.vx = 0;
dragging.vy = 0;
draw();
} else if (panning) {
pan.x = e.clientX - panStart.x;
pan.y = e.clientY - panStart.y;
draw();
} else if (!dragging) {
const node = getNodeAt(e.clientX, e.clientY);
if (node !== hoveredNode) {
hoveredNode = node;
if (canvas) canvas.style.cursor = node ? 'pointer' : 'grab';
draw();
}
}
}
function handleMouseUp(e: MouseEvent) {
if (dragging && !dragMoved) {
// It was a click, not a drag — navigate
const node = dragging;
dragging = null;
onnavigate(node.path, node.title);
return;
}
dragging = null;
panning = false;
}
function handleWheel(e: WheelEvent) {
e.preventDefault();
const rect = canvas.getBoundingClientRect();
const mx = e.clientX - rect.left;
const my = e.clientY - rect.top;
const oldZoom = zoom;
const delta = e.deltaY > 0 ? 0.9 : 1.1;
zoom = Math.max(0.2, Math.min(5, zoom * delta));
// Zoom toward mouse position
pan.x = mx - (mx - pan.x) * (zoom / oldZoom);
pan.y = my - (my - pan.y) * (zoom / oldZoom);
draw();
}
function handleKeydown(e: KeyboardEvent) {
if (e.key === 'Escape') onclose();
}
$effect(() => {
if (canvas) {
const rect = canvas.parentElement?.getBoundingClientRect();
if (rect) {
canvas.width = rect.width;
canvas.height = rect.height;
}
buildGraph();
}
});
onDestroy(() => {
if (animFrame) cancelAnimationFrame(animFrame);
});
</script>
<!-- svelte-ignore a11y_no_static_element_interactions -->
<div class="graph-overlay" onkeydown={handleKeydown}>
<div class="graph-panel">
<div class="graph-header">
<h3>Graph View</h3>
<div class="graph-stats">
{#if !loading}
{nodes.length} notes, {edges.length} connections
{/if}
</div>
<button class="graph-close" onclick={onclose}>
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<line x1="18" y1="6" x2="6" y2="18" /><line x1="6" y1="6" x2="18" y2="18" />
</svg>
</button>
</div>
<div class="graph-body">
{#if loading}
<div class="graph-loading">
<svg class="spinner" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<circle cx="12" cy="12" r="10" opacity="0.25" />
<path d="M12 2a10 10 0 019.95 9" />
</svg>
Building graph...
</div>
{/if}
<!-- svelte-ignore a11y_no_static_element_interactions -->
<canvas
bind:this={canvas}
class="graph-canvas"
onmousedown={handleMouseDown}
onmousemove={handleMouseMove}
onmouseup={handleMouseUp}
onwheel={handleWheel}
></canvas>
</div>
</div>
</div>
<style>
.graph-overlay {
position: fixed;
inset: 0;
background: rgba(0, 0, 0, 0.5);
display: flex;
align-items: center;
justify-content: center;
z-index: 2000;
}
.graph-panel {
background: var(--bg-primary);
border: 1px solid var(--border-color);
border-radius: 16px;
box-shadow: var(--shadow-lg);
width: 85vw;
height: 75vh;
max-width: 1200px;
max-height: 800px;
display: flex;
flex-direction: column;
overflow: hidden;
}
.graph-header {
display: flex;
align-items: center;
gap: 12px;
padding: 14px 20px;
border-bottom: 1px solid var(--border-light);
flex-shrink: 0;
}
.graph-header h3 {
font-size: 15px;
font-weight: 600;
color: var(--text-primary);
margin: 0;
}
.graph-stats {
flex: 1;
font-size: 12px;
color: var(--text-tertiary);
}
.graph-close {
background: none;
border: none;
color: var(--text-tertiary);
cursor: pointer;
padding: 4px;
border-radius: 6px;
display: flex;
align-items: center;
}
.graph-close:hover {
background: var(--bg-hover);
color: var(--text-primary);
}
.graph-body {
flex: 1;
position: relative;
overflow: hidden;
}
.graph-canvas {
width: 100%;
height: 100%;
cursor: grab;
}
.graph-canvas:active {
cursor: grabbing;
}
.graph-loading {
position: absolute;
inset: 0;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 12px;
color: var(--text-tertiary);
font-size: 13px;
z-index: 1;
}
.spinner {
animation: spin 0.8s linear infinite;
}
@keyframes spin {
from { transform: rotate(0deg); }
to { transform: rotate(360deg); }
}
</style>
+388
View File
@@ -0,0 +1,388 @@
<script lang="ts">
import { showInfo, appConfig } from '$lib/stores/app';
import { getVaultStats } from '$lib/api';
import { openUrl } from '@tauri-apps/plugin-opener';
import type { VaultStats } from '$lib/types';
let stats = $state<VaultStats | null>(null);
let activeTab = $state<'about' | 'shortcuts'>('shortcuts');
function close() {
$showInfo = false;
activeTab = 'shortcuts';
}
function openLink(url: string) {
openUrl(url).catch(console.error);
}
function formatSize(bytes: number): string {
if (bytes < 1024) return `${bytes} B`;
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
if (bytes < 1024 * 1024 * 1024) return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
return `${(bytes / (1024 * 1024 * 1024)).toFixed(2)} GB`;
}
$effect(() => {
if ($showInfo) {
getVaultStats().then((s) => { stats = s; }).catch(console.error);
} else {
stats = null;
}
});
</script>
{#if $showInfo}
<!-- svelte-ignore a11y_no_static_element_interactions -->
<div class="info-overlay" onclick={close} onkeydown={(e) => { if (e.key === 'Escape') close(); }}>
<!-- svelte-ignore a11y_no_static_element_interactions -->
<div class="info-panel" onclick={(e) => e.stopPropagation()}>
<div class="info-header">
<h2>Info</h2>
<button class="close-btn" onclick={close}>
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<line x1="18" y1="6" x2="6" y2="18" />
<line x1="6" y1="6" x2="18" y2="18" />
</svg>
</button>
</div>
<div class="info-body">
<div class="info-tabs">
<button class="info-tab" class:active={activeTab === 'shortcuts'} onclick={() => activeTab = 'shortcuts'}>Shortcuts</button>
<button class="info-tab" class:active={activeTab === 'about'} onclick={() => activeTab = 'about'}>About</button>
</div>
{#if activeTab === 'about'}
<div class="info-logo">
<svg width="48" height="48" viewBox="0 0 48 48" fill="none">
<rect width="48" height="48" rx="12" fill="var(--accent)" />
<circle cx="16" cy="16" r="3.5" fill="white" opacity="0.9" />
<circle cx="32" cy="16" r="3.5" fill="white" opacity="0.9" />
<circle cx="16" cy="32" r="3.5" fill="white" opacity="0.9" />
<circle cx="32" cy="32" r="3.5" fill="white" opacity="0.9" />
<line x1="19" y1="18" x2="29" y2="30" stroke="white" stroke-width="2" stroke-linecap="round" opacity="0.7" />
<line x1="29" y1="18" x2="19" y2="30" stroke="white" stroke-width="2" stroke-linecap="round" opacity="0.7" />
</svg>
</div>
<h3 class="app-name">HelixNotes</h3>
<p class="app-version">v1.0.0</p>
<p class="app-description">A local-first markdown note-taking app.</p>
{#if stats}
<div class="info-stats">
<div class="stat-row">
<span class="stat-label">Notes</span>
<span class="stat-value">{stats.total_notes}</span>
</div>
<div class="stat-row">
<span class="stat-label">Attachments</span>
<span class="stat-value">{stats.total_attachments}</span>
</div>
<div class="stat-row">
<span class="stat-label">Notes size</span>
<span class="stat-value">{formatSize(stats.notes_size)}</span>
</div>
<div class="stat-row">
<span class="stat-label">Attachments size</span>
<span class="stat-value">{formatSize(stats.attachments_size)}</span>
</div>
<div class="stat-row stat-total">
<span class="stat-label">Total vault size</span>
<span class="stat-value">{formatSize(stats.total_size)}</span>
</div>
</div>
{/if}
<div class="info-credits">
<p>Created by <strong>Yuri Karamian</strong></p>
<button class="info-link" onclick={() => openLink('https://helixnotes.com')}>
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<circle cx="12" cy="12" r="10" />
<line x1="2" y1="12" x2="22" y2="12" />
<path d="M12 2a15.3 15.3 0 014 10 15.3 15.3 0 01-4 10 15.3 15.3 0 01-4-10 15.3 15.3 0 014-10z" />
</svg>
helixnotes.com
</button>
</div>
{:else}
<div class="shortcuts-section">
<h4 class="shortcuts-group-title">Keyboard Shortcuts</h4>
<div class="shortcut-row"><span class="shortcut-desc">New note</span><span class="shortcut-keys"><kbd>Ctrl</kbd>+<kbd>N</kbd></span></div>
<div class="shortcut-row"><span class="shortcut-desc">Quick open</span><span class="shortcut-keys"><kbd>Ctrl</kbd>+<kbd>P</kbd></span></div>
<div class="shortcut-row"><span class="shortcut-desc">Search</span><span class="shortcut-keys"><kbd>Ctrl</kbd>+<kbd>F</kbd></span></div>
<div class="shortcut-row"><span class="shortcut-desc">Save</span><span class="shortcut-keys"><kbd>Ctrl</kbd>+<kbd>S</kbd></span></div>
<div class="shortcut-row"><span class="shortcut-desc">Bold</span><span class="shortcut-keys"><kbd>Ctrl</kbd>+<kbd>B</kbd></span></div>
<div class="shortcut-row"><span class="shortcut-desc">Italic</span><span class="shortcut-keys"><kbd>Ctrl</kbd>+<kbd>I</kbd></span></div>
<div class="shortcut-row"><span class="shortcut-desc">Underline</span><span class="shortcut-keys"><kbd>Ctrl</kbd>+<kbd>U</kbd></span></div>
<div class="shortcut-row"><span class="shortcut-desc">Undo</span><span class="shortcut-keys"><kbd>Ctrl</kbd>+<kbd>Z</kbd></span></div>
<div class="shortcut-row"><span class="shortcut-desc">Redo</span><span class="shortcut-keys"><kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>Z</kbd></span></div>
<div class="shortcut-row"><span class="shortcut-desc">Exit focus mode</span><span class="shortcut-keys"><kbd>Esc</kbd></span></div>
<h4 class="shortcuts-group-title">Editor Commands</h4>
<div class="shortcut-row"><span class="shortcut-desc">Slash commands</span><span class="shortcut-keys"><kbd>/</kbd></span></div>
<div class="shortcut-row command-detail"><span class="shortcut-desc">Headings, lists, code block, table, blockquote, collapsible section, horizontal rule</span></div>
<div class="shortcut-row"><span class="shortcut-desc">Wiki-link to note</span><span class="shortcut-keys"><kbd>[[</kbd></span></div>
<div class="shortcut-row command-detail"><span class="shortcut-desc">Type <kbd>[[</kbd> to search and link to another note. Close with <kbd>]]</kbd> or pick from the list.</span></div>
<h4 class="shortcuts-group-title">Editor Features</h4>
<div class="shortcut-row"><span class="shortcut-desc">Right-click in editor for formatting menu</span></div>
<div class="shortcut-row"><span class="shortcut-desc">Right-click a table cell for table options</span></div>
<div class="shortcut-row"><span class="shortcut-desc">Right-click a link to open, copy, edit, or remove</span></div>
<div class="shortcut-row"><span class="shortcut-desc">Click an image to resize (small / medium / full)</span></div>
<div class="shortcut-row"><span class="shortcut-desc">Drag & drop images, PDFs, or files into the editor</span></div>
</div>
{/if}
</div>
</div>
</div>
{/if}
<style>
.info-overlay {
position: fixed;
inset: 0;
background: rgba(0, 0, 0, 0.35);
display: flex;
align-items: center;
justify-content: center;
z-index: 2000;
}
.info-panel {
background: var(--bg-primary);
border: 1px solid var(--border-color);
border-radius: 16px;
box-shadow: var(--shadow-lg);
width: 500px;
max-height: 80vh;
overflow: hidden;
display: flex;
flex-direction: column;
}
.info-header {
display: flex;
align-items: center;
justify-content: space-between;
padding: 20px 24px 16px;
border-bottom: 1px solid var(--border-light);
}
.info-header h2 {
font-size: 18px;
font-weight: 600;
color: var(--text-primary);
}
.close-btn {
background: none;
border: none;
color: var(--text-tertiary);
cursor: pointer;
padding: 4px;
border-radius: 6px;
display: flex;
align-items: center;
}
.close-btn:hover {
background: var(--bg-hover);
color: var(--text-primary);
}
.info-body {
padding: 0 24px 32px;
display: flex;
flex-direction: column;
align-items: center;
text-align: center;
gap: 4px;
overflow-y: auto;
}
.info-tabs {
display: flex;
gap: 2px;
width: 100%;
padding: 16px 0 12px;
background: var(--bg-primary);
position: sticky;
top: 0;
z-index: 1;
}
.info-tab {
flex: 1;
background: none;
border: none;
border-bottom: 2px solid transparent;
color: var(--text-tertiary);
font-size: 13px;
font-weight: 500;
padding: 6px 8px;
cursor: pointer;
transition: color 0.15s, border-color 0.15s;
}
.info-tab:hover {
color: var(--text-secondary);
}
.info-tab.active {
color: var(--accent);
border-bottom-color: var(--accent);
}
.info-logo {
margin-bottom: 8px;
}
.app-name {
font-size: 20px;
font-weight: 700;
color: var(--text-primary);
}
.app-version {
font-size: 12px;
color: var(--text-tertiary);
}
.app-description {
font-size: 13px;
color: var(--text-secondary);
margin-top: 4px;
}
.info-stats {
width: 100%;
margin-top: 20px;
background: var(--bg-secondary);
border: 1px solid var(--border-light);
border-radius: 10px;
padding: 4px 0;
}
.stat-row {
display: flex;
justify-content: space-between;
padding: 7px 16px;
}
.stat-label {
font-size: 13px;
color: var(--text-secondary);
}
.stat-value {
font-size: 13px;
font-weight: 600;
color: var(--text-primary);
}
.stat-total {
border-top: 1px solid var(--border-light);
}
.stat-total .stat-value {
color: var(--accent);
}
.info-credits {
margin-top: 20px;
display: flex;
flex-direction: column;
align-items: center;
gap: 8px;
}
.info-credits p {
font-size: 13px;
color: var(--text-secondary);
}
.info-link {
display: inline-flex;
align-items: center;
gap: 6px;
background: none;
border: none;
color: var(--accent);
font-size: 13px;
cursor: pointer;
padding: 4px 10px;
border-radius: 6px;
transition: background 0.15s;
}
.info-link:hover {
background: var(--accent-light);
}
.shortcuts-section {
width: 100%;
text-align: left;
padding-top: 4px;
}
.shortcuts-group-title {
font-size: 11px;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.5px;
color: var(--text-tertiary);
margin: 16px 0 8px;
padding-bottom: 4px;
border-bottom: 1px solid var(--border-light);
}
.shortcuts-group-title:first-child {
margin-top: 0;
}
.shortcut-row {
display: flex;
justify-content: space-between;
align-items: center;
padding: 5px 0;
gap: 12px;
}
.shortcut-desc {
font-size: 13px;
color: var(--text-secondary);
}
.shortcut-keys {
display: flex;
align-items: center;
gap: 3px;
flex-shrink: 0;
font-size: 12px;
color: var(--text-tertiary);
}
.shortcut-keys kbd,
.shortcut-desc kbd {
display: inline-block;
background: var(--bg-secondary);
border: 1px solid var(--border-color);
border-radius: 4px;
padding: 1px 5px;
font-size: 11px;
font-family: inherit;
color: var(--text-primary);
line-height: 1.4;
}
.command-detail {
padding: 0 0 4px 8px;
}
.command-detail .shortcut-desc {
font-size: 12px;
color: var(--text-tertiary);
line-height: 1.4;
}
</style>
File diff suppressed because it is too large Load Diff
+28
View File
@@ -0,0 +1,28 @@
<script lang="ts">
let { onResize }: { onResize: (delta: number) => void } = $props();
let active = $state(false);
let startX = 0;
function onMouseDown(e: MouseEvent) {
e.preventDefault();
active = true;
startX = e.clientX;
window.addEventListener('mousemove', onMouseMove);
window.addEventListener('mouseup', onMouseUp);
}
function onMouseMove(e: MouseEvent) {
const delta = e.clientX - startX;
startX = e.clientX;
onResize(delta);
}
function onMouseUp() {
active = false;
window.removeEventListener('mousemove', onMouseMove);
window.removeEventListener('mouseup', onMouseUp);
}
</script>
<!-- svelte-ignore a11y_no_static_element_interactions -->
<div class="resize-handle" class:active onmousedown={onMouseDown}></div>
+383
View File
@@ -0,0 +1,383 @@
<script lang="ts">
import { showSearch, activeNote, activeNotePath, editorDirty, appConfig } from '$lib/stores/app';
import { searchNotes, readNote } from '$lib/api';
import { debounce } from '$lib/utils/debounce';
import type { SearchResult } from '$lib/types';
let query = $state('');
let results = $state<SearchResult[]>([]);
let selectedIndex = $state(0);
let inputEl = $state<HTMLInputElement>(null!);
let resultsEl = $state<HTMLDivElement>(null!);
const doSearch = debounce(async (q: string) => {
if (!q.trim()) {
results = [];
return;
}
try {
results = await searchNotes(q, 20);
selectedIndex = 0;
} catch (e) {
console.error('Search failed:', e);
results = [];
}
}, 150);
$effect(() => {
if ($showSearch && inputEl) {
query = '';
results = [];
selectedIndex = 0;
setTimeout(() => inputEl?.focus(), 50);
}
});
function handleInput() {
doSearch(query);
}
function scrollToSelected() {
if (!resultsEl) return;
const item = resultsEl.children[selectedIndex] as HTMLElement;
if (item) item.scrollIntoView({ block: 'nearest' });
}
function handleKeydown(e: KeyboardEvent) {
if (e.key === 'Escape') {
$showSearch = false;
} else if (e.key === 'ArrowDown') {
e.preventDefault();
selectedIndex = Math.min(selectedIndex + 1, results.length - 1);
scrollToSelected();
} else if (e.key === 'ArrowUp') {
e.preventDefault();
selectedIndex = Math.max(selectedIndex - 1, 0);
scrollToSelected();
} else if (e.key === 'Enter' && results.length > 0) {
openResult(results[selectedIndex]);
}
}
function getNotebook(path: string): string {
const vault = $appConfig?.active_vault;
if (!vault) return '';
let rel = path;
if (rel.startsWith(vault + '/')) rel = rel.substring(vault.length + 1);
const lastSlash = rel.lastIndexOf('/');
if (lastSlash <= 0) return '';
return rel.substring(0, lastSlash);
}
function highlightSnippet(snippet: string, q: string): string {
if (!q.trim() || !snippet) return escapeHtml(snippet);
const words = q.trim().split(/\s+/).filter(w => w.length > 1);
if (words.length === 0) return escapeHtml(snippet);
const escaped = escapeHtml(snippet);
const pattern = words.map(w => w.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')).join('|');
const re = new RegExp(`(${pattern})`, 'gi');
return escaped.replace(re, '<mark>$1</mark>');
}
function escapeHtml(str: string): string {
return str.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
}
async function openResult(result: SearchResult) {
try {
const content = await readNote(result.path);
$activeNote = content;
$activeNotePath = result.path;
$editorDirty = false;
$showSearch = false;
} catch (e) {
console.error('Failed to open search result:', e);
}
}
function close() {
$showSearch = false;
}
</script>
{#if $showSearch}
<!-- svelte-ignore a11y_no_static_element_interactions -->
<div class="search-overlay" onclick={close} onkeydown={handleKeydown}>
<!-- svelte-ignore a11y_no_static_element_interactions -->
<div class="search-panel" onclick={(e) => e.stopPropagation()} onkeydown={(e) => e.stopPropagation()}>
<div class="search-input-wrapper">
<svg class="search-icon" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<circle cx="11" cy="11" r="8" />
<line x1="21" y1="21" x2="16.65" y2="16.65" />
</svg>
<input
bind:this={inputEl}
type="text"
placeholder="Search notes..."
bind:value={query}
oninput={handleInput}
onkeydown={handleKeydown}
/>
<kbd class="search-esc">Esc</kbd>
</div>
{#if results.length > 0}
<div class="search-results" bind:this={resultsEl}>
{#each results as result, i}
<button
class="result-item"
class:selected={i === selectedIndex}
onclick={() => openResult(result)}
onmouseenter={() => (selectedIndex = i)}
>
<div class="result-header">
<svg class="result-icon" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="M14 2H6a2 2 0 00-2 2v16a2 2 0 002 2h12a2 2 0 002-2V8z" />
<polyline points="14 2 14 8 20 8" />
<line x1="16" y1="13" x2="8" y2="13" />
<line x1="16" y1="17" x2="8" y2="17" />
</svg>
<span class="result-title">{result.title}</span>
{#if getNotebook(result.path)}
<span class="result-notebook">{getNotebook(result.path)}</span>
{/if}
</div>
{#if result.snippet}
<span class="result-snippet">{@html highlightSnippet(result.snippet, query)}</span>
{/if}
</button>
{/each}
</div>
<div class="search-footer">
<span class="search-count">{results.length} result{results.length !== 1 ? 's' : ''}</span>
<span class="search-hints">
<kbd>&uarr;</kbd><kbd>&darr;</kbd> navigate
<kbd>&crarr;</kbd> open
</span>
</div>
{:else if query.trim()}
<div class="no-results">
<svg width="40" height="40" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" opacity="0.3">
<circle cx="11" cy="11" r="8" />
<line x1="21" y1="21" x2="16.65" y2="16.65" />
<line x1="8" y1="8" x2="14" y2="14" />
<line x1="14" y1="8" x2="8" y2="14" />
</svg>
<span>No results for "{query}"</span>
</div>
{:else}
<div class="search-empty">
<span>Type to search across all notes</span>
</div>
{/if}
</div>
</div>
{/if}
<style>
.search-overlay {
position: fixed;
inset: 0;
background: rgba(0, 0, 0, 0.4);
backdrop-filter: blur(4px);
-webkit-backdrop-filter: blur(4px);
display: flex;
align-items: flex-start;
justify-content: center;
padding-top: 15vh;
z-index: 2000;
animation: overlay-in 0.15s ease-out;
}
@keyframes overlay-in {
from { opacity: 0; }
to { opacity: 1; }
}
@keyframes panel-in {
from { opacity: 0; transform: translateY(-8px) scale(0.98); }
to { opacity: 1; transform: translateY(0) scale(1); }
}
.search-panel {
background: var(--bg-primary);
border: 1px solid var(--border-color);
border-radius: 14px;
box-shadow: 0 16px 48px rgba(0, 0, 0, 0.2), 0 0 0 1px rgba(255, 255, 255, 0.05) inset;
width: 620px;
max-height: 460px;
overflow: hidden;
display: flex;
flex-direction: column;
animation: panel-in 0.15s ease-out;
}
:global(:root.dark) .search-panel {
box-shadow: 0 16px 48px rgba(0, 0, 0, 0.5), 0 0 0 1px rgba(255, 255, 255, 0.06) inset;
}
.search-input-wrapper {
display: flex;
align-items: center;
gap: 12px;
padding: 16px 18px;
border-bottom: 1px solid var(--border-light);
}
.search-icon {
color: var(--text-tertiary);
flex-shrink: 0;
}
.search-input-wrapper input {
flex: 1;
border: none;
background: none;
color: var(--text-primary);
font-size: 17px;
outline: none;
font-weight: 400;
}
.search-input-wrapper input::placeholder {
color: var(--text-tertiary);
}
.search-esc {
font-size: 11px;
color: var(--text-tertiary);
background: var(--bg-tertiary);
border: 1px solid var(--border-color);
border-radius: 4px;
padding: 2px 6px;
flex-shrink: 0;
font-family: inherit;
line-height: 1.2;
}
.search-results {
overflow-y: auto;
padding: 6px;
flex: 1;
}
.result-item {
display: block;
width: 100%;
padding: 10px 12px;
border: none;
background: none;
border-radius: 8px;
cursor: pointer;
text-align: left;
transition: background 0.1s;
}
.result-item.selected {
background: var(--bg-hover);
}
.result-header {
display: flex;
align-items: center;
gap: 8px;
}
.result-icon {
color: var(--text-tertiary);
flex-shrink: 0;
opacity: 0.6;
}
.result-title {
font-weight: 500;
font-size: 14px;
color: var(--text-primary);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.result-notebook {
margin-left: auto;
font-size: 11px;
color: var(--text-tertiary);
background: var(--bg-tertiary);
padding: 1px 7px;
border-radius: 4px;
flex-shrink: 0;
max-width: 160px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.result-snippet {
display: block;
font-size: 12px;
color: var(--text-tertiary);
margin-top: 4px;
margin-left: 24px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
line-height: 1.4;
}
.result-snippet :global(mark) {
background: color-mix(in srgb, var(--accent) 25%, transparent);
color: var(--text-accent);
border-radius: 2px;
padding: 0 1px;
}
.search-footer {
display: flex;
align-items: center;
justify-content: space-between;
padding: 8px 18px;
border-top: 1px solid var(--border-light);
}
.search-count {
font-size: 12px;
color: var(--text-tertiary);
}
.search-hints {
font-size: 11px;
color: var(--text-tertiary);
display: flex;
align-items: center;
gap: 6px;
}
.search-hints kbd {
font-size: 11px;
color: var(--text-tertiary);
background: var(--bg-tertiary);
border: 1px solid var(--border-color);
border-radius: 4px;
padding: 0px 5px;
font-family: inherit;
line-height: 1.4;
}
.no-results {
padding: 32px 20px;
text-align: center;
color: var(--text-tertiary);
font-size: 14px;
display: flex;
flex-direction: column;
align-items: center;
gap: 10px;
}
.search-empty {
padding: 24px 20px;
text-align: center;
color: var(--text-tertiary);
font-size: 13px;
}
</style>
File diff suppressed because it is too large Load Diff
+762
View File
@@ -0,0 +1,762 @@
<script lang="ts">
import {
notebooks,
notes,
tags,
viewMode,
activeNotebook,
activeNotePath,
activeNote,
activeTag,
showSearch,
sidebarCollapsed,
showSettings,
showInfo,
notebookIcons,
appConfig,
quickAccessPaths,
collapsedNotebooks
} from '$lib/stores/app';
import { getNotebooks, getAllTags, createNotebook, deleteNotebook, renameNotebook, getNotebookIcons, setNotebookIcon, saveAttachment, getQuickAccess, addQuickAccess, removeQuickAccess, emptyTrash, moveNote, readNote, getNotes } from '$lib/api';
import { open as openDialog } from '@tauri-apps/plugin-dialog';
import { readFile } from '@tauri-apps/plugin-fs';
import { convertFileSrc } from '@tauri-apps/api/core';
import type { NotebookEntry } from '$lib/types';
let { onViewChanged = () => {} }: {
onViewChanged?: () => void;
} = $props();
let editingNotebook = $state<string | null>(null);
let editValue = $state('');
let newNotebookName = $state('');
let showNewNotebook = $state(false);
let dropTargetPath = $state<string | null>(null);
let contextMenu = $state<{ x: number; y: number; notebook: NotebookEntry } | null>(null);
let trashContextMenu = $state<{ x: number; y: number } | null>(null);
function toggleCollapse(path: string, e: MouseEvent) {
e.stopPropagation();
if ($collapsedNotebooks.includes(path)) {
$collapsedNotebooks = $collapsedNotebooks.filter(p => p !== path);
} else {
$collapsedNotebooks = [...$collapsedNotebooks, path];
}
}
export async function refresh() {
try {
$notebooks = await getNotebooks();
$tags = await getAllTags();
$notebookIcons = await getNotebookIcons();
const qaNotes = await getQuickAccess();
$quickAccessPaths = qaNotes.map(n => n.relative_path);
} catch (e) {
console.error('Failed to refresh sidebar:', e);
}
}
function selectAllNotes() {
$viewMode = 'all';
$activeNotebook = null;
$activeTag = null;
onViewChanged();
}
function selectNotebook(nb: NotebookEntry) {
$viewMode = 'notebook';
$activeNotebook = nb;
$activeTag = null;
onViewChanged();
}
function selectTag(tag: string) {
$viewMode = 'tag';
$activeTag = tag;
$activeNotebook = null;
onViewChanged();
}
function selectQuickAccess() {
$viewMode = 'quickaccess';
$activeNotebook = null;
$activeTag = null;
onViewChanged();
}
function selectTrash() {
$viewMode = 'trash';
$activeNotebook = null;
$activeTag = null;
onViewChanged();
}
async function handleCreateNotebook() {
if (!newNotebookName.trim()) return;
try {
await createNotebook(null, newNotebookName.trim());
newNotebookName = '';
showNewNotebook = false;
await refresh();
} catch (e) {
console.error('Failed to create notebook:', e);
}
}
async function handleRename(nb: NotebookEntry) {
if (!editValue.trim() || editValue.trim() === nb.name) {
editingNotebook = null;
return;
}
try {
await renameNotebook(nb.path, editValue.trim());
editingNotebook = null;
await refresh();
} catch (e) {
console.error('Failed to rename:', e);
}
}
async function handleDelete(nb: NotebookEntry) {
contextMenu = null;
try {
await deleteNotebook(nb.path);
if ($activeNotebook?.path === nb.path) {
selectAllNotes();
}
await refresh();
} catch (e) {
console.error('Failed to delete:', e);
}
}
async function handleNoteDrop(e: DragEvent, nb: NotebookEntry) {
e.preventDefault();
dropTargetPath = null;
const notePath = e.dataTransfer?.getData('text/plain');
if (!notePath) return;
// Don't move if already in this notebook
const noteDir = notePath.substring(0, notePath.lastIndexOf('/'));
if (noteDir === nb.path) return;
try {
const newPath = await moveNote(notePath, nb.path);
$notes = $notes.filter(n => n.path !== notePath);
if ($activeNotePath === notePath) {
$activeNotePath = newPath;
$activeNote = await readNote(newPath);
}
await refresh();
} catch (e) {
console.error('Failed to move note:', e);
}
}
function startRename(nb: NotebookEntry) {
contextMenu = null;
editingNotebook = nb.path;
editValue = nb.name;
}
async function handleSetIcon(nb: NotebookEntry) {
contextMenu = null;
try {
const selected = await openDialog({
multiple: false,
filters: [{ name: 'Images', extensions: ['png', 'jpg', 'jpeg', 'gif', 'svg', 'webp', 'ico'] }]
});
if (!selected) return;
const filePath = typeof selected === 'string' ? selected : selected;
// Read the file and save as attachment
const data = await readFile(filePath as string);
const fileName = (filePath as string).split('/').pop() || 'icon.png';
const iconRelative = await saveAttachment(`notebook-icon-${fileName}`, Array.from(data));
await setNotebookIcon(nb.relative_path, iconRelative);
$notebookIcons = await getNotebookIcons();
} catch (e) {
console.error('Failed to set notebook icon:', e);
}
}
async function handleRemoveIcon(nb: NotebookEntry) {
contextMenu = null;
try {
await setNotebookIcon(nb.relative_path, null);
$notebookIcons = await getNotebookIcons();
} catch (e) {
console.error('Failed to remove notebook icon:', e);
}
}
function getNotebookIconSrc(nb: NotebookEntry): string | null {
const iconPath = $notebookIcons[nb.relative_path];
if (!iconPath) return null;
const vaultRoot = $appConfig?.active_vault;
if (!vaultRoot) return null;
return convertFileSrc(`${vaultRoot}/${iconPath}`);
}
function onContextMenu(e: MouseEvent, nb: NotebookEntry) {
e.preventDefault();
contextMenu = { x: e.clientX, y: e.clientY, notebook: nb };
}
function closeContextMenu() {
contextMenu = null;
}
function onTrashContextMenu(e: MouseEvent) {
e.preventDefault();
e.stopPropagation();
trashContextMenu = { x: e.clientX, y: e.clientY };
}
async function handleEmptyTrash() {
trashContextMenu = null;
try {
await emptyTrash();
// Clear selection and refresh the list (with cache invalidation)
$activeNote = null;
$activeNotePath = '';
onViewChanged();
} catch (e) {
console.error('Failed to empty trash:', e);
}
}
// Close context menu on click outside
function handleWindowClick() {
if (contextMenu) contextMenu = null;
if (trashContextMenu) trashContextMenu = null;
}
</script>
<svelte:window onclick={handleWindowClick} />
<aside class="sidebar" class:collapsed={$sidebarCollapsed}>
<div class="sidebar-header">
<button class="collapse-btn" onclick={() => ($sidebarCollapsed = !$sidebarCollapsed)} title="Toggle sidebar">
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
{#if $sidebarCollapsed}
<polyline points="9 6 15 12 9 18" />
{:else}
<polyline points="15 6 9 12 15 18" />
{/if}
</svg>
</button>
{#if !$sidebarCollapsed}
<button class="icon-btn" onclick={() => ($showSearch = true)} title="Search (Ctrl+F)">
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<circle cx="11" cy="11" r="8" />
<line x1="21" y1="21" x2="16.65" y2="16.65" />
</svg>
</button>
{/if}
</div>
{#if !$sidebarCollapsed}
<nav class="sidebar-nav">
<button
class="nav-item"
class:active={$viewMode === 'all'}
onclick={selectAllNotes}
>
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="M16 3H5a2 2 0 00-2 2v14a2 2 0 002 2h14a2 2 0 002-2V8z" />
<polyline points="14 3 14 8 21 8" />
</svg>
<span>All Notes</span>
</button>
<button
class="nav-item"
class:active={$viewMode === 'quickaccess'}
onclick={selectQuickAccess}
>
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2" />
</svg>
<span>Quick Access</span>
</button>
<button
class="nav-item"
class:active={$viewMode === 'trash'}
onclick={selectTrash}
oncontextmenu={onTrashContextMenu}
>
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<polyline points="3 6 5 6 21 6" /><path d="M19 6v14a2 2 0 01-2 2H7a2 2 0 01-2-2V6m3 0V4a2 2 0 012-2h4a2 2 0 012 2v2" /><line x1="10" y1="11" x2="10" y2="17" /><line x1="14" y1="11" x2="14" y2="17" />
</svg>
<span>Trash</span>
</button>
</nav>
<div class="section">
<div class="section-header">
<span class="section-title">Notebooks</span>
<button class="icon-btn-sm" onclick={() => (showNewNotebook = !showNewNotebook)} title="New notebook">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<line x1="12" y1="5" x2="12" y2="19" /><line x1="5" y1="12" x2="19" y2="12" />
</svg>
</button>
</div>
{#if showNewNotebook}
<div class="new-notebook-input">
<input
type="text"
bind:value={newNotebookName}
placeholder="Notebook name..."
onkeydown={(e) => {
if (e.key === 'Enter') handleCreateNotebook();
if (e.key === 'Escape') { showNewNotebook = false; newNotebookName = ''; }
}}
/>
</div>
{/if}
<div class="notebook-list">
{#each $notebooks as nb (nb.path)}
{@render notebookItem(nb, 0)}
{/each}
</div>
</div>
{#if $tags.length > 0}
<div class="section">
<div class="section-header">
<span class="section-title">Tags</span>
</div>
<div class="tag-list">
{#each $tags as [tag, count]}
<button
class="tag-item"
class:active={$viewMode === 'tag' && $activeTag === tag}
onclick={() => selectTag(tag)}
>
<span class="tag-hash">#</span>
<span class="tag-name">{tag}</span>
<span class="tag-count">{count}</span>
</button>
{/each}
</div>
</div>
{/if}
<div class="sidebar-footer">
<button class="icon-btn" onclick={() => ($showInfo = true)} title="Info">
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<circle cx="12" cy="12" r="10" />
<line x1="12" y1="16" x2="12" y2="12" />
<line x1="12" y1="8" x2="12.01" y2="8" />
</svg>
</button>
<div class="sidebar-footer-right">
<button class="icon-btn" onclick={() => ($showSettings = true)} title="Settings">
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<circle cx="12" cy="12" r="3" />
<path d="M19.4 15a1.65 1.65 0 00.33 1.82l.06.06a2 2 0 010 2.83 2 2 0 01-2.83 0l-.06-.06a1.65 1.65 0 00-1.82-.33 1.65 1.65 0 00-1 1.51V21a2 2 0 01-4 0v-.09A1.65 1.65 0 009 19.4a1.65 1.65 0 00-1.82.33l-.06.06a2 2 0 01-2.83-2.83l.06-.06A1.65 1.65 0 004.68 15a1.65 1.65 0 00-1.51-1H3a2 2 0 010-4h.09A1.65 1.65 0 004.6 9a1.65 1.65 0 00-.33-1.82l-.06-.06a2 2 0 012.83-2.83l.06.06A1.65 1.65 0 009 4.68a1.65 1.65 0 001-1.51V3a2 2 0 014 0v.09a1.65 1.65 0 001 1.51 1.65 1.65 0 001.82-.33l.06-.06a2 2 0 012.83 2.83l-.06.06A1.65 1.65 0 0019.4 9a1.65 1.65 0 001.51 1H21a2 2 0 010 4h-.09a1.65 1.65 0 00-1.51 1z" />
</svg>
</button>
</div>
</div>
{/if}
</aside>
{#if contextMenu}
<!-- svelte-ignore a11y_no_static_element_interactions -->
<div class="context-menu" style="left: {contextMenu.x}px; top: {contextMenu.y}px" onmousedown={(e) => e.stopPropagation()}>
<button onclick={() => startRename(contextMenu!.notebook)}>
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M11 4H4a2 2 0 00-2 2v14a2 2 0 002 2h14a2 2 0 002-2v-7" /><path d="M18.5 2.5a2.121 2.121 0 013 3L12 15l-4 1 1-4 9.5-9.5z" /></svg>
Rename
</button>
<button onclick={() => handleSetIcon(contextMenu!.notebook)}>
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10" /><path d="M8 14s1.5 2 4 2 4-2 4-2" /><line x1="9" y1="9" x2="9.01" y2="9" /><line x1="15" y1="9" x2="15.01" y2="9" /></svg>
Set Icon
</button>
{#if $notebookIcons[contextMenu.notebook.relative_path]}
<button onclick={() => handleRemoveIcon(contextMenu!.notebook)}>
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10" /><line x1="15" y1="9" x2="9" y2="15" /><line x1="9" y1="9" x2="15" y2="15" /></svg>
Remove Icon
</button>
{/if}
<button class="danger" onclick={() => handleDelete(contextMenu!.notebook)}>
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 6 5 6 21 6" /><path d="M19 6l-1 14a2 2 0 01-2 2H8a2 2 0 01-2-2L5 6" /><path d="M10 11v6" /><path d="M14 11v6" /><path d="M9 6V4a1 1 0 011-1h4a1 1 0 011 1v2" /></svg>
Delete
</button>
</div>
{/if}
{#if trashContextMenu}
<!-- svelte-ignore a11y_no_static_element_interactions -->
<div class="context-menu" style="left: {trashContextMenu.x}px; top: {trashContextMenu.y}px" onmousedown={(e) => e.stopPropagation()}>
<button class="danger" onclick={handleEmptyTrash}>
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<polyline points="3 6 5 6 21 6" /><path d="M19 6v14a2 2 0 01-2 2H7a2 2 0 01-2-2V6m3 0V4a2 2 0 012-2h4a2 2 0 012 2v2" /><line x1="10" y1="11" x2="10" y2="17" /><line x1="14" y1="11" x2="14" y2="17" />
</svg>
Empty Trash
</button>
</div>
{/if}
{#snippet notebookItem(nb: NotebookEntry, depth: number)}
{@const hasChildren = nb.children.length > 0}
{@const isCollapsed = $collapsedNotebooks.includes(nb.path)}
{@const iconSrc = getNotebookIconSrc(nb)}
{#if editingNotebook === nb.path}
<div class="notebook-item" style="padding-left: {8 + depth * 16}px">
<input
type="text"
class="rename-input"
bind:value={editValue}
onkeydown={(e) => {
if (e.key === 'Enter') handleRename(nb);
if (e.key === 'Escape') editingNotebook = null;
}}
onblur={() => handleRename(nb)}
/>
</div>
{:else}
<button
class="notebook-item"
class:active={$viewMode === 'notebook' && $activeNotebook?.path === nb.path}
class:drop-target={dropTargetPath === nb.path}
style="padding-left: {8 + depth * 16}px"
onclick={() => selectNotebook(nb)}
oncontextmenu={(e) => onContextMenu(e, nb)}
ondragover={(e) => { e.preventDefault(); e.dataTransfer!.dropEffect = 'move'; dropTargetPath = nb.path; }}
ondragleave={() => { if (dropTargetPath === nb.path) dropTargetPath = null; }}
ondrop={(e) => handleNoteDrop(e, nb)}
>
{#if hasChildren}
<!-- svelte-ignore a11y_no_static_element_interactions -->
<span class="chevron" class:collapsed={isCollapsed} onclick={(e) => toggleCollapse(nb.path, e)} onkeydown={(e) => { if (e.key === 'Enter') toggleCollapse(nb.path, e); }}>
<svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<polyline points="6 9 12 15 18 9" />
</svg>
</span>
{:else}
<span class="chevron-spacer"></span>
{/if}
{#if iconSrc}
<img class="notebook-icon" src={iconSrc} alt="" />
{:else}
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" opacity="0.6">
<path d="M22 19a2 2 0 01-2 2H4a2 2 0 01-2-2V5a2 2 0 012-2h5l2 3h9a2 2 0 012 2z" />
</svg>
{/if}
<span class="notebook-name">{nb.name} <span class="notebook-count">{nb.note_count}</span></span>
</button>
{/if}
{#if hasChildren && !isCollapsed}
{#each nb.children as child (child.path)}
{@render notebookItem(child, depth + 1)}
{/each}
{/if}
{/snippet}
<style>
.sidebar {
display: flex;
flex-direction: column;
height: 100%;
background: var(--bg-secondary);
border-right: 1px solid var(--border-color);
overflow: hidden;
min-width: 44px;
user-select: none;
}
.sidebar.collapsed {
width: 44px !important;
min-width: 44px;
max-width: 44px;
}
.sidebar-header {
display: flex;
align-items: center;
justify-content: space-between;
padding: 10px 8px;
border-bottom: 1px solid var(--border-light);
flex-shrink: 0;
}
.sidebar-nav {
padding: 8px 6px;
flex-shrink: 0;
}
.nav-item {
display: flex;
align-items: center;
gap: 8px;
width: 100%;
padding: 6px 10px;
border: none;
background: none;
border-radius: 6px;
color: var(--text-secondary);
font-size: inherit;
cursor: pointer;
transition: all 0.1s;
}
.nav-item:hover {
background: var(--bg-hover);
color: var(--text-primary);
}
.nav-item.active {
background: var(--accent-light);
color: var(--text-accent);
}
.section {
flex: 1;
overflow-y: auto;
padding: 4px 0;
}
.section-header {
display: flex;
align-items: center;
justify-content: space-between;
padding: 8px 12px 4px;
}
.section-title {
font-size: 11px;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.05em;
color: var(--text-tertiary);
}
.icon-btn, .icon-btn-sm {
background: none;
border: none;
color: var(--text-tertiary);
cursor: pointer;
padding: 4px;
border-radius: 4px;
display: flex;
align-items: center;
justify-content: center;
}
.icon-btn:hover, .icon-btn-sm:hover {
background: var(--bg-hover);
color: var(--text-primary);
}
.collapse-btn {
background: none;
border: none;
color: var(--text-tertiary);
cursor: pointer;
padding: 4px;
border-radius: 4px;
display: flex;
align-items: center;
}
.collapse-btn:hover {
background: var(--bg-hover);
color: var(--text-primary);
}
.new-notebook-input {
padding: 2px 8px;
}
.new-notebook-input input, .rename-input {
width: 100%;
padding: 4px 8px;
border: 1px solid var(--accent);
border-radius: 4px;
background: var(--bg-primary);
color: var(--text-primary);
font-size: inherit;
outline: none;
}
.notebook-list {
padding: 0 2px;
}
.notebook-item {
display: flex;
align-items: center;
gap: 6px;
width: 100%;
padding: 5px 8px;
border: none;
background: none;
border-radius: 6px;
color: var(--text-secondary);
font-size: inherit;
cursor: pointer;
transition: all 0.1s;
}
.notebook-item:hover {
background: var(--bg-hover);
}
.notebook-item.active {
background: var(--accent-light);
color: var(--text-accent);
}
.notebook-item.drop-target {
background: color-mix(in srgb, var(--accent) 20%, transparent);
outline: 2px dashed var(--accent);
outline-offset: -2px;
border-radius: 6px;
}
.chevron {
display: flex;
align-items: center;
justify-content: center;
width: 14px;
height: 14px;
flex-shrink: 0;
color: var(--text-tertiary);
transition: transform 0.15s ease;
cursor: pointer;
border-radius: 3px;
}
.chevron:hover {
color: var(--text-primary);
}
.chevron.collapsed {
transform: rotate(-90deg);
}
.chevron-spacer {
width: 14px;
flex-shrink: 0;
}
.notebook-icon {
width: 20px;
height: 20px;
border-radius: 3px;
object-fit: cover;
flex-shrink: 0;
}
.notebook-name {
flex: 1;
text-align: left;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.notebook-count {
font-size: 11px;
color: var(--text-tertiary);
margin-left: 2px;
}
.tag-list {
padding: 0 4px;
}
.tag-item {
display: flex;
align-items: center;
gap: 4px;
width: 100%;
padding: 4px 12px;
border: none;
background: none;
border-radius: 6px;
color: var(--text-secondary);
font-size: inherit;
cursor: pointer;
transition: all 0.1s;
}
.tag-item:hover {
background: var(--bg-hover);
}
.tag-item.active {
background: var(--accent-light);
color: var(--text-accent);
}
.tag-hash {
color: var(--text-tertiary);
font-weight: 600;
}
.tag-name {
flex: 1;
text-align: left;
}
.tag-count {
font-size: 11px;
color: var(--text-tertiary);
}
.sidebar-footer {
padding: 8px;
border-top: 1px solid var(--border-light);
display: flex;
justify-content: space-between;
align-items: center;
flex-shrink: 0;
}
.sidebar-footer-right {
display: flex;
gap: 4px;
}
.context-menu {
position: fixed;
background: var(--bg-primary);
border: 1px solid var(--border-color);
border-radius: 8px;
box-shadow: var(--shadow-md);
padding: 4px;
z-index: 1000;
min-width: 140px;
}
.context-menu button {
display: flex;
align-items: center;
gap: 8px;
width: 100%;
padding: 6px 12px;
border: none;
background: none;
color: var(--text-primary);
font-size: 13px;
cursor: pointer;
border-radius: 4px;
text-align: left;
}
.context-menu button:hover {
background: var(--bg-hover);
}
.context-menu button.danger {
color: var(--danger);
}
.context-menu button.danger:hover {
background: color-mix(in srgb, var(--danger) 10%, transparent);
}
</style>
+222
View File
@@ -0,0 +1,222 @@
<script lang="ts">
import { getCurrentWindow } from '@tauri-apps/api/window';
import { vaultReady, focusMode } from '$lib/stores/app';
let { onNewNote = () => {} }: {
onNewNote?: () => void;
} = $props();
const appWindow = getCurrentWindow();
let maximized = $state(false);
async function checkMaximized() {
maximized = await appWindow.isMaximized();
}
$effect(() => {
checkMaximized();
const unlisten = appWindow.onResized(() => checkMaximized());
return () => { unlisten.then(fn => fn()); };
});
let lastMouseDown = 0;
function handleMouseDown(e: MouseEvent) {
if (e.button !== 0) return;
const target = e.target as HTMLElement;
if (target.closest('.titlebar-controls') || target.closest('.titlebar-actions')) return;
const now = Date.now();
if (now - lastMouseDown < 300) {
// Double-click detected — maximize/restore
appWindow.toggleMaximize();
lastMouseDown = 0;
return;
}
lastMouseDown = now;
appWindow.startDragging();
}
async function minimize() {
await appWindow.minimize();
}
async function toggleMaximize() {
await appWindow.toggleMaximize();
}
async function close() {
await appWindow.close();
}
</script>
<!-- svelte-ignore a11y_no_static_element_interactions -->
<div class="titlebar" onmousedown={handleMouseDown}>
<div class="titlebar-brand">
<svg width="18" height="18" viewBox="0 0 48 48" fill="none">
<rect width="48" height="48" rx="12" fill="var(--accent)" />
<circle cx="16" cy="16" r="3.5" fill="white" opacity="0.9" />
<circle cx="32" cy="16" r="3.5" fill="white" opacity="0.9" />
<circle cx="16" cy="32" r="3.5" fill="white" opacity="0.9" />
<circle cx="32" cy="32" r="3.5" fill="white" opacity="0.9" />
<line x1="19" y1="18" x2="29" y2="30" stroke="white" stroke-width="2" stroke-linecap="round" opacity="0.7" />
<line x1="29" y1="18" x2="19" y2="30" stroke="white" stroke-width="2" stroke-linecap="round" opacity="0.7" />
</svg>
<span class="titlebar-title">HelixNotes</span>
</div>
<div class="titlebar-actions">
<button class="switch-vault-btn" onclick={() => ($vaultReady = false)} title="Switch Vault">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="M22 19a2 2 0 01-2 2H4a2 2 0 01-2-2V5a2 2 0 012-2h5l2 3h9a2 2 0 012 2z" />
</svg>
</button>
<button class="switch-vault-btn" onclick={() => ($focusMode = true)} title="Focus mode">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="M8 3H5a2 2 0 00-2 2v3m18 0V5a2 2 0 00-2-2h-3m0 18h3a2 2 0 002-2v-3M3 16v3a2 2 0 002 2h3"/>
</svg>
</button>
<button class="new-note-btn" onclick={onNewNote} title="New Note (Ctrl+N)">
<svg width="14" height="14" viewBox="0 0 14 14" fill="none">
<path d="M7 1v12M1 7h12" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" />
</svg>
New Note
</button>
</div>
<div class="titlebar-controls">
<button class="titlebar-btn" onclick={minimize} title="Minimize">
<svg width="10" height="10" viewBox="0 0 10 10">
<line x1="1" y1="5" x2="9" y2="5" stroke="currentColor" stroke-width="1.2" stroke-linecap="round" />
</svg>
</button>
<button class="titlebar-btn" onclick={toggleMaximize} title={maximized ? 'Restore' : 'Maximize'}>
{#if maximized}
<svg width="10" height="10" viewBox="0 0 10 10">
<rect x="2.5" y="0.5" width="7" height="7" rx="1" fill="none" stroke="currentColor" stroke-width="1.2" />
<rect x="0.5" y="2.5" width="7" height="7" rx="1" fill="var(--bg-secondary)" stroke="currentColor" stroke-width="1.2" />
</svg>
{:else}
<svg width="10" height="10" viewBox="0 0 10 10">
<rect x="1" y="1" width="8" height="8" rx="1" fill="none" stroke="currentColor" stroke-width="1.2" />
</svg>
{/if}
</button>
<button class="titlebar-btn titlebar-close" onclick={close} title="Close">
<svg width="10" height="10" viewBox="0 0 10 10">
<line x1="1.5" y1="1.5" x2="8.5" y2="8.5" stroke="currentColor" stroke-width="1.2" stroke-linecap="round" />
<line x1="8.5" y1="1.5" x2="1.5" y2="8.5" stroke="currentColor" stroke-width="1.2" stroke-linecap="round" />
</svg>
</button>
</div>
</div>
<style>
.titlebar {
display: flex;
align-items: center;
height: 34px;
background: var(--bg-secondary);
border-bottom: 1px solid var(--border-color);
user-select: none;
flex-shrink: 0;
-webkit-app-region: drag;
}
.titlebar-brand {
display: flex;
align-items: center;
gap: 8px;
padding-left: 14px;
pointer-events: none;
flex: 1;
}
.titlebar-title {
font-size: 12px;
font-weight: 500;
color: var(--text-tertiary);
}
.titlebar-actions {
display: flex;
align-items: center;
gap: 6px;
margin-right: 8px;
-webkit-app-region: no-drag;
}
.switch-vault-btn {
display: flex;
align-items: center;
justify-content: center;
width: 28px;
height: 28px;
border: none;
border-radius: 7px;
background: var(--bg-hover);
color: var(--text-secondary);
cursor: pointer;
transition: background 0.15s, color 0.15s;
}
.switch-vault-btn:hover {
background: var(--bg-tertiary, var(--bg-hover));
color: var(--text-primary);
}
.new-note-btn {
display: flex;
align-items: center;
gap: 5px;
padding: 4px 12px 4px 10px;
border: none;
border-radius: 7px;
background: var(--accent);
color: white;
font-size: 11.5px;
font-weight: 600;
letter-spacing: 0.01em;
cursor: pointer;
white-space: nowrap;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.15);
transition: background 0.15s, box-shadow 0.15s, transform 0.1s;
}
.new-note-btn:hover {
background: var(--accent-hover);
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.2);
}
.new-note-btn:active {
transform: scale(0.97);
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.15);
}
.titlebar-controls {
display: flex;
height: 100%;
-webkit-app-region: no-drag;
}
.titlebar-btn {
display: flex;
align-items: center;
justify-content: center;
width: 38px;
height: 100%;
border: none;
background: none;
color: var(--text-tertiary);
cursor: pointer;
transition: background 0.1s, color 0.1s;
}
.titlebar-btn:hover {
background: var(--bg-hover);
color: var(--text-primary);
}
.titlebar-close:hover {
background: #e81123;
color: white;
}
</style>
+263
View File
@@ -0,0 +1,263 @@
<script lang="ts">
import { open } from '@tauri-apps/plugin-dialog';
import { getCurrentWindow } from '@tauri-apps/api/window';
import { openVault, getAppConfig } from '$lib/api';
import { appConfig, vaultReady } from '$lib/stores/app';
import type { VaultConfig } from '$lib/types';
const appWindow = getCurrentWindow();
let recentVaults: VaultConfig[] = $derived($appConfig?.vaults ?? []);
let loading = $state(false);
let error = $state('');
async function pickFolder() {
const selected = await open({ directory: true, multiple: false, title: 'Choose Notes Folder' });
if (selected) {
await openSelectedVault(selected as string);
}
}
async function openSelectedVault(path: string) {
loading = true;
error = '';
try {
await openVault(path);
const config = await getAppConfig();
$appConfig = config;
$vaultReady = true;
} catch (e) {
error = String(e);
} finally {
loading = false;
}
}
</script>
<!-- svelte-ignore a11y_no_static_element_interactions -->
<div class="vault-picker" onmousedown={(e) => { if (!(e.target as HTMLElement).closest('button, .picker-card')) appWindow.startDragging(); }}>
<div class="window-controls">
<button class="window-close" onclick={() => appWindow.close()} title="Close">
<svg width="10" height="10" viewBox="0 0 10 10">
<line x1="1.5" y1="1.5" x2="8.5" y2="8.5" stroke="currentColor" stroke-width="1.2" stroke-linecap="round" />
<line x1="8.5" y1="1.5" x2="1.5" y2="8.5" stroke="currentColor" stroke-width="1.2" stroke-linecap="round" />
</svg>
</button>
</div>
<div class="picker-card">
<div class="logo">
<svg width="72" height="72" viewBox="0 0 48 48" fill="none">
<rect width="48" height="48" rx="12" fill="var(--accent)" />
<circle cx="16" cy="16" r="3.5" fill="white" opacity="0.9" />
<circle cx="32" cy="16" r="3.5" fill="white" opacity="0.9" />
<circle cx="16" cy="32" r="3.5" fill="white" opacity="0.9" />
<circle cx="32" cy="32" r="3.5" fill="white" opacity="0.9" />
<line x1="19" y1="18" x2="29" y2="30" stroke="white" stroke-width="2" stroke-linecap="round" opacity="0.7" />
<line x1="29" y1="18" x2="19" y2="30" stroke="white" stroke-width="2" stroke-linecap="round" opacity="0.7" />
</svg>
</div>
<h1>HelixNotes</h1>
<p class="subtitle">Local-first markdown notes</p>
<p class="description">Your notes are stored as standard Markdown (.md) files. Pick any folder — existing .md files will be recognized automatically.</p>
{#if error}
<div class="error">{error}</div>
{/if}
<button class="btn-primary" onclick={pickFolder} disabled={loading}>
{#if loading}
Opening...
{:else}
Open Notes Folder
{/if}
</button>
{#if $appConfig?.active_vault}
<button class="btn-back" onclick={() => ($vaultReady = true)}>
Back
</button>
{/if}
{#if recentVaults.length > 0}
<div class="recent">
<span class="recent-label">Recent</span>
{#each recentVaults as vault}
<button class="vault-item" onclick={() => openSelectedVault(vault.path)}>
<span class="vault-name">{vault.name}</span>
<span class="vault-path">{vault.path}</span>
</button>
{/each}
</div>
{/if}
</div>
</div>
<style>
.vault-picker {
display: flex;
align-items: center;
justify-content: center;
height: 100vh;
background: var(--bg-primary);
position: relative;
}
.window-controls {
position: absolute;
top: 8px;
right: 8px;
z-index: 10;
}
.window-close {
display: flex;
align-items: center;
justify-content: center;
width: 32px;
height: 28px;
border: none;
background: none;
color: var(--text-tertiary);
cursor: pointer;
border-radius: 6px;
transition: background 0.1s, color 0.1s;
}
.window-close:hover {
background: #e81123;
color: white;
}
.picker-card {
text-align: center;
max-width: 400px;
width: 100%;
padding: 48px 32px;
}
.logo {
margin-bottom: 16px;
display: flex;
justify-content: center;
}
h1 {
font-size: 24px;
font-weight: 700;
margin-bottom: 4px;
color: var(--text-primary);
}
.subtitle {
color: var(--text-tertiary);
margin-bottom: 8px;
font-size: 14px;
}
.description {
color: var(--text-tertiary);
font-size: 12px;
line-height: 1.5;
margin-bottom: 24px;
opacity: 0.8;
}
.error {
background: color-mix(in srgb, var(--danger) 10%, transparent);
color: var(--danger);
padding: 8px 12px;
border-radius: 6px;
margin-bottom: 16px;
font-size: 13px;
}
.btn-primary {
width: 100%;
padding: 10px 20px;
background: var(--accent);
color: white;
border: none;
border-radius: 8px;
font-size: 14px;
font-weight: 500;
cursor: pointer;
transition: background 0.15s;
}
.btn-primary:hover {
background: var(--accent-hover);
}
.btn-primary:disabled {
opacity: 0.6;
cursor: not-allowed;
}
.btn-back {
width: 100%;
padding: 10px 20px;
background: var(--bg-tertiary);
color: var(--text-secondary);
border: 1px solid var(--border-color);
border-radius: 8px;
font-size: 14px;
font-weight: 500;
cursor: pointer;
margin-top: 8px;
transition: background 0.15s, color 0.15s;
}
.btn-back:hover {
background: var(--bg-hover);
color: var(--text-primary);
}
.recent {
margin-top: 32px;
text-align: left;
}
.recent-label {
font-size: 11px;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.05em;
color: var(--text-tertiary);
display: block;
margin-bottom: 8px;
}
.vault-item {
display: block;
width: 100%;
padding: 10px 12px;
background: var(--bg-secondary);
border: 1px solid var(--border-color);
border-radius: 8px;
cursor: pointer;
text-align: left;
margin-bottom: 6px;
transition: background 0.15s;
}
.vault-item:hover {
background: var(--bg-hover);
}
.vault-name {
display: block;
font-weight: 500;
font-size: 14px;
color: var(--text-primary);
}
.vault-path {
display: block;
font-size: 12px;
color: var(--text-tertiary);
margin-top: 2px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
</style>
+1
View File
@@ -0,0 +1 @@
// place files you want to import through the `$lib` alias in this folder.
+97
View File
@@ -0,0 +1,97 @@
import { writable, derived } from "svelte/store";
import type {
AppConfig,
NoteEntry,
NoteContent,
NotebookEntry,
VaultState,
ViewMode,
SortMode,
} from "$lib/types";
// App state
export const appConfig = writable<AppConfig | null>(null);
export const vaultReady = writable(false);
// UI state
export const viewMode = writable<ViewMode>("all");
export const sortMode = writable<SortMode>("modified");
export const sidebarCollapsed = writable(false);
export const sidebarWidth = writable(220);
export const notelistWidth = writable(280);
export const searchQuery = writable("");
export const showCommandPalette = writable(false);
export const showSearch = writable(false);
export const showSettings = writable(false);
export const showInfo = writable(false);
export const notebookIcons = writable<Record<string, string>>({});
export const quickAccessPaths = writable<string[]>([]);
export const collapsedNotebooks = writable<string[]>([]);
// Data
export const notebooks = writable<NotebookEntry[]>([]);
export const notes = writable<NoteEntry[]>([]);
export const tags = writable<[string, number][]>([]);
export const activeNote = writable<NoteContent | null>(null);
export const activeNotePath = writable<string | null>(null);
export const activeNotebook = writable<NotebookEntry | null>(null);
export const activeTag = writable<string | null>(null);
// Editor state
export const editorDirty = writable(false);
export const sourceMode = writable(false);
export const focusMode = writable(false);
// Theme
export const theme = writable<string>("system");
// Derived
export const sortedNotes = derived([notes, sortMode], ([$notes, $sortMode]) => {
const pinned = $notes.filter((n) => n.meta.pinned);
const unpinned = $notes.filter((n) => !n.meta.pinned);
const sortFn = (a: NoteEntry, b: NoteEntry) => {
switch ($sortMode) {
case "title":
return a.meta.title.localeCompare(b.meta.title);
case "created":
return (
new Date(b.meta.created).getTime() -
new Date(a.meta.created).getTime()
);
case "modified":
default:
return (
new Date(b.meta.modified).getTime() -
new Date(a.meta.modified).getTime()
);
}
};
return [...pinned.sort(sortFn), ...unpinned.sort(sortFn)];
});
export const vaultState = derived(
[
activeNotePath,
sidebarWidth,
notelistWidth,
sidebarCollapsed,
collapsedNotebooks,
],
([
$activeNotePath,
$sidebarWidth,
$notelistWidth,
$sidebarCollapsed,
$collapsedNotebooks,
]) => {
return {
last_open_note: $activeNotePath,
sidebar_width: $sidebarWidth,
notelist_width: $notelistWidth,
sidebar_collapsed: $sidebarCollapsed,
collapsed_notebooks: $collapsedNotebooks,
} satisfies VaultState;
},
);
+132
View File
@@ -0,0 +1,132 @@
export interface NoteMeta {
id: string;
title: string;
tags: string[];
pinned: boolean;
created: string;
modified: string;
}
export interface NoteEntry {
path: string;
relative_path: string;
meta: NoteMeta;
preview: string;
}
export interface NotebookEntry {
name: string;
path: string;
relative_path: string;
children: NotebookEntry[];
note_count: number;
}
export interface NoteContent {
path: string;
meta: NoteMeta;
content: string;
raw: string;
}
export interface VaultConfig {
path: string;
name: string;
}
export interface AppConfig {
vaults: VaultConfig[];
active_vault: string | null;
theme: string;
accent_color: string | null;
font_size: number | null;
font_family: string | null;
compact_notes: boolean;
time_format: string;
gpu_acceleration: boolean;
autostart: boolean;
pdf_preview: boolean;
pdf_height: number;
title_mode: string;
hide_title_in_body: boolean;
backup_enabled: boolean;
backup_frequency: string;
backup_max_count: number;
backup_location: string | null;
last_backup_time: string | null;
backup_include_attachments: boolean;
max_versions_per_note: number;
ai_provider: string | null;
ai_api_key: string | null;
openai_api_key: string | null;
ai_model: string;
ai_writing_style: string | null;
default_view_mode: boolean;
show_tray_icon: boolean;
enable_wiki_links: boolean;
}
export interface VaultState {
last_open_note: string | null;
sidebar_width: number;
notelist_width: number;
sidebar_collapsed: boolean;
collapsed_notebooks: string[];
}
export interface SearchResult {
path: string;
title: string;
snippet: string;
score: number;
}
export interface FileEvent {
event_type: string;
path: string;
}
export interface ImportResult {
files_converted: number;
links_converted: number;
}
export interface VaultStats {
total_notes: number;
total_attachments: number;
notes_size: number;
attachments_size: number;
total_size: number;
}
export interface BackupEntry {
filename: string;
path: string;
size: number;
created: string;
}
export interface VersionEntry {
timestamp: string;
size: number;
}
export interface AiStreamEvent {
event_type: string;
text: string | null;
error: string | null;
}
export interface NoteTitleEntry {
title: string;
path: string;
}
export type SortMode = "modified" | "title" | "created";
export type ViewMode =
| "all"
| "notebook"
| "tag"
| "trash"
| "search"
| "quickaccess";
+7
View File
@@ -0,0 +1,7 @@
export function debounce<T extends (...args: any[]) => any>(fn: T, ms: number): T {
let timeout: ReturnType<typeof setTimeout>;
return ((...args: any[]) => {
clearTimeout(timeout);
timeout = setTimeout(() => fn(...args), ms);
}) as T;
}
+26
View File
@@ -0,0 +1,26 @@
export function formatRelativeTime(dateStr: string): string {
const date = new Date(dateStr);
const now = new Date();
const diff = now.getTime() - date.getTime();
const seconds = Math.floor(diff / 1000);
const minutes = Math.floor(seconds / 60);
const hours = Math.floor(minutes / 60);
const days = Math.floor(hours / 24);
if (seconds < 60) return 'just now';
if (minutes < 60) return `${minutes}m ago`;
if (hours < 24) return `${hours}h ago`;
if (days < 7) return `${days}d ago`;
return date.toLocaleDateString(undefined, { month: 'short', day: 'numeric' });
}
export function formatDate(dateStr: string): string {
return new Date(dateStr).toLocaleDateString(undefined, {
year: 'numeric',
month: 'short',
day: 'numeric',
hour: '2-digit',
minute: '2-digit'
});
}
+77
View File
@@ -0,0 +1,77 @@
<script lang="ts">
import { onMount } from 'svelte';
import '../app.css';
import { theme, appConfig, activeNotePath } from '$lib/stores/app';
import { openUrl } from '@tauri-apps/plugin-opener';
import { openFile } from '$lib/api';
import { get } from 'svelte/store';
let { children } = $props();
// Reactively apply theme class to <html> whenever $theme changes
$effect(() => {
const t = $theme;
const root = document.documentElement;
root.classList.remove('dark');
if (
t === 'dark' ||
(t === 'system' && window.matchMedia('(prefers-color-scheme: dark)').matches)
) {
root.classList.add('dark');
}
});
function normalizePath(p: string): string {
const parts = p.split('/');
const resolved: string[] = [];
for (const seg of parts) {
if (seg === '..') resolved.pop();
else if (seg !== '.') resolved.push(seg);
}
return resolved.join('/');
}
// Intercept all link clicks in capture phase to prevent webview navigation
onMount(() => {
function handleLinkClick(e: MouseEvent) {
const target = (e.target as HTMLElement)?.closest('a');
if (!target) return;
const href = target.getAttribute('href');
if (!href) return;
e.preventDefault();
e.stopPropagation();
e.stopImmediatePropagation();
if (href.startsWith('http://') || href.startsWith('https://') || href.startsWith('mailto:')) {
openUrl(href).catch((err) => console.error('Failed to open URL:', err));
} else if (!href.startsWith('#')) {
const decoded = decodeURIComponent(href);
const config = get(appConfig);
const vaultRoot = config?.active_vault;
let absPath = decoded;
if (!decoded.startsWith('/') && vaultRoot) {
const notePath = get(activeNotePath);
if (notePath) {
const noteDir = notePath.substring(0, notePath.lastIndexOf('/'));
absPath = normalizePath(`${noteDir}/${decoded}`);
} else {
absPath = normalizePath(`${vaultRoot}/${decoded}`);
}
}
openFile(absPath).catch((err) => console.error('Failed to open file:', err));
}
}
document.addEventListener('click', handleLinkClick, true);
return () => document.removeEventListener('click', handleLinkClick, true);
});
</script>
<svelte:document oncontextmenu={(e) => e.preventDefault()} />
<svelte:head>
<title>HelixNotes</title>
</svelte:head>
{@render children()}
+2
View File
@@ -0,0 +1,2 @@
export const prerender = false;
export const ssr = false;
+118
View File
@@ -0,0 +1,118 @@
<script lang="ts">
import { onMount } from 'svelte';
import { appConfig, vaultReady, theme } from '$lib/stores/app';
import { getAppConfig, openVault } from '$lib/api';
import VaultPicker from '$lib/components/VaultPicker.svelte';
import AppLayout from '$lib/components/AppLayout.svelte';
let loading = $state(true);
onMount(async () => {
try {
const config = await getAppConfig();
$appConfig = config;
$theme = config.theme || 'system';
// Apply theme immediately to prevent flash
const themeValue = config.theme || 'system';
const root = document.documentElement;
root.classList.remove('dark');
if (themeValue === 'dark' || (themeValue === 'system' && window.matchMedia('(prefers-color-scheme: dark)').matches)) {
root.classList.add('dark');
}
// Apply saved font settings
if (config.font_size) {
document.documentElement.style.setProperty('--editor-font-size', `${config.font_size}px`);
}
if (config.font_family) {
const fontStacks: Record<string, string> = {
system: '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',
inter: '"Inter", -apple-system, BlinkMacSystemFont, sans-serif',
georgia: 'Georgia, "Times New Roman", serif',
merriweather: '"Merriweather", Georgia, serif',
lora: '"Lora", Georgia, serif',
opensans: '"Open Sans", -apple-system, sans-serif',
literata: '"Literata", Georgia, serif',
mono: '"JetBrains Mono", "Fira Code", "Cascadia Code", monospace',
};
const stack = fontStacks[config.font_family];
if (stack) document.documentElement.style.setProperty('--editor-font-family', stack);
}
// Apply saved accent
if (config.accent_color) {
const accentPresets: Record<string, { light: string; dark: string }> = {
Indigo: { light: '#5b6abf', dark: '#7b9bd4' },
Rose: { light: '#e11d48', dark: '#d4768a' },
Emerald: { light: '#059669', dark: '#5bab8a' },
Amber: { light: '#d97706', dark: '#c9a04e' },
Purple: { light: '#7c3aed', dark: '#9a82c4' },
Cyan: { light: '#0891b2', dark: '#5ba8b5' },
Orange: { light: '#ea580c', dark: '#c98560' },
Teal: { light: '#0d9488', dark: '#5fada5' },
};
const preset = accentPresets[config.accent_color];
if (preset) {
const themeVal = config.theme || 'light';
const isDark = themeVal === 'dark' || (themeVal === 'system' && window.matchMedia('(prefers-color-scheme: dark)').matches);
const color = isDark ? preset.dark : preset.light;
const root = document.documentElement;
root.style.setProperty('--accent', color);
root.style.setProperty('--text-accent', color);
root.style.setProperty('--accent-hover', color);
root.style.setProperty('--accent-light', isDark
? `color-mix(in srgb, ${color} 10%, transparent)`
: `color-mix(in srgb, ${color} 8%, transparent)`);
}
}
// Auto-open last vault if available
if (config.active_vault) {
try {
await openVault(config.active_vault);
$vaultReady = true;
} catch {
// Vault path might not exist anymore
}
}
} catch {
// First launch or no config
}
loading = false;
});
</script>
{#if loading}
<div class="loading">
<div class="spinner"></div>
</div>
{:else if $vaultReady}
<AppLayout />
{:else}
<VaultPicker />
{/if}
<style>
.loading {
display: flex;
align-items: center;
justify-content: center;
height: 100vh;
background: var(--bg-primary);
}
.spinner {
width: 24px;
height: 24px;
border: 2px solid var(--border-color);
border-top-color: var(--accent);
border-radius: 50%;
animation: spin 0.6s linear infinite;
}
@keyframes spin {
to {
transform: rotate(360deg);
}
}
</style>
+3
View File
@@ -0,0 +1,3 @@
# allow crawling everything by default
User-agent: *
Disallow:
+12
View File
@@ -0,0 +1,12 @@
import adapter from "@sveltejs/adapter-static";
/** @type {import('@sveltejs/kit').Config} */
const config = {
kit: {
adapter: adapter({
fallback: "index.html",
}),
},
};
export default config;
+20
View File
@@ -0,0 +1,20 @@
{
"extends": "./.svelte-kit/tsconfig.json",
"compilerOptions": {
"rewriteRelativeImportExtensions": true,
"allowJs": true,
"checkJs": true,
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true,
"skipLibCheck": true,
"sourceMap": true,
"strict": true,
"moduleResolution": "bundler"
}
// Path aliases are handled by https://svelte.dev/docs/kit/configuration#alias
// except $lib which is handled by https://svelte.dev/docs/kit/configuration#files
//
// To make changes to top-level options such as include and exclude, we recommend extending
// the generated config; see https://svelte.dev/docs/kit/configuration#typescript
}
+26
View File
@@ -0,0 +1,26 @@
import { sveltekit } from "@sveltejs/kit/vite";
import tailwindcss from "@tailwindcss/vite";
import { defineConfig } from "vite";
const host = process.env.TAURI_DEV_HOST;
export default defineConfig({
plugins: [sveltekit(), tailwindcss()],
clearScreen: false,
server: {
port: 5173,
strictPort: true,
host: host || false,
hmr: host
? {
protocol: "ws",
host,
port: 5174,
overlay: false,
}
: { overlay: false },
watch: {
ignored: ["**/src-tauri/**"],
},
},
});