Restarting the project once again.

This commit has the skeleton of what is going to be the app.
This commit is contained in:
Nixyan 2026-03-05 18:52:46 -03:00
parent e7dd6c961d
commit 87196d312e
136 changed files with 2123 additions and 18149 deletions

8
.env.local.example Normal file
View file

@ -0,0 +1,8 @@
# Better Auth Cookie Secret
BETTER_AUTH_SECRET=
# Better Auth URL
BETTER_AUTH_URL=
# Database URL
DATABASE_URL=

7
.gitignore vendored
View file

@ -31,7 +31,8 @@ yarn-error.log*
.pnpm-debug.log* .pnpm-debug.log*
# env files (can opt-in for committing if needed) # env files (can opt-in for committing if needed)
.env* .env.local
.env
# vercel # vercel
.vercel .vercel
@ -39,7 +40,3 @@ yarn-error.log*
# typescript # typescript
*.tsbuildinfo *.tsbuildinfo
next-env.d.ts next-env.d.ts
# OLM (copied from node_modules by scripts/copy-olm.js)
/public/olm.js
/public/olm.wasm

View file

@ -10,7 +10,6 @@
"editor.formatOnSave": true, "editor.formatOnSave": true,
"editor.formatOnPaste": true, "editor.formatOnPaste": true,
"editor.formatOnType": true, "editor.formatOnType": true,
"typescript.preferences.quoteStyle": "double",
"editor.formatOnSaveMode": "file", "editor.formatOnSaveMode": "file",
"editor.codeActionsOnSave": { "editor.codeActionsOnSave": {
"source.organizeImports": "explicit" "source.organizeImports": "explicit"

661
LICENSE
View file

@ -1,7 +1,660 @@
Copyright 2026 Marcello Brito # GNU AFFERO GENERAL PUBLIC LICENSE
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: Version 3, 19 November 2007
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. Copyright (C) 2007 Free Software Foundation, Inc.
<https://fsf.org/>
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 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.
SiPher
Copyright (C) 2026 Marcello Brito
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/>.

View file

@ -1,4 +1,29 @@
please don't use this # SiPher
I made this to test things > *Silent Whisper — A federated social network built for the modern age.*
I am not to be trusted under any circunstances [![License](https://img.shields.io/badge/license-AGPL--3.0-blue.svg)](./LICENSE)
![Version](https://img.shields.io/badge/version-0.1.0-purple.svg)
![Status](https://img.shields.io/badge/status-early%20development-orange.svg)
SiPher is a federated social network. Each server is independent — no central authority, no single point of failure.
Your identity is `you@yourserver.com`. Your server, your data, your rules.
---
## Roadmap
- **Phase 1** — Core federation. Two servers can follow each other, post, and see each other's posts.
- **Phase 2** — Server trust scoring and a public vouch ledger.
- **Phase 3** — Opt-in relay network for censorship resistance.
- **Phase 4** — End-to-end encryption via TBD.
---
## Author
**Marcello Brito** (Tocka) — [tockanest.com](https://tockanest.com)
## License
[AGPL-3.0](./LICENSE)

947
bun.lock

File diff suppressed because it is too large Load diff

View file

@ -11,6 +11,7 @@
"prefix": "" "prefix": ""
}, },
"iconLibrary": "lucide", "iconLibrary": "lucide",
"rtl": false,
"aliases": { "aliases": {
"components": "@/components", "components": "@/components",
"utils": "@/lib/utils", "utils": "@/lib/utils",

File diff suppressed because it is too large Load diff

View file

@ -1,23 +0,0 @@
/* eslint-disable */
/**
* Generated `api` utility.
*
* THIS CODE IS AUTOMATICALLY GENERATED.
*
* To regenerate, run `npx convex dev`.
* @module
*/
import { anyApi, componentsGeneric } from "convex/server";
/**
* A utility for referencing Convex functions in your app's API.
*
* Usage:
* ```js
* const myFunctionReference = api.myModule.myFunction;
* ```
*/
export const api = anyApi;
export const internal = anyApi;
export const components = componentsGeneric();

View file

@ -1,58 +0,0 @@
/* eslint-disable */
/**
* Generated data model types.
*
* THIS CODE IS AUTOMATICALLY GENERATED.
*
* To regenerate, run `npx convex dev`.
* @module
*/
import { AnyDataModel } from "convex/server";
import type { GenericId } from "convex/values";
/**
* No `schema.ts` file found!
*
* This generated code has permissive types like `Doc = any` because
* Convex doesn't know your schema. If you'd like more type safety, see
* https://docs.convex.dev/using/schemas for instructions on how to add a
* schema file.
*
* After you change a schema, rerun codegen with `npx convex dev`.
*/
/**
* The names of all of your Convex tables.
*/
export type TableNames = string;
/**
* The type of a document stored in Convex.
*/
export type Doc = any;
/**
* An identifier for a document in Convex.
*
* Convex documents are uniquely identified by their `Id`, which is accessible
* on the `_id` field. To learn more, see [Document IDs](https://docs.convex.dev/using/document-ids).
*
* Documents can be loaded using `db.get(tableName, id)` in query and mutation functions.
*
* IDs are just strings at runtime, but this type can be used to distinguish them from other
* strings when type checking.
*/
export type Id<TableName extends TableNames = TableNames> =
GenericId<TableName>;
/**
* A type describing your Convex data model.
*
* This type includes information about what tables you have, the type of
* documents stored in those tables, and the indexes defined on them.
*
* This type is used to parameterize methods like `queryGeneric` and
* `mutationGeneric` to make them type-safe.
*/
export type DataModel = AnyDataModel;

View file

@ -1,143 +0,0 @@
/* eslint-disable */
/**
* Generated utilities for implementing server-side Convex query and mutation functions.
*
* THIS CODE IS AUTOMATICALLY GENERATED.
*
* To regenerate, run `npx convex dev`.
* @module
*/
import {
ActionBuilder,
HttpActionBuilder,
MutationBuilder,
QueryBuilder,
GenericActionCtx,
GenericMutationCtx,
GenericQueryCtx,
GenericDatabaseReader,
GenericDatabaseWriter,
} from "convex/server";
import type { DataModel } from "./dataModel.js";
/**
* Define a query in this Convex app's public API.
*
* This function will be allowed to read your Convex database and will be accessible from the client.
*
* @param func - The query function. It receives a {@link QueryCtx} as its first argument.
* @returns The wrapped query. Include this as an `export` to name it and make it accessible.
*/
export declare const query: QueryBuilder<DataModel, "public">;
/**
* Define a query that is only accessible from other Convex functions (but not from the client).
*
* This function will be allowed to read from your Convex database. It will not be accessible from the client.
*
* @param func - The query function. It receives a {@link QueryCtx} as its first argument.
* @returns The wrapped query. Include this as an `export` to name it and make it accessible.
*/
export declare const internalQuery: QueryBuilder<DataModel, "internal">;
/**
* Define a mutation in this Convex app's public API.
*
* This function will be allowed to modify your Convex database and will be accessible from the client.
*
* @param func - The mutation function. It receives a {@link MutationCtx} as its first argument.
* @returns The wrapped mutation. Include this as an `export` to name it and make it accessible.
*/
export declare const mutation: MutationBuilder<DataModel, "public">;
/**
* Define a mutation that is only accessible from other Convex functions (but not from the client).
*
* This function will be allowed to modify your Convex database. It will not be accessible from the client.
*
* @param func - The mutation function. It receives a {@link MutationCtx} as its first argument.
* @returns The wrapped mutation. Include this as an `export` to name it and make it accessible.
*/
export declare const internalMutation: MutationBuilder<DataModel, "internal">;
/**
* Define an action in this Convex app's public API.
*
* An action is a function which can execute any JavaScript code, including non-deterministic
* code and code with side-effects, like calling third-party services.
* They can be run in Convex's JavaScript environment or in Node.js using the "use node" directive.
* They can interact with the database indirectly by calling queries and mutations using the {@link ActionCtx}.
*
* @param func - The action. It receives an {@link ActionCtx} as its first argument.
* @returns The wrapped action. Include this as an `export` to name it and make it accessible.
*/
export declare const action: ActionBuilder<DataModel, "public">;
/**
* Define an action that is only accessible from other Convex functions (but not from the client).
*
* @param func - The function. It receives an {@link ActionCtx} as its first argument.
* @returns The wrapped function. Include this as an `export` to name it and make it accessible.
*/
export declare const internalAction: ActionBuilder<DataModel, "internal">;
/**
* Define an HTTP action.
*
* The wrapped function will be used to respond to HTTP requests received
* by a Convex deployment if the requests matches the path and method where
* this action is routed. Be sure to route your httpAction in `convex/http.js`.
*
* @param func - The function. It receives an {@link ActionCtx} as its first argument
* and a Fetch API `Request` object as its second.
* @returns The wrapped function. Import this function from `convex/http.js` and route it to hook it up.
*/
export declare const httpAction: HttpActionBuilder;
/**
* A set of services for use within Convex query functions.
*
* The query context is passed as the first argument to any Convex query
* function run on the server.
*
* This differs from the {@link MutationCtx} because all of the services are
* read-only.
*/
export type QueryCtx = GenericQueryCtx<DataModel>;
/**
* A set of services for use within Convex mutation functions.
*
* The mutation context is passed as the first argument to any Convex mutation
* function run on the server.
*/
export type MutationCtx = GenericMutationCtx<DataModel>;
/**
* A set of services for use within Convex action functions.
*
* The action context is passed as the first argument to any Convex action
* function run on the server.
*/
export type ActionCtx = GenericActionCtx<DataModel>;
/**
* An interface to read from the database within Convex query functions.
*
* The two entry points are {@link DatabaseReader.get}, which fetches a single
* document by its {@link Id}, or {@link DatabaseReader.query}, which starts
* building a query.
*/
export type DatabaseReader = GenericDatabaseReader<DataModel>;
/**
* An interface to read from and write to the database within Convex mutation
* functions.
*
* Convex guarantees that all writes within a single mutation are
* executed atomically, so you never have to worry about partial writes leaving
* your data in an inconsistent state. See [the Convex Guide](https://docs.convex.dev/understanding/convex-fundamentals/functions#atomicity-and-optimistic-concurrency-control)
* for the guarantees Convex provides your functions.
*/
export type DatabaseWriter = GenericDatabaseWriter<DataModel>;

View file

@ -1,93 +0,0 @@
/* eslint-disable */
/**
* Generated utilities for implementing server-side Convex query and mutation functions.
*
* THIS CODE IS AUTOMATICALLY GENERATED.
*
* To regenerate, run `npx convex dev`.
* @module
*/
import {
actionGeneric,
httpActionGeneric,
queryGeneric,
mutationGeneric,
internalActionGeneric,
internalMutationGeneric,
internalQueryGeneric,
} from "convex/server";
/**
* Define a query in this Convex app's public API.
*
* This function will be allowed to read your Convex database and will be accessible from the client.
*
* @param func - The query function. It receives a {@link QueryCtx} as its first argument.
* @returns The wrapped query. Include this as an `export` to name it and make it accessible.
*/
export const query = queryGeneric;
/**
* Define a query that is only accessible from other Convex functions (but not from the client).
*
* This function will be allowed to read from your Convex database. It will not be accessible from the client.
*
* @param func - The query function. It receives a {@link QueryCtx} as its first argument.
* @returns The wrapped query. Include this as an `export` to name it and make it accessible.
*/
export const internalQuery = internalQueryGeneric;
/**
* Define a mutation in this Convex app's public API.
*
* This function will be allowed to modify your Convex database and will be accessible from the client.
*
* @param func - The mutation function. It receives a {@link MutationCtx} as its first argument.
* @returns The wrapped mutation. Include this as an `export` to name it and make it accessible.
*/
export const mutation = mutationGeneric;
/**
* Define a mutation that is only accessible from other Convex functions (but not from the client).
*
* This function will be allowed to modify your Convex database. It will not be accessible from the client.
*
* @param func - The mutation function. It receives a {@link MutationCtx} as its first argument.
* @returns The wrapped mutation. Include this as an `export` to name it and make it accessible.
*/
export const internalMutation = internalMutationGeneric;
/**
* Define an action in this Convex app's public API.
*
* An action is a function which can execute any JavaScript code, including non-deterministic
* code and code with side-effects, like calling third-party services.
* They can be run in Convex's JavaScript environment or in Node.js using the "use node" directive.
* They can interact with the database indirectly by calling queries and mutations using the {@link ActionCtx}.
*
* @param func - The action. It receives an {@link ActionCtx} as its first argument.
* @returns The wrapped action. Include this as an `export` to name it and make it accessible.
*/
export const action = actionGeneric;
/**
* Define an action that is only accessible from other Convex functions (but not from the client).
*
* @param func - The function. It receives an {@link ActionCtx} as its first argument.
* @returns The wrapped function. Include this as an `export` to name it and make it accessible.
*/
export const internalAction = internalActionGeneric;
/**
* Define an HTTP action.
*
* The wrapped function will be used to respond to HTTP requests received
* by a Convex deployment if the requests matches the path and method where
* this action is routed. Be sure to route your httpAction in `convex/http.js`.
*
* @param func - The function. It receives an {@link ActionCtx} as its first argument
* and a Fetch API `Request` object as its second.
* @returns The wrapped function. Import this function from `convex/http.js` and route it to hook it up.
*/
export const httpAction = httpActionGeneric;

View file

@ -1,8 +0,0 @@
import { getAuthConfigProvider } from "@convex-dev/better-auth/auth-config";
import type { AuthConfig } from "convex/server";
export default {
providers: [
getAuthConfigProvider(),
],
} satisfies AuthConfig;

View file

@ -1,256 +0,0 @@
import { createClient, type GenericCtx } from "@convex-dev/better-auth";
import { convex } from "@convex-dev/better-auth/plugins";
import { betterAuth, type BetterAuthOptions } from "better-auth";
import { captcha, oneTimeToken, openAPI, username } from "better-auth/plugins";
import { v } from "convex/values";
import { components } from "./_generated/api";
import { DataModel } from "./_generated/dataModel";
import { mutation, query } from "./_generated/server";
import authConfig from "./auth.config";
import authSchema from "./betterAuth/schema";
const siteUrl = process.env.SITE_URL!;
// The component client has methods needed for integrating Convex with Better Auth,
// as well as helper methods for general use.
export const authComponent = createClient<DataModel, typeof authSchema>(
components.betterAuth,
{
local: {
schema: authSchema
}
}
);
export const createAuthOptions = (ctx: GenericCtx<DataModel>) => {
return {
baseURL: siteUrl,
database: authComponent.adapter(ctx),
emailAndPassword: {
enabled: true,
requireEmailVerification: false,
autoSignIn: true
},
trustedOrigins: [
siteUrl,
"http://localhost:8081",
"https://sipher.tockanest.com"
],
user: {
additionalFields: {
metadata: {
type: "json",
required: false,
},
friends: {
type: "string[]",
required: false,
index: true
}
},
},
plugins: [
convex({
authConfig,
jwksRotateOnTokenGenerationError: true,
}),
captcha({
provider: "cloudflare-turnstile",
secretKey: process.env.CAPTCHA_SECRET_KEY!,
}),
username({
displayUsernameValidator: (displayUsername) => {
// Allow only alphanumeric characters, underscores, and hyphens
return /^[a-zA-Z0-9_-]+$/.test(displayUsername)
}
}),
oneTimeToken(),
openAPI(),
],
} satisfies BetterAuthOptions;
}
export const createAuth = (
ctx: GenericCtx<DataModel>
) => {
return betterAuth(createAuthOptions(ctx));
};
// Example function for getting the current user
// Feel free to edit, omit, etc.
export const getCurrentUser = query({
args: {},
handler: async (ctx) => {
return authComponent.getAuthUser(ctx);
},
});
export const sendKeysToServer = mutation({
args: {
userId: v.string(),
identityKey: v.object({
curve25519: v.string(),
ed25519: v.string(),
}),
oneTimeKeys: v.array(v.object({
keyId: v.string(),
publicKey: v.string(),
})),
forceInsert: v.boolean(),
},
handler: async (ctx, args) => {
return ctx.runMutation(components.betterAuth.olm.index.sendKeysToServer, {
userId: args.userId,
identityKey: args.identityKey,
oneTimeKeys: args.oneTimeKeys,
forceInsert: args.forceInsert,
});
},
});
export const retrieveServerOlmAccount = query({
args: {
userId: v.string(),
},
handler: async (ctx, args) => {
return ctx.runQuery(components.betterAuth.olm.index.retrieveServerOlmAccount, {
userId: args.userId,
});
},
});
export const updateUserStatus = mutation({
args: {
status: v.union(v.literal("online"), v.literal("busy"), v.literal("offline"), v.literal("away")),
isUserSet: v.optional(v.boolean()),
},
handler: async (ctx, args) => {
return ctx.runMutation(components.betterAuth.user.index.updateUserStatus, {
status: args.status,
isUserSet: args.isUserSet,
});
},
});
export const getNonOfflineUserIds = query({
args: {},
handler: async (ctx) => {
return ctx.runQuery(components.betterAuth.user.index.getNonOfflineUserIds, {});
},
});
export const forceUserOffline = mutation({
args: {
userId: v.string(),
},
handler: async (ctx, args) => {
return ctx.runMutation(components.betterAuth.user.index.forceUserOffline, {
userId: args.userId,
});
},
});
export const updateUserMetadata = mutation({
args: {
metadata: v.object({
phrasePreference: v.union(v.literal("comforting"), v.literal("mocking"), v.literal("both")),
}),
},
handler: async (ctx, args) => {
return ctx.runMutation(components.betterAuth.user.index.updateUserMetadata, {
metadata: args.metadata,
});
},
});
export const sendFriendRequest = mutation({
args: {
username: v.string(),
},
handler: async (ctx, args) => {
return ctx.runMutation(components.betterAuth.user.index.sendFriendRequest, {
username: args.username,
});
},
});
export const answerFriendRequest = mutation({
args: {
requestId: v.string(),
answer: v.union(v.literal("accept"), v.literal("decline"), v.literal("ignore")),
},
handler: async (ctx, args) => {
return ctx.runMutation(components.betterAuth.user.index.answerFriendRequest, {
requestId: args.requestId,
answer: args.answer,
});
},
});
export const getFriendRequests = query({
args: {},
handler: async (ctx) => {
return ctx.runQuery(components.betterAuth.user.index.getFriendRequests)
},
});
export const getFriends = query({
args: {},
handler: async (ctx) => {
return ctx.runQuery(components.betterAuth.user.index.getFriends)
},
});
export const getUserStatus = query({
args: {},
handler: async (ctx) => {
return ctx.runQuery(components.betterAuth.user.index.getUserStatus)
},
});
export const getParticipantDetails = query({
args: {
participantIds: v.array(v.string()),
},
handler: async (ctx, args) => {
return ctx.runQuery(components.betterAuth.user.index.getParticipantDetails, {
participantIds: args.participantIds,
});
},
});
export const consumeOTK = mutation({
args: {
userId: v.string(),
keyId: v.string(),
},
handler: async (ctx, args) => {
return ctx.runMutation(components.betterAuth.olm.index.consumeOTK, {
userId: args.userId,
keyId: args.keyId,
});
},
});
export const getKeyVersion = query({
args: {
userId: v.string(),
},
handler: async (ctx, args) => {
return ctx.runQuery(components.betterAuth.olm.index.getKeyVersion, {
userId: args.userId,
});
},
});
export const migrateOlmAccounts = mutation({
handler: async (ctx) => {
return ctx.runMutation(components.betterAuth.olm.index.migrateOlmAccounts, {});
},
});
export const getUserNests = query({
handler: async (ctx) => {
return ctx.runQuery(components.betterAuth.nests.locals.getUserNests);
},
});

View file

@ -1,62 +0,0 @@
/* eslint-disable */
/**
* Generated `api` utility.
*
* THIS CODE IS AUTOMATICALLY GENERATED.
*
* To regenerate, run `npx convex dev`.
* @module
*/
import type * as adapter from "../adapter.js";
import type * as auth from "../auth.js";
import type * as nests_locals from "../nests/locals.js";
import type * as olm_index from "../olm/index.js";
import type * as schemas_nests from "../schemas/nests.js";
import type * as schemas_user from "../schemas/user.js";
import type * as user_index from "../user/index.js";
import type {
ApiFromModules,
FilterApi,
FunctionReference,
} from "convex/server";
import { anyApi, componentsGeneric } from "convex/server";
const fullApi: ApiFromModules<{
adapter: typeof adapter;
auth: typeof auth;
"nests/locals": typeof nests_locals;
"olm/index": typeof olm_index;
"schemas/nests": typeof schemas_nests;
"schemas/user": typeof schemas_user;
"user/index": typeof user_index;
}> = anyApi as any;
/**
* A utility for referencing Convex functions in your app's public API.
*
* Usage:
* ```js
* const myFunctionReference = api.myModule.myFunction;
* ```
*/
export const api: FilterApi<
typeof fullApi,
FunctionReference<any, "public">
> = anyApi as any;
/**
* A utility for referencing Convex functions in your app's internal API.
*
* Usage:
* ```js
* const myFunctionReference = internal.myModule.myFunction;
* ```
*/
export const internal: FilterApi<
typeof fullApi,
FunctionReference<any, "internal">
> = anyApi as any;
export const components = componentsGeneric() as unknown as {};

File diff suppressed because it is too large Load diff

View file

@ -1,60 +0,0 @@
/* eslint-disable */
/**
* Generated data model types.
*
* THIS CODE IS AUTOMATICALLY GENERATED.
*
* To regenerate, run `npx convex dev`.
* @module
*/
import type {
DataModelFromSchemaDefinition,
DocumentByName,
TableNamesInDataModel,
SystemTableNames,
} from "convex/server";
import type { GenericId } from "convex/values";
import schema from "../schema.js";
/**
* The names of all of your Convex tables.
*/
export type TableNames = TableNamesInDataModel<DataModel>;
/**
* The type of a document stored in Convex.
*
* @typeParam TableName - A string literal type of the table name (like "users").
*/
export type Doc<TableName extends TableNames> = DocumentByName<
DataModel,
TableName
>;
/**
* An identifier for a document in Convex.
*
* Convex documents are uniquely identified by their `Id`, which is accessible
* on the `_id` field. To learn more, see [Document IDs](https://docs.convex.dev/using/document-ids).
*
* Documents can be loaded using `db.get(tableName, id)` in query and mutation functions.
*
* IDs are just strings at runtime, but this type can be used to distinguish them from other
* strings when type checking.
*
* @typeParam TableName - A string literal type of the table name (like "users").
*/
export type Id<TableName extends TableNames | SystemTableNames> =
GenericId<TableName>;
/**
* A type describing your Convex data model.
*
* This type includes information about what tables you have, the type of
* documents stored in those tables, and the indexes defined on them.
*
* This type is used to parameterize methods like `queryGeneric` and
* `mutationGeneric` to make them type-safe.
*/
export type DataModel = DataModelFromSchemaDefinition<typeof schema>;

View file

@ -1,156 +0,0 @@
/* eslint-disable */
/**
* Generated utilities for implementing server-side Convex query and mutation functions.
*
* THIS CODE IS AUTOMATICALLY GENERATED.
*
* To regenerate, run `npx convex dev`.
* @module
*/
import type {
ActionBuilder,
HttpActionBuilder,
MutationBuilder,
QueryBuilder,
GenericActionCtx,
GenericMutationCtx,
GenericQueryCtx,
GenericDatabaseReader,
GenericDatabaseWriter,
} from "convex/server";
import {
actionGeneric,
httpActionGeneric,
queryGeneric,
mutationGeneric,
internalActionGeneric,
internalMutationGeneric,
internalQueryGeneric,
} from "convex/server";
import type { DataModel } from "./dataModel.js";
/**
* Define a query in this Convex app's public API.
*
* This function will be allowed to read your Convex database and will be accessible from the client.
*
* @param func - The query function. It receives a {@link QueryCtx} as its first argument.
* @returns The wrapped query. Include this as an `export` to name it and make it accessible.
*/
export const query: QueryBuilder<DataModel, "public"> = queryGeneric;
/**
* Define a query that is only accessible from other Convex functions (but not from the client).
*
* This function will be allowed to read from your Convex database. It will not be accessible from the client.
*
* @param func - The query function. It receives a {@link QueryCtx} as its first argument.
* @returns The wrapped query. Include this as an `export` to name it and make it accessible.
*/
export const internalQuery: QueryBuilder<DataModel, "internal"> =
internalQueryGeneric;
/**
* Define a mutation in this Convex app's public API.
*
* This function will be allowed to modify your Convex database and will be accessible from the client.
*
* @param func - The mutation function. It receives a {@link MutationCtx} as its first argument.
* @returns The wrapped mutation. Include this as an `export` to name it and make it accessible.
*/
export const mutation: MutationBuilder<DataModel, "public"> = mutationGeneric;
/**
* Define a mutation that is only accessible from other Convex functions (but not from the client).
*
* This function will be allowed to modify your Convex database. It will not be accessible from the client.
*
* @param func - The mutation function. It receives a {@link MutationCtx} as its first argument.
* @returns The wrapped mutation. Include this as an `export` to name it and make it accessible.
*/
export const internalMutation: MutationBuilder<DataModel, "internal"> =
internalMutationGeneric;
/**
* Define an action in this Convex app's public API.
*
* An action is a function which can execute any JavaScript code, including non-deterministic
* code and code with side-effects, like calling third-party services.
* They can be run in Convex's JavaScript environment or in Node.js using the "use node" directive.
* They can interact with the database indirectly by calling queries and mutations using the {@link ActionCtx}.
*
* @param func - The action. It receives an {@link ActionCtx} as its first argument.
* @returns The wrapped action. Include this as an `export` to name it and make it accessible.
*/
export const action: ActionBuilder<DataModel, "public"> = actionGeneric;
/**
* Define an action that is only accessible from other Convex functions (but not from the client).
*
* @param func - The function. It receives an {@link ActionCtx} as its first argument.
* @returns The wrapped function. Include this as an `export` to name it and make it accessible.
*/
export const internalAction: ActionBuilder<DataModel, "internal"> =
internalActionGeneric;
/**
* Define an HTTP action.
*
* The wrapped function will be used to respond to HTTP requests received
* by a Convex deployment if the requests matches the path and method where
* this action is routed. Be sure to route your httpAction in `convex/http.js`.
*
* @param func - The function. It receives an {@link ActionCtx} as its first argument
* and a Fetch API `Request` object as its second.
* @returns The wrapped function. Import this function from `convex/http.js` and route it to hook it up.
*/
export const httpAction: HttpActionBuilder = httpActionGeneric;
/**
* A set of services for use within Convex query functions.
*
* The query context is passed as the first argument to any Convex query
* function run on the server.
*
* If you're using code generation, use the `QueryCtx` type in `convex/_generated/server.d.ts` instead.
*/
export type QueryCtx = GenericQueryCtx<DataModel>;
/**
* A set of services for use within Convex mutation functions.
*
* The mutation context is passed as the first argument to any Convex mutation
* function run on the server.
*
* If you're using code generation, use the `MutationCtx` type in `convex/_generated/server.d.ts` instead.
*/
export type MutationCtx = GenericMutationCtx<DataModel>;
/**
* A set of services for use within Convex action functions.
*
* The action context is passed as the first argument to any Convex action
* function run on the server.
*/
export type ActionCtx = GenericActionCtx<DataModel>;
/**
* An interface to read from the database within Convex query functions.
*
* The two entry points are {@link DatabaseReader.get}, which fetches a single
* document by its {@link Id}, or {@link DatabaseReader.query}, which starts
* building a query.
*/
export type DatabaseReader = GenericDatabaseReader<DataModel>;
/**
* An interface to read from and write to the database within Convex mutation
* functions.
*
* Convex guarantees that all writes within a single mutation are
* executed atomically, so you never have to worry about partial writes leaving
* your data in an inconsistent state. See [the Convex Guide](https://docs.convex.dev/understanding/convex-fundamentals/functions#atomicity-and-optimistic-concurrency-control)
* for the guarantees Convex provides your functions.
*/
export type DatabaseWriter = GenericDatabaseWriter<DataModel>;

View file

@ -1,13 +0,0 @@
import { createApi } from "@convex-dev/better-auth";
import { createAuthOptions } from "../auth";
import schema from "./schema";
export const {
create,
findOne,
findMany,
updateOne,
updateMany,
deleteOne,
deleteMany,
} = createApi(schema, createAuthOptions);

View file

@ -1,4 +0,0 @@
import { createAuth } from '../auth';
// Export a static instance for Better Auth schema generation
export const auth = createAuth({} as any)

View file

@ -1,5 +0,0 @@
import { defineComponent } from "convex/server";
const component = defineComponent("betterAuth");
export default component;

View file

@ -1,60 +0,0 @@
import { UserIdentity } from "convex/server";
import { Doc, Id } from "../_generated/dataModel";
import { MutationCtx, query, QueryCtx } from "../_generated/server";
// Overload signatures
async function userValidation(ctx: MutationCtx | QueryCtx, options: { required: false }): Promise<{ userId: Id<"user">; user: any } | null>;
async function userValidation(ctx: MutationCtx | QueryCtx, options?: { required?: true }): Promise<{ userId: Id<"user">; user: UserIdentity }>;
// Implementation
async function userValidation(ctx: MutationCtx | QueryCtx, options?: { required?: boolean }) {
const required = options?.required ?? true;
const user = await ctx.auth.getUserIdentity();
if (!user) {
if (required) throw new Error("User not found");
return null;
}
const userId = ctx.db.normalizeId("user", user.subject as string) as Id<"user">;
if (!userId) {
if (required) throw new Error("User not found");
return null;
}
return { userId, user };
}
export const getUserNests = query({
handler: async (ctx) => {
const { userId } = await userValidation(ctx, { required: true });
if (!userId) throw new Error("User not found");
const getUser = await ctx.db.get<"user">(userId);
if (!getUser) throw new Error("User not found");
else if (!getUser.nests || getUser.nests.length === 0) return [];
// Get the nests the user is a member of
const nests: Doc<"nests">[] = [];
for (const nestId of getUser.nests) {
const nest = await ctx.db.get<"nests">(nestId);
if (!nest) continue;
nests.push(nest);
}
return nests;
}
});
export const getRecommendedNests = query({
handler: async (ctx) => {
const { userId } = await userValidation(ctx, { required: true });
if (!userId) throw new Error("User not found");
const getUser = await ctx.db.get<"user">(userId);
if (!getUser) throw new Error("User not found");
const nests = await ctx.db.query<"nests">("nests").withIndex("onDiscover", q => q.eq("onDiscover", true)).collect();
return nests;
}
});

View file

@ -1,143 +0,0 @@
import { v } from "convex/values";
import { mutation, query } from "../_generated/server";
export const sendKeysToServer = mutation({
args: {
userId: v.string(),
identityKey: v.object({
curve25519: v.string(),
ed25519: v.string(),
}),
oneTimeKeys: v.array(v.object({
keyId: v.string(),
publicKey: v.string(),
})),
forceInsert: v.boolean(), // if true, insert even if user already has an olm account
},
handler: async (ctx, args) => {
const now = Date.now();
// check if user already has an olm account
const olmAccount = await ctx.db.query("olmAccount").withIndex("userId", (q) => q.eq("userId", args.userId)).first();
if (olmAccount && !args.forceInsert) {
throw new Error("User already has an olm account");
} else if (olmAccount && args.forceInsert) {
// Keys are being rotated - increment version and update timestamp
await ctx.db.patch(olmAccount._id, {
identityKey: args.identityKey,
oneTimeKeys: args.oneTimeKeys,
updatedAt: now,
keyVersion: (olmAccount.keyVersion || 0) + 1,
});
// Notify all users who have sessions with this user that their sessions are now invalid
// This will be handled client-side by checking key versions
console.log(`[OLM] Keys rotated for user ${args.userId}, new version: ${(olmAccount.keyVersion || 0) + 1}`);
return { ...olmAccount, keyVersion: (olmAccount.keyVersion || 0) + 1 };
}
// Create new account with initial key version
const newOlmAccount = await ctx.db.insert<"olmAccount">("olmAccount", {
userId: args.userId,
identityKey: args.identityKey,
oneTimeKeys: args.oneTimeKeys || [],
createdAt: now,
updatedAt: now,
keyVersion: 1,
});
return newOlmAccount;
},
});
export const retrieveServerOlmAccount = query({
args: {
userId: v.string(),
},
handler: async (ctx, args) => {
const olmAccount = await ctx.db.query("olmAccount").withIndex("userId", (q) => q.eq("userId", args.userId)).first();
if (!olmAccount) return null;
// Ensure backward compatibility with old records that don't have keyVersion
return {
...olmAccount,
keyVersion: olmAccount.keyVersion ?? 1,
createdAt: olmAccount.createdAt ?? olmAccount._creationTime,
updatedAt: olmAccount.updatedAt ?? olmAccount._creationTime,
};
},
});
export const consumeOTK = mutation({
args: {
userId: v.string(),
keyId: v.string(),
},
handler: async (ctx, args) => {
const olmAccount = await ctx.db.query("olmAccount").withIndex("userId", (q) => q.eq("userId", args.userId)).first();
if (!olmAccount) throw new Error("User has no OLM account");
const oneTimeKeys = olmAccount.oneTimeKeys;
const keyIndex = oneTimeKeys.findIndex((key) => key.keyId === args.keyId);
if (keyIndex === -1) throw new Error("The key to be consumed was not found");
oneTimeKeys.splice(keyIndex, 1);
await ctx.db.patch(olmAccount._id, {
oneTimeKeys,
});
return {
consumed: true,
keysLeft: oneTimeKeys.length
}
},
});
export const getKeyVersion = query({
args: {
userId: v.string(),
},
handler: async (ctx, args) => {
const olmAccount = await ctx.db.query("olmAccount").withIndex("userId", (q) => q.eq("userId", args.userId)).first();
if (!olmAccount) return null;
return {
keyVersion: olmAccount.keyVersion ?? 1,
updatedAt: olmAccount.updatedAt ?? olmAccount._creationTime,
identityKey: olmAccount.identityKey,
};
},
});
/**
* Migration mutation to add keyVersion, createdAt, updatedAt to existing olmAccount records
* Run this once to migrate old records
*/
export const migrateOlmAccounts = mutation({
handler: async (ctx) => {
const accounts = await ctx.db.query("olmAccount").collect();
let updated = 0;
for (const account of accounts) {
// Only update if keyVersion is missing
if (account.keyVersion === undefined) {
await ctx.db.patch(account._id, {
keyVersion: 1, // Initial version for existing accounts
createdAt: account.createdAt ?? account._creationTime,
updatedAt: account.updatedAt ?? account._creationTime,
});
updated++;
}
}
return {
message: `Migrated ${updated} olmAccount records`,
total: accounts.length,
updated
};
},
});

View file

@ -1,116 +0,0 @@
// This file is auto-generated. Do not edit this file manually.
// To regenerate the schema, run:
// `npx @better-auth/cli generate --output undefined -y`
import { defineSchema, defineTable } from "convex/server";
import { v } from "convex/values";
import { nests } from "./schemas/nests";
import { user } from "./schemas/user";
const Attachment = v.object({
contentType: v.string(), // MIME type
description: v.union(v.null(), v.string()), // Description
ephemeral: v.boolean(), // Whether the attachment is ephemeral
height: v.optional(v.number()), // Height in pixels
width: v.optional(v.number()), // Width in pixels
id: v.id("storage"), // Storage ID
size: v.number(), // Size in bytes
spoiler: v.boolean(), // Whether the attachment is a spoiler
url: v.string(), // Public URL
});
const Message = v.object({
inGuild: v.optional(v.boolean()),
attachments: v.optional(v.array(v.id("attachments"))),
authorId: v.id("user"),
channelId: v.id("channel"),
content: v.string(),
createdAt: v.string(),
createdTimestamp: v.number(),
editedAt: v.optional(v.string()),
guildId: v.optional(v.id("guild")),
id: v.string(),
nonce: v.optional(v.string()),
position: v.optional(v.number()),
referencedMessage: v.optional(
v.union(v.null(), v.id("messages"), v.id("channel"), v.id("guild")),
),
url: v.optional(v.string()),
})
export const tables = {
...user,
...nests,
messages: defineTable(Message)
.index("channelId", ["channelId"])
.index("channelId_createdTimestamp", ["channelId", "createdTimestamp"])
.index("authorId", ["authorId"])
.index("guildId", ["guildId"]),
attachments: defineTable(Attachment),
session: defineTable({
expiresAt: v.number(),
token: v.string(),
createdAt: v.number(),
updatedAt: v.number(),
ipAddress: v.optional(v.union(v.null(), v.string())),
userAgent: v.optional(v.union(v.null(), v.string())),
userId: v.string(),
})
.index("expiresAt", ["expiresAt"])
.index("expiresAt_userId", ["expiresAt", "userId"])
.index("token", ["token"])
.index("userId", ["userId"]),
account: defineTable({
accountId: v.string(),
providerId: v.string(),
userId: v.string(),
accessToken: v.optional(v.union(v.null(), v.string())),
refreshToken: v.optional(v.union(v.null(), v.string())),
idToken: v.optional(v.union(v.null(), v.string())),
accessTokenExpiresAt: v.optional(v.union(v.null(), v.number())),
refreshTokenExpiresAt: v.optional(v.union(v.null(), v.number())),
scope: v.optional(v.union(v.null(), v.string())),
password: v.optional(v.union(v.null(), v.string())),
createdAt: v.number(),
updatedAt: v.number(),
})
.index("accountId", ["accountId"])
.index("accountId_providerId", ["accountId", "providerId"])
.index("providerId_userId", ["providerId", "userId"])
.index("userId", ["userId"]),
verification: defineTable({
identifier: v.string(),
value: v.string(),
expiresAt: v.number(),
createdAt: v.number(),
updatedAt: v.number(),
})
.index("expiresAt", ["expiresAt"])
.index("identifier", ["identifier"]),
jwks: defineTable({
publicKey: v.string(),
privateKey: v.string(),
createdAt: v.number(),
}),
olmAccount: defineTable({
userId: v.string(),
identityKey: v.object({
curve25519: v.string(),
ed25519: v.string(),
}),
oneTimeKeys: v.array(v.object({
keyId: v.string(),
publicKey: v.string(),
})),
createdAt: v.optional(v.number()),
updatedAt: v.optional(v.number()),
keyVersion: v.optional(v.number()), // Increments when keys are rotated
})
.index("userId", ["userId"])
.index("userId_keys", ["userId", "oneTimeKeys"])
.index("userId_identityKey", ["userId", "identityKey"]),
};
const schema = defineSchema(tables);
export default schema;

View file

@ -1,75 +0,0 @@
import { defineTable } from "convex/server";
import { v } from "convex/values";
export const nests = {
nests: defineTable({
type: v.union(v.literal("global"), v.literal("regional"), v.literal("private")),
name: v.string(),
description: v.optional(v.string()),
images: v.optional(
v.object({
banner: v.id("storage"),
icon: v.id("storage"),
})
),
colors: v.optional(
v.object({
primary: v.string(),
accent: v.string(),
})
),
createdAt: v.number(),
updatedAt: v.number(),
managerId: v.id("user"),
members: v.array(v.id("user")),
channels: v.array(v.id("channel")),
roles: v.array(v.id("role")),
region: v.optional(v.string()),
emojis: v.array(v.object({
id: v.id("storage"),
name: v.string(),
createdAt: v.number(),
})),
onDiscover: v.optional(v.boolean()),
})
.index("managerId", ["managerId"])
.index("type", ["type"])
.index("type_region", ["type", "region"])
.index("createdAt", ["createdAt"])
.index("onDiscover", ["onDiscover"]),
roles: defineTable({
nestId: v.id("nests"),
name: v.string(),
color: v.optional(v.string()),
hoist: v.optional(v.boolean()),
mentionable: v.optional(v.boolean()),
icon: v.optional(v.id("storage")),
position: v.optional(v.number()),
permissions: v.array(v.int64()), // Permissions as bitfield
flags: v.array(v.int64()), // Flags as bitfield
createdAt: v.number(),
updatedAt: v.number(),
members: v.array(v.id("user")),
})
.index("nestId", ["nestId"])
.index("nestId_position", ["nestId", "position"])
.index("nestId_members", ["nestId", "members"])
.index("members", ["members"]),
channels: defineTable({
type: v.union(v.literal("text"), v.literal("category"), v.literal("announcement")),
name: v.string(),
nestId: v.id("nests"),
position: v.number(),
permissions: v.array(v.int64()), // Permissions as bitfield
overwrites: v.array(v.object({
id: v.union(v.id("user"), v.id("role")),
allow: v.union(v.array(v.int64()), v.null()), // Permissions as bitfield
deny: v.union(v.array(v.int64()), v.null()), // Permissions as bitfield
})),
createdAt: v.number(),
updatedAt: v.number(),
})
.index("nestId", ["nestId"])
.index("nestId_position", ["nestId", "position"])
.index("nestId_type", ["nestId", "type"])
}

View file

@ -1,64 +0,0 @@
import { defineTable } from "convex/server";
import { v } from "convex/values";
export const user = {
user: defineTable({
name: v.string(),
email: v.string(),
emailVerified: v.boolean(),
image: v.optional(v.union(v.null(), v.string())),
createdAt: v.number(),
updatedAt: v.number(),
userId: v.optional(v.union(v.null(), v.string())),
username: v.optional(v.union(v.null(), v.string())),
displayUsername: v.optional(v.union(v.null(), v.string())),
metadata: v.optional(v.object({
phrasePreference: v.union(v.literal("comforting"), v.literal("mocking"), v.literal("both")),
})),
nests: v.optional(v.array(v.id("nests"))),
})
.index("email_name", ["email", "name"])
.index("nests", ["nests"])
.index("byName", ["name"])
.index("userId", ["userId"])
.index("username", ["username"]),
userStatus: defineTable({
userId: v.id("user"),
status: v.union(v.literal("online"), v.literal("busy"), v.literal("offline"), v.literal("away")),
userSetStatus: v.optional(
v.object({
status: v.union(v.literal("online"), v.literal("busy"), v.literal("offline"), v.literal("away")),
updatedAt: v.number(),
isSet: v.boolean(),
})
),
updatedAt: v.number(),
})
.index("userId", ["userId"])
.index("status", ["status"]),
friendRequests: defineTable({
userId: v.id("user"),
requestTo: v.id("user"),
method: v.union(v.literal("receive"), v.literal("send")),
requestId: v.string(),
createdAt: v.number(),
expiresAt: v.optional(v.number()),
acceptedAt: v.optional(v.number()),
declinedAt: v.optional(v.number()),
ignoredAt: v.optional(v.number()),
})
.index("userId_method", ["userId", "method"])
.index("userId", ["userId"])
.index("requestId", ["requestId"])
.index("userId_requestTo", ["userId", "requestTo"])
.index("requestTo", ["requestTo"])
.index("expiresAt", ["expiresAt"]),
friends: defineTable({
userId: v.id("user"),
friendId: v.id("user"),
createdAt: v.number(),
})
.index("userId", ["userId"])
.index("friendId", ["friendId"])
.index("userId_friendId", ["userId", "friendId"]),
}

View file

@ -1,446 +0,0 @@
import { v } from "convex/values";
import { Id } from "../_generated/dataModel";
import { mutation, MutationCtx, query, QueryCtx } from "../_generated/server";
// Overload signatures
async function userValidation(ctx: MutationCtx | QueryCtx, options: { required: false }): Promise<{ userId: Id<"user">; user: any } | null>;
async function userValidation(ctx: MutationCtx | QueryCtx, options?: { required?: true }): Promise<{ userId: Id<"user">; user: any }>;
// Implementation
async function userValidation(ctx: MutationCtx | QueryCtx, options?: { required?: boolean }) {
const required = options?.required ?? true;
const user = await ctx.auth.getUserIdentity();
if (!user) {
if (required) throw new Error("User not found");
return null;
}
const userId = ctx.db.normalizeId("user", user.subject as string) as Id<"user">;
if (!userId) {
if (required) throw new Error("User not found");
return null;
}
return { userId, user };
}
export const updateUserStatus = mutation({
args: {
status: v.union(v.literal("online"), v.literal("busy"), v.literal("offline"), v.literal("away")),
isUserSet: v.optional(v.boolean()),
},
handler: async (ctx, args) => {
try {
const { userId } = await userValidation(ctx);
const isUserSet = args.isUserSet ?? false;
const userStatus = await ctx.db.query("userStatus").withIndex("userId", (q) => q.eq("userId", userId)).first();
if (userStatus) {
let resolvedStatus = args.status;
// Restore user-set status when reconnecting
if (args.status === "online" && !isUserSet && userStatus.userSetStatus?.isSet) {
resolvedStatus = userStatus.userSetStatus.status;
}
await ctx.db.patch(userStatus._id, {
status: resolvedStatus,
userSetStatus: isUserSet
? { status: args.status, updatedAt: Date.now(), isSet: true }
: userStatus.userSetStatus,
updatedAt: Date.now(),
});
} else {
await ctx.db.insert("userStatus", {
userId: userId,
status: args.status,
userSetStatus: {
status: args.status,
updatedAt: Date.now(),
isSet: isUserSet,
},
updatedAt: Date.now(),
});
}
return { success: true, message: "User status updated successfully" };
} catch (error) {
console.error("Error updating user status:", error);
throw new Error("Failed to update user status");
}
},
});
export const getUserStatus = query({
handler: async (ctx) => {
const validation = await userValidation(ctx, { required: false });
if (!validation) {
return null; // User not authenticated
}
const { userId } = validation;
const userStatus = await ctx.db.query("userStatus").withIndex("userId", (q) => q.eq("userId", userId)).first();
return userStatus;
}
});
export const getNonOfflineUserIds = query({
args: {},
handler: async (ctx) => {
const results: { userId: string; status: string; isUserSet: boolean }[] = [];
for (const status of ["online", "busy", "away"] as const) {
const records = await ctx.db
.query("userStatus")
.withIndex("status", (q) => q.eq("status", status))
.collect();
for (const record of records) {
results.push({
userId: record.userId,
status: record.status,
isUserSet: record.userSetStatus?.isSet ?? false,
});
}
}
return results;
},
});
export const forceUserOffline = mutation({
args: {
userId: v.string(),
},
handler: async (ctx, args) => {
const normalizedId = ctx.db.normalizeId("user", args.userId);
if (!normalizedId) return;
const userStatus = await ctx.db
.query("userStatus")
.withIndex("userId", (q) => q.eq("userId", normalizedId))
.first();
if (!userStatus || userStatus.status === "offline") return;
await ctx.db.patch(userStatus._id, {
status: "offline",
userSetStatus: userStatus.userSetStatus ? {
status: userStatus.userSetStatus.status,
updatedAt: Date.now(),
isSet: userStatus.userSetStatus.isSet,
} : undefined,
updatedAt: Date.now(),
});
console.log(`[forceUserOffline] Set user ${args.userId} offline (was: ${userStatus.status})`);
},
});
export const updateUserMetadata = mutation({
args: {
metadata: v.object({
phrasePreference: v.union(v.literal("comforting"), v.literal("mocking"), v.literal("both")),
}),
},
handler: async (ctx, args) => {
const { userId } = await userValidation(ctx);
return ctx.db.patch("user", userId, {
metadata: args.metadata,
});
},
});
export const sendFriendRequest = mutation({
args: {
username: v.string(),
},
handler: async (ctx, args) => {
const { userId, user: currentUser } = await userValidation(ctx);
// Find the target user
const targetUser = await ctx.db.query("user").withIndex("byName", (q) => q.eq("name", args.username)).first();
if (!targetUser) {
throw new Error("User not found");
}
// Check if trying to send request to yourself
if (targetUser._id === userId) {
throw new Error("You cannot send a friend request to yourself");
}
// Check if already friends
const existingFriendship = await ctx.db
.query("friends")
.withIndex("userId_friendId", (q) => q.eq("userId", userId).eq("friendId", targetUser._id))
.first();
if (existingFriendship) {
throw new Error("You are already friends with this user");
}
// Check for existing requests in both directions
const existingRequests = await ctx.db
.query("friendRequests")
.filter((q) =>
q.or(
q.and(
q.eq(q.field("userId"), userId),
q.eq(q.field("requestTo"), targetUser._id)
),
q.and(
q.eq(q.field("userId"), targetUser._id),
q.eq(q.field("requestTo"), userId)
)
)
)
.filter((q) => q.eq(q.field("acceptedAt"), undefined))
.filter((q) => q.eq(q.field("declinedAt"), undefined))
.collect();
const existingSentRequest = existingRequests.find(r => r.userId === userId);
const incomingRequest = existingRequests.find(r => r.userId === targetUser._id);
if (existingSentRequest) {
throw new Error("You have already sent a friend request to this user");
}
if (incomingRequest) {
const timestamp = Date.now();
// Auto-accept the incoming request
await ctx.db.patch(incomingRequest._id, {
acceptedAt: timestamp,
});
// Create bidirectional friendship entries
await Promise.all([
ctx.db.insert("friends", {
userId: userId,
friendId: targetUser._id,
createdAt: timestamp,
}),
ctx.db.insert("friends", {
userId: targetUser._id,
friendId: userId,
createdAt: timestamp,
}),
]);
return {
success: true,
message: "Friend request accepted automatically (they had already sent you a request)",
};
}
// Create the friend request (single row)
const requestId = crypto.randomUUID();
await ctx.db.insert("friendRequests", {
userId: userId,
requestTo: targetUser._id,
method: "send",
requestId,
createdAt: Date.now(),
});
return {
success: true,
message: "Friend request sent successfully",
};
}
})
export const answerFriendRequest = mutation({
args: {
requestId: v.string(),
answer: v.union(v.literal("accept"), v.literal("decline"), v.literal("ignore")),
},
handler: async (ctx, args) => {
const { userId } = await userValidation(ctx);
// Get the friend request
const request = await ctx.db
.query("friendRequests")
.withIndex("requestId", (q) => q.eq("requestId", args.requestId))
.first();
if (!request) {
throw new Error("Request not found");
}
// Verify current user is the recipient
if (request.requestTo !== userId) {
throw new Error("You are not the recipient of this request");
}
// Check if already answered
if (request.acceptedAt || request.declinedAt || request.ignoredAt) {
throw new Error("Request already answered");
}
const timestamp = Date.now();
// Update the request based on the answer
switch (args.answer) {
case "accept":
// Update request status
await ctx.db.patch(request._id, { acceptedAt: timestamp });
// Create bidirectional friendship entries
await Promise.all([
ctx.db.insert("friends", {
userId: userId,
friendId: request.userId,
createdAt: timestamp,
}),
ctx.db.insert("friends", {
userId: request.userId,
friendId: userId,
createdAt: timestamp,
}),
]);
break;
case "decline":
await ctx.db.patch(request._id, { declinedAt: timestamp });
break;
case "ignore":
await ctx.db.patch(request._id, { ignoredAt: timestamp });
break;
}
return {
success: true,
message: `Friend request ${args.answer}ed successfully`,
};
}
})
export const getFriendRequests = query({
handler: async (ctx) => {
const { userId } = await userValidation(ctx);
// Get all unanswered requests involving this user (sent by them OR sent to them)
const allRequests = await ctx.db
.query("friendRequests")
.filter((q) =>
q.or(
q.eq(q.field("userId"), userId), // Requests sent by me
q.eq(q.field("requestTo"), userId) // Requests sent to me
)
)
.filter((q) => q.eq(q.field("acceptedAt"), undefined))
.filter((q) => q.eq(q.field("declinedAt"), undefined))
.filter((q) => q.eq(q.field("ignoredAt"), undefined))
.collect();
// Transform to include method field based on perspective
const requestsWithMethod = await Promise.all(
allRequests.map(async (request) => {
const isSentByMe = request.userId === userId;
const otherUserId = isSentByMe ? request.requestTo : request.userId;
const otherUser = await ctx.db.get(otherUserId);
return {
id: request.requestId,
_id: request._id,
userId: otherUserId,
username: otherUser?.username || otherUser?.displayUsername || otherUser?.name || "Unknown",
avatar: otherUser?.image || "",
createdAt: request.createdAt,
method: isSentByMe ? "send" : "receive",
};
})
);
return requestsWithMethod;
}
})
export const getFriends = query({
handler: async (ctx) => {
const { userId } = await userValidation(ctx);
// Get all friendships for this user
const friendships = await ctx.db
.query("friends")
.withIndex("userId", (q) => q.eq("userId", userId))
.collect();
// Populate friend data with relevant fields
const friends = await Promise.all(
friendships.map(async (friendship) => {
const friend = await ctx.db.get(friendship.friendId);
const friendStatus = await ctx.db.query("userStatus").withIndex("userId", (q) => q.eq("userId", friendship.friendId)).first();
if (!friend) return null;
return {
_id: friend._id,
id: friend._id,
name: friend.name,
username: friend.username,
displayUsername: friend.displayUsername,
image: friend.image,
friendshipCreatedAt: friendship.createdAt,
status: friendStatus ? {
status: friendStatus.status,
isUserSet: friendStatus.userSetStatus?.isSet ?? false,
} : {
status: "offline" as const,
isUserSet: false,
},
};
})
);
return friends.filter(Boolean);
}
})
export const getParticipantDetails = query({
args: {
participantIds: v.array(v.string()),
},
handler: async (ctx, args) => {
const { participantIds } = args;
const { userId } = await userValidation(ctx);
if (!userId) throw new Error("User not found");
if (participantIds.length === 0) return [];
const normalizedParticipantIds = participantIds.map((id) => ctx.db.normalizeId("user", id));
if (normalizedParticipantIds.length === 0) return [];
// Filter out all null values
const filteredParticipantIds = normalizedParticipantIds.filter((id) => id !== null);
if (filteredParticipantIds.length === 0) return [];
const participantDetails = await Promise.all(filteredParticipantIds.map(async (id) => {
const participant = await ctx.db.get("user", id)
const participantStatus = await ctx.db.query("userStatus").withIndex("userId", (q) => q.eq("userId", id)).first();
const participantOlmAccount = await ctx.db.query("olmAccount").withIndex("userId", (q) => q.eq("userId", id)).first();
if (!participant) return null;
// Ensure backward compatibility with old olmAccount records
const olmAccountWithDefaults = participantOlmAccount ? {
...participantOlmAccount,
keyVersion: participantOlmAccount.keyVersion ?? 1,
createdAt: participantOlmAccount.createdAt ?? participantOlmAccount._creationTime,
updatedAt: participantOlmAccount.updatedAt ?? participantOlmAccount._creationTime,
} : null;
return {
id: participant._id,
name: participant.name,
username: participant.username,
displayUsername: participant.displayUsername,
image: participant.image,
status: participantStatus?.status || "offline",
olmAccount: olmAccountWithDefaults,
}
}));
return participantDetails
}
})

View file

@ -1,7 +0,0 @@
import { defineApp } from "convex/server";
import betterAuth from "./betterAuth/convex.config";
const app = defineApp();
app.use(betterAuth);
export default app;

View file

@ -1,8 +0,0 @@
import { httpRouter } from "convex/server";
import { authComponent, createAuth } from "./auth";
const http = httpRouter();
authComponent.registerRoutes(http, createAuth);
export default http;

12
drizzle.config.ts Normal file
View file

@ -0,0 +1,12 @@
import dotenv from 'dotenv';
dotenv.config({ path: '.env.local' });
import { defineConfig } from 'drizzle-kit';
export default defineConfig({
out: './drizzle',
schema: './src/lib/db/schema/index.ts',
dialect: 'postgresql',
dbCredentials: {
url: process.env.DATABASE_URL!,
},
});

View file

@ -0,0 +1,53 @@
CREATE TABLE "account" (
"id" text PRIMARY KEY NOT NULL,
"account_id" text NOT NULL,
"provider_id" text NOT NULL,
"user_id" text NOT NULL,
"access_token" text,
"refresh_token" text,
"id_token" text,
"access_token_expires_at" timestamp,
"refresh_token_expires_at" timestamp,
"scope" text,
"password" text,
"created_at" timestamp DEFAULT now() NOT NULL,
"updated_at" timestamp NOT NULL
);
--> statement-breakpoint
CREATE TABLE "session" (
"id" text PRIMARY KEY NOT NULL,
"expires_at" timestamp NOT NULL,
"token" text NOT NULL,
"created_at" timestamp DEFAULT now() NOT NULL,
"updated_at" timestamp NOT NULL,
"ip_address" text,
"user_agent" text,
"user_id" text NOT NULL,
CONSTRAINT "session_token_unique" UNIQUE("token")
);
--> statement-breakpoint
CREATE TABLE "user" (
"id" text PRIMARY KEY NOT NULL,
"name" text NOT NULL,
"email" text NOT NULL,
"email_verified" boolean DEFAULT false NOT NULL,
"image" text,
"created_at" timestamp DEFAULT now() NOT NULL,
"updated_at" timestamp DEFAULT now() NOT NULL,
CONSTRAINT "user_email_unique" UNIQUE("email")
);
--> statement-breakpoint
CREATE TABLE "verification" (
"id" text PRIMARY KEY NOT NULL,
"identifier" text NOT NULL,
"value" text NOT NULL,
"expires_at" timestamp NOT NULL,
"created_at" timestamp DEFAULT now() NOT NULL,
"updated_at" timestamp DEFAULT now() NOT NULL
);
--> statement-breakpoint
ALTER TABLE "account" ADD CONSTRAINT "account_user_id_user_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."user"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "session" ADD CONSTRAINT "session_user_id_user_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."user"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
CREATE INDEX "account_userId_idx" ON "account" USING btree ("user_id");--> statement-breakpoint
CREATE INDEX "session_userId_idx" ON "session" USING btree ("user_id");--> statement-breakpoint
CREATE INDEX "verification_identifier_idx" ON "verification" USING btree ("identifier");

View file

@ -0,0 +1,374 @@
{
"id": "5e0d4aeb-3b1b-4137-b4a9-8a09a93c788f",
"prevId": "00000000-0000-0000-0000-000000000000",
"version": "7",
"dialect": "postgresql",
"tables": {
"public.account": {
"name": "account",
"schema": "",
"columns": {
"id": {
"name": "id",
"type": "text",
"primaryKey": true,
"notNull": true
},
"account_id": {
"name": "account_id",
"type": "text",
"primaryKey": false,
"notNull": true
},
"provider_id": {
"name": "provider_id",
"type": "text",
"primaryKey": false,
"notNull": true
},
"user_id": {
"name": "user_id",
"type": "text",
"primaryKey": false,
"notNull": true
},
"access_token": {
"name": "access_token",
"type": "text",
"primaryKey": false,
"notNull": false
},
"refresh_token": {
"name": "refresh_token",
"type": "text",
"primaryKey": false,
"notNull": false
},
"id_token": {
"name": "id_token",
"type": "text",
"primaryKey": false,
"notNull": false
},
"access_token_expires_at": {
"name": "access_token_expires_at",
"type": "timestamp",
"primaryKey": false,
"notNull": false
},
"refresh_token_expires_at": {
"name": "refresh_token_expires_at",
"type": "timestamp",
"primaryKey": false,
"notNull": false
},
"scope": {
"name": "scope",
"type": "text",
"primaryKey": false,
"notNull": false
},
"password": {
"name": "password",
"type": "text",
"primaryKey": false,
"notNull": false
},
"created_at": {
"name": "created_at",
"type": "timestamp",
"primaryKey": false,
"notNull": true,
"default": "now()"
},
"updated_at": {
"name": "updated_at",
"type": "timestamp",
"primaryKey": false,
"notNull": true
}
},
"indexes": {
"account_userId_idx": {
"name": "account_userId_idx",
"columns": [
{
"expression": "user_id",
"isExpression": false,
"asc": true,
"nulls": "last"
}
],
"isUnique": false,
"concurrently": false,
"method": "btree",
"with": {}
}
},
"foreignKeys": {
"account_user_id_user_id_fk": {
"name": "account_user_id_user_id_fk",
"tableFrom": "account",
"tableTo": "user",
"columnsFrom": [
"user_id"
],
"columnsTo": [
"id"
],
"onDelete": "cascade",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"policies": {},
"checkConstraints": {},
"isRLSEnabled": false
},
"public.session": {
"name": "session",
"schema": "",
"columns": {
"id": {
"name": "id",
"type": "text",
"primaryKey": true,
"notNull": true
},
"expires_at": {
"name": "expires_at",
"type": "timestamp",
"primaryKey": false,
"notNull": true
},
"token": {
"name": "token",
"type": "text",
"primaryKey": false,
"notNull": true
},
"created_at": {
"name": "created_at",
"type": "timestamp",
"primaryKey": false,
"notNull": true,
"default": "now()"
},
"updated_at": {
"name": "updated_at",
"type": "timestamp",
"primaryKey": false,
"notNull": true
},
"ip_address": {
"name": "ip_address",
"type": "text",
"primaryKey": false,
"notNull": false
},
"user_agent": {
"name": "user_agent",
"type": "text",
"primaryKey": false,
"notNull": false
},
"user_id": {
"name": "user_id",
"type": "text",
"primaryKey": false,
"notNull": true
}
},
"indexes": {
"session_userId_idx": {
"name": "session_userId_idx",
"columns": [
{
"expression": "user_id",
"isExpression": false,
"asc": true,
"nulls": "last"
}
],
"isUnique": false,
"concurrently": false,
"method": "btree",
"with": {}
}
},
"foreignKeys": {
"session_user_id_user_id_fk": {
"name": "session_user_id_user_id_fk",
"tableFrom": "session",
"tableTo": "user",
"columnsFrom": [
"user_id"
],
"columnsTo": [
"id"
],
"onDelete": "cascade",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {
"session_token_unique": {
"name": "session_token_unique",
"nullsNotDistinct": false,
"columns": [
"token"
]
}
},
"policies": {},
"checkConstraints": {},
"isRLSEnabled": false
},
"public.user": {
"name": "user",
"schema": "",
"columns": {
"id": {
"name": "id",
"type": "text",
"primaryKey": true,
"notNull": true
},
"name": {
"name": "name",
"type": "text",
"primaryKey": false,
"notNull": true
},
"email": {
"name": "email",
"type": "text",
"primaryKey": false,
"notNull": true
},
"email_verified": {
"name": "email_verified",
"type": "boolean",
"primaryKey": false,
"notNull": true,
"default": false
},
"image": {
"name": "image",
"type": "text",
"primaryKey": false,
"notNull": false
},
"created_at": {
"name": "created_at",
"type": "timestamp",
"primaryKey": false,
"notNull": true,
"default": "now()"
},
"updated_at": {
"name": "updated_at",
"type": "timestamp",
"primaryKey": false,
"notNull": true,
"default": "now()"
}
},
"indexes": {},
"foreignKeys": {},
"compositePrimaryKeys": {},
"uniqueConstraints": {
"user_email_unique": {
"name": "user_email_unique",
"nullsNotDistinct": false,
"columns": [
"email"
]
}
},
"policies": {},
"checkConstraints": {},
"isRLSEnabled": false
},
"public.verification": {
"name": "verification",
"schema": "",
"columns": {
"id": {
"name": "id",
"type": "text",
"primaryKey": true,
"notNull": true
},
"identifier": {
"name": "identifier",
"type": "text",
"primaryKey": false,
"notNull": true
},
"value": {
"name": "value",
"type": "text",
"primaryKey": false,
"notNull": true
},
"expires_at": {
"name": "expires_at",
"type": "timestamp",
"primaryKey": false,
"notNull": true
},
"created_at": {
"name": "created_at",
"type": "timestamp",
"primaryKey": false,
"notNull": true,
"default": "now()"
},
"updated_at": {
"name": "updated_at",
"type": "timestamp",
"primaryKey": false,
"notNull": true,
"default": "now()"
}
},
"indexes": {
"verification_identifier_idx": {
"name": "verification_identifier_idx",
"columns": [
{
"expression": "identifier",
"isExpression": false,
"asc": true,
"nulls": "last"
}
],
"isUnique": false,
"concurrently": false,
"method": "btree",
"with": {}
}
},
"foreignKeys": {},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"policies": {},
"checkConstraints": {},
"isRLSEnabled": false
}
},
"enums": {},
"schemas": {},
"sequences": {},
"roles": {},
"policies": {},
"views": {},
"_meta": {
"columns": {},
"schemas": {},
"tables": {}
}
}

View file

@ -0,0 +1,13 @@
{
"version": "7",
"dialect": "postgresql",
"entries": [
{
"idx": 0,
"version": "7",
"when": 1772741645429,
"tag": "0000_lazy_slyde",
"breakpoints": true
}
]
}

View file

@ -1,44 +0,0 @@
const fs = require('fs');
const path = require('path');
// Load .env.local if it exists
function loadEnvFile(filename) {
const envPath = path.resolve(__dirname, filename);
if (!fs.existsSync(envPath)) return {};
const content = fs.readFileSync(envPath, 'utf-8');
const env = {};
for (const line of content.split('\n')) {
const trimmed = line.trim();
if (!trimmed || trimmed.startsWith('#')) continue;
const [key, ...rest] = trimmed.split('=');
if (key) env[key.trim()] = rest.join('=').trim().replace(/^["']|["']$/g, '');
}
return env;
}
const envLocal = loadEnvFile('.env.local');
module.exports = {
apps: [
{
name: 'sipher',
script: 'src/server.ts',
interpreter: 'node_modules/.bin/tsx',
instances: 1,
exec_mode: 'fork',
watch: false,
max_memory_restart: '4G',
env: {
...envLocal,
NODE_ENV: 'development',
PORT: 3000,
},
env_production: {
...envLocal,
NODE_ENV: 'production',
PORT: 8081,
},
},
],
};

View file

@ -1,70 +1,79 @@
{ {
"name": "sipher", "name": "silent-whisper",
"description": "A federated social media platform for the modern age.",
"author": [
{
"name": "Marcello Brito",
"alias": "Tocka",
"email": "tocka@tockanest.com",
"url": "https://tockanest.com"
}
],
"license": "AGPL-3.0",
"version": "0.1.0", "version": "0.1.0",
"private": true, "private": true,
"scripts": { "scripts": {
"postinstall": "bun src/lib/scripts/copy-olm.ts", "dev": "next dev",
"dev": "cross-env NODE_ENV=development PORT=3000 tsx src/server.ts", "build": "next build",
"build": "bun src/lib/scripts/copy-olm.ts && convex deploy --cmd \"next build\"", "start": "next start",
"build:local": "bun src/lib/scripts/copy-olm.ts && next build", "db:push": "drizzle-kit push",
"start": "cross-env NODE_ENV=production PORT=8081 tsx src/server.ts", "db:migrate": "bun run db:push && bun run drizzle-kit migrate"
"start:dev": "cross-env NODE_ENV=development PORT=3000 tsx src/server.ts"
}, },
"dependencies": { "dependencies": {
"@convex-dev/better-auth": "^0.10.10", "@better-auth/drizzle-adapter": "^1.5.3",
"@marsidev/react-turnstile": "^1.4.2", "@marsidev/react-turnstile": "^1.4.2",
"@matrix-org/olm": "^3.2.15",
"@nanostores/react": "^1.0.0", "@nanostores/react": "^1.0.0",
"@phosphor-icons/react": "^2.1.10", "better-auth": "^1.5.3",
"@radix-ui/react-avatar": "^1.1.11", "bullmq": "^5.70.2",
"@radix-ui/react-checkbox": "^1.3.3",
"@radix-ui/react-context-menu": "^2.2.16",
"@radix-ui/react-dialog": "^1.1.15",
"@radix-ui/react-hover-card": "^1.1.15",
"@radix-ui/react-label": "^2.1.8",
"@radix-ui/react-menubar": "^1.1.16",
"@radix-ui/react-popover": "^1.1.15",
"@radix-ui/react-progress": "^1.1.8",
"@radix-ui/react-scroll-area": "^1.2.10",
"@radix-ui/react-separator": "^1.1.8",
"@radix-ui/react-slot": "^1.2.4",
"@radix-ui/react-tooltip": "^1.2.8",
"@types/bun": "^1.3.9",
"@types/libsodium-wrappers": "^0.7.14",
"better-auth": "1.4.12",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"cmdk": "^1.1.1",
"convex": "^1.31.7",
"cross-env": "^10.1.0",
"date-fns": "^4.1.0",
"dexie": "^4.3.0", "dexie": "^4.3.0",
"dexie-react-hooks": "^4.2.0", "dexie-react-hooks": "^4.2.0",
"dotenv": "^17.3.1", "dotenv": "^17.3.1",
"framer-motion": "^12.34.0", "drizzle-orm": "^0.45.1",
"lucide-react": "^0.562.0", "express": "^5.2.1",
"moment": "^2.30.1", "http-signature": "^1.4.0",
"nanostores": "^1.1.0", "ioredis": "^5.10.0",
"next": "16.1.1", "nanostores": "^1.1.1",
"next": "16.1.6",
"next-themes": "^0.4.6", "next-themes": "^0.4.6",
"node-forge": "^1.3.3",
"pg": "^8.20.0",
"react": "19.2.3", "react": "19.2.3",
"react-day-picker": "^9.13.1",
"react-dom": "19.2.3", "react-dom": "19.2.3",
"socket.io": "^4.8.3", "socket.io": "^4.8.3",
"socket.io-client": "^4.8.3", "socket.io-client": "^4.8.3"
"sonner": "^2.0.7",
"tailwind-merge": "^3.4.0",
"zod": "^4.3.6"
}, },
"devDependencies": { "devDependencies": {
"@tailwindcss/postcss": "^4.1.18", "@tailwindcss/postcss": "^4",
"@types/node": "^25.2.2", "@types/bun": "^1.3.10",
"@types/react": "^19.2.13", "@types/node": "^20",
"@types/react-dom": "^19.2.3", "@types/pg": "^8.18.0",
"@types/react": "^19",
"@types/react-dom": "^19",
"babel-plugin-react-compiler": "1.0.0", "babel-plugin-react-compiler": "1.0.0",
"tailwindcss": "^4.1.18", "cross-env": "^10.1.0",
"drizzle-kit": "^0.31.9",
"tailwindcss": "^4",
"tsx": "^4.21.0", "tsx": "^4.21.0",
"tw-animate-css": "^1.4.0", "typescript": "^5"
"typescript": "^5.9.3" },
} "ignoreScripts": [
"sharp",
"unrs-resolver"
],
"trustedDependencies": [
"sharp",
"unrs-resolver"
],
"repository": {
"type": "git",
"url": "https://github.com/tockawaffle/sipher.git"
},
"bugs": {
"url": "https://github.com/tockawaffle/sipher/issues"
},
"keywords": [
"social",
"media",
"federated"
]
} }

File diff suppressed because one or more lines are too long

Before

Width:  |  Height:  |  Size: 5.8 KiB

View file

@ -1,38 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg id="Camada_1" xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="0 0 1024 1024">
<!-- Generator: Adobe Illustrator 29.8.1, SVG Export Plug-In . SVG Version: 2.1.1 Build 2) -->
<defs>
<style>
.st0 {
fill: #d3d0cb;
}
.st1 {
fill: #fff;
}
.st2 {
display: none;
}
</style>
</defs>
<g>
<path class="st0" d="M775.3,448.2c-7.1-39.8-22.1-69-51.4-97.7-4.2-3.8-8.8-8-.3-5.7,5.7,1.6,12.7,4.5,17.9,7.5,3.4,1.8,6,3.6,7.5,3.3,1.2-.5.5-3.1-1-6.8-2.2-4.9-5.6-11.2-8.9-16.4-12.3-20.3-27.7-36-45.5-51.7-6.7-6.1-16.9-14.1-23.7-17.2-3.6-1.8-7.2-3.6-10.9-5-2.8-1.1-6.3-2-3.4-2.7,5.8-.7,21.2.8,28.9,2.5,2.8.2,12.6,3.5,12.5,1.5-5.1-5.8-15.9-10.6-23.4-14.3-10.6-4.8-19.8-8.6-30.7-11-7.1-2-16.8-1.5-23.5-3-2.1-.7,6.7-3.1,11.1-3.6,5.2-.8,10.8-1.3,15.8-1.1,4.5,0,9.3.6,10.4,0,.4-.2.4-.4.2-.8-6.9-5.5-19.6-9-28.5-11.2-13.2-2.8-26-3.6-39.2-3.2-8.1,0-18.5,2.8-26.1,3.9-5,.1,6.7-5.4,8.2-6.1,2.7-1.8,18.1-5.3,9.4-6.2-16.9-1.3-36.3.8-52.6,6.6-6.4,1.9-13.5,7-19,9.9-.1,0-.2,0-.1,0,0-.5,3.9-4.3,7.3-7.2,2.1-1.8,4.3-3.5,6.4-4.9,8.2-5.4,9.3-6.8.4-4.7-9.1,2.5-18,5.6-26.1,10-5.7,2.8-11.1,7.6-16.3,10.6-3.5.9,1.7-5.9,2.4-7.1,4.3-6.2-13.7,3.8-14.9,5.1-12,8.3-23.4,16.8-34.3,26.3-14.2,12.5-11.7,14.9-32.2,14.9-20.7,0-40.2,2.7-60.8,6.9-34.8,7.7-68.1,22.4-92.1,51.5-7.2,9.7-15.4,25.9-19.8,37.7-.6,1.6-1.3,3.2-1.7,4.5-.2.5,0,.7.6.6l2.4-.4c2.2-.3,4.1-.5,6.4-.8,5.7-.7,9.8-1.1,16.1-1.7,27.4-2.3,52.8-5,81.8-2.5,22.6,1.9,46.5,3.4,67.1,13.2,33.7,14.5,48.2,49.8,40.6,82.2-6.6,29.3-24.7,45.9-40.5,67.8-4.4,5.8-28.3,44.8-14.5,40.9,3.9.1,26.7-20.1,21-8.6-5.8,10.1-8.8,20.9-10.1,33-4.1,23.9-3.1,52.6,7.1,74.8,1.9,3.3,3.1,3.3,3.9-.1,1.1-4.5,1.8-9.5,3.5-14.3,1.7-4.6,6.1-17.7,10.5-19.5.8,0,1.3,1.3,1.5,3.4.3,2.6,0,6.2,0,9.1,0,6.4,2.8,38.3,20.3,69.5,5.9,10.5,15.7,25.4,31.4,40.1,9.3,8.2,14.6,12.8,15,11,0-.4-.5-4-.6-5.2-.3-3-.6-5.2-.2-9.6,1-10.4,4.6-20.4,8.6-30,4.2-9.7,10.5-19.6,15.6-28.2,10.2-17.9,24-34.9,38.2-50.2,16.4-17.4,61.4-63.2,68.4-57.8.2,8.4-14.2,27.5-20.3,34.5-1.9,2.2-4.1,4.5-6.2,6.6-9.5,9.1-11.4,12.1.7,8.5,8.9-3,19.2-7.9,27.6-12.4,13-7,25.3-13.8,36.6-24.3,8.2-7.5,14.7-16.1,20.1-26,9.3-14.3,14.3-43.1,19-38,5,7,5,28.2,5.9,39.1.6,3.9-.7,17.3,4,13.7,10.1-11.1,14.2-30.5,17.1-44.9.6-1.9,1-10.7,4.2-6.4,6,12.3,7.1,26.3,8,40,1.5,13.7-3.6,43.1,4.4,26.7,6.7-14.5,14.5-29.8,17.3-44.5,2.1-9.9,2.5-19.2,2.5-28.7,0-14.3,0-25.4-3.5-44.1-3.1-15.3-7.7-28-14.4-41.8-4.4-9.2-8.3-15.4-10.9-21.8-1.5-5.2,5.8.3,7.3,1.5,5.8,4.8,10.2,9.3,15.1,15.3,2.3,2.9,4.6,6,6.8,9.1,8.8,12.9,14.6,26.3,12.4,6.2ZM520.8,289.4c6.4,0,11.5,5.2,11.5,11.5s-5.2,11.5-11.5,11.5-11.5-5.2-11.5-11.5,5.2-11.5,11.5-11.5ZM407.3,328.3c-13.6-1.5-27.7-2-41.6-2.2-20.2-.3-40.8-.6-60.7,2-12.8,2-25.6,3.4-37.7,7.8-2,.6-6,3.1-4.5.3h0c4.7-7.1,11.1-12.1,17.8-16.9,8.5-6.3,17-11.6,26.4-15.6,12.4-5.7,25.8-10.4,39.2-12.8,14.7-2.3,32-4.3,47.2-4.1,8.2.2,18.2-.3,26.1.7,1.4.5-2.7,1.5-5.2,2.2-4.4,1.2-7.8,2.1-12.4,3.4-5.9,1.7-11.9,3.5-16.5,5.3-1.9.7-4.8,1.9-6.6,2.9-1,.5-1.5.9-1.5,1.2.6.7,2.5.4,4.7.5,4.8,0,10.3.4,15,1,8.3,1,16.8,2.5,25.1,4.3,7.6,1.6,12.4,2.4,17.6,4.1,14.7,4.9,28.6,13.1,40,23.5,2.8,2.5,5.9,5.8,8.3,8.5,1,1.2,1.7,2,1.5,2.2-.4.4-3.6-1.1-4.6-1.5-9-4-19.8-6.3-29.4-8.7-15.6-3.6-32.2-6.1-48.5-8.2ZM478.3,533.9c-2.9,3.7-3.7,4.7-5,6-2.2,2.3-3.3,3.4-4.9,4-.8.3-3.3,1.2-5.9,0-1.9-.9-2.8-2.5-3.1-3-2-3.5-.3-7.3,0-7.8.4-.8.8-1.5,5.1-5,2.9-2.3,4.7-3.8,8-6.1,1.5-1.1,3-2.1,6-4,6.1-4,7.5-4.8,11-7.2,2.4-1.6,4.3-3,5.7-4-.7,1.8-1.9,4.7-3.8,7.9-1,1.8-1.2,1.8-3.9,6.2-3.2,5.1-3.4,5.7-5,7.9-.3.3-1.5,1.9-4,5ZM533.7,546.6c-2,4.8-4.2,9.4-5.9,14.3-5.5,14.9-9.6,30.1-15,45.1-1.8,5.3-3.5,11.1-7.7,14.9-8.5,8.8-21,2.8-21.1-8.9,0-2.4.5-4.8,1.4-7,5.5-11.5,11.6-21.1,19.7-31.5,6-7.2,12.6-14.5,19.2-20.9h.1c1.2-1.1,10.9-10.3,9.3-6ZM577.9,528.4c-3.2,3.6-8.1,5.2-12.6,2.9-4.4-2.1-6.1-7.7-5.4-12.2,1.1-5.5,5.9-11.9,9.5-17.3,5.5-8.2,8.8-16.1,12.4-26.4.2-.7.6-2,1-2.3h0c.5-.2.8,1.4.9,1.9,4.1,17.3,9.4,38.4-5.8,53.3ZM645.2,492.5c-.7,4-4.1,8-8.5,8.1-3,.2-6.3-1.4-8.8-3.1-7.1-6.6-5.1-16.8-6.7-25.2-1.9-10-4.6-20.3-10.9-28.1,0,0,0-.1,0,0,16,10.1,35.6,27.5,34.8,48.4ZM685.2,438.4c0,1.4,0,1.4-.2,2.1-.2,1.1-.9,2.8-1.6,3.7l-.5.6c-.9,1.2-2.1,2.2-3.4,2.8l-.8.4c-.8.4-1.6.6-2.4.8l-1.2.2c-1.1.2-2.1.2-3.2,0-1.3-.2-2.5-.6-3.6-1.2l-.5-.3c-.4-.3-.9-.5-1.3-.9-5.1-4.5-7-12.8-8.9-19-2-6.4-6.2-14.8-9.5-20.6-8.9-13.5-20.7-26-33.6-35.7,0,0,0,0,0,0,23.9,7.6,46.9,23.1,61.9,43.4,3.8,6.6,8.9,14.3,8.9,22.7s0,0,0,1Z"/>
<g class="st2">
<path class="st1" d="M489.8,346.7c.1-.3-.5-1.1-1.5-2.2-2.4-2.7-5.5-6-8.3-8.5-11.5-10.4-25.3-18.6-40-23.5-5.2-1.7-10-2.6-17.6-4.1-8.3-1.9-16.8-3.3-25.1-4.3-4.7-.6-10.2-1-15-1-2.2-.1-4.1.2-4.7-.5,0-.3.5-.7,1.5-1.2,1.8-1,4.7-2.1,6.6-2.9,4.6-1.8,10.7-3.6,16.5-5.3,4.6-1.3,8-2.2,12.4-3.4,2.5-.7,6.6-1.7,5.2-2.2-7.9-1-17.9-.4-26.1-.7-15.2-.2-32.6,1.8-47.2,4.1-13.4,2.5-26.8,7.1-39.2,12.8-9.5,4-18,9.3-26.4,15.6-6.7,4.8-13.2,9.8-17.8,16.7h0c-1.6,2.9,2.5.5,4.5-.1,12.1-4.4,24.9-5.8,37.7-7.8,20-2.6,40.5-2.3,60.7-2,13.9.3,28,.7,41.6,2.2,16.3,2.1,32.9,4.5,48.5,8.2,9.6,2.4,20.4,4.7,29.4,8.7,1.1.4,4.2,1.9,4.6,1.5Z"/>
<circle class="st1" cx="520.8" cy="300.9" r="11.5" transform="translate(-41.5 87.3) rotate(-9.2)"/>
<path class="st1" d="M614.5,371.3s0,0,0,0c12.9,9.7,24.7,22.2,33.6,35.7,3.3,5.8,7.5,14.2,9.5,20.6,1.9,6.2,3.7,14.5,8.9,19,.4.3.8.6,1.3.9l.5.3c1.1.6,2.3,1.1,3.6,1.2,1.1.1,2.1.1,3.2,0l1.2-.2c.8-.2,1.6-.4,2.4-.8l.8-.4c1.4-.7,2.5-1.6,3.4-2.8l.5-.6c.7-.9,1.4-2.6,1.6-3.7.1-.7.2-.7.2-2.1,0-1.1,0-.7,0-1,0-8.4-5-16.2-8.9-22.7-15-20.3-37.9-35.8-61.9-43.4Z"/>
<path class="st1" d="M610.5,444.2c0,0-.1,0,0,0,6.3,7.7,9,18.1,10.9,28.1,1.6,8.4-.4,18.5,6.7,25.2,2.4,1.7,5.7,3.3,8.8,3.1,4.3-.1,7.7-4.1,8.5-8.1.9-20.9-18.8-38.3-34.8-48.4Z"/>
<path class="st1" d="M582.8,473.1h0c-.4.3-.8,1.6-1,2.3-3.6,10.3-6.9,18.1-12.4,26.4-3.5,5.4-8.3,11.9-9.5,17.3-.7,4.5,1,10.1,5.4,12.2,4.5,2.3,9.4.7,12.6-2.9,15.3-15,10-36,5.8-53.3-.2-.5-.4-2.1-.9-2Z"/>
<path class="st1" d="M491.2,514.8c1.9-3.3,3.1-6.1,3.8-7.9-1.4,1-3.3,2.4-5.7,4-3.5,2.4-5,3.2-11,7.2-2.9,1.9-4.4,2.9-6,4-3.3,2.3-5.1,3.8-8,6.1-4.2,3.5-4.7,4.2-5.1,5-.3.6-2,4.3,0,7.8.3.5,1.2,2.1,3.1,3,2.6,1.2,5.2.3,5.9,0,1.6-.6,2.8-1.8,4.9-4,1.3-1.3,2.1-2.3,5-6,2.5-3.1,3.7-4.7,4-5,1.6-2.3,1.8-2.8,5-7.9,2.8-4.4,2.9-4.4,3.9-6.2Z"/>
<path class="st1" d="M524.5,552.5h-.1c-6.6,6.5-13.2,13.8-19.2,21-8,10.4-14.2,20.1-19.7,31.5-.9,2.2-1.4,4.6-1.4,7,0,11.7,12.5,17.6,21.1,8.9,4.2-3.8,5.9-9.6,7.7-14.9,5.3-15,9.4-30.2,15-45.1,1.7-4.9,3.9-9.5,5.9-14.3,1.6-4.4-8,4.9-9.3,5.8Z"/>
</g>
</g>
<g>
<circle class="st0" cx="695.1" cy="187.8" r="7.7"/>
<circle class="st0" cx="685.8" cy="222" r="4.5"/>
<ellipse class="st0" cx="731" cy="209.2" rx="4.2" ry="3.5"/>
<circle class="st0" cx="731" cy="243.6" r="7.2"/>
<circle class="st0" cx="745.2" cy="273.8" r="4.1"/>
</g>
</svg>

Before

Width:  |  Height:  |  Size: 6.6 KiB

1
public/file.svg Normal file
View file

@ -0,0 +1 @@
<svg fill="none" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><path d="M14.5 13.5V5.41a1 1 0 0 0-.3-.7L9.8.29A1 1 0 0 0 9.08 0H1.5v13.5A2.5 2.5 0 0 0 4 16h8a2.5 2.5 0 0 0 2.5-2.5m-1.5 0v-7H8v-5H3v12a1 1 0 0 0 1 1h8a1 1 0 0 0 1-1M9.5 5V2.12L12.38 5zM5.13 5h-.62v1.25h2.12V5zm-.62 3h7.12v1.25H4.5zm.62 3h-.62v1.25h7.12V11z" clip-rule="evenodd" fill="#666" fill-rule="evenodd"/></svg>

After

Width:  |  Height:  |  Size: 391 B

1
public/globe.svg Normal file
View file

@ -0,0 +1 @@
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><g clip-path="url(#a)"><path fill-rule="evenodd" clip-rule="evenodd" d="M10.27 14.1a6.5 6.5 0 0 0 3.67-3.45q-1.24.21-2.7.34-.31 1.83-.97 3.1M8 16A8 8 0 1 0 8 0a8 8 0 0 0 0 16m.48-1.52a7 7 0 0 1-.96 0H7.5a4 4 0 0 1-.84-1.32q-.38-.89-.63-2.08a40 40 0 0 0 3.92 0q-.25 1.2-.63 2.08a4 4 0 0 1-.84 1.31zm2.94-4.76q1.66-.15 2.95-.43a7 7 0 0 0 0-2.58q-1.3-.27-2.95-.43a18 18 0 0 1 0 3.44m-1.27-3.54a17 17 0 0 1 0 3.64 39 39 0 0 1-4.3 0 17 17 0 0 1 0-3.64 39 39 0 0 1 4.3 0m1.1-1.17q1.45.13 2.69.34a6.5 6.5 0 0 0-3.67-3.44q.65 1.26.98 3.1M8.48 1.5l.01.02q.41.37.84 1.31.38.89.63 2.08a40 40 0 0 0-3.92 0q.25-1.2.63-2.08a4 4 0 0 1 .85-1.32 7 7 0 0 1 .96 0m-2.75.4a6.5 6.5 0 0 0-3.67 3.44 29 29 0 0 1 2.7-.34q.31-1.83.97-3.1M4.58 6.28q-1.66.16-2.95.43a7 7 0 0 0 0 2.58q1.3.27 2.95.43a18 18 0 0 1 0-3.44m.17 4.71q-1.45-.12-2.69-.34a6.5 6.5 0 0 0 3.67 3.44q-.65-1.27-.98-3.1" fill="#666"/></g><defs><clipPath id="a"><path fill="#fff" d="M0 0h16v16H0z"/></clipPath></defs></svg>

After

Width:  |  Height:  |  Size: 1 KiB

1
public/next.svg Normal file
View file

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 394 80"><path fill="#000" d="M262 0h68.5v12.7h-27.2v66.6h-13.6V12.7H262V0ZM149 0v12.7H94v20.4h44.3v12.6H94v21h55v12.6H80.5V0h68.7zm34.3 0h-17.8l63.8 79.4h17.9l-32-39.7 32-39.6h-17.9l-23 28.6-23-28.6zm18.3 56.7-9-11-27.1 33.7h17.8l18.3-22.7z"/><path fill="#000" d="M81 79.3 17 0H0v79.3h13.6V17l50.2 62.3H81Zm252.6-.4c-1 0-1.8-.4-2.5-1s-1.1-1.6-1.1-2.6.3-1.8 1-2.5 1.6-1 2.6-1 1.8.3 2.5 1a3.4 3.4 0 0 1 .6 4.3 3.7 3.7 0 0 1-3 1.8zm23.2-33.5h6v23.3c0 2.1-.4 4-1.3 5.5a9.1 9.1 0 0 1-3.8 3.5c-1.6.8-3.5 1.3-5.7 1.3-2 0-3.7-.4-5.3-1s-2.8-1.8-3.7-3.2c-.9-1.3-1.4-3-1.4-5h6c.1.8.3 1.6.7 2.2s1 1.2 1.6 1.5c.7.4 1.5.5 2.4.5 1 0 1.8-.2 2.4-.6a4 4 0 0 0 1.6-1.8c.3-.8.5-1.8.5-3V45.5zm30.9 9.1a4.4 4.4 0 0 0-2-3.3 7.5 7.5 0 0 0-4.3-1.1c-1.3 0-2.4.2-3.3.5-.9.4-1.6 1-2 1.6a3.5 3.5 0 0 0-.3 4c.3.5.7.9 1.3 1.2l1.8 1 2 .5 3.2.8c1.3.3 2.5.7 3.7 1.2a13 13 0 0 1 3.2 1.8 8.1 8.1 0 0 1 3 6.5c0 2-.5 3.7-1.5 5.1a10 10 0 0 1-4.4 3.5c-1.8.8-4.1 1.2-6.8 1.2-2.6 0-4.9-.4-6.8-1.2-2-.8-3.4-2-4.5-3.5a10 10 0 0 1-1.7-5.6h6a5 5 0 0 0 3.5 4.6c1 .4 2.2.6 3.4.6 1.3 0 2.5-.2 3.5-.6 1-.4 1.8-1 2.4-1.7a4 4 0 0 0 .8-2.4c0-.9-.2-1.6-.7-2.2a11 11 0 0 0-2.1-1.4l-3.2-1-3.8-1c-2.8-.7-5-1.7-6.6-3.2a7.2 7.2 0 0 1-2.4-5.7 8 8 0 0 1 1.7-5 10 10 0 0 1 4.3-3.5c2-.8 4-1.2 6.4-1.2 2.3 0 4.4.4 6.2 1.2 1.8.8 3.2 2 4.3 3.4 1 1.4 1.5 3 1.5 5h-5.8z"/></svg>

After

Width:  |  Height:  |  Size: 1.3 KiB

1
public/vercel.svg Normal file
View file

@ -0,0 +1 @@
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1155 1000"><path d="m577.3 0 577.4 1000H0z" fill="#fff"/></svg>

After

Width:  |  Height:  |  Size: 128 B

1
public/window.svg Normal file
View file

@ -0,0 +1 @@
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><path fill-rule="evenodd" clip-rule="evenodd" d="M1.5 2.5h13v10a1 1 0 0 1-1 1h-11a1 1 0 0 1-1-1zM0 1h16v11.5a2.5 2.5 0 0 1-2.5 2.5h-11A2.5 2.5 0 0 1 0 12.5zm3.75 4.5a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5M7 4.75a.75.75 0 1 1-1.5 0 .75.75 0 0 1 1.5 0m1.75.75a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5" fill="#666"/></svg>

After

Width:  |  Height:  |  Size: 385 B

View file

@ -1,4 +0,0 @@
export default function DmPage() {
return null;
}

View file

@ -1,3 +0,0 @@
export default function FriendsPage() {
return null;
}

View file

@ -1,3 +0,0 @@
export default function GlobalNestsPage() {
return null;
}

View file

@ -1,3 +0,0 @@
export default function DiscoverPage() {
return null;
}

View file

@ -1,5 +0,0 @@
import AppContainer from "@/components/app-container";
export default function AppLayout() {
return <AppContainer />;
}

View file

@ -1,4 +0,0 @@
export default function HomePage() {
return null;
}

View file

@ -1,3 +0,0 @@
import { handler } from "@/lib/auth/auth-server";
export const { GET, POST } = handler;

View file

@ -1,89 +0,0 @@
"use client";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { authClient } from "@/lib/auth/client";
import { ErrorContext } from "better-auth/react";
import { Loader2 } from "lucide-react";
import { useRouter } from "next/navigation";
import { useState } from "react";
import { toast } from "sonner";
export function SignInForm(
{ captchaToken }: { captchaToken: string | null }
) {
const router = useRouter();
const [username, setUsername] = useState("");
const [password, setPassword] = useState("");
const [loading, setLoading] = useState(false);
const handleSignIn = async (e: React.FormEvent) => {
e.preventDefault();
await authClient.signIn.username(
{
username,
password,
fetchOptions: {
headers: {
"x-captcha-response": captchaToken ?? "",
},
},
},
{
onRequest: () => {
setLoading(true);
},
onSuccess: (d: any) => {
console.log(d)
setLoading(false);
toast.success("Signed in successfully");
router.push("/");
},
onError: (ctx: ErrorContext) => {
setLoading(false);
toast.error(ctx.error.message);
},
}
);
};
return (
<form onSubmit={handleSignIn} className="grid gap-4">
<div className="grid gap-2">
<Label htmlFor="username">Username</Label>
<Input
id="username"
type="text"
placeholder="john_doe"
required
value={username}
onChange={(e) => setUsername(e.target.value)}
className="bg-background/50 focus:bg-background transition-colors"
/>
</div>
<div className="grid gap-2">
<Label htmlFor="password">Password</Label>
<Input
id="password"
type="password"
placeholder="********"
autoComplete="current-password"
required
value={password}
onChange={(e) => setPassword(e.target.value)}
className="bg-background/50 focus:bg-background transition-colors"
/>
</div>
<Button
type="submit"
className="w-full font-semibold mt-2"
disabled={loading}
>
{loading ? <Loader2 className="mr-2 h-4 w-4 animate-spin" /> : "Sign In"}
</Button>
</form>
);
}

View file

@ -1,217 +0,0 @@
"use client";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { authClient } from "@/lib/auth/client";
import { ErrorContext } from "better-auth/react";
import { Check, Eye, EyeOff, Loader2, RefreshCw, X } from "lucide-react";
import { useRouter } from "next/navigation";
import { useState } from "react";
import { toast } from "sonner";
export function SignUpForm(
{ captchaToken, setShowSignIn }: { captchaToken: string | null, setShowSignIn: (show: boolean) => void }
) {
const router = useRouter();
const [username, setUsername] = useState("");
const [password, setPassword] = useState("");
const [confirmPassword, setConfirmPassword] = useState("");
const [isUsernameAvailable, setIsUsernameAvailable] = useState<boolean | null>(null);
const [loading, setLoading] = useState(false);
const [isValidatingUsername, setIsValidatingUsername] = useState(false);
const [showPassword, setShowPassword] = useState(false);
const handleSignUp = async (e: React.FormEvent) => {
e.preventDefault();
if (password !== confirmPassword) {
toast.error("Passwords do not match");
return;
}
if (password.length > 30) {
toast.error("Password must be less than 30 characters");
return;
}
await authClient.signUp.email(
{
email: `${username}.user@sipher.space`,
name: username,
username,
password,
fetchOptions: {
headers: {
"x-captcha-response": captchaToken ?? "",
},
},
},
{
onRequest: () => {
setLoading(true);
},
onSuccess: async () => {
setLoading(false);
toast.success("Account created successfully, now log in to continue!");
setShowSignIn(true);
router.push("/");
},
onError: (ctx: ErrorContext) => {
setLoading(false);
toast.error(ctx.error.message);
},
}
);
};
const generatePassword = () => {
const chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()_+";
let newPassword = "";
for (let i = 0; i < 16; i++) {
newPassword += chars.charAt(Math.floor(Math.random() * chars.length));
}
setPassword(newPassword);
setConfirmPassword(newPassword);
navigator.clipboard.writeText(newPassword);
toast.success("Password generated and copied to clipboard");
};
return (
<form onSubmit={handleSignUp} className="grid gap-4">
<div className="grid gap-2">
<Label htmlFor="username">Username</Label>
<div className="relative">
<Input
id="username"
type="text"
placeholder="john_doe"
required
value={username}
onChange={async (e) => {
const val = e.target.value;
setUsername(val);
if (val) {
setIsValidatingUsername(true);
// @ts-ignore
const isValid = await authClient.isUsernameAvailable({ username: val });
setIsUsernameAvailable(!!isValid);
setIsValidatingUsername(false);
} else {
setIsUsernameAvailable(null);
}
}}
className={`bg-background/50 focus:bg-background transition-colors pr-10 ${isUsernameAvailable === false ? "border-red-500 focus-visible:ring-red-500" :
isUsernameAvailable === true ? "border-green-500 focus-visible:ring-green-500" : ""
}`}
/>
<div className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground">
{isValidatingUsername ? (
<Loader2 className="size-4 animate-spin" />
) : isUsernameAvailable === true ? (
<Check className="size-4 text-green-500" />
) : isUsernameAvailable === false ? (
<X className="size-4 text-red-500" />
) : null}
</div>
</div>
{isUsernameAvailable === false && (
<p className="text-xs text-red-500">Username is already taken</p>
)}
</div>
<div className="grid gap-2">
<Label htmlFor="password">Password</Label>
<div className="relative">
<Input
id="password"
type={showPassword ? "text" : "password"}
placeholder="********"
autoComplete="new-password"
required
value={password}
onChange={(e) => setPassword(e.target.value)}
className={`bg-background/50 focus:bg-background transition-colors pr-24 ${password.length >= 8 && password.length <= 30
? "border-green-500 focus-visible:ring-green-500"
: password.length > 30
? "border-red-500 focus-visible:ring-red-500"
: ""
}`}
/>
<div className="absolute right-3 top-1/2 -translate-y-1/2 flex items-center gap-2">
{password.length > 30 ? (
<X className="size-4 text-red-500" />
) : password.length >= 8 && (
<Check className="size-4 text-green-500" />
)}
<Button
type="button"
variant="ghost"
size="icon"
className="size-6 text-muted-foreground hover:text-primary"
onClick={() => setShowPassword(!showPassword)}
title={showPassword ? "Hide password" : "Show password"}
>
{showPassword ? <EyeOff className="size-3" /> : <Eye className="size-3" />}
</Button>
<Button
type="button"
variant="ghost"
size="icon"
className="size-6 text-muted-foreground hover:text-primary"
onClick={generatePassword}
title="Generate secure password"
>
<RefreshCw className="size-3" />
</Button>
</div>
</div>
{password.length > 30 && (
<p className="text-xs text-red-500">Password must be less than 30 characters</p>
)}
</div>
<div className="grid gap-2">
<Label htmlFor="confirmPassword">Confirm Password</Label>
<div className="relative">
<Input
id="confirmPassword"
type={showPassword ? "text" : "password"}
placeholder="********"
autoComplete="new-password"
required
value={confirmPassword}
onChange={(e) => setConfirmPassword(e.target.value)}
className={`bg-background/50 focus:bg-background transition-colors pr-10 ${confirmPassword && password === confirmPassword && password.length <= 30
? "border-green-500 focus-visible:ring-green-500"
: (confirmPassword && password !== confirmPassword) || (confirmPassword && password.length > 30)
? "border-red-500 focus-visible:ring-red-500"
: ""
}`}
/>
<div className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground">
{confirmPassword && password === confirmPassword && password.length <= 30 ? (
<Check className="size-4 text-green-500" />
) : confirmPassword && (password !== confirmPassword || password.length > 30) ? (
<X className="size-4 text-red-500" />
) : null}
</div>
</div>
{confirmPassword && password !== confirmPassword && (
<p className="text-xs text-red-500">Passwords do not match</p>
)}
</div>
<Button
type="submit"
className="w-full font-semibold mt-2"
disabled={
loading ||
isUsernameAvailable === false ||
password !== confirmPassword ||
password.length < 8 ||
password.length > 30
}
>
{loading ? <Loader2 className="mr-2 h-4 w-4 animate-spin" /> : "Sign Up"}
</Button>
</form>
);
}

View file

@ -1,162 +0,0 @@
"use client";
import { ModeToggle } from "@/components/mode-toggle";
import { Button } from "@/components/ui/button";
import Captcha, { CaptchaRef } from "@/components/ui/captcha";
import {
Card,
CardContent,
CardDescription,
CardFooter,
CardHeader,
CardTitle,
} from "@/components/ui/card";
import { Spinner } from "@/components/ui/spinner";
import { authClient } from "@/lib/auth/client";
import { AnimatePresence, motion } from "framer-motion";
import { RefreshCw } from "lucide-react";
import Link from "next/link";
import { redirect } from "next/navigation";
import { useEffect, useRef, useState } from "react";
import { toast } from "sonner";
import { SignInForm } from "./components/sign-in-form";
import { SignUpForm } from "./components/sign-up-form";
export default function AuthPage() {
const { data, error, isPending } = authClient.useSession();
const [captchaToken, setCaptchaToken] = useState<string | null>(null);
const [method, setMethod] = useState<"signIn" | "signUp">("signIn");
const captchaRef = useRef<CaptchaRef>(null);
useEffect(() => {
if (error && error.status !== 404) {
console.error("[AuthPage] > Error:", error);
toast.error(error.message);
} else if (data) {
console.log(`[AuthPage] > User ${data.user.username} logged in, redirecting to home...`);
redirect("/");
}
}, [error, data])
if (isPending) {
return (
<div className="flex items-center justify-center h-screen w-full bg-background">
<Spinner className="size-10 animate-spin text-primary" />
</div>
);
}
const toggleMethod = () => {
setMethod(method === "signIn" ? "signUp" : "signIn");
};
return (
<div className="min-h-screen w-full flex items-center justify-center bg-background relative overflow-hidden p-4">
{/* Animated Background Blobs */}
<motion.div
animate={{
scale: [1, 1.2, 1],
rotate: [0, 90, 0],
}}
transition={{
duration: 20,
repeat: Infinity,
ease: "linear",
}}
className="absolute top-0 left-0 w-[500px] h-[500px] bg-primary/20 rounded-full mix-blend-multiply filter blur-[100px] opacity-50 pointer-events-none"
/>
<motion.div
animate={{
scale: [1, 1.1, 1],
rotate: [0, -60, 0],
}}
transition={{
duration: 15,
repeat: Infinity,
ease: "linear",
}}
className="absolute bottom-0 right-0 w-[500px] h-[500px] bg-accent/20 rounded-full mix-blend-multiply filter blur-[100px] opacity-50 pointer-events-none"
/>
<motion.div
initial={{ opacity: 0, scale: 0.95 }}
animate={{ opacity: 1, scale: 1 }}
transition={{ duration: 0.5, type: "spring" }}
className="w-full max-w-md z-10"
>
<Card className="backdrop-blur-md bg-card/90 border-muted/50 shadow-2xl relative">
<div className="absolute top-4 right-4">
<ModeToggle />
</div>
<CardHeader className="space-y-1 text-center">
<AnimatePresence mode="wait">
<motion.div
key={method}
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, y: -20 }}
transition={{ duration: 0.2 }}
>
<CardTitle className="text-2xl font-bold">
{method === "signIn" ? "Welcome Back" : "Create Account"}
</CardTitle>
<CardDescription>
{method === "signIn"
? "Enter your credentials to access your account"
: "Enter your details to get started with us"}
</CardDescription>
</motion.div>
</AnimatePresence>
</CardHeader>
<CardContent>
{method === "signIn" ? <SignInForm captchaToken={captchaToken} /> : <SignUpForm captchaToken={captchaToken} setShowSignIn={() => setMethod("signIn")} />}
</CardContent>
<CardFooter className="flex flex-col gap-4 pt-2">
<div className="text-center text-sm text-muted-foreground">
{method === "signIn" ? "Don't have an account? " : "Already have an account? "}
<button
type="button"
onClick={toggleMethod}
className="font-semibold text-primary hover:underline focus:outline-none"
>
{method === "signIn" ? "Sign up" : "Sign in"}
</button>
</div>
{/* Turnstile */}
<div className="flex flex-col justify-center items-center gap-2">
<Captcha ref={captchaRef} onSuccess={setCaptchaToken} />
{/* Reload the captcha */}
<Button
variant="outline"
size="sm"
onClick={() => {
setCaptchaToken(null);
captchaRef.current?.reset();
}}
>
<RefreshCw className="size-4" />
<div className="border-px border-l border-border h-full ml-2" />
<span className="text-xs">Reload Captcha</span>
</Button>
</div>
<div className="flex justify-center w-full border-t pt-4">
<p className="text-center text-xs text-muted-foreground">
built with{" "}
<Link
href="https://better-auth.com"
className="underline hover:text-primary transition-colors"
target="_blank"
>
better-auth
</Link>
</p>
</div>
</CardFooter>
</Card>
</motion.div>
</div>
);
}

View file

@ -1,125 +0,0 @@
import { db } from "@/lib/db";
// Track OLM initialization state
let olmInitPromise: Promise<any> | null = null;
// Load OLM via script tag to bypass bundler entirely
export async function loadOlm() {
if (typeof window === "undefined") throw new Error("OLM requires browser");
// If already initialized, return cached Olm
if ((window as any).__olmInitialized && (window as any).Olm) {
console.debug("[makeKeysOnSignUp]: OLM already initialized");
return (window as any).Olm;
}
// If initialization is in progress, wait for it
if (olmInitPromise) {
console.debug("[makeKeysOnSignUp]: OLM initialization in progress, waiting for it");
return olmInitPromise;
}
// Start initialization
olmInitPromise = new Promise((resolve, reject) => {
// Check if script already loaded but not initialized
if ((window as any).Olm) {
const Olm = (window as any).Olm;
Olm.init({ locateFile: () => "/olm.wasm" })
.then(() => {
(window as any).__olmInitialized = true;
resolve(Olm);
})
.catch(reject);
return;
}
const script = document.createElement("script");
script.src = "/olm.js";
script.onload = async () => {
try {
const Olm = (window as any).Olm;
await Olm.init({ locateFile: () => "/olm.wasm" });
(window as any).__olmInitialized = true;
resolve(Olm);
} catch (err) {
reject(err);
}
};
script.onerror = (err) => {
console.error("[makeKeysOnSignUp]: Failed to load OLM: ", err);
reject(new Error(`Failed to load OLM: ${err}`));
};
document.head.appendChild(script);
});
return olmInitPromise;
}
type SendKeysToServerFn = (args: {
userId: string;
identityKey: { curve25519: string; ed25519: string };
oneTimeKeys: { keyId: string; publicKey: string }[];
forceInsert: boolean;
}) => Promise<unknown>;
export default async function makeKeysOnSignUp(
odId: string,
localPassword: string,
sendKeysToServer: SendKeysToServerFn,
forceInsert: boolean = false,
) {
const Olm = await loadOlm() as typeof import("@matrix-org/olm");
const account = new Olm.Account();
account.create();
const identityKey: { curve25519: string; ed25519: string } = JSON.parse(account.identity_keys());
console.debug("[makeKeysOnSignUp] Identity key: ", identityKey);
account.generate_one_time_keys(50);
const oneTimeKeys = JSON.parse(account.one_time_keys());
console.debug("[makeKeysOnSignUp] One time keys: ", oneTimeKeys);
account.mark_keys_as_published();
try {
await sendKeysToServer({
userId: odId,
identityKey: {
curve25519: identityKey.curve25519,
ed25519: identityKey.ed25519,
},
oneTimeKeys: Object.entries(oneTimeKeys.curve25519).map(([key, value]) => ({
keyId: key,
publicKey: value as string,
})),
forceInsert,
});
} catch (error) {
console.error("Failed to make keys", error);
return false;
}
const pickledAccount = account.pickle(localPassword);
// Note: Password storage is handled by the OlmContext with encryption
// Do NOT store plain text password here
// Cache the account in window
if (!(window as any).olmAccountCache) {
(window as any).olmAccountCache = {};
}
(window as any).olmAccountCache[odId] = account;
// Set the OLM session into the window object
(window as any).olmSession = new Olm.Session();
// Store the olm account on DB
await db.olmAccounts.put({
odId,
pickledAccount,
createdAt: Date.now(),
updatedAt: Date.now(),
});
return true;
}

BIN
src/app/favicon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

View file

@ -1,165 +1,188 @@
@import "tailwindcss"; @import "tailwindcss";
@import "tw-animate-css";
@custom-variant dark (&:is(.dark *)); @custom-variant dark (&:is(.dark *));
:root {
--background: oklch(0.1467 0.0041 49.3141);
--foreground: oklch(0.8848 0.0037 56.3763);
--card: oklch(0.1588 0.0050 48.3894);
--card-foreground: oklch(0.8848 0.0037 56.3763);
--popover: oklch(0.1588 0.0050 48.3894);
--popover-foreground: oklch(0.8848 0.0037 56.3763);
--primary: oklch(0.7065 0.1860 48.1293);
--primary-foreground: oklch(0.9620 0.0012 56.4186);
--secondary: oklch(0.2698 0.0089 52.1501);
--secondary-foreground: oklch(0.8848 0.0037 56.3763);
--muted: oklch(0.2698 0.0089 52.1501);
--muted-foreground: oklch(0.7250 0.0092 56.2587);
--accent: oklch(0.2698 0.0089 52.1501);
--accent-foreground: oklch(0.8848 0.0037 56.3763);
--destructive: oklch(0.5714 0.2121 27.2502);
--destructive-foreground: oklch(0.9620 0.0012 56.4186);
--border: oklch(0.2371 0.0107 48.2489);
--input: oklch(0.2371 0.0107 48.2489);
--ring: oklch(0.7065 0.1860 48.1293);
--chart-1: oklch(0.7065 0.1860 48.1293);
--chart-2: oklch(0.6356 0.1398 156.1492);
--chart-3: oklch(0.6296 0.1443 251.2286);
--chart-4: oklch(0.6665 0.1797 327.3573);
--chart-5: oklch(0.9204 0.1621 109.2030);
--sidebar: oklch(0.1154 0.0031 50.5978);
--sidebar-foreground: oklch(0.9081 0.0030 56.3898);
--sidebar-primary: oklch(0.7065 0.1860 48.1293);
--sidebar-primary-foreground: oklch(0.9620 0.0012 56.4186);
--sidebar-accent: oklch(0.1931 0.0052 52.2293);
--sidebar-accent-foreground: oklch(0.9081 0.0030 56.3898);
--sidebar-border: oklch(0.2151 0.0091 48.2763);
--sidebar-ring: oklch(0.7065 0.1860 48.1293);
--font-sans: "Inter", sans-serif;
--font-serif: "Lora", serif;
--font-mono: "Fira Mono", monospace;
--radius: 0.5rem;
--shadow-x: 0px;
--shadow-y: 4px;
--shadow-blur: 10px;
--shadow-spread: -2px;
--shadow-opacity: 0.3;
--shadow-color: hsl(20, 14.3%, 2%);
--shadow-2xs: 0px 4px 10px -2px hsl(20 14.3000% 2% / 0.15);
--shadow-xs: 0px 4px 10px -2px hsl(20 14.3000% 2% / 0.15);
--shadow-sm: 0px 4px 10px -2px hsl(20 14.3000% 2% / 0.30), 0px 1px 2px -3px hsl(20 14.3000% 2% / 0.30);
--shadow: 0px 4px 10px -2px hsl(20 14.3000% 2% / 0.30), 0px 1px 2px -3px hsl(20 14.3000% 2% / 0.30);
--shadow-md: 0px 4px 10px -2px hsl(20 14.3000% 2% / 0.30), 0px 2px 4px -3px hsl(20 14.3000% 2% / 0.30);
--shadow-lg: 0px 4px 10px -2px hsl(20 14.3000% 2% / 0.30), 0px 4px 6px -3px hsl(20 14.3000% 2% / 0.30);
--shadow-xl: 0px 4px 10px -2px hsl(20 14.3000% 2% / 0.30), 0px 8px 10px -3px hsl(20 14.3000% 2% / 0.30);
--shadow-2xl: 0px 4px 10px -2px hsl(20 14.3000% 2% / 0.75);
--tracking-normal: 0em;
--spacing: 0.25rem;
}
.dark {
--background: oklch(0.1467 0.0041 49.3141);
--foreground: oklch(0.8848 0.0037 56.3763);
--card: oklch(0.1588 0.0050 48.3894);
--card-foreground: oklch(0.8848 0.0037 56.3763);
--popover: oklch(0.1588 0.0050 48.3894);
--popover-foreground: oklch(0.8848 0.0037 56.3763);
--primary: oklch(0.7065 0.1860 48.1293);
--primary-foreground: oklch(0.9620 0.0012 56.4186);
--secondary: oklch(0.2698 0.0089 52.1501);
--secondary-foreground: oklch(0.8848 0.0037 56.3763);
--muted: oklch(0.2698 0.0089 52.1501);
--muted-foreground: oklch(0.7250 0.0092 56.2587);
--accent: oklch(0.2698 0.0089 52.1501);
--accent-foreground: oklch(0.8848 0.0037 56.3763);
--destructive: oklch(0.5714 0.2121 27.2502);
--destructive-foreground: oklch(0.9620 0.0012 56.4186);
--border: oklch(0.2371 0.0107 48.2489);
--input: oklch(0.2371 0.0107 48.2489);
--ring: oklch(0.7065 0.1860 48.1293);
--chart-1: oklch(0.7065 0.1860 48.1293);
--chart-2: oklch(0.6356 0.1398 156.1492);
--chart-3: oklch(0.6296 0.1443 251.2286);
--chart-4: oklch(0.6665 0.1797 327.3573);
--chart-5: oklch(0.9204 0.1621 109.2030);
--sidebar: oklch(0.1154 0.0031 50.5978);
--sidebar-foreground: oklch(0.9081 0.0030 56.3898);
--sidebar-primary: oklch(0.7065 0.1860 48.1293);
--sidebar-primary-foreground: oklch(0.9620 0.0012 56.4186);
--sidebar-accent: oklch(0.1931 0.0052 52.2293);
--sidebar-accent-foreground: oklch(0.9081 0.0030 56.3898);
--sidebar-border: oklch(0.2151 0.0091 48.2763);
--sidebar-ring: oklch(0.7065 0.1860 48.1293);
--font-sans: "Inter", sans-serif;
--font-serif: "Lora", serif;
--font-mono: "Fira Mono", monospace;
--radius: 0.5rem;
--shadow-x: 0px;
--shadow-y: 4px;
--shadow-blur: 10px;
--shadow-spread: -2px;
--shadow-opacity: 0.3;
--shadow-color: hsl(20, 14.3%, 2%);
--shadow-2xs: 0px 4px 10px -2px hsl(20 14.3000% 2% / 0.15);
--shadow-xs: 0px 4px 10px -2px hsl(20 14.3000% 2% / 0.15);
--shadow-sm: 0px 4px 10px -2px hsl(20 14.3000% 2% / 0.30), 0px 1px 2px -3px hsl(20 14.3000% 2% / 0.30);
--shadow: 0px 4px 10px -2px hsl(20 14.3000% 2% / 0.30), 0px 1px 2px -3px hsl(20 14.3000% 2% / 0.30);
--shadow-md: 0px 4px 10px -2px hsl(20 14.3000% 2% / 0.30), 0px 2px 4px -3px hsl(20 14.3000% 2% / 0.30);
--shadow-lg: 0px 4px 10px -2px hsl(20 14.3000% 2% / 0.30), 0px 4px 6px -3px hsl(20 14.3000% 2% / 0.30);
--shadow-xl: 0px 4px 10px -2px hsl(20 14.3000% 2% / 0.30), 0px 8px 10px -3px hsl(20 14.3000% 2% / 0.30);
--shadow-2xl: 0px 4px 10px -2px hsl(20 14.3000% 2% / 0.75);
}
@theme inline { @theme inline {
--color-background: var(--background); --color-background: var(--background);
--color-foreground: var(--foreground); --color-foreground: var(--foreground);
--color-card: var(--card); --font-sans: "Inter", sans-serif;
--color-card-foreground: var(--card-foreground); --font-mono: "JetBrains Mono", monospace;
--color-popover: var(--popover); --font-serif: "Playfair Display", serif;
--color-popover-foreground: var(--popover-foreground); --radius: 0.5rem;
--color-primary: var(--primary); --tracking-tighter: calc(var(--tracking-normal) - 0.05em);
--color-primary-foreground: var(--primary-foreground); --tracking-tight: calc(var(--tracking-normal) - 0.025em);
--color-secondary: var(--secondary); --tracking-wide: calc(var(--tracking-normal) + 0.025em);
--color-secondary-foreground: var(--secondary-foreground); --tracking-wider: calc(var(--tracking-normal) + 0.05em);
--color-muted: var(--muted); --tracking-widest: calc(var(--tracking-normal) + 0.1em);
--color-muted-foreground: var(--muted-foreground); --tracking-normal: var(--tracking-normal);
--color-accent: var(--accent); --shadow-2xl: var(--shadow-2xl);
--color-accent-foreground: var(--accent-foreground); --shadow-xl: var(--shadow-xl);
--color-destructive: var(--destructive); --shadow-lg: var(--shadow-lg);
--color-destructive-foreground: var(--destructive-foreground); --shadow-md: var(--shadow-md);
--color-border: var(--border); --shadow: var(--shadow);
--color-input: var(--input); --shadow-sm: var(--shadow-sm);
--color-ring: var(--ring); --shadow-xs: var(--shadow-xs);
--color-chart-1: var(--chart-1); --shadow-2xs: var(--shadow-2xs);
--color-chart-2: var(--chart-2); --spacing: var(--spacing);
--color-chart-3: var(--chart-3); --letter-spacing: var(--letter-spacing);
--color-chart-4: var(--chart-4); --shadow-offset-y: var(--shadow-offset-y);
--color-chart-5: var(--chart-5); --shadow-offset-x: var(--shadow-offset-x);
--color-sidebar: var(--sidebar); --shadow-spread: var(--shadow-spread);
--color-sidebar-foreground: var(--sidebar-foreground); --shadow-blur: var(--shadow-blur);
--color-sidebar-primary: var(--sidebar-primary); --shadow-opacity: var(--shadow-opacity);
--color-sidebar-primary-foreground: var(--sidebar-primary-foreground); --color-shadow-color: var(--shadow-color);
--color-sidebar-accent: var(--sidebar-accent);
--color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
--color-sidebar-border: var(--sidebar-border);
--color-sidebar-ring: var(--sidebar-ring); --color-sidebar-ring: var(--sidebar-ring);
--color-sidebar-border: var(--sidebar-border);
--font-sans: var(--font-sans); --color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
--font-mono: var(--font-mono); --color-sidebar-accent: var(--sidebar-accent);
--font-serif: var(--font-serif); --color-sidebar-primary-foreground: var(--sidebar-primary-foreground);
--color-sidebar-primary: var(--sidebar-primary);
--color-sidebar-foreground: var(--sidebar-foreground);
--color-sidebar: var(--sidebar);
--color-chart-5: var(--chart-5);
--color-chart-4: var(--chart-4);
--color-chart-3: var(--chart-3);
--color-chart-2: var(--chart-2);
--color-chart-1: var(--chart-1);
--color-ring: var(--ring);
--color-input: var(--input);
--color-border: var(--border);
--color-destructive-foreground: var(--destructive-foreground);
--color-destructive: var(--destructive);
--color-accent-foreground: var(--accent-foreground);
--color-accent: var(--accent);
--color-muted-foreground: var(--muted-foreground);
--color-muted: var(--muted);
--color-secondary-foreground: var(--secondary-foreground);
--color-secondary: var(--secondary);
--color-primary-foreground: var(--primary-foreground);
--color-primary: var(--primary);
--color-popover-foreground: var(--popover-foreground);
--color-popover: var(--popover);
--color-card-foreground: var(--card-foreground);
--color-card: var(--card);
--radius-sm: calc(var(--radius) - 4px); --radius-sm: calc(var(--radius) - 4px);
--radius-md: calc(var(--radius) - 2px); --radius-md: calc(var(--radius) - 2px);
--radius-lg: var(--radius); --radius-lg: var(--radius);
--radius-xl: calc(var(--radius) + 4px); --radius-xl: calc(var(--radius) + 4px);
--radius-2xl: calc(var(--radius) + 8px);
--shadow-2xs: var(--shadow-2xs); --radius-3xl: calc(var(--radius) + 12px);
--shadow-xs: var(--shadow-xs); --radius-4xl: calc(var(--radius) + 16px);
--shadow-sm: var(--shadow-sm); }
--shadow: var(--shadow);
--shadow-md: var(--shadow-md); :root {
--shadow-lg: var(--shadow-lg); --background: oklch(0.9848 0 0);
--shadow-xl: var(--shadow-xl); --foreground: oklch(0.1445 0 0);
--shadow-2xl: var(--shadow-2xl); --card: oklch(1.0000 0 0);
--card-foreground: oklch(0.1445 0 0);
--popover: oklch(1.0000 0 0);
--popover-foreground: oklch(0.1445 0 0);
--primary: oklch(0.1457 0 0);
--primary-foreground: oklch(0.9848 0 0);
--secondary: oklch(0.6909 0.1457 163.5382);
--secondary-foreground: oklch(0.9848 0 0);
--muted: oklch(0.9703 0 0);
--muted-foreground: oklch(0.5555 0 0);
--accent: oklch(0.8608 0.1340 168.3558);
--accent-foreground: oklch(0.2722 0.0523 166.7898);
--destructive: oklch(0.6368 0.2078 25.3259);
--destructive-foreground: oklch(0.9848 0 0);
--border: oklch(0.9219 0 0);
--input: oklch(0.9219 0 0);
--ring: oklch(0.6909 0.1457 163.5382);
--chart-1: oklch(0.1457 0 0);
--chart-2: oklch(0.6909 0.1457 163.5382);
--chart-3: oklch(0.8608 0.1340 168.3558);
--chart-4: oklch(0.6709 0.1163 168.0411);
--chart-5: oklch(0.3211 0 0);
--radius: 0.5rem;
--sidebar: oklch(0.9848 0 0);
--sidebar-foreground: oklch(0.2697 0 0);
--sidebar-primary: oklch(0.1457 0 0);
--sidebar-primary-foreground: oklch(0.9848 0 0);
--sidebar-accent: oklch(0.8608 0.1340 168.3558);
--sidebar-accent-foreground: oklch(0.2722 0.0523 166.7898);
--sidebar-border: oklch(0.9312 0 0);
--sidebar-ring: oklch(0.6909 0.1457 163.5382);
--font-sans: "Inter", sans-serif;
--font-serif: "Playfair Display", serif;
--font-mono: "JetBrains Mono", monospace;
--shadow-color: hsl(0, 0%, 0%);
--shadow-opacity: 0.1;
--shadow-blur: 8px;
--shadow-spread: 0px;
--shadow-offset-x: 0px;
--shadow-offset-y: 2px;
--letter-spacing: -0.01em;
--spacing: 0.25rem;
--shadow-2xs: 0px 2px 8px 0px hsl(0 0% 0% / 0.05);
--shadow-xs: 0px 2px 8px 0px hsl(0 0% 0% / 0.05);
--shadow-sm: 0px 2px 8px 0px hsl(0 0% 0% / 0.10), 0px 1px 2px -1px hsl(0 0% 0% / 0.10);
--shadow: 0px 2px 8px 0px hsl(0 0% 0% / 0.10), 0px 1px 2px -1px hsl(0 0% 0% / 0.10);
--shadow-md: 0px 2px 8px 0px hsl(0 0% 0% / 0.10), 0px 2px 4px -1px hsl(0 0% 0% / 0.10);
--shadow-lg: 0px 2px 8px 0px hsl(0 0% 0% / 0.10), 0px 4px 6px -1px hsl(0 0% 0% / 0.10);
--shadow-xl: 0px 2px 8px 0px hsl(0 0% 0% / 0.10), 0px 8px 10px -1px hsl(0 0% 0% / 0.10);
--shadow-2xl: 0px 2px 8px 0px hsl(0 0% 0% / 0.25);
--tracking-normal: -0.01em;
}
.dark {
--background: oklch(0.1457 0 0);
--foreground: oklch(0.9848 0 0);
--card: oklch(0.1698 0 0);
--card-foreground: oklch(0.9848 0 0);
--popover: oklch(0.1698 0 0);
--popover-foreground: oklch(0.9848 0 0);
--primary: oklch(0.9848 0 0);
--primary-foreground: oklch(0.1457 0 0);
--secondary: oklch(0.6909 0.1457 163.5382);
--secondary-foreground: oklch(0.9848 0 0);
--muted: oklch(0.2376 0 0);
--muted-foreground: oklch(0.7153 0 0);
--accent: oklch(0.8608 0.1340 168.3558);
--accent-foreground: oklch(0.2722 0.0523 166.7898);
--destructive: oklch(0.3959 0.1331 25.7205);
--destructive-foreground: oklch(0.9848 0 0);
--border: oklch(0.2686 0 0);
--input: oklch(0.2686 0 0);
--ring: oklch(0.6909 0.1457 163.5382);
--chart-1: oklch(0.9848 0 0);
--chart-2: oklch(0.6909 0.1457 163.5382);
--chart-3: oklch(0.8608 0.1340 168.3558);
--chart-4: oklch(0.7557 0.1432 166.5106);
--chart-5: oklch(0.8452 0 0);
--radius: 0.5rem;
--sidebar: oklch(0.1698 0 0);
--sidebar-foreground: oklch(0.8845 0 0);
--sidebar-primary: oklch(0.6909 0.1457 163.5382);
--sidebar-primary-foreground: oklch(0.9848 0 0);
--sidebar-accent: oklch(0.2376 0 0);
--sidebar-accent-foreground: oklch(0.8608 0.1340 168.3558);
--sidebar-border: oklch(0.2697 0 0);
--sidebar-ring: oklch(0.6909 0.1457 163.5382);
--font-sans: "Inter", sans-serif;
--font-serif: "Playfair Display", serif;
--font-mono: "JetBrains Mono", monospace;
--shadow-color: hsl(0, 0%, 0%);
--shadow-opacity: 0.4;
--shadow-blur: 12px;
--shadow-spread: 0px;
--shadow-offset-x: 0px;
--shadow-offset-y: 4px;
--letter-spacing: -0.01em;
--spacing: 0.25rem;
--shadow-2xs: 0px 4px 12px 0px hsl(0 0% 0% / 0.20);
--shadow-xs: 0px 4px 12px 0px hsl(0 0% 0% / 0.20);
--shadow-sm: 0px 4px 12px 0px hsl(0 0% 0% / 0.40), 0px 1px 2px -1px hsl(0 0% 0% / 0.40);
--shadow: 0px 4px 12px 0px hsl(0 0% 0% / 0.40), 0px 1px 2px -1px hsl(0 0% 0% / 0.40);
--shadow-md: 0px 4px 12px 0px hsl(0 0% 0% / 0.40), 0px 2px 4px -1px hsl(0 0% 0% / 0.40);
--shadow-lg: 0px 4px 12px 0px hsl(0 0% 0% / 0.40), 0px 4px 6px -1px hsl(0 0% 0% / 0.40);
--shadow-xl: 0px 4px 12px 0px hsl(0 0% 0% / 0.40), 0px 8px 10px -1px hsl(0 0% 0% / 0.40);
--shadow-2xl: 0px 4px 12px 0px hsl(0 0% 0% / 1.00);
}
@layer base {
body {
letter-spacing: var(--tracking-normal);
}
} }

View file

@ -1,59 +1,47 @@
import { AutoRequestNotifications } from "@/components/notifications/NotificationSettings";
import { ThemeProvider } from "@/components/theme-provider";
import { Toaster } from "@/components/ui/sonner";
import { getToken } from "@/lib/auth/auth-server";
import { ConvexClientProvider } from "@/lib/providers/Convex";
import type { Metadata } from "next"; import type { Metadata } from "next";
import { Inter, JetBrains_Mono, Playfair_Display } from "next/font/google";
import "./globals.css"; import "./globals.css";
const fontSans = Inter({
subsets: ["latin"],
variable: "--font-sans",
});
const fontSerif = Playfair_Display({
subsets: ["latin"],
variable: "--font-serif",
});
const fontMono = JetBrains_Mono({
subsets: ["latin"],
variable: "--font-mono",
});
export const metadata: Metadata = { export const metadata: Metadata = {
title: "SiPher - Don't trust us. We don't trust you.", title: "Sipher",
description: "SiPher is a platform made for communication. Secure? Maybe. Reliable? I don't think so. We don't trust you. We don't trust us. We don't trust anyone.", description: "A federated social media platform for the modern age.",
icons: { icons: {
icon: [ icon: "/favicon.svg",
{ },
url: "/assets/logo/logo-white.svg", manifest: "/manifest.json",
href: "/assets/logo/logo-white.svg", themeColor: "#18181b",
media: "(prefers-color-scheme: dark)", viewport: {
type: "image/svg+xml", width: "device-width",
sizes: "32x32", initialScale: 1,
rel: "icon" maximumScale: 1,
userScalable: false,
}, },
{
url: "/assets/logo/logo-dark.svg",
href: "/assets/logo/logo-dark.svg",
media: "(prefers-color-scheme: light)",
type: "image/svg+xml",
sizes: "32x32",
rel: "icon"
}
]
}
}; };
export default async function RootLayout({ export default function RootLayout({
children, children,
}: Readonly<{ }: Readonly<{
children: React.ReactNode; children: React.ReactNode;
}>) { }>) {
const token = await getToken();
return ( return (
<html lang="en" suppressHydrationWarning> <html lang="en">
<body <body className={`${fontSans.variable} ${fontSerif.variable} ${fontMono.variable} antialiased`}>
className="antialiased min-h-screen bg-background"
>
<ConvexClientProvider initialToken={token ?? null}>
<ThemeProvider
attribute="class"
defaultTheme="system"
enableSystem
disableTransitionOnChange
>
{children} {children}
<AutoRequestNotifications />
</ThemeProvider>
<Toaster richColors />
</ConvexClientProvider>
</body> </body>
</html> </html>
); );

6
src/app/page.tsx Normal file
View file

@ -0,0 +1,6 @@
export default function Home() {
return (
<></>
);
}

View file

@ -1,190 +0,0 @@
"use client"
import AppSidebar from "@/components/home";
import OlmSetupDialog from "@/components/olm/olm-setup-dialog";
import { MainContentLayout } from "@/components/ui/layout";
import { Spinner } from "@/components/ui/spinner";
import UserFloatingCard from "@/components/ui/user/floating-card";
import { OlmProvider, useOlmContext } from "@/contexts/olm-context";
import { SocketProvider, useSocketContext } from "@/contexts/socket-context";
import { authClient } from "@/lib/auth/client";
import { getRandomPhrase, type PhrasePreference } from "@/lib/constants/phrases";
import { useMutation, useQuery } from "convex/react";
import { redirect, useParams, usePathname } from "next/navigation";
import { useCallback, useEffect, useMemo } from "react";
import { api } from "../../convex/_generated/api";
import OlmPasswordDialog from "./olm/olm-password-dialog";
type RouteParams = Record<string, string | string[] | undefined>;
type RouteMatcher = {
path?: string;
pattern?: RegExp;
type: SiPher.PageTypes;
extract?: (match: RegExpMatchArray, params: RouteParams) => Partial<SiPher.RouteInfo>;
};
const routes: RouteMatcher[] = [
{ path: '/channels/me/friends', type: 'friends' },
{ path: '/discover', type: 'discover' },
{ path: '/support', type: 'support' },
{ path: '/channels/nests/global', type: 'global-nests' },
{
pattern: /^\/channels\/me\/(.+)$/,
type: 'dm',
extract: (_, params) => ({
dmChannelId: params.id ? decodeURIComponent(params.id as string) : undefined
})
},
{
pattern: /^\/channels\/servers\/(.+)$/,
type: 'server',
extract: (_, params) => ({
serverId: params.serverId ? decodeURIComponent(params.serverId as string) : undefined,
serverChannelId: params.channelId ? decodeURIComponent(params.channelId as string) : undefined
})
},
];
function AppContainerContent() {
const pathname = usePathname();
const params = useParams();
const routeInfo: SiPher.RouteInfo = useMemo(() => {
for (const route of routes) {
if (route.path && pathname === route.path) {
return { type: route.type };
}
if (route.pattern) {
const match = pathname.match(route.pattern);
if (match) {
return {
type: route.type,
...route.extract?.(match, params)
};
}
}
}
return { type: 'friends' };
}, [pathname, params]);
const { data } = authClient.useSession();
// Use socket context instead of hook
const { socketStatus, socketInfo, disconnect, connect } = useSocketContext();
// Use OLM context
const { olmStatus, showOlmModal, setShowOlmModal, handleCreateAccount } = useOlmContext();
const updateUserMetadata = useMutation(api.auth.updateUserMetadata);
const userNests = useQuery(api.auth.getUserNests);
useEffect(() => {
if (!data) return;
const metadata = data.user.metadata
if (!metadata) {
console.debug("[AppContainer] > User metadata set", data.user.metadata)
updateUserMetadata({ metadata: { phrasePreference: "comforting" } });
}
}, [data, updateUserMetadata]);
const getPhrase = useCallback(() => {
const preference = data?.user?.metadata?.phrasePreference as PhrasePreference | undefined;
return getRandomPhrase(preference);
}, [data?.user?.metadata?.phrasePreference]);
if (["connecting", "error", "disconnected"].includes(socketStatus)) {
return (
<div className="flex items-center justify-center h-screen w-full bg-background">
<Spinner className="size-10 animate-spin" />
</div>
);
}
if (!data?.user) {
return null;
}
return (
<>
<UserFloatingCard user={data.user} />
<AppSidebar
socketStatus={socketStatus}
socketInfo={socketInfo}
disconnectSocket={disconnect}
connectSocket={connect}
routeInfo={routeInfo}
>
<MainContentLayout
socketStatus={socketStatus}
emptyChannelMessage={getPhrase()}
emptyFriendsMessage={getPhrase()}
userId={data.user.id}
routeInfo={routeInfo}
userNests={userNests}
/>
</AppSidebar>
<OlmPasswordDialog userId={data.user.id} />
<OlmSetupDialog
open={showOlmModal}
onOpenChange={setShowOlmModal}
olmStatus={olmStatus}
onCreateAccount={handleCreateAccount}
/>
</>
);
}
export default function AppContainer() {
const { data, error, isPending, refetch } = authClient.useSession();
const userStatus = useQuery(api.auth.getUserStatus);
const hasServerOlm = useQuery(
api.auth.retrieveServerOlmAccount,
data?.user?.id ? { userId: data.user.id } : "skip"
);
const sendKeysToServer = useMutation(api.auth.sendKeysToServer);
const consumeOTK = useMutation(api.auth.consumeOTK);
if (isPending) {
return (
<div className="flex items-center justify-center h-screen w-full bg-background">
<Spinner className="size-10 animate-spin" />
</div>
);
}
if (error || !data) {
return redirect(`/auth${error ? `?error=${error.cause}` : "?error=no-data"}`);
}
return (
<OlmProvider
userId={data?.user?.id}
hasServerOlm={hasServerOlm}
sendKeysToServer={sendKeysToServer}
consumeOTK={consumeOTK}
>
<SocketProvider
user={{
id: data?.user?.id,
status: userStatus ? {
status: userStatus.status,
isUserSet: userStatus.isUserSet,
} : {
status: "offline" as const,
isUserSet: false,
},
}}
refetchUser={refetch}
>
<AppContainerContent />
</SocketProvider>
</OlmProvider>
);
}

View file

@ -1,211 +0,0 @@
"use client";
import { cn } from "@/lib/utils";
import { BroadcastIcon as Broadcast } from "@phosphor-icons/react";
import { Activity, Clock, Globe, LogInIcon, LogOutIcon, Radio, Zap } from "lucide-react";
import { useEffect, useState } from "react";
import { Button } from "../ui/button";
import { Popover, PopoverContent, PopoverTrigger } from "../ui/popover";
function formatUptime(ms: number): string {
const seconds = Math.floor(ms / 1000);
const minutes = Math.floor(seconds / 60);
const hours = Math.floor(minutes / 60);
if (hours > 0) return `${hours}h ${minutes % 60}m`;
if (minutes > 0) return `${minutes}m ${seconds % 60}s`;
return `${seconds}s`;
}
/**
* Connection status indicator with popover details
*/
export default function ConnectionStatusIndicator({ socketStatus, socketInfo, disconnectSocket, connectSocket }: { socketStatus: SiPher.SocketStatus; socketInfo: SiPher.SocketInfo; disconnectSocket: () => void; connectSocket: () => void }) {
const [uptime, setUptime] = useState<string>("0s");
const [isOpen, setIsOpen] = useState(false);
// Update uptime every second when connected
useEffect(() => {
if (socketStatus !== "connected" || !socketInfo.connectedAt) return;
const interval = setInterval(() => {
setUptime(formatUptime(Date.now() - socketInfo.connectedAt!));
}, 1000);
// Initial update
setUptime(formatUptime(Date.now() - socketInfo.connectedAt));
return () => clearInterval(interval);
}, [socketStatus, socketInfo.connectedAt]);
const statusConfig = {
connected: {
label: "Connected",
color: "text-primary",
glow: "drop-shadow-[0_0_6px_var(--primary)]",
dotColor: "bg-primary"
},
connecting: {
label: "Connecting",
color: "text-chart-2",
glow: "",
dotColor: "bg-chart-2 animate-pulse"
},
disconnected: {
label: "Disconnected",
color: "text-muted-foreground",
glow: "",
dotColor: "bg-muted-foreground"
},
error: {
label: "Connection Error",
color: "text-destructive",
glow: "",
dotColor: "bg-destructive"
}
};
const config = statusConfig[socketStatus as keyof typeof statusConfig] || statusConfig.error;
const getPingQuality = (ping: number | null) => {
if (!ping) return { label: "Unknown", color: "text-muted-foreground" };
if (ping < 50) return { label: "Excellent", color: "text-primary" };
if (ping < 100) return { label: "Good", color: "text-chart-1" };
if (ping < 200) return { label: "Fair", color: "text-chart-2" };
return { label: "Poor", color: "text-destructive" };
};
const pingQuality = getPingQuality(socketInfo.ping);
return (
<Popover open={isOpen} onOpenChange={setIsOpen}>
<PopoverTrigger asChild>
<button
className={cn(
"relative flex items-center justify-center p-1.5 rounded-lg transition-all duration-200",
"hover:bg-accent/50 active:scale-95",
config.color, config.glow
)}
aria-label="Connection status"
>
<Broadcast
className="size-5"
weight={socketStatus === "connected" ? "fill" : "regular"}
/>
{/* Animated ring for connecting state */}
{socketStatus === "connecting" && (
<span className="absolute inset-0 rounded-lg border-2 border-chart-2/50 animate-ping" />
)}
</button>
</PopoverTrigger>
<PopoverContent
className={cn(
"w-72 p-0 overflow-hidden",
"bg-popover backdrop-blur-xl",
"border border-border shadow-xl"
)}
align="end"
sideOffset={8}
>
{/* Header */}
<div className="px-4 py-3 border-b border-border">
<div className="flex items-center gap-3">
<div className={cn("size-3 rounded-full", config.dotColor)} />
<div>
<p className={cn("font-semibold text-sm", config.color)}>{config.label}</p>
{socketInfo.error && (
<p className="text-xs text-destructive mt-0.5">{socketInfo.error}</p>
)}
</div>
</div>
</div>
{/* Stats Grid */}
<div className="p-3 space-y-1.5">
{/* Ping */}
<div className="flex items-center justify-between p-2.5 rounded-md bg-muted/50">
<div className="flex items-center gap-2.5 text-muted-foreground">
<Activity className="size-4" />
<span className="text-xs font-medium">Latency</span>
</div>
<div className="text-right">
<span className={cn("text-sm font-mono font-semibold", pingQuality.color)}>
{socketInfo.ping ? `${socketInfo.ping}ms` : "—"}
</span>
<p className={cn("text-[10px]", pingQuality.color)}>{pingQuality.label}</p>
</div>
</div>
{/* Transport */}
<div className="flex items-center justify-between p-2.5 rounded-md bg-muted/50">
<div className="flex items-center gap-2.5 text-muted-foreground">
<Zap className="size-4" />
<span className="text-xs font-medium">Transport</span>
</div>
<span className="text-sm font-medium capitalize text-foreground">
{socketInfo.transport || "—"}
</span>
</div>
{/* Uptime */}
{socketStatus === "connected" && (
<div className="flex items-center justify-between p-2.5 rounded-md bg-muted/50">
<div className="flex items-center gap-2.5 text-muted-foreground">
<Clock className="size-4" />
<span className="text-xs font-medium">Uptime</span>
</div>
<span className="text-sm font-mono font-medium text-primary">
{uptime}
</span>
</div>
)}
{/* Server */}
{socketInfo.serverUrl && (
<div className="flex items-center justify-between p-2.5 rounded-md bg-muted/50">
<div className="flex items-center gap-2.5 text-muted-foreground">
<Globe className="size-4" />
<span className="text-xs font-medium">Server</span>
</div>
<span className="text-xs font-mono text-foreground truncate max-w-[120px]">
{new URL(socketInfo.serverUrl).host}
</span>
</div>
)}
{/* Socket ID */}
{socketInfo.socketId && (
<div className="flex items-center justify-between p-2.5 rounded-md bg-muted/50">
<div className="flex items-center gap-2.5 text-muted-foreground">
<Radio className="size-4" />
<span className="text-xs font-medium">Session</span>
</div>
<span className="text-[10px] font-mono text-muted-foreground">
{socketInfo.socketId.slice(0, 12)}...
</span>
</div>
)}
</div>
{/* Footer hint */}
<div className="flex flex-row items-center justify-between gap-2 px-4 py-2 border-t border-border bg-muted/30">
<p className="text-[10px] text-muted-foreground text-center">
Real-time connection via Socket.IO
</p>
<Button variant="ghost" size="icon-sm" className="hover:cursor-pointer hover:bg-transparent!" onClick={() => {
socketStatus === "connected" ? disconnectSocket() : connectSocket();
}}>
{
socketStatus === "connected" ? (
<LogOutIcon className="size-4" />
) : (
<LogInIcon className="size-4" />
)
}
</Button>
</div>
</PopoverContent>
</Popover>
);
}

View file

@ -1,143 +0,0 @@
"use client";
import LogoIcon from "@/components/ui/logo-icon";
import {
Sidebar,
SidebarContent,
SidebarHeader,
SidebarInset,
SidebarMenu,
SidebarMenuItem,
SidebarProvider
} from "@/components/ui/sidebar";
import { CompassIcon, GlobeIcon, HouseIcon } from "@phosphor-icons/react";
import { Plus } from "lucide-react";
import { useRouter } from "next/navigation";
import { useState } from "react";
import { Avatar, AvatarFallback, AvatarImage } from "../ui/avatar";
import { Separator } from "../ui/separator";
import ConnectionStatusIndicator from "./csi";
import SidebarIcon from "./sicons";
const SidebarItems: SiPher.SidebarItem[] = [
{
id: "global-nests",
icon: <GlobeIcon className="size-5" weight="fill" />,
label: "Global Nest",
href: "/channels/nests/global"
},
{
id: "discover",
icon: <CompassIcon className="size-5" weight="fill" />,
label: "Discover",
href: "/discover"
}
];
/**
* The main component for the homepage. This component is used to wrap all the components of any page.
* It also is the controller for everything on the app, including going to other pages, showing conversations and other.
* @param children - The children to be rendered in the sidebar inset
*/
export default function AppSidebar({ children, socketStatus, socketInfo, currentChannel, disconnectSocket, connectSocket, routeInfo }: SiPher.AppSidebarProps) {
const [activeItem, setActiveItem] = useState<string>("home");
const router = useRouter();
return (
<SidebarProvider
style={{
"--sidebar-width": "5rem",
"--sidebar-width-mobile": "5rem",
} as React.CSSProperties}
defaultOpen={true}
>
<Sidebar variant="inset" collapsible="offcanvas" className="border-r-0">
<SidebarHeader className="py-3 px-0">
<SidebarIcon
isActive={activeItem === "home"}
isHome
label="Home"
onClick={() => setActiveItem("home")}
>
<LogoIcon className="size-7" />
</SidebarIcon>
</SidebarHeader>
<div className="px-5 py-0.5">
<Separator className="bg-sidebar-border" />
</div>
<SidebarContent className="pt-2 px-0 overflow-hidden">
<SidebarMenu className="gap-2">
{SidebarItems.map((item) => (
<SidebarMenuItem key={item.id} onClick={() => {
if (item.href) {
router.push(item.href);
}
}}>
<SidebarIcon
isActive={activeItem === item.id && routeInfo.type === item.id}
label={item.label}
onClick={() => setActiveItem(item.id)}
>
{item.icon}
</SidebarIcon>
</SidebarMenuItem>
))}
{/* Add Server/Channel button */}
<SidebarMenuItem>
<SidebarIcon label="Add a Server">
<Plus className="size-5 text-green-500 hover:text-white transition-colors" />
</SidebarIcon>
</SidebarMenuItem>
</SidebarMenu>
</SidebarContent>
</Sidebar>
<div className="flex flex-col flex-1 h-svh min-h-0 overflow-hidden">
<header className="flex items-center justify-between md:justify-center gap-2 px-4 py-0.5 md:border-none border-b border-border backdrop-blur sticky top-0 z-10">
<div className="flex items-center gap-2 justify-end w-full select-none">
<div className="flex items-center justify-center gap-2 text-sm font-semibold w-full text-center">
{
currentChannel ? (
<>
{
currentChannel.metadata?.icon ? (
<Avatar className="size-5">
<AvatarImage src={currentChannel.metadata!.icon!} alt={currentChannel.name} />
<AvatarFallback className="bg-primary/20 text-primary-foreground font-semibold">
{currentChannel.name?.charAt(0).toUpperCase()}
</AvatarFallback>
</Avatar>
) : (
<span className="size-5 rounded-full bg-primary/20 text-primary-foreground font-semibold">
{currentChannel.name?.charAt(0).toUpperCase()}
</span>
)
}
<span className="truncate">{currentChannel.name}</span>
</>
) : (
<>
<HouseIcon className="size-5" weight="fill" />
<span className="font-semibold">
Home
</span>
</>
)
}
</div>
{/* Socket connection status */}
<ConnectionStatusIndicator socketStatus={socketStatus} socketInfo={socketInfo} disconnectSocket={disconnectSocket} connectSocket={connectSocket} />
</div>
</header>
<SidebarInset className="mr-0 mb-0 border-none flex-1 min-h-0 overflow-hidden rounded-l-lg">
<div className="w-full h-full bg-background border-border border rounded-l-lg rounded-bl-none overflow-hidden min-h-0">
{children}
</div>
</SidebarInset>
</div>
</SidebarProvider>
)
}

View file

@ -1,305 +0,0 @@
"use client"
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Button } from "@/components/ui/button";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Spinner } from "@/components/ui/spinner";
import { useMutation, useQuery } from "convex/react";
import { CheckIcon, UserPlusIcon, XIcon } from "lucide-react";
import { useEffect, useState } from "react";
import { toast } from "sonner";
import { api } from "../../../../convex/_generated/api";
interface FriendRequestModalProps {
open: boolean;
onOpenChange: (open: boolean) => void;
}
export default function FriendRequestModal({
open,
onOpenChange,
}: FriendRequestModalProps) {
const getFriendRequests = useQuery(api.auth.getFriendRequests);
const sendFriendRequest = useMutation(api.auth.sendFriendRequest);
const answerFriendRequest = useMutation(api.auth.answerFriendRequest);
const [username, setUsername] = useState("");
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [activeTab, setActiveTab] = useState<"send" | "pending" | "sent">("send");
const [pendingRequests, setPendingRequests] = useState<any[]>([]);
const [sentRequests, setSentRequests] = useState<any[]>([]);
useEffect(() => {
if (getFriendRequests) {
if (!getFriendRequests || getFriendRequests.length === 0) {
console.debug("[FriendRequestModal] > Such a sad day, no friend requests found")
setPendingRequests([]);
setSentRequests([]);
return;
}
console.debug("[FriendRequestModal] > This guy is important, look at him with his big friend request list (¬.¬) :", getFriendRequests);
setPendingRequests(getFriendRequests.filter((request: any) => request.method === "receive"));
setSentRequests(getFriendRequests.filter((request: any) => request.method === "send"));
}
}, [getFriendRequests]);
const handleSendRequest = async () => {
if (!username.trim()) return;
setIsLoading(true);
setError(null);
try {
await sendFriendRequest({
username: username,
});
toast.success("Friend request sent successfully");
setUsername("");
} catch (err) {
setError(err instanceof Error ? err.message : "Failed to send friend request");
} finally {
setIsLoading(false);
}
};
const handleAccept = async (requestId: string) => {
setIsLoading(true);
try {
await answerFriendRequest({
requestId: requestId,
answer: "accept",
});
} catch (err) {
setError(err instanceof Error ? err.message : "Failed to accept request");
} finally {
setIsLoading(false);
}
};
const handleDecline = async (requestId: string) => {
setIsLoading(true);
try {
await answerFriendRequest({
requestId: requestId,
answer: "decline",
});
} catch (err) {
setError(err instanceof Error ? err.message : "Failed to decline request");
} finally {
setIsLoading(false);
}
};
const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
if (e.key === "Enter" && !isLoading) {
handleSendRequest();
}
};
const formatTimeAgo = (timestamp: number) => {
const seconds = Math.floor((Date.now() - timestamp) / 1000);
if (seconds < 60) return "just now";
const minutes = Math.floor(seconds / 60);
if (minutes < 60) return `${minutes}m ago`;
const hours = Math.floor(minutes / 60);
if (hours < 24) return `${hours}h ago`;
const days = Math.floor(hours / 24);
return `${days}d ago`;
};
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-md">
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
<UserPlusIcon className="size-5" />
Friend Requests
</DialogTitle>
<DialogDescription>
Send, accept, or manage your friend requests.
</DialogDescription>
</DialogHeader>
{/* Tabs */}
<div className="flex items-center gap-2 border-b border-border">
<Button
variant="ghost"
size="sm"
className={`rounded-b-none ${activeTab === "send" ? "border-b-2 border-primary" : ""}`}
onClick={() => setActiveTab("send")}
>
Send Request
</Button>
<Button
variant="ghost"
size="sm"
className={`rounded-b-none ${activeTab === "pending" ? "border-b-2 border-primary" : ""}`}
onClick={() => setActiveTab("pending")}
>
Pending ({pendingRequests.length})
</Button>
<Button
variant="ghost"
size="sm"
className={`rounded-b-none ${activeTab === "sent" ? "border-b-2 border-primary" : ""}`}
onClick={() => setActiveTab("sent")}
>
Sent ({sentRequests.length})
</Button>
</div>
{/* Content */}
<div className="min-h-[200px] max-h-[400px] overflow-y-auto">
{activeTab === "send" && (
<div className="flex flex-col gap-4 py-2">
<div className="flex flex-col gap-2">
<Input
placeholder="Enter username..."
value={username}
onChange={(e) => setUsername(e.target.value)}
onKeyDown={handleKeyDown}
disabled={isLoading}
/>
{error && (
<p className="text-sm text-destructive">{error}</p>
)}
</div>
<Button
onClick={handleSendRequest}
disabled={!username.trim() || isLoading}
className="w-full"
>
{isLoading ? (
<>
<Spinner className="size-4 animate-spin mr-2" />
Sending...
</>
) : (
<>
<UserPlusIcon className="size-4 mr-2" />
Send Friend Request
</>
)}
</Button>
</div>
)}
{activeTab === "pending" && (
<div className="flex flex-col gap-2 py-2">
{pendingRequests.length === 0 ? (
<div className="flex flex-col items-center justify-center py-8 text-center">
<p className="text-sm text-muted-foreground">
No pending friend requests
</p>
</div>
) : (
pendingRequests.map((request) => (
<div
key={request.id}
className="flex items-center justify-between gap-3 p-3 rounded-lg border border-border hover:bg-accent/50 transition-colors"
>
<div className="flex items-center gap-3 flex-1 min-w-0">
<Avatar className="size-10 shrink-0">
<AvatarImage src={request.avatar} alt={request.username} />
<AvatarFallback className="bg-primary/20 text-primary-foreground font-semibold">
{request.username.charAt(0).toUpperCase()}
</AvatarFallback>
</Avatar>
<div className="flex flex-col min-w-0 flex-1">
<span className="text-sm font-medium truncate">
{request.username}
</span>
<span className="text-xs text-muted-foreground">
{formatTimeAgo(request.createdAt)}
</span>
</div>
</div>
<div className="flex items-center gap-2 shrink-0">
<Button
size="icon-sm"
variant="ghost"
className="size-8 text-green-500 hover:text-green-600 hover:bg-green-500/10"
onClick={() => handleAccept(request.id)}
disabled={isLoading}
>
<CheckIcon className="size-4" />
</Button>
<Button
size="icon-sm"
variant="ghost"
className="size-8 text-destructive hover:text-destructive hover:bg-destructive/10"
onClick={() => handleDecline(request.id)}
disabled={isLoading}
>
<XIcon className="size-4" />
</Button>
</div>
</div>
))
)}
</div>
)}
{activeTab === "sent" && (
<div className="flex flex-col gap-2 py-2">
{sentRequests.length === 0 ? (
<div className="flex flex-col items-center justify-center py-8 text-center">
<p className="text-sm text-muted-foreground">
No sent friend requests
</p>
</div>
) : (
sentRequests.map((request) => (
<div
key={request.id}
className="flex items-center justify-between gap-3 p-3 rounded-lg border border-border"
>
<div className="flex items-center gap-3 flex-1 min-w-0">
<Avatar className="size-10 shrink-0">
<AvatarImage src={request.avatar} alt={request.username} />
<AvatarFallback className="bg-primary/20 text-primary-foreground font-semibold">
{request.username.charAt(0).toUpperCase()}
</AvatarFallback>
</Avatar>
<div className="flex flex-col min-w-0 flex-1">
<span className="text-sm font-medium truncate">
{request.username}
</span>
<span className="text-xs text-muted-foreground">
Sent {formatTimeAgo(request.createdAt)}
</span>
</div>
</div>
<span className="text-xs text-muted-foreground shrink-0">
Pending...
</span>
</div>
))
)}
</div>
)}
</div>
<DialogFooter>
<Button variant="outline" onClick={() => onOpenChange(false)}>
Close
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}

View file

@ -1,67 +0,0 @@
import { cn } from "@/lib/utils";
import { useState } from "react";
import { Button } from "../ui/button";
/**
* Discord-style sidebar icon with pill indicator
*/
export default function SidebarIcon({
children,
isActive,
isHome,
label,
onClick
}: {
children: React.ReactNode;
isActive?: boolean;
isHome?: boolean;
label?: string;
onClick?: () => void;
}) {
const [isHovered, setIsHovered] = useState(false);
return (
<div className="relative flex items-center justify-center w-full group">
{/* Left pill indicator */}
<div
className={cn(
"absolute left-0 w-1 bg-sidebar-foreground rounded-r-full transition-all duration-200",
isActive ? "h-10" : isHovered ? "h-5" : "h-0"
)}
/>
{/* Icon button */}
<Button
type="button"
variant="ghost"
size="icon-xl"
onClick={onClick}
onMouseEnter={() => setIsHovered(true)}
onMouseLeave={() => setIsHovered(false)}
className={cn(
"relative flex items-center justify-center size-12 transition-all duration-200 overflow-hidden",
"focus-visible:ring-0 focus-visible:border-none",
isHome
? "bg-primary text-primary-foreground hover:bg-primary/80"
: "bg-sidebar hover:bg-sidebar-accent text-sidebar-foreground hover:text-sidebar-foreground",
isActive
? "rounded-2xl bg-primary text-primary-foreground"
: "rounded-[24px] hover:rounded-2xl"
)}
>
{children}
</Button>
{/* Tooltip */}
{label && (
<div className={cn(
"absolute left-full ml-3 px-3 py-2 bg-popover text-popover-foreground text-sm font-medium rounded-md shadow-lg whitespace-nowrap z-50 pointer-events-none transition-all duration-150",
isHovered ? "opacity-100 translate-x-0" : "opacity-0 -translate-x-1"
)}>
{label}
<div className="absolute right-full top-1/2 -translate-y-1/2 border-4 border-transparent border-r-popover" />
</div>
)}
</div>
);
}

View file

@ -1,20 +0,0 @@
"use client"
import * as React from "react"
import { Moon, Sun } from "lucide-react"
import { useTheme } from "next-themes"
import { Button } from "@/components/ui/button"
export function ModeToggle() {
const { theme, setTheme } = useTheme()
return (
<Button variant="ghost" size="icon" onClick={() => setTheme(theme === "dark" ? "light" : "dark")}>
<Sun className="h-[1.2rem] w-[1.2rem] rotate-0 scale-100 transition-all dark:-rotate-90 dark:scale-0" />
<Moon className="absolute h-[1.2rem] w-[1.2rem] rotate-90 scale-0 transition-all dark:rotate-0 dark:scale-100" />
<span className="sr-only">Toggle theme</span>
</Button>
)
}

View file

@ -1,99 +0,0 @@
"use client";
import { requestNotificationPermission } from "@/lib/notifications";
import { Bell, BellOff } from "lucide-react";
import { useEffect, useState } from "react";
import { Button } from "../ui/button";
export function NotificationSettings({ userStatus }: { userStatus: "online" | "busy" | "offline" | "away" }) {
const [permission, setPermission] = useState<NotificationPermission>("default");
const [isLoading, setIsLoading] = useState(false);
useEffect(() => {
if ("Notification" in window) {
setPermission(Notification.permission);
}
}, []);
const handleRequestPermission = async () => {
setIsLoading(true);
try {
const newPermission = await requestNotificationPermission();
setPermission(newPermission);
if (newPermission === "granted") {
if (userStatus === "busy") return;
// Show a test notification
new Notification("Notifications enabled!", {
body: "You'll now receive message notifications",
icon: "/logo.png",
});
}
} catch (error) {
console.error("Failed to request notification permission:", error);
} finally {
setIsLoading(false);
}
};
if (!("Notification" in window)) {
return null; // Browser doesn't support notifications
}
if (permission === "granted") {
return (
<div className="flex items-center gap-2 text-sm text-muted-foreground">
<Bell className="h-4 w-4 text-green-500" />
<span>Notifications enabled</span>
</div>
);
}
if (permission === "denied") {
return (
<div className="flex items-center gap-2 text-sm text-muted-foreground">
<BellOff className="h-4 w-4 text-red-500" />
<span>Notifications blocked. Enable in browser settings.</span>
</div>
);
}
return (
<Button
variant="outline"
size="sm"
onClick={handleRequestPermission}
disabled={isLoading}
className="gap-2"
>
<Bell className="h-4 w-4" />
{isLoading ? "Requesting..." : "Enable Notifications"}
</Button>
);
}
/**
* Auto-request notification permission component
* Place in your app layout to automatically request permission on load
*/
export function AutoRequestNotifications() {
useEffect(() => {
if ("Notification" in window && Notification.permission === "default") {
// Auto-request permission after a short delay (to not interrupt page load)
const timer = setTimeout(async () => {
try {
const permission = await requestNotificationPermission();
if (permission === "granted") {
console.log("[Notifications] Permission granted automatically");
}
} catch (error) {
console.debug("[Notifications] Auto-request failed or was dismissed:", error);
}
}, 2000); // Wait 2 seconds after page load
return () => clearTimeout(timer);
}
}, []);
return null; // This component doesn't render anything
}

View file

@ -1,122 +0,0 @@
import { useOlmContext } from "@/contexts/olm-context";
import { AlertCircle, Info, KeyRound, ShieldCheck } from "lucide-react";
import { useEffect, useState } from "react";
import { Button } from "../ui/button";
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "../ui/dialog";
import { Input } from "../ui/input";
export default function OlmPasswordDialog({ userId }: { userId: string }) {
const [needsPassword, setNeedsPassword] = useState(false);
const [password, setPasswordInput] = useState("");
const { setPassword, passwordError, clearPasswordError } = useOlmContext();
useEffect(() => {
// The context handles loading & decrypting the password from sessionStorage.
// We only need to show the dialog if the context doesn't have a password.
// This will be handled by the passwordError effect below.
// For initial load, we check if there's encrypted data - if not, show dialog.
const hasStoredPassword = sessionStorage.getItem(`olm_password_${userId}`);
if (!hasStoredPassword) {
setNeedsPassword(true);
}
// If there IS stored data, the context will decrypt it and load it.
// If decryption fails or password is wrong, passwordError will be set.
}, [userId]);
// Show dialog when there's a password error (wrong password was entered)
useEffect(() => {
if (passwordError) {
setNeedsPassword(true);
setPasswordInput(""); // Clear the input for retry
}
}, [passwordError]);
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
if (password.trim()) {
setPassword(password);
setNeedsPassword(false);
}
};
return (
<Dialog open={needsPassword}>
<DialogContent className="sm:max-w-[440px]" showCloseButton={false} onPointerDownOutside={(e) => e.preventDefault()} onEscapeKeyDown={(e) => e.preventDefault()}>
<DialogHeader className="space-y-4">
<div className="flex flex-col items-center text-center space-y-3">
<div className="h-14 w-14 rounded-full bg-primary/10 flex items-center justify-center ring-8 ring-primary/5">
<KeyRound className="h-7 w-7 text-primary" />
</div>
<div className="space-y-2">
<DialogTitle className="text-2xl font-semibold tracking-tight">
Encryption Password Required
</DialogTitle>
<DialogDescription className="text-sm text-muted-foreground max-w-sm">
Enter your encryption password to access this conversation. This may be different from your login password.
</DialogDescription>
</div>
</div>
</DialogHeader>
<form onSubmit={handleSubmit} className="space-y-6 pt-2">
<div className="space-y-3">
<Input
type="password"
placeholder="Enter your encryption password"
className={`h-11 text-center ${passwordError ? "border-destructive focus-visible:ring-destructive" : ""}`}
autoFocus
value={password}
onChange={(e) => {
setPasswordInput(e.target.value);
if (passwordError) clearPasswordError();
}}
/>
{passwordError && (
<div className="flex items-center gap-2 rounded-md bg-destructive/10 px-3 py-2.5 text-destructive border border-destructive/20">
<AlertCircle className="h-4 w-4 shrink-0" />
<p className="text-xs leading-relaxed">
{passwordError}
</p>
</div>
)}
<div className="space-y-2">
<div className="flex items-center gap-2 rounded-md bg-chart-3/10 px-3 py-2.5 text-chart-3 border border-chart-3/20">
<Info className="h-4 w-4 shrink-0" />
<p className="text-xs leading-relaxed">
You'll be asked to re-enter this password each time you start a new browser session.
<br />
When continuing, the window will be reloaded, please do not close the window or refresh the page by yourself.
</p>
</div>
</div>
<div className="flex items-center gap-2 rounded-md bg-chart-2/10 px-3 py-2.5 text-chart-2 border border-chart-2/20">
<ShieldCheck className="h-4 w-4 shrink-0" />
<p className="text-xs leading-relaxed">
Your password is encrypted before being stored in your browser's session storage using a secure key that cannot be exported.
</p>
</div>
</div>
<div className="flex gap-3">
<Button
type="button"
variant="outline"
onClick={() => setNeedsPassword(false)}
className="flex-1"
>
Cancel
</Button>
<Button
type="submit"
className="flex-1"
disabled={!password.trim()}
>
Continue
</Button>
</div>
</form>
</DialogContent>
</Dialog>
)
}

View file

@ -1,114 +0,0 @@
"use client"
import { Button } from "@/components/ui/button";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Spinner } from "@/components/ui/spinner";
import { useState } from "react";
interface OlmSetupDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
olmStatus: SiPher.OlmStatus;
onCreateAccount: (password: string) => Promise<void>;
}
export default function OlmSetupDialog({
open,
onOpenChange,
olmStatus,
onCreateAccount,
}: OlmSetupDialogProps) {
const [localPassword, setLocalPassword] = useState("");
const handleSubmit = async () => {
if (!localPassword.trim()) return;
await onCreateAccount(localPassword);
setLocalPassword("");
};
const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
if (e.key === "Enter") {
handleSubmit();
}
};
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent showCloseButton={olmStatus !== "creating"}>
<DialogHeader>
<DialogTitle>
{olmStatus === "not_setup" && "Set Up Encryption"}
{olmStatus === "mismatched" && "Encryption Keys Out of Sync"}
{olmStatus === "creating" && "Creating Encryption Keys..."}
</DialogTitle>
<DialogDescription>
{olmStatus === "not_setup" && (
"Create a local password to encrypt your messages. This password is stored locally and never sent to our servers."
)}
{olmStatus === "mismatched" && (
"Your local encryption keys don't match the server. This can happen if you cleared your browser data or logged in from a new device."
)}
</DialogDescription>
</DialogHeader>
{olmStatus === "creating" ? (
<div className="flex items-center justify-center py-6">
<Spinner className="size-8 animate-spin" />
</div>
) : olmStatus === "not_setup" ? (
<>
<Input
type="password"
placeholder="Enter a local encryption password"
value={localPassword}
onChange={(e) => setLocalPassword(e.target.value)}
onKeyDown={handleKeyDown}
/>
<DialogFooter>
<Button onClick={handleSubmit} disabled={!localPassword.trim()}>
Create Encryption Keys
</Button>
</DialogFooter>
</>
) : olmStatus === "mismatched" ? (
<>
<div className="flex flex-col gap-2 text-sm text-muted-foreground">
<p>You have two options:</p>
<ul className="list-disc list-inside space-y-1">
<li><strong>Reset:</strong> Create new keys (you'll lose access to old messages)</li>
<li><strong>Restore:</strong> Import your backup if you have one</li>
</ul>
</div>
<Input
type="password"
placeholder="Enter password to create new keys"
value={localPassword}
onChange={(e) => setLocalPassword(e.target.value)}
onKeyDown={handleKeyDown}
/>
<DialogFooter className="gap-2">
<Button variant="outline" onClick={() => onOpenChange(false)}>
Import Keys from Backup
</Button>
<Button variant="outline" onClick={() => onOpenChange(false)}>
Cancel
</Button>
<Button onClick={handleSubmit} disabled={!localPassword.trim()}>
Reset & Create New Keys
</Button>
</DialogFooter>
</>
) : null}
</DialogContent>
</Dialog>
);
}

View file

@ -1,12 +0,0 @@
"use client"
import { ThemeProvider as NextThemesProvider } from "next-themes"
import * as React from "react"
export function ThemeProvider({
children,
...props
}: React.ComponentProps<typeof NextThemesProvider>) {
return <NextThemesProvider {...props}>{children}</NextThemesProvider>
}

View file

@ -1,53 +0,0 @@
"use client"
import * as React from "react"
import * as AvatarPrimitive from "@radix-ui/react-avatar"
import { cn } from "@/lib/utils"
function Avatar({
className,
...props
}: React.ComponentProps<typeof AvatarPrimitive.Root>) {
return (
<AvatarPrimitive.Root
data-slot="avatar"
className={cn(
"relative flex size-8 shrink-0 overflow-hidden rounded-full",
className
)}
{...props}
/>
)
}
function AvatarImage({
className,
...props
}: React.ComponentProps<typeof AvatarPrimitive.Image>) {
return (
<AvatarPrimitive.Image
data-slot="avatar-image"
className={cn("aspect-square size-full", className)}
{...props}
/>
)
}
function AvatarFallback({
className,
...props
}: React.ComponentProps<typeof AvatarPrimitive.Fallback>) {
return (
<AvatarPrimitive.Fallback
data-slot="avatar-fallback"
className={cn(
"bg-muted flex size-full items-center justify-center rounded-full",
className
)}
{...props}
/>
)
}
export { Avatar, AvatarImage, AvatarFallback }

View file

@ -1,83 +0,0 @@
import { Slot } from "@radix-ui/react-slot"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
import { Separator } from "@/components/ui/separator"
const buttonGroupVariants = cva(
"flex w-fit items-stretch *:focus-visible:z-10 *:focus-visible:relative [&>[data-slot=select-trigger]:not([class*='w-'])]:w-fit [&>input]:flex-1 has-[select[aria-hidden=true]:last-child]:[&>[data-slot=select-trigger]:last-of-type]:rounded-r-md has-[>[data-slot=button-group]]:gap-2",
{
variants: {
orientation: {
horizontal:
"[&>*:not(:first-child)]:rounded-l-none [&>*:not(:first-child)]:border-l-0 [&>*:not(:last-child)]:rounded-r-none",
vertical:
"flex-col [&>*:not(:first-child)]:rounded-t-none [&>*:not(:first-child)]:border-t-0 [&>*:not(:last-child)]:rounded-b-none",
},
},
defaultVariants: {
orientation: "horizontal",
},
}
)
function ButtonGroup({
className,
orientation,
...props
}: React.ComponentProps<"div"> & VariantProps<typeof buttonGroupVariants>) {
return (
<div
role="group"
data-slot="button-group"
data-orientation={orientation}
className={cn(buttonGroupVariants({ orientation }), className)}
{...props}
/>
)
}
function ButtonGroupText({
className,
asChild = false,
...props
}: React.ComponentProps<"div"> & {
asChild?: boolean
}) {
const Comp = asChild ? Slot : "div"
return (
<Comp
className={cn(
"bg-muted flex items-center gap-2 rounded-md border px-4 text-sm font-medium shadow-xs [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4",
className
)}
{...props}
/>
)
}
function ButtonGroupSeparator({
className,
orientation = "vertical",
...props
}: React.ComponentProps<typeof Separator>) {
return (
<Separator
data-slot="button-group-separator"
orientation={orientation}
className={cn(
"bg-input relative m-0! self-stretch data-[orientation=vertical]:h-auto",
className
)}
{...props}
/>
)
}
export {
ButtonGroup,
ButtonGroupSeparator,
ButtonGroupText,
buttonGroupVariants,
}

View file

@ -1,61 +0,0 @@
import { Slot } from "@radix-ui/react-slot"
import { cva, type VariantProps } from "class-variance-authority"
import * as React from "react"
import { cn } from "@/lib/utils"
const buttonVariants = cva(
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
{
variants: {
variant: {
default: "bg-primary text-primary-foreground hover:bg-primary/90",
destructive:
"bg-destructive text-white hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",
outline:
"border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50",
secondary:
"bg-secondary text-secondary-foreground hover:bg-secondary/80",
ghost:
"hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",
link: "text-primary underline-offset-4 hover:underline",
},
size: {
default: "h-9 px-4 py-2 has-[>svg]:px-3",
sm: "h-8 rounded-md gap-1.5 px-3 has-[>svg]:px-2.5",
lg: "h-10 rounded-md px-6 has-[>svg]:px-4",
icon: "size-9",
"icon-sm": "size-8",
"icon-lg": "size-10",
"icon-xl": "size-12",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
}
)
function Button({
className,
variant,
size,
asChild = false,
...props
}: React.ComponentProps<"button"> &
VariantProps<typeof buttonVariants> & {
asChild?: boolean
}) {
const Comp = asChild ? Slot : "button"
return (
<Comp
data-slot="button"
className={cn(buttonVariants({ variant, size, className }))}
{...props}
/>
)
}
export { Button, buttonVariants }

View file

@ -1,216 +0,0 @@
"use client"
import * as React from "react"
import {
ChevronDownIcon,
ChevronLeftIcon,
ChevronRightIcon,
} from "lucide-react"
import { DayButton, DayPicker, getDefaultClassNames } from "react-day-picker"
import { cn } from "@/lib/utils"
import { Button, buttonVariants } from "@/components/ui/button"
function Calendar({
className,
classNames,
showOutsideDays = true,
captionLayout = "label",
buttonVariant = "ghost",
formatters,
components,
...props
}: React.ComponentProps<typeof DayPicker> & {
buttonVariant?: React.ComponentProps<typeof Button>["variant"]
}) {
const defaultClassNames = getDefaultClassNames()
return (
<DayPicker
showOutsideDays={showOutsideDays}
className={cn(
"bg-background group/calendar p-3 [--cell-size:--spacing(8)] in-data-[slot=card-content]:bg-transparent in-data-[slot=popover-content]:bg-transparent",
String.raw`rtl:**:[.rdp-button\_next>svg]:rotate-180`,
String.raw`rtl:**:[.rdp-button\_previous>svg]:rotate-180`,
className
)}
captionLayout={captionLayout}
formatters={{
formatMonthDropdown: (date) =>
date.toLocaleString("default", { month: "short" }),
...formatters,
}}
classNames={{
root: cn("w-fit", defaultClassNames.root),
months: cn(
"flex gap-4 flex-col md:flex-row relative",
defaultClassNames.months
),
month: cn("flex flex-col w-full gap-4", defaultClassNames.month),
nav: cn(
"flex items-center gap-1 w-full absolute top-0 inset-x-0 justify-between",
defaultClassNames.nav
),
button_previous: cn(
buttonVariants({ variant: buttonVariant }),
"size-(--cell-size) aria-disabled:opacity-50 p-0 select-none",
defaultClassNames.button_previous
),
button_next: cn(
buttonVariants({ variant: buttonVariant }),
"size-(--cell-size) aria-disabled:opacity-50 p-0 select-none",
defaultClassNames.button_next
),
month_caption: cn(
"flex items-center justify-center h-(--cell-size) w-full px-(--cell-size)",
defaultClassNames.month_caption
),
dropdowns: cn(
"w-full flex items-center text-sm font-medium justify-center h-(--cell-size) gap-1.5",
defaultClassNames.dropdowns
),
dropdown_root: cn(
"relative has-focus:border-ring border border-input shadow-xs has-focus:ring-ring/50 has-focus:ring-[3px] rounded-md",
defaultClassNames.dropdown_root
),
dropdown: cn(
"absolute bg-popover inset-0 opacity-0",
defaultClassNames.dropdown
),
caption_label: cn(
"select-none font-medium",
captionLayout === "label"
? "text-sm"
: "rounded-md pl-2 pr-1 flex items-center gap-1 text-sm h-8 [&>svg]:text-muted-foreground [&>svg]:size-3.5",
defaultClassNames.caption_label
),
table: "w-full border-collapse",
weekdays: cn("flex", defaultClassNames.weekdays),
weekday: cn(
"text-muted-foreground rounded-md flex-1 font-normal text-[0.8rem] select-none",
defaultClassNames.weekday
),
week: cn("flex w-full mt-2", defaultClassNames.week),
week_number_header: cn(
"select-none w-(--cell-size)",
defaultClassNames.week_number_header
),
week_number: cn(
"text-[0.8rem] select-none text-muted-foreground",
defaultClassNames.week_number
),
day: cn(
"relative w-full h-full p-0 text-center [&:last-child[data-selected=true]_button]:rounded-r-md group/day aspect-square select-none",
props.showWeekNumber
? "[&:nth-child(2)[data-selected=true]_button]:rounded-l-md"
: "[&:first-child[data-selected=true]_button]:rounded-l-md",
defaultClassNames.day
),
range_start: cn(
"rounded-l-md bg-accent",
defaultClassNames.range_start
),
range_middle: cn("rounded-none", defaultClassNames.range_middle),
range_end: cn("rounded-r-md bg-accent", defaultClassNames.range_end),
today: cn(
"bg-accent text-accent-foreground rounded-md data-[selected=true]:rounded-none",
defaultClassNames.today
),
outside: cn(
"text-muted-foreground aria-selected:text-muted-foreground",
defaultClassNames.outside
),
disabled: cn(
"text-muted-foreground opacity-50",
defaultClassNames.disabled
),
hidden: cn("invisible", defaultClassNames.hidden),
...classNames,
}}
components={{
Root: ({ className, rootRef, ...props }) => {
return (
<div
data-slot="calendar"
ref={rootRef}
className={cn(className)}
{...props}
/>
)
},
Chevron: ({ className, orientation, ...props }) => {
if (orientation === "left") {
return (
<ChevronLeftIcon className={cn("size-4", className)} {...props} />
)
}
if (orientation === "right") {
return (
<ChevronRightIcon
className={cn("size-4", className)}
{...props}
/>
)
}
return (
<ChevronDownIcon className={cn("size-4", className)} {...props} />
)
},
DayButton: CalendarDayButton,
WeekNumber: ({ children, ...props }) => {
return (
<td {...props}>
<div className="flex size-(--cell-size) items-center justify-center text-center">
{children}
</div>
</td>
)
},
...components,
}}
{...props}
/>
)
}
function CalendarDayButton({
className,
day,
modifiers,
...props
}: React.ComponentProps<typeof DayButton>) {
const defaultClassNames = getDefaultClassNames()
const ref = React.useRef<HTMLButtonElement>(null)
React.useEffect(() => {
if (modifiers.focused) ref.current?.focus()
}, [modifiers.focused])
return (
<Button
ref={ref}
variant="ghost"
size="icon"
data-day={day.date.toLocaleDateString()}
data-selected-single={
modifiers.selected &&
!modifiers.range_start &&
!modifiers.range_end &&
!modifiers.range_middle
}
data-range-start={modifiers.range_start}
data-range-end={modifiers.range_end}
data-range-middle={modifiers.range_middle}
className={cn(
"data-[selected-single=true]:bg-primary data-[selected-single=true]:text-primary-foreground data-[range-middle=true]:bg-accent data-[range-middle=true]:text-accent-foreground data-[range-start=true]:bg-primary data-[range-start=true]:text-primary-foreground data-[range-end=true]:bg-primary data-[range-end=true]:text-primary-foreground group-data-[focused=true]/day:border-ring group-data-[focused=true]/day:ring-ring/50 dark:hover:text-accent-foreground flex aspect-square size-auto w-full min-w-(--cell-size) flex-col gap-1 leading-none font-normal group-data-[focused=true]/day:relative group-data-[focused=true]/day:z-10 group-data-[focused=true]/day:ring-[3px] data-[range-end=true]:rounded-md data-[range-end=true]:rounded-r-md data-[range-middle=true]:rounded-none data-[range-start=true]:rounded-md data-[range-start=true]:rounded-l-md [&>span]:text-xs [&>span]:opacity-70",
defaultClassNames.day,
className
)}
{...props}
/>
)
}
export { Calendar, CalendarDayButton }

View file

@ -1,24 +0,0 @@
import { Turnstile, TurnstileInstance } from '@marsidev/react-turnstile';
import { forwardRef, useImperativeHandle, useRef } from 'react';
export interface CaptchaRef {
reset: () => void;
}
const Captcha = forwardRef<CaptchaRef, { onSuccess: (token: string) => void }>(
({ onSuccess }, ref) => {
const turnstileRef = useRef<TurnstileInstance>(null);
useImperativeHandle(ref, () => ({
reset: () => {
turnstileRef.current?.reset();
},
}));
return <Turnstile ref={turnstileRef} siteKey='0x4AAAAAACDEvU2-PUzwj3L0' onSuccess={onSuccess} />
}
);
Captcha.displayName = 'Captcha';
export default Captcha;

View file

@ -1,92 +0,0 @@
import * as React from "react"
import { cn } from "@/lib/utils"
function Card({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card"
className={cn(
"bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-sm",
className
)}
{...props}
/>
)
}
function CardHeader({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-header"
className={cn(
"@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-2 px-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6",
className
)}
{...props}
/>
)
}
function CardTitle({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-title"
className={cn("leading-none font-semibold", className)}
{...props}
/>
)
}
function CardDescription({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-description"
className={cn("text-muted-foreground text-sm", className)}
{...props}
/>
)
}
function CardAction({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-action"
className={cn(
"col-start-2 row-span-2 row-start-1 self-start justify-self-end",
className
)}
{...props}
/>
)
}
function CardContent({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-content"
className={cn("px-6", className)}
{...props}
/>
)
}
function CardFooter({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-footer"
className={cn("flex items-center px-6 [.border-t]:pt-6", className)}
{...props}
/>
)
}
export {
Card,
CardHeader,
CardFooter,
CardTitle,
CardAction,
CardDescription,
CardContent,
}

View file

@ -1,32 +0,0 @@
"use client"
import * as React from "react"
import * as CheckboxPrimitive from "@radix-ui/react-checkbox"
import { CheckIcon } from "lucide-react"
import { cn } from "@/lib/utils"
function Checkbox({
className,
...props
}: React.ComponentProps<typeof CheckboxPrimitive.Root>) {
return (
<CheckboxPrimitive.Root
data-slot="checkbox"
className={cn(
"peer border-input dark:bg-input/30 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground dark:data-[state=checked]:bg-primary data-[state=checked]:border-primary focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive size-4 shrink-0 rounded-[4px] border shadow-xs transition-shadow outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",
className
)}
{...props}
>
<CheckboxPrimitive.Indicator
data-slot="checkbox-indicator"
className="grid place-content-center text-current transition-none"
>
<CheckIcon className="size-3.5" />
</CheckboxPrimitive.Indicator>
</CheckboxPrimitive.Root>
)
}
export { Checkbox }

View file

@ -1,184 +0,0 @@
"use client"
import * as React from "react"
import { Command as CommandPrimitive } from "cmdk"
import { SearchIcon } from "lucide-react"
import { cn } from "@/lib/utils"
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog"
function Command({
className,
...props
}: React.ComponentProps<typeof CommandPrimitive>) {
return (
<CommandPrimitive
data-slot="command"
className={cn(
"bg-popover text-popover-foreground flex h-full w-full flex-col overflow-hidden rounded-md",
className
)}
{...props}
/>
)
}
function CommandDialog({
title = "Command Palette",
description = "Search for a command to run...",
children,
className,
showCloseButton = true,
...props
}: React.ComponentProps<typeof Dialog> & {
title?: string
description?: string
className?: string
showCloseButton?: boolean
}) {
return (
<Dialog {...props}>
<DialogHeader className="sr-only">
<DialogTitle>{title}</DialogTitle>
<DialogDescription>{description}</DialogDescription>
</DialogHeader>
<DialogContent
className={cn("overflow-hidden p-0", className)}
showCloseButton={showCloseButton}
>
<Command className="**:[[cmdk-group-heading]]:text-muted-foreground **:data-[slot=command-input-wrapper]:h-12 **:[[cmdk-group-heading]]:px-2 **:[[cmdk-group-heading]]:font-medium **:[[cmdk-group]]:px-2 [&_[cmdk-group]:not([hidden])_~[cmdk-group]]:pt-0 [&_[cmdk-input-wrapper]_svg]:h-5 [&_[cmdk-input-wrapper]_svg]:w-5 **:[[cmdk-input]]:h-12 **:[[cmdk-item]]:px-2 **:[[cmdk-item]]:py-3 [&_[cmdk-item]_svg]:h-5 [&_[cmdk-item]_svg]:w-5">
{children}
</Command>
</DialogContent>
</Dialog>
)
}
function CommandInput({
className,
...props
}: React.ComponentProps<typeof CommandPrimitive.Input>) {
return (
<div
data-slot="command-input-wrapper"
className="flex h-9 items-center gap-2 border-b px-3"
>
<SearchIcon className="size-4 shrink-0 opacity-50" />
<CommandPrimitive.Input
data-slot="command-input"
className={cn(
"placeholder:text-muted-foreground flex h-10 w-full rounded-md bg-transparent py-3 text-sm outline-hidden disabled:cursor-not-allowed disabled:opacity-50",
className
)}
{...props}
/>
</div>
)
}
function CommandList({
className,
...props
}: React.ComponentProps<typeof CommandPrimitive.List>) {
return (
<CommandPrimitive.List
data-slot="command-list"
className={cn(
"max-h-[300px] scroll-py-1 overflow-x-hidden overflow-y-auto",
className
)}
{...props}
/>
)
}
function CommandEmpty({
...props
}: React.ComponentProps<typeof CommandPrimitive.Empty>) {
return (
<CommandPrimitive.Empty
data-slot="command-empty"
className="py-6 text-center text-sm"
{...props}
/>
)
}
function CommandGroup({
className,
...props
}: React.ComponentProps<typeof CommandPrimitive.Group>) {
return (
<CommandPrimitive.Group
data-slot="command-group"
className={cn(
"text-foreground **:[[cmdk-group-heading]]:text-muted-foreground overflow-hidden p-1 **:[[cmdk-group-heading]]:px-2 **:[[cmdk-group-heading]]:py-1.5 **:[[cmdk-group-heading]]:text-xs **:[[cmdk-group-heading]]:font-medium",
className
)}
{...props}
/>
)
}
function CommandSeparator({
className,
...props
}: React.ComponentProps<typeof CommandPrimitive.Separator>) {
return (
<CommandPrimitive.Separator
data-slot="command-separator"
className={cn("bg-border -mx-1 h-px", className)}
{...props}
/>
)
}
function CommandItem({
className,
...props
}: React.ComponentProps<typeof CommandPrimitive.Item>) {
return (
<CommandPrimitive.Item
data-slot="command-item"
className={cn(
"data-[selected=true]:bg-accent data-[selected=true]:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className
)}
{...props}
/>
)
}
function CommandShortcut({
className,
...props
}: React.ComponentProps<"span">) {
return (
<span
data-slot="command-shortcut"
className={cn(
"text-muted-foreground ml-auto text-xs tracking-widest",
className
)}
{...props}
/>
)
}
export {
Command,
CommandDialog,
CommandInput,
CommandList,
CommandEmpty,
CommandGroup,
CommandItem,
CommandShortcut,
CommandSeparator,
}

View file

@ -1,252 +0,0 @@
"use client"
import * as React from "react"
import * as ContextMenuPrimitive from "@radix-ui/react-context-menu"
import { CheckIcon, ChevronRightIcon, CircleIcon } from "lucide-react"
import { cn } from "@/lib/utils"
function ContextMenu({
...props
}: React.ComponentProps<typeof ContextMenuPrimitive.Root>) {
return <ContextMenuPrimitive.Root data-slot="context-menu" {...props} />
}
function ContextMenuTrigger({
...props
}: React.ComponentProps<typeof ContextMenuPrimitive.Trigger>) {
return (
<ContextMenuPrimitive.Trigger data-slot="context-menu-trigger" {...props} />
)
}
function ContextMenuGroup({
...props
}: React.ComponentProps<typeof ContextMenuPrimitive.Group>) {
return (
<ContextMenuPrimitive.Group data-slot="context-menu-group" {...props} />
)
}
function ContextMenuPortal({
...props
}: React.ComponentProps<typeof ContextMenuPrimitive.Portal>) {
return (
<ContextMenuPrimitive.Portal data-slot="context-menu-portal" {...props} />
)
}
function ContextMenuSub({
...props
}: React.ComponentProps<typeof ContextMenuPrimitive.Sub>) {
return <ContextMenuPrimitive.Sub data-slot="context-menu-sub" {...props} />
}
function ContextMenuRadioGroup({
...props
}: React.ComponentProps<typeof ContextMenuPrimitive.RadioGroup>) {
return (
<ContextMenuPrimitive.RadioGroup
data-slot="context-menu-radio-group"
{...props}
/>
)
}
function ContextMenuSubTrigger({
className,
inset,
children,
...props
}: React.ComponentProps<typeof ContextMenuPrimitive.SubTrigger> & {
inset?: boolean
}) {
return (
<ContextMenuPrimitive.SubTrigger
data-slot="context-menu-sub-trigger"
data-inset={inset}
className={cn(
"focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground flex cursor-default items-center rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-inset:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className
)}
{...props}
>
{children}
<ChevronRightIcon className="ml-auto" />
</ContextMenuPrimitive.SubTrigger>
)
}
function ContextMenuSubContent({
className,
...props
}: React.ComponentProps<typeof ContextMenuPrimitive.SubContent>) {
return (
<ContextMenuPrimitive.SubContent
data-slot="context-menu-sub-content"
className={cn(
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 min-w-32 origin-(--radix-context-menu-content-transform-origin) overflow-hidden rounded-md border p-1 shadow-lg",
className
)}
{...props}
/>
)
}
function ContextMenuContent({
className,
...props
}: React.ComponentProps<typeof ContextMenuPrimitive.Content>) {
return (
<ContextMenuPrimitive.Portal>
<ContextMenuPrimitive.Content
data-slot="context-menu-content"
className={cn(
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 max-h-(--radix-context-menu-content-available-height) min-w-32 origin-(--radix-context-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border p-1 shadow-md",
className
)}
{...props}
/>
</ContextMenuPrimitive.Portal>
)
}
function ContextMenuItem({
className,
inset,
variant = "default",
...props
}: React.ComponentProps<typeof ContextMenuPrimitive.Item> & {
inset?: boolean
variant?: "default" | "destructive"
}) {
return (
<ContextMenuPrimitive.Item
data-slot="context-menu-item"
data-inset={inset}
data-variant={variant}
className={cn(
"focus:bg-accent focus:text-accent-foreground data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 dark:data-[variant=destructive]:focus:bg-destructive/20 data-[variant=destructive]:focus:text-destructive data-[variant=destructive]:*:[svg]:text-destructive! [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-disabled:pointer-events-none data-disabled:opacity-50 data-inset:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className
)}
{...props}
/>
)
}
function ContextMenuCheckboxItem({
className,
children,
checked,
...props
}: React.ComponentProps<typeof ContextMenuPrimitive.CheckboxItem>) {
return (
<ContextMenuPrimitive.CheckboxItem
data-slot="context-menu-checkbox-item"
className={cn(
"focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className
)}
checked={checked}
{...props}
>
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
<ContextMenuPrimitive.ItemIndicator>
<CheckIcon className="size-4" />
</ContextMenuPrimitive.ItemIndicator>
</span>
{children}
</ContextMenuPrimitive.CheckboxItem>
)
}
function ContextMenuRadioItem({
className,
children,
...props
}: React.ComponentProps<typeof ContextMenuPrimitive.RadioItem>) {
return (
<ContextMenuPrimitive.RadioItem
data-slot="context-menu-radio-item"
className={cn(
"focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className
)}
{...props}
>
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
<ContextMenuPrimitive.ItemIndicator>
<CircleIcon className="size-2 fill-current" />
</ContextMenuPrimitive.ItemIndicator>
</span>
{children}
</ContextMenuPrimitive.RadioItem>
)
}
function ContextMenuLabel({
className,
inset,
...props
}: React.ComponentProps<typeof ContextMenuPrimitive.Label> & {
inset?: boolean
}) {
return (
<ContextMenuPrimitive.Label
data-slot="context-menu-label"
data-inset={inset}
className={cn(
"text-foreground px-2 py-1.5 text-sm font-medium data-inset:pl-8",
className
)}
{...props}
/>
)
}
function ContextMenuSeparator({
className,
...props
}: React.ComponentProps<typeof ContextMenuPrimitive.Separator>) {
return (
<ContextMenuPrimitive.Separator
data-slot="context-menu-separator"
className={cn("bg-border -mx-1 my-1 h-px", className)}
{...props}
/>
)
}
function ContextMenuShortcut({
className,
...props
}: React.ComponentProps<"span">) {
return (
<span
data-slot="context-menu-shortcut"
className={cn(
"text-muted-foreground ml-auto text-xs tracking-widest",
className
)}
{...props}
/>
)
}
export {
ContextMenu,
ContextMenuTrigger,
ContextMenuContent,
ContextMenuItem,
ContextMenuCheckboxItem,
ContextMenuRadioItem,
ContextMenuLabel,
ContextMenuSeparator,
ContextMenuShortcut,
ContextMenuGroup,
ContextMenuPortal,
ContextMenuSub,
ContextMenuSubContent,
ContextMenuSubTrigger,
ContextMenuRadioGroup,
}

View file

@ -1,143 +0,0 @@
"use client"
import * as React from "react"
import * as DialogPrimitive from "@radix-ui/react-dialog"
import { XIcon } from "lucide-react"
import { cn } from "@/lib/utils"
function Dialog({
...props
}: React.ComponentProps<typeof DialogPrimitive.Root>) {
return <DialogPrimitive.Root data-slot="dialog" {...props} />
}
function DialogTrigger({
...props
}: React.ComponentProps<typeof DialogPrimitive.Trigger>) {
return <DialogPrimitive.Trigger data-slot="dialog-trigger" {...props} />
}
function DialogPortal({
...props
}: React.ComponentProps<typeof DialogPrimitive.Portal>) {
return <DialogPrimitive.Portal data-slot="dialog-portal" {...props} />
}
function DialogClose({
...props
}: React.ComponentProps<typeof DialogPrimitive.Close>) {
return <DialogPrimitive.Close data-slot="dialog-close" {...props} />
}
function DialogOverlay({
className,
...props
}: React.ComponentProps<typeof DialogPrimitive.Overlay>) {
return (
<DialogPrimitive.Overlay
data-slot="dialog-overlay"
className={cn(
"data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",
className
)}
{...props}
/>
)
}
function DialogContent({
className,
children,
showCloseButton = true,
...props
}: React.ComponentProps<typeof DialogPrimitive.Content> & {
showCloseButton?: boolean
}) {
return (
<DialogPortal data-slot="dialog-portal">
<DialogOverlay />
<DialogPrimitive.Content
data-slot="dialog-content"
className={cn(
"bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 sm:max-w-lg",
className
)}
{...props}
>
{children}
{showCloseButton && (
<DialogPrimitive.Close
data-slot="dialog-close"
className="ring-offset-background focus:ring-ring data-[state=open]:bg-accent data-[state=open]:text-muted-foreground absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4"
>
<XIcon />
<span className="sr-only">Close</span>
</DialogPrimitive.Close>
)}
</DialogPrimitive.Content>
</DialogPortal>
)
}
function DialogHeader({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="dialog-header"
className={cn("flex flex-col gap-2 text-center sm:text-left", className)}
{...props}
/>
)
}
function DialogFooter({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="dialog-footer"
className={cn(
"flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",
className
)}
{...props}
/>
)
}
function DialogTitle({
className,
...props
}: React.ComponentProps<typeof DialogPrimitive.Title>) {
return (
<DialogPrimitive.Title
data-slot="dialog-title"
className={cn("text-lg leading-none font-semibold", className)}
{...props}
/>
)
}
function DialogDescription({
className,
...props
}: React.ComponentProps<typeof DialogPrimitive.Description>) {
return (
<DialogPrimitive.Description
data-slot="dialog-description"
className={cn("text-muted-foreground text-sm", className)}
{...props}
/>
)
}
export {
Dialog,
DialogClose,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogOverlay,
DialogPortal,
DialogTitle,
DialogTrigger,
}

View file

@ -1,407 +0,0 @@
import { useOlmContext } from "@/contexts/olm-context";
import { useSocketContext } from "@/contexts/socket-context";
import { clearUnread, db, sendMessage } from "@/lib/db";
import { setActiveChannel } from "@/lib/notifications";
import { useLiveQuery } from "dexie-react-hooks";
import { KeyRound, SendIcon } from "lucide-react";
import moment from "moment";
import React, { useEffect, useMemo, useState } from "react";
import { toast } from "sonner";
import { Avatar, AvatarFallback, AvatarImage } from "../avatar";
import { Button } from "../button";
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "../dialog";
import { Input } from "../input";
interface DMChannelContentProps {
userId: string
channelId: string
participantDetails: SiPher.ParticipantDetail[]
}
export default function DMChannelContent(
{
userId,
channelId,
participantDetails,
}: DMChannelContentProps
) {
const otherUser = useMemo(() => {
return participantDetails.find((p) => p.id !== userId);
}, [participantDetails, userId]);
const [olmSession, setOlmSession] = useState<Olm.Session | null>(null);
const [sessionError, setSessionError] = useState<string | null>(null);
const [messageInput, setMessageInput] = useState("");
const [messageLimit, setMessageLimit] = useState(50);
const [isLoadingMore, setIsLoadingMore] = useState(false);
const { sendMessage: sendMessageToServer } = useSocketContext();
const { olmAccount, password, isReady, getSession } = useOlmContext();
const messagesEndRef = React.useRef<HTMLDivElement>(null);
const scrollContainerRef = React.useRef<HTMLDivElement>(null);
const prevScrollHeightRef = React.useRef<number>(0);
// Get total message count
const totalMessageCount = useLiveQuery(
() => db.messages.where("channelId").equals(channelId).count(),
[channelId]
) ?? 0;
// Get messages from the local database with pagination
const allMessages = useLiveQuery(
() => db.messages.where("channelId").equals(channelId).sortBy("timestamp"),
[channelId]
) ?? [];
// Take only the most recent messages based on limit
const messages = useMemo(() => {
return allMessages.slice(-messageLimit);
}, [allMessages, messageLimit]);
const hasMoreMessages = messages.length < totalMessageCount;
// Reset message limit when channel changes
useEffect(() => {
setMessageLimit(50);
}, [channelId]);
// Handle scroll to load more messages
const handleScroll = React.useCallback(async (e: React.UIEvent<HTMLDivElement>) => {
const target = e.currentTarget;
const scrollTop = target.scrollTop;
// If scrolled near the top (within 100px) and there are more messages
if (scrollTop < 100 && hasMoreMessages && !isLoadingMore) {
setIsLoadingMore(true);
// Save current scroll height
prevScrollHeightRef.current = target.scrollHeight;
// Load 50 more messages
await new Promise(resolve => setTimeout(resolve, 100)); // Small delay to avoid rapid firing
setMessageLimit(prev => prev + 50);
setIsLoadingMore(false);
}
}, [hasMoreMessages, isLoadingMore]);
// Preserve scroll position after loading more messages
useEffect(() => {
if (prevScrollHeightRef.current > 0 && scrollContainerRef.current) {
const newScrollHeight = scrollContainerRef.current.scrollHeight;
const scrollDiff = newScrollHeight - prevScrollHeightRef.current;
scrollContainerRef.current.scrollTop += scrollDiff;
prevScrollHeightRef.current = 0;
}
}, [messages.length]);
// Scroll to bottom on initial load / channel change (instant)
useEffect(() => {
messagesEndRef.current?.scrollIntoView({ behavior: "auto" });
}, [channelId]);
// Auto-scroll to bottom when new messages arrive (smooth)
useEffect(() => {
if (messages.length > 0 && scrollContainerRef.current) {
const container = scrollContainerRef.current;
const isNearBottom = container.scrollHeight - container.scrollTop - container.clientHeight < 200;
// Only auto-scroll if user is near the bottom
if (isNearBottom) {
messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
}
}
}, [allMessages.length]);
// Set active channel and clear unread count when viewing this channel
useEffect(() => {
// Mark this channel as active (prevents notifications)
setActiveChannel(channelId);
// Clear any existing unread count
clearUnread(channelId);
console.debug("[DMChannelContent] Set active channel and cleared unread:", channelId);
// Cleanup: unset active channel when leaving
return () => {
setActiveChannel(null);
console.debug("[DMChannelContent] Cleared active channel");
};
}, [channelId]);
// Guard: Check if otherUser exists
if (!otherUser) {
return (
<div className="flex items-center justify-center h-full">
<div className="text-center space-y-2">
<p className="text-muted-foreground">Loading participant information...</p>
</div>
</div>
);
}
// Get or create session when OLM is ready and we have the other user's account
useEffect(() => {
const loadSession = async () => {
console.log("[DMChannelContent] loadSession effect triggered", {
isReady,
hasOlmAccount: !!olmAccount,
hasOtherUser: !!otherUser,
hasOtherUserOlmAccount: !!otherUser?.olmAccount,
otherUserId: otherUser?.id
});
if (!isReady || !olmAccount || !otherUser || !otherUser.olmAccount) {
console.log("[DMChannelContent] Not ready to load session, skipping");
return;
}
setSessionError(null);
console.log("[DMChannelContent] Calling getSession for", otherUser.id);
try {
const session = await getSession(otherUser.id, otherUser.olmAccount);
console.log("[DMChannelContent] getSession returned:", !!session);
if (session) {
setOlmSession(session);
console.log("[DMChannelContent] Session set successfully");
} else {
console.error("[DMChannelContent] getSession returned null");
setSessionError("Failed to create encryption session");
}
} catch (err) {
console.error("[DMChannelContent] Failed to get session:", err);
setSessionError(err instanceof Error ? err.message : "Unknown error");
}
};
loadSession();
}, [isReady, olmAccount, otherUser, password, getSession])
// Check if OLM is ready
if (!isReady || !olmAccount) {
return <div>Loading encryption keys...</div>
}
// Get the other user's id key and OT keys from the server to be prepared for messaging
if (!otherUser.olmAccount) {
return (
<Dialog open={true} onOpenChange={() => { }}>
<DialogContent className="sm:max-w-md">
<DialogHeader>
<div className="mx-auto mb-4 flex h-16 w-16 items-center justify-center rounded-full bg-accent/20">
<KeyRound className="h-8 w-8 text-accent-foreground" />
</div>
<DialogTitle className="text-2xl text-center">Encryption Setup Required</DialogTitle>
</DialogHeader>
<DialogDescription className="space-y-4 pt-2">
<div className="rounded-lg bg-card border border-border p-4">
<p className="text-sm text-card-foreground/90 leading-relaxed">
<span className="font-semibold text-card-foreground">{otherUser.name}</span> hasn't set up end-to-end encryption yet.
</p>
</div>
<div className="space-y-2 text-sm text-muted-foreground">
<p className="flex items-start gap-2">
<span className="text-accent-foreground/60 mt-0.5"></span>
<span>They need to log in and complete the encryption setup</span>
</p>
<p className="flex items-start gap-2">
<span className="text-accent-foreground/60 mt-0.5"></span>
<span>Once complete, you'll be able to send encrypted messages</span>
</p>
</div>
<p className="text-xs text-center text-muted-foreground/70 pt-2">
🔒 All messages are end-to-end encrypted for your privacy
</p>
</DialogDescription>
</DialogContent>
</Dialog>
)
}
// Show error if session creation failed
if (sessionError) {
return (
<div className="flex items-center justify-center h-full">
<div className="text-center space-y-2">
<p className="text-destructive">Failed to create encryption session</p>
<p className="text-sm text-muted-foreground">{sessionError}</p>
</div>
</div>
);
}
// Wait for session to be established
if (!olmSession) {
return (
<div className="flex items-center justify-center h-full">
<div className="text-center space-y-2">
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto"></div>
<p className="text-sm text-muted-foreground">Establishing secure connection...</p>
</div>
</div>
);
}
return (
<div className="flex flex-col flex-1 min-h-0">
<div className="flex-1 min-h-0 overflow-hidden">
<div
ref={scrollContainerRef}
className="h-full overflow-y-auto flex flex-col"
onScroll={handleScroll}
>
{/* Spacer to push messages to the bottom when there are few messages */}
<div className="flex-1 min-h-0" />
<div className="pt-2 md:pt-4">
{/* Load more indicator */}
{hasMoreMessages && (
<div className="flex justify-center py-4">
{isLoadingMore ? (
<div className="flex items-center gap-2 text-muted-foreground">
<div className="w-4 h-4 border-2 border-muted-foreground/30 border-t-muted-foreground rounded-full animate-spin" />
<span className="text-xs">Loading older messages...</span>
</div>
) : (
<button
onClick={() => {
setIsLoadingMore(true);
prevScrollHeightRef.current = scrollContainerRef.current?.scrollHeight ?? 0;
setTimeout(() => {
setMessageLimit(prev => prev + 50);
setIsLoadingMore(false);
}, 100);
}}
className="text-xs text-muted-foreground hover:text-foreground transition-colors px-3 py-1 rounded-md hover:bg-muted/50 active:bg-muted/70"
>
Load more messages
</button>
)}
</div>
)}
{messages.map((msg, index) => {
const sender = participantDetails.find((p) => p.id === msg.fromUserId);
const selfDetail = participantDetails.find((p) => p.id === userId);
const isSelf = msg.fromUserId === userId;
const displayName = isSelf ? selfDetail?.displayUsername ?? selfDetail?.username ?? selfDetail?.name ?? "You" : (sender?.displayUsername ?? sender?.username ?? sender?.name ?? "Unknown");
const timestamp = moment(msg.timestamp);
const timeLabel = timestamp.isSame(moment(), "day") ? timestamp.format("h:mm A") : timestamp.format("MMM D, YYYY h:mm A");
const shortTimeLabel = timestamp.format("h:mm A")
// Check if this message is from the same user as the previous one within 5 minutes
const prevMsg = index > 0 ? messages[index - 1] : null;
const isGrouped = prevMsg &&
prevMsg.fromUserId === msg.fromUserId &&
msg.timestamp && prevMsg.timestamp &&
(msg.timestamp - prevMsg.timestamp) < 5 * 60 * 1000;
return (
<div
key={msg.id}
className="group relative px-2 md:px-4 py-0.5 hover:bg-muted/50 active:bg-muted/50 transition-colors duration-100"
>
{!isGrouped ? (
// Full message with avatar and header
<div className="flex gap-2 md:gap-4 mt-3 md:mt-[17px]">
<Avatar className="w-8 h-8 md:w-10 md:h-10 shrink-0 mt-0.5">
<AvatarImage src={sender?.image ?? undefined} alt={displayName} />
<AvatarFallback className="text-xs">
{displayName.slice(0, 2).toUpperCase()}
</AvatarFallback>
</Avatar>
<div className="flex-1 min-w-0 pt-0.5">
<div className="flex items-baseline gap-2 leading-snug flex-wrap">
<span className="font-semibold text-sm md:text-[15px] text-foreground hover:underline cursor-pointer">
{displayName}
</span>
<span className="text-[10px] md:text-[11px] text-muted-foreground font-medium">
{timeLabel}
</span>
</div>
<div className="text-sm md:text-[15px] leading-5.5 text-foreground mt-0.5 wrap-break-word">
{msg.content}
</div>
</div>
</div>
) : (
// Compact message without avatar (grouped)
<div className="flex gap-2 md:gap-4 leading-5.5">
<div className="w-6 md:w-10 shrink-0 flex items-start justify-end pt-0.5">
<span className="text-[9px] text-transparent group-hover:text-muted-foreground transition-colors duration-100 font-light">
{shortTimeLabel}
</span>
</div>
<div className="flex-1 min-w-0 text-sm md:text-[15px] leading-5.5 text-foreground wrap-break-word">
{msg.content}
</div>
</div>
)}
</div>
);
})}
{/* Invisible element for auto-scrolling */}
<div ref={messagesEndRef} />
</div>
</div>
</div>
{/* Message input */}
<div className="flex items-center gap-2 shrink-0 px-2 md:px-4 pb-4 md:pb-6 pt-2">
<Input
className="h-10 md:h-11 rounded-lg bg-muted border-0 focus-visible:ring-0 focus-visible:ring-offset-0 px-3 md:px-4 text-sm md:text-[15px]"
placeholder={
otherUser.status === "offline" ?
"As of now, you cannot message offline users." :
`Message @${otherUser.username ?? otherUser.name}`
}
value={messageInput}
onChange={(e) => setMessageInput(e.target.value)}
disabled={otherUser.status === "offline"}
onKeyDown={async (e) => {
if (e.key === 'Enter' && !e.shiftKey && messageInput.trim() && password) {
e.preventDefault();
console.log("[DMChannelContent] Attempting to send message", {
hasOlmSession: !!olmSession,
hasPassword: !!password,
recipientId: otherUser.id,
recipientKeyVersion: otherUser.olmAccount?.keyVersion
});
try {
const messageId = await sendMessage({
channelId,
content: messageInput,
fromUserId: userId,
to: otherUser.id,
timestamp: Date.now(),
status: "sent",
}, olmSession, sendMessageToServer, {
userId,
recipientId: otherUser.id,
password,
recipientKeyVersion: otherUser.olmAccount?.keyVersion,
recipientIdentityKey: otherUser.olmAccount?.identityKey,
});
console.log("[DMChannelContent] Message sent successfully, ID:", messageId);
if (messageId) {
setMessageInput("");
}
} catch (error) {
console.error("[DMChannelContent] Failed to send message:", error);
toast.error("Failed to send message: " + (error instanceof Error ? error.message : "Unknown error"));
}
}
}}
/>
<Button className="flex md:hidden items-center justify-center h-10 md:h-11 w-10 md:w-11" variant="outline" size="icon">
<SendIcon className="size-4" />
</Button>
</div>
</div>
);
}

View file

@ -1,104 +0,0 @@
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
function Empty({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="empty"
className={cn(
"flex min-w-0 flex-1 flex-col items-center justify-center gap-6 rounded-lg border-dashed p-6 text-center text-balance md:p-12",
className
)}
{...props}
/>
)
}
function EmptyHeader({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="empty-header"
className={cn(
"flex max-w-sm flex-col items-center gap-2 text-center",
className
)}
{...props}
/>
)
}
const emptyMediaVariants = cva(
"flex shrink-0 items-center justify-center mb-2 [&_svg]:pointer-events-none [&_svg]:shrink-0",
{
variants: {
variant: {
default: "bg-transparent",
icon: "bg-muted text-foreground flex size-10 shrink-0 items-center justify-center rounded-lg [&_svg:not([class*='size-'])]:size-6",
},
},
defaultVariants: {
variant: "default",
},
}
)
function EmptyMedia({
className,
variant = "default",
...props
}: React.ComponentProps<"div"> & VariantProps<typeof emptyMediaVariants>) {
return (
<div
data-slot="empty-icon"
data-variant={variant}
className={cn(emptyMediaVariants({ variant, className }))}
{...props}
/>
)
}
function EmptyTitle({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="empty-title"
className={cn("text-lg font-medium tracking-tight", className)}
{...props}
/>
)
}
function EmptyDescription({ className, ...props }: React.ComponentProps<"p">) {
return (
<div
data-slot="empty-description"
className={cn(
"text-muted-foreground [&>a:hover]:text-primary text-sm/relaxed [&>a]:underline [&>a]:underline-offset-4",
className
)}
{...props}
/>
)
}
function EmptyContent({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="empty-content"
className={cn(
"flex w-full max-w-sm min-w-0 flex-col items-center gap-4 text-sm text-balance",
className
)}
{...props}
/>
)
}
export {
Empty,
EmptyHeader,
EmptyTitle,
EmptyDescription,
EmptyContent,
EmptyMedia,
}

View file

@ -1,248 +0,0 @@
"use client"
import { useMemo } from "react"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
import { Label } from "@/components/ui/label"
import { Separator } from "@/components/ui/separator"
function FieldSet({ className, ...props }: React.ComponentProps<"fieldset">) {
return (
<fieldset
data-slot="field-set"
className={cn(
"flex flex-col gap-6",
"has-[>[data-slot=checkbox-group]]:gap-3 has-[>[data-slot=radio-group]]:gap-3",
className
)}
{...props}
/>
)
}
function FieldLegend({
className,
variant = "legend",
...props
}: React.ComponentProps<"legend"> & { variant?: "legend" | "label" }) {
return (
<legend
data-slot="field-legend"
data-variant={variant}
className={cn(
"mb-3 font-medium",
"data-[variant=legend]:text-base",
"data-[variant=label]:text-sm",
className
)}
{...props}
/>
)
}
function FieldGroup({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="field-group"
className={cn(
"group/field-group @container/field-group flex w-full flex-col gap-7 data-[slot=checkbox-group]:gap-3 *:data-[slot=field-group]:gap-4",
className
)}
{...props}
/>
)
}
const fieldVariants = cva(
"group/field flex w-full gap-3 data-[invalid=true]:text-destructive",
{
variants: {
orientation: {
vertical: ["flex-col *:w-full [&>.sr-only]:w-auto"],
horizontal: [
"flex-row items-center",
"*:data-[slot=field-label]:flex-auto",
"has-[>[data-slot=field-content]]:items-start has-[>[data-slot=field-content]]:[&>[role=checkbox],[role=radio]]:mt-px",
],
responsive: [
"flex-col *:w-full [&>.sr-only]:w-auto @md/field-group:flex-row @md/field-group:items-center @md/field-group:*:w-auto",
"@md/field-group:*:data-[slot=field-label]:flex-auto",
"@md/field-group:has-[>[data-slot=field-content]]:items-start @md/field-group:has-[>[data-slot=field-content]]:[&>[role=checkbox],[role=radio]]:mt-px",
],
},
},
defaultVariants: {
orientation: "vertical",
},
}
)
function Field({
className,
orientation = "vertical",
...props
}: React.ComponentProps<"div"> & VariantProps<typeof fieldVariants>) {
return (
<div
role="group"
data-slot="field"
data-orientation={orientation}
className={cn(fieldVariants({ orientation }), className)}
{...props}
/>
)
}
function FieldContent({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="field-content"
className={cn(
"group/field-content flex flex-1 flex-col gap-1.5 leading-snug",
className
)}
{...props}
/>
)
}
function FieldLabel({
className,
...props
}: React.ComponentProps<typeof Label>) {
return (
<Label
data-slot="field-label"
className={cn(
"group/field-label peer/field-label flex w-fit gap-2 leading-snug group-data-[disabled=true]/field:opacity-50",
"has-[>[data-slot=field]]:w-full has-[>[data-slot=field]]:flex-col has-[>[data-slot=field]]:rounded-md has-[>[data-slot=field]]:border *:data-[slot=field]:p-4",
"has-data-[state=checked]:bg-primary/5 has-data-[state=checked]:border-primary dark:has-data-[state=checked]:bg-primary/10",
className
)}
{...props}
/>
)
}
function FieldTitle({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="field-label"
className={cn(
"flex w-fit items-center gap-2 text-sm leading-snug font-medium group-data-[disabled=true]/field:opacity-50",
className
)}
{...props}
/>
)
}
function FieldDescription({ className, ...props }: React.ComponentProps<"p">) {
return (
<p
data-slot="field-description"
className={cn(
"text-muted-foreground text-sm leading-normal font-normal group-has-data-[orientation=horizontal]/field:text-balance",
"last:mt-0 nth-last-2:-mt-1 [[data-variant=legend]+&]:-mt-1.5",
"[&>a:hover]:text-primary [&>a]:underline [&>a]:underline-offset-4",
className
)}
{...props}
/>
)
}
function FieldSeparator({
children,
className,
...props
}: React.ComponentProps<"div"> & {
children?: React.ReactNode
}) {
return (
<div
data-slot="field-separator"
data-content={!!children}
className={cn(
"relative -my-2 h-5 text-sm group-data-[variant=outline]/field-group:-mb-2",
className
)}
{...props}
>
<Separator className="absolute inset-0 top-1/2" />
{children && (
<span
className="bg-background text-muted-foreground relative mx-auto block w-fit px-2"
data-slot="field-separator-content"
>
{children}
</span>
)}
</div>
)
}
function FieldError({
className,
children,
errors,
...props
}: React.ComponentProps<"div"> & {
errors?: Array<{ message?: string } | undefined>
}) {
const content = useMemo(() => {
if (children) {
return children
}
if (!errors?.length) {
return null
}
const uniqueErrors = [
...new Map(errors.map((error) => [error?.message, error])).values(),
]
if (uniqueErrors?.length == 1) {
return uniqueErrors[0]?.message
}
return (
<ul className="ml-4 flex list-disc flex-col gap-1">
{uniqueErrors.map(
(error, index) =>
error?.message && <li key={index}>{error.message}</li>
)}
</ul>
)
}, [children, errors])
if (!content) {
return null
}
return (
<div
role="alert"
data-slot="field-error"
className={cn("text-destructive text-sm font-normal", className)}
{...props}
>
{content}
</div>
)
}
export {
Field,
FieldLabel,
FieldDescription,
FieldError,
FieldGroup,
FieldLegend,
FieldSeparator,
FieldSet,
FieldContent,
FieldTitle,
}

View file

@ -1,96 +0,0 @@
"use client"
import { Button } from "@/components/ui/button"
import {
Popover,
PopoverContent,
PopoverTrigger,
} from "@/components/ui/popover"
import { Separator } from "@/components/ui/separator"
import {
MoreVerticalIcon,
PhoneIcon,
ShieldBanIcon,
UserMinusIcon,
UsersIcon,
VideoIcon,
} from "lucide-react"
export interface FriendActionsMenuProps {
friendId: string
onStartCall?: (friendId: string) => void
onVideoCall?: (friendId: string) => void
onViewProfile?: (friendId: string) => void
onRemoveFriend?: (friendId: string) => void
onBlock?: (friendId: string) => void
}
export function FriendActionsMenu({
friendId,
onStartCall,
onVideoCall,
onViewProfile,
onRemoveFriend,
onBlock,
}: FriendActionsMenuProps) {
return (
<Popover>
<PopoverTrigger asChild>
<Button
variant="ghost"
size="icon-sm"
className="size-8 hover:bg-background/80"
title="More options"
>
<MoreVerticalIcon className="size-4" />
</Button>
</PopoverTrigger>
<PopoverContent className="w-48 p-1" align="end">
<div className="flex flex-col">
<Button
variant="ghost"
className="justify-start h-9 px-2 font-normal hover:bg-accent"
onClick={() => onStartCall?.(friendId)}
>
<PhoneIcon className="size-4" />
<span className="text-sm">Start Call</span>
</Button>
<Button
variant="ghost"
className="justify-start h-9 px-2 font-normal hover:bg-accent"
onClick={() => onVideoCall?.(friendId)}
>
<VideoIcon className="size-4" />
<span className="text-sm">Start Video Call</span>
</Button>
<Button
variant="ghost"
className="justify-start h-9 px-2 font-normal hover:bg-accent"
onClick={() => onViewProfile?.(friendId)}
>
<UsersIcon className="size-4" />
<span className="text-sm">View Profile</span>
</Button>
<Separator className="my-1" />
<Button
variant="ghost"
className="justify-start h-9 px-2 font-normal hover:bg-accent text-orange-500 hover:text-orange-600"
onClick={() => onRemoveFriend?.(friendId)}
>
<UserMinusIcon className="size-4" />
<span className="text-sm">Remove Friend</span>
</Button>
<Button
variant="ghost"
className="justify-start h-9 px-2 font-normal hover:bg-accent text-red-500 hover:text-red-600"
onClick={() => onBlock?.(friendId)}
>
<ShieldBanIcon className="size-4" />
<span className="text-sm">Block</span>
</Button>
</div>
</PopoverContent>
</Popover>
)
}

View file

@ -1,109 +0,0 @@
"use client"
import { Button } from "@/components/ui/button"
import { getOrCreateDmChannel } from "@/lib/db"
import { MessageCircleIcon } from "lucide-react"
import { useRouter } from "next/navigation"
import UserCard from "../user/user-card"
import { FriendActionsMenu } from "./friend-actions-menu"
export interface FriendData {
_id: string
id: string
name?: string | null
username?: string | null
displayUsername?: string | null
image?: string | null
friendshipCreatedAt?: number
status?: {
status: "online" | "busy" | "offline" | "away"
isUserSet: boolean
}
}
export interface FriendListItemProps {
friend: FriendData
onMessage?: (friendId: string) => void
onStartCall?: (friendId: string) => void
onVideoCall?: (friendId: string) => void
onViewProfile?: (friendId: string) => void
onRemoveFriend?: (friendId: string) => void
onBlock?: (friendId: string) => void
userId: string
}
export function FriendListItem({
friend,
onMessage,
onStartCall,
onVideoCall,
onViewProfile,
onRemoveFriend,
onBlock,
userId,
}: FriendListItemProps) {
const router = useRouter()
const displayName = friend.displayUsername || friend.username || friend.name
const status = friend.status?.status || "offline"
return (
<div
className="flex flex-row items-center justify-between w-full p-2 md:p-3 rounded-md hover:bg-accent/50 active:bg-accent/60 transition-colors group border border-transparent hover:border-border/40 hover:cursor-pointer"
onClick={() => {
// Call the db to create or get the dm channel
getOrCreateDmChannel(userId, {
id: friend._id,
name: displayName ?? "",
}).then((channel) => {
if (channel) {
router.push(`/channels/me/${channel.id}`)
}
})
}}
>
{/* Left side: Avatar + Info */}
<div className="flex flex-row items-center gap-2 md:gap-3 flex-1 min-w-0">
<UserCard
userName={displayName ?? ""}
image={friend.image ?? undefined}
status={status}
/>
<div className="flex flex-col justify-center items-start overflow-hidden flex-1 min-w-0">
<span className="text-sm font-semibold truncate w-full text-foreground">
{displayName}
</span>
<span className="text-xs text-muted-foreground capitalize truncate w-full">
{status}
</span>
</div>
</div>
{/* Right side: Actions Menu - always visible on mobile via opacity, hover on desktop */}
<div className="flex items-center gap-1 md:gap-2 md:opacity-0 md:group-hover:opacity-100 transition-opacity shrink-0">
<Button
variant="ghost"
size="icon-sm"
className="size-9 md:size-8 hover:bg-background/80"
onClick={(e) => {
e.stopPropagation()
onMessage?.(friend._id)
}}
title="Message"
>
<MessageCircleIcon className="size-4" />
</Button>
<FriendActionsMenu
friendId={friend._id}
onStartCall={onStartCall}
onVideoCall={onVideoCall}
onViewProfile={onViewProfile}
onRemoveFriend={onRemoveFriend}
onBlock={onBlock}
/>
</div>
</div>
)
}

View file

@ -1,124 +0,0 @@
"use client"
import { Input } from "@/components/ui/input"
import { useQuery } from "convex/react"
import * as React from "react"
import { api } from "../../../../convex/_generated/api"
import { FriendListItem, type FriendData } from "./friend-list-item"
export interface FriendsPageProps {
friendsPage: "all" | "available"
socketStatus: string
emptyMessage?: string
userId: string
}
export function FriendsPage({
friendsPage,
socketStatus,
userId,
emptyMessage = "No friends found",
}: FriendsPageProps) {
const [friendsSearch, setFriendsSearch] = React.useState("")
// Fetch friends directly in this component
const friends = useQuery(
api.auth.getFriends,
socketStatus === "connected" ? {} : "skip"
)
const filteredFriends = React.useMemo(() => {
if (!friends) return []
let filtered = friends.filter(Boolean) as FriendData[]
// Filter by availability
if (friendsPage === "available") {
filtered = filtered.filter((f: FriendData) => f.status?.status !== "offline")
}
// Filter by search
if (friendsSearch) {
const search = friendsSearch.toLowerCase()
filtered = filtered.filter((f: FriendData) => {
const displayName = f.displayUsername || f.username || f.name || ""
return displayName.toLowerCase().includes(search)
})
}
return filtered
}, [friends, friendsPage, friendsSearch])
const handleMessage = React.useCallback((friendId: string) => {
// TODO: Open DM with friend
console.log("Open DM with", friendId)
}, [])
const handleStartCall = React.useCallback((friendId: string) => {
console.log("Start Call with", friendId)
}, [])
const handleVideoCall = React.useCallback((friendId: string) => {
console.log("Start Video Call with", friendId)
}, [])
const handleViewProfile = React.useCallback((friendId: string) => {
console.log("View Profile", friendId)
}, [])
const handleRemoveFriend = React.useCallback((friendId: string) => {
console.log("Remove Friend", friendId)
}, [])
const handleBlock = React.useCallback((friendId: string) => {
console.log("Block User", friendId)
}, [])
return (
<div className="flex flex-col flex-1 overflow-hidden">
{/* Search Input - Sticky at top */}
<div className="flex flex-col p-2 md:p-4 pb-2 bg-background border-b border-border/40">
<Input
placeholder="Search for a friend..."
value={friendsSearch}
onChange={(e) => setFriendsSearch(e.target.value)}
className="w-full h-10 md:h-9"
/>
</div>
{/* Scrollable Friends List */}
<div className="flex flex-col flex-1 overflow-y-auto p-2 md:p-4">
<div className="flex flex-col items-start w-full gap-1 md:gap-2">
<span className="text-xs md:text-sm text-start font-medium text-muted-foreground mb-1">
{friendsPage === "all"
? `All Friends • ${filteredFriends.length} of ${friends?.length || 0}`
: `Available Friends • ${filteredFriends.length} of ${friends?.filter((f: FriendData) => f && f.status?.status !== "offline").length || 0}`
}
</span>
{filteredFriends.length > 0 ? (
filteredFriends.map((friend: FriendData) => (
<FriendListItem
userId={userId}
key={friend._id}
friend={friend}
onMessage={handleMessage}
onStartCall={handleStartCall}
onVideoCall={handleVideoCall}
onViewProfile={handleViewProfile}
onRemoveFriend={handleRemoveFriend}
onBlock={handleBlock}
/>
))
) : (
<div className="flex flex-col items-center justify-center w-full py-8 md:py-12">
<span className="text-sm font-medium text-muted-foreground text-center px-4">
{friendsSearch ? `No friends found matching "${friendsSearch}"` : emptyMessage}
</span>
</div>
)}
</div>
</div>
</div>
)
}

View file

@ -1,7 +0,0 @@
export { FriendListItem } from "./friend-list-item"
export type { FriendListItemProps, FriendData } from "./friend-list-item"
export { FriendActionsMenu } from "./friend-actions-menu"
export type { FriendActionsMenuProps } from "./friend-actions-menu"
export { FriendsPage } from "./friends-page"
export type { FriendsPageProps } from "./friends-page"

View file

@ -1,44 +0,0 @@
"use client"
import * as React from "react"
import * as HoverCardPrimitive from "@radix-ui/react-hover-card"
import { cn } from "@/lib/utils"
function HoverCard({
...props
}: React.ComponentProps<typeof HoverCardPrimitive.Root>) {
return <HoverCardPrimitive.Root data-slot="hover-card" {...props} />
}
function HoverCardTrigger({
...props
}: React.ComponentProps<typeof HoverCardPrimitive.Trigger>) {
return (
<HoverCardPrimitive.Trigger data-slot="hover-card-trigger" {...props} />
)
}
function HoverCardContent({
className,
align = "center",
sideOffset = 4,
...props
}: React.ComponentProps<typeof HoverCardPrimitive.Content>) {
return (
<HoverCardPrimitive.Portal data-slot="hover-card-portal">
<HoverCardPrimitive.Content
data-slot="hover-card-content"
align={align}
sideOffset={sideOffset}
className={cn(
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-64 origin-(--radix-hover-card-content-transform-origin) rounded-md border p-4 shadow-md outline-hidden",
className
)}
{...props}
/>
</HoverCardPrimitive.Portal>
)
}
export { HoverCard, HoverCardTrigger, HoverCardContent }

View file

@ -1,21 +0,0 @@
import * as React from "react"
import { cn } from "@/lib/utils"
function Input({ className, type, ...props }: React.ComponentProps<"input">) {
return (
<input
type={type}
data-slot="input"
className={cn(
"file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground dark:bg-input/30 border-input h-9 w-full min-w-0 rounded-md border bg-transparent px-3 py-1 text-base shadow-xs transition-[color,box-shadow] outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
"focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]",
"aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
className
)}
{...props}
/>
)
}
export { Input }

View file

@ -1,193 +0,0 @@
import * as React from "react"
import { Slot } from "@radix-ui/react-slot"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
import { Separator } from "@/components/ui/separator"
function ItemGroup({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
role="list"
data-slot="item-group"
className={cn("group/item-group flex flex-col", className)}
{...props}
/>
)
}
function ItemSeparator({
className,
...props
}: React.ComponentProps<typeof Separator>) {
return (
<Separator
data-slot="item-separator"
orientation="horizontal"
className={cn("my-0", className)}
{...props}
/>
)
}
const itemVariants = cva(
"group/item flex items-center border border-transparent text-sm rounded-md transition-colors [a]:hover:bg-accent/50 [a]:transition-colors duration-100 flex-wrap outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]",
{
variants: {
variant: {
default: "bg-transparent",
outline: "border-border",
muted: "bg-muted/50",
},
size: {
default: "p-4 gap-4 ",
sm: "py-3 px-4 gap-2.5",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
}
)
function Item({
className,
variant = "default",
size = "default",
asChild = false,
...props
}: React.ComponentProps<"div"> &
VariantProps<typeof itemVariants> & { asChild?: boolean }) {
const Comp = asChild ? Slot : "div"
return (
<Comp
data-slot="item"
data-variant={variant}
data-size={size}
className={cn(itemVariants({ variant, size, className }))}
{...props}
/>
)
}
const itemMediaVariants = cva(
"flex shrink-0 items-center justify-center gap-2 group-has-data-[slot=item-description]/item:self-start [&_svg]:pointer-events-none group-has-data-[slot=item-description]/item:translate-y-0.5",
{
variants: {
variant: {
default: "bg-transparent",
icon: "size-8 border rounded-sm bg-muted [&_svg:not([class*='size-'])]:size-4",
image:
"size-10 rounded-sm overflow-hidden [&_img]:size-full [&_img]:object-cover",
},
},
defaultVariants: {
variant: "default",
},
}
)
function ItemMedia({
className,
variant = "default",
...props
}: React.ComponentProps<"div"> & VariantProps<typeof itemMediaVariants>) {
return (
<div
data-slot="item-media"
data-variant={variant}
className={cn(itemMediaVariants({ variant, className }))}
{...props}
/>
)
}
function ItemContent({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="item-content"
className={cn(
"flex flex-1 flex-col gap-1 [&+[data-slot=item-content]]:flex-none",
className
)}
{...props}
/>
)
}
function ItemTitle({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="item-title"
className={cn(
"flex w-fit items-center gap-2 text-sm leading-snug font-medium",
className
)}
{...props}
/>
)
}
function ItemDescription({ className, ...props }: React.ComponentProps<"p">) {
return (
<p
data-slot="item-description"
className={cn(
"text-muted-foreground line-clamp-2 text-sm leading-normal font-normal text-balance",
"[&>a:hover]:text-primary [&>a]:underline [&>a]:underline-offset-4",
className
)}
{...props}
/>
)
}
function ItemActions({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="item-actions"
className={cn("flex items-center gap-2", className)}
{...props}
/>
)
}
function ItemHeader({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="item-header"
className={cn(
"flex basis-full items-center justify-between gap-2",
className
)}
{...props}
/>
)
}
function ItemFooter({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="item-footer"
className={cn(
"flex basis-full items-center justify-between gap-2",
className
)}
{...props}
/>
)
}
export {
Item,
ItemMedia,
ItemContent,
ItemActions,
ItemGroup,
ItemSeparator,
ItemTitle,
ItemDescription,
ItemHeader,
ItemFooter,
}

View file

@ -1,28 +0,0 @@
import { cn } from "@/lib/utils"
function Kbd({ className, ...props }: React.ComponentProps<"kbd">) {
return (
<kbd
data-slot="kbd"
className={cn(
"bg-muted text-muted-foreground pointer-events-none inline-flex h-5 w-fit min-w-5 items-center justify-center gap-1 rounded-sm px-1 font-sans text-xs font-medium select-none",
"[&_svg:not([class*='size-'])]:size-3",
"in-data-[slot=tooltip-content]:bg-background/20 in-data-[slot=tooltip-content]:text-background dark:in-data-[slot=tooltip-content]:bg-background/10",
className
)}
{...props}
/>
)
}
function KbdGroup({ className, ...props }: React.ComponentProps<"div">) {
return (
<kbd
data-slot="kbd-group"
className={cn("inline-flex items-center gap-1", className)}
{...props}
/>
)
}
export { Kbd, KbdGroup }

View file

@ -1,24 +0,0 @@
"use client"
import * as React from "react"
import * as LabelPrimitive from "@radix-ui/react-label"
import { cn } from "@/lib/utils"
function Label({
className,
...props
}: React.ComponentProps<typeof LabelPrimitive.Root>) {
return (
<LabelPrimitive.Root
data-slot="label"
className={cn(
"flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",
className
)}
{...props}
/>
)
}
export { Label }

View file

@ -1,372 +0,0 @@
"use client"
import { Button } from "@/components/ui/button"
import { ScrollArea } from "@/components/ui/scroll-area"
import { clearUnread, db } from "@/lib/db"
import { QuestionMarkIcon } from "@phosphor-icons/react"
import { formatDistanceToNow } from "date-fns"
import { useLiveQuery } from "dexie-react-hooks"
import { Globe2Icon, GlobeIcon, HomeIcon, MessageSquarePlusIcon, SettingsIcon, UsersIcon, XIcon } from "lucide-react"
import { useRouter } from "next/navigation"
import { useMemo } from "react"
import UserCard from "../user/user-card"
// Mock channels for testing scroll behavior - set to true to enable
const ENABLE_MOCK_CHANNELS = true
function createMockChannel(id: string, name: string, message: string, hoursAgo: number): SiPher.Channel {
return {
id: `mock-${id}`,
name,
type: "DM" as SiPher.Channel["type"],
participants: ["current-user", `user-${id}`],
isOpen: true,
metadata: {},
times: {
createdAt: Date.now() - 1000 * 60 * 60 * 24 * 30,
updatedAt: Date.now() - 1000 * 60 * 60 * hoursAgo,
lastMessage: { content: message } as unknown as SiPher.Channel["times"]["lastMessage"],
lastMessageAt: Date.now() - 1000 * 60 * 60 * hoursAgo
}
}
}
// const mockChannels: SiPher.Channel[] = ENABLE_MOCK_CHANNELS ? [
// createMockChannel("1", "Alice Johnson", "Hey, are you coming to the meeting?", 0.08),
// createMockChannel("2", "Bob Smith", "The project looks great!", 0.5),
// createMockChannel("3", "Charlie Brown", "Can you review my PR?", 1),
// createMockChannel("4", "Diana Prince", "Thanks for the help!", 2),
// createMockChannel("5", "Edward Norton", "Let's catch up soon", 5),
// createMockChannel("6", "Fiona Green", "Did you see the news?", 12),
// createMockChannel("7", "George Wilson", "Meeting at 3pm", 24),
// createMockChannel("8", "Hannah Baker", "Sounds good to me!", 48),
// createMockChannel("9", "Ivan Petrov", "I'll send over the files", 72),
// createMockChannel("10", "Julia Roberts", "Great work on that!", 96),
// createMockChannel("11", "Kevin Hart", "LOL that's hilarious", 120),
// createMockChannel("12", "Laura Palmer", "See you tomorrow", 144),
// ] : []
export interface ChannelListProps {
currentChannel: SiPher.Channel | null
openDmChannels: SiPher.Channel[]
page: SiPher.PageTypes
onPageChange: (page: SiPher.PageTypes) => void
emptyMessage?: string
dmChannel?: {
id: string
participantDetails: {
id: string
name: string
username: string
displayUsername: string
image: string
status: "online" | "busy" | "offline" | "away"
isCurrentUser: boolean
}[]
}
onChannelSelect?: () => void
isMobile?: boolean
}
export function ChannelList({
currentChannel,
openDmChannels,
page,
onPageChange,
emptyMessage = "No messages yet",
dmChannel,
onChannelSelect,
isMobile,
}: ChannelListProps) {
const router = useRouter()
const unreadCount = useLiveQuery(
() => db.unreadCounts.toArray(),
[]
)
// Combine real channels with mock channels for testing, sorted by most recent activity
const allDmChannels = useMemo(() => {
return [...openDmChannels].sort((a, b) => {
const aTime = a.times?.lastMessageAt ?? a.times?.updatedAt ?? 0
const bTime = b.times?.lastMessageAt ?? b.times?.updatedAt ?? 0
return bTime - aTime // Descending order (most recent first)
})
}, [openDmChannels])
const handleNavigation = (path: string) => {
router.push(path)
onChannelSelect?.()
}
return (
<div className={`flex flex-col shrink-0 border-border/40 ${isMobile ? 'w-full h-full bg-transparent' : 'max-w-72 min-w-72 h-full border-r bg-linear-to-b from-background to-muted/20'}`}>
{/* Channel List Header - Navigation Items (Desktop only) */}
{!isMobile && (
<>
<div className="flex flex-col p-2 gap-1">
<Button
variant="ghost"
className={`w-full justify-start gap-3 h-11 px-3 rounded-lg transition-all ${page === "friends"
? "bg-primary/10 text-primary hover:bg-primary/15 ring-1 ring-primary/20"
: "hover:bg-accent/60"
}`}
onClick={() => {
onPageChange("friends")
handleNavigation("/channels/me/friends")
}}
>
<div className={`flex items-center justify-center w-8 h-8 rounded-lg ${page === "friends"
? "bg-primary/20"
: "bg-muted/50"
}`}>
<UsersIcon className="size-4" />
</div>
<span className="text-sm font-semibold">Friends</span>
</Button>
<Button
variant="ghost"
className={`w-full justify-start gap-3 h-11 px-3 rounded-lg transition-all ${page === "support"
? "bg-primary/10 text-primary hover:bg-primary/15 ring-1 ring-primary/20"
: "hover:bg-accent/60"
}`}
onClick={() => {
onPageChange("support")
onChannelSelect?.()
}}
>
<div className={`flex items-center justify-center w-8 h-8 rounded-lg ${page === "support"
? "bg-primary/20"
: "bg-muted/50"
}`}>
<SettingsIcon className="size-4" />
</div>
<span className="text-sm font-semibold">Settings</span>
</Button>
</div>
{/* Divider with label */}
<div className="flex items-center gap-2 px-3 py-2">
<div className="h-px flex-1 bg-linear-to-r from-border/60 to-transparent" />
</div>
</>
)}
{/* Mobile Navigation Buttons */}
{isMobile && (
<div className="flex gap-2 px-2 py-2">
<Button
variant={page === "friends" ? "default" : "outline"}
size="sm"
className="flex-1 h-9 text-xs font-semibold"
onClick={() => {
onPageChange("friends")
handleNavigation("/")
}}
>
<UsersIcon className="size-3.5 mr-1.5" />
Friends
</Button>
<Button
variant={page === "support" ? "default" : "outline"}
size="sm"
className="flex-1 h-9 text-xs font-semibold"
onClick={() => {
onPageChange("support")
onChannelSelect?.()
}}
>
<SettingsIcon className="size-3.5 mr-1.5" />
Settings
</Button>
</div>
)}
{/* Channel List */}
<div className={`flex flex-col flex-1 min-h-0 ${isMobile ? 'px-2' : 'px-2'}`}>
<div className="flex flex-col w-full gap-2">
<div className="flex items-center justify-between px-1 py-2 select-none">
<span className={`font-bold uppercase tracking-wider text-muted-foreground/70 ${isMobile ? 'text-[10px]' : 'text-[11px]'}`}>
Global Nests
</span>
</div>
{/* Nest Type Selector */}
<div className={`flex ${isMobile ? 'flex-col gap-1' : 'flex-row gap-0.5'} p-1 bg-muted/40 rounded-lg`}>
{[
{ id: 'global', icon: GlobeIcon, label: 'Global', description: 'Worldwide nests' },
{ id: 'continental', icon: Globe2Icon, label: 'Continent', description: 'Nests by continent' },
{ id: 'country', icon: HomeIcon, label: 'Country', description: 'Your country nests' },
].map((nest) => {
const isActive = nest.id === 'global' // TODO: Replace with actual state
const Icon = nest.icon
return (
<Button
key={nest.id}
variant="ghost"
size="sm"
className={`
${isMobile
? 'w-full justify-start gap-3 h-11 px-3'
: 'flex-1 gap-1.5 h-7 px-2'
}
rounded-md transition-all duration-150
${isActive
? 'bg-background text-foreground shadow-sm'
: 'text-muted-foreground hover:text-foreground hover:bg-transparent'
}
`}
title={nest.description}
onClick={() => {
// TODO: Handle nest type selection
onChannelSelect?.()
}}
>
{isMobile ? (
<>
<div className={`
flex items-center justify-center w-7 h-7 rounded-md transition-colors
${isActive ? 'bg-primary/15' : 'bg-muted/50'}
`}>
<Icon className="size-4" />
</div>
<span className="text-sm font-medium">{nest.label}</span>
</>
) : (
<>
<Icon className="size-3.5" />
<span className="text-[11px] font-medium">{nest.label}</span>
</>
)}
</Button>
)
})}
</div>
</div>
{(page === "friends" || !currentChannel) && (
<div className="flex flex-col w-full flex-1 min-h-0 overflow-hidden mb-16">
{/* DM Header */}
<div className="flex items-center justify-between px-1 py-2 select-none shrink-0">
<span className={`font-bold uppercase tracking-wider text-muted-foreground/70 ${isMobile ? 'text-[10px]' : 'text-[11px]'}`}>
Direct Messages
</span>
<Button
variant="ghost"
size="icon-sm"
className="size-6 hover:bg-accent rounded-md"
title="New Message"
>
<MessageSquarePlusIcon className="size-3.5" />
</Button>
</div>
{allDmChannels.length > 0 && (
<ScrollArea className="flex-1 -mx-2 h-full">
<div className="flex flex-col gap-0.5 px-2 pb-2">
{allDmChannels.map((channel) => {
const isActive = dmChannel?.id === channel.id
const lastMessage = channel.times?.lastMessage
const lastMessageTime = channel.times?.lastMessageAt
const channelUnreadCount = unreadCount?.find((unread) => unread.channelId === channel.id)?.count ?? 0
if (!channel.isOpen) return null;
return (
<div
key={channel.id}
className={`flex flex-row items-center gap-3 px-2 py-2.5 rounded-lg transition-all cursor-pointer group ${isActive
? "bg-accent/80 shadow-sm ring-1 ring-accent"
: "hover:bg-accent/40 active:bg-accent/60"
}`}
onClick={() => {
clearUnread(channel.id)
console.log("Cleared unread count for channel", channel.id)
handleNavigation(`/channels/me/${channel.id}`)
}}
>
<div className="relative shrink-0">
<UserCard
userName={channel.name}
image={channel.metadata?.icon ?? undefined}
status={"none"}
/>
{channelUnreadCount > 0 && (
<span className="absolute -top-1 -right-1 flex items-center justify-center min-w-[18px] h-[18px] px-1.5 rounded-full bg-linear-to-br from-red-500 to-red-600 text-[10px] font-bold text-white shadow-md ring-2 ring-background">
{channelUnreadCount > 99 ? '99+' : channelUnreadCount}
</span>
)}
</div>
{/* Channel Info */}
<div className="flex flex-col justify-center flex-1 min-w-0 overflow-hidden">
<div className="flex items-center justify-between gap-2">
<span className={`text-sm truncate ${isActive ? 'font-bold' : 'font-semibold'} text-foreground`}>
{channel.name}
</span>
{lastMessageTime && (
<span className="text-[10px] text-muted-foreground/60 shrink-0 font-medium">
{formatDistanceToNow(lastMessageTime, { addSuffix: false })}
</span>
)}
</div>
{lastMessage && (
<span className="text-xs text-muted-foreground/70 truncate mt-0.5">
{lastMessage.content}
</span>
)}
</div>
{/* Close button - always visible on mobile, hover-visible on desktop */}
<Button
variant="ghost"
size="icon"
className={`size-7 p-0 shrink-0 hover:bg-destructive/10 hover:text-destructive rounded-md transition-all ${isMobile ? 'opacity-60' : 'opacity-0 group-hover:opacity-100'}`}
onClick={(e) => {
e.stopPropagation()
const isCurrentlyViewing = isActive
db.channels.where("id").equals(channel.id).modify((channel) => {
channel.isOpen = false;
});
// Navigate away if we're closing the currently viewed channel
if (isCurrentlyViewing) {
console.log("Navigating away from channel")
handleNavigation("/")
}
}}
title="Close DM"
>
<XIcon className="size-3.5" />
</Button>
</div>
)
})}
</div>
</ScrollArea>
)}
{allDmChannels.length === 0 && (
<div className="flex flex-col items-center justify-center py-8 px-4 text-center">
<div className="flex items-center justify-center w-12 h-12 rounded-full bg-muted/50 mb-3">
<QuestionMarkIcon size={20} className="text-muted-foreground/50" />
</div>
<span className="text-xs font-medium text-muted-foreground/70 leading-relaxed">
{emptyMessage}
</span>
</div>
)}
</div>
)}
{page !== "friends" && currentChannel && (
<div className="flex items-center justify-center py-8">
<span className="text-sm font-medium text-muted-foreground">No channels</span>
</div>
)}
</div>
</div>
)
}

View file

@ -1,9 +0,0 @@
export { ChannelList } from "./channel-list"
export type { ChannelListProps } from "./channel-list"
export { MainContentLayout } from "./main-content-layout"
export type { MainContentLayoutProps } from "./main-content-layout"
export { PageHeader } from "./page-header"
export type { PageHeaderProps } from "./page-header"
export { SettingsPage } from "./settings-page"
export type { SettingsPageProps } from "./settings-page"

View file

@ -1,312 +0,0 @@
"use client"
import FriendRequestModal from "@/components/home/modals/friendRequest"
import { Button } from "@/components/ui/button"
import LogoIcon from "@/components/ui/logo-icon"
import { Sheet, SheetContent, SheetDescription, SheetHeader, SheetTitle } from "@/components/ui/sheet"
import { useIsMobile } from "@/hooks/use-mobile"
import { db } from "@/lib/db"
import { cn } from "@/lib/utils"
import { CompassIcon } from "@phosphor-icons/react"
import { useQuery } from "convex/react"
import { useLiveQuery } from "dexie-react-hooks"
import { Plus } from "lucide-react"
import * as React from "react"
import { useEffect, useMemo } from "react"
import { api } from "../../../../convex/_generated/api"
import { Doc } from "../../../../convex/betterAuth/_generated/dataModel"
import DMChannelContent from "../dm/DmChannelContent"
import { FriendsPage } from "../friends/friends-page"
import { Spinner } from "../spinner"
import { ChannelList } from "./channel-list"
import { PageHeader } from "./page-header"
import { SettingsPage } from "./settings-page"
export interface MainContentLayoutProps {
socketStatus: string
emptyChannelMessage?: string
emptyFriendsMessage?: string
userId: string
routeInfo: {
type: SiPher.PageTypes
dmChannelId?: string
serverId?: string
serverChannelId?: string
}
userNests: Doc<"nests">[] | undefined
}
export function MainContentLayout({
socketStatus,
emptyChannelMessage,
emptyFriendsMessage,
userId,
routeInfo,
userNests,
}: MainContentLayoutProps) {
const { type, dmChannelId, serverId, serverChannelId } = routeInfo
const [page, setPage] = React.useState<SiPher.PageTypes>(type)
const [friendsPage, setFriendsPage] = React.useState<"all" | "available">("all")
const [friendModal, setFriendModal] = React.useState(false)
const [currentChannel] = React.useState<SiPher.Channel | null>(null)
const [mobileChannelListOpen, setMobileChannelListOpen] = React.useState(false)
const isMobile = useIsMobile()
// Use useLiveQuery to reactively fetch channels - automatically updates when DB changes
const openDmChannels = useLiveQuery(
() => db.channels.where("participants").equals(userId).toArray(),
[userId]
) ?? []
const participantIds = openDmChannels
.find((channel) => channel.id === dmChannelId)
?.participants ?? []
const getParticipantDetails: SiPher.ParticipantDetail[] | undefined = useQuery(
api.auth.getParticipantDetails,
participantIds.length > 0 && dmChannelId ? { participantIds } : "skip"
)
// Combine channel from local DB with participant details from Convex
const dmChannel = useMemo(() => {
if (!dmChannelId) return undefined
const channel = openDmChannels.find((ch) => ch.id === dmChannelId)
if (!channel || !getParticipantDetails) return undefined
return {
id: channel.id,
participantDetails: getParticipantDetails.map((participant) => ({
id: participant.id as string,
name: participant.name,
username: participant.username ?? "",
displayUsername: participant.displayUsername ?? "",
image: participant.image ?? "",
status: participant.status,
isCurrentUser: participant.id === userId,
}))
}
}, [openDmChannels, dmChannelId, getParticipantDetails])
// Sync page state with route props for seamless navigation
useEffect(() => {
setPage(type);
}, [type]);
// Close mobile channel list when navigating to a channel
const handlePageChange = React.useCallback((newPage: SiPher.PageTypes) => {
setPage(newPage);
if (isMobile) {
setMobileChannelListOpen(false);
}
}, [isMobile]);
// Close mobile sheet when a DM channel is selected
const handleMobileChannelSelect = React.useCallback(() => {
if (isMobile) {
setMobileChannelListOpen(false);
}
}, [isMobile]);
const channelListContent = (
<ChannelList
currentChannel={currentChannel}
openDmChannels={openDmChannels}
page={page}
onPageChange={handlePageChange}
emptyMessage={emptyChannelMessage}
dmChannel={dmChannel}
onChannelSelect={handleMobileChannelSelect}
isMobile={isMobile}
/>
);
return (
<>
<div className="flex flex-col h-full">
<PageHeader
currentChannel={currentChannel}
page={page}
friendsPage={friendsPage}
onFriendsPageChange={setFriendsPage}
onAddFriend={() => setFriendModal(true)}
dmChannel={dmChannel}
serverId={serverId}
serverChannelId={serverChannelId}
onToggleMobileChannelList={() => setMobileChannelListOpen(true)}
isMobile={isMobile}
/>
<div className="flex flex-1 overflow-hidden">
<div className="hidden md:flex h-full">
{channelListContent}
</div>
{isMobile && (
<Sheet open={mobileChannelListOpen} onOpenChange={setMobileChannelListOpen}>
<SheetContent side="left" className="w-[calc(100%-3rem)] max-w-[340px] p-0 [&>button]:hidden">
<SheetHeader className="sr-only">
<SheetTitle>Channels</SheetTitle>
<SheetDescription>Navigate between channels and DMs</SheetDescription>
</SheetHeader>
<div className="flex h-full">
<div className="flex flex-col items-center w-[72px] shrink-0 bg-muted/50 py-3 gap-2">
<MobileServerIcon
isActive={true}
isHome
>
<LogoIcon className="size-6" />
</MobileServerIcon>
<div className="w-8 h-0.5 rounded-full bg-border/60 my-1" />
<MobileServerIcon>
<CompassIcon className="size-5" weight="fill" />
</MobileServerIcon>
{/* Future: Server icons will go here */}
{/* Placeholder for servers */}
<MobileServerIcon isAddButton>
<Plus className="size-5" />
</MobileServerIcon>
</div>
<div className="flex-1 flex flex-col bg-background min-w-0 border-l border-border/30">
<div className="flex items-center px-4 h-12 shrink-0 border-b border-border/30">
<span className="text-sm font-semibold text-foreground">Direct Messages</span>
</div>
<div className="flex-1 overflow-y-auto">
{channelListContent}
</div>
</div>
</div>
</SheetContent>
</Sheet>
)}
{/* Main Content */}
<div className="flex flex-col flex-1 overflow-hidden">
{page === "dm" && dmChannelId && getParticipantDetails && (
<div className="flex flex-1 min-h-0">
<DMChannelContent userId={userId} channelId={dmChannelId} participantDetails={getParticipantDetails} />
</div>
)}
{page === "dm" && dmChannelId && !getParticipantDetails && (
<div className="flex flex-1 min-h-0">
<div className="flex items-center justify-center flex-1">
<Spinner className="size-4 animate-spin" />
<p className="text-sm text-muted-foreground">Loading...</p>
</div>
</div>
)}
{page === "server" && serverChannelId && (
<div className="p-4">
<p className="text-sm text-muted-foreground">Server channel {serverChannelId}</p>
</div>
)}
{page === "friends" && (
<FriendsPage
userId={userId}
friendsPage={friendsPage}
socketStatus={socketStatus}
emptyMessage={emptyFriendsMessage}
/>
)}
{page === "nests" && (
<div className="p-4">
<p className="text-sm text-muted-foreground">Nests</p>
</div>
)}
{page === "discover" && <DiscoverPage userNests={userNests ?? []} />}
{page === "global-nests" && <GlobalNestsPage />}
{page === "support" && <SettingsPage />}
</div>
</div>
</div>
<FriendRequestModal
open={friendModal}
onOpenChange={setFriendModal}
/>
</>
)
}
function GlobalNestsPage() {
return (
<div className="flex flex-col flex-1 overflow-hidden">
<div className="flex items-center justify-center flex-1">
<Spinner className="size-4 animate-spin" />
<p className="text-sm text-muted-foreground">Loading...</p>
</div>
</div>
)
}
function DiscoverPage({ userNests }: { userNests: Doc<"nests">[] }) {
return (
<div className="flex flex-col flex-1 overflow-hidden">
<div className="flex items-center justify-center flex-1">
<Spinner className="size-4 animate-spin" />
<p className="text-sm text-muted-foreground">Loading...</p>
</div>
</div>
)
}
function MobileServerIcon({
children,
isActive,
isHome,
isAddButton,
onClick
}: {
children: React.ReactNode
isActive?: boolean
isHome?: boolean
isAddButton?: boolean
onClick?: () => void
}) {
return (
<div className="relative flex items-center justify-center w-full group">
{/* Left pill indicator */}
<div
className={cn(
"absolute left-0 w-1 bg-foreground rounded-r-full transition-all duration-200",
isActive ? "h-9" : "h-0 group-active:h-5"
)}
/>
{/* Icon button */}
<Button
type="button"
variant="ghost"
size="icon"
onClick={onClick}
className={cn(
"relative flex items-center justify-center size-12 transition-all duration-200 overflow-hidden",
isHome && isActive
? "bg-primary text-primary-foreground rounded-2xl"
: isHome
? "bg-primary/80 text-primary-foreground rounded-[24px] active:rounded-2xl"
: isAddButton
? "bg-muted text-emerald-500 rounded-[24px] active:rounded-2xl active:bg-emerald-500 active:text-white"
: isActive
? "bg-primary text-primary-foreground rounded-2xl"
: "bg-muted text-muted-foreground rounded-[24px] active:rounded-2xl active:bg-primary active:text-primary-foreground"
)}
>
{children}
</Button>
</div>
)
}

View file

@ -1,155 +0,0 @@
"use client"
import { Button } from "@/components/ui/button"
import { MenuIcon, PhoneIcon, SearchIcon, UserIcon, UserPlusIcon, UsersIcon, VideoIcon } from "lucide-react"
import UserCard from "../user/user-card"
export interface PageHeaderProps {
currentChannel: SiPher.Channel | null
page: SiPher.PageTypes
friendsPage?: "all" | "available"
onFriendsPageChange?: (page: "all" | "available") => void
onAddFriend?: () => void
dmChannel?: {
id: string
participantDetails: {
id: string
name: string
username: string
displayUsername: string
image: string
status: "online" | "busy" | "offline" | "away"
isCurrentUser: boolean
}[]
}
serverId?: string
serverChannelId?: string
onToggleMobileChannelList?: () => void
isMobile?: boolean
}
export function PageHeader({
currentChannel,
page,
friendsPage,
onFriendsPageChange,
onAddFriend,
dmChannel,
serverId,
serverChannelId,
onToggleMobileChannelList,
isMobile,
}: PageHeaderProps) {
const otherParticipant = dmChannel && dmChannel.participantDetails.find((p) => !p.isCurrentUser)
return (
<div className="flex items-center min-h-12 md:min-h-10 max-h-12 md:max-h-10 border-b border-border/40 sticky top-0 z-10 bg-background">
{/* Mobile: Menu toggle button */}
{isMobile && (
<Button
variant="ghost"
size="icon"
className="h-10 w-10 shrink-0 ml-1"
onClick={onToggleMobileChannelList}
>
<MenuIcon className="size-5" />
</Button>
)}
{/* Desktop: SCS or DM Selector */}
<div className="hidden md:flex justify-center items-center gap-2 max-w-72 min-w-72 border-r h-10 border-border/40">
{!currentChannel || currentChannel.type === "DM" ? (
<Button
variant="outline"
className="w-[calc(100%-2rem)] h-3/4 rounded-lg hover:cursor-pointer"
>
<SearchIcon className="size-4" />
<span className="text-sm font-medium">Search for a Server or DM</span>
</Button>
) : (
<span className="text-sm font-medium">{currentChannel.name}</span>
)}
</div>
{/* Page title/options */}
{dmChannel && otherParticipant ? (
<div className="flex flex-row justify-start items-center gap-2 w-full px-2 md:px-4">
<UserCard
userName={otherParticipant.name}
image={otherParticipant.image}
status={otherParticipant.status}
size="small"
/>
<span className="text-sm font-medium truncate">{otherParticipant.name}</span>
<div className="flex flex-row gap-1 md:gap-2 ml-auto shrink-0">
<Button
variant="ghost"
size="icon"
className="h-8 w-8"
>
<PhoneIcon className="size-4" />
</Button>
<Button
variant="ghost"
size="icon"
className="h-8 w-8"
>
<VideoIcon className="size-4" />
</Button>
<Button
variant="ghost"
size="icon"
className="h-8 w-8 hidden sm:flex"
>
<UserIcon className="size-4" />
</Button>
</div>
</div>
) : serverChannelId ? (
<div className="flex flex-row justify-start items-center gap-2 w-full px-2 md:px-4">
<span className="text-sm font-medium">#{serverChannelId}</span>
</div>
) : page === "friends" ? (
<div className="flex flex-row justify-start items-center gap-1 md:gap-2 w-full overflow-x-auto">
<div className="flex flex-row gap-2 justify-start p-2 shrink-0">
<UsersIcon className="size-4" />
<span className="text-sm font-medium hidden sm:inline">Friends</span>
</div>
<span className="text-sm font-medium hidden sm:inline"></span>
<div className="flex flex-row gap-1 md:gap-2 h-full">
<Button
variant="ghost"
disabled={friendsPage === "available"}
className={`h-full hover:cursor-pointer justify-start px-2 md:p-2 text-xs md:text-sm ${friendsPage === "available" ? "bg-primary text-primary-foreground" : ""
}`}
onClick={() => onFriendsPageChange?.("available")}
>
<span className="hidden sm:inline">Available</span>
<span className="sm:hidden">Online</span>
</Button>
<Button
variant="ghost"
disabled={friendsPage === "all"}
className={`h-full hover:cursor-pointer justify-start px-2 md:p-2 text-xs md:text-sm ${friendsPage === "all" ? "bg-primary text-primary-foreground" : ""
}`}
onClick={() => onFriendsPageChange?.("all")}
>
<span className="hidden sm:inline">All Known</span>
<span className="sm:hidden">All</span>
</Button>
<Button
variant="ghost"
className="h-full bg-primary text-primary-foreground hover:cursor-pointer justify-start px-2 md:p-2 text-xs md:text-sm"
onClick={onAddFriend}
>
<UserPlusIcon className="size-4 sm:hidden" />
<span className="hidden sm:inline">Add Friend</span>
</Button>
</div>
</div>
) : null}
</div>
)
}

View file

@ -1,18 +0,0 @@
"use client"
import * as React from "react"
export interface SettingsPageProps {
// Add settings-specific props as needed
}
export function SettingsPage({}: SettingsPageProps) {
return (
<div className="flex flex-col flex-1 overflow-y-auto p-2 md:p-4">
<div className="flex items-center min-h-10 max-h-10">
<span className="text-sm font-medium">Servers</span>
</div>
</div>
)
}

View file

@ -1,17 +0,0 @@
// Get the logo SVG and return it as a React component
import logoDark from "@/assets/logo/logo-dark.svg";
import logoLight from "@/assets/logo/logo-white.svg";
import { cn } from "@/lib/utils";
import { useTheme } from "next-themes";
export default function LogoIcon(
{
className,
}: {
className?: string;
}
) {
const { theme } = useTheme();
return theme === "dark" ? <img src={logoLight.src} alt="Logo" className={cn("size-6", className)} /> : <img src={logoDark.src} alt="Logo" className={cn("size-6", className)} />;
}

View file

@ -1,276 +0,0 @@
"use client"
import * as React from "react"
import * as MenubarPrimitive from "@radix-ui/react-menubar"
import { CheckIcon, ChevronRightIcon, CircleIcon } from "lucide-react"
import { cn } from "@/lib/utils"
function Menubar({
className,
...props
}: React.ComponentProps<typeof MenubarPrimitive.Root>) {
return (
<MenubarPrimitive.Root
data-slot="menubar"
className={cn(
"bg-background flex h-9 items-center gap-1 rounded-md border p-1 shadow-xs",
className
)}
{...props}
/>
)
}
function MenubarMenu({
...props
}: React.ComponentProps<typeof MenubarPrimitive.Menu>) {
return <MenubarPrimitive.Menu data-slot="menubar-menu" {...props} />
}
function MenubarGroup({
...props
}: React.ComponentProps<typeof MenubarPrimitive.Group>) {
return <MenubarPrimitive.Group data-slot="menubar-group" {...props} />
}
function MenubarPortal({
...props
}: React.ComponentProps<typeof MenubarPrimitive.Portal>) {
return <MenubarPrimitive.Portal data-slot="menubar-portal" {...props} />
}
function MenubarRadioGroup({
...props
}: React.ComponentProps<typeof MenubarPrimitive.RadioGroup>) {
return (
<MenubarPrimitive.RadioGroup data-slot="menubar-radio-group" {...props} />
)
}
function MenubarTrigger({
className,
...props
}: React.ComponentProps<typeof MenubarPrimitive.Trigger>) {
return (
<MenubarPrimitive.Trigger
data-slot="menubar-trigger"
className={cn(
"focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground flex items-center rounded-sm px-2 py-1 text-sm font-medium outline-hidden select-none",
className
)}
{...props}
/>
)
}
function MenubarContent({
className,
align = "start",
alignOffset = -4,
sideOffset = 8,
...props
}: React.ComponentProps<typeof MenubarPrimitive.Content>) {
return (
<MenubarPortal>
<MenubarPrimitive.Content
data-slot="menubar-content"
align={align}
alignOffset={alignOffset}
sideOffset={sideOffset}
className={cn(
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 min-w-48 origin-(--radix-menubar-content-transform-origin) overflow-hidden rounded-md border p-1 shadow-md",
className
)}
{...props}
/>
</MenubarPortal>
)
}
function MenubarItem({
className,
inset,
variant = "default",
...props
}: React.ComponentProps<typeof MenubarPrimitive.Item> & {
inset?: boolean
variant?: "default" | "destructive"
}) {
return (
<MenubarPrimitive.Item
data-slot="menubar-item"
data-inset={inset}
data-variant={variant}
className={cn(
"focus:bg-accent focus:text-accent-foreground data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 dark:data-[variant=destructive]:focus:bg-destructive/20 data-[variant=destructive]:focus:text-destructive data-[variant=destructive]:*:[svg]:text-destructive! [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-disabled:pointer-events-none data-disabled:opacity-50 data-inset:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className
)}
{...props}
/>
)
}
function MenubarCheckboxItem({
className,
children,
checked,
...props
}: React.ComponentProps<typeof MenubarPrimitive.CheckboxItem>) {
return (
<MenubarPrimitive.CheckboxItem
data-slot="menubar-checkbox-item"
className={cn(
"focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-xs py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className
)}
checked={checked}
{...props}
>
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
<MenubarPrimitive.ItemIndicator>
<CheckIcon className="size-4" />
</MenubarPrimitive.ItemIndicator>
</span>
{children}
</MenubarPrimitive.CheckboxItem>
)
}
function MenubarRadioItem({
className,
children,
...props
}: React.ComponentProps<typeof MenubarPrimitive.RadioItem>) {
return (
<MenubarPrimitive.RadioItem
data-slot="menubar-radio-item"
className={cn(
"focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-xs py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className
)}
{...props}
>
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
<MenubarPrimitive.ItemIndicator>
<CircleIcon className="size-2 fill-current" />
</MenubarPrimitive.ItemIndicator>
</span>
{children}
</MenubarPrimitive.RadioItem>
)
}
function MenubarLabel({
className,
inset,
...props
}: React.ComponentProps<typeof MenubarPrimitive.Label> & {
inset?: boolean
}) {
return (
<MenubarPrimitive.Label
data-slot="menubar-label"
data-inset={inset}
className={cn(
"px-2 py-1.5 text-sm font-medium data-inset:pl-8",
className
)}
{...props}
/>
)
}
function MenubarSeparator({
className,
...props
}: React.ComponentProps<typeof MenubarPrimitive.Separator>) {
return (
<MenubarPrimitive.Separator
data-slot="menubar-separator"
className={cn("bg-border -mx-1 my-1 h-px", className)}
{...props}
/>
)
}
function MenubarShortcut({
className,
...props
}: React.ComponentProps<"span">) {
return (
<span
data-slot="menubar-shortcut"
className={cn(
"text-muted-foreground ml-auto text-xs tracking-widest",
className
)}
{...props}
/>
)
}
function MenubarSub({
...props
}: React.ComponentProps<typeof MenubarPrimitive.Sub>) {
return <MenubarPrimitive.Sub data-slot="menubar-sub" {...props} />
}
function MenubarSubTrigger({
className,
inset,
children,
...props
}: React.ComponentProps<typeof MenubarPrimitive.SubTrigger> & {
inset?: boolean
}) {
return (
<MenubarPrimitive.SubTrigger
data-slot="menubar-sub-trigger"
data-inset={inset}
className={cn(
"focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground flex cursor-default items-center rounded-sm px-2 py-1.5 text-sm outline-none select-none data-inset:pl-8",
className
)}
{...props}
>
{children}
<ChevronRightIcon className="ml-auto h-4 w-4" />
</MenubarPrimitive.SubTrigger>
)
}
function MenubarSubContent({
className,
...props
}: React.ComponentProps<typeof MenubarPrimitive.SubContent>) {
return (
<MenubarPrimitive.SubContent
data-slot="menubar-sub-content"
className={cn(
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 min-w-32 origin-(--radix-menubar-content-transform-origin) overflow-hidden rounded-md border p-1 shadow-lg",
className
)}
{...props}
/>
)
}
export {
Menubar,
MenubarPortal,
MenubarMenu,
MenubarTrigger,
MenubarContent,
MenubarGroup,
MenubarSeparator,
MenubarLabel,
MenubarItem,
MenubarShortcut,
MenubarCheckboxItem,
MenubarRadioGroup,
MenubarRadioItem,
MenubarSub,
MenubarSubTrigger,
MenubarSubContent,
}

View file

@ -1,48 +0,0 @@
"use client"
import * as React from "react"
import * as PopoverPrimitive from "@radix-ui/react-popover"
import { cn } from "@/lib/utils"
function Popover({
...props
}: React.ComponentProps<typeof PopoverPrimitive.Root>) {
return <PopoverPrimitive.Root data-slot="popover" {...props} />
}
function PopoverTrigger({
...props
}: React.ComponentProps<typeof PopoverPrimitive.Trigger>) {
return <PopoverPrimitive.Trigger data-slot="popover-trigger" {...props} />
}
function PopoverContent({
className,
align = "center",
sideOffset = 4,
...props
}: React.ComponentProps<typeof PopoverPrimitive.Content>) {
return (
<PopoverPrimitive.Portal>
<PopoverPrimitive.Content
data-slot="popover-content"
align={align}
sideOffset={sideOffset}
className={cn(
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-72 origin-(--radix-popover-content-transform-origin) rounded-md border p-4 shadow-md outline-hidden",
className
)}
{...props}
/>
</PopoverPrimitive.Portal>
)
}
function PopoverAnchor({
...props
}: React.ComponentProps<typeof PopoverPrimitive.Anchor>) {
return <PopoverPrimitive.Anchor data-slot="popover-anchor" {...props} />
}
export { Popover, PopoverTrigger, PopoverContent, PopoverAnchor }

View file

@ -1,31 +0,0 @@
"use client"
import * as React from "react"
import * as ProgressPrimitive from "@radix-ui/react-progress"
import { cn } from "@/lib/utils"
function Progress({
className,
value,
...props
}: React.ComponentProps<typeof ProgressPrimitive.Root>) {
return (
<ProgressPrimitive.Root
data-slot="progress"
className={cn(
"bg-primary/20 relative h-2 w-full overflow-hidden rounded-full",
className
)}
{...props}
>
<ProgressPrimitive.Indicator
data-slot="progress-indicator"
className="bg-primary h-full w-full flex-1 transition-all"
style={{ transform: `translateX(-${100 - (value || 0)}%)` }}
/>
</ProgressPrimitive.Root>
)
}
export { Progress }

View file

@ -1,58 +0,0 @@
"use client"
import * as ScrollAreaPrimitive from "@radix-ui/react-scroll-area"
import * as React from "react"
import { cn } from "@/lib/utils"
function ScrollArea({
className,
children,
...props
}: React.ComponentProps<typeof ScrollAreaPrimitive.Root>) {
return (
<ScrollAreaPrimitive.Root
data-slot="scroll-area"
className={cn("relative overflow-hidden", className)}
{...props}
>
<ScrollAreaPrimitive.Viewport
data-slot="scroll-area-viewport"
className="size-full rounded-[inherit] [&>div]:block!"
>
{children}
</ScrollAreaPrimitive.Viewport>
<ScrollBar />
<ScrollAreaPrimitive.Corner />
</ScrollAreaPrimitive.Root>
)
}
function ScrollBar({
className,
orientation = "vertical",
...props
}: React.ComponentProps<typeof ScrollAreaPrimitive.ScrollAreaScrollbar>) {
return (
<ScrollAreaPrimitive.ScrollAreaScrollbar
data-slot="scroll-area-scrollbar"
orientation={orientation}
className={cn(
"flex touch-none p-px transition-colors select-none",
orientation === "vertical" &&
"h-full w-2.5 border-l border-l-transparent",
orientation === "horizontal" &&
"h-2.5 flex-col border-t border-t-transparent",
className
)}
{...props}
>
<ScrollAreaPrimitive.ScrollAreaThumb
data-slot="scroll-area-thumb"
className="bg-border relative flex-1 rounded-full"
/>
</ScrollAreaPrimitive.ScrollAreaScrollbar>
)
}
export { ScrollArea, ScrollBar }

View file

@ -1,28 +0,0 @@
"use client"
import * as React from "react"
import * as SeparatorPrimitive from "@radix-ui/react-separator"
import { cn } from "@/lib/utils"
function Separator({
className,
orientation = "horizontal",
decorative = true,
...props
}: React.ComponentProps<typeof SeparatorPrimitive.Root>) {
return (
<SeparatorPrimitive.Root
data-slot="separator"
decorative={decorative}
orientation={orientation}
className={cn(
"bg-border shrink-0 data-[orientation=horizontal]:h-px data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-px",
className
)}
{...props}
/>
)
}
export { Separator }

Some files were not shown because too many files have changed in this diff Show more