initial commit

This commit is contained in:
Marcus Schiesser
2023-08-29 16:29:18 +07:00
commit 3ce4c8adce
142 changed files with 18745 additions and 0 deletions
+14
View File
@@ -0,0 +1,14 @@
{
"presets": [
[
"next/babel",
{
"preset-env": {
"targets": {
"browsers": ["> 0.25%, not dead"]
}
}
}
]
]
}
+29
View File
@@ -0,0 +1,29 @@
# Your openai api key. (required)
OPENAI_API_KEY=sk-xxxx
# Override openai api request base url. (optional)
# Default: https://api.openai.com
# Examples: http://your-openai-proxy.com
BASE_URL=
# Specify OpenAI organization ID.(optional)
# Default: Empty
# If you do not want users to input their own API key, set this value to 1.
OPENAI_ORG_ID=
# (optional)
# Default: Empty
# If you do not want users to use GPT-4, set this value to 1.
DISABLE_GPT4=
# see https://next-auth.js.org/providers/linkedin
LINKEDIN_CLIENT_ID=
LINKEDIN_CLIENT_SECRET=
# use https://generate-secret.vercel.app/32 to generate secret
NEXTAUTH_SECRET=
NEXTAUTH_URL=
# if configured, sends a message to the hook for each sign-in
SLACK_WEBHOOK_URL=
+1
View File
@@ -0,0 +1 @@
public/serviceWorker.js
+9
View File
@@ -0,0 +1,9 @@
{
"extends": "next/core-web-vitals",
"plugins": ["prettier"],
"rules": {
"no-unused-vars": ["warn", { "args": "none" }],
"@next/next/no-img-element": "off"
},
"ignorePatterns": ["**/*.css"]
}
+43
View File
@@ -0,0 +1,43 @@
---
name: Bug report
about: Create a report to help us improve
title: "[Bug] "
labels: ''
assignees: ''
---
**Describe the bug**
A clear and concise description of what the bug is.
**To Reproduce**
Steps to reproduce the behavior:
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
4. See error
**Expected behavior**
A clear and concise description of what you expected to happen.
**Screenshots**
If applicable, add screenshots to help explain your problem.
**Deployment**
- [ ] Docker
- [ ] Vercel
- [ ] Server
**Desktop (please complete the following information):**
- OS: [e.g. iOS]
- Browser [e.g. chrome, safari]
- Version [e.g. 22]
**Smartphone (please complete the following information):**
- Device: [e.g. iPhone6]
- OS: [e.g. iOS8.1]
- Browser [e.g. stock browser, safari]
- Version [e.g. 22]
**Additional Logs**
Add any logs about the problem here.
+20
View File
@@ -0,0 +1,20 @@
---
name: Feature request
about: Suggest an idea for this project
title: "[Feature] "
labels: ''
assignees: ''
---
**Is your feature request related to a problem? Please describe.**
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
**Describe the solution you'd like**
A clear and concise description of what you want to happen.
**Describe alternatives you've considered**
A clear and concise description of any alternative solutions or features you've considered.
**Additional context**
Add any other context or screenshots about the feature request here.
+12
View File
@@ -0,0 +1,12 @@
# To get started with Dependabot version updates, you'll need to specify which
# package ecosystems to update and where the package manifests are located.
# Please see the documentation for all configuration options:
# https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates
version: 2
updates:
- package-ecosystem: "npm" # See documentation for possible values
directory: "/" # Location of package manifests
schedule:
interval: "weekly"
target-branch: "develop"
+46
View File
@@ -0,0 +1,46 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# 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*
# local env files
.env*.local
# vercel
.vercel
# typescript
*.tsbuildinfo
next-env.d.ts
dev
.vscode
.idea
# docker-compose env files
.env
*.key
*.key.pub
+11
View File
@@ -0,0 +1,11 @@
# This configuration file was automatically generated by Gitpod.
# Please adjust to your needs (see https://www.gitpod.io/docs/introduction/learn-gitpod/gitpod-yaml)
# and commit this file to your remote git repository to share the goodness with others.
# Learn more from ready-to-use templates: https://www.gitpod.io/docs/introduction/getting-started/quickstart
tasks:
- init: yarn install && yarn run dev
command: yarn run dev
+4
View File
@@ -0,0 +1,4 @@
#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"
npx lint-staged
+6
View File
@@ -0,0 +1,6 @@
{
"./app/**/*.{js,ts,jsx,tsx,json,html,css,md}": [
"eslint --fix",
"prettier --write"
]
}
+10
View File
@@ -0,0 +1,10 @@
module.exports = {
printWidth: 80,
tabWidth: 2,
useTabs: false,
semi: true,
singleQuote: false,
trailingComma: 'all',
bracketSpacing: true,
arrowParens: 'always',
};
+661
View File
@@ -0,0 +1,661 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<https://www.gnu.org/licenses/>.
+71
View File
@@ -0,0 +1,71 @@
<br /><br />
<p align="center">
<img src="./public/android-chrome-192x192.png" alt="Unc Logo" width="70">
</p>
<h3 align="center"><b>Unc</b></h3>
<p align="center"><b>A privacy-first, enterprise-ready, open-source ChatGPT platform</b></p>
<p>
<img
src="./public/screenshot.png"
alt="Unc Screen"
width="100%"
/>
</p>
Welcome to [Unc](https://unc.de). A robust, scalable open-source platform built specifically for implementing privacy-first, enterprise-level ChatGPT.
Getting started with Unc is a breeze. Visit [unc.de](https://unc.de) - a hosted version of Unc with no user authentication, provides an immediate start.
## 🚀 Features
Unc is enterprise-ready, featuring:
- Self-hosted, can be installed in own cloud (private or public).
- Chat with your own HTML and PDF documents.
- Create bots using prompt engineering (no-code) and share them with other users. This avoids the repetition of frequently used prompts.
- Supports [Azure OpenAI from Microsoft](https://azure.microsoft.com/en-us/products/ai-services/openai-service), eliminating traffic to OpenAI.
- Privacy first; personal data is stored locally in the browser.
## 💼 Enterprise
A typical enterprise installation requires:
- Custom user authentication (e.g. Active Directory).
- Installation in a corporate cloud (AWS or Azure).
- Integration with data from third-party systems (e.g., Salesforce, ServiceNow, SAP, Oracle).
For enterprise support and installations, reach out to me on
[LinkedIn](https://linkedin.com/marcusschiesser).
## ⚡️ Quick start
### Use Gitpod
[![Open in Gitpod](https://gitpod.io/button/open-in-gitpod.svg)](https://gitpod.io/#https://github.com/marcusschiesser/unc)
### Local Development
Requirement: [NodeJS](https://nodejs.org) 18
- Clone the repository
```bash
git clone https://github.com/marcusschiesser/unc
cd unc
```
- Run the dev server
```bash
yarn install
yarn dev
```
## ❤️ Community
Join the Unc community on [GitHub Discussions](https://github.com/marcusschiesser/unc/discussions). You can ask questions, share ideas, and showcase your projects.
Feedback is paramount. Please do share any suggestions, ideas, or bugs you encounter via [GitHub issues](https://github.com/marcusschiesser/unc/issues). Your insight is invaluable for enhancing future releases.
+3
View File
@@ -0,0 +1,3 @@
import { handlers } from "@/app/auth/auth-api";
export { handlers as GET, handlers as POST };
+28
View File
@@ -0,0 +1,28 @@
import { fetchContentFromURL } from "@/app/utils/content";
import { NextResponse, NextRequest } from "next/server";
export async function GET(request: NextRequest) {
const url = new URL(request.url);
const searchParams = new URLSearchParams(url.search);
const site = searchParams.get("site");
if (!site) {
return NextResponse.json(
{ error: "Missing site parameter" },
{ status: 400 },
);
}
const host = request.headers.get("host");
const protocol = request.headers.get("x-forwarded-proto") || "http";
const serverURL = `${protocol}://${host}`;
try {
const urlContent = await fetchContentFromURL(site, serverURL);
return NextResponse.json(urlContent);
} catch (error) {
return NextResponse.json(
{ error: (error as Error).message },
{ status: 400 },
);
}
}
+49
View File
@@ -0,0 +1,49 @@
import { getServerSideConfig } from "@/app/config/server";
import { NextRequest } from "next/server";
function getIP(req: NextRequest) {
let ip = req.ip ?? req.headers.get("x-real-ip");
const forwardedFor = req.headers.get("x-forwarded-for");
if (!ip && forwardedFor) {
ip = forwardedFor.split(",").at(0) ?? "";
}
return ip;
}
function parseApiKey(bearToken: string) {
const token = bearToken.trim().replaceAll("Bearer ", "").trim();
return {
apiKey: token,
};
}
export function auth(req: NextRequest) {
const authToken = req.headers.get("Authorization") ?? "";
// check if it is openai api key or user token
const { apiKey: token } = parseApiKey(authToken);
const serverConfig = getServerSideConfig();
console.log("[User IP] ", getIP(req));
console.log("[Time] ", new Date().toLocaleString());
// if user does not provide an api key, inject system api key
if (!token) {
const apiKey = serverConfig.apiKey;
if (apiKey) {
console.log("[Auth] use system api key");
req.headers.set("Authorization", `Bearer ${apiKey}`);
} else {
console.log("[Auth] admin did not provide an api key");
}
} else {
console.log("[Auth] use user api key");
}
return {
error: false,
};
}
+46
View File
@@ -0,0 +1,46 @@
import { prettyObject } from "@/app/utils/format";
import { NextRequest, NextResponse } from "next/server";
import { requestOpenai } from "../../common";
import { Bot } from "@/app/store/bot";
import { kv } from "@vercel/kv";
async function handle(
req: NextRequest,
{ params }: { params: { path: string[] } },
) {
console.log("[OpenAI Route] params ", params);
if (req.method === "OPTIONS") {
return NextResponse.json({ body: "OK" }, { status: 200 });
}
// lookup token of the shared bot via its id
const botId = params.path.shift();
// remove proxy prefix from pathname
req.nextUrl.pathname = req.nextUrl.pathname.replaceAll(
/\/api\/openai\/b\/[^\/]+\//g,
"/",
);
try {
const res: { bot: Bot } | null = await kv.get(botId!);
const token = res?.bot.share?.token || null;
if (token) {
req.headers.set("Authorization", "Bearer " + token);
}
} catch (e) {
console.error(`[OpenAI] failed to load bot with key ${botId}`, e);
return NextResponse.json(prettyObject(e));
}
try {
return await requestOpenai(req);
} catch (e) {
console.error("[OpenAI] ", e);
return NextResponse.json(prettyObject(e));
}
}
export const GET = handle;
export const POST = handle;
export const runtime = "edge";
+123
View File
@@ -0,0 +1,123 @@
import { NextRequest, NextResponse } from "next/server";
import { OpenaiPath } from "@/app/constant";
import { auth } from "./auth";
export const OPENAI_URL = "api.openai.com";
const DEFAULT_PROTOCOL = "https";
const PROTOCOL = process.env.PROTOCOL || DEFAULT_PROTOCOL;
const BASE_URL = process.env.BASE_URL || OPENAI_URL;
const DISABLE_GPT4 = !!process.env.DISABLE_GPT4;
const ALLOWED_PATHS = new Set(Object.values(OpenaiPath));
export async function requestOpenai(req: NextRequest) {
const controller = new AbortController();
const path = req.nextUrl.pathname.slice(1);
const fullPath = `${path}${req.nextUrl.search}`;
if (!ALLOWED_PATHS.has(path)) {
console.log("[OpenAI Route] forbidden path ", path);
return NextResponse.json(
{
error: true,
msg: "you are not allowed to request " + path,
},
{
status: 403,
},
);
}
const authResult = auth(req);
if (authResult.error) {
return NextResponse.json(authResult, {
status: 401,
});
}
const authValue = req.headers.get("Authorization") ?? "";
let baseUrl = BASE_URL;
if (!baseUrl.startsWith("http")) {
baseUrl = `${PROTOCOL}://${baseUrl}`;
}
if (baseUrl.endsWith("/")) {
baseUrl = baseUrl.slice(0, -1);
}
console.log("[Proxy] ", fullPath);
console.log("[Base Url]", baseUrl);
if (process.env.OPENAI_ORG_ID) {
console.log("[Org ID]", process.env.OPENAI_ORG_ID);
}
const timeoutId = setTimeout(
() => {
controller.abort();
},
10 * 60 * 1000,
);
const fetchUrl = `${baseUrl}/${fullPath}`;
const fetchOptions: RequestInit = {
headers: {
"Content-Type": "application/json",
"Cache-Control": "no-store",
Authorization: authValue,
...(process.env.OPENAI_ORG_ID && {
"OpenAI-Organization": process.env.OPENAI_ORG_ID,
}),
},
method: req.method,
body: req.body,
// to fix #2485: https://stackoverflow.com/questions/55920957/cloudflare-worker-typeerror-one-time-use-body
redirect: "manual",
// @ts-ignore
duplex: "half",
signal: controller.signal,
};
// #1815 try to refuse gpt4 request
if (DISABLE_GPT4 && req.body) {
try {
const clonedBody = await req.text();
fetchOptions.body = clonedBody;
const jsonBody = JSON.parse(clonedBody);
if ((jsonBody?.model ?? "").includes("gpt-4")) {
return NextResponse.json(
{
error: true,
message: "you are not allowed to use gpt-4 model",
},
{
status: 403,
},
);
}
} catch (e) {
console.error("[OpenAI] gpt4 filter", e);
}
}
try {
const res = await fetch(fetchUrl, fetchOptions);
// to prevent browser prompt for credentials
const newHeaders = new Headers(res.headers);
newHeaders.delete("www-authenticate");
// to disable nginx buffering
newHeaders.set("X-Accel-Buffering", "no");
return new Response(res.body, {
status: res.status,
statusText: res.statusText,
headers: newHeaders,
});
} finally {
clearTimeout(timeoutId);
}
}
+29
View File
@@ -0,0 +1,29 @@
import { prettyObject } from "@/app/utils/format";
import { NextRequest, NextResponse } from "next/server";
import { requestOpenai } from "../../common";
async function handle(
req: NextRequest,
{ params }: { params: { path: string[] } },
) {
console.log("[OpenAI Route] params ", params);
if (req.method === "OPTIONS") {
return NextResponse.json({ body: "OK" }, { status: 200 });
}
// remove proxy prefix from pathname
req.nextUrl.pathname = req.nextUrl.pathname.replaceAll("/api/openai/n/", "/");
try {
return await requestOpenai(req);
} catch (e) {
console.error("[OpenAI] ", e);
return NextResponse.json(prettyObject(e));
}
}
export const GET = handle;
export const POST = handle;
export const runtime = "edge";
+46
View File
@@ -0,0 +1,46 @@
import { kv } from "@vercel/kv";
import { NextRequest, NextResponse } from "next/server";
import { Bot } from "@/app/store/bot";
import { TTL } from "../common";
export async function PATCH(
req: NextRequest,
{ params }: { params: { id: string } },
) {
try {
const body: { shareToken: string } = await req.json();
const res: { bot: Bot } | null = await kv.get(params.id);
if (!res) {
throw new Error("Can't find bot with key " + params.id);
}
if (!res.bot.share) {
throw new Error(`Bot with key ${params.id} doesn't have share data`);
}
res.bot.share.token = body.shareToken;
const data = await kv.set<{ bot: Bot }>(params.id, res, {
ex: TTL,
});
if (!data) {
throw new Error(`Can't update bot with key ${params.id}`);
}
console.log(`[Share] updated shared key for bot with key ${params.id}`);
return NextResponse.json({});
} catch (error) {
console.error("[Share] error while updating bot", error);
return NextResponse.json(
{
error: true,
msg: (error as Error).message,
},
{
status: 500,
},
);
}
}
export const runtime = "edge";
+2
View File
@@ -0,0 +1,2 @@
export const DAYS_TO_LIVE = 30;
export const TTL = 60 * 60 * 24 * DAYS_TO_LIVE;
+68
View File
@@ -0,0 +1,68 @@
import { kv } from "@vercel/kv";
import { NextRequest, NextResponse } from "next/server";
import { nanoid } from "nanoid";
import { Bot } from "@/app/store/bot";
import { DAYS_TO_LIVE, TTL } from "./common";
const MAX_KEY_GENERATION_RETRY = 100;
export interface ShareResponse {
key: string;
url: string;
}
async function getKey() {
let key;
let counter = 0;
do {
key = nanoid();
counter++;
} while ((await kv.exists(key)) && counter < MAX_KEY_GENERATION_RETRY);
if (counter === MAX_KEY_GENERATION_RETRY) {
// Handle the case when a unique key was not found within the maximum allowed iterations
throw new Error("Failed to generate a unique key");
}
return key;
}
export async function POST(req: NextRequest) {
try {
const body: { bot: Bot } = await req.json();
const key = await getKey();
body.bot.share = { ...body.bot.share, id: key };
const data = await kv.set<{ bot: Bot }>(key, body, {
ex: TTL,
});
if (!data) {
throw new Error(`Can't store bot with key ${key}`);
}
const protocol = req.headers.get("x-forwarded-proto") || "http";
const url = `${protocol}://${req.headers.get("host")}/b/${key}`;
console.log(`[Share] shared bot '${body.bot.name}' created at ${url}`);
return NextResponse.json({
key: key,
url: url,
data: data,
days: DAYS_TO_LIVE,
} as ShareResponse);
} catch (error) {
console.error("[Share] error while sharing bot", error);
return NextResponse.json(
{
error: true,
msg: (error as Error).message,
},
{
status: 500,
},
);
}
}
export const runtime = "edge";
+54
View File
@@ -0,0 +1,54 @@
import NextAuth, { NextAuthOptions } from "next-auth";
import { Provider } from "next-auth/providers";
import LinkedInProvider from "next-auth/providers/linkedin";
import { getServerSideConfig } from "../config/server";
import BlankAvatar from "@/app/icons/blank_avatar.png";
import { sendSlackMessage } from "../slack/slack";
const configureIdentityProvider = () => {
const serverConfig = getServerSideConfig();
const providers: Array<Provider> = [];
if (serverConfig.linkedinClientId && serverConfig.linkedinClientSecret) {
providers.push(
LinkedInProvider({
clientId: serverConfig.linkedinClientId,
clientSecret: serverConfig.linkedinClientSecret,
authorization: {
params: { scope: "openid profile email" },
},
issuer: "https://www.linkedin.com",
jwks_endpoint: "https://www.linkedin.com/oauth/openid/jwks",
profile(profile, tokens) {
const defaultImage = BlankAvatar.src;
return {
id: profile.sub,
name: profile.name,
email: profile.email,
image: profile.picture ?? defaultImage,
};
},
}),
);
}
return providers;
};
export const options: NextAuthOptions = {
secret: process.env.NEXTAUTH_SECRET,
providers: [...configureIdentityProvider()],
session: {
strategy: "jwt",
},
events: {
async signIn(message) {
const serverConfig = getServerSideConfig();
if (!serverConfig.slackWebhookUrl) return;
sendSlackMessage(
`User signed in: ${message.profile?.name} - ${message.profile?.email}`,
);
},
},
};
export const handlers = NextAuth(options);
+33
View File
@@ -0,0 +1,33 @@
import { createHash } from "crypto";
import { getServerSession } from "next-auth";
import { options } from "./auth-api";
export const userSession = async (): Promise<UserModel | null> => {
const session = await getServerSession(options);
if (session && session.user) {
return session.user as UserModel;
}
return null;
};
export const userHashedId = async (): Promise<string> => {
const user = await userSession();
if (user) {
return hashValue(user.email);
}
throw new Error("User not found");
};
export type UserModel = {
name: string;
image: string;
email: string;
};
export const hashValue = (value: string): string => {
const hash = createHash("sha256");
hash.update(value);
return hash.digest("hex");
};
+7
View File
@@ -0,0 +1,7 @@
"use client";
import { SessionProvider } from "next-auth/react";
export const AuthProviders = ({ children }: { children: React.ReactNode }) => {
return <SessionProvider>{children}</SessionProvider>;
};
+40
View File
@@ -0,0 +1,40 @@
import { Home } from "@/app/components/home";
import { Bot } from "@/app/store/bot";
import { Analytics } from "@vercel/analytics/react";
import { kv } from "@vercel/kv";
export default async function App({ params }: { params: { botId: string } }) {
console.log(`[Share] try loading bot with key ${params.botId}`);
let bot: Bot | null = null;
try {
const res: { bot: Bot } | null = await kv.get(params.botId);
bot = res?.bot || null;
} catch (e) {
console.error(`[Share] failed to load bot with key ${params.botId}`, e);
}
if (!bot) {
console.log(`[Share] requested unknown bot with id ${params.botId}`);
return (
<>
Sorry, there is no bot at this URL. Try&nbsp;
<a href="/">creating your own bot</a>.
</>
);
}
if (bot.share?.token) {
// if the bot has a share token, hide it to the client, but tell the client that it has a token
bot.share.token = undefined;
bot.share.hasToken = true;
}
console.debug("[Share] bot loaded", bot);
return (
<>
<Home bot={bot} />
<Analytics />
</>
);
}
+171
View File
@@ -0,0 +1,171 @@
[
{
"avatar": "1f916",
"name": "GPT-4",
"context": [],
"modelConfig": {
"model": "gpt-4",
"temperature": 1,
"max_tokens": 8000,
"presence_penalty": 0,
"frequency_penalty": 0,
"sendMemory": true,
"historyMessageCount": 32,
"compressMessageLengthThreshold": 1000,
"template": "{{input}}",
"top_p": 1
},
"lang": "en",
"builtin": true
},
{
"avatar": "1f454",
"name": "CEO",
"context": [
{
"role": "system",
"content": "I want you to act as a Chief Executive Officer for a hypothetical company. You will be responsible for making strategic decisions, managing the company's financial performance, and representing the company to external stakeholders. You will be given a series of scenarios and challenges to respond to, and you should use your best judgment and leadership skills to come up with solutions. Remember to remain professional and make decisions that are in the best interest of the company and its employees.",
"date": ""
}
],
"modelConfig": {
"model": "gpt-4",
"temperature": 1,
"max_tokens": 8000,
"presence_penalty": 0,
"frequency_penalty": 0,
"sendMemory": true,
"historyMessageCount": 32,
"compressMessageLengthThreshold": 1000,
"template": "{{input}}",
"top_p": 1
},
"lang": "en",
"builtin": true
},
{
"avatar": "1f454",
"name": "Salesperson",
"context": [
{
"role": "system",
"content": "You are an experienced sales master with experience in multiple industries, B2B and B2C. You're online savvy and know how to get the deal done. Help me to write content.",
"date": ""
}
],
"modelConfig": {
"model": "gpt-4",
"temperature": 1,
"max_tokens": 8000,
"presence_penalty": 0,
"frequency_penalty": 0,
"sendMemory": true,
"historyMessageCount": 32,
"compressMessageLengthThreshold": 1000,
"template": "{{input}}",
"top_p": 1
},
"lang": "en",
"builtin": true
},
{
"avatar": "1f4da",
"name": "Proofreader",
"context": [
{
"role": "system",
"content": "I want you act as a proofreader. I will provide you texts and I would like you to review them for any spelling, grammar, or punctuation errors. Once you have finished reviewing the text, provide me with any necessary corrections or suggestions for improve the text.",
"date": ""
}
],
"modelConfig": {
"model": "gpt-4",
"temperature": 1,
"max_tokens": 8000,
"presence_penalty": 0,
"frequency_penalty": 0,
"sendMemory": true,
"historyMessageCount": 32,
"compressMessageLengthThreshold": 1000,
"template": "{{input}}",
"top_p": 1
},
"lang": "en",
"builtin": true
},
{
"avatar": "1f5a5-fe0f",
"name": "IT Expert",
"context": [
{
"role": "system",
"content": "I want you to act as an IT Expert. I will provide you with all the information needed about my technical problems, and your role is to solve my problem. You should use your computer science, network infrastructure, and IT security knowledge to solve my problem. Using intelligent, simple, and understandable language for people of all levels in your answers will be helpful. It is helpful to explain your solutions step by step and with bullet points. Try to avoid too many technical details, but use them when necessary. I want you to reply with the solution, not write any explanations.",
"date": ""
}
],
"modelConfig": {
"model": "gpt-4",
"temperature": 1,
"max_tokens": 8000,
"presence_penalty": 0,
"frequency_penalty": 0,
"sendMemory": true,
"historyMessageCount": 32,
"compressMessageLengthThreshold": 1000,
"template": "{{input}}",
"top_p": 1
},
"lang": "en",
"builtin": true
},
{
"avatar": "1f4da",
"name": "Legal Advisor",
"context": [
{
"role": "system",
"content": "I want you to act as my legal advisor. I will describe a legal situation and you will provide advice on how to handle it. You should only reply with your advice, and nothing else. Do not write explanations.",
"date": ""
}
],
"modelConfig": {
"model": "gpt-4",
"temperature": 1,
"max_tokens": 8000,
"presence_penalty": 0,
"frequency_penalty": 0,
"sendMemory": true,
"historyMessageCount": 32,
"compressMessageLengthThreshold": 1000,
"template": "{{input}}",
"top_p": 1
},
"lang": "en",
"builtin": true
},
{
"avatar": "1f454",
"name": "Recruiter",
"context": [
{
"role": "system",
"content": "I want you to act as a recruiter. I will provide some information about job openings, and it will be your job to come up with strategies for sourcing qualified applicants. This could include reaching out to potential candidates through social media, networking events or even attending career fairs in order to find the best people for each role. ",
"date": ""
}
],
"modelConfig": {
"model": "gpt-4",
"temperature": 1,
"max_tokens": 8000,
"presence_penalty": 0,
"frequency_penalty": 0,
"sendMemory": true,
"historyMessageCount": 32,
"compressMessageLengthThreshold": 1000,
"template": "{{input}}",
"top_p": 1
},
"lang": "en",
"builtin": true
}
]
+36
View File
@@ -0,0 +1,36 @@
import { Bot } from "../store/bot";
import bots from "./bots.json";
import { type BuiltinBot } from "./typing";
export { type BuiltinBot } from "./typing";
import Locale from "../locales";
export const BUILTIN_BOT_ID = 100000;
export const BUILTIN_BOT_STORE = {
buildinId: BUILTIN_BOT_ID,
bots: {} as Record<string, BuiltinBot>,
get(id?: string) {
if (!id) return undefined;
return this.bots[id] as Bot | undefined;
},
add(m: BuiltinBot) {
const bot = {
...m,
id: this.buildinId++,
builtin: true,
botHello: Locale.Store.BotHello,
};
this.bots[bot.id] = bot;
return bot;
},
getDefault(): Bot {
return this.bots[BUILTIN_BOT_ID] as Bot;
},
};
export const BUILTIN_BOTS: BuiltinBot[] = bots.map((m: any) =>
BUILTIN_BOT_STORE.add(m),
);
+10
View File
@@ -0,0 +1,10 @@
import { ModelConfig } from "../store";
import { type Bot } from "../store/bot";
export type BuiltinBot = Omit<
Bot,
"id" | "modelConfig" | "deployment" | "share" | "botHello"
> & {
builtin: Boolean;
modelConfig: Partial<ModelConfig>;
};
+20
View File
@@ -0,0 +1,20 @@
import { ModelType } from "../store";
import { LLMApi } from "./platforms/llm/interfaces";
import { OpenAIApi } from "./platforms/llm/openai";
export {
ROLES,
type LLMConfig,
type RequestMessage,
} from "./platforms/llm/interfaces";
export type ChatModel = ModelType;
export class ClientApi {
public llm: LLMApi;
constructor() {
this.llm = new OpenAIApi();
}
}
export const api = new ClientApi();
+37
View File
@@ -0,0 +1,37 @@
// To store message streaming controller
export const ChatControllerPool = {
controllers: {} as Record<string, AbortController>,
addController(
sessionId: string,
messageId: string,
controller: AbortController,
) {
const key = this.key(sessionId, messageId);
this.controllers[key] = controller;
return key;
},
stop(sessionId: string, messageId: string) {
const key = this.key(sessionId, messageId);
const controller = this.controllers[key];
controller?.abort();
},
stopAll() {
Object.values(this.controllers).forEach((v) => v.abort());
},
hasPending() {
return Object.values(this.controllers).length > 0;
},
remove(sessionId: string, messageId: string) {
const key = this.key(sessionId, messageId);
delete this.controllers[key];
},
key(sessionId: string, messageIndex: string) {
return `${sessionId},${messageIndex}`;
},
};
+36
View File
@@ -0,0 +1,36 @@
import { Share } from "@/app/store/bot";
export const ROLES = ["system", "user", "assistant", "URL"] as const;
export type MessageRole = (typeof ROLES)[number];
export const Models = ["gpt-3.5-turbo", "gpt-4"] as const;
export interface RequestMessage {
role: MessageRole;
content: string;
}
export interface LLMConfig {
model: string;
temperature?: number;
top_p?: number;
stream?: boolean;
presence_penalty?: number;
frequency_penalty?: number;
}
export interface ChatOptions {
messages: RequestMessage[];
config: LLMConfig;
token?: string;
share: Share | null;
onUpdate?: (message: string, chunk: string) => void;
onFinish: (message: string) => void;
onError?: (err: Error) => void;
onController?: (controller: AbortController) => void;
}
export abstract class LLMApi {
abstract chat(options: ChatOptions): Promise<void>;
}
+192
View File
@@ -0,0 +1,192 @@
import {
DEFAULT_API_HOST,
OpenaiPath,
REQUEST_TIMEOUT_MS,
} from "@/app/constant";
import { ChatOptions, LLMApi } from "./interfaces";
import Locale from "../../../locales";
import {
EventStreamContentType,
fetchEventSource,
} from "@fortaine/fetch-event-source";
import { prettyObject } from "@/app/utils/format";
import { Share } from "@/app/store/bot";
import { getClientConfig } from "@/app/config/client";
function getHeaders(token?: string) {
let headers: Record<string, string> = {
"Content-Type": "application/json",
"x-requested-with": "XMLHttpRequest",
};
const makeBearer = (token: string) => `Bearer ${token.trim()}`;
if (token && token.length > 0) {
headers.Authorization = makeBearer(token);
}
return headers;
}
export class OpenAIApi implements LLMApi {
path(path: string, share: Share | null = null): string {
const botId = share?.id;
const botHasToken = share?.hasToken || share?.token;
const clientConfig = getClientConfig();
if (clientConfig?.hasServerApiKey) {
// if the server has an api key configured, use it by calling the proxy
return `/api/openai/n/${path}`;
}
// use API proxy for bots with token
if (botId && botHasToken) {
return `/api/openai/b/${botId}/${path}`;
}
// all other calls can be direct without proxy
return [DEFAULT_API_HOST, path].join("/");
}
extractMessage(res: any) {
return res.choices?.at(0)?.message?.content ?? "";
}
async chat(options: ChatOptions) {
const messages = options.messages.map((v) => ({
role: v.role,
content: v.content,
}));
const requestPayload = {
messages,
stream: options.config.stream,
model: options.config.model,
temperature: options.config.temperature,
presence_penalty: options.config.presence_penalty,
frequency_penalty: options.config.frequency_penalty,
top_p: options.config.top_p,
};
console.log("[Request] openai payload: ", requestPayload);
const shouldStream = !!options.config.stream;
const controller = new AbortController();
options.onController?.(controller);
try {
const chatPath = this.path(OpenaiPath.ChatPath, options.share);
const chatPayload = {
method: "POST",
body: JSON.stringify(requestPayload),
signal: controller.signal,
headers: getHeaders(options.token),
};
// make a fetch request
const requestTimeoutId = setTimeout(
() => controller.abort(),
REQUEST_TIMEOUT_MS,
);
if (shouldStream) {
let responseText = "";
let finished = false;
const finish = () => {
if (!finished) {
options.onFinish(responseText);
finished = true;
}
};
controller.signal.onabort = finish;
await fetchEventSource(chatPath, {
...chatPayload,
async onopen(res) {
clearTimeout(requestTimeoutId);
const contentType = res.headers.get("content-type");
console.log(
"[OpenAI] request response content type: ",
contentType,
);
if (contentType?.startsWith("text/plain")) {
responseText = await res.clone().text();
return finish();
}
if (
!res.ok ||
!res.headers
.get("content-type")
?.startsWith(EventStreamContentType) ||
res.status !== 200
) {
const responseTexts = [responseText];
let extraInfo = await res.clone().text();
try {
const resJson = await res.clone().json();
extraInfo = prettyObject(resJson);
} catch {}
if (res.status === 401) {
responseTexts.push(Locale.Error.Unauthorized);
}
if (extraInfo) {
responseTexts.push(extraInfo);
}
responseText = responseTexts.join("\n\n");
return finish();
}
},
onmessage(msg) {
if (msg.data === "[DONE]" || finished) {
return finish();
}
const text = msg.data;
try {
const json = JSON.parse(text);
const delta = json.choices[0].delta.content;
if (delta) {
responseText += delta;
options.onUpdate?.(responseText, delta);
}
} catch (e) {
console.error("[Request] parse error", text, msg);
}
},
onclose() {
finish();
},
onerror(e) {
options.onError?.(e);
throw e;
},
openWhenHidden: true,
});
} else {
const res = await fetch(chatPath, chatPayload);
clearTimeout(requestTimeoutId);
const resJson = await res.json();
if (resJson.error) {
console.log("[Request] failed to make a chat request", resJson.error);
options.onError?.(resJson.error);
return;
}
const message = this.extractMessage(resJson);
options.onFinish(message);
}
} catch (e) {
console.log("[Request] failed to make a chat request", e);
options.onError?.(e as Error);
}
}
}
+95
View File
@@ -0,0 +1,95 @@
import telegramifyMarkdown from "telegramify-markdown";
const timeout: number = 10;
export enum ParseMode {
"MarkdownV2" = "MarkdownV2",
"HTML" = "HTML",
}
export interface PollUpdate {
update_id: number;
my_chat_member: {
chat: {
id: number;
};
};
message: {
chat: {
id: number;
};
text: string;
};
}
interface TelegramResponse {
ok: boolean;
result: PollUpdate[];
error_code?: number;
}
export interface PollResponse {
ok: boolean;
newOffset?: number;
description?: string;
error_code?: number;
}
export type PollUpdater = (update: PollUpdate) => void;
export class TelegramAPI {
sendMessage(
token: string,
chatId: number,
text: string,
parse_mode?: ParseMode,
): void {
if (parse_mode === ParseMode.MarkdownV2) {
// XXX: need to escape > and | symbols as telegramifyMarkdown doesn't do it
const clean = (text: string) => text.replace(/([>|])/g, "\\$1");
text = clean(telegramifyMarkdown(text));
}
const data = {
chat_id: chatId,
text: text,
parse_mode: parse_mode,
};
console.log("[Request] telegram payload: ", data);
fetch(`https://api.telegram.org/bot${token}/sendMessage`, {
method: "POST",
body: JSON.stringify(data),
headers: {
"Content-Type": "application/json",
},
}).catch(console.error);
}
async poll(
token: string,
updater: PollUpdater,
offset?: number,
): Promise<PollResponse> {
let url: string = `https://api.telegram.org/bot${token}/getUpdates?timeout=${timeout}`;
if (offset) url += "&offset=" + offset;
try {
const response = await fetch(url);
const data: TelegramResponse = await response.json();
if (!data.ok) {
return data;
}
const updates = data.result;
let newOffset: number | undefined;
if (updates.length > 0) {
newOffset = updates[updates.length - 1].update_id + 1;
}
updates.forEach((data) => updater(data));
return { ok: true, newOffset };
} catch (err: any) {
return { ok: false, description: err.message };
}
}
}
+34
View File
@@ -0,0 +1,34 @@
import { cn } from "@/app/lib/utils";
import { Bot } from "../../store/bot";
import BotOptions from "./bot-options";
import { BotItemContextProvider, useBot } from "./use-bot";
import { BotAvatar } from "@/app/components/ui/emoji";
function BotItemUI() {
const { bot, isActive, ensureSession } = useBot();
return (
<div
className={cn(
"flex items-center justify-between cursor-pointer mb-2 last:mb-0 rounded-md border-2 border-muted bg-popover p-4 hover:bg-accent hover:text-accent-foreground",
isActive && "border-primary",
)}
onClick={ensureSession}
>
<div className="flex items-center justify-between space-x-2">
<div className="w-[18px] h-[18px]">
<BotAvatar avatar={bot.avatar} />
</div>
<div className="font-medium">{bot.name}</div>
</div>
<BotOptions />
</div>
);
}
export default function BotItem(props: { bot: Bot }) {
return (
<BotItemContextProvider bot={props.bot}>
<BotItemUI />
</BotItemContextProvider>
);
}
+71
View File
@@ -0,0 +1,71 @@
import EditBotDialogContent from "@/app/components/bot/bot-options/edit-bot-dialog";
import { BotItemContextProvider } from "@/app/components/bot/use-bot";
import { Dialog, DialogTrigger } from "@/app/components/ui/dialog";
import { useChatStore } from "@/app/store";
import { PlusCircle } from "lucide-react";
import { useState } from "react";
import { useNavigate } from "react-router-dom";
import { Path } from "../../constant";
import Locale from "../../locales";
import { useBotStore } from "../../store/bot";
import { Button } from "../ui/button";
import { Input } from "../ui/input";
import { ScrollArea } from "../ui/scroll-area";
import BotItem from "./bot-item";
export default function BotList() {
const botStore = useBotStore();
const chatStore = useChatStore();
const navigate = useNavigate();
const [searchText, setSearchText] = useState("");
const [editBotId, setEditBotId] = useState<string | undefined>(undefined);
const onClickContainer = (e: React.MouseEvent) => {
if (e.target === e.currentTarget) {
navigate(Path.Home);
}
};
const onClickCreate = () => {
const newBot = botStore.create();
chatStore.ensureSession(newBot);
setEditBotId(newBot.id);
};
const allBots = botStore.getAll();
const filteredBots = allBots.filter((b) =>
b.name.toLowerCase().includes(searchText.toLowerCase()),
);
const botList = searchText.length > 0 ? filteredBots : allBots;
const editBot = botStore.get(editBotId);
return (
<div className="flex-1" onClick={onClickContainer}>
<div className="space-y-2 mb-4">
<Dialog>
<DialogTrigger asChild>
<Button className="w-full" onClick={onClickCreate}>
<PlusCircle className="mr-2 h-4 w-4" /> {Locale.Bot.Page.Create}
</Button>
</DialogTrigger>
{editBot && (
<BotItemContextProvider bot={editBot}>
<EditBotDialogContent />
</BotItemContextProvider>
)}
</Dialog>
<Input
className="text-center"
type="text"
placeholder={Locale.Bot.Page.Search(allBots.length)}
onInput={(e) => setSearchText(e.currentTarget.value)}
/>
</div>
<ScrollArea className="h-[60vh] pr-3">
{botList.map((b) => (
<BotItem key={b.id} bot={b} />
))}
</ScrollArea>
</div>
);
}
@@ -0,0 +1,36 @@
import { cn } from "@/app/lib/utils";
import Locale from "../../../locales";
import {
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from "../../ui/alert-dialog";
import { useBot } from "../use-bot";
import { buttonVariants } from "@/app/components/ui/button";
export default function DeleteBotDialogContent() {
const { deleteBot } = useBot();
return (
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Are you absolutely sure?</AlertDialogTitle>
<AlertDialogDescription>
{Locale.Bot.Item.DeleteConfirm}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction
className={cn(buttonVariants({ variant: "destructive" }))}
onClick={deleteBot}
>
Continue
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
);
}
@@ -0,0 +1,172 @@
import { getClientConfig } from "@/app/config/client";
import { useAccessStore } from "@/app/store";
import { DEFAULT_DEPLOYMENT, Deployment } from "@/app/store/deployment";
import { useWorkerStore } from "@/app/store/workers";
import { Ban, Zap } from "lucide-react";
import { useEffect, useState } from "react";
import Locale from "../../../locales";
import { Button } from "../../ui/button";
import { Card, CardContent } from "../../ui/card";
import {
DialogContent,
DialogFooter,
DialogHeader,
DialogTitle,
} from "../../ui/dialog";
import { Input } from "../../ui/input";
import { Separator } from "../../ui/separator";
import { useBot } from "../use-bot";
import { LoadingThreeDot } from "@/app/components/ui/loading";
enum Status {
Stopped = "STOPPED",
Starting = "STARTING",
Stopping = "STOPPING",
Running = "RUNNING",
InvalidToken = "INVALID_TOKEN",
Unknown = "UNKNOWN",
}
export default function DeployBotDialogContent() {
const { bot, updateBot } = useBot();
const workerStore = useWorkerStore();
const [status, setStatus] = useState(Status.Stopped);
const deployment = bot.deployment || DEFAULT_DEPLOYMENT;
const worker = deployment.worker_id
? workerStore.get(deployment.worker_id)
: null;
const updateConfig = (updater: (config: Deployment) => void) => {
const config = { ...deployment };
updater(config);
updateBot((bot) => {
bot.deployment = config;
});
};
const onChangeInput = (e: React.ChangeEvent<HTMLInputElement>) => {
updateConfig((config) => (config.token = e.currentTarget.value));
};
const startBot = () => {
const worker = new Worker(
new URL("../../../workers/telegram.ts", import.meta.url),
);
const accessStore = useAccessStore.getState();
const id = workerStore.create(worker);
const config = getClientConfig();
worker.postMessage({
command: "start",
data: {
token: deployment.token,
openaiToken: accessStore.token,
bot: bot,
config,
},
});
updateConfig((config) => (config.worker_id = id));
};
const stopBot = () => {
if (worker) {
worker.postMessage({ command: "stop" });
workerStore.delete(deployment.worker_id!);
updateConfig((config) => (config.worker_id = null));
}
};
const renderStatus = (status: Status | string) => {
switch (status) {
case Status.Stopped:
return "Bot not running.";
case Status.Starting:
case Status.Stopping:
return (
<div className="text-primary">
<LoadingThreeDot />
</div>
);
case Status.Running:
return "Bot running.";
case Status.InvalidToken:
status = "Invalid Telegram bot token. Please check.";
default:
return <span className="text-destructive">{status}</span>;
}
};
useEffect(() => {
// set status from worker and setup message callback
// from worker
if (worker) {
worker.onmessage = function (event) {
// Handle the received message here
const status: Status = event.data.status;
if (status === Status.Unknown) {
setStatus(event.data.error ?? Status.Unknown);
} else {
setStatus(status);
}
};
// if worker already exists, ask it of its last status, if we don't receive a message
// we assume that the worker is already stopped (which is ok as the default status is 'stopped')
worker.postMessage({ command: "get_status" });
}
}, [worker]);
return (
<DialogContent className="max-w-3xl">
<DialogHeader>
<DialogTitle>{Locale.Deploy.Config.Title}</DialogTitle>
</DialogHeader>
<Separator />
<Card>
<CardContent className="flex items-center justify-between p-6 gap-4">
<div className="w-1/2">
<div className="font-bold">{Locale.Deploy.Config.Token.Title}</div>
<div className="text-sm">
{Locale.Deploy.Config.Token.Hint}&nbsp;
<a
href="https://t.me/BotFather"
target="_blank"
className="text-primary"
>
https://t.me/BotFather
</a>
</div>
</div>
<Input
className="flex-1"
type="text"
value={bot.deployment?.token}
placeholder={Locale.Deploy.Config.Token.Placeholder}
onInput={onChangeInput}
/>
</CardContent>
</Card>
<DialogFooter className="items-center">
<div>{renderStatus(status)}</div>
<Button
disabled={
status === Status.Running ||
status === Status.Starting ||
status === Status.Stopping
}
onClick={startBot}
>
<Zap className="mr-2 w-4 h-4" />
{Locale.Deploy.Config.Start}
</Button>
<Button
variant="destructive"
disabled={status !== Status.Running}
onClick={stopBot}
>
<Ban className="mr-2 w-4 h-4" />
{Locale.Deploy.Config.Stop}
</Button>
</DialogFooter>
</DialogContent>
);
}
@@ -0,0 +1,19 @@
import Locale from "../../../locales";
import { DialogContent, DialogHeader, DialogTitle } from "../../ui/dialog";
import { ScrollArea } from "../../ui/scroll-area";
import { Separator } from "../../ui/separator";
import BotSettings from "../bot-settings";
export default function EditBotDialogContent() {
return (
<DialogContent className="max-w-4xl">
<DialogHeader>
<DialogTitle>{Locale.Bot.EditModal.Title}</DialogTitle>
</DialogHeader>
<Separator />
<ScrollArea className="h-[50vh] mt-4 pr-4">
<BotSettings />
</ScrollArea>
</DialogContent>
);
}
+91
View File
@@ -0,0 +1,91 @@
import {
ClipboardEdit,
Copy,
MoreHorizontal,
Share2,
XCircle,
Zap,
} from "lucide-react";
import { useState } from "react";
import Locale from "../../../locales";
import { AlertDialog, AlertDialogTrigger } from "../../ui/alert-dialog";
import { Button } from "../../ui/button";
import { Dialog, DialogTrigger } from "../../ui/dialog";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "../../ui/dropdown-menu";
import { useBot } from "../use-bot";
import DeleteBotDialogContent from "./delete-bot-dialog";
import EditBotDialogContent from "./edit-bot-dialog";
import DeployBotDialogContent from "./deploy-bot-dialog";
import ShareBotDialogContent from "./share-bot-dialog";
export default function BotOptions() {
const { isBuiltin, isShareble, cloneBot } = useBot();
const [dialogContent, setDialogContent] = useState<JSX.Element | null>(null);
return (
<Dialog>
<AlertDialog>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" className="h-8 w-8 p-0">
<span className="sr-only">Open menu</span>
<MoreHorizontal className="h-4 w-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent>
<DropdownMenuLabel>Options</DropdownMenuLabel>
<DropdownMenuSeparator />
<DropdownMenuItem onClick={cloneBot}>
<Copy className="mr-2 w-4 h-4" />
<span>{Locale.Bot.EditModal.Clone}</span>
</DropdownMenuItem>
<DialogTrigger asChild>
<DropdownMenuItem
disabled={isBuiltin}
onClick={() => setDialogContent(<EditBotDialogContent />)}
>
<ClipboardEdit className="mr-2 w-4 h-4" />
<span>{Locale.Bot.Item.Edit}</span>
</DropdownMenuItem>
</DialogTrigger>
<AlertDialogTrigger className="w-full">
<DropdownMenuItem
disabled={isBuiltin && !isShareble}
onClick={() => setDialogContent(<DeleteBotDialogContent />)}
>
<XCircle className="mr-2 w-4 h-4" />
<span>{Locale.Bot.Item.Delete}</span>
</DropdownMenuItem>
</AlertDialogTrigger>
<DialogTrigger asChild>
<DropdownMenuItem
disabled={isBuiltin && !isShareble}
onClick={() => setDialogContent(<DeployBotDialogContent />)}
>
<Zap className="mr-2 w-4 h-4" />
<span>{Locale.Bot.Item.Deploy}</span>
</DropdownMenuItem>
</DialogTrigger>
<DialogTrigger asChild>
<DropdownMenuItem
disabled={isBuiltin}
onClick={() => setDialogContent(<ShareBotDialogContent />)}
>
<Share2 className="mr-2 w-4 h-4" />
<span>{Locale.Bot.Item.Share}</span>
</DropdownMenuItem>
</DialogTrigger>
</DropdownMenuContent>
</DropdownMenu>
{dialogContent}
</AlertDialog>
</Dialog>
);
}
@@ -0,0 +1,172 @@
import { ShareResponse } from "@/app/api/share/route";
import ConfigItem from "@/app/components/bot/bot-settings/config-item";
import { Card, CardContent } from "@/app/components/ui/card";
import { Input } from "@/app/components/ui/input";
import { Bot, Share } from "@/app/store/bot";
import { copyToClipboard } from "@/app/utils";
import { Copy } from "lucide-react";
import { useEffect, useState } from "react";
import { useMutation } from "react-query";
import Locale from "../../../locales";
import { Button } from "../../ui/button";
import {
DialogContent,
DialogFooter,
DialogHeader,
DialogTitle,
} from "../../ui/dialog";
import { useBot } from "../use-bot";
import { useToast } from "@/app/components/ui/use-toast";
import { LoadingThreeDot } from "@/app/components/ui/loading";
async function share(bot: Bot): Promise<ShareResponse> {
const res = await fetch("/api/share", {
method: "POST",
body: JSON.stringify({ bot: bot }),
});
const json = await res.json();
console.log("[Share]", json);
if (!res.ok) {
throw new Error(json.msg);
}
return json;
}
async function patch(share: Share): Promise<void> {
if (!share.id) {
throw new Error("Can't patch without share id being set.");
}
const res = await fetch(`/api/share/${share.id}`, {
method: "PATCH",
body: JSON.stringify({ shareToken: share.token }),
});
const json = await res.json();
if (!res.ok) {
throw new Error(json.msg);
}
}
export default function ShareBotDialogContent() {
const { toast } = useToast();
const { bot, updateBot } = useBot();
const [showToken, setShowToken] = useState(bot.share?.token ? true : false);
const [token, setToken] = useState(bot.share?.token || "");
const shareMutation = useMutation(share, {
onSuccess: (data) => {
updateBot((bot) => {
bot.share = { ...bot.share, id: data.key };
});
},
});
const patchMutation = useMutation(patch);
const onClose = () => {
const newToken = showToken ? token : undefined;
if (bot.share && newToken !== bot.share.token) {
// token got changed, update it locally
const newShare = { ...bot.share!, token: newToken };
updateBot((bot) => {
bot.share = newShare;
});
// and on the server side if a key was generated
if (shareMutation.data) {
setTimeout(() => {
patchMutation.mutate(newShare, {
onError: () => {
toast({
title: Locale.Share.Token.Error,
variant: "destructive",
});
},
});
}, 0);
}
}
};
// FIXME: check dependency warning
useEffect(() => {
shareMutation.mutate(bot);
return () => {
onClose();
};
}, []);
return (
<DialogContent className="max-w-3xl">
<DialogHeader>
<DialogTitle>{Locale.Share.Title}</DialogTitle>
</DialogHeader>
<div>
{!shareMutation.error && (
<Card>
<CardContent className="divide-y pt-6">
<ConfigItem title={Locale.Share.Url.Title}>
{shareMutation.data ? (
<div className="flex flex-1 gap-4">
<Input
className="max-w-full flex-1"
type="text"
value={shareMutation.data.url}
readOnly
/>
<Button
variant="outline"
size="icon"
onClick={() =>
copyToClipboard(shareMutation.data.url, toast)
}
>
<Copy className="w-4 h-4" />
</Button>
</div>
) : (
<LoadingThreeDot />
)}
</ConfigItem>
{bot.share && (
<>
<ConfigItem
title={Locale.Share.ShowToken.Title}
subTitle={Locale.Share.ShowToken.SubTitle}
>
<input
type="checkbox"
checked={showToken}
onChange={(e) => setShowToken(!showToken)}
></input>
</ConfigItem>
{showToken && (
<ConfigItem
title={Locale.Share.Token.Title}
subTitle={Locale.Share.Token.SubTitle}
>
<Input
value={token}
type="password"
placeholder={Locale.Settings.Token.Placeholder}
onChange={(e) => {
setToken(e.currentTarget.value);
}}
/>
</ConfigItem>
)}
</>
)}
</CardContent>
</Card>
)}
</div>
<DialogFooter>
<div>
{shareMutation.error ? (
<span className="text-destructive">{Locale.Share.Url.Error}</span>
) : (
<div>{Locale.Share.Url.Hint}</div>
)}
</div>
</DialogFooter>
</DialogContent>
);
}
@@ -0,0 +1,80 @@
import { useBot } from "@/app/components/bot/use-bot";
import EmojiPicker, { Theme as EmojiTheme } from "emoji-picker-react";
import { useState } from "react";
import Locale from "../../../locales";
import { Card, CardContent } from "../../ui/card";
import { Checkbox } from "../../ui/checkbox";
import { Input } from "../../ui/input";
import { Popover, PopoverContent, PopoverTrigger } from "../../ui/popover";
import ConfigItem from "./config-item";
import { BotAvatar, getEmojiUrl } from "@/app/components/ui/emoji";
export default function BotConfig() {
const { bot, updateBot } = useBot();
const [showPicker, setShowPicker] = useState(false);
return (
<>
<div className="font-semibold mb-2">{Locale.Bot.Config.Title}</div>
<Card>
<CardContent className="divide-y p-5">
<ConfigItem title={Locale.Bot.Config.Avatar}>
<Popover open={showPicker}>
<PopoverTrigger onClick={() => setShowPicker(true)}>
<BotAvatar avatar={bot.avatar} />
</PopoverTrigger>
<PopoverContent align="end" className="w-fit">
<EmojiPicker
lazyLoadEmojis
theme={EmojiTheme.AUTO}
getEmojiUrl={getEmojiUrl}
onEmojiClick={(e) => {
updateBot((bot) => (bot.avatar = e.unified));
setShowPicker(false);
}}
/>
</PopoverContent>
</Popover>
</ConfigItem>
<ConfigItem title={Locale.Bot.Config.Name}>
<Input
type="text"
value={bot.name}
onInput={(e) =>
updateBot((bot) => {
bot.name = e.currentTarget.value;
})
}
/>
</ConfigItem>
<ConfigItem
title={Locale.Bot.Config.HideContext.Title}
subTitle={Locale.Bot.Config.HideContext.SubTitle}
>
<Checkbox
checked={bot.hideContext}
onCheckedChange={(checked) => {
updateBot((bot) => {
bot.hideContext = Boolean(checked);
});
}}
/>
</ConfigItem>
<ConfigItem
title={Locale.Bot.Config.BotHello.Title}
subTitle={Locale.Bot.Config.BotHello.SubTitle}
>
<Input
type="text"
value={bot.botHello || ""}
onChange={(e) => {
updateBot((bot) => {
bot.botHello = e.currentTarget.value;
});
}}
/>
</ConfigItem>
</CardContent>
</Card>
</>
);
}
@@ -0,0 +1,15 @@
export default function ConfigItem(props: {
title: string;
subTitle?: string;
children: JSX.Element;
}) {
return (
<div className="flex justify-between items-center min-h-[40px] px-3 py-5 gap-4 first:pt-0 last:pb-0">
<div className="w-1/2">
<div className="font-medium text-sm">{props.title}</div>
<div className="text-xs text-muted-foreground">{props.subTitle}</div>
</div>
<div className="text-sm">{props.children}</div>
</div>
);
}
@@ -0,0 +1,233 @@
import { Button } from "@/app/components/ui/button";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/app/components/ui/select";
import { Textarea } from "@/app/components/ui/textarea";
import { ArrowDownLeftSquare, PlusCircle, XCircle } from "lucide-react";
import { useQuery } from "react-query";
import { ROLES } from "../../../client/api";
import Locale from "../../../locales";
import { ChatMessage, createMessage } from "../../../store";
import { fetchSiteContent, isURL } from "../../../utils/url";
interface PromptInputStatusProps {
status: "loading" | "success" | "error";
detail: string;
}
const promptInputStatusStyle = {
loading: "text-yellow-500",
success: "text-primary",
error: "text-destructive",
};
function ContextPromptInputStatus(props: PromptInputStatusProps) {
return (
<div className={promptInputStatusStyle[props.status]}>{props.detail}</div>
);
}
function ContextPromptItem(props: {
index: number;
prompt: ChatMessage;
update: (prompt: ChatMessage) => void;
remove: () => void;
insert: () => void;
}) {
const requiredUrlInput = props.prompt.role === "URL";
const currentInputValue = props.prompt.urlDetail
? props.prompt.urlDetail.url
: props.prompt.content;
const invalidUrlInput =
!!currentInputValue && requiredUrlInput && !isURL(currentInputValue);
const isFetchContentSuccess = requiredUrlInput && !!props.prompt.urlDetail;
const { isLoading, error } = useQuery(
["content", currentInputValue],
() => fetchSiteContent(currentInputValue),
{
enabled: requiredUrlInput && isURL(currentInputValue),
refetchOnWindowFocus: false,
retry: false,
onSuccess: (urlDetail) => {
props.update({
...props.prompt,
content: urlDetail.content!,
urlDetail,
});
},
},
);
const handleUpdatePrompt = async (input: string) => {
props.update({
...props.prompt,
content: input,
urlDetail: undefined,
});
};
const getPromptInputStatus = (): PromptInputStatusProps | undefined => {
if (invalidUrlInput) {
return {
status: "error",
detail: "Please enter a valid URL",
};
}
const errorMsg = (error as any)?.message;
if (errorMsg) {
return {
status: "error",
detail: errorMsg,
};
}
if (isLoading) {
return {
status: "loading",
detail: "Fetching site content...",
};
}
if (isFetchContentSuccess) {
return {
status: "success",
detail: "The URL has been successfully retrieved.",
};
}
return undefined;
};
const promptInputStatus = getPromptInputStatus();
return (
<>
{promptInputStatus && <ContextPromptInputStatus {...promptInputStatus} />}
<div className="flex justify-center gap-2 w-full group items-start py-2">
<div className="flex gap-2 items-center">
<Select
value={props.prompt.role}
onValueChange={(value) =>
props.update({
...props.prompt,
role: value as any,
})
}
>
<SelectTrigger className="w-[120px]">
<SelectValue placeholder="Select role" />
</SelectTrigger>
<SelectContent>
{ROLES.map((r) => (
<SelectItem key={r} value={r}>
{r}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<Textarea
value={currentInputValue}
className={
"flex-1 max-w-full text-left min-h-0 ring-inset focus-visible:ring-offset-0"
}
rows={4}
onBlur={() => {
// If the selection is not removed when the user loses focus, some
// extensions like "Translate" will always display a floating bar
window?.getSelection()?.removeAllRanges();
}}
onInput={(e) => handleUpdatePrompt(e.currentTarget.value)}
/>
<div className="flex flex-col space-y-2">
<Button
variant="destructive"
size="icon"
onClick={() => props.remove()}
className="h-8 w-8"
>
<XCircle className="w-5 h-5" />
</Button>
<Button
variant="secondary"
size="icon"
onClick={() => props.insert()}
className="h-8 w-8"
>
<ArrowDownLeftSquare className="w-5 h-5" />
</Button>
</div>
</div>
</>
);
}
export function ContextPrompts(props: {
context: ChatMessage[];
updateContext: (updater: (context: ChatMessage[]) => void) => void;
}) {
const context = props.context;
const addContextPrompt = (prompt: ChatMessage, i: number) => {
props.updateContext((context) => context.splice(i, 0, prompt));
};
const createNewEmptyPrompt = () => {
addContextPrompt(
createMessage({
role: "user",
content: "",
date: "",
}),
props.context.length,
);
};
const removeContextPrompt = (i: number) => {
props.updateContext((context) => context.splice(i, 1));
};
const updateContextPrompt = (i: number, prompt: ChatMessage) => {
props.updateContext((context) => (context[i] = prompt));
};
return (
<>
<div className="mb-5">
<div className="font-semibold mb-2 flex items-center justify-between">
<span>{Locale.Context.Title}</span>
<Button variant="secondary" onClick={createNewEmptyPrompt}>
<PlusCircle className="mr-2 h-4 w-4" /> {Locale.Context.Add}
</Button>
</div>
{context.map((c, i) => (
<div key={i} className="p-2">
<ContextPromptItem
index={i}
prompt={c}
update={(prompt) => updateContextPrompt(i, prompt)}
remove={() => removeContextPrompt(i)}
insert={() => {
addContextPrompt(
createMessage({
role: "user",
content: "",
date: new Date().toLocaleString(),
}),
i + 1,
);
}}
/>
</div>
))}
</div>
</>
);
}
+36
View File
@@ -0,0 +1,36 @@
import { ContextPrompts } from "@/app/components/bot/bot-settings/context-prompt";
import { useBot } from "@/app/components/bot/use-bot";
import { ModelConfig } from "../../../store";
import BotConfig from "./bot-config";
import { ModelConfigList } from "./model-config";
import { Separator } from "@/app/components/ui/separator";
export default function BotSettings(props: { extraConfigs?: JSX.Element }) {
const { bot, updateBot } = useBot();
const updateConfig = (updater: (config: ModelConfig) => void) => {
if (bot.builtin) return;
const config = { ...bot.modelConfig };
updater(config);
updateBot((bot) => {
bot.modelConfig = config;
});
};
return (
<div className="space-y-5 pb-5">
<ContextPrompts
context={bot.context}
updateContext={(updater) => {
const context = bot.context.slice();
updater(context);
updateBot((bot) => (bot.context = context));
}}
/>
<Separator />
<BotConfig />
<ModelConfigList
modelConfig={{ ...bot.modelConfig }}
updateConfig={updateConfig}
/>
</div>
);
}
@@ -0,0 +1,208 @@
import { Checkbox } from "@/app/components/ui/checkbox";
import { Input, InputRange } from "@/app/components/ui/input";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/app/components/ui/select";
import Locale from "../../../locales";
import { ALL_MODELS, ModalConfigValidator, ModelConfig } from "../../../store";
import { Card, CardContent } from "../../ui/card";
import ConfigItem from "./config-item";
export function ModelConfigList(props: {
modelConfig: ModelConfig;
updateConfig: (updater: (config: ModelConfig) => void) => void;
}) {
return (
<Card>
<CardContent className="divide-y p-5">
<ConfigItem title={Locale.Settings.Model}>
<Select
value={props.modelConfig.model}
onValueChange={(value) => {
props.updateConfig(
(config) => (config.model = ModalConfigValidator.model(value)),
);
}}
>
<SelectTrigger className="w-[180px]">
<SelectValue placeholder="Select model" />
</SelectTrigger>
<SelectContent>
{ALL_MODELS.map((v) => (
<SelectItem value={v.name} key={v.name} disabled={!v.available}>
{v.name}
</SelectItem>
))}
</SelectContent>
</Select>
</ConfigItem>
<ConfigItem
title={Locale.Settings.Temperature.Title}
subTitle={Locale.Settings.Temperature.SubTitle}
>
<InputRange
value={props.modelConfig.temperature?.toFixed(1)}
min="0"
max="1" // lets limit it to 0-1
step="0.1"
onChange={(e) => {
props.updateConfig(
(config) =>
(config.temperature = ModalConfigValidator.temperature(
e.currentTarget.valueAsNumber,
)),
);
}}
></InputRange>
</ConfigItem>
<ConfigItem
title={Locale.Settings.TopP.Title}
subTitle={Locale.Settings.TopP.SubTitle}
>
<InputRange
value={(props.modelConfig.top_p ?? 1).toFixed(1)}
min="0"
max="1"
step="0.1"
onChange={(e) => {
props.updateConfig(
(config) =>
(config.top_p = ModalConfigValidator.top_p(
e.currentTarget.valueAsNumber,
)),
);
}}
></InputRange>
</ConfigItem>
<ConfigItem
title={Locale.Settings.MaxTokens.Title}
subTitle={Locale.Settings.MaxTokens.SubTitle}
>
<Input
type="number"
min={100}
max={100000}
value={props.modelConfig.max_tokens}
onChange={(e) =>
props.updateConfig(
(config) =>
(config.max_tokens = ModalConfigValidator.max_tokens(
e.currentTarget.valueAsNumber,
)),
)
}
/>
</ConfigItem>
<ConfigItem
title={Locale.Settings.PresencePenalty.Title}
subTitle={Locale.Settings.PresencePenalty.SubTitle}
>
<InputRange
value={props.modelConfig.presence_penalty?.toFixed(1)}
min="-2"
max="2"
step="0.1"
onChange={(e) => {
props.updateConfig(
(config) =>
(config.presence_penalty =
ModalConfigValidator.presence_penalty(
e.currentTarget.valueAsNumber,
)),
);
}}
></InputRange>
</ConfigItem>
<ConfigItem
title={Locale.Settings.FrequencyPenalty.Title}
subTitle={Locale.Settings.FrequencyPenalty.SubTitle}
>
<InputRange
value={props.modelConfig.frequency_penalty?.toFixed(1)}
min="-2"
max="2"
step="0.1"
onChange={(e) => {
props.updateConfig(
(config) =>
(config.frequency_penalty =
ModalConfigValidator.frequency_penalty(
e.currentTarget.valueAsNumber,
)),
);
}}
></InputRange>
</ConfigItem>
<ConfigItem
title={Locale.Settings.InputTemplate.Title}
subTitle={Locale.Settings.InputTemplate.SubTitle}
>
<Input
type="text"
value={props.modelConfig.template}
onChange={(e) =>
props.updateConfig(
(config) => (config.template = e.currentTarget.value),
)
}
></Input>
</ConfigItem>
<ConfigItem
title={Locale.Settings.HistoryCount.Title}
subTitle={Locale.Settings.HistoryCount.SubTitle}
>
<InputRange
title={props.modelConfig.historyMessageCount.toString()}
value={props.modelConfig.historyMessageCount}
min="0"
max="64"
step="1"
onChange={(e) =>
props.updateConfig(
(config) =>
(config.historyMessageCount = e.target.valueAsNumber),
)
}
></InputRange>
</ConfigItem>
<ConfigItem
title={Locale.Settings.CompressThreshold.Title}
subTitle={Locale.Settings.CompressThreshold.SubTitle}
>
<Input
type="number"
min={500}
max={4000}
value={props.modelConfig.compressMessageLengthThreshold}
onChange={(e) =>
props.updateConfig(
(config) =>
(config.compressMessageLengthThreshold =
e.currentTarget.valueAsNumber),
)
}
></Input>
</ConfigItem>
<ConfigItem title={Locale.Memory.Title} subTitle={Locale.Memory.Send}>
<Checkbox
checked={props.modelConfig.sendMemory}
onCheckedChange={(checked) =>
props.updateConfig(
(config) => (config.sendMemory = Boolean(checked)),
)
}
/>
</ConfigItem>
</CardContent>
</Card>
);
}
+74
View File
@@ -0,0 +1,74 @@
import { createContext, useContext } from "react";
import { useNavigate } from "react-router-dom";
import { Path } from "../../constant";
import { useChatStore } from "../../store";
import { Bot, useBotStore } from "../../store/bot";
import { useSidebarContext } from "../home";
import { Updater } from "@/app/typing";
const BotItemContext = createContext<{
bot: Bot;
isActive: boolean;
isBuiltin: boolean;
isShareble: boolean;
ensureSession: () => void;
cloneBot: () => void;
deleteBot: () => void;
updateBot: Updater<Bot>;
}>({} as any);
export const BotItemContextProvider = (props: {
bot: Bot;
children: JSX.Element;
}) => {
const bot = props.bot;
const chatStore = useChatStore();
const botStore = useBotStore();
const navigate = useNavigate();
const { setShowSidebar } = useSidebarContext();
const cloneBot = () => {
const newBot = botStore.create(bot, {
reset: true,
});
newBot.name = `My ${bot.name}`;
};
const isBuiltin = bot.builtin;
const isShareble = !!bot.share;
const ensureSession = () => {
navigate(Path.Home);
chatStore.ensureSession(bot);
setShowSidebar(false);
};
const deleteBot = () => {
botStore.delete(bot.id);
};
const updateBot: Updater<Bot> = (updater) => {
botStore.update(bot.id, updater);
};
const isActive = chatStore.currentSession().bot.id === props.bot.id;
return (
<BotItemContext.Provider
value={{
bot,
isActive,
isBuiltin,
isShareble,
ensureSession,
cloneBot,
deleteBot,
updateBot,
}}
>
{props.children}
</BotItemContext.Provider>
);
};
export const useBot = () => useContext(BotItemContext);
+50
View File
@@ -0,0 +1,50 @@
import { Button } from "@/app/components/ui/button";
import {
Tooltip,
TooltipContent,
TooltipProvider,
TooltipTrigger,
} from "@/app/components/ui/tooltip";
export function ChatAction(props: {
text: string;
icon: JSX.Element;
onClick: () => void;
showTitle?: boolean;
buttonVariant?: "ghost" | "outline";
}) {
const { text, icon, onClick, showTitle, buttonVariant } = props;
const buttonVariantDefault = "ghost";
const variant = buttonVariant || buttonVariantDefault;
if (!showTitle) {
return (
<TooltipProvider delayDuration={200}>
<Tooltip>
<TooltipTrigger asChild>
<div className="px-1">
<Button
size="icon"
variant={variant}
className="group"
onClick={onClick}
>
{icon}
</Button>
</div>
</TooltipTrigger>
<TooltipContent side="top" className="text-xs text-muted-foreground">
{text}
</TooltipContent>
</Tooltip>
</TooltipProvider>
);
}
return (
<Button size="sm" variant={variant} className="group" onClick={onClick}>
{icon}
<div className="text-xs text-muted-foreground ml-2">{text}</div>
</Button>
);
}
+512
View File
@@ -0,0 +1,512 @@
import { Button } from "@/app/components/ui/button";
import {
HoverCard,
HoverCardContent,
HoverCardTrigger,
} from "@/app/components/ui/hover-card";
import { LoadingThreeDot } from "@/app/components/ui/loading";
import { ScrollArea } from "@/app/components/ui/scroll-area";
import { Textarea } from "@/app/components/ui/textarea";
import { useToast } from "@/app/components/ui/use-toast";
import { useScrollToBottom } from "@/app/hooks/useScroll";
import { useSubmitHandler } from "@/app/hooks/useSubmit";
import { cn } from "@/app/lib/utils";
import { FileWrap } from "@/app/utils/file";
import { isURL } from "@/app/utils/url";
import {
Clipboard,
Eraser,
PauseCircle,
Send,
Trash,
Undo2,
} from "lucide-react";
import dynamic from "next/dynamic";
import React, { useEffect, useMemo, useRef, useState } from "react";
import { useDebouncedCallback } from "use-debounce";
import { ChatControllerPool } from "../../client/controller";
import {
ALLOWED_DOCUMENT_EXTENSIONS,
CHAT_PAGE_SIZE,
DOCUMENT_FILE_SIZE_LIMIT,
LAST_INPUT_KEY,
REQUEST_TIMEOUT_MS,
} from "../../constant";
import Locale from "../../locales";
import {
ChatMessage,
createMessage,
useAppConfig,
useChatStore,
} from "../../store";
import {
autoGrowTextArea,
copyToClipboard,
useMobileScreen,
} from "../../utils";
import { prettyObject } from "../../utils/format";
import { useSidebarContext } from "../home";
import FileUploader from "../ui/file-uploader";
import { Separator } from "../ui/separator";
import Typography from "../ui/typography";
import { ChatAction } from "./chat-action";
import { ClearContextDivider } from "./clear-context-divider";
type RenderMessage = ChatMessage & { preview?: boolean };
const Markdown = dynamic(
async () => (await import("../ui/markdown")).Markdown,
{
loading: () => <LoadingThreeDot />,
},
);
function ChatHeader() {
const isMobileScreen = useMobileScreen();
const { setShowSidebar } = useSidebarContext();
const chatStore = useChatStore();
const session = chatStore.currentSession();
return (
<div>
<div>
{isMobileScreen && (
<Button
size="icon"
variant="outline"
title={Locale.Chat.Actions.ChatList}
onClick={() => setShowSidebar(true)}
>
<Undo2 />
</Button>
)}
</div>
<div className="text-center py-4">
<Typography.H4>{session.bot.name}</Typography.H4>
<div className="text-sm text-muted-foreground">
{Locale.Chat.SubTitle(session.messages.length)}
</div>
</div>
<Separator />
</div>
);
}
export function Chat() {
const { toast } = useToast();
const chatStore = useChatStore();
const session = chatStore.currentSession();
const config = useAppConfig();
const fontSize = config.fontSize;
const inputRef = useRef<HTMLTextAreaElement>(null);
const [userInput, setUserInput] = useState("");
const [temporaryURLInput, setTemporaryURLInput] = useState("");
const { submitKey, shouldSubmit } = useSubmitHandler();
const { scrollRef, setAutoScroll, scrollDomToBottom } = useScrollToBottom();
const isMobileScreen = useMobileScreen();
// auto grow input
const [inputRows, setInputRows] = useState(2);
const measure = useDebouncedCallback(
() => {
const rows = inputRef.current ? autoGrowTextArea(inputRef.current) : 1;
const inputRows = Math.min(
20,
Math.max(2 + Number(!isMobileScreen), rows),
);
setInputRows(inputRows);
},
100,
{
leading: true,
trailing: true,
},
);
// eslint-disable-next-line react-hooks/exhaustive-deps
useEffect(measure, [userInput]);
const onInput = (text: string) => {
setUserInput(text);
};
const showError = (errMsg: string) => {
toast({
title: errMsg,
variant: "destructive",
});
};
const doSubmitFile = async (fileInput: FileWrap) => {
await chatStore.onUserInput(fileInput);
};
const doSubmit = (userInput: string) => {
if (userInput.trim() === "") return;
if (isURL(userInput)) {
setTemporaryURLInput(userInput);
}
chatStore.onUserInput(userInput).then(() => {
setTemporaryURLInput("");
});
localStorage.setItem(LAST_INPUT_KEY, userInput);
setUserInput("");
if (!isMobileScreen) inputRef.current?.focus();
setAutoScroll(true);
};
// stop response
const onUserStop = (messageId: string) => {
ChatControllerPool.stop(session.id, messageId);
};
useEffect(() => {
chatStore.updateCurrentSession((session) => {
const stopTiming = Date.now() - REQUEST_TIMEOUT_MS;
session.messages.forEach((m) => {
// check if should stop all stale messages
if (m.isError || new Date(m.date).getTime() < stopTiming) {
if (m.streaming) {
m.streaming = false;
}
if (m.content.length === 0) {
m.isError = true;
m.content = prettyObject({
error: true,
message: "empty response",
});
}
}
});
});
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
// check if should send message
const onInputKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
// if ArrowUp and no userInput, fill with last input
if (
e.key === "ArrowUp" &&
userInput.length <= 0 &&
!(e.metaKey || e.altKey || e.ctrlKey)
) {
setUserInput(localStorage.getItem(LAST_INPUT_KEY) ?? "");
e.preventDefault();
return;
}
if (shouldSubmit(e)) {
doSubmit(userInput);
e.preventDefault();
}
};
const deleteMessage = (msgId?: string) => {
chatStore.updateCurrentSession(
(session) =>
(session.messages = session.messages.filter((m) => m.id !== msgId)),
);
};
const onDelete = (msgId: string) => {
deleteMessage(msgId);
};
const context: RenderMessage[] = useMemo(() => {
return session.bot.hideContext ? [] : session.bot.context.slice();
}, [session.bot.context, session.bot.hideContext]);
const getUrlTypePrefix = (type: string) => {
if (type === "text/html") return "HTML";
if (type === "application/pdf") return "PDF";
if (type === "text/plain") return "TXT";
return Locale.Upload.UnknownFileType;
};
// preview messages
const renderMessages = useMemo(() => {
const getFrontendMessages = (messages: RenderMessage[]) => {
return messages.map((message) => {
if (!message.urlDetail) return message;
const urlTypePrefix = getUrlTypePrefix(message.urlDetail.type);
const sizeInKB = Math.round(message.urlDetail.size / 1024);
return {
...message,
content: `${message.urlDetail.url}\n\`${urlTypePrefix}${sizeInKB} KB\``,
};
});
};
const getUrlPreviewMessage = () => {
const lastMessage = session.messages[session.messages.length - 1];
const showPreviewUrl = temporaryURLInput && !lastMessage.streaming;
let previewUrlMessage: ChatMessage | undefined;
if (showPreviewUrl) {
previewUrlMessage = createMessage({
role: "user",
content: `${temporaryURLInput}\n\`${Locale.Chat.LoadingURL}\``,
});
}
return previewUrlMessage;
};
return context
.concat(
session.bot.botHello
? [
createMessage({
role: "assistant",
content: session.bot.botHello,
}),
]
: [],
)
.concat(getFrontendMessages(session.messages as RenderMessage[]))
.concat(getUrlPreviewMessage() || []);
}, [session.messages, session.bot.botHello, temporaryURLInput, context]);
const [msgRenderIndex, _setMsgRenderIndex] = useState(
Math.max(0, renderMessages.length - CHAT_PAGE_SIZE),
);
function setMsgRenderIndex(newIndex: number) {
newIndex = Math.min(renderMessages.length - CHAT_PAGE_SIZE, newIndex);
newIndex = Math.max(0, newIndex);
_setMsgRenderIndex(newIndex);
}
const messages = useMemo(() => {
const endRenderIndex = Math.min(
msgRenderIndex + 3 * CHAT_PAGE_SIZE,
renderMessages.length,
);
return renderMessages.slice(msgRenderIndex, endRenderIndex);
}, [msgRenderIndex, renderMessages]);
const onChatBodyScroll = (e: HTMLElement) => {
const bottomHeight = e.scrollTop + e.clientHeight;
const edgeThreshold = e.clientHeight;
const isTouchTopEdge = e.scrollTop <= edgeThreshold;
const isTouchBottomEdge = bottomHeight >= e.scrollHeight - edgeThreshold;
const isHitBottom = bottomHeight >= e.scrollHeight - 10;
const prevPageMsgIndex = msgRenderIndex - CHAT_PAGE_SIZE;
const nextPageMsgIndex = msgRenderIndex + CHAT_PAGE_SIZE;
if (isTouchTopEdge && !isTouchBottomEdge) {
setMsgRenderIndex(prevPageMsgIndex);
} else if (isTouchBottomEdge) {
setMsgRenderIndex(nextPageMsgIndex);
}
setAutoScroll(isHitBottom);
};
function scrollToBottom() {
setMsgRenderIndex(renderMessages.length - CHAT_PAGE_SIZE);
scrollDomToBottom();
}
// clear context index = context length + index in messages
const clearContextIndex =
(session.clearContextIndex ?? -1) >= 0
? session.clearContextIndex! +
context.length +
(session.bot.botHello ? 1 : 0) -
msgRenderIndex
: -1;
const autoFocus = !isMobileScreen; // wont auto focus on mobile screen
const stopAll = () => ChatControllerPool.stopAll();
const clearContext = () => {
chatStore.updateCurrentSession((session) => {
if (session.clearContextIndex === session.messages.length) {
session.clearContextIndex = undefined;
} else {
session.clearContextIndex = session.messages.length;
session.memoryPrompt = ""; // will clear memory
}
});
};
const couldStop = ChatControllerPool.hasPending();
return (
<div className="flex flex-col relative h-full" key={session.id}>
<ChatHeader />
<ScrollArea
className="flex-1 overflow-auto overflow-x-hidden relative overscroll-none pb-10 p-5"
ref={scrollRef}
onScroll={(e) => onChatBodyScroll(e.currentTarget)}
onMouseDown={() => inputRef.current?.blur()}
onTouchStart={() => {
inputRef.current?.blur();
setAutoScroll(false);
}}
>
<div className="space-y-5">
{messages.map((message, i) => {
const isUser = message.role === "user";
const isContext = i < context.length;
const showActions =
i > 0 &&
!(message.preview || message.content.length === 0) &&
!isContext;
const showTyping = message.preview || message.streaming;
const shouldShowClearContextDivider = i === clearContextIndex - 1;
return (
<div className="space-y-5" key={message.id}>
<div
className={
isUser
? "flex flex-row-reverse"
: "flex flex-row last:animate-[slide-in_ease_0.3s]"
}
>
<HoverCard openDelay={200}>
<HoverCardTrigger asChild>
<div
className={cn(
"max-w-[80%] flex flex-col items-start",
isUser && "items-end",
)}
>
{showTyping && (
<div
className={
"text-xs text-[#aaa] leading-normal my-1"
}
>
{Locale.Chat.Typing}
</div>
)}
<div
className={cn(
"box-border max-w-full text-sm select-text relative break-words rounded-lg px-3 py-2",
isUser
? "ml-auto bg-primary text-primary-foreground"
: "bg-muted",
)}
>
<Markdown
content={message.content}
loading={
(message.preview || message.streaming) &&
message.content.length === 0 &&
!isUser
}
onDoubleClickCapture={() => {
if (!isMobileScreen) return;
setUserInput(message.content);
}}
fontSize={fontSize}
parentRef={scrollRef}
defaultShow={i >= messages.length - 6}
/>
</div>
<div className="text-xs text-muted-foreground opacity-80 whitespace-nowrap text-right w-full box-border pointer-events-none z-[1]">
{isContext
? Locale.Chat.IsContext
: message.date.toLocaleString()}
</div>
</div>
</HoverCardTrigger>
{showActions && (
<HoverCardContent
side="top"
align={isUser ? "end" : "start"}
className="py-1 px-0 w-fit"
>
<div className="flex items-center divide-x">
{message.streaming ? (
<ChatAction
text={Locale.Chat.Actions.Stop}
icon={<PauseCircle className="w-4 h-4" />}
onClick={() => onUserStop(message.id ?? i)}
/>
) : (
<>
<ChatAction
text={Locale.Chat.Actions.Delete}
icon={<Trash className="w-4 h-4" />}
onClick={() => onDelete(message.id ?? i)}
/>
<ChatAction
text={Locale.Chat.Actions.Copy}
icon={<Clipboard className="w-4 h-4" />}
onClick={() =>
copyToClipboard(message.content, toast)
}
/>
</>
)}
</div>
</HoverCardContent>
)}
</HoverCard>
</div>
{shouldShowClearContextDivider && <ClearContextDivider />}
</div>
);
})}
</div>
</ScrollArea>
<Separator />
<div className="relative w-full box-border flex-col pt-2.5 p-5 space-y-2">
<div className="flex justify-between items-center">
<ChatAction
text={Locale.Chat.InputActions.Clear}
icon={<Eraser className="w-4 h-4" />}
onClick={clearContext}
showTitle
buttonVariant="outline"
/>
{couldStop && (
<ChatAction
onClick={stopAll}
text={Locale.Chat.InputActions.Stop}
icon={<PauseCircle className="w-4 h-4" />}
showTitle
buttonVariant="outline"
/>
)}
</div>
<div className="flex flex-1 items-center">
<Textarea
className="ring-inset focus-visible:ring-offset-0"
ref={inputRef}
placeholder={Locale.Chat.Input(submitKey)}
onInput={(e) => onInput(e.currentTarget.value)}
value={userInput}
onKeyDown={onInputKeyDown}
onFocus={scrollToBottom}
onClick={scrollToBottom}
rows={inputRows}
autoFocus={autoFocus}
style={{
fontSize: config.fontSize,
}}
/>
<div className="flex items-center gap-2.5 absolute right-[35px]">
<FileUploader
config={{
inputId: "document-uploader",
allowedExtensions: ALLOWED_DOCUMENT_EXTENSIONS,
fileSizeLimit: DOCUMENT_FILE_SIZE_LIMIT,
}}
onUpload={doSubmitFile}
onError={showError}
/>
<Button onClick={() => doSubmit(userInput)}>
<Send className="h-4 w-4 mr-2" />
{isMobileScreen ? undefined : Locale.Chat.Send}
</Button>
</div>
</div>
</div>
</div>
);
}
@@ -0,0 +1,29 @@
import { useChatStore } from "../../store";
import Locale from "../../locales";
import { Card, CardContent } from "@/app/components/ui/card";
export function ClearContextDivider() {
const chatStore = useChatStore();
return (
<Card
className="cursor-pointer hover:border-primary rounded-sm"
onClick={() =>
chatStore.updateCurrentSession(
(session) => (session.clearContextIndex = undefined),
)
}
>
<CardContent className="p-1 group text-foreground hover:text-primary">
<div className="text-center text-xs font-semibold">
<span className="inline-block group-hover:hidden opacity-50">
{Locale.Context.Clear}
</span>
<span className="hidden group-hover:inline-block">
{Locale.Context.Revert}
</span>
</div>
</CardContent>
</Card>
);
}
+220
View File
@@ -0,0 +1,220 @@
"use client";
require("../polyfill");
import React, { useContext, useEffect, useState } from "react";
import { QueryClient, QueryClientProvider } from "react-query";
import { getCSSVar, useMobileScreen } from "../utils";
import dynamic from "next/dynamic";
import { Path, SlotID } from "../constant";
import { ErrorBoundary } from "./layout/error";
import { getLang } from "../locales";
import { useSession } from "next-auth/react";
import {
Route,
HashRouter as Router,
Routes,
useNavigate,
} from "react-router-dom";
import { getClientConfig } from "../config/client";
import { useChatStore } from "../store";
import { Bot, useBotStore } from "../store/bot";
import { useAppConfig } from "../store/config";
import LoginPage from "./login";
import { SideBar } from "./layout/sidebar";
import { LoadingModule } from "@/app/components/ui/loading";
const SettingsPage = dynamic(
async () => (await import("./settings")).Settings,
{
loading: () => <LoadingModule />,
},
);
const ChatPage = dynamic(async () => (await import("./chat/chat")).Chat, {
loading: () => <LoadingModule />,
});
export function useSwitchTheme() {
const config = useAppConfig();
useEffect(() => {
document.body.classList.remove("light");
document.body.classList.remove("dark");
if (config.theme === "dark") {
document.body.classList.add("dark");
} else if (config.theme === "light") {
document.body.classList.add("light");
}
const metaDescriptionDark = document.querySelector(
'meta[name="theme-color"][media*="dark"]',
);
const metaDescriptionLight = document.querySelector(
'meta[name="theme-color"][media*="light"]',
);
if (config.theme === "auto") {
metaDescriptionDark?.setAttribute("content", "#151515");
metaDescriptionLight?.setAttribute("content", "#fafafa");
} else {
const themeColor = getCSSVar("--theme-color");
metaDescriptionDark?.setAttribute("content", themeColor);
metaDescriptionLight?.setAttribute("content", themeColor);
}
}, [config.theme]);
}
function useHtmlLang() {
useEffect(() => {
const lang = getLang();
const htmlLang = document.documentElement.lang;
if (lang !== htmlLang) {
document.documentElement.lang = lang;
}
}, []);
}
const useHasHydrated = () => {
const [hasHydrated, setHasHydrated] = useState<boolean>(false);
useEffect(() => {
setHasHydrated(true);
}, []);
return hasHydrated;
};
const loadAsyncGoogleFont = () => {
const linkEl = document.createElement("link");
const proxyFontUrl = "/google-fonts";
const remoteFontUrl = "https://fonts.googleapis.com";
const googleFontUrl =
getClientConfig()?.buildMode === "export" ? remoteFontUrl : proxyFontUrl;
linkEl.rel = "stylesheet";
linkEl.href =
googleFontUrl + "/css2?family=Noto+Sans:wght@300;400;700;900&display=swap";
document.head.appendChild(linkEl);
};
// if a bot is passed this HOC ensures that the bot is added to the store
// and that the user can directly have a chat session with it
function withBot(Component: React.FunctionComponent, bot?: Bot) {
return function WithBotComponent() {
const [botInitialized, setBotInitialized] = useState(false);
const navigate = useNavigate();
const botStore = useBotStore();
const chatStore = useChatStore();
if (bot && !botInitialized) {
if (!bot.share?.id) {
throw new Error("bot must have a shared id");
}
// ensure that bot for the same share id is not created a 2nd time
let sharedBot = botStore.getByShareId(bot.share?.id);
if (!sharedBot) {
sharedBot = botStore.create(bot, { readOnly: true });
}
// let the user directly chat with the bot
chatStore.ensureSession(sharedBot);
setTimeout(() => {
// redirect to chat - use history API to clear URL
history.pushState({}, "", "/");
navigate(Path.Chat);
}, 1);
setBotInitialized(true);
return <LoadingModule />;
}
return <Component />;
};
}
const SidebarContext = React.createContext<{
showSidebar: boolean;
setShowSidebar: (show: boolean) => void;
} | null>(null);
function SidebarContextProvider(props: { children: React.ReactNode }) {
const [showSidebar, setShowSidebar] = useState(true);
return (
<SidebarContext.Provider value={{ showSidebar, setShowSidebar }}>
{props.children}
</SidebarContext.Provider>
);
}
export const useSidebarContext = () => {
const context = useContext(SidebarContext);
if (!context) {
throw new Error(
"useSidebarContext must be used within an SidebarContextProvider",
);
}
return context;
};
function Screen() {
const isMobileScreen = useMobileScreen();
const { showSidebar } = useSidebarContext();
const { data: session, status } = useSession();
const clientConfig = getClientConfig();
const showSidebarOnMobile = showSidebar || !isMobileScreen;
useEffect(() => {
loadAsyncGoogleFont();
}, []);
if (status === "loading") return <LoadingModule />;
return (
<main className="flex overflow-hidden h-screen w-screen box-border">
{clientConfig.hasNextAuth && !session ? (
<LoginPage />
) : (
<>
{showSidebarOnMobile && <SideBar />}
<div id={SlotID.AppBody} className="flex-1 overflow-hidden">
<Routes>
<Route path={Path.Chat} element={<ChatPage />} />
<Route path={Path.Settings} element={<SettingsPage />} />
</Routes>
</div>
</>
)}
</main>
);
}
export function Home({ bot }: { bot?: Bot }) {
useSwitchTheme();
useHtmlLang();
useEffect(() => {
console.log("[Config] got config from build time", getClientConfig());
}, []);
if (!useHasHydrated()) {
return <LoadingModule />;
}
const BotScreen = withBot(Screen, bot);
const queryClient = new QueryClient();
return (
<ErrorBoundary>
<Router>
<QueryClientProvider client={queryClient}>
<SidebarContextProvider>
<BotScreen />
</SidebarContextProvider>
</QueryClientProvider>
</Router>
</ErrorBoundary>
);
}
+111
View File
@@ -0,0 +1,111 @@
import React from "react";
import { LINKEDIN_URL } from "../../constant";
import Locale from "../../locales";
import { downloadAs } from "../../utils";
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
AlertDialogTrigger,
} from "@/app/components/ui/alert-dialog";
import { cn } from "@/app/lib/utils";
import { Button, buttonVariants } from "@/app/components/ui/button";
import { Linkedin, RefreshCcw } from "lucide-react";
import {
Card,
CardContent,
CardHeader,
CardTitle,
} from "@/app/components/ui/card";
interface IErrorBoundaryState {
hasError: boolean;
error: Error | null;
info: React.ErrorInfo | null;
}
export class ErrorBoundary extends React.Component<any, IErrorBoundaryState> {
constructor(props: any) {
super(props);
this.state = { hasError: false, error: null, info: null };
}
componentDidCatch(error: Error, info: React.ErrorInfo) {
// Update state with error details
this.setState({ hasError: true, error, info });
}
clearAndSaveData() {
try {
downloadAs(JSON.stringify(localStorage), "unc-snapshot.json");
} finally {
localStorage.clear();
location.reload();
}
}
render() {
if (this.state.hasError) {
// Render error message
return (
<div className="flex items-center justify-center w-screen h-screen">
<Card className="bg-background text-sm rounded-md w-4/5 mx-auto">
<CardHeader>
<CardTitle>Oops, something went wrong!</CardTitle>
</CardHeader>
<CardContent className="space-y-5">
<pre className="overflow-auto text-xs h-[500px]">
<code>{this.state.error?.toString()}</code>
<code>{this.state.info?.componentStack}</code>
</pre>
<div className="flex justify-between">
<Button
variant="outline"
size="sm"
onClick={() => window.open(LINKEDIN_URL, "_blank")}
>
<Linkedin className="mr-2 h-4 w-4" />
<span>Report This Error</span>
</Button>
<AlertDialog>
<AlertDialogTrigger asChild>
<Button variant="outline">
<RefreshCcw className="mr-2 h-4 w-4" />
<span>Clear All Data</span>
</Button>
</AlertDialogTrigger>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>
{Locale.Settings.Danger.Reset.Confirm}
</AlertDialogTitle>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction
className={cn(
buttonVariants({ variant: "destructive" }),
)}
onClick={() => {
this.clearAndSaveData();
}}
>
Continue
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
</CardContent>
</Card>
</div>
);
}
// if no error occurred, render children
return this.props.children;
}
}
+109
View File
@@ -0,0 +1,109 @@
import { ThemeToggle } from "@/app/components/layout/theme-toggle";
import { Linkedin, LogOut, Settings } from "lucide-react";
import { signOut, useSession } from "next-auth/react";
import dynamic from "next/dynamic";
import { useNavigate } from "react-router-dom";
import { getClientConfig } from "../../config/client";
import { LINKEDIN_URL, Path } from "../../constant";
import Locale from "../../locales";
import { Avatar, AvatarFallback, AvatarImage } from "../ui/avatar";
import { Button } from "../ui/button";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "../ui/dropdown-menu";
import Typography from "../ui/typography";
const BotList = dynamic(async () => (await import("../bot/bot-list")).default, {
loading: () => null,
});
export function SideBar(props: { className?: string }) {
const { data: session } = useSession();
const clientConfig = getClientConfig();
const navigate = useNavigate();
const dropdownItems = [
{
icon: <Settings className="mr-2 h-4 w-4" />,
text: Locale.Home.Settings,
action: () => {
navigate(Path.Settings);
},
},
{
icon: <LogOut className="mr-2 h-4 w-4" />,
text: Locale.Home.Logout,
action: () => {
signOut();
},
},
];
const shortUsername = session?.user?.name!.substring(0, 2).toUpperCase();
return (
<div className="h-full relative group border-r w-[300px]">
<div className="w-full h-full p-5 flex flex-col gap-5">
<div className="flex flex-col flex-1">
<div className="mb-5 flex justify-between gap-5 items-start">
<div>
<Typography.H1>{Locale.Welcome.Title}</Typography.H1>
<div className="text-sm text-muted-foreground">
{Locale.Welcome.SubTitle}
</div>
</div>
<ThemeToggle />
</div>
<BotList />
</div>
<div className="flex items-center justify-between">
{clientConfig.hasNextAuth ? (
<DropdownMenu>
<DropdownMenuTrigger>
<Avatar>
<AvatarImage src={session?.user?.image!} />
<AvatarFallback>{shortUsername}</AvatarFallback>
</Avatar>
</DropdownMenuTrigger>
<DropdownMenuContent>
<DropdownMenuLabel>Preferences</DropdownMenuLabel>
<DropdownMenuSeparator />
{dropdownItems.map((item) => (
<DropdownMenuItem key={item.text} onClick={item.action}>
{item.icon}
<span>{item.text}</span>
</DropdownMenuItem>
))}
</DropdownMenuContent>
</DropdownMenu>
) : (
<Button
variant="secondary"
size="icon"
onClick={() => {
navigate(Path.Settings);
}}
>
<Settings className="h-4 w-4" />
</Button>
)}
<Button
variant="outline"
size="sm"
onClick={() => window.open(LINKEDIN_URL, "_blank")}
>
<Linkedin className="mr-2 h-4 w-4" />
<span>{Locale.Home.LinkedIn}</span>
</Button>
</div>
</div>
</div>
);
}
+9
View File
@@ -0,0 +1,9 @@
"use client";
import * as React from "react";
import { ThemeProvider as NextThemesProvider } from "next-themes";
import { type ThemeProviderProps } from "next-themes/dist/types";
export function ThemeProvider({ children, ...props }: ThemeProviderProps) {
return <NextThemesProvider {...props}>{children}</NextThemesProvider>;
}
+23
View File
@@ -0,0 +1,23 @@
"use client";
import * as React from "react";
import { Moon, Sun } from "lucide-react";
import { useTheme } from "next-themes";
import { Button } from "@/app/components/ui/button";
export function ThemeToggle() {
const { setTheme, theme } = useTheme();
return (
<Button
variant="ghost"
size="icon"
onClick={() => setTheme(theme === "light" ? "dark" : "light")}
>
<Sun className="h-[1.5rem] w-[1.3rem] dark:hidden" />
<Moon className="hidden h-5 w-5 dark:block" />
<span className="sr-only">Toggle theme</span>
</Button>
);
}
+83
View File
@@ -0,0 +1,83 @@
import { Linkedin } from "lucide-react";
import { signIn } from "next-auth/react";
import Link from "next/link";
import { LINKEDIN_URL } from "../constant";
import Locale from "../locales";
import { Button, buttonVariants } from "./ui/button";
import { cn } from "../lib/utils";
export default function LoginPage() {
return (
<div className="container relative hidden flex-col items-center justify-center md:grid lg:max-w-none lg:grid-cols-2 lg:px-0">
<Link
href={LINKEDIN_URL}
className={cn(
buttonVariants({ variant: "ghost" }),
"absolute right-4 top-4 md:right-8 md:top-8",
)}
>
Contact
</Link>
<div className="relative hidden h-full flex-col bg-muted p-10 text-white dark:border-r lg:flex">
<div className="absolute inset-0 bg-zinc-900" />
<div className="relative z-20 flex items-center text-lg font-medium">
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
className="mr-2 h-6 w-6"
>
<path d="M15 6v12a3 3 0 1 0 3-3H6a3 3 0 1 0 3 3V6a3 3 0 1 0-3 3h12a3 3 0 1 0-3-3" />
</svg>
{Locale.Welcome.Title}
</div>
<div className="relative z-20 mt-auto">
<blockquote className="space-y-2">
<p className="text-lg">{Locale.Welcome.Quote}</p>
<footer className="text-sm">Marcus Schmitt</footer>
</blockquote>
</div>
</div>
<div className="lg:p-8">
<div className="mx-auto flex w-full flex-col justify-center space-y-6 sm:w-[350px]">
<div className="flex flex-col space-y-6 text-center">
<h1 className="text-2xl font-semibold tracking-tight mx-10">
{Locale.Welcome.SubTitle}
</h1>
<div>
<Button
variant="outline"
size="lg"
onClick={() => signIn("linkedin")}
>
<Linkedin className="mr-2 h-4 w-4 text-[#0a66c2]" />
{Locale.Welcome.LoginLinkedinTitle}
</Button>
</div>
<p className="px-8 text-center text-sm text-muted-foreground">
By clicking login, you agree to our{" "}
<Link
href="#"
className="underline underline-offset-4 hover:text-primary"
>
Terms of Service
</Link>{" "}
and{" "}
<Link
href="#"
className="underline underline-offset-4 hover:text-primary"
>
Privacy Policy
</Link>
.
</p>
</div>
</div>
</div>
</div>
);
}
+325
View File
@@ -0,0 +1,325 @@
import ConfigItem from "@/app/components/bot/bot-settings/config-item";
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
AlertDialogTrigger,
} from "@/app/components/ui/alert-dialog";
import { Button, buttonVariants } from "@/app/components/ui/button";
import { Card, CardContent } from "@/app/components/ui/card";
import { Input, InputRange } from "@/app/components/ui/input";
import {
Popover,
PopoverContent,
PopoverTrigger,
} from "@/app/components/ui/popover";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/app/components/ui/select";
import { Separator } from "@/app/components/ui/separator";
import Typography from "@/app/components/ui/typography";
import { useToast } from "@/app/components/ui/use-toast";
import { ArchiveRestore, HardDriveDownload, X } from "lucide-react";
import { useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
import { getClientConfig } from "../config/client";
import { FileName, Path } from "../constant";
import Locale from "../locales";
import {
SubmitKey,
Theme,
useAccessStore,
useAppConfig,
useChatStore,
} from "../store";
import { useBotStore } from "../store/bot";
import { downloadAs, readFromFile } from "../utils";
import { ErrorBoundary } from "./layout/error";
import { BotAvatar, EmojiAvatarPicker } from "./ui/emoji";
import { cn } from "@/app/lib/utils";
function SettingHeader() {
const navigate = useNavigate();
return (
<div className="relative flex justify-between items-center px-5 py-3.5">
<div>
<Typography.H4>{Locale.Settings.Title}</Typography.H4>
<div className="text-sm text-muted-foreground">
{Locale.Settings.SubTitle}
</div>
</div>
<Button variant="outline" size="icon" onClick={() => navigate(Path.Home)}>
<X className="w-4 h-4" />
</Button>
</div>
);
}
function CommonSettings() {
const [showEmojiPicker, setShowEmojiPicker] = useState(false);
const config = useAppConfig();
const updateConfig = config.update;
const clientConfig = getClientConfig();
const accessStore = useAccessStore();
return (
<>
<Card>
<CardContent className="divide-y p-5">
<ConfigItem title={Locale.Settings.Avatar}>
<Popover open={showEmojiPicker}>
<PopoverTrigger onClick={() => setShowEmojiPicker(true)}>
<BotAvatar avatar={config.avatar} />
</PopoverTrigger>
<PopoverContent align="end" className="w-fit">
<EmojiAvatarPicker
onEmojiClick={(avatar: string) => {
updateConfig((config) => (config.avatar = avatar));
setShowEmojiPicker(false);
}}
/>
</PopoverContent>
</Popover>
</ConfigItem>
<ConfigItem title={Locale.Settings.SendKey}>
<Select
value={config.submitKey}
onValueChange={(value) => {
updateConfig(
(config) => (config.submitKey = value as SubmitKey),
);
}}
>
<SelectTrigger className="w-[180px]">
<SelectValue placeholder="Select key" />
</SelectTrigger>
<SelectContent>
{Object.values(SubmitKey).map((v) => (
<SelectItem value={v} key={v}>
{v}
</SelectItem>
))}
</SelectContent>
</Select>
</ConfigItem>
<ConfigItem title={Locale.Settings.Theme}>
<Select
value={config.theme}
onValueChange={(value) => {
updateConfig((config) => (config.theme = value as Theme));
}}
>
<SelectTrigger className="w-[180px]">
<SelectValue placeholder="Select theme" />
</SelectTrigger>
<SelectContent>
{Object.values(Theme).map((v) => (
<SelectItem value={v} key={v}>
{v}
</SelectItem>
))}
</SelectContent>
</Select>
</ConfigItem>
<ConfigItem
title={Locale.Settings.FontSize.Title}
subTitle={Locale.Settings.FontSize.SubTitle}
>
<InputRange
title={`${config.fontSize ?? 14}px`}
value={config.fontSize}
min="12"
max="18"
step="1"
onChange={(e) =>
updateConfig(
(config) =>
(config.fontSize = Number.parseInt(e.currentTarget.value)),
)
}
></InputRange>
</ConfigItem>
</CardContent>
</Card>
{!clientConfig.hasServerApiKey && (
<Card>
<CardContent className="divide-y p-5">
<ConfigItem
title={Locale.Settings.Token.Title}
subTitle={Locale.Settings.Token.SubTitle}
>
<Input
value={accessStore.token}
type="password"
placeholder={Locale.Settings.Token.Placeholder}
onChange={(e) => {
accessStore.updateToken(e.currentTarget.value);
}}
/>
</ConfigItem>
</CardContent>
</Card>
)}
</>
);
}
function DangerItems() {
const chatStore = useChatStore();
const appConfig = useAppConfig();
return (
<Card>
<CardContent className="divide-y p-5">
<ConfigItem
title={Locale.Settings.Danger.Reset.Title}
subTitle={Locale.Settings.Danger.Reset.SubTitle}
>
<AlertDialog>
<AlertDialogTrigger asChild>
<Button variant="destructive">
{Locale.Settings.Danger.Reset.Action}
</Button>
</AlertDialogTrigger>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>
{Locale.Settings.Danger.Reset.Confirm}
</AlertDialogTitle>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction
className={cn(buttonVariants({ variant: "destructive" }))}
onClick={() => {
appConfig.reset();
}}
>
Continue
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</ConfigItem>
<ConfigItem
title={Locale.Settings.Danger.Clear.Title}
subTitle={Locale.Settings.Danger.Clear.SubTitle}
>
<AlertDialog>
<AlertDialogTrigger asChild>
<Button variant="destructive">
{Locale.Settings.Danger.Clear.Action}
</Button>
</AlertDialogTrigger>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>
{Locale.Settings.Danger.Clear.Confirm}
</AlertDialogTitle>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction
className={cn(buttonVariants({ variant: "destructive" }))}
onClick={() => {
chatStore.clearAllData();
}}
>
Continue
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</ConfigItem>
</CardContent>
</Card>
);
}
function BackupItems() {
const botStore = useBotStore();
const { toast } = useToast();
const backupBots = () => {
downloadAs(JSON.stringify(botStore.backup()), FileName.Bots);
};
const restoreBots = async () => {
try {
const content = await readFromFile();
const importBots = JSON.parse(content);
botStore.restore(importBots);
toast({
title: Locale.Settings.Backup.Upload.Success,
variant: "success",
});
} catch (err) {
console.error("[Restore] ", err);
toast({
title: Locale.Settings.Backup.Upload.Failed((err as Error).message),
variant: "destructive",
});
}
};
return (
<Card>
<CardContent className="divide-y p-5">
<ConfigItem
title={Locale.Settings.Backup.Download.Title}
subTitle={Locale.Settings.Backup.Download.SutTitle}
>
<Button variant="outline" size="icon" onClick={backupBots}>
<HardDriveDownload className="w-5 h-5" />
</Button>
</ConfigItem>
<ConfigItem
title={Locale.Settings.Backup.Upload.Title}
subTitle={Locale.Settings.Backup.Upload.SutTitle}
>
<Button variant="outline" size="icon" onClick={restoreBots}>
<ArchiveRestore className="w-5 h-5" />
</Button>
</ConfigItem>
</CardContent>
</Card>
);
}
export function Settings() {
const navigate = useNavigate();
useEffect(() => {
const keydownEvent = (e: KeyboardEvent) => {
if (e.key === "Escape") {
navigate(Path.Home);
}
};
document.addEventListener("keydown", keydownEvent);
return () => {
document.removeEventListener("keydown", keydownEvent);
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
return (
<ErrorBoundary>
<SettingHeader />
<Separator />
<div className="space-y-5 p-5">
<CommonSettings />
<BackupItems />
<DangerItems />
</div>
</ErrorBoundary>
);
}
+145
View File
@@ -0,0 +1,145 @@
"use client";
import * as React from "react";
import * as AlertDialogPrimitive from "@radix-ui/react-alert-dialog";
import { cn } from "@/app/lib/utils";
import { buttonVariants } from "@/app/components/ui/button";
const AlertDialog = AlertDialogPrimitive.Root;
const AlertDialogTrigger = AlertDialogPrimitive.Trigger;
const AlertDialogPortal = ({
className,
...props
}: AlertDialogPrimitive.AlertDialogPortalProps) => (
<AlertDialogPrimitive.Portal className={cn(className)} {...props} />
);
AlertDialogPortal.displayName = AlertDialogPrimitive.Portal.displayName;
const AlertDialogOverlay = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Overlay>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Overlay>
>(({ className, children, ...props }, ref) => (
<AlertDialogPrimitive.Overlay
className={cn(
"fixed inset-0 z-50 bg-background/80 backdrop-blur-sm data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",
className,
)}
{...props}
ref={ref}
/>
));
AlertDialogOverlay.displayName = AlertDialogPrimitive.Overlay.displayName;
const AlertDialogContent = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Content>
>(({ className, ...props }, ref) => (
<AlertDialogPortal>
<AlertDialogOverlay />
<AlertDialogPrimitive.Content
ref={ref}
className={cn(
"fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg md:w-full",
className,
)}
{...props}
/>
</AlertDialogPortal>
));
AlertDialogContent.displayName = AlertDialogPrimitive.Content.displayName;
const AlertDialogHeader = ({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) => (
<div
className={cn(
"flex flex-col space-y-2 text-center sm:text-left",
className,
)}
{...props}
/>
);
AlertDialogHeader.displayName = "AlertDialogHeader";
const AlertDialogFooter = ({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) => (
<div
className={cn(
"flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",
className,
)}
{...props}
/>
);
AlertDialogFooter.displayName = "AlertDialogFooter";
const AlertDialogTitle = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Title>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Title>
>(({ className, ...props }, ref) => (
<AlertDialogPrimitive.Title
ref={ref}
className={cn("text-lg font-semibold", className)}
{...props}
/>
));
AlertDialogTitle.displayName = AlertDialogPrimitive.Title.displayName;
const AlertDialogDescription = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Description>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Description>
>(({ className, ...props }, ref) => (
<AlertDialogPrimitive.Description
ref={ref}
className={cn("text-sm text-muted-foreground", className)}
{...props}
/>
));
AlertDialogDescription.displayName =
AlertDialogPrimitive.Description.displayName;
const AlertDialogAction = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Action>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Action>
>(({ className, ...props }, ref) => (
<AlertDialogPrimitive.Action
ref={ref}
className={cn(buttonVariants(), className)}
{...props}
/>
));
AlertDialogAction.displayName = AlertDialogPrimitive.Action.displayName;
const AlertDialogCancel = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Cancel>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Cancel>
>(({ className, ...props }, ref) => (
<AlertDialogPrimitive.Cancel
ref={ref}
className={cn(
buttonVariants({ variant: "outline" }),
"mt-2 sm:mt-0",
className,
)}
{...props}
/>
));
AlertDialogCancel.displayName = AlertDialogPrimitive.Cancel.displayName;
export {
AlertDialog,
AlertDialogTrigger,
AlertDialogContent,
AlertDialogHeader,
AlertDialogFooter,
AlertDialogTitle,
AlertDialogDescription,
AlertDialogAction,
AlertDialogCancel,
};
+50
View File
@@ -0,0 +1,50 @@
"use client";
import * as React from "react";
import * as AvatarPrimitive from "@radix-ui/react-avatar";
import { cn } from "@/app/lib/utils";
const Avatar = React.forwardRef<
React.ElementRef<typeof AvatarPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof AvatarPrimitive.Root>
>(({ className, ...props }, ref) => (
<AvatarPrimitive.Root
ref={ref}
className={cn(
"relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full",
className,
)}
{...props}
/>
));
Avatar.displayName = AvatarPrimitive.Root.displayName;
const AvatarImage = React.forwardRef<
React.ElementRef<typeof AvatarPrimitive.Image>,
React.ComponentPropsWithoutRef<typeof AvatarPrimitive.Image>
>(({ className, ...props }, ref) => (
<AvatarPrimitive.Image
ref={ref}
className={cn("aspect-square h-full w-full", className)}
{...props}
/>
));
AvatarImage.displayName = AvatarPrimitive.Image.displayName;
const AvatarFallback = React.forwardRef<
React.ElementRef<typeof AvatarPrimitive.Fallback>,
React.ComponentPropsWithoutRef<typeof AvatarPrimitive.Fallback>
>(({ className, ...props }, ref) => (
<AvatarPrimitive.Fallback
ref={ref}
className={cn(
"flex h-full w-full items-center justify-center rounded-full bg-muted",
className,
)}
{...props}
/>
));
AvatarFallback.displayName = AvatarPrimitive.Fallback.displayName;
export { Avatar, AvatarImage, AvatarFallback };
+36
View File
@@ -0,0 +1,36 @@
import * as React from "react";
import { cva, type VariantProps } from "class-variance-authority";
import { cn } from "@/app/lib/utils";
const badgeVariants = cva(
"inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",
{
variants: {
variant: {
default:
"border-transparent bg-primary text-primary-foreground hover:bg-primary/80",
secondary:
"border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",
destructive:
"border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80",
outline: "text-foreground",
},
},
defaultVariants: {
variant: "default",
},
},
);
export interface BadgeProps
extends React.HTMLAttributes<HTMLDivElement>,
VariantProps<typeof badgeVariants> {}
function Badge({ className, variant, ...props }: BadgeProps) {
return (
<div className={cn(badgeVariants({ variant }), className)} {...props} />
);
}
export { Badge, badgeVariants };
+56
View File
@@ -0,0 +1,56 @@
import * as React from "react";
import { Slot } from "@radix-ui/react-slot";
import { cva, type VariantProps } from "class-variance-authority";
import { cn } from "@/app/lib/utils";
const buttonVariants = cva(
"inline-flex items-center justify-center rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50",
{
variants: {
variant: {
default: "bg-primary text-primary-foreground hover:bg-primary/90",
destructive:
"bg-destructive text-destructive-foreground hover:bg-destructive/90",
outline:
"border border-input bg-background hover:bg-accent hover:text-accent-foreground",
secondary:
"bg-secondary text-secondary-foreground hover:bg-secondary/80",
ghost: "hover:bg-accent hover:text-accent-foreground",
link: "text-primary underline-offset-4 hover:underline",
},
size: {
default: "h-10 px-4 py-2",
sm: "h-9 rounded-md px-3",
lg: "h-11 rounded-md px-8",
icon: "h-10 w-10",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
},
);
export interface ButtonProps
extends React.ButtonHTMLAttributes<HTMLButtonElement>,
VariantProps<typeof buttonVariants> {
asChild?: boolean;
}
const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
({ className, variant, size, asChild = false, ...props }, ref) => {
const Comp = asChild ? Slot : "button";
return (
<Comp
className={cn(buttonVariants({ variant, size, className }))}
ref={ref}
{...props}
/>
);
},
);
Button.displayName = "Button";
export { Button, buttonVariants };
+86
View File
@@ -0,0 +1,86 @@
import * as React from "react";
import { cn } from "@/app/lib/utils";
const Card = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn(
"rounded-lg border bg-card text-card-foreground shadow-sm",
className,
)}
{...props}
/>
));
Card.displayName = "Card";
const CardHeader = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn("flex flex-col space-y-1.5 p-6", className)}
{...props}
/>
));
CardHeader.displayName = "CardHeader";
const CardTitle = React.forwardRef<
HTMLParagraphElement,
React.HTMLAttributes<HTMLHeadingElement>
>(({ className, ...props }, ref) => (
<h3
ref={ref}
className={cn(
"text-2xl font-semibold leading-none tracking-tight",
className,
)}
{...props}
/>
));
CardTitle.displayName = "CardTitle";
const CardDescription = React.forwardRef<
HTMLParagraphElement,
React.HTMLAttributes<HTMLParagraphElement>
>(({ className, ...props }, ref) => (
<p
ref={ref}
className={cn("text-sm text-muted-foreground", className)}
{...props}
/>
));
CardDescription.displayName = "CardDescription";
const CardContent = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div ref={ref} className={cn("p-6 pt-0", className)} {...props} />
));
CardContent.displayName = "CardContent";
const CardFooter = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn("flex items-center p-6 pt-0", className)}
{...props}
/>
));
CardFooter.displayName = "CardFooter";
export {
Card,
CardHeader,
CardFooter,
CardTitle,
CardDescription,
CardContent,
};
+30
View File
@@ -0,0 +1,30 @@
"use client";
import * as React from "react";
import * as CheckboxPrimitive from "@radix-ui/react-checkbox";
import { Check } from "lucide-react";
import { cn } from "@/app/lib/utils";
const Checkbox = React.forwardRef<
React.ElementRef<typeof CheckboxPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof CheckboxPrimitive.Root>
>(({ className, ...props }, ref) => (
<CheckboxPrimitive.Root
ref={ref}
className={cn(
"peer h-4 w-4 shrink-0 rounded-sm border border-primary ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground",
className,
)}
{...props}
>
<CheckboxPrimitive.Indicator
className={cn("flex items-center justify-center text-current")}
>
<Check className="h-4 w-4" />
</CheckboxPrimitive.Indicator>
</CheckboxPrimitive.Root>
));
Checkbox.displayName = CheckboxPrimitive.Root.displayName;
export { Checkbox };
+123
View File
@@ -0,0 +1,123 @@
"use client";
import * as React from "react";
import * as DialogPrimitive from "@radix-ui/react-dialog";
import { X } from "lucide-react";
import { cn } from "@/app/lib/utils";
const Dialog = DialogPrimitive.Root;
const DialogTrigger = DialogPrimitive.Trigger;
const DialogPortal = ({
className,
...props
}: DialogPrimitive.DialogPortalProps) => (
<DialogPrimitive.Portal className={cn(className)} {...props} />
);
DialogPortal.displayName = DialogPrimitive.Portal.displayName;
const DialogOverlay = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Overlay>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Overlay>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Overlay
ref={ref}
className={cn(
"fixed inset-0 z-50 bg-background/80 backdrop-blur-sm data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",
className,
)}
{...props}
/>
));
DialogOverlay.displayName = DialogPrimitive.Overlay.displayName;
const DialogContent = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content>
>(({ className, children, ...props }, ref) => (
<DialogPortal>
<DialogOverlay />
<DialogPrimitive.Content
ref={ref}
className={cn(
"fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg md:w-full",
className,
)}
{...props}
>
{children}
<DialogPrimitive.Close className="absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground">
<X className="h-4 w-4" />
<span className="sr-only">Close</span>
</DialogPrimitive.Close>
</DialogPrimitive.Content>
</DialogPortal>
));
DialogContent.displayName = DialogPrimitive.Content.displayName;
const DialogHeader = ({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) => (
<div
className={cn(
"flex flex-col space-y-1.5 text-center sm:text-left",
className,
)}
{...props}
/>
);
DialogHeader.displayName = "DialogHeader";
const DialogFooter = ({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) => (
<div
className={cn(
"flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",
className,
)}
{...props}
/>
);
DialogFooter.displayName = "DialogFooter";
const DialogTitle = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Title>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Title>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Title
ref={ref}
className={cn(
"text-lg font-semibold leading-none tracking-tight",
className,
)}
{...props}
/>
));
DialogTitle.displayName = DialogPrimitive.Title.displayName;
const DialogDescription = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Description>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Description>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Description
ref={ref}
className={cn("text-sm text-muted-foreground", className)}
{...props}
/>
));
DialogDescription.displayName = DialogPrimitive.Description.displayName;
export {
Dialog,
DialogTrigger,
DialogContent,
DialogHeader,
DialogFooter,
DialogTitle,
DialogDescription,
};
+200
View File
@@ -0,0 +1,200 @@
"use client";
import * as React from "react";
import * as DropdownMenuPrimitive from "@radix-ui/react-dropdown-menu";
import { Check, ChevronRight, Circle } from "lucide-react";
import { cn } from "@/app/lib/utils";
const DropdownMenu = DropdownMenuPrimitive.Root;
const DropdownMenuTrigger = DropdownMenuPrimitive.Trigger;
const DropdownMenuGroup = DropdownMenuPrimitive.Group;
const DropdownMenuPortal = DropdownMenuPrimitive.Portal;
const DropdownMenuSub = DropdownMenuPrimitive.Sub;
const DropdownMenuRadioGroup = DropdownMenuPrimitive.RadioGroup;
const DropdownMenuSubTrigger = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.SubTrigger>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.SubTrigger> & {
inset?: boolean;
}
>(({ className, inset, children, ...props }, ref) => (
<DropdownMenuPrimitive.SubTrigger
ref={ref}
className={cn(
"flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent data-[state=open]:bg-accent",
inset && "pl-8",
className,
)}
{...props}
>
{children}
<ChevronRight className="ml-auto h-4 w-4" />
</DropdownMenuPrimitive.SubTrigger>
));
DropdownMenuSubTrigger.displayName =
DropdownMenuPrimitive.SubTrigger.displayName;
const DropdownMenuSubContent = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.SubContent>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.SubContent>
>(({ className, ...props }, ref) => (
<DropdownMenuPrimitive.SubContent
ref={ref}
className={cn(
"z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
className,
)}
{...props}
/>
));
DropdownMenuSubContent.displayName =
DropdownMenuPrimitive.SubContent.displayName;
const DropdownMenuContent = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Content>
>(({ className, sideOffset = 4, ...props }, ref) => (
<DropdownMenuPrimitive.Portal>
<DropdownMenuPrimitive.Content
ref={ref}
sideOffset={sideOffset}
className={cn(
"z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
className,
)}
{...props}
/>
</DropdownMenuPrimitive.Portal>
));
DropdownMenuContent.displayName = DropdownMenuPrimitive.Content.displayName;
const DropdownMenuItem = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.Item>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Item> & {
inset?: boolean;
}
>(({ className, inset, ...props }, ref) => (
<DropdownMenuPrimitive.Item
ref={ref}
className={cn(
"relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
inset && "pl-8",
className,
)}
{...props}
/>
));
DropdownMenuItem.displayName = DropdownMenuPrimitive.Item.displayName;
const DropdownMenuCheckboxItem = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.CheckboxItem>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.CheckboxItem>
>(({ className, children, checked, ...props }, ref) => (
<DropdownMenuPrimitive.CheckboxItem
ref={ref}
className={cn(
"relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
className,
)}
checked={checked}
{...props}
>
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
<DropdownMenuPrimitive.ItemIndicator>
<Check className="h-4 w-4" />
</DropdownMenuPrimitive.ItemIndicator>
</span>
{children}
</DropdownMenuPrimitive.CheckboxItem>
));
DropdownMenuCheckboxItem.displayName =
DropdownMenuPrimitive.CheckboxItem.displayName;
const DropdownMenuRadioItem = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.RadioItem>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.RadioItem>
>(({ className, children, ...props }, ref) => (
<DropdownMenuPrimitive.RadioItem
ref={ref}
className={cn(
"relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
className,
)}
{...props}
>
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
<DropdownMenuPrimitive.ItemIndicator>
<Circle className="h-2 w-2 fill-current" />
</DropdownMenuPrimitive.ItemIndicator>
</span>
{children}
</DropdownMenuPrimitive.RadioItem>
));
DropdownMenuRadioItem.displayName = DropdownMenuPrimitive.RadioItem.displayName;
const DropdownMenuLabel = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.Label>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Label> & {
inset?: boolean;
}
>(({ className, inset, ...props }, ref) => (
<DropdownMenuPrimitive.Label
ref={ref}
className={cn(
"px-2 py-1.5 text-sm font-semibold",
inset && "pl-8",
className,
)}
{...props}
/>
));
DropdownMenuLabel.displayName = DropdownMenuPrimitive.Label.displayName;
const DropdownMenuSeparator = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.Separator>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Separator>
>(({ className, ...props }, ref) => (
<DropdownMenuPrimitive.Separator
ref={ref}
className={cn("-mx-1 my-1 h-px bg-muted", className)}
{...props}
/>
));
DropdownMenuSeparator.displayName = DropdownMenuPrimitive.Separator.displayName;
const DropdownMenuShortcut = ({
className,
...props
}: React.HTMLAttributes<HTMLSpanElement>) => {
return (
<span
className={cn("ml-auto text-xs tracking-widest opacity-60", className)}
{...props}
/>
);
};
DropdownMenuShortcut.displayName = "DropdownMenuShortcut";
export {
DropdownMenu,
DropdownMenuTrigger,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuCheckboxItem,
DropdownMenuRadioItem,
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuShortcut,
DropdownMenuGroup,
DropdownMenuPortal,
DropdownMenuSub,
DropdownMenuSubContent,
DropdownMenuSubTrigger,
DropdownMenuRadioGroup,
};
+42
View File
@@ -0,0 +1,42 @@
import { DEFAULT_BOT_AVATAR } from "@/app/store/bot";
import EmojiPicker, {
Emoji,
EmojiStyle,
Theme as EmojiTheme,
} from "emoji-picker-react";
import BotIcon from "../../icons/bot.svg";
export function getEmojiUrl(unified: string, style: EmojiStyle) {
return `https://cdn.staticfile.org/emoji-datasource-apple/14.0.0/img/${style}/64/${unified}.png`;
}
export function EmojiAvatarPicker(props: {
onEmojiClick: (emojiId: string) => void;
}) {
return (
<EmojiPicker
lazyLoadEmojis
theme={EmojiTheme.AUTO}
getEmojiUrl={getEmojiUrl}
onEmojiClick={(e) => {
props.onEmojiClick(e.unified);
}}
/>
);
}
export function EmojiAvatar(props: { avatar: string; size?: number }) {
return (
<Emoji
unified={props.avatar}
size={props.size ?? 18}
getEmojiUrl={getEmojiUrl}
/>
);
}
export function BotAvatar(props: { avatar: string }) {
const { avatar } = props;
if (avatar === DEFAULT_BOT_AVATAR) return <BotIcon width={18} height={18} />;
return <EmojiAvatar avatar={avatar} />;
}
+98
View File
@@ -0,0 +1,98 @@
import { buttonVariants } from "@/app/components/ui/button";
import { cn } from "@/app/lib/utils";
import { FileWrap } from "@/app/utils/file";
import { ChangeEvent, useState } from "react";
import Locale from "../../locales";
import { Paperclip, Loader2 } from "lucide-react";
export interface FileUploaderProps {
config?: {
inputId?: string;
fileSizeLimit?: number;
allowedExtensions?: string[];
};
onUpload: (file: FileWrap) => Promise<void>;
onError: (errMsg: string) => void;
}
const DEFAULT_INPUT_ID = "fileInput";
const DEFAULT_FILE_SIZE_LIMIT = 1024 * 1024 * 50; // 50 MB
export default function FileUploader({
config,
onUpload,
onError,
}: FileUploaderProps) {
const [uploading, setUploading] = useState(false);
const inputId = config?.inputId || DEFAULT_INPUT_ID;
const fileSizeLimit = config?.fileSizeLimit || DEFAULT_FILE_SIZE_LIMIT;
const allowedExtensions = config?.allowedExtensions;
const shouldCheckFileExtension =
allowedExtensions != null && allowedExtensions.length > 0;
const isFileExtensionValid = (file: FileWrap) => {
if (!shouldCheckFileExtension) return true;
return allowedExtensions.includes(file.extension);
};
const isFileSizeExceeded = (file: FileWrap) => {
return file.size > fileSizeLimit;
};
const resetInput = () => {
const fileInput = document.getElementById(inputId) as HTMLInputElement;
fileInput.value = "";
};
const onFileChange = async (e: ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (!file) return;
setUploading(true);
const fileWrap = new FileWrap(file);
await handleUpload(fileWrap);
resetInput();
setUploading(false);
};
const handleUpload = async (file: FileWrap) => {
if (!isFileExtensionValid(file)) {
return onError(Locale.Upload.Invalid(allowedExtensions!.join(",")));
}
if (isFileSizeExceeded(file)) {
return onError(Locale.Upload.SizeExceeded(fileSizeLimit / 1024 / 1024));
}
await onUpload(file);
};
return (
<div className="self-stretch">
<input
type="file"
id={inputId}
style={{ display: "none" }}
onChange={onFileChange}
accept={allowedExtensions?.join(",")}
disabled={uploading}
/>
<label
htmlFor={inputId}
className={cn(
buttonVariants({ variant: "secondary", size: "icon" }),
"cursor-pointer",
uploading && "opacity-50",
)}
>
{uploading ? (
<Loader2 className="h-4 w-4 animate-spin" />
) : (
<Paperclip className="-rotate-45 w-4 h-4" />
)}
</label>
</div>
);
}
+29
View File
@@ -0,0 +1,29 @@
"use client";
import * as React from "react";
import * as HoverCardPrimitive from "@radix-ui/react-hover-card";
import { cn } from "@/app/lib/utils";
const HoverCard = HoverCardPrimitive.Root;
const HoverCardTrigger = HoverCardPrimitive.Trigger;
const HoverCardContent = React.forwardRef<
React.ElementRef<typeof HoverCardPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof HoverCardPrimitive.Content>
>(({ className, align = "center", sideOffset = 4, ...props }, ref) => (
<HoverCardPrimitive.Content
ref={ref}
align={align}
sideOffset={sideOffset}
className={cn(
"z-50 w-64 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
className,
)}
{...props}
/>
));
HoverCardContent.displayName = HoverCardPrimitive.Content.displayName;
export { HoverCard, HoverCardTrigger, HoverCardContent };
+56
View File
@@ -0,0 +1,56 @@
import * as React from "react";
import { cn } from "@/app/lib/utils";
export interface InputProps
extends React.InputHTMLAttributes<HTMLInputElement> {}
export interface InputRangeProps {
onChange: React.ChangeEventHandler<HTMLInputElement>;
title?: string;
value: number | string;
className?: string;
min: string;
max: string;
step: string;
}
const Input = React.forwardRef<HTMLInputElement, InputProps>(
({ className, type, ...props }, ref) => {
return (
<input
type={type}
className={cn(
"flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50",
className,
)}
ref={ref}
{...props}
/>
);
},
);
Input.displayName = "Input";
function InputRange(props: InputRangeProps) {
const { className, title, value, ...rest } = props;
return (
<div
className={cn(
"rounded-lg border-2 border-muted p-2 text-sm flex items-center gap-2",
className,
)}
>
<span>{title || value}</span>
<Input
className="p-0 accent-primary"
type="range"
title={title}
value={value}
{...rest}
></Input>
</div>
);
}
export { Input, InputRange };
+17
View File
@@ -0,0 +1,17 @@
import LoadingIcon from "@/app/icons/three-dots.svg";
export function LoadingThreeDot() {
return (
<div className="text-primary">
<LoadingIcon />
</div>
);
}
export function LoadingModule() {
return (
<div className="w-full h-screen max-h-full flex items-center justify-center">
<LoadingThreeDot />
</div>
);
}
+186
View File
@@ -0,0 +1,186 @@
import "katex/dist/katex.min.css";
import mermaid from "mermaid";
import { RefObject, useEffect, useRef, useState } from "react";
import ReactMarkdown from "react-markdown";
import RehypeHighlight from "rehype-highlight";
import RehypeKatex from "rehype-katex";
import RemarkBreaks from "remark-breaks";
import RemarkGfm from "remark-gfm";
import RemarkMath from "remark-math";
import Locale from "../../locales";
import { copyToClipboard } from "../../utils";
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/app/components/ui/dialog";
import { Separator } from "@/app/components/ui/separator";
import { useToast } from "@/app/components/ui/use-toast";
import React from "react";
import { useDebouncedCallback } from "use-debounce";
import { LoadingThreeDot } from "@/app/components/ui/loading";
export function Mermaid(props: { code: string }) {
const ref = useRef<HTMLDivElement>(null);
const [hasError, setHasError] = useState(false);
const [imageUrl, setImageUrl] = useState<string | undefined>(undefined);
useEffect(() => {
if (props.code && ref.current) {
mermaid
.run({
nodes: [ref.current],
suppressErrors: true,
})
.catch((e) => {
setHasError(true);
console.error("[Mermaid] ", e.message);
});
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [props.code]);
function viewSvgInNewWindow() {
const svg = ref.current?.querySelector("svg");
if (!svg) return;
const text = new XMLSerializer().serializeToString(svg);
const blob = new Blob([text], { type: "image/svg+xml" });
setImageUrl(URL.createObjectURL(blob));
}
if (hasError) {
return null;
}
return (
<Dialog open={!!imageUrl}>
<DialogTrigger asChild>
<div
className="no-dark mermaid"
style={{
cursor: "pointer",
overflow: "auto",
}}
ref={ref}
onClick={() => viewSvgInNewWindow()}
>
{props.code}
</div>
</DialogTrigger>
<DialogContent className="max-w-4xl">
<DialogHeader>
<DialogTitle>{Locale.Export.Image.Modal}</DialogTitle>
</DialogHeader>
<div>
<img src={imageUrl} alt="preview" className="max-w-full" />
</div>
<Separator />
</DialogContent>
</Dialog>
);
}
export function PreCode(props: { children: any }) {
const { toast } = useToast();
const ref = useRef<HTMLPreElement>(null);
const refText = ref.current?.innerText;
const [mermaidCode, setMermaidCode] = useState("");
const renderMermaid = useDebouncedCallback(() => {
if (!ref.current) return;
const mermaidDom = ref.current.querySelector("code.language-mermaid");
if (mermaidDom) {
setMermaidCode((mermaidDom as HTMLElement).innerText);
}
}, 600);
useEffect(() => {
setTimeout(renderMermaid, 1);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [refText]);
return (
<>
{mermaidCode.length > 0 && (
<Mermaid code={mermaidCode} key={mermaidCode} />
)}
<pre ref={ref} className="group relative">
<span
className="copy-code-button group-hover:translate-x-0 group-hover:opacity-100 group-hover:pointer-events-auto"
onClick={() => {
if (ref.current) {
const code = ref.current.innerText;
copyToClipboard(code, toast);
}
}}
></span>
{props.children}
</pre>
</>
);
}
function _MarkDownContent(props: { content: string }) {
return (
<ReactMarkdown
remarkPlugins={[RemarkMath, RemarkGfm, RemarkBreaks]}
rehypePlugins={[
RehypeKatex,
[
RehypeHighlight,
{
detect: false,
ignoreMissing: true,
},
],
]}
components={{
pre: PreCode,
p: (pProps) => <p {...pProps} dir="auto" />,
a: (aProps) => {
const href = aProps.href || "";
const isInternal = /^\/#/i.test(href);
const target = isInternal ? "_self" : aProps.target ?? "_blank";
return <a {...aProps} target={target} />;
},
}}
>
{props.content}
</ReactMarkdown>
);
}
export const MarkdownContent = React.memo(_MarkDownContent);
export function Markdown(
props: {
content: string;
loading?: boolean;
fontSize?: number;
parentRef?: RefObject<HTMLDivElement>;
defaultShow?: boolean;
} & React.DOMAttributes<HTMLDivElement>,
) {
const mdRef = useRef<HTMLDivElement>(null);
return (
<div
className="markdown-body"
style={{
fontSize: `${props.fontSize ?? 14}px`,
}}
ref={mdRef}
onContextMenu={props.onContextMenu}
onDoubleClickCapture={props.onDoubleClickCapture}
>
{props.loading ? (
<LoadingThreeDot />
) : (
<MarkdownContent content={props.content} />
)}
</div>
);
}
+31
View File
@@ -0,0 +1,31 @@
"use client";
import * as React from "react";
import * as PopoverPrimitive from "@radix-ui/react-popover";
import { cn } from "@/app/lib/utils";
const Popover = PopoverPrimitive.Root;
const PopoverTrigger = PopoverPrimitive.Trigger;
const PopoverContent = React.forwardRef<
React.ElementRef<typeof PopoverPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof PopoverPrimitive.Content>
>(({ className, align = "center", sideOffset = 4, ...props }, ref) => (
<PopoverPrimitive.Portal>
<PopoverPrimitive.Content
ref={ref}
align={align}
sideOffset={sideOffset}
className={cn(
"z-50 w-72 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
className,
)}
{...props}
/>
</PopoverPrimitive.Portal>
));
PopoverContent.displayName = PopoverPrimitive.Content.displayName;
export { Popover, PopoverTrigger, PopoverContent };
+28
View File
@@ -0,0 +1,28 @@
"use client";
import * as React from "react";
import * as ProgressPrimitive from "@radix-ui/react-progress";
import { cn } from "@/app/lib/utils";
const Progress = React.forwardRef<
React.ElementRef<typeof ProgressPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof ProgressPrimitive.Root>
>(({ className, value, ...props }, ref) => (
<ProgressPrimitive.Root
ref={ref}
className={cn(
"relative h-4 w-full overflow-hidden rounded-full bg-secondary",
className,
)}
{...props}
>
<ProgressPrimitive.Indicator
className="h-full w-full flex-1 bg-primary transition-all"
style={{ transform: `translateX(-${100 - (value || 0)}%)` }}
/>
</ProgressPrimitive.Root>
));
Progress.displayName = ProgressPrimitive.Root.displayName;
export { Progress };
+50
View File
@@ -0,0 +1,50 @@
"use client";
import * as React from "react";
import * as ScrollAreaPrimitive from "@radix-ui/react-scroll-area";
import { cn } from "@/app/lib/utils";
const ScrollArea = React.forwardRef<
React.ElementRef<typeof ScrollAreaPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof ScrollAreaPrimitive.Root>
>(({ className, children, ...props }, ref) => (
<ScrollAreaPrimitive.Root
className={cn("relative overflow-hidden", className)}
{...props}
>
<ScrollAreaPrimitive.Viewport
className="h-full w-full rounded-[inherit] custom-scrollarea-viewport"
ref={ref}
>
{children}
</ScrollAreaPrimitive.Viewport>
<ScrollBar />
<ScrollAreaPrimitive.Corner />
</ScrollAreaPrimitive.Root>
));
ScrollArea.displayName = ScrollAreaPrimitive.Root.displayName;
const ScrollBar = React.forwardRef<
React.ElementRef<typeof ScrollAreaPrimitive.ScrollAreaScrollbar>,
React.ComponentPropsWithoutRef<typeof ScrollAreaPrimitive.ScrollAreaScrollbar>
>(({ className, orientation = "vertical", ...props }, ref) => (
<ScrollAreaPrimitive.ScrollAreaScrollbar
ref={ref}
orientation={orientation}
className={cn(
"flex touch-none select-none transition-colors",
orientation === "vertical" &&
"h-full w-2.5 border-l border-l-transparent p-[1px]",
orientation === "horizontal" &&
"h-2.5 border-t border-t-transparent p-[1px]",
className,
)}
{...props}
>
<ScrollAreaPrimitive.ScrollAreaThumb className="relative flex-1 rounded-full bg-border" />
</ScrollAreaPrimitive.ScrollAreaScrollbar>
));
ScrollBar.displayName = ScrollAreaPrimitive.ScrollAreaScrollbar.displayName;
export { ScrollArea, ScrollBar };
+121
View File
@@ -0,0 +1,121 @@
"use client";
import * as React from "react";
import * as SelectPrimitive from "@radix-ui/react-select";
import { Check, ChevronDown } from "lucide-react";
import { cn } from "@/app/lib/utils";
const Select = SelectPrimitive.Root;
const SelectGroup = SelectPrimitive.Group;
const SelectValue = SelectPrimitive.Value;
const SelectTrigger = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Trigger>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Trigger>
>(({ className, children, ...props }, ref) => (
<SelectPrimitive.Trigger
ref={ref}
className={cn(
"flex h-10 w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",
className,
)}
{...props}
>
{children}
<SelectPrimitive.Icon asChild>
<ChevronDown className="h-4 w-4 opacity-50" />
</SelectPrimitive.Icon>
</SelectPrimitive.Trigger>
));
SelectTrigger.displayName = SelectPrimitive.Trigger.displayName;
const SelectContent = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Content>
>(({ className, children, position = "popper", ...props }, ref) => (
<SelectPrimitive.Portal>
<SelectPrimitive.Content
ref={ref}
className={cn(
"relative z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
position === "popper" &&
"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",
className,
)}
position={position}
{...props}
>
<SelectPrimitive.Viewport
className={cn(
"p-1",
position === "popper" &&
"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]",
)}
>
{children}
</SelectPrimitive.Viewport>
</SelectPrimitive.Content>
</SelectPrimitive.Portal>
));
SelectContent.displayName = SelectPrimitive.Content.displayName;
const SelectLabel = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Label>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Label>
>(({ className, ...props }, ref) => (
<SelectPrimitive.Label
ref={ref}
className={cn("py-1.5 pl-8 pr-2 text-sm font-semibold", className)}
{...props}
/>
));
SelectLabel.displayName = SelectPrimitive.Label.displayName;
const SelectItem = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Item>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Item>
>(({ className, children, ...props }, ref) => (
<SelectPrimitive.Item
ref={ref}
className={cn(
"relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
className,
)}
{...props}
>
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
<SelectPrimitive.ItemIndicator>
<Check className="h-4 w-4" />
</SelectPrimitive.ItemIndicator>
</span>
<SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>
</SelectPrimitive.Item>
));
SelectItem.displayName = SelectPrimitive.Item.displayName;
const SelectSeparator = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Separator>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Separator>
>(({ className, ...props }, ref) => (
<SelectPrimitive.Separator
ref={ref}
className={cn("-mx-1 my-1 h-px bg-muted", className)}
{...props}
/>
));
SelectSeparator.displayName = SelectPrimitive.Separator.displayName;
export {
Select,
SelectGroup,
SelectValue,
SelectTrigger,
SelectContent,
SelectLabel,
SelectItem,
SelectSeparator,
};
+31
View File
@@ -0,0 +1,31 @@
"use client";
import * as React from "react";
import * as SeparatorPrimitive from "@radix-ui/react-separator";
import { cn } from "@/app/lib/utils";
const Separator = React.forwardRef<
React.ElementRef<typeof SeparatorPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof SeparatorPrimitive.Root>
>(
(
{ className, orientation = "horizontal", decorative = true, ...props },
ref,
) => (
<SeparatorPrimitive.Root
ref={ref}
decorative={decorative}
orientation={orientation}
className={cn(
"shrink-0 bg-border",
orientation === "horizontal" ? "h-[1px] w-full" : "h-full w-[1px]",
className,
)}
{...props}
/>
),
);
Separator.displayName = SeparatorPrimitive.Root.displayName;
export { Separator };
+24
View File
@@ -0,0 +1,24 @@
import * as React from "react";
import { cn } from "@/app/lib/utils";
export interface TextareaProps
extends React.TextareaHTMLAttributes<HTMLTextAreaElement> {}
const Textarea = React.forwardRef<HTMLTextAreaElement, TextareaProps>(
({ className, ...props }, ref) => {
return (
<textarea
className={cn(
"flex min-h-[80px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",
className,
)}
ref={ref}
{...props}
/>
);
},
);
Textarea.displayName = "Textarea";
export { Textarea };
+128
View File
@@ -0,0 +1,128 @@
import * as React from "react";
import * as ToastPrimitives from "@radix-ui/react-toast";
import { cva, type VariantProps } from "class-variance-authority";
import { X } from "lucide-react";
import { cn } from "@/app/lib/utils";
const ToastProvider = ToastPrimitives.Provider;
const ToastViewport = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Viewport>,
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Viewport>
>(({ className, ...props }, ref) => (
<ToastPrimitives.Viewport
ref={ref}
className={cn(
"fixed top-0 z-[100] flex max-h-screen w-full flex-col-reverse p-4 sm:bottom-0 sm:right-0 sm:top-auto sm:flex-col md:max-w-[420px]",
className,
)}
{...props}
/>
));
ToastViewport.displayName = ToastPrimitives.Viewport.displayName;
const toastVariants = cva(
"group pointer-events-auto relative flex w-full items-center justify-between space-x-4 overflow-hidden rounded-md border p-6 pr-8 shadow-lg transition-all data-[swipe=cancel]:translate-x-0 data-[swipe=end]:translate-x-[var(--radix-toast-swipe-end-x)] data-[swipe=move]:translate-x-[var(--radix-toast-swipe-move-x)] data-[swipe=move]:transition-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[swipe=end]:animate-out data-[state=closed]:fade-out-80 data-[state=closed]:slide-out-to-right-full data-[state=open]:slide-in-from-top-full data-[state=open]:sm:slide-in-from-bottom-full",
{
variants: {
variant: {
default: "border bg-background text-foreground",
success: "text-primary bg-background group border-primary",
destructive:
"destructive group border-destructive bg-destructive text-destructive-foreground",
},
},
defaultVariants: {
variant: "default",
},
},
);
const Toast = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Root>,
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Root> &
VariantProps<typeof toastVariants>
>(({ className, variant, ...props }, ref) => {
return (
<ToastPrimitives.Root
ref={ref}
className={cn(toastVariants({ variant }), className)}
{...props}
/>
);
});
Toast.displayName = ToastPrimitives.Root.displayName;
const ToastAction = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Action>,
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Action>
>(({ className, ...props }, ref) => (
<ToastPrimitives.Action
ref={ref}
className={cn(
"inline-flex h-8 shrink-0 items-center justify-center rounded-md border bg-transparent px-3 text-sm font-medium ring-offset-background transition-colors hover:bg-secondary focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 group-[.destructive]:border-muted/40 group-[.destructive]:hover:border-destructive/30 group-[.destructive]:hover:bg-destructive group-[.destructive]:hover:text-destructive-foreground group-[.destructive]:focus:ring-destructive",
className,
)}
{...props}
/>
));
ToastAction.displayName = ToastPrimitives.Action.displayName;
const ToastClose = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Close>,
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Close>
>(({ className, ...props }, ref) => (
<ToastPrimitives.Close
ref={ref}
className={cn(
"absolute right-2 top-2 rounded-md p-1 text-foreground/50 opacity-0 transition-opacity hover:text-foreground focus:opacity-100 focus:outline-none focus:ring-2 group-hover:opacity-100 group-[.destructive]:text-red-300 group-[.destructive]:hover:text-red-50 group-[.destructive]:focus:ring-red-400 group-[.destructive]:focus:ring-offset-red-600",
className,
)}
toast-close=""
{...props}
>
<X className="h-4 w-4" />
</ToastPrimitives.Close>
));
ToastClose.displayName = ToastPrimitives.Close.displayName;
const ToastTitle = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Title>,
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Title>
>(({ className, ...props }, ref) => (
<ToastPrimitives.Title
ref={ref}
className={cn("text-sm font-semibold", className)}
{...props}
/>
));
ToastTitle.displayName = ToastPrimitives.Title.displayName;
const ToastDescription = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Description>,
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Description>
>(({ className, ...props }, ref) => (
<ToastPrimitives.Description
ref={ref}
className={cn("text-sm opacity-90", className)}
{...props}
/>
));
ToastDescription.displayName = ToastPrimitives.Description.displayName;
type ToastProps = React.ComponentPropsWithoutRef<typeof Toast>;
type ToastActionElement = React.ReactElement<typeof ToastAction>;
export {
type ToastProps,
type ToastActionElement,
ToastProvider,
ToastViewport,
Toast,
ToastTitle,
ToastDescription,
ToastClose,
ToastAction,
};
+35
View File
@@ -0,0 +1,35 @@
"use client";
import {
Toast,
ToastClose,
ToastDescription,
ToastProvider,
ToastTitle,
ToastViewport,
} from "@/app/components/ui/toast";
import { useToast } from "@/app/components/ui/use-toast";
export function Toaster() {
const { toasts } = useToast();
return (
<ToastProvider>
{toasts.map(function ({ id, title, description, action, ...props }) {
return (
<Toast key={id} {...props}>
<div className="grid gap-1">
{title && <ToastTitle>{title}</ToastTitle>}
{description && (
<ToastDescription>{description}</ToastDescription>
)}
</div>
{action}
<ToastClose />
</Toast>
);
})}
<ToastViewport />
</ToastProvider>
);
}
+30
View File
@@ -0,0 +1,30 @@
"use client";
import * as React from "react";
import * as TooltipPrimitive from "@radix-ui/react-tooltip";
import { cn } from "@/app/lib/utils";
const TooltipProvider = TooltipPrimitive.Provider;
const Tooltip = TooltipPrimitive.Root;
const TooltipTrigger = TooltipPrimitive.Trigger;
const TooltipContent = React.forwardRef<
React.ElementRef<typeof TooltipPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof TooltipPrimitive.Content>
>(({ className, sideOffset = 4, ...props }, ref) => (
<TooltipPrimitive.Content
ref={ref}
sideOffset={sideOffset}
className={cn(
"z-50 overflow-hidden rounded-md border bg-popover px-3 py-1.5 text-sm text-popover-foreground shadow-md animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
className,
)}
{...props}
/>
));
TooltipContent.displayName = TooltipPrimitive.Content.displayName;
export { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider };
+111
View File
@@ -0,0 +1,111 @@
import { cn } from "@/app/lib/utils";
type HeadingProps = React.DetailedHTMLProps<
React.HTMLAttributes<HTMLHeadingElement>,
HTMLHeadingElement
>;
type ParagraphProps = React.DetailedHTMLProps<
React.HTMLAttributes<HTMLParagraphElement>,
HTMLDivElement
>;
type LinkProps = React.DetailedHTMLProps<
React.AnchorHTMLAttributes<HTMLAnchorElement>,
HTMLAnchorElement
>;
function H1(props: HeadingProps) {
const { className, children, ...rest } = props;
return (
<h1
className={cn(
"scroll-m-20 text-4xl font-extrabold tracking-tight",
className,
)}
{...rest}
>
{children}
</h1>
);
}
function H2(props: HeadingProps) {
const { className, children, ...rest } = props;
return (
<h2
className={cn(
"scroll-m-20 text-3xl font-semibold tracking-tight",
className,
)}
{...rest}
>
{children}
</h2>
);
}
function H3(props: HeadingProps) {
const { className, children, ...rest } = props;
return (
<h3
className={cn(
"scroll-m-20 text-2xl font-semibold tracking-tight",
className,
)}
{...rest}
>
{children}
</h3>
);
}
function H4(props: HeadingProps) {
const { className, children, ...rest } = props;
return (
<h4
className={cn(
"scroll-m-20 text-xl font-semibold tracking-tight",
className,
)}
{...rest}
>
{children}
</h4>
);
}
function P(props: ParagraphProps) {
const { className, children, ...rest } = props;
return (
<p className={cn("leading-7", className)} {...rest}>
{children}
</p>
);
}
function Link(props: LinkProps) {
const { className, children, ...rest } = props;
return (
<a
className={cn(
"font-medium text-primary underline underline-offset-4",
className,
)}
{...rest}
>
{children}
</a>
);
}
const Typography = {
H1,
H2,
H3,
H4,
P,
Link,
};
export default Typography;
+189
View File
@@ -0,0 +1,189 @@
// Inspired by react-hot-toast library
import * as React from "react";
import type { ToastActionElement, ToastProps } from "@/app/components/ui/toast";
const TOAST_LIMIT = 1;
const TOAST_REMOVE_DELAY = 1000000;
type ToasterToast = ToastProps & {
id: string;
title?: React.ReactNode;
description?: React.ReactNode;
action?: ToastActionElement;
};
const actionTypes = {
ADD_TOAST: "ADD_TOAST",
UPDATE_TOAST: "UPDATE_TOAST",
DISMISS_TOAST: "DISMISS_TOAST",
REMOVE_TOAST: "REMOVE_TOAST",
} as const;
let count = 0;
function genId() {
count = (count + 1) % Number.MAX_VALUE;
return count.toString();
}
type ActionType = typeof actionTypes;
type Action =
| {
type: ActionType["ADD_TOAST"];
toast: ToasterToast;
}
| {
type: ActionType["UPDATE_TOAST"];
toast: Partial<ToasterToast>;
}
| {
type: ActionType["DISMISS_TOAST"];
toastId?: ToasterToast["id"];
}
| {
type: ActionType["REMOVE_TOAST"];
toastId?: ToasterToast["id"];
};
interface State {
toasts: ToasterToast[];
}
const toastTimeouts = new Map<string, ReturnType<typeof setTimeout>>();
const addToRemoveQueue = (toastId: string) => {
if (toastTimeouts.has(toastId)) {
return;
}
const timeout = setTimeout(() => {
toastTimeouts.delete(toastId);
dispatch({
type: "REMOVE_TOAST",
toastId: toastId,
});
}, TOAST_REMOVE_DELAY);
toastTimeouts.set(toastId, timeout);
};
export const reducer = (state: State, action: Action): State => {
switch (action.type) {
case "ADD_TOAST":
return {
...state,
toasts: [action.toast, ...state.toasts].slice(0, TOAST_LIMIT),
};
case "UPDATE_TOAST":
return {
...state,
toasts: state.toasts.map((t) =>
t.id === action.toast.id ? { ...t, ...action.toast } : t,
),
};
case "DISMISS_TOAST": {
const { toastId } = action;
// ! Side effects ! - This could be extracted into a dismissToast() action,
// but I'll keep it here for simplicity
if (toastId) {
addToRemoveQueue(toastId);
} else {
state.toasts.forEach((toast) => {
addToRemoveQueue(toast.id);
});
}
return {
...state,
toasts: state.toasts.map((t) =>
t.id === toastId || toastId === undefined
? {
...t,
open: false,
}
: t,
),
};
}
case "REMOVE_TOAST":
if (action.toastId === undefined) {
return {
...state,
toasts: [],
};
}
return {
...state,
toasts: state.toasts.filter((t) => t.id !== action.toastId),
};
}
};
const listeners: Array<(state: State) => void> = [];
let memoryState: State = { toasts: [] };
function dispatch(action: Action) {
memoryState = reducer(memoryState, action);
listeners.forEach((listener) => {
listener(memoryState);
});
}
type Toast = Omit<ToasterToast, "id">;
function toast({ ...props }: Toast) {
const id = genId();
const update = (props: ToasterToast) =>
dispatch({
type: "UPDATE_TOAST",
toast: { ...props, id },
});
const dismiss = () => dispatch({ type: "DISMISS_TOAST", toastId: id });
dispatch({
type: "ADD_TOAST",
toast: {
...props,
id,
open: true,
onOpenChange: (open) => {
if (!open) dismiss();
},
},
});
return {
id: id,
dismiss,
update,
};
}
function useToast() {
const [state, setState] = React.useState<State>(memoryState);
React.useEffect(() => {
listeners.push(setState);
return () => {
const index = listeners.indexOf(setState);
if (index > -1) {
listeners.splice(index, 1);
}
};
}, [state]);
return {
...state,
toast,
dismiss: (toastId?: string) => dispatch({ type: "DISMISS_TOAST", toastId }),
};
}
export { useToast, toast };
+40
View File
@@ -0,0 +1,40 @@
export const getBuildConfig = () => {
if (typeof process === "undefined") {
throw Error(
"[Server Config] you are importing a nodejs-only module outside of nodejs",
);
}
const buildMode = process.env.BUILD_MODE ?? "standalone";
const isApp = !!process.env.BUILD_APP;
const commitInfo = (() => {
try {
const childProcess = require("child_process");
const commitDate: string = childProcess
.execSync('git log -1 --format="%at000" --date=unix')
.toString()
.trim();
const commitHash: string = childProcess
.execSync('git log --pretty=format:"%H" -n 1')
.toString()
.trim();
return { commitDate, commitHash };
} catch (e) {
console.error("[Build Config] No git or not from git repo.");
return {
commitDate: "unknown",
commitHash: "unknown",
};
}
})();
return {
...commitInfo,
buildMode,
isApp,
};
};
export type BuildConfig = ReturnType<typeof getBuildConfig>;
+47
View File
@@ -0,0 +1,47 @@
import { BuildConfig, getBuildConfig } from "./build";
import { getServerSideConfig } from "./server";
export type ClientConfig = BuildConfig & {
hasServerApiKey: boolean;
hasNextAuth: boolean;
};
export function getClientConfig(): ClientConfig {
if (typeof document !== "undefined") {
// client side
return JSON.parse(queryMeta("config")) as ClientConfig;
}
if (
typeof self === "object" &&
self.constructor &&
self.constructor.name === "DedicatedWorkerGlobalScope"
) {
// worker side
return (self as any)?.startData?.config;
}
if (typeof process !== "undefined") {
// server side generation of the client config
return {
...getBuildConfig(),
hasServerApiKey: !!getServerSideConfig().apiKey,
hasNextAuth: !!getServerSideConfig().nextAuthUrl,
};
}
throw new Error("code is neither running in the browser nor in node.js");
}
function queryMeta(key: string, defaultValue?: string): string {
let ret: string;
if (document) {
const meta = document.head.querySelector(
`meta[name='${key}']`,
) as HTMLMetaElement;
ret = meta?.content ?? "";
} else {
ret = defaultValue ?? "";
}
return ret;
}
+34
View File
@@ -0,0 +1,34 @@
declare global {
namespace NodeJS {
interface ProcessEnv {
OPENAI_API_KEY?: string;
BASE_URL?: string;
VERCEL?: "1";
DISABLE_GPT4?: string; // allow user to use gpt-4 or not
BUILD_MODE?: "standalone" | "export";
BUILD_APP?: string; // is building desktop app
LINKEDIN_CLIENT_ID?: string;
LINKEDIN_CLIENT_SECRET?: string;
SLACK_WEBHOOK_URL?: string;
}
}
}
export const getServerSideConfig = () => {
if (typeof process === "undefined") {
throw Error(
"[Server Config] you are importing a nodejs-only module outside of nodejs",
);
}
return {
apiKey: process.env.OPENAI_API_KEY,
nextAuthUrl: process.env.NEXTAUTH_URL,
baseUrl: process.env.BASE_URL,
isVercel: !!process.env.VERCEL,
disableGPT4: !!process.env.DISABLE_GPT4,
linkedinClientId: process.env.LINKEDIN_CLIENT_ID,
linkedinClientSecret: process.env.LINKEDIN_CLIENT_SECRET,
slackWebhookUrl: process.env.SLACK_WEBHOOK_URL,
};
};
+112
View File
@@ -0,0 +1,112 @@
export const OWNER = "marcusschiesser";
export const REPO = "unc";
export const REPO_URL = `https://github.com/${OWNER}/${REPO}`;
export const ISSUE_URL = `https://github.com/${OWNER}/${REPO}/issues`;
export const UPDATE_URL = `${REPO_URL}#keep-updated`;
export const RELEASE_URL = `${REPO_URL}/releases`;
export const FETCH_COMMIT_URL = `https://api.github.com/repos/${OWNER}/${REPO}/commits?per_page=1`;
export const FETCH_TAG_URL = `https://api.github.com/repos/${OWNER}/${REPO}/tags?per_page=1`;
export const RUNTIME_CONFIG_DOM = "danger-runtime-config";
export const DEFAULT_API_HOST = "https://api.openai.com";
export const LINKEDIN_URL = "https://www.linkedin.com/in/marcusschiesser";
export enum Path {
Home = "/",
Chat = "/",
Settings = "/settings",
NewChat = "/new-chat",
Bots = "/",
Auth = "/auth",
}
export enum SlotID {
AppBody = "app-body",
}
export enum FileName {
Bots = "bots.json",
Prompts = "prompts.json",
}
export enum StoreKey {
Chat = "chat-next-web-store",
Access = "access-control",
Config = "app-config",
Bot = "bot-store",
Prompt = "prompt-store",
Update = "chat-update",
Sync = "sync",
}
export const LAST_INPUT_KEY = "last-input";
export const REQUEST_TIMEOUT_MS = 60000;
export const EXPORT_MESSAGE_CLASS_NAME = "export-markdown";
export const OpenaiPath = {
ChatPath: "v1/chat/completions",
};
export const DEFAULT_INPUT_TEMPLATE = `{{input}}`; // input / time / model / lang
export const DEFAULT_SYSTEM_TEMPLATE = `
You are ChatGPT, a large language model trained by OpenAI.
Knowledge cutoff: 2021-09
Current model: {{model}}
Current time: {{time}}`;
export const PDF_TO_TEXT_API_ROUTE = "/api/pdf2text";
export const FETCH_SITE_CONTENT_URL = "/api/fetch";
export const DEFAULT_MODELS = [
{
name: "gpt-4",
available: true,
},
{
name: "gpt-4-0314",
available: true,
},
{
name: "gpt-4-0613",
available: true,
},
{
name: "gpt-4-32k",
available: true,
},
{
name: "gpt-4-32k-0314",
available: true,
},
{
name: "gpt-4-32k-0613",
available: true,
},
{
name: "gpt-3.5-turbo",
available: true,
},
{
name: "gpt-3.5-turbo-0301",
available: true,
},
{
name: "gpt-3.5-turbo-0613",
available: true,
},
{
name: "gpt-3.5-turbo-16k",
available: true,
},
{
name: "gpt-3.5-turbo-16k-0613",
available: true,
},
] as const;
export const CHAT_PAGE_SIZE = 15;
export const MAX_RENDER_MSG_COUNT = 45;
export const ALLOWED_DOCUMENT_EXTENSIONS = ["pdf", "txt"];
export const DOCUMENT_FILE_SIZE_LIMIT = 1024 * 1024 * 10; // 10 MB
+17
View File
@@ -0,0 +1,17 @@
declare module "*.jpg";
declare module "*.png";
declare module "*.woff2";
declare module "*.woff";
declare module "*.ttf";
declare module "*.scss" {
const content: Record<string, string>;
export default content;
}
declare module "*.svg";
declare interface Window {
__TAURI__?: {
writeText(text: string): Promise<void>;
};
}
+31
View File
@@ -0,0 +1,31 @@
import { useEffect, useRef, useState } from "react";
export function useScrollToBottom() {
// for auto-scroll
const scrollRef = useRef<HTMLDivElement>(null);
const [autoScroll, setAutoScroll] = useState(true);
function scrollDomToBottom() {
const dom = scrollRef.current;
if (dom) {
requestAnimationFrame(() => {
setAutoScroll(true);
dom.scrollTo(0, dom.scrollHeight);
});
}
}
// auto scroll
useEffect(() => {
if (autoScroll) {
scrollDomToBottom();
}
});
return {
scrollRef,
autoScroll,
setAutoScroll,
scrollDomToBottom,
};
}
+47
View File
@@ -0,0 +1,47 @@
import { useRef, useEffect } from "react";
import { SubmitKey, useAppConfig } from "../store";
export function useSubmitHandler() {
const config = useAppConfig();
const submitKey = config.submitKey;
const isComposing = useRef(false);
useEffect(() => {
const onCompositionStart = () => {
isComposing.current = true;
};
const onCompositionEnd = () => {
isComposing.current = false;
};
window.addEventListener("compositionstart", onCompositionStart);
window.addEventListener("compositionend", onCompositionEnd);
return () => {
window.removeEventListener("compositionstart", onCompositionStart);
window.removeEventListener("compositionend", onCompositionEnd);
};
}, []);
const shouldSubmit = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
if (e.key !== "Enter") return false;
if (e.key === "Enter" && (e.nativeEvent.isComposing || isComposing.current))
return false;
return (
(config.submitKey === SubmitKey.AltEnter && e.altKey) ||
(config.submitKey === SubmitKey.CtrlEnter && e.ctrlKey) ||
(config.submitKey === SubmitKey.ShiftEnter && e.shiftKey) ||
(config.submitKey === SubmitKey.MetaEnter && e.metaKey) ||
(config.submitKey === SubmitKey.Enter &&
!e.altKey &&
!e.ctrlKey &&
!e.shiftKey &&
!e.metaKey)
);
};
return {
submitKey,
shouldSubmit,
};
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 312 KiB

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="30" height="14" fill="currentColor" viewBox="0 0 120 30"><circle cx="15" cy="15" r="15" fill="var(--primary, red)"><animate attributeName="r" begin="0s" calcMode="linear" dur="0.8s" from="15" repeatCount="indefinite" to="15" values="15;9;15"/><animate attributeName="fill-opacity" begin="0s" calcMode="linear" dur="0.8s" from="1" repeatCount="indefinite" to="1" values="1;.5;1"/></circle><circle cx="60" cy="15" r="9" fill="var(--primary, red)" fill-opacity=".3"><animate attributeName="r" begin="0s" calcMode="linear" dur="0.8s" from="9" repeatCount="indefinite" to="9" values="9;15;9"/><animate attributeName="fill-opacity" begin="0s" calcMode="linear" dur="0.8s" from=".5" repeatCount="indefinite" to=".5" values=".5;1;.5"/></circle><circle cx="105" cy="15" r="15" fill="var(--primary, red)"><animate attributeName="r" begin="0s" calcMode="linear" dur="0.8s" from="15" repeatCount="indefinite" to="15" values="15;9;15"/><animate attributeName="fill-opacity" begin="0s" calcMode="linear" dur="0.8s" from="1" repeatCount="indefinite" to="1" values="1;.5;1"/></circle></svg>

After

Width:  |  Height:  |  Size: 1.1 KiB

+50
View File
@@ -0,0 +1,50 @@
import "./styles/globals.css";
import "./styles/lib/markdown.css";
import "./styles/lib/highlight.css";
import { getClientConfig } from "./config/client";
import Locale from "./locales";
import { type Metadata } from "next";
import { AuthProviders } from "./auth/providers";
import { Toaster } from "@/app/components/ui/toaster";
import { ThemeProvider } from "@/app/components/layout/theme-provider";
export const metadata: Metadata = {
title: Locale.Welcome.Title,
description: Locale.Welcome.SubTitle,
viewport: {
width: "device-width",
initialScale: 1,
maximumScale: 1,
},
themeColor: [
{ media: "(prefers-color-scheme: light)", color: "white" },
{ media: "(prefers-color-scheme: dark)", color: "black" },
],
appleWebApp: {
title: Locale.Welcome.Title,
statusBarStyle: "default",
},
};
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<html lang="en">
<head>
<meta name="config" content={JSON.stringify(getClientConfig())} />
<link rel="manifest" href="/site.webmanifest"></link>
<script src="/serviceWorkerRegister.js" defer></script>
</head>
<body>
<ThemeProvider attribute="class" defaultTheme="system" enableSystem>
<AuthProviders>{children}</AuthProviders>
<Toaster />
</ThemeProvider>
</body>
</html>
);
}
+6
View File
@@ -0,0 +1,6 @@
import { type ClassValue, clsx } from "clsx";
import { twMerge } from "tailwind-merge";
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs));
}
+265
View File
@@ -0,0 +1,265 @@
import { SubmitKey } from "../store/config";
import type { LocaleType } from "./index";
const de: LocaleType = {
Error: {
Unauthorized:
"Sie haben Ihren OpenAI-Key noch nicht konfiguriert. Bitte einen auf der [OpenAI-Zugangsseite](https://platform.openai.com/account/api-keys) erstellen, und bei Ihren [Einstellungen](/#/settings) eintragen.",
},
Chat: {
SubTitle: (count: number) => `${count} Nachrichten`,
Actions: {
ChatList: "Zur Chat-Liste gehen",
Copy: "Kopieren",
Stop: "Stop",
Retry: "Wiederholen",
Delete: "Löschen",
Pin: "Pin",
PinToastContent: "Eine Nachricht zum Kontext hinzugefügt",
PinToastAction: "Anzeigen",
},
Commands: {
new: "Start a new chat",
newm: "Start a new chat with bot",
next: "Next Chat",
prev: "Previous Chat",
clear: "Kontext löschen",
del: "Delete Chat",
},
InputActions: {
Stop: "Stop",
ToBottom: "Zum Ende springen",
Clear: "Kontext löschen",
Settings: "Einstellungen",
},
Typing: "Tippen...",
Input: (submitKey: string) => {
var inputHints = `${submitKey} um zu Senden`;
if (submitKey === String(SubmitKey.Enter)) {
inputHints += ", Umschalt + Eingabe für Zeilenumbruch";
}
inputHints += ", URLs fügen PDF- oder HTML-Dokumente zum Kontext hinzu";
return inputHints;
},
Send: "Senden",
IsContext: "Kontext-Prompt",
LoadingURL: "Lade URL...",
},
Upload: {
Invalid: (acceptTypes: string) =>
`Unbekannter Datei-Typ. Bitte wählen Sie eine Datei mit einem unterstützten Format (${acceptTypes}) aus`,
SizeExceeded: (limitSize: number) =>
`Datei ist zu groß. Das Limit beträgt ${limitSize} MB`,
ParseDataURLFailed:
"Datei kann nicht gelesen werden: Bitte überprüfen, ob sie verschlüsselt ist.",
UnknownFileType: "TEXT FILE",
},
Export: {
Image: {
Modal: "Lange drücken oder Rechtsklick, um das Bild zu speichern",
},
},
Memory: {
Title: "Gedächtnis-Prompt",
EmptyContent: "Noch nichts.",
Send: "Gedächtnis senden",
},
Home: {
LinkedIn: "Kontaktieren",
Logout: "Abmelden",
Settings: "Einstellungen",
},
Settings: {
Title: "Einstellungen",
SubTitle: "Alle Einstellungen",
Danger: {
Reset: {
Title: "Reset All Settings",
SubTitle: "Reset all setting items to default",
Action: "Reset",
Confirm: "Confirm to reset all settings to default?",
},
Clear: {
Title: "Clear All Data",
SubTitle: "Clear all messages and settings",
Action: "Clear",
Confirm: "Confirm to clear all messages and settings?",
},
},
Avatar: "Avatar",
FontSize: {
Title: "Schriftgröße",
SubTitle: "Schriftgröße des Chat-Inhalts anpassen",
},
InputTemplate: {
Title: "Input Template",
SubTitle: "Newest message will be filled to this template",
},
SendKey: "Senden-Taste",
Theme: "Theme",
HistoryCount: {
Title: "Anzahl der angehängten Nachrichten",
SubTitle: "Anzahl der pro Anfrage angehängten gesendeten Nachrichten",
},
CompressThreshold: {
Title: "Schwellenwert für Verlaufskomprimierung",
SubTitle:
"Komprimierung, wenn die Länge der unkomprimierten Nachrichten den Wert überschreitet",
},
Token: {
Title: "API-Schlüssel",
SubTitle: "Verwenden Sie hier Ihren OpenAI API-Schlüssel",
Placeholder: "OpenAI API-Schlüssel",
},
Model: "Modell",
Temperature: {
Title: "Temperature", //Temperatur
SubTitle: "Ein größerer Wert führt zu zufälligeren Antworten",
},
TopP: {
Title: "Top P",
SubTitle: "Diesen Wert nicht zusammen mit der Temperature ändern",
},
MaxTokens: {
Title: "Max Tokens", //Maximale Token
SubTitle: "Maximale Anzahl der Anfrage- plus Antwort-Token",
},
PresencePenalty: {
Title: "Presence Penalty", //Anwesenheitsstrafe
SubTitle:
"Ein größerer Wert erhöht die Wahrscheinlichkeit, dass über neue Themen gesprochen wird",
},
FrequencyPenalty: {
Title: "Frequency Penalty", // HäufigkeitStrafe
SubTitle:
"Ein größerer Wert verringert die Wahrscheinlichkeit, dass dieselbe Zeile wiederholt wird",
},
Backup: {
Download: {
Title: "Backup Bots",
SutTitle: "Download the state of your bots to a JSON file",
},
Upload: {
Title: "Restore Bots",
SutTitle: "Upload the state of your bots from a JSON file",
Success: "Successfully restored the bots from the JSON file",
Failed: (e: string) => `Error importing the JSON file: ${e}`,
},
},
},
Store: {
DefaultBotName: "Neuer Bot",
DefaultTopic: "Neues Gespräch",
BotHello: "Hallo! Wie kann ich Ihnen heute helfen?",
Error:
"Etwas ist schief gelaufen, bitte versuchen Sie es später noch einmal.",
Prompt: {
History: (content: string) =>
"Dies ist eine Zusammenfassung des Chatverlaufs zwischen der KI und dem Benutzer als Rückblick: " +
content,
Topic:
"Bitte erstellen Sie einen vier- bis fünfwörtigen Titel, der unser Gespräch zusammenfasst, ohne Einleitung, Zeichensetzung, Anführungszeichen, Punkte, Symbole oder zusätzlichen Text. Entfernen Sie Anführungszeichen.",
Summarize:
"Fassen Sie unsere Diskussion kurz in 200 Wörtern oder weniger zusammen, um sie als Pronpt für zukünftige Gespräche zu verwenden.",
},
},
Copy: {
Success: "In die Zwischenablage kopiert",
Failed:
"Kopieren fehlgeschlagen, bitte geben Sie die Berechtigung zum Zugriff auf die Zwischenablage frei",
},
Context: {
Toast: (x: any) => `Mit ${x} Kontext-Prompts`,
Edit: "Kontext- und Gedächtnis-Prompts",
Add: "Hinzufügen",
Clear: "Kontext gelöscht",
Revert: "Rückgängig",
Title: "Einstellungen Kontext-Prompt",
},
Share: {
Title: "Bot teilen",
Url: {
Title: "URL",
Hint: "Mit dieser URL können Sie Ihren Bot teilen. Die URL ist 30 Tage gültig.",
Error: "Oops, something went wrong. Please try again later.",
},
ShowToken: {
Title: "API-Schlüssel",
SubTitle:
"API-Schüssel der für Ihren Bot verwendet wird. Bot-Benutzer benötigen dann keinen Schlüssel. Sie bezahlen für deren Benutzung.",
},
Token: {
Title: "API-Schlüssel",
SubTitle: "OpenAI API-Schlüssel für diesen Bot.",
Placeholder: "OpenAI API-Schlüssel",
Error:
"Oops, there was an error setting the API key. Please try again later.",
},
},
Deploy: {
Config: {
Title: "Bot in Telegram deployen",
Start: "Bot starten",
Stop: "Bot stoppen",
Token: {
Title: "Telegram Bot-Token",
Hint: "Bot-Token für das Deployen in Telegram. Sie können einen hier erstellen",
Placeholder: "Telegram Bot-Token",
},
},
},
Bot: {
Name: "Bot",
Page: {
Search: (count: number) => `Bots suchen - ${count} Bots`,
Create: "Neuer Bot",
},
Item: {
Edit: "Editieren",
Delete: "Löschen",
DeleteConfirm: "Löschen bestätigen?",
Deploy: "Telegram",
Share: "Teilen",
},
EditModal: {
Title: `Bot editieren`,
Clone: "Kopie erstellen",
},
Config: {
Avatar: "Bot-Avatar",
Name: "Bot-Name",
HideContext: {
Title: "Kontext-Prompts verstecken",
SubTitle: "Kontext-Prompts nicht im Chat anzeigen",
},
BotHello: {
Title: "Willkommens-Nachricht",
SubTitle:
"Nachricht, die beim Starten eines neuen Chats angezeigt wird",
},
Title: "Einstellungen Bot",
},
},
Welcome: {
Title: "Unc",
SubTitle: "The open and secure ChatGPT platform",
Quote:
"“This tool has saved me countless hours of work and helped me apply AI features to my work faster than ever before.”",
LoginLinkedinTitle: "Login with LinkedIn",
},
UI: {
Confirm: "Bestätigen",
Cancel: "Abbrechen",
Close: "Schließen",
Create: "Erstellen",
Edit: "Editieren",
},
URLCommand: {
Code: "Detected access code from url, confirm to apply? ",
Settings: "Detected settings from url, confirm to apply?",
},
};
export default de;
+266
View File
@@ -0,0 +1,266 @@
import { SubmitKey } from "../store/config";
const en = {
Error: {
Unauthorized:
"You haven't configured your OpenAI key. Please get one from the [OpenAI Account page](https://platform.openai.com/account/api-keys), and enter it in the [settings](/#/settings) page.",
},
Chat: {
SubTitle: (count: number) => `${count} messages`,
Actions: {
ChatList: "Go To Chat List",
Copy: "Copy",
Stop: "Stop",
Retry: "Retry",
Pin: "Pin",
PinToastContent: "Pinned 1 messages to contextual prompts",
PinToastAction: "View",
Delete: "Delete",
},
Commands: {
new: "Start a new chat",
newm: "Start a new chat with bot",
next: "Next Chat",
prev: "Previous Chat",
clear: "Clear Context",
del: "Delete Chat",
},
InputActions: {
Stop: "Stop generating",
ToBottom: "To Latest",
Clear: "Clear Context",
Settings: "Settings",
},
Typing: "Typing…",
Input: (submitKey: string) => {
var inputHints = `${submitKey} to send`;
if (submitKey === String(SubmitKey.Enter)) {
inputHints += ", Shift + Enter to wrap";
}
inputHints += ", enter URLs to add a PDF or HTML document to the context";
return inputHints;
},
Send: "Send",
IsContext: "Contextual Prompt",
LoadingURL: "Loading content...",
},
Upload: {
Invalid: (acceptTypes: string) =>
`Invalid file type. Please select a file with one of these formats: ${acceptTypes}`,
SizeExceeded: (limitSize: number) =>
`File size exceeded. Limit is ${limitSize} MB`,
ParseDataURLFailed: "Unable to read file: Please check if it's encrypted.",
UnknownFileType: "TEXT FILE",
},
Export: {
Image: {
Modal: "Long press or right click to save image",
},
},
Memory: {
Title: "Memory Prompt",
EmptyContent: "Nothing yet.",
Send: "Send Memory",
},
Home: {
LinkedIn: "Contact",
Logout: "Logout",
Settings: "Settings",
},
Settings: {
Title: "Settings",
SubTitle: "All Settings",
Danger: {
Reset: {
Title: "Reset All Settings",
SubTitle: "Reset all setting items to default",
Action: "Reset",
Confirm: "Confirm to reset all settings to default?",
},
Clear: {
Title: "Clear All Data",
SubTitle: "Clear all messages and settings",
Action: "Clear",
Confirm: "Confirm to clear all messages and settings?",
},
},
Avatar: "Avatar",
FontSize: {
Title: "Font Size",
SubTitle: "Adjust font size of chat content",
},
InputTemplate: {
Title: "Input Template",
SubTitle: "Newest message will be filled to this template",
},
SendKey: "Send Key",
Theme: "Theme",
HistoryCount: {
Title: "Attached Messages Count",
SubTitle: "Number of sent messages attached per request",
},
CompressThreshold: {
Title: "History Compression Threshold",
SubTitle:
"Will compress if uncompressed messages length exceeds the value",
},
Token: {
Title: "API Key",
SubTitle: "Enter your API key from OpenAI here",
Placeholder: "OpenAI API Key",
},
Model: "Model",
Temperature: {
Title: "Temperature",
SubTitle: "A larger value makes the more random output",
},
TopP: {
Title: "Top P",
SubTitle: "Do not alter this value together with temperature",
},
MaxTokens: {
Title: "Max Tokens",
SubTitle: "Maximum length of input tokens and generated tokens",
},
PresencePenalty: {
Title: "Presence Penalty",
SubTitle:
"A larger value increases the likelihood to talk about new topics",
},
FrequencyPenalty: {
Title: "Frequency Penalty",
SubTitle:
"A larger value decreasing the likelihood to repeat the same line",
},
Backup: {
Download: {
Title: "Backup Bots",
SutTitle: "Download the state of your bots to a JSON file",
},
Upload: {
Title: "Restore Bots",
SutTitle: "Upload the state of your bots from a JSON file",
Success: "Successfully restored the bots from the JSON file",
Failed: (e: string) => `Error importing the JSON file: ${e}`,
},
},
},
Store: {
DefaultBotName: "New Bot",
DefaultTopic: "New Conversation",
BotHello: "Hello! How can I assist you today?",
Error: "Something went wrong, please try again later.",
Prompt: {
History: (content: string) =>
"This is a summary of the chat history as a recap: " + content,
Topic:
"Please generate a four to five word title summarizing our conversation without any lead-in, punctuation, quotation marks, periods, symbols, or additional text. Remove enclosing quotation marks.",
Summarize:
"Summarize the discussion briefly in 200 words or less to use as a prompt for future context.",
},
},
Copy: {
Success: "Copied to clipboard",
Failed: "Copy failed, please grant permission to access clipboard",
},
Context: {
Toast: (x: any) => `With ${x} contextual prompts`,
Edit: "Current Chat Settings",
Add: "Add a Prompt",
Clear: "Context Cleared",
Revert: "Revert",
Title: "Context Prompt Settings",
},
Share: {
Title: "Share Bot",
Url: {
Title: "URL",
Hint: "Use the URL to share your bot. The URL will be valid for 30 days.",
Error: "Oops, something went wrong. Please try again later.",
},
ShowToken: {
Title: "Use API Key",
SubTitle:
"Provide an OpenAI API key for your shared bot. The users of the bot don't need a key. You'll pay for them.",
},
Token: {
Title: "API Key",
SubTitle: "OpenAI API key used by this shared bot.",
Placeholder: "OpenAI API Key",
Error:
"Oops, there was an error setting the API key. Please try again later.",
},
},
Deploy: {
Config: {
Title: "Deploy Bot To Telegram",
Start: "Start Bot",
Stop: "Stop Bot",
Token: {
Title: "Telegram Bot token",
Hint: "Enter your Telegram Bot token, get it from",
Placeholder: "Telegram Bot token",
},
},
},
Bot: {
Name: "Bot",
Page: {
Search: (count: number) => `Search Bot - ${count} bots`,
Create: "Create bot",
},
Item: {
Edit: "Edit",
Delete: "Delete",
DeleteConfirm: "Confirm to delete?",
Deploy: "Telegram",
Share: "Share",
},
EditModal: {
Title: `Edit Bot`,
Clone: "Clone",
},
Config: {
Avatar: "Bot Avatar",
Name: "Bot Name",
HideContext: {
Title: "Hide Context Prompts",
SubTitle: "Do not show in-context prompts in chat",
},
BotHello: {
Title: "Welcome Message",
SubTitle: "Welcome message sent when starting a new chat",
},
Title: "Bot Settings",
},
},
Welcome: {
Title: "Unc",
SubTitle: "The open and secure ChatGPT platform",
Quote:
"“This tool has saved me countless hours of work and helped me apply AI features to my work faster than ever before.”",
LoginLinkedinTitle: "Login with LinkedIn",
},
UI: {
Confirm: "Confirm",
Cancel: "Cancel",
Close: "Close",
Create: "Create",
Edit: "Edit",
},
URLCommand: {
Code: "Detected access code from url, confirm to apply? ",
Settings: "Detected settings from url, confirm to apply?",
},
};
export type LocaleType = typeof en;
export default en;
+71
View File
@@ -0,0 +1,71 @@
import en from "./en";
import de from "./de";
import type { LocaleType } from "./en";
export type { LocaleType } from "./en";
const ALL_LANGS = {
en,
de,
};
export type Lang = keyof typeof ALL_LANGS;
export const AllLangs = Object.keys(ALL_LANGS) as Lang[];
export const ALL_LANG_OPTIONS: Record<Lang, string> = {
en: "English",
de: "Deutsch",
};
const LANG_KEY = "lang";
const DEFAULT_LANG = "en";
const targetLang = ALL_LANGS[getLang()] as LocaleType;
export default targetLang as LocaleType;
function getItem(key: string) {
try {
return localStorage.getItem(key);
} catch {
return null;
}
}
function setItem(key: string, value: string) {
try {
localStorage.setItem(key, value);
} catch {}
}
function getLanguage() {
try {
return navigator.language.toLowerCase();
} catch {
return DEFAULT_LANG;
}
}
export function getLang(): Lang {
const savedLang = getItem(LANG_KEY);
if (AllLangs.includes((savedLang ?? "") as Lang)) {
return savedLang as Lang;
}
const lang = getLanguage();
for (const option of AllLangs) {
if (lang.includes(option)) {
return option;
}
}
return DEFAULT_LANG;
}
export function changeLang(lang: Lang) {
setItem(LANG_KEY, lang);
location.reload();
}
+12
View File
@@ -0,0 +1,12 @@
import { Analytics } from "@vercel/analytics/react";
import { Home } from "./components/home";
export default async function App() {
return (
<>
<Home />
<Analytics />
</>
);
}
+27
View File
@@ -0,0 +1,27 @@
declare global {
interface Array<T> {
at(index: number): T | undefined;
}
}
if (!Array.prototype.at) {
Array.prototype.at = function (index: number) {
// Get the length of the array
const length = this.length;
// Convert negative index to a positive index
if (index < 0) {
index = length + index;
}
// Return undefined if the index is out of range
if (index < 0 || index >= length) {
return undefined;
}
// Use Array.prototype.slice method to get value at the specified index
return Array.prototype.slice.call(this, index, index + 1)[0];
};
}
export {};

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