Merge branch 'dev'

This commit is contained in:
Daniel 2023-06-29 05:33:17 +03:30
commit 75e75b2db6
119 changed files with 12471 additions and 0 deletions

4
.env.sample Normal file
View File

@ -0,0 +1,4 @@
NEXTAUTH_SECRET=very_sensitive_secret2
DATABASE_URL=postgresql://user:password@localhost:5432/linkwarden
NEXTAUTH_URL=http://localhost:3000
PAGINATION_TAKE_COUNT=20

6
.eslintrc.json Normal file
View File

@ -0,0 +1,6 @@
{
"extends": "next/core-web-vitals",
"rules": {
"react-hooks/exhaustive-deps": "off"
}
}

17
.github/CONTRIBUTING.md vendored Normal file
View File

@ -0,0 +1,17 @@
# How to contribute
> **For questions/help, feature requests and bug reports please create an [issue](https://github.com/Daniel31x13/link-warden/issues) (please use the right lable).**
First off, I'm really glad you're reading this and thank you for taking the time to contribute!
1. Confirm your planned implementation fit into our project [features](https://github.com/Daniel31x13/link-warden#features) and [project roadmap](https://github.com/Daniel31x13/link-warden/wiki#project-roadmap) (wether it's adding a new feature or improving our existing code).
2. Open an [issue](https://github.com/Daniel31x13/link-warden/issues/new?assignees=&labels=contribution&template=contribution.md&title=Contribution) with your planned implementation to discuss.
3. Check in with me before starting development to make sure your work wont conflict with or duplicate existing work (by doing step 2).
4. Commit, push, and submit a PR and wait for review feedback.
5. Have patience, don't abandon your PR! We love contributors but we don't always have time to respond to notifications instantly. If you want a faster response, DM me on [Twitter](https://twitter.com/daniel31x13).
Thanks again! <3

38
.gitignore vendored Normal file
View File

@ -0,0 +1,38 @@
# dependencies
/node_modules
/.pnp
.pnp.js
# testing
/coverage
# next.js
/.next/
/out/
# production
/build
# misc
.DS_Store
*.pem
# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*
.pnpm-debug.log*
# env files
.env*.local
.env
# vercel
.vercel
# typescript
*.tsbuildinfo
next-env.d.ts
# generated files and folders
/data

661
LICENSE Normal file
View File

@ -0,0 +1,661 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<https://www.gnu.org/licenses/>.

3
README.md Normal file
View File

@ -0,0 +1,3 @@
# Linkwarden
Rebuilding things from ground up...

38
SAMPLE.README.md Normal file
View File

@ -0,0 +1,38 @@
This is a [Next.js](https://nextjs.org/) project bootstrapped with [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app).
## Getting Started
First, run the development server:
```bash
npm run dev
# or
yarn dev
# or
pnpm dev
```
Open [http://localhost:3000](http://localhost:3000) with your browser to see the result.
You can start editing the page by modifying `pages/index.tsx`. The page auto-updates as you edit the file.
[API routes](https://nextjs.org/docs/api-routes/introduction) can be accessed on [http://localhost:3000/api/hello](http://localhost:3000/api/hello). This endpoint can be edited in `pages/api/hello.ts`.
The `pages/api` directory is mapped to `/api/*`. Files in this directory are treated as [API routes](https://nextjs.org/docs/api-routes/introduction) instead of React pages.
This project uses [`next/font`](https://nextjs.org/docs/basic-features/font-optimization) to automatically optimize and load Inter, a custom Google Font.
## Learn More
To learn more about Next.js, take a look at the following resources:
- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API.
- [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial.
You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js/) - your feedback and contributions are welcome!
## Deploy on Vercel
The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js.
Check out our [Next.js deployment documentation](https://nextjs.org/docs/deployment) for more details.

34
components/Checkbox.tsx Normal file
View File

@ -0,0 +1,34 @@
import { faSquare, faSquareCheck } from "@fortawesome/free-regular-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { ChangeEventHandler } from "react";
type Props = {
label: string;
state: boolean;
className?: string;
onClick: ChangeEventHandler<HTMLInputElement>;
};
export default function Checkbox({ label, state, className, onClick }: Props) {
return (
<label
className={`cursor-pointer flex items-center gap-2 text-sky-500 ${className}`}
>
<input
type="checkbox"
checked={state}
onChange={onClick}
className="peer sr-only"
/>
<FontAwesomeIcon
icon={faSquareCheck}
className="w-5 h-5 text-sky-500 peer-checked:block hidden"
/>
<FontAwesomeIcon
icon={faSquare}
className="w-5 h-5 text-sky-500 peer-checked:hidden block"
/>
<span className="text-sky-900 rounded select-none">{label}</span>
</label>
);
}

View File

@ -0,0 +1,42 @@
import React, { useRef, useEffect, ReactNode, RefObject } from "react";
type Props = {
children: ReactNode;
onClickOutside: Function;
className?: string;
};
function useOutsideAlerter(
ref: RefObject<HTMLElement>,
onClickOutside: Function
) {
useEffect(() => {
function handleClickOutside(event: Event) {
if (
ref.current &&
!ref.current.contains(event.target as HTMLInputElement)
) {
onClickOutside(event);
}
}
document.addEventListener("mousedown", handleClickOutside);
return () => {
document.removeEventListener("mousedown", handleClickOutside);
};
}, [ref, onClickOutside]);
}
export default function ClickAwayHandler({
children,
onClickOutside,
className,
}: Props) {
const wrapperRef = useRef(null);
useOutsideAlerter(wrapperRef, onClickOutside);
return (
<div ref={wrapperRef} className={className}>
{children}
</div>
);
}

View File

@ -0,0 +1,149 @@
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faEllipsis, faLink } from "@fortawesome/free-solid-svg-icons";
import Link from "next/link";
import { CollectionIncludingMembersAndLinkCount } from "@/types/global";
import Dropdown from "./Dropdown";
import { useState } from "react";
import ProfilePhoto from "./ProfilePhoto";
import { faCalendarDays } from "@fortawesome/free-regular-svg-icons";
import useModalStore from "@/store/modals";
import usePermissions from "@/hooks/usePermissions";
type Props = {
collection: CollectionIncludingMembersAndLinkCount;
className?: string;
};
export default function CollectionCard({ collection, className }: Props) {
const { setModal } = useModalStore();
const formattedDate = new Date(collection.createdAt as string).toLocaleString(
"en-US",
{
year: "numeric",
month: "short",
day: "numeric",
}
);
const [expandDropdown, setExpandDropdown] = useState(false);
const permissions = usePermissions(collection.id as number);
return (
<div
className={`bg-gradient-to-tr from-sky-100 from-10% via-gray-100 via-20% to-white to-100% self-stretch min-h-[12rem] rounded-2xl shadow duration-100 hover:shadow-none group relative ${className}`}
>
<div
onClick={() => setExpandDropdown(!expandDropdown)}
id={"expand-dropdown" + collection.id}
className="inline-flex absolute top-5 right-5 rounded-md cursor-pointer hover:bg-slate-200 duration-100 p-1"
>
<FontAwesomeIcon
icon={faEllipsis}
id={"expand-dropdown" + collection.id}
className="w-5 h-5 text-gray-500"
/>
</div>
<Link
href={`/collections/${collection.id}`}
className="flex flex-col gap-2 justify-between min-h-[12rem] h-full select-none p-5"
>
<p className="text-2xl font-bold capitalize text-sky-500 break-words line-clamp-3 w-4/5">
{collection.name}
</p>
<div className="flex justify-between items-center">
<div className="text-sky-400 flex items-center w-full">
{collection.members
.sort((a, b) => (a.userId as number) - (b.userId as number))
.map((e, i) => {
return (
<ProfilePhoto
key={i}
src={`/api/avatar/${e.userId}`}
className="-mr-3 border-[3px]"
/>
);
})
.slice(0, 4)}
{collection.members.length - 4 > 0 ? (
<div className="h-10 w-10 text-white flex items-center justify-center rounded-full border-[3px] bg-sky-500 border-sky-100 -mr-3">
+{collection.members.length - 4}
</div>
) : null}
</div>
<div className="text-right w-40">
<div className="text-sky-500 font-bold text-sm flex justify-end gap-1 items-center">
<FontAwesomeIcon icon={faLink} className="w-5 h-5 text-sky-600" />
{collection._count && collection._count.links}
</div>
<div className="flex items-center justify-end gap-1 text-gray-600">
<FontAwesomeIcon icon={faCalendarDays} className="w-4 h-4" />
<p className="font-bold text-xs">{formattedDate}</p>
</div>
</div>
</div>
</Link>
{expandDropdown ? (
<Dropdown
items={[
permissions === true
? {
name: "Edit Collection Info",
onClick: () => {
collection &&
setModal({
modal: "COLLECTION",
state: true,
method: "UPDATE",
isOwner: permissions === true,
active: collection,
});
setExpandDropdown(false);
},
}
: undefined,
{
name: permissions === true ? "Share/Collaborate" : "View Team",
onClick: () => {
collection &&
setModal({
modal: "COLLECTION",
state: true,
method: "UPDATE",
isOwner: permissions === true,
active: collection,
defaultIndex: permissions === true ? 1 : 0,
});
setExpandDropdown(false);
},
},
{
name:
permissions === true ? "Delete Collection" : "Leave Collection",
onClick: () => {
collection &&
setModal({
modal: "COLLECTION",
state: true,
method: "UPDATE",
isOwner: permissions === true,
active: collection,
defaultIndex: permissions === true ? 2 : 1,
});
setExpandDropdown(false);
},
},
]}
onClickOutside={(e: Event) => {
const target = e.target as HTMLInputElement;
if (target.id !== "expand-dropdown" + collection.id)
setExpandDropdown(false);
}}
className="absolute top-[3.2rem] right-5 z-10"
/>
) : null}
</div>
);
}

53
components/Dropdown.tsx Normal file
View File

@ -0,0 +1,53 @@
import Link from "next/link";
import React, { MouseEventHandler } from "react";
import ClickAwayHandler from "./ClickAwayHandler";
type MenuItem =
| {
name: string;
onClick: MouseEventHandler;
href?: string;
}
| {
name: string;
onClick?: MouseEventHandler;
href: string;
}
| undefined;
type Props = {
onClickOutside: Function;
className?: string;
items: MenuItem[];
};
export default function Dropdown({ onClickOutside, className, items }: Props) {
return (
<ClickAwayHandler
onClickOutside={onClickOutside}
className={`${className} py-1 shadow-md border border-sky-100 bg-gray-50 rounded-md flex flex-col z-20`}
>
{items.map((e, i) => {
const inner = e && (
<div className="cursor-pointer rounded-md">
<div className="flex items-center gap-2 py-1 px-2 hover:bg-slate-200 duration-100">
<p className="text-sky-900 select-none">{e.name}</p>
</div>
</div>
);
return e && e.href ? (
<Link key={i} href={e.href}>
{inner}
</Link>
) : (
e && (
<div key={i} onClick={e.onClick}>
{inner}
</div>
)
);
})}
</ClickAwayHandler>
);
}

View File

@ -0,0 +1,76 @@
import React, { SetStateAction } from "react";
import ClickAwayHandler from "./ClickAwayHandler";
import Checkbox from "./Checkbox";
type Props = {
setFilterDropdown: (value: SetStateAction<boolean>) => void;
setSearchFilter: Function;
searchFilter: {
name: boolean;
url: boolean;
description: boolean;
collection: boolean;
tags: boolean;
};
};
export default function FilterSearchDropdown({
setFilterDropdown,
setSearchFilter,
searchFilter,
}: Props) {
return (
<ClickAwayHandler
onClickOutside={(e: Event) => {
const target = e.target as HTMLInputElement;
if (target.id !== "filter-dropdown") setFilterDropdown(false);
}}
className="absolute top-8 right-0 border border-sky-100 shadow-md bg-gray-50 rounded-md p-2 z-20 w-40"
>
<p className="mb-2 text-sky-900 text-center font-semibold">Filter by</p>
<div className="flex flex-col gap-2">
<Checkbox
label="Name"
state={searchFilter.name}
onClick={() =>
setSearchFilter({ ...searchFilter, name: !searchFilter.name })
}
/>
<Checkbox
label="Link"
state={searchFilter.url}
onClick={() =>
setSearchFilter({ ...searchFilter, url: !searchFilter.url })
}
/>
<Checkbox
label="Description"
state={searchFilter.description}
onClick={() =>
setSearchFilter({
...searchFilter,
description: !searchFilter.description,
})
}
/>
<Checkbox
label="Collection"
state={searchFilter.collection}
onClick={() =>
setSearchFilter({
...searchFilter,
collection: !searchFilter.collection,
})
}
/>
<Checkbox
label="Tags"
state={searchFilter.tags}
onClick={() =>
setSearchFilter({ ...searchFilter, tags: !searchFilter.tags })
}
/>
</div>
</ClickAwayHandler>
);
}

View File

@ -0,0 +1,55 @@
import useCollectionStore from "@/store/collections";
import { useRouter } from "next/router";
import { useEffect, useState } from "react";
import Select from "react-select";
import { styles } from "./styles";
import { Options } from "./types";
type Props = {
onChange: any;
defaultValue:
| {
label: string;
value?: number;
}
| undefined;
};
export default function CollectionSelection({ onChange, defaultValue }: Props) {
const { collections } = useCollectionStore();
const router = useRouter();
const [options, setOptions] = useState<Options[]>([]);
const collectionId = Number(router.query.id);
const activeCollection = collections.find((e) => {
return e.id === collectionId;
});
if (activeCollection && !defaultValue) {
defaultValue = {
value: activeCollection?.id,
label: activeCollection?.name,
};
}
useEffect(() => {
const formatedCollections = collections.map((e) => {
return { value: e.id, label: e.name, ownerId: e.ownerId };
});
setOptions(formatedCollections);
}, [collections]);
return (
<Select
isClearable
onChange={onChange}
options={options}
styles={styles}
defaultValue={defaultValue}
// menuPosition="fixed"
/>
);
}

View File

@ -0,0 +1,39 @@
import useTagStore from "@/store/tags";
import { useEffect, useState } from "react";
import CreatableSelect from "react-select/creatable";
import { styles } from "./styles";
import { Options } from "./types";
type Props = {
onChange: any;
defaultValue?: {
value: number;
label: string;
}[];
};
export default function TagSelection({ onChange, defaultValue }: Props) {
const { tags } = useTagStore();
const [options, setOptions] = useState<Options[]>([]);
useEffect(() => {
const formatedCollections = tags.map((e) => {
return { value: e.id, label: e.name };
});
setOptions(formatedCollections);
}, [tags]);
return (
<CreatableSelect
isClearable
onChange={onChange}
options={options}
styles={styles}
defaultValue={defaultValue}
// menuPosition="fixed"
isMulti
/>
);
}

View File

@ -0,0 +1,65 @@
import { StylesConfig } from "react-select";
const font =
"ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, Segoe UI, Roboto, Helvetica Neue, Arial, Noto Sans, sans-serif, Apple Color Emoji, Segoe UI Emoji, Segoe UI Symbol, Noto Color Emoji";
export const styles: StylesConfig = {
option: (styles, state) => ({
...styles,
fontFamily: font,
cursor: "pointer",
backgroundColor: state.isSelected ? "#0ea5e9" : "inherit",
"&:hover": {
backgroundColor: state.isSelected ? "#0ea5e9" : "#e2e8f0",
},
transition: "all 50ms",
}),
control: (styles) => ({
...styles,
fontFamily: font,
border: "none",
}),
container: (styles) => ({
...styles,
border: "1px solid #e0f2fe",
borderRadius: "0.375rem",
lineHeight: "1.25rem",
// "@media screen and (min-width: 1024px)": {
// fontSize: "0.875rem",
// },
}),
input: (styles) => ({
...styles,
cursor: "text",
}),
dropdownIndicator: (styles) => ({
...styles,
cursor: "pointer",
}),
clearIndicator: (styles) => ({
...styles,
visibility: "hidden",
}),
placeholder: (styles) => ({
...styles,
borderColor: "black",
}),
multiValue: (styles) => {
return {
...styles,
backgroundColor: "#0ea5e9",
color: "white",
};
},
multiValueLabel: (styles) => ({
...styles,
color: "white",
}),
multiValueRemove: (styles) => ({
...styles,
":hover": {
color: "white",
backgroundColor: "#38bdf8",
},
}),
};

View File

@ -0,0 +1,4 @@
export interface Options {
label: string;
value?: string | number;
}

215
components/LinkCard.tsx Normal file
View File

@ -0,0 +1,215 @@
import {
CollectionIncludingMembersAndLinkCount,
LinkIncludingShortenedCollectionAndTags,
} from "@/types/global";
import { faFolder, faEllipsis } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { useEffect, useState } from "react";
import Image from "next/image";
import Dropdown from "./Dropdown";
import useLinkStore from "@/store/links";
import useCollectionStore from "@/store/collections";
import useAccountStore from "@/store/account";
import useModalStore from "@/store/modals";
import { faCalendarDays } from "@fortawesome/free-regular-svg-icons";
import usePermissions from "@/hooks/usePermissions";
import { toast } from "react-hot-toast";
import isValidUrl from "@/lib/client/isValidUrl";
type Props = {
link: LinkIncludingShortenedCollectionAndTags;
count: number;
className?: string;
};
export default function LinkCard({ link, count, className }: Props) {
const { setModal } = useModalStore();
const permissions = usePermissions(link.collection.id as number);
const [expandDropdown, setExpandDropdown] = useState(false);
const { collections } = useCollectionStore();
const { account } = useAccountStore();
const [collection, setCollection] =
useState<CollectionIncludingMembersAndLinkCount>(
collections.find(
(e) => e.id === link.collection.id
) as CollectionIncludingMembersAndLinkCount
);
useEffect(() => {
setCollection(
collections.find(
(e) => e.id === link.collection.id
) as CollectionIncludingMembersAndLinkCount
);
}, [collections]);
const { removeLink, updateLink } = useLinkStore();
const pinLink = async () => {
const isAlreadyPinned = link?.pinnedBy && link.pinnedBy[0];
const load = toast.loading("Applying...");
setExpandDropdown(false);
const response = await updateLink({
...link,
pinnedBy: isAlreadyPinned ? undefined : [{ id: account.id }],
});
toast.dismiss(load);
response.ok &&
toast.success(`Link ${isAlreadyPinned ? "Unpinned!" : "Pinned!"}`);
};
const deleteLink = async () => {
const load = toast.loading("Deleting...");
const response = await removeLink(link);
toast.dismiss(load);
response.ok && toast.success(`Link Deleted.`);
setExpandDropdown(false);
};
const url = isValidUrl(link.url) ? new URL(link.url) : undefined;
const formattedDate = new Date(link.createdAt as string).toLocaleString(
"en-US",
{
year: "numeric",
month: "short",
day: "numeric",
}
);
return (
<div
className={`bg-gradient-to-tr from-slate-200 from-10% to-gray-50 via-20% shadow hover:shadow-none cursor-pointer duration-100 rounded-2xl relative group ${className}`}
>
{(permissions === true ||
permissions?.canUpdate ||
permissions?.canDelete) && (
<div
onClick={() => setExpandDropdown(!expandDropdown)}
id={"expand-dropdown" + link.id}
className="text-gray-500 inline-flex rounded-md cursor-pointer hover:bg-slate-200 absolute right-5 top-5 z-10 duration-100 p-1"
>
<FontAwesomeIcon
icon={faEllipsis}
title="More"
className="w-5 h-5"
id={"expand-dropdown" + link.id}
/>
</div>
)}
<div
onClick={() => {
setModal({
modal: "LINK",
state: true,
method: "UPDATE",
isOwnerOrMod:
permissions === true || (permissions?.canUpdate as boolean),
active: link,
});
}}
className="flex items-start gap-5 sm:gap-10 h-full w-full p-5"
>
{url && (
<Image
src={`https://t2.gstatic.com/faviconV2?client=SOCIAL&type=FAVICON&fallback_opts=TYPE,SIZE,URL&url=${url.origin}&size=32`}
width={64}
height={64}
alt=""
className="blur-sm absolute w-16 group-hover:opacity-80 duration-100 rounded-md bottom-5 right-5 opacity-60 select-none"
draggable="false"
onError={(e) => {
const target = e.target as HTMLElement;
target.style.display = "none";
}}
/>
)}
<div className="flex justify-between gap-5 w-full h-full z-0">
<div className="flex flex-col justify-between w-full">
<div className="flex items-baseline gap-1">
<p className="text-sm text-sky-400 font-bold">{count + 1}.</p>
<p className="text-lg text-sky-500 font-bold truncate max-w-[10rem] capitalize">
{link.name}
</p>
</div>
<div className="flex gap-3 items-center flex-wrap my-3">
<div className="flex items-center gap-1">
<FontAwesomeIcon
icon={faFolder}
className="w-4 h-4 mt-1 drop-shadow"
style={{ color: collection?.color }}
/>
<p className="text-sky-900 truncate max-w-[10rem] capitalize">
{collection?.name}
</p>
</div>
</div>
<div className="flex items-center gap-1 text-gray-500">
<FontAwesomeIcon icon={faCalendarDays} className="w-4 h-4" />
<p>{formattedDate}</p>
</div>
</div>
</div>
</div>
{expandDropdown ? (
<Dropdown
items={[
permissions === true
? {
name:
link?.pinnedBy && link.pinnedBy[0]
? "Unpin"
: "Pin to Dashboard",
onClick: pinLink,
}
: undefined,
permissions === true || permissions?.canUpdate
? {
name: "Edit",
onClick: () => {
setModal({
modal: "LINK",
state: true,
method: "UPDATE",
isOwnerOrMod:
permissions === true || permissions?.canUpdate,
active: link,
defaultIndex: 1,
});
setExpandDropdown(false);
},
}
: undefined,
permissions === true || permissions?.canDelete
? {
name: "Delete",
onClick: deleteLink,
}
: undefined,
]}
onClickOutside={(e: Event) => {
const target = e.target as HTMLInputElement;
if (target.id !== "expand-dropdown" + link.id)
setExpandDropdown(false);
}}
className="absolute top-12 right-5 w-36"
/>
) : null}
</div>
);
}

7
components/Loader.tsx Normal file
View File

@ -0,0 +1,7 @@
export default function Loading() {
return (
<div>
<p>Loading...</p>
</div>
);
}

View File

@ -0,0 +1,128 @@
import { Dispatch, SetStateAction, useState } from "react";
import {
faFolder,
faPenToSquare,
faPlus,
} from "@fortawesome/free-solid-svg-icons";
import useCollectionStore from "@/store/collections";
import { CollectionIncludingMembersAndLinkCount } from "@/types/global";
import RequiredBadge from "../../RequiredBadge";
import SubmitButton from "@/components/SubmitButton";
import { HexColorPicker } from "react-colorful";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { toast } from "react-hot-toast";
type Props = {
toggleCollectionModal: Function;
setCollection: Dispatch<
SetStateAction<CollectionIncludingMembersAndLinkCount>
>;
collection: CollectionIncludingMembersAndLinkCount;
method: "CREATE" | "UPDATE";
};
export default function CollectionInfo({
toggleCollectionModal,
setCollection,
collection,
method,
}: Props) {
const [submitLoader, setSubmitLoader] = useState(false);
const { updateCollection, addCollection } = useCollectionStore();
const submit = async () => {
if (!collection) return null;
setSubmitLoader(true);
const load = toast.loading(
method === "UPDATE" ? "Applying..." : "Creating..."
);
let response;
if (method === "CREATE") response = await addCollection(collection);
else response = await updateCollection(collection);
toast.dismiss(load);
if (response.ok) {
toast.success(
`Collection ${method === "UPDATE" ? "Saved!" : "Created!"}`
);
toggleCollectionModal();
} else toast.error(response.data as string);
setSubmitLoader(false);
};
return (
<div className="flex flex-col gap-3 sm:w-[35rem] w-80">
<div className="flex flex-col sm:flex-row gap-3">
<div className="w-full">
<p className="text-sm text-sky-500 mb-2">
Name
<RequiredBadge />
</p>
<div className="flex flex-col gap-3">
<input
value={collection.name}
onChange={(e) =>
setCollection({ ...collection, name: e.target.value })
}
type="text"
placeholder="e.g. Example Collection"
className="w-full rounded-md p-3 border-sky-100 border-solid border outline-none focus:border-sky-500 duration-100"
/>
<div className="color-picker flex justify-between">
<div className="flex flex-col justify-between items-center w-32">
<p className="text-sm w-full text-sky-500 mb-2">Icon Color</p>
<div style={{ color: collection.color }}>
<FontAwesomeIcon
icon={faFolder}
className="w-12 h-12 drop-shadow"
/>
</div>
<div
className="py-1 px-2 rounded-md text-xs font-semibold cursor-pointer text-sky-500 hover:bg-slate-200 duration-100"
onClick={() =>
setCollection({ ...collection, color: "#0ea5e9" })
}
>
Reset
</div>
</div>
<HexColorPicker
color={collection.color}
onChange={(e) => setCollection({ ...collection, color: e })}
/>
</div>
</div>
</div>
<div className="w-full">
<p className="text-sm text-sky-500 mb-2">Description</p>
<textarea
className="w-full h-[11.4rem] resize-none border rounded-md duration-100 bg-white p-3 outline-none border-sky-100 focus:border-sky-500"
placeholder="The purpose of this Collection..."
value={collection.description}
onChange={(e) =>
setCollection({
...collection,
description: e.target.value,
})
}
/>
</div>
</div>
<SubmitButton
onClick={submit}
loading={submitLoader}
label={method === "CREATE" ? "Add" : "Save"}
icon={method === "CREATE" ? faPlus : faPenToSquare}
className="mx-auto mt-2"
/>
</div>
);
}

View File

@ -0,0 +1,124 @@
import React, { useState } from "react";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import {
faRightFromBracket,
faTrashCan,
} from "@fortawesome/free-solid-svg-icons";
import { CollectionIncludingMembersAndLinkCount } from "@/types/global";
import useCollectionStore from "@/store/collections";
import { useRouter } from "next/router";
import usePermissions from "@/hooks/usePermissions";
import { toast } from "react-hot-toast";
type Props = {
toggleDeleteCollectionModal: Function;
collection: CollectionIncludingMembersAndLinkCount;
};
export default function DeleteCollection({
toggleDeleteCollectionModal,
collection,
}: Props) {
const [inputField, setInputField] = useState("");
const { removeCollection } = useCollectionStore();
const router = useRouter();
const submit = async () => {
if (permissions === true) if (collection.name !== inputField) return null;
const load = toast.loading("Deleting...");
const response = await removeCollection(collection.id as number);
toast.dismiss(load);
if (response.ok) {
toast.success("Collection Deleted.");
toggleDeleteCollectionModal();
router.push("/collections");
}
};
const permissions = usePermissions(collection.id as number);
return (
<div className="flex flex-col gap-3 justify-between sm:w-[35rem] w-80">
{permissions === true ? (
<>
<p className="text-red-500 font-bold text-center">Warning!</p>
<div className="max-h-[20rem] overflow-y-auto">
<div className="text-gray-500">
<p>
Please note that deleting the collection will permanently remove
all its contents, including the following:
</p>
<div className="p-3">
<li className="list-inside">
Links: All links within the collection will be permanently
deleted.
</li>
<li className="list-inside">
Tags: All tags associated with the collection will be removed.
</li>
<li className="list-inside">
Screenshots/PDFs: Any screenshots or PDFs attached to links
within this collection will be permanently deleted.
</li>
<li className="list-inside">
Members: Any members who have been granted access to the
collection will lose their permissions and no longer be able
to view or interact with the content.
</li>
</div>
<p>
Please double-check that you have backed up any essential data
and have informed the relevant members about this action.
</p>
</div>
</div>
<div className="flex flex-col gap-3">
<p className="text-sky-900 select-none text-center">
To confirm, type &quot;
<span className="font-bold text-sky-500">{collection.name}</span>
&quot; in the box below:
</p>
<input
autoFocus
value={inputField}
onChange={(e) => setInputField(e.target.value)}
type="text"
placeholder={`Type "${collection.name}" Here.`}
className="w-72 sm:w-96 rounded-md p-3 mx-auto border-sky-100 border-solid border outline-none focus:border-sky-500 duration-100"
/>
</div>
</>
) : (
<p className="text-gray-500">
Click the button below to leave the current collection:
</p>
)}
<div
className={`mx-auto mt-2 text-white flex items-center gap-2 py-2 px-5 rounded-md select-none font-bold duration-100 ${
permissions === true
? inputField === collection.name
? "bg-red-500 hover:bg-red-400 cursor-pointer"
: "cursor-not-allowed bg-red-300"
: "bg-red-500 hover:bg-red-400 cursor-pointer"
}`}
onClick={submit}
>
<FontAwesomeIcon
icon={permissions === true ? faTrashCan : faRightFromBracket}
className="h-5"
/>
{permissions === true ? "Delete" : "Leave"} Collection
</div>
</div>
);
}

View File

@ -0,0 +1,405 @@
import { Dispatch, SetStateAction, useState } from "react";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import {
faClose,
faPenToSquare,
faPlus,
faUserPlus,
} from "@fortawesome/free-solid-svg-icons";
import useCollectionStore from "@/store/collections";
import { CollectionIncludingMembersAndLinkCount, Member } from "@/types/global";
import { useSession } from "next-auth/react";
import addMemberToCollection from "@/lib/client/addMemberToCollection";
import Checkbox from "../../Checkbox";
import SubmitButton from "@/components/SubmitButton";
import ProfilePhoto from "@/components/ProfilePhoto";
import usePermissions from "@/hooks/usePermissions";
import { toast } from "react-hot-toast";
type Props = {
toggleCollectionModal: Function;
setCollection: Dispatch<
SetStateAction<CollectionIncludingMembersAndLinkCount>
>;
collection: CollectionIncludingMembersAndLinkCount;
method: "CREATE" | "UPDATE";
};
export default function TeamManagement({
toggleCollectionModal,
setCollection,
collection,
method,
}: Props) {
const permissions = usePermissions(collection.id as number);
const currentURL = new URL(document.URL);
const publicCollectionURL = `${currentURL.origin}/public/collections/${collection.id}`;
const [member, setMember] = useState<Member>({
canCreate: false,
canUpdate: false,
canDelete: false,
user: {
name: "",
email: "",
},
});
const { addCollection, updateCollection } = useCollectionStore();
const session = useSession();
const setMemberState = (newMember: Member) => {
if (!collection) return null;
setCollection({
...collection,
members: [...collection.members, newMember],
});
setMember({
canCreate: false,
canUpdate: false,
canDelete: false,
user: {
name: "",
email: "",
},
});
};
const [submitLoader, setSubmitLoader] = useState(false);
const submit = async () => {
if (!collection) return null;
setSubmitLoader(true);
const load = toast.loading(
method === "UPDATE" ? "Applying..." : "Creating..."
);
let response;
if (method === "CREATE") response = await addCollection(collection);
else response = await updateCollection(collection);
toast.dismiss(load);
if (response.ok) {
toast.success("Collection Saved!");
toggleCollectionModal();
} else toast.error(response.data as string);
setSubmitLoader(false);
};
return (
<div className="flex flex-col gap-3 sm:w-[35rem] w-80">
{permissions === true && (
<>
<p className="text-sm text-sky-500">Make Public</p>
<Checkbox
label="Make this a public collection."
state={collection.isPublic}
onClick={() =>
setCollection({ ...collection, isPublic: !collection.isPublic })
}
/>
<p className="text-gray-500 text-sm">
This will let <b>Anyone</b> to view this collection.
</p>
</>
)}
{collection.isPublic ? (
<div>
<p className="text-sm text-sky-500 mb-2">
Public Link (Click to copy)
</p>
<div
onClick={() => {
try {
navigator.clipboard
.writeText(publicCollectionURL)
.then(() => toast.success("Copied!"));
} catch (err) {
console.log(err);
}
}}
className="w-full hide-scrollbar overflow-x-auto whitespace-nowrap rounded-md p-3 border-sky-100 border-solid border outline-none hover:border-sky-500 duration-100 cursor-text"
>
{publicCollectionURL}
</div>
</div>
) : null}
{permissions !== true && collection.isPublic && <hr />}
{permissions === true && (
<>
<p className="text-sm text-sky-500">Member Management</p>
<div className="flex items-center gap-2">
<input
value={member.user.email}
onChange={(e) => {
setMember({
...member,
user: { ...member.user, email: e.target.value },
});
}}
onKeyDown={(e) =>
e.key === "Enter" &&
addMemberToCollection(
session.data?.user.email as string,
member.user.email,
collection,
setMemberState
)
}
type="text"
placeholder="Email"
className="w-full rounded-md p-3 border-sky-100 border-solid border outline-none focus:border-sky-500 duration-100"
/>
<div
onClick={() =>
addMemberToCollection(
session.data?.user.email as string,
member.user.email,
collection,
setMemberState
)
}
className="flex items-center justify-center bg-sky-500 hover:bg-sky-400 duration-100 text-white w-12 h-12 p-3 rounded-md cursor-pointer"
>
<FontAwesomeIcon icon={faUserPlus} className="w-5 h-5" />
</div>
</div>
</>
)}
{collection?.members[0]?.user && (
<>
<p className="text-center text-gray-500 text-xs sm:text-sm">
(All Members have <b>Read</b> access to this collection.)
</p>
<div className="max-h-[20rem] overflow-auto flex flex-col gap-3 rounded-md">
{collection.members
.sort((a, b) => (a.userId as number) - (b.userId as number))
.map((e, i) => {
return (
<div
key={i}
className="relative border p-2 rounded-md border-sky-100 flex flex-col sm:flex-row sm:items-center gap-2 justify-between"
>
{permissions === true && (
<FontAwesomeIcon
icon={faClose}
className="absolute right-2 top-2 text-gray-500 h-4 hover:text-red-500 duration-100 cursor-pointer"
title="Remove Member"
onClick={() => {
const updatedMembers = collection.members.filter(
(member) => {
return member.user.email !== e.user.email;
}
);
setCollection({
...collection,
members: updatedMembers,
});
}}
/>
)}
<div className="flex items-center gap-2">
<ProfilePhoto
src={`/api/avatar/${e.userId}`}
className="border-[3px]"
/>
<div>
<p className="text-sm font-bold text-sky-500">
{e.user.name}
</p>
<p className="text-sky-900">{e.user.email}</p>
</div>
</div>
<div className="flex sm:block items-center gap-5 min-w-[10rem]">
<div>
<p
className={`font-bold text-sm text-sky-500 ${
permissions === true ? "" : "mb-2"
}`}
>
Permissions
</p>
{permissions === true && (
<p className="text-xs text-gray-500 mb-2">
(Click to toggle.)
</p>
)}
</div>
{permissions !== true &&
!e.canCreate &&
!e.canUpdate &&
!e.canDelete ? (
<p className="text-sm text-gray-500">
Has no permissions.
</p>
) : (
<div>
<label
className={
permissions === true
? "cursor-pointer mr-1"
: "mr-1"
}
>
<input
type="checkbox"
id="canCreate"
className="peer sr-only"
checked={e.canCreate}
onChange={() => {
if (permissions === true) {
const updatedMembers = collection.members.map(
(member) => {
if (member.user.email === e.user.email) {
return {
...member,
canCreate: !e.canCreate,
};
}
return member;
}
);
setCollection({
...collection,
members: updatedMembers,
});
}
}}
/>
<span
className={`text-sky-900 peer-checked:bg-sky-500 text-sm ${
permissions === true
? "hover:bg-slate-200 duration-75"
: ""
} peer-checked:text-white rounded p-1 select-none`}
>
Create
</span>
</label>
<label
className={
permissions === true
? "cursor-pointer mr-1"
: "mr-1"
}
>
<input
type="checkbox"
id="canUpdate"
className="peer sr-only"
checked={e.canUpdate}
onChange={() => {
if (permissions === true) {
const updatedMembers = collection.members.map(
(member) => {
if (member.user.email === e.user.email) {
return {
...member,
canUpdate: !e.canUpdate,
};
}
return member;
}
);
setCollection({
...collection,
members: updatedMembers,
});
}
}}
/>
<span
className={`text-sky-900 peer-checked:bg-sky-500 text-sm ${
permissions === true
? "hover:bg-slate-200 duration-75"
: ""
} peer-checked:text-white rounded p-1 select-none`}
>
Update
</span>
</label>
<label
className={
permissions === true
? "cursor-pointer mr-1"
: "mr-1"
}
>
<input
type="checkbox"
id="canDelete"
className="peer sr-only"
checked={e.canDelete}
onChange={() => {
if (permissions === true) {
const updatedMembers = collection.members.map(
(member) => {
if (member.user.email === e.user.email) {
return {
...member,
canDelete: !e.canDelete,
};
}
return member;
}
);
setCollection({
...collection,
members: updatedMembers,
});
}
}}
/>
<span
className={`text-sky-900 peer-checked:bg-sky-500 text-sm ${
permissions === true
? "hover:bg-slate-200 duration-75"
: ""
} peer-checked:text-white rounded p-1 select-none`}
>
Delete
</span>
</label>
</div>
)}
</div>
</div>
);
})}
</div>
</>
)}
{permissions === true && (
<SubmitButton
onClick={submit}
loading={submitLoader}
label={method === "CREATE" ? "Add" : "Save"}
icon={method === "CREATE" ? faPlus : faPenToSquare}
className="mx-auto mt-2"
/>
)}
</div>
);
}

View File

@ -0,0 +1,120 @@
import { Tab } from "@headlessui/react";
import CollectionInfo from "./CollectionInfo";
import { CollectionIncludingMembersAndLinkCount } from "@/types/global";
import TeamManagement from "./TeamManagement";
import { useState } from "react";
import DeleteCollection from "./DeleteCollection";
type Props =
| {
toggleCollectionModal: Function;
activeCollection: CollectionIncludingMembersAndLinkCount;
method: "UPDATE";
isOwner: boolean;
className?: string;
defaultIndex?: number;
}
| {
toggleCollectionModal: Function;
activeCollection?: CollectionIncludingMembersAndLinkCount;
method: "CREATE";
isOwner: boolean;
className?: string;
defaultIndex?: number;
};
export default function CollectionModal({
className,
defaultIndex,
toggleCollectionModal,
isOwner,
activeCollection,
method,
}: Props) {
const [collection, setCollection] =
useState<CollectionIncludingMembersAndLinkCount>(
activeCollection || {
name: "",
description: "",
color: "#0ea5e9",
isPublic: false,
members: [],
}
);
return (
<div className={className}>
<Tab.Group defaultIndex={defaultIndex}>
{method === "CREATE" && (
<p className="text-xl text-sky-500 text-center">New Collection</p>
)}
<Tab.List className="flex justify-center flex-col max-w-[15rem] sm:max-w-[30rem] mx-auto sm:flex-row gap-2 sm:gap-3 mb-5 text-sky-600">
{method === "UPDATE" && (
<>
{isOwner && (
<Tab
className={({ selected }) =>
selected
? "px-2 py-1 bg-sky-200 duration-100 rounded-md outline-none"
: "px-2 py-1 hover:bg-slate-200 rounded-md duration-100 outline-none"
}
>
Collection Info
</Tab>
)}
<Tab
className={({ selected }) =>
selected
? "px-2 py-1 bg-sky-200 duration-100 rounded-md outline-none"
: "px-2 py-1 hover:bg-slate-200 rounded-md duration-100 outline-none"
}
>
{isOwner ? "Share & Collaborate" : "View Team"}
</Tab>
<Tab
className={({ selected }) =>
selected
? "px-2 py-1 bg-sky-200 duration-100 rounded-md outline-none"
: "px-2 py-1 hover:bg-slate-200 rounded-md duration-100 outline-none"
}
>
{isOwner ? "Delete Collection" : "Leave Collection"}
</Tab>
</>
)}
</Tab.List>
<Tab.Panels>
{(isOwner || method === "CREATE") && (
<Tab.Panel>
<CollectionInfo
toggleCollectionModal={toggleCollectionModal}
setCollection={setCollection}
collection={collection}
method={method}
/>
</Tab.Panel>
)}
{method === "UPDATE" && (
<>
<Tab.Panel>
<TeamManagement
toggleCollectionModal={toggleCollectionModal}
setCollection={setCollection}
collection={collection}
method={method}
/>
</Tab.Panel>
<Tab.Panel>
<DeleteCollection
toggleDeleteCollectionModal={toggleCollectionModal}
collection={collection}
/>
</Tab.Panel>
</>
)}
</Tab.Panels>
</Tab.Group>
</div>
);
}

View File

@ -0,0 +1,212 @@
import React, { useEffect, useState } from "react";
import CollectionSelection from "@/components/InputSelect/CollectionSelection";
import TagSelection from "@/components/InputSelect/TagSelection";
import { LinkIncludingShortenedCollectionAndTags } from "@/types/global";
import { faPenToSquare } from "@fortawesome/free-regular-svg-icons";
import useLinkStore from "@/store/links";
import { faPlus } from "@fortawesome/free-solid-svg-icons";
import RequiredBadge from "../../RequiredBadge";
import { useSession } from "next-auth/react";
import useCollectionStore from "@/store/collections";
import { useRouter } from "next/router";
import SubmitButton from "../../SubmitButton";
import { toast } from "react-hot-toast";
type Props =
| {
toggleLinkModal: Function;
method: "CREATE";
activeLink?: LinkIncludingShortenedCollectionAndTags;
}
| {
toggleLinkModal: Function;
method: "UPDATE";
activeLink: LinkIncludingShortenedCollectionAndTags;
};
export default function AddOrEditLink({
toggleLinkModal,
method,
activeLink,
}: Props) {
const [submitLoader, setSubmitLoader] = useState(false);
const { data } = useSession();
const [link, setLink] = useState<LinkIncludingShortenedCollectionAndTags>(
activeLink || {
name: "",
url: "",
description: "",
tags: [],
collection: {
name: "",
ownerId: data?.user.id as number,
},
}
);
const { updateLink, addLink } = useLinkStore();
const router = useRouter();
const { collections } = useCollectionStore();
useEffect(() => {
if (router.query.id) {
const currentCollection = collections.find(
(e) => e.id == Number(router.query.id)
);
if (currentCollection && currentCollection.ownerId)
setLink({
...link,
collection: {
id: currentCollection.id,
name: currentCollection.name,
ownerId: currentCollection.ownerId,
},
});
}
}, []);
// const shortendURL = method === "UPDATE" ? new URL(link.url).host.toLowerCase() : undefined;
const setTags = (e: any) => {
const tagNames = e.map((e: any) => {
return { name: e.label };
});
setLink({ ...link, tags: tagNames });
};
const setCollection = (e: any) => {
if (e?.__isNew__) e.value = null;
setLink({
...link,
collection: { id: e?.value, name: e?.label, ownerId: e?.ownerId },
});
};
const submit = async () => {
setSubmitLoader(true);
let response;
const load = toast.loading(
method === "UPDATE" ? "Applying..." : "Creating..."
);
if (method === "UPDATE") response = await updateLink(link);
else response = await addLink(link);
toast.dismiss(load);
if (response.ok) {
toast.success(`Link ${method === "UPDATE" ? "Saved!" : "Created!"}`);
toggleLinkModal();
} else toast.error(response.data as string);
setSubmitLoader(false);
return response;
};
return (
<div className="flex flex-col gap-3 sm:w-[35rem] w-80">
{method === "UPDATE" ? (
<p
className="text-gray-500 my-2 text-center truncate w-full"
title={link.url}
>
Edit <span className="underline">{link.url}</span>
</p>
) : null}
<div className="grid sm:grid-cols-2 gap-3">
<div>
<p className="text-sm text-sky-500 mb-2">
Name
<RequiredBadge />
</p>
<input
value={link.name}
onChange={(e) => setLink({ ...link, name: e.target.value })}
type="text"
placeholder="e.g. Example Link"
className="w-full rounded-md p-2 border-sky-100 border-solid border outline-none focus:border-sky-500 duration-100"
/>
</div>
{method === "CREATE" ? (
<div>
<p className="text-sm text-sky-500 mb-2">
URL
<RequiredBadge />
</p>
<input
value={link.url}
onChange={(e) => setLink({ ...link, url: e.target.value })}
type="text"
placeholder="e.g. http://example.com/"
className="w-full rounded-md p-2 border-sky-100 border-solid border outline-none focus:border-sky-500 duration-100"
/>
</div>
) : null}
<div>
<p className="text-sm text-sky-500 mb-2">
Collection
<RequiredBadge />
</p>
<CollectionSelection
onChange={setCollection}
// defaultValue={{
// label: link.collection.name,
// value: link.collection.id,
// }}
defaultValue={
link.collection.name && link.collection.id
? {
value: link.collection.id,
label: link.collection.name,
}
: undefined
}
/>
</div>
<div className={method === "UPDATE" ? "sm:col-span-2" : ""}>
<p className="text-sm text-sky-500 mb-2">Tags</p>
<TagSelection
onChange={setTags}
defaultValue={link.tags.map((e) => {
return { label: e.name, value: e.id };
})}
/>
</div>
<div className="sm:col-span-2">
<p className="text-sm text-sky-500 mb-2">Description</p>
<textarea
value={link.description}
onChange={(e) => setLink({ ...link, description: e.target.value })}
placeholder={
method === "CREATE"
? "Will be auto generated if nothing is provided."
: ""
}
className="resize-none w-full rounded-md p-2 border-sky-100 border-solid border outline-none focus:border-sky-500 duration-100"
/>
</div>
</div>
<SubmitButton
onClick={submit}
label={method === "CREATE" ? "Add" : "Save"}
icon={method === "CREATE" ? faPlus : faPenToSquare}
loading={submitLoader}
className={`mx-auto mt-2`}
/>
</div>
);
}

View File

@ -0,0 +1,288 @@
import {
CollectionIncludingMembersAndLinkCount,
LinkIncludingShortenedCollectionAndTags,
} from "@/types/global";
import Image from "next/image";
import ColorThief, { RGBColor } from "colorthief";
import { useEffect, useState } from "react";
import Link from "next/link";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import {
faArrowUpRightFromSquare,
faBoxArchive,
faCloudArrowDown,
faFolder,
} from "@fortawesome/free-solid-svg-icons";
import useCollectionStore from "@/store/collections";
import {
faCalendarDays,
faFileImage,
faFilePdf,
} from "@fortawesome/free-regular-svg-icons";
import isValidUrl from "@/lib/client/isValidUrl";
type Props = {
link: LinkIncludingShortenedCollectionAndTags;
};
export default function LinkDetails({ link }: Props) {
const [imageError, setImageError] = useState<boolean>(false);
const formattedDate = new Date(link.createdAt as string).toLocaleString(
"en-US",
{
year: "numeric",
month: "short",
day: "numeric",
}
);
const { collections } = useCollectionStore();
const [collection, setCollection] =
useState<CollectionIncludingMembersAndLinkCount>(
collections.find(
(e) => e.id === link.collection.id
) as CollectionIncludingMembersAndLinkCount
);
useEffect(() => {
setCollection(
collections.find(
(e) => e.id === link.collection.id
) as CollectionIncludingMembersAndLinkCount
);
}, [collections]);
const [colorPalette, setColorPalette] = useState<RGBColor[]>();
const colorThief = new ColorThief();
const url = isValidUrl(link.url) ? new URL(link.url) : undefined;
const rgbToHex = (r: number, g: number, b: number): string =>
"#" +
[r, g, b]
.map((x) => {
const hex = x.toString(16);
return hex.length === 1 ? "0" + hex : hex;
})
.join("");
useEffect(() => {
const banner = document.getElementById("link-banner");
const bannerInner = document.getElementById("link-banner-inner");
if (colorPalette && banner && bannerInner) {
banner.style.background = `linear-gradient(to right, ${rgbToHex(
colorPalette[0][0],
colorPalette[0][1],
colorPalette[0][2]
)}, ${rgbToHex(
colorPalette[1][0],
colorPalette[1][1],
colorPalette[1][2]
)})`;
bannerInner.style.background = `linear-gradient(to right, ${rgbToHex(
colorPalette[2][0],
colorPalette[2][1],
colorPalette[2][2]
)}, ${rgbToHex(
colorPalette[3][0],
colorPalette[3][1],
colorPalette[3][2]
)})`;
}
}, [colorPalette]);
const handleDownload = (format: "png" | "pdf") => {
const path = `/api/archives/${link.collection.id}/${link.id}.${format}`;
fetch(path)
.then((response) => {
if (response.ok) {
// Create a temporary link and click it to trigger the download
const link = document.createElement("a");
link.href = path;
link.download = format === "pdf" ? "PDF" : "Screenshot";
link.click();
} else {
console.error("Failed to download file");
}
})
.catch((error) => {
console.error("Error:", error);
});
};
return (
<div className="flex flex-col gap-3 sm:w-[35rem] w-80">
{!imageError && (
<div id="link-banner" className="link-banner h-32 -mx-5 -mt-5 relative">
<div id="link-banner-inner" className="link-banner-inner"></div>
</div>
)}
<div
className={`relative flex gap-5 items-start ${!imageError && "-mt-24"}`}
>
{!imageError && url && (
<Image
src={`https://t2.gstatic.com/faviconV2?client=SOCIAL&type=FAVICON&fallback_opts=TYPE,SIZE,URL&url=${url.origin}&size=32`}
width={42}
height={42}
alt=""
id={"favicon-" + link.id}
className="select-none mt-2 rounded-full shadow border-[3px] border-white bg-white aspect-square"
draggable="false"
onLoad={(e) => {
try {
const color = colorThief.getPalette(
e.target as HTMLImageElement,
4,
20
);
setColorPalette(color);
} catch (err) {
console.log(err);
}
}}
onError={(e) => {
setImageError(true);
}}
/>
)}
<div className="flex flex-col gap- justify-end drop-shadow">
<p className="text-2xl text-sky-500 capitalize hyphens-auto">
{link.name}
</p>
<Link
href={link.url}
target="_blank"
rel="noreferrer"
className="text-sm text-gray-500 break-all hover:underline cursor-pointer w-fit"
>
{url ? url.host : link.url}
</Link>
</div>
</div>
<div className="flex gap-1 items-center flex-wrap">
<Link
href={`/collections/${link.collection.id}`}
className="flex items-center gap-1 cursor-pointer hover:opacity-60 duration-100 mr-2 z-10"
>
<FontAwesomeIcon
icon={faFolder}
className="w-5 h-5 drop-shadow"
style={{ color: collection?.color }}
/>
<p
title={collection?.name}
className="text-sky-900 text-lg truncate max-w-[12rem]"
>
{collection?.name}
</p>
</Link>
{link.tags.map((e, i) => (
<Link key={i} href={`/tags/${e.id}`} className="z-10">
<p
title={e.name}
className="px-2 py-1 bg-sky-200 text-sky-700 text-xs rounded-3xl cursor-pointer hover:opacity-60 duration-100 truncate max-w-[19rem]"
>
{e.name}
</p>
</Link>
))}
</div>
{link.description && (
<>
<div className="text-gray-500 max-h-[20rem] my-3 rounded-md overflow-y-auto hyphens-auto">
{link.description}
</div>
</>
)}
<div className="flex justify-between items-center">
<div className="flex items-center gap-1 text-gray-500">
<FontAwesomeIcon icon={faBoxArchive} className="w-4 h-4" />
<p className=" text-gray-500">Archived Formats:</p>
</div>
<div
className="flex items-center gap-1 text-gray-500"
title={"Created at: " + formattedDate}
>
<FontAwesomeIcon icon={faCalendarDays} className="w-4 h-4" />
<p>{formattedDate}</p>
</div>
</div>
<div className="flex flex-col gap-2">
<div className="flex justify-between items-center p-2 border border-sky-100 rounded-md">
<div className="flex gap-2 items-center">
<div className="text-white bg-sky-300 p-2 rounded-md">
<FontAwesomeIcon icon={faFileImage} className="w-6 h-6" />
</div>
<p className="text-gray-500">Screenshot</p>
</div>
<div className="flex text-sky-600 gap-1">
<Link
href={`/api/archives/${link.collectionId}/${link.id}.png`}
target="_blank"
rel="noreferrer"
className="cursor-pointer hover:bg-sky-100 duration-100 p-2 rounded-md"
>
<FontAwesomeIcon
icon={faArrowUpRightFromSquare}
className="w-5 h-5"
/>
</Link>
<div
onClick={() => handleDownload("png")}
className="cursor-pointer hover:bg-sky-100 duration-100 p-2 rounded-md"
>
<FontAwesomeIcon
icon={faCloudArrowDown}
className="w-5 h-5 cursor-pointer"
/>
</div>
</div>
</div>
<div className="flex justify-between items-center p-2 border border-sky-100 rounded-md">
<div className="flex gap-2 items-center">
<div className="text-white bg-sky-300 p-2 rounded-md">
<FontAwesomeIcon icon={faFilePdf} className="w-6 h-6" />
</div>
<p className="text-gray-500">PDF</p>
</div>
<div className="flex text-sky-600 gap-1">
<Link
href={`/api/archives/${link.collectionId}/${link.id}.pdf`}
target="_blank"
rel="noreferrer"
className="cursor-pointer hover:bg-sky-100 duration-100 p-2 rounded-md"
>
<FontAwesomeIcon
icon={faArrowUpRightFromSquare}
className="w-5 h-5"
/>
</Link>
<div
onClick={() => handleDownload("pdf")}
className="cursor-pointer hover:bg-sky-100 duration-100 p-2 rounded-md"
>
<FontAwesomeIcon
icon={faCloudArrowDown}
className="w-5 h-5 cursor-pointer"
/>
</div>
</div>
</div>
</div>
</div>
);
}

View File

@ -0,0 +1,91 @@
import { Tab } from "@headlessui/react";
import { LinkIncludingShortenedCollectionAndTags } from "@/types/global";
import AddOrEditLink from "./AddOrEditLink";
import LinkDetails from "./LinkDetails";
type Props =
| {
toggleLinkModal: Function;
method: "CREATE";
isOwnerOrMod?: boolean;
activeLink?: LinkIncludingShortenedCollectionAndTags;
defaultIndex?: number;
className?: string;
}
| {
toggleLinkModal: Function;
method: "UPDATE";
isOwnerOrMod: boolean;
activeLink: LinkIncludingShortenedCollectionAndTags;
defaultIndex?: number;
className?: string;
};
export default function LinkModal({
className,
defaultIndex,
toggleLinkModal,
isOwnerOrMod,
activeLink,
method,
}: Props) {
return (
<div className={className}>
<Tab.Group defaultIndex={defaultIndex}>
{method === "CREATE" && (
<p className="text-xl text-sky-500 text-center">New Link</p>
)}
<Tab.List
className={`flex justify-center flex-col max-w-[15rem] sm:max-w-[30rem] mx-auto sm:flex-row gap-2 sm:gap-3 mb-5 text-sky-600 ${
isOwnerOrMod ? "" : "pb-8"
}`}
>
{method === "UPDATE" && isOwnerOrMod && (
<>
<Tab
className={({ selected }) =>
selected
? "px-2 py-1 bg-sky-200 duration-100 rounded-md outline-none"
: "px-2 py-1 hover:bg-slate-200 rounded-md duration-100 outline-none"
}
>
Link Details
</Tab>
<Tab
className={({ selected }) =>
selected
? "px-2 py-1 bg-sky-200 duration-100 rounded-md outline-none"
: "px-2 py-1 hover:bg-slate-200 rounded-md duration-100 outline-none"
}
>
Edit Link
</Tab>
</>
)}
</Tab.List>
<Tab.Panels>
{activeLink && method === "UPDATE" && (
<Tab.Panel>
<LinkDetails link={activeLink} />
</Tab.Panel>
)}
<Tab.Panel>
{activeLink && method === "UPDATE" ? (
<AddOrEditLink
toggleLinkModal={toggleLinkModal}
method="UPDATE"
activeLink={activeLink}
/>
) : (
<AddOrEditLink
toggleLinkModal={toggleLinkModal}
method="CREATE"
/>
)}
</Tab.Panel>
</Tab.Panels>
</Tab.Group>
</div>
);
}

View File

@ -0,0 +1,109 @@
import { Dispatch, SetStateAction, useEffect, useState } from "react";
import { AccountSettings } from "@/types/global";
import useAccountStore from "@/store/account";
import { useSession } from "next-auth/react";
import { faPenToSquare } from "@fortawesome/free-regular-svg-icons";
import SubmitButton from "@/components/SubmitButton";
import { toast } from "react-hot-toast";
type Props = {
togglePasswordFormModal: Function;
setUser: Dispatch<SetStateAction<AccountSettings>>;
user: AccountSettings;
};
export default function ChangePassword({
togglePasswordFormModal,
setUser,
user,
}: Props) {
const [oldPassword, setOldPassword] = useState("");
const [newPassword, setNewPassword1] = useState("");
const [newPassword2, setNewPassword2] = useState("");
const [submitLoader, setSubmitLoader] = useState(false);
const { account, updateAccount } = useAccountStore();
const { update } = useSession();
useEffect(() => {
if (
!(oldPassword == "" || newPassword == "" || newPassword2 == "") &&
newPassword === newPassword2
) {
setUser({ ...user, oldPassword, newPassword });
}
}, [oldPassword, newPassword, newPassword2]);
const submit = async () => {
if (oldPassword == "" || newPassword == "" || newPassword2 == "") {
toast.error("Please fill all the fields.");
} else if (newPassword === newPassword2) {
setSubmitLoader(true);
const load = toast.loading("Applying...");
const response = await updateAccount({
...user,
});
toast.dismiss(load);
if (response.ok) {
toast.success("Settings Applied!");
togglePasswordFormModal();
} else toast.error(response.data as string);
setSubmitLoader(false);
if (user.email !== account.email || user.name !== account.name)
update({ email: user.email, name: user.name });
if (response.ok) {
setUser({ ...user, oldPassword: undefined, newPassword: undefined });
togglePasswordFormModal();
}
} else {
toast.error("Passwords do not match.");
}
};
return (
<div className="mx-auto sm:w-[35rem] w-80">
<div className="max-w-[25rem] w-full mx-auto flex flex-col gap-3 justify-between">
<p className="text-sm text-sky-500">Old Password</p>
<input
value={oldPassword}
onChange={(e) => setOldPassword(e.target.value)}
type="password"
className="w-full rounded-md p-3 mx-auto border-sky-100 border-solid border outline-none focus:border-sky-500 duration-100"
/>
<p className="text-sm text-sky-500">New Password</p>
<input
value={newPassword}
onChange={(e) => setNewPassword1(e.target.value)}
type="password"
className="w-full rounded-md p-3 mx-auto border-sky-100 border-solid border outline-none focus:border-sky-500 duration-100"
/>
<p className="text-sm text-sky-500">Re-enter New Password</p>
<input
value={newPassword2}
onChange={(e) => setNewPassword2(e.target.value)}
type="password"
className="w-full rounded-md p-3 mx-auto border-sky-100 border-solid border outline-none focus:border-sky-500 duration-100"
/>
<SubmitButton
onClick={submit}
loading={submitLoader}
label="Apply Settings"
icon={faPenToSquare}
className="mx-auto mt-2"
/>
</div>
</div>
);
}

View File

@ -0,0 +1,120 @@
import { Dispatch, SetStateAction, useEffect, useState } from "react";
import Checkbox from "../../Checkbox";
import useAccountStore from "@/store/account";
import { AccountSettings } from "@/types/global";
import { useSession } from "next-auth/react";
import { faPenToSquare } from "@fortawesome/free-regular-svg-icons";
import SubmitButton from "../../SubmitButton";
import { toast } from "react-hot-toast";
type Props = {
toggleSettingsModal: Function;
setUser: Dispatch<SetStateAction<AccountSettings>>;
user: AccountSettings;
};
export default function PrivacySettings({
toggleSettingsModal,
setUser,
user,
}: Props) {
const { update } = useSession();
const { account, updateAccount } = useAccountStore();
const [submitLoader, setSubmitLoader] = useState(false);
const [whitelistedUsersTextbox, setWhiteListedUsersTextbox] = useState(
user.whitelistedUsers.join(", ")
);
useEffect(() => {
setUser({
...user,
whitelistedUsers: stringToArray(whitelistedUsersTextbox),
});
}, [whitelistedUsersTextbox]);
useEffect(() => {
setUser({ ...user, oldPassword: undefined, newPassword: undefined });
}, []);
const stringToArray = (str: string) => {
const stringWithoutSpaces = str.replace(/\s+/g, "");
const wordsArray = stringWithoutSpaces.split(",");
return wordsArray;
};
const submit = async () => {
setSubmitLoader(true);
const load = toast.loading("Applying...");
const response = await updateAccount({
...user,
});
toast.dismiss(load);
if (response.ok) {
toast.success("Settings Applied!");
toggleSettingsModal();
} else toast.error(response.data as string);
setSubmitLoader(false);
if (user.email !== account.email || user.name !== account.name)
update({ email: user.email, name: user.name });
if (response.ok) {
setUser({ ...user, oldPassword: undefined, newPassword: undefined });
toggleSettingsModal();
}
};
return (
<div className="flex flex-col gap-3 justify-between sm:w-[35rem] w-80">
<div>
<p className="text-sm text-sky-500 mb-2">Profile Visibility</p>
<Checkbox
label="Make profile private"
state={user.isPrivate}
className="text-sm sm:text-base"
onClick={() => setUser({ ...user, isPrivate: !user.isPrivate })}
/>
<p className="text-gray-500 text-sm">
This will limit who can find and add you to other Collections.
</p>
{user.isPrivate && (
<div>
<p className="text-sm text-sky-500 my-2">Whitelisted Users</p>
<p className="text-gray-500 text-sm mb-3">
Please provide the Email addresses of the users you wish to grant
visibility to your profile. Separated by comma.
</p>
<textarea
className="w-full resize-none border rounded-md duration-100 bg-white p-2 outline-none border-sky-100 focus:border-sky-500"
placeholder="Your profile is hidden from everyone right now..."
value={whitelistedUsersTextbox}
onChange={(e) => {
setWhiteListedUsersTextbox(e.target.value);
}}
/>
</div>
)}
</div>
<SubmitButton
onClick={submit}
loading={submitLoader}
label="Apply Settings"
icon={faPenToSquare}
className="mx-auto mt-2"
/>
</div>
);
}

View File

@ -0,0 +1,178 @@
import { Dispatch, SetStateAction, useEffect, useState } from "react";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faClose } from "@fortawesome/free-solid-svg-icons";
import useAccountStore from "@/store/account";
import { AccountSettings } from "@/types/global";
import { useSession } from "next-auth/react";
import { resizeImage } from "@/lib/client/resizeImage";
import { faPenToSquare } from "@fortawesome/free-regular-svg-icons";
import SubmitButton from "../../SubmitButton";
import ProfilePhoto from "../../ProfilePhoto";
import { toast } from "react-hot-toast";
type Props = {
toggleSettingsModal: Function;
setUser: Dispatch<SetStateAction<AccountSettings>>;
user: AccountSettings;
};
export default function ProfileSettings({
toggleSettingsModal,
setUser,
user,
}: Props) {
const { update } = useSession();
const { account, updateAccount } = useAccountStore();
const [profileStatus, setProfileStatus] = useState(true);
const [submitLoader, setSubmitLoader] = useState(false);
const handleProfileStatus = (e: boolean) => {
setProfileStatus(!e);
};
const handleImageUpload = async (e: any) => {
const file: File = e.target.files[0];
const fileExtension = file.name.split(".").pop()?.toLowerCase();
const allowedExtensions = ["png", "jpeg", "jpg"];
if (allowedExtensions.includes(fileExtension as string)) {
const resizedFile = await resizeImage(file);
if (
resizedFile.size < 1048576 // 1048576 Bytes == 1MB
) {
const reader = new FileReader();
reader.onload = () => {
setUser({ ...user, profilePic: reader.result as string });
};
reader.readAsDataURL(resizedFile);
} else {
toast.error("Please select a PNG or JPEG file thats less than 1MB.");
}
} else {
toast.error("Invalid file format.");
}
};
useEffect(() => {
setUser({ ...user, oldPassword: undefined, newPassword: undefined });
}, []);
const submit = async () => {
setSubmitLoader(true);
const load = toast.loading("Applying...");
const response = await updateAccount({
...user,
});
toast.dismiss(load);
if (response.ok) {
toast.success("Settings Applied!");
toggleSettingsModal();
} else toast.error(response.data as string);
setSubmitLoader(false);
if (user.email !== account.email || user.name !== account.name)
update({ email: user.email, name: user.name });
if (response.ok) {
setUser({ ...user, oldPassword: undefined, newPassword: undefined });
toggleSettingsModal();
}
};
return (
<div className="flex flex-col gap-3 justify-between sm:w-[35rem] w-80">
<div className="grid sm:grid-cols-2 gap-3 auto-rows-auto">
<div className="sm:row-span-2 sm:justify-self-center mx-auto mb-3">
<p className="text-sm text-sky-500 mb-2 text-center">Profile Photo</p>
<div className="w-28 h-28 flex items-center justify-center rounded-full relative">
<ProfilePhoto
src={user.profilePic}
className="h-auto w-28"
status={handleProfileStatus}
/>
{profileStatus && (
<div
onClick={() =>
setUser({
...user,
profilePic: "",
})
}
className="absolute top-1 left-1 w-5 h-5 flex items-center justify-center border p-1 bg-white border-slate-200 rounded-full text-gray-500 hover:text-red-500 duration-100 cursor-pointer"
>
<FontAwesomeIcon icon={faClose} className="w-3 h-3" />
</div>
)}
<div className="absolute -bottom-2 left-0 right-0 mx-auto w-fit text-center">
<label
htmlFor="upload-photo"
title="PNG or JPG (Max: 3MB)"
className="border border-slate-200 rounded-md bg-white px-2 text-center select-none cursor-pointer text-sky-900 duration-100 hover:border-sky-500"
>
Browse...
<input
type="file"
name="photo"
id="upload-photo"
accept=".png, .jpeg, .jpg"
className="hidden"
onChange={handleImageUpload}
/>
</label>
</div>
</div>
</div>
<div className="flex flex-col gap-3">
<div>
<p className="text-sm text-sky-500 mb-2">Display Name</p>
<input
type="text"
value={user.name}
onChange={(e) => setUser({ ...user, name: e.target.value })}
className="w-full rounded-md p-2 border-sky-100 border-solid border outline-none focus:border-sky-500 duration-100"
/>
</div>
<div>
<p className="text-sm text-sky-500 mb-2">Email</p>
<input
type="text"
value={user.email}
onChange={(e) => setUser({ ...user, email: e.target.value })}
className="w-full rounded-md p-2 border-sky-100 border-solid border outline-none focus:border-sky-500 duration-100"
/>
</div>
</div>
</div>
{/* <hr /> TODO: Export functionality
<p className="text-sky-600">Data Settings</p>
<div className="w-fit">
<div className="border border-sky-100 rounded-md bg-white px-2 py-1 text-center select-none cursor-pointer text-sky-900 duration-100 hover:border-sky-500">
Export Data
</div>
</div> */}
<SubmitButton
onClick={submit}
loading={submitLoader}
label="Apply Settings"
icon={faPenToSquare}
className="mx-auto mt-2"
/>
</div>
);
}

View File

@ -0,0 +1,85 @@
import { Tab } from "@headlessui/react";
import { AccountSettings } from "@/types/global";
import { useState } from "react";
import ChangePassword from "./ChangePassword";
import ProfileSettings from "./ProfileSettings";
import PrivacySettings from "./PrivacySettings";
type Props = {
toggleSettingsModal: Function;
activeUser: AccountSettings;
className?: string;
defaultIndex?: number;
};
export default function UserModal({
className,
defaultIndex,
toggleSettingsModal,
activeUser,
}: Props) {
const [user, setUser] = useState<AccountSettings>(activeUser);
return (
<div className={className}>
<Tab.Group defaultIndex={defaultIndex}>
<Tab.List className="flex justify-center flex-col max-w-[15rem] sm:max-w-[30rem] mx-auto sm:flex-row gap-2 sm:gap-3 mb-5 text-sky-600">
<Tab
className={({ selected }) =>
selected
? "px-2 py-1 bg-sky-200 duration-100 rounded-md outline-none"
: "px-2 py-1 hover:bg-slate-200 rounded-md duration-100 outline-none"
}
>
Profile Settings
</Tab>
<Tab
className={({ selected }) =>
selected
? "px-2 py-1 bg-sky-200 duration-100 rounded-md outline-none"
: "px-2 py-1 hover:bg-slate-200 rounded-md duration-100 outline-none"
}
>
Privacy Settings
</Tab>
<Tab
className={({ selected }) =>
selected
? "px-2 py-1 bg-sky-200 duration-100 rounded-md outline-none"
: "px-2 py-1 hover:bg-slate-200 rounded-md duration-100 outline-none"
}
>
Password
</Tab>
</Tab.List>
<Tab.Panels>
<Tab.Panel>
<ProfileSettings
toggleSettingsModal={toggleSettingsModal}
setUser={setUser}
user={user}
/>
</Tab.Panel>
<Tab.Panel>
<PrivacySettings
toggleSettingsModal={toggleSettingsModal}
setUser={setUser}
user={user}
/>
</Tab.Panel>
<Tab.Panel>
<ChangePassword
togglePasswordFormModal={toggleSettingsModal}
setUser={setUser}
user={user}
/>
</Tab.Panel>
</Tab.Panels>
</Tab.Group>
</div>
);
}

View File

@ -0,0 +1,34 @@
import { MouseEventHandler, ReactNode } from "react";
import ClickAwayHandler from "@/components/ClickAwayHandler";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faChevronLeft } from "@fortawesome/free-solid-svg-icons";
type Props = {
toggleModal: Function;
children: ReactNode;
className?: string;
};
export default function Modal({ toggleModal, className, children }: Props) {
return (
<div className="overflow-y-auto py-2 fixed top-0 bottom-0 right-0 left-0 bg-gray-500 bg-opacity-10 backdrop-blur-sm flex items-center fade-in z-30">
<ClickAwayHandler
onClickOutside={toggleModal}
className={`w-fit m-auto mt-10 sm:mt-20 ${className}`}
>
<div className="slide-up relative border-sky-100 rounded-2xl border-solid border shadow-lg p-5 bg-white">
<div
onClick={toggleModal as MouseEventHandler<HTMLDivElement>}
className="absolute top-5 left-5 inline-flex rounded-md cursor-pointer hover:bg-slate-200 duration-100 z-20 p-2"
>
<FontAwesomeIcon
icon={faChevronLeft}
className="w-4 h-4 text-gray-500"
/>
</div>
{children}
</div>
</ClickAwayHandler>
</div>
);
}

View File

@ -0,0 +1,63 @@
import useModalStore from "@/store/modals";
import Modal from "./Modal";
import LinkModal from "./Modal/Link";
import {
AccountSettings,
CollectionIncludingMembersAndLinkCount,
LinkIncludingShortenedCollectionAndTags,
} from "@/types/global";
import CollectionModal from "./Modal/Collection";
import UserModal from "./Modal/User";
import { useEffect } from "react";
import { useRouter } from "next/router";
export default function ModalManagement() {
const { modal, setModal } = useModalStore();
const toggleModal = () => {
setModal(null);
};
const router = useRouter();
useEffect(() => {
toggleModal();
}, [router]);
if (modal && modal.modal === "LINK")
return (
<Modal toggleModal={toggleModal}>
<LinkModal
toggleLinkModal={toggleModal}
method={modal.method}
isOwnerOrMod={modal.isOwnerOrMod as boolean}
defaultIndex={modal.defaultIndex}
activeLink={modal.active as LinkIncludingShortenedCollectionAndTags}
/>
</Modal>
);
else if (modal && modal.modal === "COLLECTION")
return (
<Modal toggleModal={toggleModal}>
<CollectionModal
toggleCollectionModal={toggleModal}
method={modal.method}
isOwner={modal.isOwner as boolean}
defaultIndex={modal.defaultIndex}
activeCollection={
modal.active as CollectionIncludingMembersAndLinkCount
}
/>
</Modal>
);
else if (modal && modal.modal === "ACCOUNT")
return (
<Modal toggleModal={toggleModal}>
<UserModal
toggleSettingsModal={toggleModal}
defaultIndex={modal.defaultIndex}
activeUser={modal.active as AccountSettings}
/>
</Modal>
);
else return <></>;
}

124
components/Navbar.tsx Normal file
View File

@ -0,0 +1,124 @@
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { signOut } from "next-auth/react";
import { faPlus, faBars } from "@fortawesome/free-solid-svg-icons";
import { useEffect, useState } from "react";
import Dropdown from "@/components/Dropdown";
import ClickAwayHandler from "@/components/ClickAwayHandler";
import Sidebar from "@/components/Sidebar";
import { useRouter } from "next/router";
import Search from "@/components/Search";
import useAccountStore from "@/store/account";
import ProfilePhoto from "@/components/ProfilePhoto";
import useModalStore from "@/store/modals";
export default function Navbar() {
const { setModal } = useModalStore();
const { account } = useAccountStore();
const [profileDropdown, setProfileDropdown] = useState(false);
const [sidebar, setSidebar] = useState(false);
const router = useRouter();
window.addEventListener("resize", () => setSidebar(false));
useEffect(() => {
setSidebar(false);
}, [router]);
const toggleSidebar = () => {
setSidebar(!sidebar);
};
return (
<div className="flex justify-between gap-2 items-center px-5 py-2 border-solid border-b-sky-100 border-b h-16">
<div
onClick={toggleSidebar}
className="inline-flex lg:hidden gap-1 items-center select-none cursor-pointer p-[0.687rem] text-gray-500 rounded-md duration-100 hover:bg-slate-200"
>
<FontAwesomeIcon icon={faBars} className="w-5 h-5" />
</div>
<Search />
<div className="flex items-center gap-2">
<div
onClick={() => {
setModal({
modal: "LINK",
state: true,
method: "CREATE",
});
}}
className="inline-flex gap-1 relative sm:w-[7.2rem] items-center font-semibold select-none cursor-pointer p-[0.687rem] sm:p-2 sm:px-3 rounded-md sm:rounded-full hover:bg-sky-100 text-sky-500 sm:text-white sm:bg-sky-500 sm:hover:bg-sky-400 duration-100 group"
>
<FontAwesomeIcon
icon={faPlus}
className="w-5 h-5 sm:group-hover:ml-9 sm:absolute duration-100"
/>
<span className="hidden sm:block group-hover:opacity-0 text-right w-full duration-100">
New Link
</span>
</div>
<div className="relative">
<div
className="flex gap-1 group sm:hover:bg-slate-200 sm:hover:p-1 sm:hover:pr-2 duration-100 h-10 rounded-full items-center w-fit bg-white cursor-pointer"
onClick={() => setProfileDropdown(!profileDropdown)}
id="profile-dropdown"
>
<ProfilePhoto
src={account.profilePic}
className="sm:group-hover:h-8 sm:group-hover:w-8 duration-100 border-[3px]"
/>
<p
id="profile-dropdown"
className="font-bold text-sky-500 leading-3 hidden sm:block select-none truncate max-w-[8rem] py-1"
>
{account.name}
</p>
</div>
{profileDropdown ? (
<Dropdown
items={[
{
name: "Settings",
onClick: () => {
setModal({
modal: "ACCOUNT",
state: true,
active: account,
});
setProfileDropdown(!profileDropdown);
},
},
{
name: "Logout",
onClick: () => {
signOut();
setProfileDropdown(!profileDropdown);
},
},
]}
onClickOutside={(e: Event) => {
const target = e.target as HTMLInputElement;
if (target.id !== "profile-dropdown") setProfileDropdown(false);
}}
className="absolute top-11 right-0 z-20 w-36"
/>
) : null}
{sidebar ? (
<div className="fixed top-0 bottom-0 right-0 left-0 bg-gray-500 bg-opacity-10 backdrop-blur-sm flex items-center fade-in z-30">
<ClickAwayHandler onClickOutside={toggleSidebar}>
<div className="slide-right shadow-lg">
<Sidebar />
</div>
</ClickAwayHandler>
</div>
) : null}
</div>
</div>
</div>
);
}

View File

@ -0,0 +1,49 @@
import React, { useEffect, useState } from "react";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faUser } from "@fortawesome/free-solid-svg-icons";
import Image from "next/image";
import avatarExists from "@/lib/client/avatarExists";
type Props = {
src: string;
className?: string;
emptyImage?: boolean;
status?: Function;
};
export default function ProfilePhoto({
src,
className,
emptyImage,
status,
}: Props) {
const [error, setError] = useState<boolean>(emptyImage || true);
const checkAvatarExistence = async () => {
const canPass = await avatarExists(src);
setError(!canPass);
};
useEffect(() => {
if (src) checkAvatarExistence();
status && status(error || !src);
}, [src, error]);
return error || !src ? (
<div
className={`bg-sky-500 text-white h-10 w-10 aspect-square shadow rounded-full border border-slate-200 flex items-center justify-center ${className}`}
>
<FontAwesomeIcon icon={faUser} className="w-1/2 h-1/2 aspect-square" />
</div>
) : (
<Image
alt=""
src={src}
height={112}
width={112}
className={`h-10 w-10 shadow rounded-full aspect-square border border-slate-200 ${className}`}
/>
);
}

View File

@ -0,0 +1,97 @@
import { faChevronRight } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import Image from "next/image";
import { Link as LinkType, Tag } from "@prisma/client";
import isValidUrl from "@/lib/client/isValidUrl";
interface LinksIncludingTags extends LinkType {
tags: Tag[];
}
type Props = {
link: LinksIncludingTags;
count: number;
};
export default function LinkCard({ link, count }: Props) {
const url = isValidUrl(link.url) ? new URL(link.url) : undefined;
const formattedDate = new Date(
link.createdAt as unknown as string
).toLocaleString("en-US", {
year: "numeric",
month: "short",
day: "numeric",
});
return (
<a href={link.url} target="_blank" rel="noreferrer" className="rounded-3xl">
<div className="bg-gradient-to-tr from-slate-200 from-10% to-gray-50 via-20% shadow-md sm:hover:shadow-none duration-100 rounded-3xl cursor-pointer p-5 flex items-start relative gap-5 sm:gap-10 group/item">
{url && (
<>
<Image
src={`https://t2.gstatic.com/faviconV2?client=SOCIAL&type=FAVICON&fallback_opts=TYPE,SIZE,URL&url=${url.origin}&size=32`}
width={42}
height={42}
alt=""
className="select-none mt-3 z-10 rounded-full shadow border-[3px] border-white bg-white"
draggable="false"
onError={(e) => {
const target = e.target as HTMLElement;
target.style.display = "none";
}}
/>
<Image
src={`https://t2.gstatic.com/faviconV2?client=SOCIAL&type=FAVICON&fallback_opts=TYPE,SIZE,URL&url=${url.origin}&size=32`}
width={80}
height={80}
alt=""
className="blur-sm absolute left-2 opacity-40 select-none hidden sm:block"
draggable="false"
onError={(e) => {
const target = e.target as HTMLElement;
target.style.display = "none";
}}
/>
</>
)}
<div className="flex justify-between items-center gap-5 w-full h-full z-0">
<div className="flex flex-col justify-between">
<div className="flex items-baseline gap-1">
<p className="text-sm text-sky-400 font-bold">{count + 1}.</p>
<p className="text-lg text-sky-500 font-bold">{link.name}</p>
</div>
<p className="text-gray-500 text-sm font-medium">
{link.description}
</p>
<div className="flex gap-3 items-center flex-wrap my-3">
<div className="flex gap-1 items-center flex-wrap mt-1">
{link.tags.map((e, i) => (
<p
key={i}
className="px-2 py-1 bg-sky-200 text-sky-700 text-xs rounded-3xl cursor-pointer truncate max-w-[10rem]"
>
{e.name}
</p>
))}
</div>
</div>
<div className="flex gap-2 items-center flex-wrap mt-2">
<p className="text-gray-500">{formattedDate}</p>
<div className="text-sky-400 font-bold flex items-center gap-1">
<p>{url ? url.host : link.url}</p>
</div>
</div>
</div>
<div className="hidden sm:group-hover/item:block duration-100 text-slate-500">
<FontAwesomeIcon
icon={faChevronRight}
className="w-7 h-7 slide-right-with-fade"
/>
</div>
</div>
</div>
</a>
);
}

View File

@ -0,0 +1,32 @@
import { faCircle, faCircleCheck } from "@fortawesome/free-regular-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { ChangeEventHandler } from "react";
type Props = {
label: string;
state: boolean;
onClick: ChangeEventHandler<HTMLInputElement>;
};
export default function RadioButton({ label, state, onClick }: Props) {
return (
<label className="cursor-pointer flex items-center gap-2">
<input
type="radio"
value={label}
className="peer sr-only"
checked={state}
onChange={onClick}
/>
<FontAwesomeIcon
icon={faCircleCheck}
className="w-5 h-5 text-sky-500 peer-checked:block hidden"
/>
<FontAwesomeIcon
icon={faCircle}
className="w-5 h-5 text-sky-500 peer-checked:hidden block"
/>
<span className="text-sky-900 rounded select-none">{label}</span>
</label>
);
}

View File

@ -0,0 +1,8 @@
export default function RequiredBadge() {
return (
<span title="Required Field" className="text-sky-500 cursor-help">
{" "}
*
</span>
);
}

51
components/Search.tsx Normal file
View File

@ -0,0 +1,51 @@
import { faMagnifyingGlass } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { useState } from "react";
import { useRouter } from "next/router";
import { toast } from "react-hot-toast";
export default function Search() {
const router = useRouter();
const routeQuery = router.query.query;
const [searchQuery, setSearchQuery] = useState(
routeQuery ? decodeURIComponent(routeQuery as string) : ""
);
const [searchBox, setSearchBox] = useState(
router.pathname.startsWith("/search") || false
);
return (
<div
className="flex items-center relative group"
onClick={() => setSearchBox(true)}
>
<label
htmlFor="search-box"
className="inline-flex w-fit absolute left-2 pointer-events-none rounded-md p-1 text-sky-500 group-hover:text-sky-600"
>
<FontAwesomeIcon icon={faMagnifyingGlass} className="w-5 h-5" />
</label>
<input
id="search-box"
type="text"
placeholder="Search for Links"
value={searchQuery}
onChange={(e) => {
e.target.value.includes("%") &&
toast.error("The search query should not contain '%'.");
setSearchQuery(e.target.value.replace("%", ""));
}}
onKeyDown={(e) =>
e.key === "Enter" &&
router.push("/search/" + encodeURIComponent(searchQuery))
}
autoFocus={searchBox}
className="border border-sky-100 rounded-md pl-10 py-2 pr-2 w-44 sm:w-60 focus:border-sky-500 md:focus:w-80 hover:border-sky-500 duration-100 outline-none"
/>
</div>
);
}

208
components/Sidebar.tsx Normal file
View File

@ -0,0 +1,208 @@
import useCollectionStore from "@/store/collections";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import {
faFolder,
faBox,
faHashtag,
faChartSimple,
faChevronDown,
faLink,
} from "@fortawesome/free-solid-svg-icons";
import useTagStore from "@/store/tags";
import Link from "next/link";
import { useRouter } from "next/router";
import { useEffect, useState } from "react";
import { Disclosure, Transition } from "@headlessui/react";
export default function Sidebar({ className }: { className?: string }) {
const [tagDisclosure, setTagDisclosure] = useState<boolean>(() => {
const storedValue = localStorage.getItem("tagDisclosure");
return storedValue ? storedValue === "true" : true;
});
const [collectionDisclosure, setCollectionDisclosure] = useState<boolean>(
() => {
const storedValue = localStorage.getItem("collectionDisclosure");
return storedValue ? storedValue === "true" : true;
}
);
const { collections } = useCollectionStore();
const { tags } = useTagStore();
const router = useRouter();
const [active, setActive] = useState("");
useEffect(() => {
localStorage.setItem("tagDisclosure", tagDisclosure ? "true" : "false");
}, [tagDisclosure]);
useEffect(() => {
localStorage.setItem(
"collectionDisclosure",
collectionDisclosure ? "true" : "false"
);
}, [collectionDisclosure]);
useEffect(() => {
setActive(router.asPath);
}, [router, collections]);
return (
<div
className={`bg-gray-100 h-screen w-64 xl:w-80 overflow-y-auto border-solid border-r-sky-100 px-2 border z-20 ${className}`}
>
<p className="p-2 text-sky-500 font-bold text-2xl my-2 leading-4">
Linkwarden
</p>
<div className="flex flex-col gap-1">
<Link href="/dashboard">
<div
className={`${
active === "/dashboard"
? "bg-sky-200"
: "hover:bg-slate-200 bg-gray-100"
} outline-sky-100 outline-1 duration-100 py-1 px-2 rounded-md cursor-pointer flex items-center gap-2`}
>
<FontAwesomeIcon
icon={faChartSimple}
className={`w-6 h-6 drop-shadow text-sky-500`}
/>
<p className="text-sky-600">Dashboard</p>
</div>
</Link>
<Link href="/links">
<div
className={`${
active === "/links"
? "bg-sky-200"
: "hover:bg-slate-200 bg-gray-100"
} outline-sky-100 outline-1 duration-100 py-1 px-2 rounded-md cursor-pointer flex items-center gap-2`}
>
<FontAwesomeIcon
icon={faLink}
className={`w-6 h-6 drop-shadow text-sky-500`}
/>
<p className="text-sky-600">All Links</p>
</div>
</Link>
<Link href="/collections">
<div
className={`${
active === "/collections" ? "bg-sky-200" : "hover:bg-slate-200"
} outline-sky-100 outline-1 duration-100 py-1 px-2 rounded-md cursor-pointer flex items-center gap-2`}
>
<FontAwesomeIcon
icon={faBox}
className={`w-6 h-6 drop-shadow text-sky-500`}
/>
<p className="text-sky-600">All Collections</p>
</div>
</Link>
</div>
<Disclosure defaultOpen={collectionDisclosure}>
<Disclosure.Button
onClick={() => {
setCollectionDisclosure(!collectionDisclosure);
}}
className="flex items-center justify-between text-sm w-full text-left mb-2 pl-2 font-bold text-gray-500 mt-5"
>
<p>Collections</p>
<FontAwesomeIcon
icon={faChevronDown}
className={`w-3 h-3 ${
collectionDisclosure ? "rotate-reverse" : "rotate"
}`}
/>
</Disclosure.Button>
<Transition
enter="transition duration-100 ease-out"
enterFrom="transform opacity-0 -translate-y-3"
enterTo="transform opacity-100 translate-y-0"
leave="transition duration-100 ease-out"
leaveFrom="transform opacity-100 translate-y-0"
leaveTo="transform opacity-0 -translate-y-3"
>
<Disclosure.Panel className="flex flex-col gap-1">
{collections
.sort((a, b) => a.name.localeCompare(b.name))
.map((e, i) => {
return (
<Link key={i} href={`/collections/${e.id}`}>
<div
className={`${
active === `/collections/${e.id}`
? "bg-sky-200"
: "hover:bg-slate-200 bg-gray-100"
} duration-100 py-1 px-2 cursor-pointer flex items-center gap-2 w-full rounded-md h-8 capitalize`}
>
<FontAwesomeIcon
icon={faFolder}
className="w-6 h-6 drop-shadow"
style={{ color: e.color }}
/>
<p className="text-sky-600 truncate w-4/6">{e.name}</p>
</div>
</Link>
);
})}
</Disclosure.Panel>
</Transition>
</Disclosure>
<Disclosure defaultOpen={tagDisclosure}>
<Disclosure.Button
onClick={() => {
setTagDisclosure(!tagDisclosure);
}}
className="flex items-center justify-between text-sm w-full text-left mb-2 pl-2 font-bold text-gray-500 mt-5"
>
<p>Tags</p>
<FontAwesomeIcon
icon={faChevronDown}
className={`w-3 h-3 ${tagDisclosure ? "rotate-reverse" : "rotate"}`}
/>
</Disclosure.Button>
<Transition
enter="transition duration-100 ease-out"
enterFrom="transform opacity-0 -translate-y-3"
enterTo="transform opacity-100 translate-y-0"
leave="transition duration-100 ease-out"
leaveFrom="transform opacity-100 translate-y-0"
leaveTo="transform opacity-0 -translate-y-3"
>
<Disclosure.Panel className="flex flex-col gap-1">
{tags
.sort((a, b) => a.name.localeCompare(b.name))
.map((e, i) => {
return (
<Link key={i} href={`/tags/${e.id}`}>
<div
className={`${
active === `/tags/${e.id}`
? "bg-sky-200"
: "hover:bg-slate-200 bg-gray-100"
} duration-100 py-1 px-2 cursor-pointer flex items-center gap-2 w-full rounded-md h-8`}
>
<FontAwesomeIcon
icon={faHashtag}
className="w-4 h-4 text-sky-500 mt-1"
/>
<p className="text-sky-600 truncate w-4/6">{e.name}</p>
</div>
</Link>
);
})}
</Disclosure.Panel>
</Transition>
</Disclosure>
</div>
);
}

View File

@ -0,0 +1,66 @@
import React, { Dispatch, SetStateAction } from "react";
import ClickAwayHandler from "./ClickAwayHandler";
import RadioButton from "./RadioButton";
import { Sort } from "@/types/global";
type Props = {
sortBy: Sort;
setSort: Dispatch<SetStateAction<Sort>>;
toggleSortDropdown: Function;
};
export default function SortDropdown({
sortBy,
toggleSortDropdown,
setSort,
}: Props) {
return (
<ClickAwayHandler
onClickOutside={(e: Event) => {
const target = e.target as HTMLInputElement;
if (target.id !== "sort-dropdown") toggleSortDropdown();
}}
className="absolute top-8 right-0 border border-sky-100 shadow-md bg-gray-50 rounded-md p-2 z-10 w-48"
>
<p className="mb-2 text-sky-900 text-center font-semibold">Sort by</p>
<div className="flex flex-col gap-2">
<RadioButton
label="Date (Newest First)"
state={sortBy === Sort.DateNewestFirst}
onClick={() => setSort(Sort.DateNewestFirst)}
/>
<RadioButton
label="Date (Oldest First)"
state={sortBy === Sort.DateOldestFirst}
onClick={() => setSort(Sort.DateOldestFirst)}
/>
<RadioButton
label="Name (A-Z)"
state={sortBy === Sort.NameAZ}
onClick={() => setSort(Sort.NameAZ)}
/>
<RadioButton
label="Name (Z-A)"
state={sortBy === Sort.NameZA}
onClick={() => setSort(Sort.NameZA)}
/>
<RadioButton
label="Description (A-Z)"
state={sortBy === Sort.DescriptionAZ}
onClick={() => setSort(Sort.DescriptionAZ)}
/>
<RadioButton
label="Description (Z-A)"
state={sortBy === Sort.DescriptionZA}
onClick={() => setSort(Sort.DescriptionZA)}
/>
</div>
</ClickAwayHandler>
);
}

View File

@ -0,0 +1,34 @@
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { IconDefinition } from "@fortawesome/free-regular-svg-icons";
type Props = {
onClick: Function;
icon?: IconDefinition;
label: string;
loading: boolean;
className?: string;
};
export default function SubmitButton({
onClick,
icon,
label,
loading,
className,
}: Props) {
return (
<div
className={`text-white flex items-center gap-2 py-2 px-5 rounded-md text-lg tracking-wide select-none font-semibold duration-100 w-fit ${
loading
? "bg-sky-400 cursor-auto"
: "bg-sky-500 hover:bg-sky-400 cursor-pointer"
} ${className}`}
onClick={() => {
if (!loading) onClick();
}}
>
{icon && <FontAwesomeIcon icon={icon} className="h-5" />}
<p className="text-center w-full">{label}</p>
</div>
);
}

View File

@ -0,0 +1,25 @@
import { useState, useEffect } from "react";
const useDetectPageBottom = () => {
const [reachedBottom, setReachedBottom] = useState<boolean>(false);
useEffect(() => {
const handleScroll = () => {
const offsetHeight = document.documentElement.offsetHeight;
const innerHeight = window.innerHeight;
const scrollTop = document.documentElement.scrollTop;
const hasReachedBottom = offsetHeight - (innerHeight + scrollTop) <= 100;
setReachedBottom(hasReachedBottom);
};
window.addEventListener("scroll", handleScroll);
return () => window.removeEventListener("scroll", handleScroll);
}, []);
return reachedBottom;
};
export default useDetectPageBottom;

23
hooks/useInitialData.tsx Normal file
View File

@ -0,0 +1,23 @@
import useCollectionStore from "@/store/collections";
import { useEffect } from "react";
import { useSession } from "next-auth/react";
import useTagStore from "@/store/tags";
import useLinkStore from "@/store/links";
import useAccountStore from "@/store/account";
export default function useInitialData() {
const { status, data } = useSession();
const { setCollections } = useCollectionStore();
const { setTags } = useTagStore();
// const { setLinks } = useLinkStore();
const { setAccount } = useAccountStore();
useEffect(() => {
if (status === "authenticated") {
setCollections();
setTags();
// setLinks();
setAccount(data.user.email as string);
}
}, [status]);
}

53
hooks/useLinks.tsx Normal file
View File

@ -0,0 +1,53 @@
import { LinkRequestQuery } from "@/types/global";
import { useEffect } from "react";
import useDetectPageBottom from "./useDetectPageBottom";
import { useRouter } from "next/router";
import useLinkStore from "@/store/links";
export default function useLinks(
{
sort,
searchFilter,
searchQuery,
pinnedOnly,
collectionId,
tagId,
}: Omit<LinkRequestQuery, "cursor"> = { sort: 0 }
) {
const { links, setLinks, resetLinks } = useLinkStore();
const router = useRouter();
const hasReachedBottom = useDetectPageBottom();
const getLinks = async (isInitialCall: boolean, cursor?: number) => {
const requestBody: LinkRequestQuery = {
cursor,
sort,
searchFilter,
searchQuery,
pinnedOnly,
collectionId,
tagId,
};
const encodedData = encodeURIComponent(JSON.stringify(requestBody));
const response = await fetch(
`/api/routes/links?body=${encodeURIComponent(encodedData)}`
);
const data = await response.json();
if (response.ok) setLinks(data.response, isInitialCall);
};
useEffect(() => {
resetLinks();
getLinks(true);
}, [router, sort, searchFilter]);
useEffect(() => {
if (hasReachedBottom) getLinks(false, links?.at(-1)?.id);
}, [hasReachedBottom]);
}

32
hooks/usePermissions.tsx Normal file
View File

@ -0,0 +1,32 @@
import useAccountStore from "@/store/account";
import useCollectionStore from "@/store/collections";
import { Member } from "@/types/global";
import { useEffect, useState } from "react";
export default function usePermissions(collectionId: number) {
const { collections } = useCollectionStore();
const { account } = useAccountStore();
const [permissions, setPermissions] = useState<Member | true>();
useEffect(() => {
const collection = collections.find((e) => e.id === collectionId);
if (collection) {
let getPermission: Member | undefined = collection.members.find(
(e) => e.userId === account.id
);
if (
getPermission?.canCreate === false &&
getPermission?.canUpdate === false &&
getPermission?.canDelete === false
)
getPermission = undefined;
setPermissions(account.id === collection.ownerId || getPermission);
}
}, [account, collections, collectionId]);
return permissions;
}

30
hooks/useRedirect.tsx Normal file
View File

@ -0,0 +1,30 @@
import { useEffect, useState } from "react";
import { useSession } from "next-auth/react";
import { useRouter } from "next/router";
export default function useRedirect() {
const router = useRouter();
const { status } = useSession();
const [redirect, setRedirect] = useState(true);
useEffect(() => {
if (
status === "authenticated" &&
(router.pathname === "/login" || router.pathname === "/register")
) {
router.push("/").then(() => {
setRedirect(false);
});
} else if (
status === "unauthenticated" &&
!(router.pathname === "/login" || router.pathname === "/register")
) {
router.push("/login").then(() => {
setRedirect(false);
});
} else if (status === "loading") setRedirect(true);
else setRedirect(false);
}, [status]);
return redirect;
}

56
hooks/useSort.tsx Normal file
View File

@ -0,0 +1,56 @@
import {
CollectionIncludingMembersAndLinkCount,
LinkIncludingShortenedCollectionAndTags,
Sort,
} from "@/types/global";
import { SetStateAction, useEffect } from "react";
type Props<
T extends
| CollectionIncludingMembersAndLinkCount
| LinkIncludingShortenedCollectionAndTags
> = {
sortBy: Sort;
data: T[];
setData: (value: SetStateAction<T[]>) => void;
};
export default function useSort<
T extends
| CollectionIncludingMembersAndLinkCount
| LinkIncludingShortenedCollectionAndTags
>({ sortBy, data, setData }: Props<T>) {
useEffect(() => {
const dataArray = [...data];
if (sortBy === Sort.NameAZ)
setData(dataArray.sort((a, b) => a.name.localeCompare(b.name)));
else if (sortBy === Sort.DescriptionAZ)
setData(
dataArray.sort((a, b) => a.description.localeCompare(b.description))
);
else if (sortBy === Sort.NameZA)
setData(dataArray.sort((a, b) => b.name.localeCompare(a.name)));
else if (sortBy === Sort.DescriptionZA)
setData(
dataArray.sort((a, b) => b.description.localeCompare(a.description))
);
else if (sortBy === Sort.DateNewestFirst)
setData(
dataArray.sort(
(a, b) =>
new Date(b.createdAt as string).getTime() -
new Date(a.createdAt as string).getTime()
)
);
else if (sortBy === Sort.DateOldestFirst)
setData(
dataArray.sort(
(a, b) =>
new Date(a.createdAt as string).getTime() -
new Date(b.createdAt as string).getTime()
)
);
}, [sortBy, data]);
}

44
layouts/AuthRedirect.tsx Normal file
View File

@ -0,0 +1,44 @@
import { ReactNode } from "react";
import { useSession } from "next-auth/react";
import Loader from "../components/Loader";
import { useRouter } from "next/router";
import { useEffect, useState } from "react";
import useInitialData from "@/hooks/useInitialData";
interface Props {
children: ReactNode;
}
export default function AuthRedirect({ children }: Props) {
const router = useRouter();
const { status } = useSession();
const [redirect, setRedirect] = useState(true);
useInitialData();
useEffect(() => {
if (!router.pathname.startsWith("/public")) {
if (
status === "authenticated" &&
(router.pathname === "/login" || router.pathname === "/register")
) {
router.push("/").then(() => {
setRedirect(false);
});
} else if (
status === "unauthenticated" &&
!(router.pathname === "/login" || router.pathname === "/register")
) {
router.push("/login").then(() => {
setRedirect(false);
});
} else if (status === "loading") setRedirect(true);
else setRedirect(false);
} else {
setRedirect(false);
}
}, [status]);
if (status !== "loading" && !redirect) return <>{children}</>;
else return <></>;
}

48
layouts/MainLayout.tsx Normal file
View File

@ -0,0 +1,48 @@
import Navbar from "@/components/Navbar";
import Sidebar from "@/components/Sidebar";
import { ReactNode, useEffect } from "react";
import { useSession } from "next-auth/react";
import Loader from "../components/Loader";
import useRedirect from "@/hooks/useRedirect";
import { useRouter } from "next/router";
import ModalManagement from "@/components/ModalManagement";
import useModalStore from "@/store/modals";
interface Props {
children: ReactNode;
}
export default function MainLayout({ children }: Props) {
const { status } = useSession();
const router = useRouter();
const redirect = useRedirect();
const routeExists = router.route === "/_error" ? false : true;
const { modal } = useModalStore();
useEffect(() => {
modal
? (document.body.style.overflow = "hidden")
: (document.body.style.overflow = "auto");
}, [modal]);
if (status === "authenticated" && !redirect && routeExists)
return (
<>
<ModalManagement />
<div className="flex">
<div className="hidden lg:block">
<Sidebar className="fixed" />
</div>
<div className="w-full lg:ml-64 xl:ml-80">
<Navbar />
{children}
</div>
</div>
</>
);
else if ((status === "unauthenticated" && !redirect) || !routeExists)
return <>{children}</>;
else return <></>;
}

72
lib/api/archive.ts Normal file
View File

@ -0,0 +1,72 @@
import { Page } from "puppeteer";
import { prisma } from "@/lib/api/db";
import puppeteer from "puppeteer-extra";
import AdblockerPlugin from "puppeteer-extra-plugin-adblocker";
import StealthPlugin from "puppeteer-extra-plugin-stealth";
export default async function archive(
url: string,
collectionId: number,
linkId: number
) {
const archivePath = `data/archives/${collectionId}/${linkId}`;
const browser = await puppeteer.launch();
try {
puppeteer.use(AdblockerPlugin()).use(StealthPlugin());
const page = await browser.newPage();
await page.goto(url, { waitUntil: "domcontentloaded", timeout: 300000 });
await page.setViewport({ width: 1080, height: 1024 });
await autoScroll(page);
const linkExists = await prisma.link.findFirst({
where: {
id: linkId,
},
});
if (linkExists) {
await Promise.all([
page.pdf({
path: archivePath + ".pdf",
width: "1366px",
height: "1931px",
printBackground: true,
margin: { top: "15px", bottom: "15px" },
}),
page.screenshot({ fullPage: true, path: archivePath + ".png" }),
]);
}
await browser.close();
} catch (err) {
console.log(err);
await browser.close();
}
}
const autoScroll = async (page: Page) => {
await page.evaluate(async () => {
await new Promise<void>((resolve, reject) => {
let totalHeight = 0;
let distance = 100;
let scrollDown = setInterval(() => {
let scrollHeight = document.body.scrollHeight;
window.scrollBy(0, distance);
totalHeight += distance;
if (totalHeight >= scrollHeight) {
clearInterval(scrollDown);
window.scroll(0, 0);
resolve();
}
}, 100);
});
await new Promise((r) => setTimeout(r, 2000));
});
};

View File

@ -0,0 +1,75 @@
import { prisma } from "@/lib/api/db";
import getPermission from "@/lib/api/getPermission";
import { Collection, UsersAndCollections } from "@prisma/client";
import fs from "fs";
export default async function deleteCollection(
collection: { id: number },
userId: number
) {
const collectionId = collection.id;
if (!collectionId)
return { response: "Please choose a valid collection.", status: 401 };
const collectionIsAccessible = (await getPermission(userId, collectionId)) as
| (Collection & {
members: UsersAndCollections[];
})
| null;
const memberHasAccess = collectionIsAccessible?.members.some(
(e: UsersAndCollections) => e.userId === userId
);
if (collectionIsAccessible?.ownerId !== userId && memberHasAccess) {
// Remove relation/Leave collection
const deletedUsersAndCollectionsRelation =
await prisma.usersAndCollections.delete({
where: {
userId_collectionId: {
userId: userId,
collectionId: collectionId,
},
},
});
return { response: deletedUsersAndCollectionsRelation, status: 200 };
} else if (collectionIsAccessible?.ownerId !== userId) {
return { response: "Collection is not accessible.", status: 401 };
}
const deletedCollection = await prisma.$transaction(async () => {
await prisma.usersAndCollections.deleteMany({
where: {
collection: {
id: collectionId,
},
},
});
await prisma.link.deleteMany({
where: {
collection: {
id: collectionId,
},
},
});
try {
fs.rmdirSync(`data/archives/${collectionId}`, { recursive: true });
} catch (error) {
console.log(
"Collection's archive directory wasn't deleted most likely because it didn't exist..."
);
}
return await prisma.collection.delete({
where: {
id: collectionId,
},
});
});
return { response: deletedCollection, status: 200 };
}

View File

@ -0,0 +1,29 @@
import { prisma } from "@/lib/api/db";
export default async function getCollection(userId: number) {
const collections = await prisma.collection.findMany({
where: {
OR: [
{ ownerId: userId },
{ members: { some: { user: { id: userId } } } },
],
},
include: {
_count: {
select: { links: true },
},
members: {
include: {
user: {
select: {
email: true,
name: true,
},
},
},
},
},
});
return { response: collections, status: 200 };
}

View File

@ -0,0 +1,74 @@
import { prisma } from "@/lib/api/db";
import { CollectionIncludingMembersAndLinkCount } from "@/types/global";
import { existsSync, mkdirSync } from "fs";
export default async function postCollection(
collection: CollectionIncludingMembersAndLinkCount,
userId: number
) {
if (!collection || collection.name.trim() === "")
return {
response: "Please enter a valid collection.",
status: 400,
};
const findCollection = await prisma.user.findUnique({
where: {
id: userId,
},
select: {
collections: {
where: {
name: collection.name,
},
},
},
});
const checkIfCollectionExists = findCollection?.collections[0];
if (checkIfCollectionExists)
return { response: "Collection already exists.", status: 400 };
const newCollection = await prisma.collection.create({
data: {
owner: {
connect: {
id: userId,
},
},
name: collection.name,
description: collection.description,
color: collection.color,
members: {
create: collection.members.map((e) => ({
user: { connect: { email: e.user.email } },
canCreate: e.canCreate,
canUpdate: e.canUpdate,
canDelete: e.canDelete,
})),
},
},
include: {
_count: {
select: { links: true },
},
members: {
include: {
user: {
select: {
email: true,
name: true,
},
},
},
},
},
});
const collectionPath = `data/archives/${newCollection.id}`;
if (!existsSync(collectionPath))
mkdirSync(collectionPath, { recursive: true });
return { response: newCollection, status: 200 };
}

View File

@ -0,0 +1,73 @@
import { prisma } from "@/lib/api/db";
import { CollectionIncludingMembersAndLinkCount } from "@/types/global";
import getPermission from "@/lib/api/getPermission";
import { Collection, UsersAndCollections } from "@prisma/client";
export default async function updateCollection(
collection: CollectionIncludingMembersAndLinkCount,
userId: number
) {
if (!collection.id)
return { response: "Please choose a valid collection.", status: 401 };
const collectionIsAccessible = (await getPermission(
userId,
collection.id
)) as
| (Collection & {
members: UsersAndCollections[];
})
| null;
if (!(collectionIsAccessible?.ownerId === userId))
return { response: "Collection is not accessible.", status: 401 };
const updatedCollection = await prisma.$transaction(async () => {
await prisma.usersAndCollections.deleteMany({
where: {
collection: {
id: collection.id,
},
},
});
return await prisma.collection.update({
where: {
id: collection.id,
},
data: {
name: collection.name,
description: collection.description,
color: collection.color,
isPublic: collection.isPublic,
members: {
create: collection.members.map((e) => ({
user: { connect: { email: e.user.email } },
canCreate: e.canCreate,
canUpdate: e.canUpdate,
canDelete: e.canDelete,
})),
},
},
include: {
_count: {
select: { links: true },
},
members: {
include: {
user: {
select: {
email: true,
name: true,
id: true,
},
},
},
},
},
});
});
return { response: updatedCollection, status: 200 };
}

View File

@ -0,0 +1,45 @@
import { prisma } from "@/lib/api/db";
import { LinkIncludingShortenedCollectionAndTags } from "@/types/global";
import fs from "fs";
import { Collection, Link, UsersAndCollections } from "@prisma/client";
import getPermission from "@/lib/api/getPermission";
export default async function deleteLink(
link: LinkIncludingShortenedCollectionAndTags,
userId: number
) {
if (!link || !link.collectionId)
return { response: "Please choose a valid link.", status: 401 };
const collectionIsAccessible = (await getPermission(
userId,
link.collectionId
)) as
| (Collection & {
members: UsersAndCollections[];
})
| null;
const memberHasAccess = collectionIsAccessible?.members.some(
(e: UsersAndCollections) => e.userId === userId && e.canDelete
);
if (!(collectionIsAccessible?.ownerId === userId || memberHasAccess))
return { response: "Collection is not accessible.", status: 401 };
const deleteLink: Link = await prisma.link.delete({
where: {
id: link.id,
},
});
fs.unlink(`data/archives/${link.collectionId}/${link.id}.pdf`, (err) => {
if (err) console.log(err);
});
fs.unlink(`data/archives/${link.collectionId}/${link.id}.png`, (err) => {
if (err) console.log(err);
});
return { response: deleteLink, status: 200 };
}

View File

@ -0,0 +1,161 @@
import { prisma } from "@/lib/api/db";
import { LinkRequestQuery, Sort } from "@/types/global";
export default async function getLink(userId: number, body: string) {
const query: LinkRequestQuery = JSON.parse(decodeURIComponent(body));
console.log(query);
// Sorting logic
let order: any;
if (query.sort === Sort.DateNewestFirst)
order = {
createdAt: "desc",
};
else if (query.sort === Sort.DateOldestFirst)
order = {
createdAt: "asc",
};
else if (query.sort === Sort.NameAZ)
order = {
name: "asc",
};
else if (query.sort === Sort.NameZA)
order = {
name: "desc",
};
else if (query.sort === Sort.DescriptionAZ)
order = {
name: "asc",
};
else if (query.sort === Sort.DescriptionZA)
order = {
name: "desc",
};
const links = await prisma.link.findMany({
take: Number(process.env.PAGINATION_TAKE_COUNT),
skip: query.cursor ? 1 : undefined,
cursor: query.cursor
? {
id: query.cursor,
}
: undefined,
where: {
[query.searchQuery ? "OR" : "AND"]: [
{
pinnedBy: query.pinnedOnly ? { some: { id: userId } } : undefined,
},
{
name: {
contains:
query.searchQuery && query.searchFilter?.name
? query.searchQuery
: undefined,
mode: "insensitive",
},
},
{
url: {
contains:
query.searchQuery && query.searchFilter?.url
? query.searchQuery
: undefined,
mode: "insensitive",
},
},
{
description: {
contains:
query.searchQuery && query.searchFilter?.description
? query.searchQuery
: undefined,
mode: "insensitive",
},
},
{
collection: {
id: query.collectionId ? query.collectionId : undefined, // If collectionId was defined, filter by collection
name:
query.searchQuery && query.searchFilter?.collection
? {
contains: query.searchQuery,
mode: "insensitive",
}
: undefined,
OR: query.searchQuery
? undefined
: [
{
ownerId: userId,
},
{
members: {
some: {
userId,
},
},
},
],
},
},
{
tags:
query.searchQuery && !query.searchFilter?.tags
? undefined
: {
some: query.tagId
? {
// If tagId was defined, filter by tag
id: query.tagId,
name:
query.searchQuery && query.searchFilter?.tags
? {
contains: query.searchQuery,
mode: "insensitive",
}
: undefined,
OR: [
{ ownerId: userId }, // Tags owned by the user
{
links: {
some: {
name: {
contains:
query.searchQuery &&
query.searchFilter?.tags
? query.searchQuery
: undefined,
mode: "insensitive",
},
collection: {
members: {
some: {
userId, // Tags from collections where the user is a member
},
},
},
},
},
},
],
}
: undefined,
},
},
],
},
include: {
tags: true,
collection: true,
pinnedBy: {
where: { id: userId },
select: { id: true },
},
},
orderBy: order || {
createdAt: "desc",
},
});
return { response: links, status: 200 };
}

View File

@ -0,0 +1,94 @@
import { prisma } from "@/lib/api/db";
import { LinkIncludingShortenedCollectionAndTags } from "@/types/global";
import getTitle from "../../getTitle";
import archive from "../../archive";
import { Collection, Link, UsersAndCollections } from "@prisma/client";
import getPermission from "@/lib/api/getPermission";
import { existsSync, mkdirSync } from "fs";
export default async function postLink(
link: LinkIncludingShortenedCollectionAndTags,
userId: number
) {
link.collection.name = link.collection.name.trim();
if (!link.name) {
return { response: "Please enter a valid name for the link.", status: 400 };
} else if (!link.collection.name) {
return { response: "Please enter a valid collection.", status: 400 };
}
if (link.collection.id) {
const collectionIsAccessible = (await getPermission(
userId,
link.collection.id
)) as
| (Collection & {
members: UsersAndCollections[];
})
| null;
const memberHasAccess = collectionIsAccessible?.members.some(
(e: UsersAndCollections) => e.userId === userId && e.canCreate
);
if (!(collectionIsAccessible?.ownerId === userId || memberHasAccess))
return { response: "Collection is not accessible.", status: 401 };
} else {
link.collection.ownerId = userId;
}
const description =
link.description && link.description !== ""
? link.description
: await getTitle(link.url);
const newLink: Link = await prisma.link.create({
data: {
name: link.name,
url: link.url,
description,
collection: {
connectOrCreate: {
where: {
name_ownerId: {
ownerId: link.collection.ownerId,
name: link.collection.name,
},
},
create: {
name: link.collection.name,
ownerId: userId,
},
},
},
tags: {
connectOrCreate: link.tags.map((tag) => ({
where: {
name_ownerId: {
name: tag.name,
ownerId: link.collection.ownerId,
},
},
create: {
name: tag.name,
owner: {
connect: {
id: link.collection.ownerId,
},
},
},
})),
},
},
include: { tags: true, collection: true },
});
const collectionPath = `data/archives/${newLink.collectionId}`;
if (!existsSync(collectionPath))
mkdirSync(collectionPath, { recursive: true });
archive(newLink.url, newLink.collectionId, newLink.id);
return { response: newLink, status: 200 };
}

View File

@ -0,0 +1,103 @@
import { prisma } from "@/lib/api/db";
import { LinkIncludingShortenedCollectionAndTags } from "@/types/global";
import { Collection, Link, UsersAndCollections } from "@prisma/client";
import getPermission from "@/lib/api/getPermission";
export default async function updateLink(
link: LinkIncludingShortenedCollectionAndTags,
userId: number
) {
if (!link || !link.collection.id)
return {
response: "Please choose a valid link and collection.",
status: 401,
};
const targetLink = (await getPermission(
userId,
link.collection.id,
link.id
)) as
| (Link & {
collection: Collection & {
members: UsersAndCollections[];
};
})
| null;
const memberHasAccess = targetLink?.collection.members.some(
(e: UsersAndCollections) => e.userId === userId && e.canUpdate
);
const isCollectionOwner =
targetLink?.collection.ownerId === link.collection.ownerId &&
link.collection.ownerId === userId &&
targetLink?.collection.ownerId === userId;
// Makes sure collection members (non-owners) cannot move a link to/from a collection.
if (!isCollectionOwner)
return {
response: "You can't move a link to/from a collection you don't own.",
status: 401,
};
else if (targetLink?.collection.ownerId !== userId && !memberHasAccess)
return {
response: "Collection is not accessible.",
status: 401,
};
else {
const updatedLink = await prisma.link.update({
where: {
id: link.id,
},
data: {
name: link.name,
description: link.description,
collection:
targetLink?.collection.ownerId === link.collection.ownerId &&
link.collection.ownerId === userId
? {
connect: {
id: link.collection.id,
},
}
: undefined,
tags: {
set: [],
connectOrCreate: link.tags.map((tag) => ({
where: {
name_ownerId: {
name: tag.name,
ownerId: link.collection.ownerId,
},
},
create: {
name: tag.name,
owner: {
connect: {
id: link.collection.ownerId,
},
},
},
})),
},
pinnedBy:
link?.pinnedBy && link.pinnedBy[0]
? { connect: { id: userId } }
: { disconnect: { id: userId } },
},
include: {
tags: true,
collection: true,
pinnedBy: isCollectionOwner
? {
where: { id: userId },
select: { id: true },
}
: undefined,
},
});
return { response: updatedLink, status: 200 };
}
}

View File

@ -0,0 +1,45 @@
import { prisma } from "@/lib/api/db";
import { PublicLinkRequestQuery } from "@/types/global";
export default async function getCollection(body: string) {
const query: PublicLinkRequestQuery = JSON.parse(decodeURIComponent(body));
console.log(query);
let data;
const collection = await prisma.collection.findFirst({
where: {
id: query.collectionId,
isPublic: true,
},
});
if (collection) {
const links = await prisma.link.findMany({
take: Number(process.env.PAGINATION_TAKE_COUNT),
skip: query.cursor ? 1 : undefined,
cursor: query.cursor
? {
id: query.cursor,
}
: undefined,
where: {
collection: {
id: query.collectionId,
},
},
include: {
tags: true,
},
orderBy: {
createdAt: "desc",
},
});
data = { ...collection, links: [...links] };
return { response: data, status: 200 };
} else {
return { response: "Collection not found...", status: 400 };
}
}

View File

@ -0,0 +1,41 @@
import { prisma } from "@/lib/api/db";
export default async function getTags(userId: number) {
// Remove empty tags
await prisma.tag.deleteMany({
where: {
ownerId: userId,
links: {
none: {},
},
},
});
const tags = await prisma.tag.findMany({
where: {
OR: [
{ ownerId: userId }, // Tags owned by the user
{
links: {
some: {
collection: {
members: {
some: {
userId, // Tags from collections where the user is a member
},
},
},
},
},
},
],
},
// orderBy: {
// links: {
// _count: "desc",
// },
// },
});
return { response: tags, status: 200 };
}

View File

@ -0,0 +1,37 @@
import { prisma } from "@/lib/api/db";
export default async function getUser(
lookupEmail: string,
isSelf: boolean,
userEmail: string
) {
const user = await prisma.user.findUnique({
where: {
email: lookupEmail,
},
});
if (!user) return { response: "User not found.", status: 404 };
if (
!isSelf &&
user?.isPrivate &&
!user.whitelistedUsers.includes(userEmail)
) {
return { response: "This profile is private.", status: 401 };
}
const { password, ...unsensitiveInfo } = user;
const data = isSelf
? // If user is requesting its own data
unsensitiveInfo
: {
// If user is requesting someone elses data
id: unsensitiveInfo.id,
name: unsensitiveInfo.name,
email: unsensitiveInfo.email,
};
return { response: data || null, status: 200 };
}

View File

@ -0,0 +1,94 @@
import { prisma } from "@/lib/api/db";
import { AccountSettings } from "@/types/global";
import fs from "fs";
import path from "path";
import bcrypt from "bcrypt";
export default async function updateUser(
user: AccountSettings,
userId: number
) {
// Password Settings
if (user.newPassword && user.oldPassword) {
const targetUser = await prisma.user.findUnique({
where: {
id: user.id,
},
});
if (
targetUser &&
bcrypt.compareSync(user.oldPassword, targetUser.password)
) {
const saltRounds = 10;
const newHashedPassword = bcrypt.hashSync(user.newPassword, saltRounds);
await prisma.user.update({
where: {
id: userId,
},
data: {
password: newHashedPassword,
},
});
} else {
return { response: "Old password is incorrect.", status: 400 };
}
}
// Avatar Settings
const profilePic = user.profilePic;
if (profilePic.startsWith("data:image/jpeg;base64")) {
if (user.profilePic.length < 1572864) {
try {
const filePath = path.join(
process.cwd(),
`data/uploads/avatar/${userId}.jpg`
);
const base64Data = profilePic.replace(/^data:image\/jpeg;base64,/, "");
fs.writeFile(filePath, base64Data, "base64", function (err) {
console.log(err);
});
} catch (err) {
console.log("Error saving image:", err);
}
} else {
console.log("A file larger than 1.5MB was uploaded.");
return {
response: "A file larger than 1.5MB was uploaded.",
status: 400,
};
}
} else if (profilePic == "") {
fs.unlink(`data/uploads/avatar/${userId}.jpg`, (err) => {
if (err) console.log(err);
});
}
// Other settings
const updatedUser = await prisma.user.update({
where: {
id: userId,
},
data: {
name: user.name,
email: user.email,
isPrivate: user.isPrivate,
whitelistedUsers: user.whitelistedUsers,
},
});
const { password, ...userInfo } = updatedUser;
const response: Omit<AccountSettings, "password"> = {
...userInfo,
profilePic: `/api/avatar/${userInfo.id}?${Date.now()}`,
};
return { response, status: 200 };
}

18
lib/api/db.ts Normal file
View File

@ -0,0 +1,18 @@
import { PrismaClient } from "@prisma/client";
const globalForPrisma = global as unknown as { prisma: PrismaClient };
export const prisma =
globalForPrisma.prisma ||
new PrismaClient({
log: ["query"],
});
if (process.env.NODE_ENV !== "production") globalForPrisma.prisma = prisma;
if (process.env.NODE_ENV !== "production")
prisma.$on("query" as any, (e: any) => {
console.log("Query: " + e.query);
console.log("Params: " + e.params);
console.log("\x1b[31m", `Duration: ${e.duration}ms`, "\x1b[0m"); // For benchmarking
});

34
lib/api/getPermission.ts Normal file
View File

@ -0,0 +1,34 @@
import { prisma } from "@/lib/api/db";
export default async function getPermission(
userId: number,
collectionId: number,
linkId?: number
) {
if (linkId) {
const link = await prisma.link.findUnique({
where: {
id: linkId,
},
include: {
collection: {
include: { members: true },
},
},
});
return link;
} else {
const check = await prisma.collection.findFirst({
where: {
AND: {
id: collectionId,
OR: [{ ownerId: userId }, { members: { some: { userId } } }],
},
},
include: { members: true },
});
return check;
}
}

13
lib/api/getTitle.ts Normal file
View File

@ -0,0 +1,13 @@
export default async function getTitle(url: string) {
try {
const response = await fetch(url);
const text = await response.text();
// regular expression to find the <title> tag
let match = text.match(/<title.*>([^<]*)<\/title>/);
if (match) return match[1] + " [AUTO GENERATED]";
else return "";
} catch (err) {
console.log(err);
}
}

View File

@ -0,0 +1,45 @@
import { CollectionIncludingMembersAndLinkCount, Member } from "@/types/global";
import getPublicUserDataByEmail from "./getPublicUserDataByEmail";
import { toast } from "react-hot-toast";
const addMemberToCollection = async (
ownerEmail: string,
memberEmail: string,
collection: CollectionIncludingMembersAndLinkCount,
setMember: (newMember: Member) => null | undefined
) => {
const checkIfMemberAlreadyExists = collection.members.find((e) => {
const email = e.user.email;
return email === memberEmail;
});
if (
// no duplicate members
!checkIfMemberAlreadyExists &&
// member can't be empty
memberEmail.trim() !== "" &&
// member can't be the owner
memberEmail.trim() !== ownerEmail
) {
// Lookup, get data/err, list ...
const user = await getPublicUserDataByEmail(memberEmail.trim());
if (user.email) {
setMember({
collectionId: collection.id,
userId: user.id,
canCreate: false,
canUpdate: false,
canDelete: false,
user: {
name: user.name,
email: user.email,
},
});
}
} else if (checkIfMemberAlreadyExists) toast.error("User already exists.");
else if (memberEmail.trim() === ownerEmail)
toast.error("You are already the collection owner.");
};
export default addMemberToCollection;

View File

@ -0,0 +1,4 @@
export default async function avatarExists(fileUrl: string): Promise<boolean> {
const response = await fetch(fileUrl, { method: "HEAD" });
return !(response.headers.get("content-type") === "text/plain");
}

View File

@ -0,0 +1,35 @@
import {
PublicCollectionIncludingLinks,
PublicLinkRequestQuery,
} from "@/types/global";
import { Dispatch, SetStateAction } from "react";
const getPublicCollectionData = async (
collectionId: number,
prevData: PublicCollectionIncludingLinks,
setData: Dispatch<SetStateAction<PublicCollectionIncludingLinks | undefined>>
) => {
const requestBody: PublicLinkRequestQuery = {
cursor: prevData?.links?.at(-1)?.id,
collectionId,
};
const encodedData = encodeURIComponent(JSON.stringify(requestBody));
const res = await fetch(
"/api/public/routes/collections?body=" + encodeURIComponent(encodedData)
);
const data = await res.json();
prevData
? setData({
...data.response,
links: [...prevData.links, ...data.response.links],
})
: setData(data.response);
return data;
};
export default getPublicCollectionData;

View File

@ -0,0 +1,11 @@
import { toast } from "react-hot-toast";
export default async function getPublicUserDataByEmail(email: string) {
const response = await fetch(`/api/routes/users?email=${email}`);
const data = await response.json();
if (!response.ok) toast.error(data.response);
return data.response;
}

8
lib/client/isValidUrl.ts Normal file
View File

@ -0,0 +1,8 @@
export default function isValidUrl(string: string) {
try {
new URL(string);
return true;
} catch (err) {
return false;
}
}

17
lib/client/resizeImage.ts Normal file
View File

@ -0,0 +1,17 @@
import Resizer from "react-image-file-resizer";
export const resizeImage = (file: File): Promise<Blob> =>
new Promise<Blob>((resolve) => {
Resizer.imageFileResizer(
file,
150, // target width
150, // target height
"JPEG", // output format
100, // quality
0, // rotation
(uri: any) => {
resolve(uri as Blob);
},
"blob" // output type
);
});

9
next.config.js Normal file
View File

@ -0,0 +1,9 @@
/** @type {import('next').NextConfig} */
const nextConfig = {
reactStrictMode: true,
images: {
domains: ["t2.gstatic.com"],
},
};
module.exports = nextConfig;

56
package.json Normal file
View File

@ -0,0 +1,56 @@
{
"name": "linkwarden",
"version": "3.0.0",
"main": "index.js",
"repository": "https://github.com/Daniel31x13/link-warden.git",
"author": "Daniel31X13 <daniel31x13@gmail.com>",
"license": "AGPL-3.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint"
},
"dependencies": {
"@fortawesome/fontawesome-svg-core": "^6.3.0",
"@fortawesome/free-regular-svg-icons": "^6.3.0",
"@fortawesome/free-solid-svg-icons": "^6.3.0",
"@fortawesome/react-fontawesome": "^0.2.0",
"@headlessui/react": "^1.7.15",
"@next/font": "13.1.6",
"@prisma/client": "^4.9.0",
"@types/crypto-js": "^4.1.1",
"@types/node": "18.11.18",
"@types/react": "18.0.27",
"@types/react-dom": "18.0.10",
"bcrypt": "^5.1.0",
"colorthief": "^2.4.0",
"crypto-js": "^4.1.1",
"eslint": "8.33.0",
"eslint-config-next": "13.1.6",
"multer": "^1.4.5-lts.1",
"next": "13.1.6",
"next-auth": "^4.22.1",
"puppeteer": "^19.8.0",
"puppeteer-extra": "^3.3.6",
"puppeteer-extra-plugin-adblocker": "^2.13.6",
"puppeteer-extra-plugin-stealth": "^2.11.2",
"react": "18.2.0",
"react-colorful": "^5.6.1",
"react-dom": "18.2.0",
"react-hot-toast": "^2.4.1",
"react-image-file-resizer": "^0.4.8",
"react-select": "^5.7.0",
"typescript": "4.9.4",
"zustand": "^4.3.3"
},
"devDependencies": {
"@types/bcrypt": "^5.0.0",
"@types/multer": "^1.4.7",
"autoprefixer": "^10.4.14",
"postcss": "^8.4.24",
"prisma": "^4.9.0",
"tailwindcss": "^3.3.2"
}
}

44
pages/_app.tsx Normal file
View File

@ -0,0 +1,44 @@
import React from "react";
import "@/styles/globals.css";
import { SessionProvider } from "next-auth/react";
import type { AppProps } from "next/app";
import Head from "next/head";
import AuthRedirect from "@/layouts/AuthRedirect";
import { Toaster } from "react-hot-toast";
export default function App({ Component, pageProps }: AppProps) {
return (
<SessionProvider session={pageProps.session}>
<Head>
<title>Linkwarden</title>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link
rel="apple-touch-icon"
sizes="180x180"
href="/apple-touch-icon.png"
/>
<link
rel="icon"
type="image/png"
sizes="32x32"
href="/favicon-32x32.png"
/>
<link
rel="icon"
type="image/png"
sizes="16x16"
href="/favicon-16x16.png"
/>
<link rel="manifest" href="/site.webmanifest" />
</Head>
<Toaster
position="top-center"
reverseOrder={false}
toastOptions={{ className: "border border-sky-100" }}
/>
<AuthRedirect>
<Component {...pageProps} />
</AuthRedirect>
</SessionProvider>
);
}

13
pages/_document.tsx Normal file
View File

@ -0,0 +1,13 @@
import { Html, Head, Main, NextScript } from "next/document";
export default function Document() {
return (
<Html lang="en">
<Head />
<body>
<Main />
<NextScript />
</body>
</Html>
);
}

View File

@ -0,0 +1,46 @@
import type { NextApiRequest, NextApiResponse } from "next";
import { getServerSession } from "next-auth/next";
import { authOptions } from "pages/api/auth/[...nextauth]";
import path from "path";
import fs from "fs";
import getPermission from "@/lib/api/getPermission";
export default async function Index(req: NextApiRequest, res: NextApiResponse) {
if (!req.query.params)
return res.status(401).json({ response: "Invalid parameters." });
const collectionId = req.query.params[0];
const linkId = req.query.params[1];
const session = await getServerSession(req, res, authOptions);
if (!session?.user?.email)
return res.status(401).json({ response: "You must be logged in." });
const collectionIsAccessible = await getPermission(
session.user.id,
Number(collectionId)
);
if (!collectionIsAccessible)
return res
.status(401)
.json({ response: "You don't have access to this collection." });
const requestedPath = `data/archives/${collectionId}/${linkId}`;
const filePath = path.join(process.cwd(), requestedPath);
const file = fs.existsSync(filePath)
? fs.readFileSync(filePath)
: "File not found, it's possible that the file you're looking for either doesn't exist or hasn't been created yet.";
if (!fs.existsSync(filePath))
res.setHeader("Content-Type", "text/plain").status(404);
else if (filePath.endsWith(".pdf"))
res.setHeader("Content-Type", "application/pdf").status(200);
else if (filePath.endsWith(".png"))
res.setHeader("Content-Type", "image/png").status(200);
return res.send(file);
}

View File

@ -0,0 +1,65 @@
import { prisma } from "@/lib/api/db";
import NextAuth from "next-auth/next";
import CredentialsProvider from "next-auth/providers/credentials";
import { AuthOptions } from "next-auth";
import bcrypt from "bcrypt";
export const authOptions: AuthOptions = {
session: {
strategy: "jwt",
},
providers: [
CredentialsProvider({
type: "credentials",
credentials: {},
async authorize(credentials, req) {
const { email, password } = credentials as {
id: number;
email: string;
password: string;
};
const findUser = await prisma.user.findFirst({
where: {
email: email,
},
});
let passwordMatches: boolean = false;
if (findUser?.password) {
passwordMatches = bcrypt.compareSync(password, findUser.password);
}
if (passwordMatches) {
return {
id: findUser?.id,
name: findUser?.name,
email: findUser?.email,
};
} else return null as any;
},
}),
],
pages: {
signIn: "/login",
},
callbacks: {
session: async ({ session, token }) => {
session.user.id = parseInt(token?.sub as any);
return session;
},
// Using the `...rest` parameter to be able to narrow down the type based on `trigger`
jwt({ token, trigger, session }) {
if (trigger === "update" && session?.name && session?.email) {
// Note, that `session` can be any arbitrary object, remember to validate it!
token.name = session.name;
token.email = session.email;
}
return token;
},
},
};
export default NextAuth(authOptions);

View File

@ -0,0 +1,49 @@
import { prisma } from "@/lib/api/db";
import type { NextApiRequest, NextApiResponse } from "next";
import bcrypt from "bcrypt";
interface Data {
response: string | object;
}
interface User {
name: string;
email: string;
password: string;
}
export default async function Index(
req: NextApiRequest,
res: NextApiResponse<Data>
) {
const body: User = req.body;
if (!body.email || !body.password || !body.name)
return res
.status(400)
.json({ response: "Please fill out all the fields." });
const checkIfUserExists = await prisma.user.findFirst({
where: {
email: body.email,
},
});
if (!checkIfUserExists) {
const saltRounds = 10;
const hashedPassword = bcrypt.hashSync(body.password, saltRounds);
await prisma.user.create({
data: {
name: body.name,
email: body.email,
password: hashedPassword,
},
});
res.status(201).json({ response: "User successfully created." });
} else if (checkIfUserExists) {
res.status(400).json({ response: "User already exists." });
}
}

57
pages/api/avatar/[id].ts Normal file
View File

@ -0,0 +1,57 @@
import type { NextApiRequest, NextApiResponse } from "next";
import { getServerSession } from "next-auth/next";
import { authOptions } from "pages/api/auth/[...nextauth]";
import { prisma } from "@/lib/api/db";
import path from "path";
import fs from "fs";
export default async function Index(req: NextApiRequest, res: NextApiResponse) {
const session = await getServerSession(req, res, authOptions);
const userId = session?.user.id;
const userEmail = session?.user.email;
const queryId = Number(req.query.id);
if (!queryId)
return res
.setHeader("Content-Type", "text/plain")
.status(401)
.send("Invalid parameters.");
if (!userId || !userEmail)
return res
.setHeader("Content-Type", "text/plain")
.status(401)
.send("You must be logged in.");
if (userId !== queryId) {
const targetUser = await prisma.user.findUnique({
where: {
id: queryId,
},
});
if (
targetUser?.isPrivate &&
!targetUser.whitelistedUsers.includes(userEmail)
) {
return res
.setHeader("Content-Type", "text/plain")
.send("This profile is private.");
}
}
const filePath = path.join(
process.cwd(),
`data/uploads/avatar/${queryId}.jpg`
);
const file = fs.existsSync(filePath)
? fs.readFileSync(filePath)
: "File not found.";
if (!fs.existsSync(filePath)) res.setHeader("Content-Type", "text/plain");
else res.setHeader("Content-Type", "image/jpeg");
return res.send(file);
}

View File

@ -0,0 +1,20 @@
import getCollection from "@/lib/api/controllers/public/getCollection";
import type { NextApiRequest, NextApiResponse } from "next";
export default async function collections(
req: NextApiRequest,
res: NextApiResponse
) {
if (!req?.query?.body) {
return res
.status(401)
.json({ response: "Please choose a valid collection." });
}
if (req.method === "GET") {
const collection = await getCollection(req?.query?.body as string);
return res
.status(collection.status)
.json({ response: collection.response });
}
}

View File

@ -0,0 +1,36 @@
import type { NextApiRequest, NextApiResponse } from "next";
import { getServerSession } from "next-auth/next";
import { authOptions } from "pages/api/auth/[...nextauth]";
import getCollections from "@/lib/api/controllers/collections/getCollections";
import postCollection from "@/lib/api/controllers/collections/postCollection";
import updateCollection from "@/lib/api/controllers/collections/updateCollection";
import deleteCollection from "@/lib/api/controllers/collections/deleteCollection";
export default async function collections(
req: NextApiRequest,
res: NextApiResponse
) {
const session = await getServerSession(req, res, authOptions);
if (!session?.user?.email) {
return res.status(401).json({ response: "You must be logged in." });
}
if (req.method === "GET") {
const collections = await getCollections(session.user.id);
return res
.status(collections.status)
.json({ response: collections.response });
} else if (req.method === "POST") {
const newCollection = await postCollection(req.body, session.user.id);
return res
.status(newCollection.status)
.json({ response: newCollection.response });
} else if (req.method === "PUT") {
const updated = await updateCollection(req.body, session.user.id);
return res.status(updated.status).json({ response: updated.response });
} else if (req.method === "DELETE") {
const deleted = await deleteCollection(req.body, session.user.id);
return res.status(deleted.status).json({ response: deleted.response });
}
}

View File

@ -0,0 +1,35 @@
import type { NextApiRequest, NextApiResponse } from "next";
import { getServerSession } from "next-auth/next";
import { authOptions } from "pages/api/auth/[...nextauth]";
import getLinks from "@/lib/api/controllers/links/getLinks";
import postLink from "@/lib/api/controllers/links/postLink";
import deleteLink from "@/lib/api/controllers/links/deleteLink";
import updateLink from "@/lib/api/controllers/links/updateLink";
export default async function links(req: NextApiRequest, res: NextApiResponse) {
const session = await getServerSession(req, res, authOptions);
if (!session?.user?.email) {
return res.status(401).json({ response: "You must be logged in." });
}
if (req.method === "GET") {
const links = await getLinks(session.user.id, req?.query?.body as string);
return res.status(links.status).json({ response: links.response });
} else if (req.method === "POST") {
const newlink = await postLink(req.body, session.user.id);
return res.status(newlink.status).json({
response: newlink.response,
});
} else if (req.method === "PUT") {
const updated = await updateLink(req.body, session.user.id);
return res.status(updated.status).json({
response: updated.response,
});
} else if (req.method === "DELETE") {
const deleted = await deleteLink(req.body, session.user.id);
return res.status(deleted.status).json({
response: deleted.response,
});
}
}

View File

@ -0,0 +1,17 @@
import type { NextApiRequest, NextApiResponse } from "next";
import { getServerSession } from "next-auth/next";
import { authOptions } from "pages/api/auth/[...nextauth]";
import getTags from "@/lib/api/controllers/tags/getTags";
export default async function tags(req: NextApiRequest, res: NextApiResponse) {
const session = await getServerSession(req, res, authOptions);
if (!session?.user?.email) {
return res.status(401).json({ response: "You must be logged in." });
}
if (req.method === "GET") {
const tags = await getTags(session.user.id);
return res.status(tags.status).json({ response: tags.response });
}
}

View File

@ -0,0 +1,24 @@
import type { NextApiRequest, NextApiResponse } from "next";
import { getServerSession } from "next-auth/next";
import { authOptions } from "pages/api/auth/[...nextauth]";
import getUsers from "@/lib/api/controllers/users/getUsers";
import updateUser from "@/lib/api/controllers/users/updateUser";
export default async function users(req: NextApiRequest, res: NextApiResponse) {
const session = await getServerSession(req, res, authOptions);
if (!session?.user?.email) {
return res.status(401).json({ response: "You must be logged in." });
}
const lookupEmail = req.query.email as string;
const isSelf = session.user.email === lookupEmail ? true : false;
if (req.method === "GET") {
const users = await getUsers(lookupEmail, isSelf, session.user.email);
return res.status(users.status).json({ response: users.response });
} else if (req.method === "PUT" && !req.body.password) {
const updated = await updateUser(req.body, session.user.id);
return res.status(updated.status).json({ response: updated.response });
}
}

247
pages/collections/[id].tsx Normal file
View File

@ -0,0 +1,247 @@
import Dropdown from "@/components/Dropdown";
import LinkCard from "@/components/LinkCard";
import useCollectionStore from "@/store/collections";
import useLinkStore from "@/store/links";
import { CollectionIncludingMembersAndLinkCount, Sort } from "@/types/global";
import {
faEllipsis,
faFolder,
faSort,
} from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { useRouter } from "next/router";
import { useEffect, useState } from "react";
import MainLayout from "@/layouts/MainLayout";
import { useSession } from "next-auth/react";
import ProfilePhoto from "@/components/ProfilePhoto";
import SortDropdown from "@/components/SortDropdown";
import useModalStore from "@/store/modals";
import useLinks from "@/hooks/useLinks";
import usePermissions from "@/hooks/usePermissions";
export default function Index() {
const { setModal } = useModalStore();
const router = useRouter();
const { links } = useLinkStore();
const { collections } = useCollectionStore();
const { data } = useSession();
const [expandDropdown, setExpandDropdown] = useState(false);
const [sortDropdown, setSortDropdown] = useState(false);
const [sortBy, setSortBy] = useState<Sort>(Sort.DateNewestFirst);
const [activeCollection, setActiveCollection] =
useState<CollectionIncludingMembersAndLinkCount>();
const permissions = usePermissions(activeCollection?.id as number);
useLinks({ collectionId: Number(router.query.id), sort: sortBy });
useEffect(() => {
setActiveCollection(
collections.find((e) => e.id === Number(router.query.id))
);
}, [router, collections]);
return (
<MainLayout>
<div className="p-5 flex flex-col gap-5 w-full">
<div className="bg-gradient-to-tr from-sky-100 from-10% via-gray-100 via-20% rounded-2xl shadow min-h-[10rem] p-5 flex gap-5 flex-col justify-between">
<div className="flex flex-col sm:flex-row gap-3 justify-between items-center sm:items-start">
{activeCollection && (
<div className="flex gap-3 items-center">
<div className="flex gap-2">
<FontAwesomeIcon
icon={faFolder}
style={{ color: activeCollection?.color }}
className="sm:w-8 sm:h-8 w-6 h-6 mt-3 drop-shadow"
/>
<p className="sm:text-4xl text-3xl capitalize bg-gradient-to-tr from-sky-500 to-slate-400 bg-clip-text text-transparent font-bold py-1">
{activeCollection?.name}
</p>
</div>
</div>
)}
{activeCollection ? (
<div
className={`text-sky-400 min-w-[15rem] ${
activeCollection.members[0] && "mr-3"
}`}
>
<div
onClick={() =>
setModal({
modal: "COLLECTION",
state: true,
method: "UPDATE",
isOwner: permissions === true,
active: activeCollection,
defaultIndex: permissions === true ? 1 : 0,
})
}
className="flex justify-center sm:justify-end items-center w-fit mx-auto sm:mr-0 sm:ml-auto group cursor-pointer"
>
<div
className={`bg-sky-500 p-2 leading-3 select-none group-hover:bg-sky-400 duration-100 text-white rounded-full text-xs ${
activeCollection.members[0] && "mr-1"
}`}
>
{permissions === true ? "Manage" : "View"} Team
</div>
{activeCollection?.members
.sort((a, b) => (a.userId as number) - (b.userId as number))
.map((e, i) => {
return (
<ProfilePhoto
key={i}
src={`/api/avatar/${e.userId}`}
className="-mr-3 duration-100 border-[3px]"
/>
);
})
.slice(0, 4)}
{activeCollection?.members.length &&
activeCollection.members.length - 4 > 0 ? (
<div className="h-10 w-10 text-white flex items-center justify-center rounded-full border-[3px] bg-sky-500 border-sky-100 -mr-3">
+{activeCollection?.members?.length - 4}
</div>
) : null}
</div>
</div>
) : null}
</div>
<div className="text-gray-500 flex justify-between items-end gap-5">
<p>{activeCollection?.description}</p>
<div className="flex items-center gap-2">
<div className="relative">
<div
onClick={() => setSortDropdown(!sortDropdown)}
id="sort-dropdown"
className="inline-flex rounded-md cursor-pointer hover:bg-slate-200 duration-100 p-1"
>
<FontAwesomeIcon
icon={faSort}
id="sort-dropdown"
className="w-5 h-5 text-gray-500"
/>
</div>
{sortDropdown ? (
<SortDropdown
sortBy={sortBy}
setSort={setSortBy}
toggleSortDropdown={() => setSortDropdown(!sortDropdown)}
/>
) : null}
</div>
<div className="relative">
<div
onClick={() => setExpandDropdown(!expandDropdown)}
id="expand-dropdown"
className="inline-flex rounded-md cursor-pointer hover:bg-slate-200 duration-100 p-1"
>
<FontAwesomeIcon
icon={faEllipsis}
id="expand-dropdown"
title="More"
className="w-5 h-5 text-gray-500"
/>
</div>
{expandDropdown ? (
<Dropdown
items={[
permissions === true || permissions?.canCreate
? {
name: "Add Link Here",
onClick: () => {
setModal({
modal: "LINK",
state: true,
method: "CREATE",
});
setExpandDropdown(false);
},
}
: undefined,
permissions === true
? {
name: "Edit Collection Info",
onClick: () => {
activeCollection &&
setModal({
modal: "COLLECTION",
state: true,
method: "UPDATE",
isOwner: permissions === true,
active: activeCollection,
});
setExpandDropdown(false);
},
}
: undefined,
{
name:
permissions === true
? "Share/Collaborate"
: "View Team",
onClick: () => {
activeCollection &&
setModal({
modal: "COLLECTION",
state: true,
method: "UPDATE",
isOwner: permissions === true,
active: activeCollection,
defaultIndex: permissions === true ? 1 : 0,
});
setExpandDropdown(false);
},
},
{
name:
permissions === true
? "Delete Collection"
: "Leave Collection",
onClick: () => {
activeCollection &&
setModal({
modal: "COLLECTION",
state: true,
method: "UPDATE",
isOwner: permissions === true,
active: activeCollection,
defaultIndex: permissions === true ? 2 : 1,
});
setExpandDropdown(false);
},
},
]}
onClickOutside={(e: Event) => {
const target = e.target as HTMLInputElement;
if (target.id !== "expand-dropdown")
setExpandDropdown(false);
}}
className="absolute top-8 right-0 z-10 w-40"
/>
) : null}
</div>
</div>
</div>
</div>
<div className="grid 2xl:grid-cols-3 xl:grid-cols-2 gap-5">
{links
.filter((e) => e.collectionId === Number(router.query.id))
.map((e, i) => {
return <LinkCard key={i} link={e} count={i} />;
})}
</div>
</div>
</MainLayout>
);
}

135
pages/collections/index.tsx Normal file
View File

@ -0,0 +1,135 @@
import useCollectionStore from "@/store/collections";
import {
faBox,
faEllipsis,
faPlus,
faSort,
} from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import CollectionCard from "@/components/CollectionCard";
import Dropdown from "@/components/Dropdown";
import { useState } from "react";
import MainLayout from "@/layouts/MainLayout";
import { useSession } from "next-auth/react";
import useModalStore from "@/store/modals";
import SortDropdown from "@/components/SortDropdown";
import { Sort } from "@/types/global";
import useSort from "@/hooks/useSort";
export default function Collections() {
const { collections } = useCollectionStore();
const [expandDropdown, setExpandDropdown] = useState(false);
const [sortDropdown, setSortDropdown] = useState(false);
const [sortBy, setSortBy] = useState<Sort>(Sort.DateNewestFirst);
const [sortedCollections, setSortedCollections] = useState(collections);
const session = useSession();
const { setModal } = useModalStore();
useSort({ sortBy, setData: setSortedCollections, data: collections });
return (
<MainLayout>
<div className="p-5">
<div className="flex gap-3 items-center justify-between mb-5">
<div className="flex gap-3 items-end">
<div className="flex gap-2">
<FontAwesomeIcon
icon={faBox}
className="sm:w-8 sm:h-8 w-6 h-6 mt-2 text-sky-500 drop-shadow"
/>
<p className="sm:text-4xl text-3xl capitalize bg-gradient-to-tr from-sky-500 to-slate-400 bg-clip-text text-transparent font-bold">
All Collections
</p>
</div>
<div className="relative">
<div
onClick={() => setExpandDropdown(!expandDropdown)}
id="expand-dropdown"
className="inline-flex rounded-md cursor-pointer hover:bg-slate-200 duration-100 p-1"
>
<FontAwesomeIcon
icon={faEllipsis}
id="expand-dropdown"
className="w-5 h-5 text-gray-500"
/>
</div>
{expandDropdown ? (
<Dropdown
items={[
{
name: "New Collection",
onClick: () => {
setModal({
modal: "COLLECTION",
state: true,
method: "CREATE",
});
setExpandDropdown(false);
},
},
]}
onClickOutside={(e: Event) => {
const target = e.target as HTMLInputElement;
if (target.id !== "expand-dropdown")
setExpandDropdown(false);
}}
className="absolute top-8 left-0 w-36"
/>
) : null}
</div>
</div>
<div className="relative">
<div
onClick={() => setSortDropdown(!sortDropdown)}
id="sort-dropdown"
className="inline-flex rounded-md cursor-pointer hover:bg-slate-200 duration-100 p-1"
>
<FontAwesomeIcon
icon={faSort}
id="sort-dropdown"
className="w-5 h-5 text-gray-500"
/>
</div>
{sortDropdown ? (
<SortDropdown
sortBy={sortBy}
setSort={setSortBy}
toggleSortDropdown={() => setSortDropdown(!sortDropdown)}
/>
) : null}
</div>
</div>
<div className="grid 2xl:grid-cols-4 xl:grid-cols-3 sm:grid-cols-2 grid-cols-1 gap-5">
{sortedCollections.map((e, i) => {
return <CollectionCard key={i} collection={e} />;
})}
<div
className="p-5 self-stretch bg-gradient-to-tr from-sky-100 from-10% via-gray-100 via-20% min-h-[12rem] rounded-2xl cursor-pointer shadow duration-100 hover:shadow-none flex flex-col gap-4 justify-center items-center group"
onClick={() => {
setModal({
modal: "COLLECTION",
state: true,
method: "CREATE",
});
}}
>
<p className="text-sky-900 group-hover:opacity-0 duration-100">
New Collection
</p>
<FontAwesomeIcon
icon={faPlus}
className="w-8 h-8 text-sky-500 group-hover:w-12 group-hover:h-12 group-hover:-mt-10 duration-100"
/>
</div>
</div>
</div>
</MainLayout>
);
}

243
pages/dashboard.tsx Normal file
View File

@ -0,0 +1,243 @@
import useCollectionStore from "@/store/collections";
import {
faChartSimple,
faChevronDown,
} from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import MainLayout from "@/layouts/MainLayout";
import useLinkStore from "@/store/links";
import useTagStore from "@/store/tags";
import LinkCard from "@/components/LinkCard";
import Link from "next/link";
import CollectionCard from "@/components/CollectionCard";
import { Disclosure, Transition } from "@headlessui/react";
import { useEffect, useState } from "react";
import useLinks from "@/hooks/useLinks";
export default function Dashboard() {
const { collections } = useCollectionStore();
const { links } = useLinkStore();
const { tags } = useTagStore();
const [numberOfLinks, setNumberOfLinks] = useState(0);
const [tagPinDisclosure, setTagPinDisclosure] = useState<boolean>(() => {
const storedValue = localStorage.getItem("tagPinDisclosure");
return storedValue ? storedValue === "true" : true;
});
const [collectionPinDisclosure, setCollectionPinDisclosure] =
useState<boolean>(() => {
const storedValue = localStorage.getItem("collectionPinDisclosure");
return storedValue ? storedValue === "true" : true;
});
const [linkPinDisclosure, setLinkPinDisclosure] = useState<boolean>(() => {
const storedValue = localStorage.getItem("linkPinDisclosure");
return storedValue ? storedValue === "true" : true;
});
useLinks({ pinnedOnly: true, sort: 0 });
useEffect(() => {
setNumberOfLinks(
collections.reduce(
(accumulator, collection) =>
accumulator + (collection._count as any).links,
0
)
);
}, [collections]);
useEffect(() => {
localStorage.setItem(
"tagPinDisclosure",
tagPinDisclosure ? "true" : "false"
);
}, [tagPinDisclosure]);
useEffect(() => {
localStorage.setItem(
"collectionPinDisclosure",
collectionPinDisclosure ? "true" : "false"
);
}, [collectionPinDisclosure]);
useEffect(() => {
localStorage.setItem(
"linkPinDisclosure",
linkPinDisclosure ? "true" : "false"
);
}, [linkPinDisclosure]);
return (
// ml-80
<MainLayout>
<div className="p-5">
<div className="flex gap-3 items-center mb-5">
<div className="flex gap-2">
<FontAwesomeIcon
icon={faChartSimple}
className="sm:w-8 sm:h-8 w-6 h-6 mt-2 text-sky-500 drop-shadow"
/>
<p className="sm:text-4xl text-3xl capitalize bg-gradient-to-tr from-sky-500 to-slate-400 bg-clip-text text-transparent font-bold">
Dashboard
</p>
</div>
</div>
<br />
<div className="flex flex-col md:flex-row md:items-center justify-evenly gap-2 mb-10">
<div className="flex items-baseline gap-2">
<p className="font-bold text-6xl bg-gradient-to-tr from-sky-500 to-slate-400 bg-clip-text text-transparent">
{numberOfLinks}
</p>
<p className="text-sky-900 text-xl">
{numberOfLinks === 1 ? "Link" : "Links"}
</p>
</div>
<div className="flex items-baseline gap-2">
<p className="font-bold text-6xl bg-gradient-to-tr from-sky-500 to-slate-400 bg-clip-text text-transparent">
{collections.length}
</p>
<p className="text-sky-900 text-xl">Collections</p>
</div>
<div className="flex items-baseline gap-2">
<p className="font-bold text-6xl bg-gradient-to-tr from-sky-500 to-slate-400 bg-clip-text text-transparent">
{tags.length}
</p>
<p className="text-sky-900 text-xl">Tags</p>
</div>
</div>
{/* <hr className="my-5 border-sky-100" /> */}
<br />
<div className="flex flex-col 2xl:flex-row items-start justify-evenly 2xl:gap-2">
<Disclosure defaultOpen={linkPinDisclosure}>
<div className="flex flex-col gap-5 p-2 w-full mx-auto md:w-2/3">
<Disclosure.Button
onClick={() => {
setLinkPinDisclosure(!linkPinDisclosure);
}}
className="flex justify-between gap-2 items-baseline shadow active:shadow-inner duration-100 py-2 px-4 rounded-full"
>
<p className="text-sky-600 text-xl">Pinned Links</p>
<div className="text-sky-600 flex items-center gap-2">
{linkPinDisclosure ? "Hide" : "Show"}
<FontAwesomeIcon
icon={faChevronDown}
className={`w-4 h-4 text-sky-300 ${
linkPinDisclosure ? "rotate-reverse" : "rotate"
}`}
/>
</div>
</Disclosure.Button>
<Transition
enter="transition duration-100 ease-out"
enterFrom="transform opacity-0 -translate-y-3"
enterTo="transform opacity-100 translate-y-0"
leave="transition duration-100 ease-out"
leaveFrom="transform opacity-100 translate-y-0"
leaveTo="transform opacity-0 -translate-y-3"
>
<Disclosure.Panel className="grid grid-cols-1 xl:grid-cols-2 gap-5 w-full">
{links
.filter((e) => e.pinnedBy && e.pinnedBy[0])
.map((e, i) => (
<LinkCard key={i} link={e} count={i} />
))}
</Disclosure.Panel>
</Transition>
</div>
</Disclosure>
{/* <Disclosure defaultOpen={collectionPinDisclosure}>
<div className="flex flex-col gap-5 p-2 w-full">
<Disclosure.Button
onClick={() => {
setCollectionPinDisclosure(!collectionPinDisclosure);
}}
className="flex justify-between gap-2 items-baseline shadow active:shadow-inner duration-100 py-2 px-4 rounded-full"
>
<p className="text-sky-600 text-xl">Pinned Collections</p>
<div className="text-sky-600 flex items-center gap-2">
{collectionPinDisclosure ? "Hide" : "Show"}
<FontAwesomeIcon
icon={faChevronDown}
className={`w-4 h-4 text-sky-300 ${
collectionPinDisclosure ? "rotate-reverse" : "rotate"
}`}
/>
</div>
</Disclosure.Button>
<Transition
enter="transition duration-100 ease-out"
enterFrom="transform opacity-0 -translate-y-3"
enterTo="transform opacity-100 translate-y-0"
leave="transition duration-100 ease-out"
leaveFrom="transform opacity-100 translate-y-0"
leaveTo="transform opacity-0 -translate-y-3"
>
<Disclosure.Panel className="flex flex-col gap-5 w-full">
{collections.slice(0, 5).map((e, i) => (
<CollectionCard key={i} collection={e} />
))}
</Disclosure.Panel>
</Transition>
</div>
</Disclosure> */}
{/* <Disclosure defaultOpen={tagPinDisclosure}>
<div className="flex flex-col gap-5 p-2 w-full">
<Disclosure.Button
onClick={() => {
setTagPinDisclosure(!tagPinDisclosure);
}}
className="flex justify-between gap-2 items-baseline shadow active:shadow-inner duration-100 py-2 px-4 rounded-full"
>
<p className="text-sky-600 text-xl">Pinned Tags</p>
<div className="text-sky-600 flex items-center gap-2">
{tagPinDisclosure ? "Hide" : "Show"}
<FontAwesomeIcon
icon={faChevronDown}
className={`w-4 h-4 text-sky-300 ${
tagPinDisclosure ? "rotate-reverse" : "rotate"
}`}
/>
</div>
</Disclosure.Button>
<Transition
enter="transition duration-100 ease-out"
enterFrom="transform opacity-0 -translate-y-3"
enterTo="transform opacity-100 translate-y-0"
leave="transition duration-100 ease-out"
leaveFrom="transform opacity-100 translate-y-0"
leaveTo="transform opacity-0 -translate-y-3"
>
<Disclosure.Panel className="flex gap-2 flex-wrap">
{tags.slice(0, 19).map((e, i) => (
<Link
href={`/tags/${e.id}`}
key={i}
className="px-2 py-1 bg-sky-200 rounded-full hover:opacity-60 duration-100 text-sky-700"
>
{e.name}
</Link>
))}
</Disclosure.Panel>
</Transition>
</div>
</Disclosure> */}
</div>
</div>
</MainLayout>
);
}

10
pages/index.tsx Normal file
View File

@ -0,0 +1,10 @@
import { useRouter } from "next/router";
import { useEffect } from "react";
export default function Home() {
const router = useRouter();
useEffect(() => {
router.push("/dashboard");
}, []);
}

63
pages/links.tsx Normal file
View File

@ -0,0 +1,63 @@
import LinkCard from "@/components/LinkCard";
import SortDropdown from "@/components/SortDropdown";
import useLinks from "@/hooks/useLinks";
import MainLayout from "@/layouts/MainLayout";
import useLinkStore from "@/store/links";
import { Sort } from "@/types/global";
import { faLink, faSort } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { useState } from "react";
export default function Links() {
const { links } = useLinkStore();
const [sortDropdown, setSortDropdown] = useState(false);
const [sortBy, setSortBy] = useState<Sort>(Sort.DateNewestFirst);
useLinks({ sort: sortBy });
return (
<MainLayout>
<div className="p-5 flex flex-col gap-5 w-full">
<div className="flex gap-3 justify-between items-center">
<div className="flex gap-2">
<FontAwesomeIcon
icon={faLink}
className="sm:w-8 sm:h-8 w-6 h-6 mt-2 text-sky-500 drop-shadow"
/>
<p className="sm:text-4xl text-3xl capitalize bg-gradient-to-tr from-sky-500 to-slate-400 bg-clip-text text-transparent font-bold">
All Links
</p>
</div>
<div className="relative">
<div
onClick={() => setSortDropdown(!sortDropdown)}
id="sort-dropdown"
className="inline-flex rounded-md cursor-pointer hover:bg-slate-200 duration-100 p-1"
>
<FontAwesomeIcon
icon={faSort}
id="sort-dropdown"
className="w-5 h-5 text-gray-500"
/>
</div>
{sortDropdown ? (
<SortDropdown
sortBy={sortBy}
setSort={setSortBy}
toggleSortDropdown={() => setSortDropdown(!sortDropdown)}
/>
) : null}
</div>
</div>
<div className="grid 2xl:grid-cols-3 xl:grid-cols-2 gap-5">
{links.map((e, i) => {
return <LinkCard key={i} link={e} count={i} />;
})}
</div>
</div>
</MainLayout>
);
}

91
pages/login.tsx Normal file
View File

@ -0,0 +1,91 @@
import SubmitButton from "@/components/SubmitButton";
import { signIn } from "next-auth/react";
import Link from "next/link";
import { useState } from "react";
import { toast } from "react-hot-toast";
interface FormData {
email: string;
password: string;
}
export default function Login() {
const [submitLoader, setSubmitLoader] = useState(false);
const [form, setForm] = useState<FormData>({
email: "",
password: "",
});
async function loginUser() {
if (form.email !== "" && form.password !== "") {
setSubmitLoader(true);
const load = toast.loading("Authenticating...");
const res = await signIn("credentials", {
email: form.email,
password: form.password,
redirect: false,
});
toast.dismiss(load);
setSubmitLoader(false);
if (!res?.ok) {
toast.error("Invalid login.");
}
} else {
toast.error("Please fill out all the fields.");
}
}
return (
<>
<p className="text-xl font-bold text-center text-sky-500 my-10">
Linkwarden
</p>
<div className="p-5 mx-auto flex flex-col gap-3 justify-between sm:w-[28rem] w-80 bg-slate-50 rounded-md border border-sky-100">
<div className="my-5 text-center">
<p className="text-3xl font-bold text-sky-500">Welcome back</p>
<p className="text-md font-semibold text-sky-400">
Sign in to your account
</p>
</div>
<p className="text-sm text-sky-500 w-fit font-semibold">Email</p>
<input
type="text"
placeholder="johnny@example.com"
value={form.email}
onChange={(e) => setForm({ ...form, email: e.target.value })}
className="w-full rounded-md p-3 mx-auto border-sky-100 border-solid border outline-none focus:border-sky-500 duration-100"
/>
<p className="text-sm text-sky-500 w-fit font-semibold">Password</p>
<input
type="password"
placeholder="*****************"
value={form.password}
onChange={(e) => setForm({ ...form, password: e.target.value })}
className="w-full rounded-md p-3 mx-auto border-sky-100 border-solid border outline-none focus:border-sky-500 duration-100"
/>
<SubmitButton
onClick={loginUser}
label="Login"
className="mt-2 w-full text-center"
loading={submitLoader}
/>
</div>
<div className="flex items-baseline gap-1 justify-center mt-10">
<p className="w-fit text-gray-500">New here?</p>
<Link href={"/register"} className="block text-sky-500 font-bold">
Sign Up
</Link>
</div>
</>
);
}

View File

@ -0,0 +1,73 @@
import LinkCard from "@/components/PublicPage/LinkCard";
import useDetectPageBottom from "@/hooks/useDetectPageBottom";
import getPublicCollectionData from "@/lib/client/getPublicCollectionData";
import { PublicCollectionIncludingLinks } from "@/types/global";
import { useRouter } from "next/router";
import React, { useEffect, useState } from "react";
export default function PublicCollections() {
const router = useRouter();
const hasReachedBottom = useDetectPageBottom();
const [data, setData] = useState<PublicCollectionIncludingLinks>();
useEffect(() => {
if (router.query.id) {
getPublicCollectionData(
Number(router.query.id),
data as PublicCollectionIncludingLinks,
setData
);
}
// document
// .querySelector("body")
// ?.classList.add(
// "bg-gradient-to-br",
// "from-slate-50",
// "to-sky-50",
// "min-h-screen"
// );
}, []);
useEffect(() => {
if (hasReachedBottom && router.query.id) {
getPublicCollectionData(
Number(router.query.id),
data as PublicCollectionIncludingLinks,
setData
);
}
}, [hasReachedBottom]);
return data ? (
<div className="max-w-4xl mx-auto p-5 bg">
<div
className={`text-center bg-gradient-to-tr from-sky-100 from-10% via-gray-100 via-20% rounded-3xl shadow-lg p-5`}
>
<p className="text-5xl bg-gradient-to-tr from-sky-500 to-slate-400 bg-clip-text text-transparent font-bold mb-5 capitalize">
{data.name}
</p>
{data.description && (
<>
<hr className="mt-5 max-w-[30rem] mx-auto border-1 border-slate-400" />
<p className="mt-2 text-gray-500">{data.description}</p>
</>
)}
</div>
<div className="flex flex-col gap-5 my-8">
{data?.links?.map((e, i) => {
return <LinkCard key={i} link={e} count={i} />;
})}
</div>
<p className="text-center font-bold text-gray-500">
List created with <span className="text-sky-500">Linkwarden.</span>
</p>
</div>
) : (
<></>
);
}

147
pages/register.tsx Normal file
View File

@ -0,0 +1,147 @@
import Link from "next/link";
import { useState } from "react";
import { useRouter } from "next/router";
import { toast } from "react-hot-toast";
import SubmitButton from "@/components/SubmitButton";
interface FormData {
name: string;
email: string;
password: string;
passwordConfirmation: string;
}
export default function Register() {
const router = useRouter();
const [submitLoader, setSubmitLoader] = useState(false);
const [form, setForm] = useState<FormData>({
name: "",
email: "",
password: "",
passwordConfirmation: "",
});
async function registerUser() {
if (
form.name !== "" &&
form.email !== "" &&
form.password !== "" &&
form.passwordConfirmation !== ""
) {
if (form.password === form.passwordConfirmation) {
const { passwordConfirmation, ...request } = form;
setSubmitLoader(true);
const load = toast.loading("Creating Account...");
const response = await fetch("/api/auth/register", {
body: JSON.stringify(request),
headers: {
"Content-Type": "application/json",
},
method: "POST",
});
const data = await response.json();
toast.dismiss(load);
setSubmitLoader(false);
if (response.ok) {
setForm({
name: "",
email: "",
password: "",
passwordConfirmation: "",
});
toast.success("User Created!");
router.push("/login");
} else {
toast.error(data.response);
}
} else {
toast.error("Passwords do not match.");
}
} else {
toast.error("Please fill out all the fields.");
}
}
return (
<>
<p className="text-xl font-bold text-center my-10 text-sky-500">
Linkwarden
</p>
<div className="p-5 mx-auto flex flex-col gap-3 justify-between sm:w-[28rem] w-80 bg-slate-50 rounded-md border border-sky-100">
<div className="my-5 text-center">
<p className="text-3xl font-bold text-sky-500">Get started</p>
<p className="text-md font-semibold text-sky-400">
Create a new account
</p>
</div>
<p className="text-sm text-sky-500 w-fit font-semibold">Display Name</p>
<input
type="text"
placeholder="Johnny"
value={form.name}
onChange={(e) => setForm({ ...form, name: e.target.value })}
className="w-full rounded-md p-3 mx-auto border-sky-100 border-solid border outline-none focus:border-sky-500 duration-100"
/>
<p className="text-sm text-sky-500 w-fit font-semibold">Email</p>
<input
type="text"
placeholder="johnny@example.com"
value={form.email}
onChange={(e) => setForm({ ...form, email: e.target.value })}
className="w-full rounded-md p-3 mx-auto border-sky-100 border-solid border outline-none focus:border-sky-500 duration-100"
/>
<p className="text-sm text-sky-500 w-fit font-semibold">Password</p>
<input
type="password"
placeholder="*****************"
value={form.password}
onChange={(e) => setForm({ ...form, password: e.target.value })}
className="w-full rounded-md p-3 mx-auto border-sky-100 border-solid border outline-none focus:border-sky-500 duration-100"
/>
<p className="text-sm text-sky-500 w-fit font-semibold">
Re-enter Password
</p>
<input
type="password"
placeholder="*****************"
value={form.passwordConfirmation}
onChange={(e) =>
setForm({ ...form, passwordConfirmation: e.target.value })
}
className="w-full rounded-md p-3 mx-auto border-sky-100 border-solid border outline-none focus:border-sky-500 duration-100"
/>
<SubmitButton
onClick={registerUser}
label="Sign Up"
className="mt-2 w-full text-center"
loading={submitLoader}
/>
</div>
<div className="flex items-baseline gap-1 justify-center mt-10">
<p className="w-fit text-gray-500">Have an account?</p>
<Link href={"/login"} className="block w-min text-sky-500 font-bold">
Login
</Link>
</div>
</>
);
}

113
pages/search/[query].tsx Normal file
View File

@ -0,0 +1,113 @@
import FilterSearchDropdown from "@/components/FilterSearchDropdown";
import LinkCard from "@/components/LinkCard";
import SortDropdown from "@/components/SortDropdown";
import useLinks from "@/hooks/useLinks";
import MainLayout from "@/layouts/MainLayout";
import useLinkStore from "@/store/links";
import { LinkSearchFilter, Sort } from "@/types/global";
import { faFilter, faSearch, faSort } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { useRouter } from "next/router";
import { useState } from "react";
export default function Links() {
const { links } = useLinkStore();
const router = useRouter();
const [searchFilter, setSearchFilter] = useState<LinkSearchFilter>({
name: true,
url: true,
description: true,
collection: true,
tags: true,
});
const [filterDropdown, setFilterDropdown] = useState(false);
const [sortDropdown, setSortDropdown] = useState(false);
const [sortBy, setSortBy] = useState<Sort>(Sort.DateNewestFirst);
useLinks({
searchFilter: searchFilter,
searchQuery: router.query.query as string,
sort: sortBy,
});
return (
<MainLayout>
<div className="p-5 flex flex-col gap-5 w-full">
<div className="flex gap-3 items-center justify-between">
<div className="flex gap-3 items-center mb-5">
<div className="flex gap-2">
<FontAwesomeIcon
icon={faSearch}
className="sm:w-8 sm:h-8 w-6 h-6 mt-2 text-sky-500 drop-shadow"
/>
<p className="sm:text-4xl text-3xl capitalize bg-gradient-to-tr from-sky-500 to-slate-400 bg-clip-text text-transparent font-bold">
Search Results
</p>
</div>
</div>
<div className="flex gap-3 items-center">
<div className="relative">
<div
onClick={() => setFilterDropdown(!filterDropdown)}
id="filter-dropdown"
className="inline-flex rounded-md cursor-pointer hover:bg-slate-200 duration-100 p-1"
>
<FontAwesomeIcon
icon={faFilter}
id="filter-dropdown"
className="w-5 h-5 text-gray-500"
/>
</div>
{filterDropdown ? (
<FilterSearchDropdown
setFilterDropdown={setFilterDropdown}
searchFilter={searchFilter}
setSearchFilter={setSearchFilter}
/>
) : null}
</div>
<div className="relative">
<div
onClick={() => setSortDropdown(!sortDropdown)}
id="sort-dropdown"
className="inline-flex rounded-md cursor-pointer hover:bg-slate-200 duration-100 p-1"
>
<FontAwesomeIcon
icon={faSort}
id="sort-dropdown"
className="w-5 h-5 text-gray-500"
/>
</div>
{sortDropdown ? (
<SortDropdown
sortBy={sortBy}
setSort={setSortBy}
toggleSortDropdown={() => setSortDropdown(!sortDropdown)}
/>
) : null}
</div>
</div>
</div>
{links[0] ? (
links.map((e, i) => {
return <LinkCard key={i} link={e} count={i} />;
})
) : (
<p className="text-sky-900">
Nothing found.{" "}
<span className="text-sky-500 font-bold text-xl" title="Shruggie">
¯\_()_/¯
</span>
</p>
)}
</div>
</MainLayout>
);
}

10
pages/search/index.tsx Normal file
View File

@ -0,0 +1,10 @@
import { useRouter } from "next/router";
import { useEffect } from "react";
export default function Home() {
const router = useRouter();
useEffect(() => {
router.push("/links");
}, []);
}

79
pages/tags/[id].tsx Normal file
View File

@ -0,0 +1,79 @@
import LinkCard from "@/components/LinkCard";
import useLinkStore from "@/store/links";
import { faHashtag, faSort } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { useRouter } from "next/router";
import { useEffect, useState } from "react";
import MainLayout from "@/layouts/MainLayout";
import { Tag } from "@prisma/client";
import useTagStore from "@/store/tags";
import SortDropdown from "@/components/SortDropdown";
import { Sort } from "@/types/global";
import useLinks from "@/hooks/useLinks";
export default function Index() {
const router = useRouter();
const { links } = useLinkStore();
const { tags } = useTagStore();
const [sortDropdown, setSortDropdown] = useState(false);
const [sortBy, setSortBy] = useState<Sort>(Sort.DateNewestFirst);
const [activeTag, setActiveTag] = useState<Tag>();
useLinks({ tagId: Number(router.query.id), sort: sortBy });
useEffect(() => {
setActiveTag(tags.find((e) => e.id === Number(router.query.id)));
}, [router, tags]);
return (
<MainLayout>
<div className="p-5 flex flex-col gap-5 w-full">
<div className="flex gap-3 items-center justify-between">
<div className="flex gap-3 items-center">
<div className="flex gap-2">
<FontAwesomeIcon
icon={faHashtag}
className="sm:w-8 sm:h-8 w-6 h-6 mt-2 text-sky-500"
/>
<p className="sm:text-4xl text-3xl capitalize bg-gradient-to-tr from-sky-500 to-slate-400 bg-clip-text text-transparent font-bold">
{activeTag?.name}
</p>
</div>
</div>
<div className="relative">
<div
onClick={() => setSortDropdown(!sortDropdown)}
id="sort-dropdown"
className="inline-flex rounded-md cursor-pointer hover:bg-slate-200 duration-100 p-1"
>
<FontAwesomeIcon
icon={faSort}
id="sort-dropdown"
className="w-5 h-5 text-gray-500"
/>
</div>
{sortDropdown ? (
<SortDropdown
sortBy={sortBy}
setSort={setSortBy}
toggleSortDropdown={() => setSortDropdown(!sortDropdown)}
/>
) : null}
</div>
</div>
<div className="grid 2xl:grid-cols-3 xl:grid-cols-2 gap-5">
{links
.filter((e) => e.tags.some((e) => e.id === Number(router.query.id)))
.map((e, i) => {
return <LinkCard key={i} link={e} count={i} />;
})}
</div>
</div>
</MainLayout>
);
}

6
postcss.config.js Normal file
View File

@ -0,0 +1,6 @@
module.exports = {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
}

View File

@ -0,0 +1,117 @@
-- CreateTable
CREATE TABLE "User" (
"id" SERIAL NOT NULL,
"name" TEXT NOT NULL,
"email" TEXT NOT NULL,
"password" TEXT NOT NULL,
"isPrivate" BOOLEAN NOT NULL DEFAULT false,
"whitelistedUsers" TEXT[] DEFAULT ARRAY[]::TEXT[],
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "User_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "Collection" (
"id" SERIAL NOT NULL,
"name" TEXT NOT NULL,
"description" TEXT NOT NULL DEFAULT '',
"color" TEXT NOT NULL DEFAULT '#0ea5e9',
"isPublic" BOOLEAN NOT NULL DEFAULT false,
"ownerId" INTEGER NOT NULL,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "Collection_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "UsersAndCollections" (
"userId" INTEGER NOT NULL,
"collectionId" INTEGER NOT NULL,
"canCreate" BOOLEAN NOT NULL,
"canUpdate" BOOLEAN NOT NULL,
"canDelete" BOOLEAN NOT NULL,
CONSTRAINT "UsersAndCollections_pkey" PRIMARY KEY ("userId","collectionId")
);
-- CreateTable
CREATE TABLE "Link" (
"id" SERIAL NOT NULL,
"name" TEXT NOT NULL,
"url" TEXT NOT NULL,
"description" TEXT NOT NULL DEFAULT '',
"collectionId" INTEGER NOT NULL,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "Link_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "Tag" (
"id" SERIAL NOT NULL,
"name" TEXT NOT NULL,
"ownerId" INTEGER NOT NULL,
CONSTRAINT "Tag_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "_LinkToUser" (
"A" INTEGER NOT NULL,
"B" INTEGER NOT NULL
);
-- CreateTable
CREATE TABLE "_LinkToTag" (
"A" INTEGER NOT NULL,
"B" INTEGER NOT NULL
);
-- CreateIndex
CREATE UNIQUE INDEX "User_email_key" ON "User"("email");
-- CreateIndex
CREATE UNIQUE INDEX "Collection_name_ownerId_key" ON "Collection"("name", "ownerId");
-- CreateIndex
CREATE UNIQUE INDEX "Tag_name_ownerId_key" ON "Tag"("name", "ownerId");
-- CreateIndex
CREATE UNIQUE INDEX "_LinkToUser_AB_unique" ON "_LinkToUser"("A", "B");
-- CreateIndex
CREATE INDEX "_LinkToUser_B_index" ON "_LinkToUser"("B");
-- CreateIndex
CREATE UNIQUE INDEX "_LinkToTag_AB_unique" ON "_LinkToTag"("A", "B");
-- CreateIndex
CREATE INDEX "_LinkToTag_B_index" ON "_LinkToTag"("B");
-- AddForeignKey
ALTER TABLE "Collection" ADD CONSTRAINT "Collection_ownerId_fkey" FOREIGN KEY ("ownerId") REFERENCES "User"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "UsersAndCollections" ADD CONSTRAINT "UsersAndCollections_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "UsersAndCollections" ADD CONSTRAINT "UsersAndCollections_collectionId_fkey" FOREIGN KEY ("collectionId") REFERENCES "Collection"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "Link" ADD CONSTRAINT "Link_collectionId_fkey" FOREIGN KEY ("collectionId") REFERENCES "Collection"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "Tag" ADD CONSTRAINT "Tag_ownerId_fkey" FOREIGN KEY ("ownerId") REFERENCES "User"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "_LinkToUser" ADD CONSTRAINT "_LinkToUser_A_fkey" FOREIGN KEY ("A") REFERENCES "Link"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "_LinkToUser" ADD CONSTRAINT "_LinkToUser_B_fkey" FOREIGN KEY ("B") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "_LinkToTag" ADD CONSTRAINT "_LinkToTag_A_fkey" FOREIGN KEY ("A") REFERENCES "Link"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "_LinkToTag" ADD CONSTRAINT "_LinkToTag_B_fkey" FOREIGN KEY ("B") REFERENCES "Tag"("id") ON DELETE CASCADE ON UPDATE CASCADE;

View File

@ -0,0 +1,3 @@
# Please do not edit this file manually
# It should be added in your version-control system (i.e. Git)
provider = "postgresql"

79
prisma/schema.prisma Normal file
View File

@ -0,0 +1,79 @@
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
model User {
id Int @id @default(autoincrement())
name String
email String @unique
password String
collections Collection[]
tags Tag[]
pinnedLinks Link[]
collectionsJoined UsersAndCollections[]
isPrivate Boolean @default(false)
whitelistedUsers String[] @default([])
createdAt DateTime @default(now())
}
model Collection {
id Int @id @default(autoincrement())
name String
description String @default("")
color String @default("#0ea5e9")
isPublic Boolean @default(false)
owner User @relation(fields: [ownerId], references: [id])
ownerId Int
members UsersAndCollections[]
links Link[]
createdAt DateTime @default(now())
@@unique([name, ownerId])
}
model UsersAndCollections {
user User @relation(fields: [userId], references: [id])
userId Int
collection Collection @relation(fields: [collectionId], references: [id])
collectionId Int
canCreate Boolean
canUpdate Boolean
canDelete Boolean
@@id([userId, collectionId])
}
model Link {
id Int @id @default(autoincrement())
name String
url String
description String @default("")
pinnedBy User[]
collection Collection @relation(fields: [collectionId], references: [id])
collectionId Int
tags Tag[]
createdAt DateTime @default(now())
}
model Tag {
id Int @id @default(autoincrement())
name String
links Link[]
owner User @relation(fields: [ownerId], references: [id])
ownerId Int
@@unique([name, ownerId])
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 33 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 214 KiB

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