remove old snoopForms code, change license to MIT, remove unused code configs

This commit is contained in:
Matthias Nannt
2022-11-10 09:40:15 +01:00
parent 8ae2ec5b62
commit beb00d6dbd
204 changed files with 162 additions and 13145 deletions

View File

@@ -1,6 +0,0 @@
Dockerfile
.dockerignore
.turbo
node_modules
README.md
.next

View File

@@ -1,78 +0,0 @@
########################################################################
# ------------ MANDATORY (CHANGE ACCORDING TO YOUR SETUP) ------------#
########################################################################
############
# Basics #
############
NEXTAUTH_SECRET=RANDOM_STRING
NEXTAUTH_URL=http://localhost:3000
# This should always be localhost:3000 (or whatever port your app is running on)
NEXTAUTH_URL_INTERNAL=http://localhost:3000
DATABASE_URL='postgresql://postgres:postgres@postgres:5432/snoopforms?schema=public'
################
# Mail Setup #
################
# Necessary if email verification and password reset are enabled.
# See optional configurations below if you want to disable these features.
# MAIL_FROM=noreply@example.com
# SMTP_HOST=localhost
# SMTP_PORT=1025
# SMTP_SECURE_ENABLED=0 # Enable for TLS (port 465)
# SMTP_USER=smtpUser
# SMTP_PASSWORD=smtpPassword
########################################################################
# ------------------------------ OPTIONAL -----------------------------#
########################################################################
# Uncomment the variables you would like to use and customize the values.
#####################
# Disable Features #
#####################
# Email Verification. If you enable Email Verification you have to setup SMTP-Settings, too.
NEXT_PUBLIC_EMAIL_VERIFICATION_DISABLED=1
# Password Reset. If you enable Password Reset functionality you have to setup SMTP-Settings, too.
NEXT_PUBLIC_PASSWORD_RESET_DISABLED=1
# Signup. Disable the ability for new users to create an account.
# NEXT_PUBLIC_SIGNUP_DISABLED=1
#######################
# Additional Options #
#######################
# NEXT_PUBLIC_TERMS_URL=https://www.example.com/terms
# NEXT_PUBLIC_PRIVACY_URL=https://www.example.com/privacy
# NEXT_PUBLIC_IMPRINT_URL=https://www.example.com/imprint
# NEXT_PUBLIC_PRIVACY_URL=https://www.example.com/enduserPrivacy
######################
# Posthog Tracking #
######################
# POSTHOG_API_HOST=https://app.posthog.com
# POSTHOG_API_KEY=<YOUR POSTHOG API KEY>
###############
# Telemetry #
###############
# We also track anononymous usage telemetry on the server to improve snoopForms.
# That way we can see how many people use snoopForms.
# We can't identify you, or your users and only receive the number of submissions on your instance.
# You help us a lot, if you leave this activated.
# If you still want to opt-out, uncomment the next line.
# TELEMETRY_DISABLED=1

View File

@@ -1,82 +0,0 @@
########################################################################
# ------------ MANDATORY (CHANGE ACCORDING TO YOUR SETUP) ------------#
########################################################################
############
# Basics #
############
NEXTAUTH_SECRET=RANDOM_STRING
# Set this to your public-facing URL, e.g., https://example.com
NEXTAUTH_URL=http://localhost:3000
# This should always be localhost:3000 (or whatever port your app is running on)
NEXTAUTH_URL_INTERNAL=http://localhost:3000
DATABASE_URL='postgresql://postgres:postgres@localhost:5432/snoopforms?schema=public'
# For Docker Compose Production Setup use this Database URL:
# DATABASE_URL='postgresql://postgres:postgres@postgres:5432/snoopforms?schema=public'
################
# Mail Setup #
################
# Necessary if email verification and password reset are enabled.
# See optional configurations below if you want to disable these features.
MAIL_FROM=noreply@example.com
SMTP_HOST=localhost
SMTP_PORT=1025
SMTP_SECURE_ENABLED=0 # Enable for TLS (port 465)
SMTP_USER=smtpUser
SMTP_PASSWORD=smtpPassword
########################################################################
# ------------------------------ OPTIONAL -----------------------------#
########################################################################
# Uncomment the variables you would like to use and customize the values.
#####################
# Disable Features #
#####################
# Email Verification. If you enable Email Verification you have to setup SMTP-Settings, too.
# NEXT_PUBLIC_EMAIL_VERIFICATION_DISABLED=1
# Password Reset. If you enable Password Reset functionality you have to setup SMTP-Settings, too.
# NEXT_PUBLIC_PASSWORD_RESET_DISABLED=1
# Signup. Disable the ability for new users to create an account.
# NEXT_PUBLIC_SIGNUP_DISABLED=1
#######################
# Additional Options #
#######################
# NEXT_PUBLIC_TERMS_URL=https://www.example.com/terms
# NEXT_PUBLIC_PRIVACY_URL=https://www.example.com/privacy
# NEXT_PUBLIC_IMPRINT_URL=https://www.example.com/imprint
# NEXT_PUBLIC_PRIVACY_URL=https://www.example.com/enduserPrivacy
######################
# Posthog Tracking #
######################
# POSTHOG_API_HOST=https://app.posthog.com
# POSTHOG_API_KEY=<YOUR POSTHOG API KEY>
###############
# Telemetry #
###############
# We also track anononymous usage telemetry on the server to improve snoopForms.
# That way we can see how many people use snoopForms.
# We can't identify you, or your users and only receive the number of submissions on your instance.
# You help us a lot, if you leave this activated.
# If you still want to opt-out, uncomment the next line.
# TELEMETRY_DISABLED=1

1
.envrc
View File

@@ -1 +0,0 @@
use flake

View File

@@ -1,5 +1,11 @@
{
"recommendations": [
"ms-vscode-remote.remote-containers"
]
}
"recommendations": [
"ban.spellright", // Spell check for docs
"bradlc.vscode-tailwindcss", // hinting / autocompletion for tailwind
"DavidAnson.vscode-markdownlint", // markdown linting
"dbaeumer.vscode-eslint", // eslint plugin
"esbenp.prettier-vscode", // prettier plugin
"Prisma.prisma", // syntax|format|completion for prisma
"yzhang.markdown-all-in-one" // nicer markdown support
]
}

28
.vscode/launch.json vendored
View File

@@ -1,28 +0,0 @@
{
"version": "0.2.0",
"configurations": [
{
"name": "Next.js: debug server-side",
"type": "node-terminal",
"request": "launch",
"command": "yarn dev"
},
{
"name": "Next.js: debug client-side",
"type": "chrome",
"request": "launch",
"url": "http://localhost:3000"
},
{
"name": "Next.js: debug full stack",
"type": "node-terminal",
"request": "launch",
"command": "yarn dev",
"serverReadyAction": {
"pattern": "started server on .+, url: (https?://.+)",
"uriFormat": "%s",
"action": "debugWithChrome"
}
}
]
}

View File

@@ -1,2 +0,0 @@
{
}

View File

@@ -1,16 +1,10 @@
There are many ways to contribute to snoopForms.
We are so happy that you are interested in contributing to Formbricks 🤗
# Creating a PR
Please fork the repository, make your changes and create a new pull request if you want to make an update.
If you want to speak to us before doing lots of work, please join our [Discord server](https://snoopforms.com/discord) and tell us what you would like to work on - we're very responsive and friendly!
For QA of your Pull-Request, you can also get in touch with Matti on Discord. But we will also get to your PR without you taking additional action ;-)
There are many ways to contribute to Formbricks with writing Issues, fixing bugs, building new features or updating the docs.
# Issues
Spotted a bug? Has deployment gone wrong? Do you have user feedback? Raise an issue for the fastest response.
Spotted a bug? Has deployment gone wrong? Do you have user feedback? [Raise an issue](https://github.com/formbricks/formbricks/issues/new/choose) for the fastest response.
... or pick up and fix an issue if you want to do a Pull Request.
@@ -18,10 +12,18 @@ Spotted a bug? Has deployment gone wrong? Do you have user feedback? Raise an is
Raise an issue for these and tag it as an Enhancement. We love every idea. Please give us as much context on the why as possible.
# Creating a PR
Please fork the repository, make your changes and create a new pull request if you want to make an update.
If you want to speak to us before doing lots of work, please join our [Discord server](https://formbricks.com/discord) and tell us what you would like to work on - we're very responsive and friendly!
For QA of your Pull-Request, you can also get in touch with Matti on Discord. But we will also get to your PR without you taking additional action ;-)
# Features
We are currently working on having a clear [Roadmap](https://github.com/orgs/formbricks/projects/1) for the next steps ahead.
But you can also pick a feature that is not already on the roadmap if you think it creates a positive impact for snoopForms.
But you can also pick a feature that is not already on the roadmap if you think it creates a positive impact for Formbricks.
If you are at all unsure, just raise it as an enhancement issue first and tell us that you like to work on it, and we'll very quickly respond.

682
LICENSE
View File

@@ -1,661 +1,21 @@
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/>.
MIT License
Copyright (c) 2022 Matthias Nannt
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

176
README.md
View File

@@ -1,43 +1,72 @@
<p align="center">
<a href="https://github.com/formbricks/snoopforms">
<img src="https://user-images.githubusercontent.com/72809645/172191504-808da997-025b-4b1f-90c0-b8ef658af2dd.svg" alt="Logo" width="500">
<a href="https://github.com/formbricks/formbricks">
<img src="https://user-images.githubusercontent.com/675065/201035557-a94a6bde-dff0-4bd3-9693-ec9257a9b1b3.svg" alt="Logo" width="500">
</a>
<h3 align="center">snoopForms</h3>
<h3 align="center">Formbricks</h3>
<p align="center">
Finally, good open source forms!
The Open Source Forms & Survey Toolbox
<br />
<a href="https://snoopforms.com/">Website & Hosted version</a> | <a href="https://snoopforms.com/discord">Join Discord community</a>
<a href="https://formbricks.com/">Website & Hosted version</a> | <a href="https://formbricks.com/discord">Join Discord community</a>
</p>
</p>
<p align="center">
<a href="https://github.com/formbricks/snoopforms/blob/main/LICENSE"><img src="https://img.shields.io/badge/license-AGPLv3-purple" alt="License"></a> <a href="https://discord.gg/3YFcABF2Ts"><img src="https://img.shields.io/discord/979077669410979880?label=Discord&logo=discord&logoColor=%23fff" alt="Join snoopForms Discord"></a> <a href="https://github.com/formbricks/snoopforms/stargazers"><img src="https://img.shields.io/github/stars/snoopForms/snoopforms?logo=github" alt="Github Stars"></a>
<a href="https://github.com/formbricks/formbricks/blob/main/LICENSE"><img src="https://img.shields.io/badge/license-MIT-purple" alt="License"></a> <a href="https://formbricks.com/discord"><img src="https://img.shields.io/discord/979077669410979880?label=Discord&logo=discord&logoColor=%23fff" alt="Join Formbricks Discord"></a> <a href="https://github.com/formbricks/formbricks/stargazers"><img src="https://img.shields.io/github/stars/formbricks/formbricks?logo=github" alt="Github Stars"></a>
<a href="https://news.ycombinator.com/item?id=32303986"><img src="https://img.shields.io/badge/Hacker%20News-122-%23FF6600" alt="Hacker News"></a>
<a href="https://www.producthunt.com/products/snoopforms"><img src="https://img.shields.io/badge/Product%20Hunt-%232%20Product%20of%20the%20Day-orange?logo=producthunt&logoColor=%23fff" alt="Product Hunt"></a>
</p>
<br/>
> :warning: snoopForms now becomes Formbricks. As part of the renaming, we are also sharpening the product and optimizing the core functionality for future features. Be excited when we present the new Formbricks in a few weeks. Until the core rebuild is complete, we are also pausing contributions to avoid major merge conflicts.
> :octocat: Are you looking for snoopForms - the Open Source Typeform Alternative? We're building the next stage of the snoopForms evolution here with Formbricks - more modular, more open, and for all your form needs. If you still are looking for the code of snoopForms you can find it in the [snoopforms branch](https://github.com/formbricks/formbricks/tree/snoopforms).
## About snoopForms
> :warning: Repository still in progress `#buildinpublic`
<img width="937" alt="snoopForms-architecture" src="https://user-images.githubusercontent.com/675065/182550268-09794c9e-1187-470e-b795-697ceb2a93b8.svg">
## About Formbricks
Spin up forms in minutes. Pipe your data exactly where you need it. Maximize your results with juicy analytics.
We're building all essential form functionality so you don't have to. Modular, customizable, extendable. And open source.
## What is snoopForms?
### Mission: Stop rewriting existing code
With snoopForms you can build complex multi-page forms in minutes using either our built-in No Code Builder or our [React library](https://github.com/formbricks/snoopforms/tree/main/packages/snoopforms-react). All form submissions are automatically sent to the snoopForms platform for processing and analysis. You can view the submission within the platform or you can easily configure pipelines to send your data to other systems, services or databases.
We want to solve forms once and for all. If, in 10 years, a web developer rewrites core form functionality instead of building on top of our stack, we didnt do our job. We want you to build your next big thing faster. Our big thing is the last form tool humanity needs. Hold us accountable!
[Read more in our blog](https://formbricks-com.vercel.app/blog/snoopforms-becomes-formbricks)
## Our Toolbox
Build a 'home-cooked' solution at the fraction of the time. We do the heavy lifting, you customize to your needs.
### React Forms Library
Building React forms has never been quicker. But there is more...
Loads of question types, validation, multi-page forms, logic jumps, i18n, custom styles - all the good stuff you want, but don't want to build yourself.
Building forms fast is great, but where do you pipe your data? And what is it worth without a schema?"
### Core API - The OS form engine
Your form looks perfect? Time to build integrations...
Our core API handles all of the submission handling of your forms and surveys. Our main objective is versatility, so that you can use it with any currently existing form. Soon we will integrate it with our React Form Builder. This allows for handling schemas so that you get a full image of your submission data.
### Features
- React Lib & No Code Builder to build & integrate forms rapidly.
- 100% compliant with all privacy regulations (self-hosted).
- (next) Put your data to work with integrations.
- (next) Juicy analytics out of the box.
- (always) smooth Developer Experience comes first.
- **Fast Form Creation**: Build complex forms with our React Lib. Our data pipes also work with any other form.
- **Data Pipelines**: Save your data where you need it. Use webhooks or pre-built integrations.
- **Powerful Data Insights**: View and manage your results quicker. Handle submissions in our dahsboard.
- **No-Code Builder**: Let your operators create and change forms. Stick with React to style and embed forms. `(coming soon)`
- **Built-in Analytics**: Opening rate, drop-offs, conversions. Use privacy-first analytics out of the box. `(coming soon)`
- **Survey Templates**: NPS, CSAT, Employee Surveys. Name your business objective, we have the questions. `(coming soon)`
### Why Formbricks
- **Futureproof**: Form needs change. With Formbricks youll avoid island solutions right from the start.
- **Privacy by design**: Self-host the entire product and fly through privacy compliance reviews.
- **Community driven**: We're building for you. If you need something specific, were happy to build it!
- **Great DX**: We love a solid developer experience. We felt your pain and do our best to avoid it.
- **Customizable**: We have to build opinionated. If it doesn't suit your need, just change it up.
- **Extendable**: Even though we try, we cannot build every single integration. With Formbricks, you can.
### Built With
@@ -47,115 +76,6 @@ With snoopForms you can build complex multi-page forms in minutes using either o
- [TailwindCSS](https://tailwindcss.com/)
- [Prisma](https://prisma.io/)
## Cloud vs. self-hosted
## Installation and usage
We offer you a ready hosted and maintained version of snoopForms on [snoopforms.com](https://snoopforms.com). It is always up to date and offers a generous free plan. If you want to try snoopForms, or save yourself the hassle and stress of self-hosting, this is the place to start.
The version of snoopForms you'll find in this repository is the same version that runs in the cloud, and you can easily host it yourself on your servers. See the readme below for the deployment instructions.
(In the future we may develop additional features that aren't in the free Open-Source version)
## Get started with development
This repository is a monorepository using [Turborepo](https://turborepo.org/) and [pnpm](https://pnpm.io/). It contains the snoopForms [server application](https://github.com/formbricks/snoopforms/tree/main/apps/web), the [react library](https://github.com/formbricks/snoopforms/tree/main/packages/react) and other helper packages like database or UI library.
### How to run locally
To get the project running locally on your machine you need to have the following development tools installed:
- Node.JS (we recommend v16)
- [pnpm](https://pnpm.io/)
- [Docker](https://www.docker.com/) (to run PostgreSQL / MailHog)
1. Clone the project:
```bash
git clone https://github.com/formbricks/snoopforms.git
```
and move into the directory
```bash
cd snoopforms
```
2. Install Node.JS packages via pnpm. Don't have pnpm? Get it [here](https://pnpm.io/installation)
```bash
pnpm install
```
3. To make the process of installing a dev dependencies easier, we offer a [`docker-compose.yml`](https://docs.docker.com/compose/) with the following containers:
- a `postgres` container and environment variables preset to reach it,
- a `mailhog` container that acts as a mock SMTP server and shows received mails in a web UI (forwarded to your host's `localhost:8025`)
```bash
docker-compose -f docker-compose.dev.yml up -d
```
4. Create a `.env` file based on `.env.example` and change it according to your setup. If you are using a cloud based database or another mail server, you will need to update the `DATABASE_URL` and SMTP settings in your `.env` accordingly.
```bash
cp .env.example .env
```
5. Make sure your PostgreSQL Database Server is running. Then let prisma set up the database for you:
```bash
pnpm dlx prisma migrate dev
```
6. Start the development server:
```bash
pnpm dev
```
**You can now access the app on [https://localhost:3000](https://localhost:3000)**. You will be automatically redirected to the login. To use your local installation of snoopForms, create a new account.
For viewing the confirmation email and other emails the system sends you, you can access mailhog at [https://localhost:8025](https://localhost:8025)
## Deployment for Production Setup
The easiest way to deploy snoopForms on your own machine is using Docker. This requires Docker and the docker compose plugin on your system to work.
Clone the repository:
```bash
git clone https://github.com/formbricks/snoopforms.git && cd snoopforms
```
Create a `.env` file based on `.env.docker` and change all fields according to your setup. This file comes with a basic setup and snoopForms works without making any changes to the file. To enable email sending functionality you need to configure the SMTP settings in the `.env` file. If you configured your email credentials, you can also comment the following lines to enable email verification (`# NEXT_PUBLIC_EMAIL_VERIFICATION_DISABLED=1`) and password reset (`# NEXT_PUBLIC_PASSWORD_RESET_DISABLED=1`)
Copy the `.env.docker` file to `.env` and edit it with an editor of your choice if needed.
```bash
cp .env.docker .env
```
Note: The environment variables are used at build time. When you change environment variables later, you need to rebuild the image with `docker compose build` for the changes to take effect.
Finally start the docker compose process to build and spin up the snoopForms container as well as the PostgreSQL database.
```bash
docker compose up -d
# (use docker-compose if you are on an older docker version)
```
You can now access the app on [https://localhost:3000](https://localhost:3000). You will be automatically redirected to the login. To use your local installation of snoopForms, create a new account.
## Contributing
Contributions are what make the open source community such an amazing place to be learn, inspire, and create. Any contributions you make are **greatly appreciated**.
1. Fork the project
2. Create your feature branch (`git checkout -b feature/AmazingFeature`)
3. Make your changes
4. Commit your changes (`git commit -m 'Add some AmazingFeature'`)
5. Push to the branch (`git push origin feature/AmazingFeature`)
6. Open a pull request
## License
Distributed under the AGPLv3 License. See `LICENSE` for more information.
Coming soon - we will update this Readme in the weeks ahead and show you how to leverage all the advantages of Formbricks

View File

@@ -98,10 +98,6 @@ Alongside the React Form Builder we'll redesign our Core API. You'll be able to:
Please [join our Discord](https://discord.com/invite/3YFcABF2Ts) to provide feedback on what's important to you!
## Becoming a company
Lastly, Matti and I wrapped up our other responsibilities to be able to fully focus on Formbricks. We incorporated in the US and are in the process of securing funding. We are super excited to get Formbricks up and running as quickly as possible.
**If youd like to follow along, connect with us on [Twitter](https://twitter.com/formbricks) and [join our Discord](https://discord.com/invite/3YFcABF2Ts)**
export default ({ children }) => <LayoutMdx meta={meta}>{children}</LayoutMdx>;

View File

@@ -1,2 +0,0 @@
User-agent: *
Disallow: /

View File

@@ -1,4 +0,0 @@
module.exports = {
root: true,
extends: ["formbricks"],
};

39
apps/web/.gitignore vendored
View File

@@ -1,39 +0,0 @@
# 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
.idea/
# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*
.pnpm-debug.log*
# local env files
.env.local
.env.development.local
.env.test.local
.env.production.local
# vercel
.vercel
# typescript
*.tsbuildinfo

View File

@@ -1,8 +0,0 @@
# web
## 1.0.1
### Patch Changes
- Updated dependencies [28b6410]
- @snoopforms/react@0.3.6

View File

@@ -1,41 +0,0 @@
# Add lockfile and package.json's of isolated subworkspace
FROM node:16-alpine AS installer
RUN apk update
RUN apk --no-cache add curl libc6-compat
RUN curl -fsSL "https://github.com/pnpm/pnpm/releases/latest/download/pnpm-linuxstatic-x64" -o /bin/pnpm; chmod +x /bin/pnpm;
WORKDIR /app
# First install the dependencies (as they change less often)
COPY . .
# Copy .env file because Docker don't follow symlinks
COPY .env /app/apps/web/
RUN pnpm install
# Build the project
RUN pnpm dlx prisma generate
RUN pnpm turbo run build --filter=web...
FROM node:16-alpine AS runner
RUN apk --no-cache add curl libc6-compat
RUN curl -fsSL "https://github.com/pnpm/pnpm/releases/latest/download/pnpm-linuxstatic-x64" -o /bin/pnpm; chmod +x /bin/pnpm;
# Don't run production as root
RUN addgroup --system --gid 1001 nodejs
RUN adduser --system --uid 1001 nextjs
USER nextjs
WORKDIR /home/nextjs
COPY --from=installer /app/apps/web/next.config.js .
COPY --from=installer /app/apps/web/package.json .
# Automatically leverage output traces to reduce image size
# https://nextjs.org/docs/advanced-features/output-file-tracing
COPY --from=installer --chown=nextjs:nodejs /app/apps/web/.next/standalone ./
COPY --from=installer --chown=nextjs:nodejs /app/apps/web/.next/static ./apps/web/.next/static
COPY --from=installer --chown=nextjs:nodejs /app/apps/web/public ./apps/web/public
COPY --from=installer --chown=nextjs:nodejs /app/packages/database/prisma ./packages/database/prisma
CMD pnpm dlx prisma migrate deploy && node apps/web/server.js

View File

@@ -1,147 +0,0 @@
import { Menu, Transition } from "@headlessui/react";
import { DocumentPlusIcon, PlusIcon, CommandLineIcon, SquaresPlusIcon } from "@heroicons/react/24/outline";
import { EllipsisHorizontalIcon, TrashIcon } from "@heroicons/react/24/solid";
import Link from "next/link";
import { Fragment, useState } from "react";
import { useForms } from "../lib/forms";
import { classNames } from "../lib/utils";
import NewFormModal from "./form/NewFormModal";
import EmptyPageFiller from "./layout/EmptyPageFiller";
export default function FormList() {
const { forms, mutateForms } = useForms();
const [openNewFormModal, setOpenNewFormModal] = useState(false);
const newForm = async () => {
setOpenNewFormModal(true);
};
const deleteForm = async (form, formIdx) => {
try {
await fetch(`/api/forms/${form.id}`, {
method: "DELETE",
});
// remove locally
const updatedForms = [...forms];
updatedForms.splice(formIdx, 1);
mutateForms(updatedForms);
} catch (error) {
console.error(error);
}
};
return (
<>
<div className="h-full px-6 py-8">
{forms &&
(forms.length === 0 ? (
<div className="mt-5 text-center">
<EmptyPageFiller
onClick={() => newForm()}
alertText="You don't have any forms yet."
hintText="Start by creating a form."
buttonText="create form"
borderStyles="border-4 border-dotted border-red"
hasButton={true}>
<DocumentPlusIcon className="text-ui-gray-medium stroke-thin mx-auto h-24 w-24" />
</EmptyPageFiller>
</div>
) : (
<ul className="grid grid-cols-2 place-content-stretch gap-6 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 ">
<button onClick={() => newForm()}>
<li className="col-span-1 h-56">
<div className="bg-snoopfade flex h-full items-center justify-center overflow-hidden rounded-md font-light text-white shadow">
<div className="px-4 py-8 sm:p-14">
<PlusIcon className="stroke-thin mx-auto h-14 w-14" />
create form
</div>
</div>
</li>
</button>
{forms
.sort((a, b) => b.updatedAt - a.updatedAt)
.map((form, formIdx) => (
<li key={form.id} className="relative col-span-1 h-56">
<div className="flex h-full flex-col justify-between rounded-md bg-white shadow">
<div className="p-6">
<p className="line-clamp-3 text-lg">{form.name}</p>
</div>
<Link href={`/forms/${form.id}`} className="absolute h-full w-full"></Link>
<div className="divide-ui-gray-light divide-y ">
<div className="bg-ui-gray-light text-ui-gray-dark mb-2 ml-4 inline-flex rounded-sm px-2 py-1 text-sm">
{form.formType == "NOCODE" ? (
<div className="flex">
<SquaresPlusIcon className="my-auto mr-1 h-4 w-4" />
No-Code
</div>
) : (
<div className="flex">
<CommandLineIcon className="my-auto mr-1 h-4 w-4" />
Code
</div>
)}
</div>
<div className="flex justify-between px-4 py-2 text-right sm:px-6">
<p className="text-ui-gray-medium text-xs ">
{form._count?.submissionSessions} responses
</p>
<Menu as="div" className="relative z-10 inline-block text-left">
{({ open }) => (
<>
<div>
<Menu.Button className="text-red -m-2 flex items-center rounded-full p-2">
<span className="sr-only">Open options</span>
<EllipsisHorizontalIcon className="h-5 w-5" aria-hidden="true" />
</Menu.Button>
</div>
<Transition
show={open}
as={Fragment}
enter="transition ease-out duration-100"
enterFrom="transform opacity-0 scale-95"
enterTo="transform opacity-100 scale-100"
leave="transition ease-in duration-75"
leaveFrom="transform opacity-100 scale-100"
leaveTo="transform opacity-0 scale-95">
<Menu.Items
static
className="absolute left-0 mt-2 w-56 origin-top-right rounded-sm bg-white px-1 shadow-lg">
<div className="py-1">
<Menu.Item>
{({ active }) => (
<button
onClick={() => deleteForm(form, formIdx)}
className={classNames(
active
? "bg-ui-gray-light text-ui-black rounded-sm"
: "text-ui-gray-dark",
"flex w-full px-4 py-2 text-sm"
)}>
<TrashIcon
className="text-ui-gray-dark mr-3 h-5 w-5"
aria-hidden="true"
/>
<span>Delete Form</span>
</button>
)}
</Menu.Item>
</div>
</Menu.Items>
</Transition>
</>
)}
</Menu>
</div>
</div>
</div>
</li>
))}
</ul>
))}
</div>
<NewFormModal open={openNewFormModal} setOpen={setOpenNewFormModal} />
</>
);
}

View File

@@ -1,16 +0,0 @@
import { TailSpin } from "react-loader-spinner";
export default function Loading() {
return (
<div className="min-h-screen bg-white px-4 py-16 sm:px-6 sm:py-24 md:grid md:place-items-center lg:px-8">
<div className="mx-auto max-w-max">
<main>
<div className="flex justify-center">
<TailSpin color="#1f2937" height={30} width={30} />
</div>
<p className="text-ui-gray-dark mt-5 text-sm">Loading...</p>
</main>
</div>
</div>
);
}

View File

@@ -1,46 +0,0 @@
import { Fragment } from "react";
import { Dialog, Transition } from "@headlessui/react";
import { TailSpin } from "react-loader-spinner";
export default function LoadingModal({ isLoading }) {
return (
<Transition.Root show={isLoading} as={Fragment}>
<Dialog
as="div"
static
className="fixed inset-0 z-10 overflow-y-auto"
open={isLoading}
onClose={() => {}}>
<div className="flex min-h-screen items-end justify-center px-4 pt-4 pb-20 text-center sm:block sm:p-0">
<Transition.Child
as={Fragment}
enter="ease-out duration-300"
enterFrom="opacity-0"
enterTo="opacity-100"
leave="ease-in duration-200"
leaveFrom="opacity-100"
leaveTo="opacity-0">
<Dialog.Overlay className="fixed inset-0 bg-gray-500 bg-opacity-20 transition-opacity" />
</Transition.Child>
{/* This element is to trick the browser into centering the modal contents. */}
<span className="hidden sm:inline-block sm:h-screen sm:align-middle" aria-hidden="true">
&#8203;
</span>
<Transition.Child
as={Fragment}
enter="ease-out duration-300"
enterFrom="opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95"
enterTo="opacity-100 translate-y-0 sm:scale-100"
leave="ease-in duration-200"
leaveFrom="opacity-100 translate-y-0 sm:scale-100"
leaveTo="opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95">
<div className="inline-flex transform items-center justify-center overflow-hidden rounded-lg px-4 py-20 pb-4 text-left align-bottom transition-all sm:my-8 sm:w-full sm:max-w-sm sm:p-6 sm:align-middle">
<TailSpin color="#000" height={50} width={50} />
</div>
</Transition.Child>
</div>
</Dialog>
</Transition.Root>
);
}

View File

@@ -1,11 +0,0 @@
export default function MessagePage({ text }) {
return (
<div className="min-h-screen bg-white px-4 py-16 sm:px-6 sm:py-24 md:grid md:place-items-center lg:px-8">
<div className="mx-auto max-w-max">
<main>
<div className="text-ui-gray-dark flex justify-center text-sm">{text}</div>
</main>
</div>
</div>
);
}

View File

@@ -1,49 +0,0 @@
/* This example requires Tailwind CSS v2.0+ */
import { Dialog, Transition } from "@headlessui/react";
import { XMarkIcon } from "@heroicons/react/24/outline";
import { Fragment } from "react";
export default function Modal({ open, setOpen, children }) {
return (
<Transition.Root show={open} as={Fragment}>
<Dialog as="div" className="relative z-10" onClose={setOpen}>
<Transition.Child
as={Fragment}
enter="ease-out duration-300"
enterFrom="opacity-0"
enterTo="opacity-100"
leave="ease-in duration-200"
leaveFrom="opacity-100"
leaveTo="opacity-0">
<div className="fixed inset-0 bg-gray-500 bg-opacity-75 transition-opacity" />
</Transition.Child>
<div className="fixed inset-0 z-10 overflow-y-auto">
<div className="flex min-h-full items-end justify-center p-4 text-center sm:items-center sm:p-0">
<Transition.Child
as={Fragment}
enter="ease-out duration-300"
enterFrom="opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95"
enterTo="opacity-100 translate-y-0 sm:scale-100"
leave="ease-in duration-200"
leaveFrom="opacity-100 translate-y-0 sm:scale-100"
leaveTo="opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95">
<Dialog.Panel className="relative transform overflow-hidden rounded-lg bg-white px-4 pt-5 pb-4 text-left shadow-xl transition-all sm:my-8 sm:w-full sm:max-w-xl sm:p-6 lg:max-w-3xl">
<div className="absolute top-0 right-0 hidden pt-4 pr-4 sm:block">
<button
type="button"
className="rounded-md bg-white text-gray-400 hover:text-gray-500 focus:outline-none focus:ring-2 focus:ring-red-500 focus:ring-offset-2"
onClick={() => setOpen(false)}>
<span className="sr-only">Close</span>
<XMarkIcon className="h-6 w-6" aria-hidden="true" />
</button>
</div>
<div className="flex-col sm:flex sm:items-start">{children}</div>
</Dialog.Panel>
</Transition.Child>
</div>
</div>
</Dialog>
</Transition.Root>
);
}

View File

@@ -1,44 +0,0 @@
import React from "react";
import { classNames } from "../lib/utils";
interface Props {
children: React.ReactNode;
onClick?: () => void;
disabled?: boolean;
fullwidth?: boolean;
small?: boolean;
icon?: boolean;
secondary?: boolean;
[key: string]: any;
}
// button component, consuming props
const StandardButton: React.FC<Props> = ({
children,
onClick = () => {},
disabled = false,
fullwidth = false,
small = false,
icon = false,
secondary = false,
...rest
}) => {
return (
<button
className={classNames(
`inline-flex items-center rounded shadow-sm focus:outline-none focus:ring-2 focus:ring-red-500 focus:ring-offset-2`,
disabled ? "disabled:opacity-50" : "",
fullwidth ? " w-full justify-center " : "",
small ? "px-2.5 py-1.5 text-xs" : "px-5 py-3 text-sm",
icon ? "px-1.5 py-1.5 text-xs" : "px-5 py-3 text-sm",
secondary ? "bg-ui-gray-light text-red" : "bg-snoopfade text-white"
)}
onClick={onClick}
disabled={disabled}
{...rest}>
{children}
</button>
);
};
export default StandardButton;

View File

@@ -1,138 +0,0 @@
import EditorJS from "@editorjs/editorjs";
import {
CogIcon,
DocumentPlusIcon,
EyeIcon,
PaperAirplaneIcon,
ShareIcon,
} from "@heroicons/react/24/outline";
import dynamic from "next/dynamic";
import { useRouter } from "next/router";
import { useRef, useState } from "react";
import { toast } from "react-toastify";
import { useForm } from "../../lib/forms";
import { persistNoCodeForm, useNoCodeForm } from "../../lib/noCodeForm";
import LimitedWidth from "../layout/LimitedWidth";
import SecondNavBar from "../layout/SecondNavBar";
import Loading from "../Loading";
import LoadingModal from "../LoadingModal";
import ShareModal from "./ShareModal";
import SettingsModal from "./SettingsModal";
let Editor = dynamic(() => import("../editorjs/Editor"), {
ssr: false,
});
/* import Editor from "../editorjs/Editor"; */
export default function Builder({ formId }) {
const router = useRouter();
const editorRef = useRef<EditorJS | null>();
const { isLoadingForm } = useForm(formId);
const { noCodeForm, isLoadingNoCodeForm, mutateNoCodeForm } = useNoCodeForm(formId);
const [openShareModal, setOpenShareModal] = useState(false);
const [openSettingsModal, setOpenSettingsModal] = useState(false);
const [loading, setLoading] = useState(false);
const addPage = () => {
editorRef.current.blocks.insert("pageTransition", {
submitLabel: "Submit",
});
const block = editorRef.current.blocks.insert("paragraph");
editorRef.current.caret.setToBlock(editorRef.current.blocks.getBlockIndex(block.id));
};
const initAction = async (editor: EditorJS) => {
editor.blocks.insert("header", {
text: noCodeForm.form.name,
});
const focusBlock = editor.blocks.insert("textQuestion");
editor.blocks.insert("pageTransition", {
submitLabel: "Submit",
});
editor.blocks.insert("header", {
text: "Thank you",
});
editor.blocks.insert("paragraph", {
text: "Thanks a lot for your time and insights 🙏",
});
editor.blocks.delete(0); // remove defaultBlock
editor.caret.setToBlock(editorRef.current.blocks.getBlockIndex(focusBlock.id));
};
const publishChanges = async () => {
setLoading(true);
setTimeout(async () => {
const newNoCodeForm = JSON.parse(JSON.stringify(noCodeForm));
const firstPublish = newNoCodeForm.published ? false : true;
newNoCodeForm.blocks = newNoCodeForm.blocksDraft;
newNoCodeForm.published = true;
await persistNoCodeForm(newNoCodeForm);
mutateNoCodeForm(newNoCodeForm);
setLoading(false);
toast(firstPublish ? "Your form is now published 🎉" : "Your changes are now published 🎉");
}, 500);
};
const noCodeSecondNavigation = [
{
id: "addPage",
onClick: () => addPage(),
Icon: DocumentPlusIcon,
//Icon: PlusIcon
label: "Page",
},
{
id: "preview",
onClick: () => {
router.push(`/forms/${formId}/preview`);
},
Icon: EyeIcon,
label: "Preview",
},
{
id: "publish",
onClick: () => publishChanges(),
Icon: PaperAirplaneIcon,
label: "Publish",
},
{
id: "share",
onClick: () => setOpenShareModal(true),
Icon: ShareIcon,
label: "Share",
},
{
id: "settings",
onClick: () => setOpenSettingsModal(true),
Icon: CogIcon,
label: "Settings",
},
];
if (isLoadingNoCodeForm || isLoadingForm) {
return <Loading />;
}
return (
<>
<SecondNavBar navItems={noCodeSecondNavigation} />
<div className="mb-20 h-full w-full overflow-auto bg-white">
<div className="flex w-full justify-center pt-10 pb-56">
<LimitedWidth>
{Editor && (
<Editor
id="editor"
formId={formId}
editorRef={editorRef}
autofocus={true}
initAction={initAction}
/>
)}
</LimitedWidth>
</div>
</div>
<ShareModal open={openShareModal} setOpen={setOpenShareModal} formId={formId} />
<SettingsModal open={openSettingsModal} setOpen={setOpenSettingsModal} formId={formId} />
<LoadingModal isLoading={loading} />
</>
);
}

View File

@@ -1,53 +0,0 @@
/* This example requires Tailwind CSS v2.0+ */
import { TrashIcon } from "@heroicons/react/24/solid";
import { MdWavingHand } from "react-icons/md";
import { classNames } from "../../lib/utils";
export default function PageToolbar({ page, pageIdx, deletePageAction, setPageType }) {
return (
<div className="relative">
<div className="absolute inset-0 flex items-center" aria-hidden="true">
<div className="w-full border-t border-gray-200" />
</div>
<div className="relative flex justify-center">
<span className="relative z-0 inline-flex -space-x-px rounded-md shadow-sm">
<button
type="button"
onClick={() => {
if (page.type === "form") {
return setPageType("thankyou");
} else if (page.type === "thankyou") {
return setPageType("form");
}
}}
className={classNames(
page.type === "thankyou"
? "bg-red-400 text-white hover:bg-red-500"
: "bg-white text-gray-400 hover:bg-gray-50",
"has-tooltip relative inline-flex items-center rounded-l-md border border-gray-300 px-4 py-2 text-sm font-medium focus:z-10 focus:border-red-500 focus:outline-none focus:ring-1 focus:ring-red-500"
)}>
<span className="sr-only">Thank You Page</span>
<span className="tooltip -mt-16 -ml-10 w-32 rounded bg-gray-600 p-1 text-xs text-white shadow-lg">
Is Thank You Page
</span>
<MdWavingHand className="h-4 w-4" aria-hidden="true" />
</button>
<button
type="button"
onClick={() => {
if (confirm("Do you really want to delete this page?")) {
deletePageAction(pageIdx);
}
}}
className="has-tooltip relative inline-flex items-center rounded-r-md border border-gray-300 bg-white px-4 py-2 text-sm font-medium text-gray-400 hover:bg-gray-50 focus:z-10 focus:border-red-500 focus:outline-none focus:ring-1 focus:ring-red-500">
<span className="sr-only">Delete</span>
<span className="tooltip -mt-16 -ml-8 w-24 rounded bg-gray-600 p-1 text-xs text-white shadow-lg">
Delete Page
</span>
<TrashIcon className="h-4 w-4" aria-hidden="true" />
</button>
</span>
</div>
</div>
);
}

View File

@@ -1,115 +0,0 @@
/* This example requires Tailwind CSS v2.0+ */
import { Dialog, Switch, Transition } from "@headlessui/react";
import { Fragment, useState } from "react";
import { TailSpin } from "react-loader-spinner";
import { persistNoCodeForm, useNoCodeForm } from "../../lib/noCodeForm";
import Loading from "../Loading";
import { XMarkIcon } from "@heroicons/react/24/outline";
import { toast } from "react-toastify";
import { classNames } from "../../lib/utils";
export default function SettingsModal({ open, setOpen, formId }) {
const { noCodeForm, isLoadingNoCodeForm, mutateNoCodeForm } = useNoCodeForm(formId);
const [loading, setLoading] = useState(false);
const toggleClose = async () => {
setLoading(true);
setTimeout(async () => {
const newNoCodeForm = JSON.parse(JSON.stringify(noCodeForm));
newNoCodeForm.closed = !noCodeForm.closed;
await persistNoCodeForm(newNoCodeForm);
mutateNoCodeForm(newNoCodeForm);
setLoading(false);
toast(
newNoCodeForm.closed
? "Your form is now closed for submissions "
: "Your form is now open for submissions 🎉"
);
}, 500);
};
if (isLoadingNoCodeForm) {
return <Loading />;
}
return (
<Transition.Root show={open} as={Fragment}>
<Dialog as="div" className="relative z-10" onClose={setOpen}>
<Transition.Child
as={Fragment}
enter="ease-out duration-300"
enterFrom="opacity-0"
enterTo="opacity-100"
leave="ease-in duration-200"
leaveFrom="opacity-100"
leaveTo="opacity-0">
<div className="fixed inset-0 bg-gray-500 bg-opacity-75 transition-opacity" />
</Transition.Child>
<div className="fixed inset-0 z-10 overflow-y-auto">
<div className="flex min-h-full items-end justify-center p-4 text-center sm:items-center sm:p-0">
<Transition.Child
as={Fragment}
enter="ease-out duration-300"
enterFrom="opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95"
enterTo="opacity-100 translate-y-0 sm:scale-100"
leave="ease-in duration-200"
leaveFrom="opacity-100 translate-y-0 sm:scale-100"
leaveTo="opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95">
<Dialog.Panel className="relative transform overflow-hidden rounded-lg bg-white px-4 pt-5 pb-4 text-left shadow-xl transition-all sm:my-8 sm:w-full sm:max-w-4xl sm:p-6">
<div className="absolute top-0 right-0 hidden pt-4 pr-4 sm:block">
<button
type="button"
className="rounded-md bg-white text-gray-400 hover:text-gray-500 focus:outline-none focus:ring-2 focus:ring-red-500 focus:ring-offset-2"
onClick={() => setOpen(false)}>
<span className="sr-only">Close</span>
<XMarkIcon className="h-6 w-6" aria-hidden="true" />
</button>
</div>
<div className="px-4 py-5 sm:p-6">
<div className="mb-4">
<h1 className="text-2xl font-medium leading-6 text-gray-900">Settings</h1>
</div>
<h3 className="text-lg font-medium leading-6 text-gray-900">Access</h3>
<div className="mt-2 w-full text-sm text-gray-500">
<Switch.Group as="div" className="flex w-full items-center justify-between">
<span className="flex flex-grow flex-col">
<Switch.Label as="span" className="text-sm font-medium text-gray-900" passive={true}>
Close form for new submissions?
</Switch.Label>
<Switch.Description as="span" className="text-sm text-gray-500">
Your form is currently{" "}
<span className="font-bold">{noCodeForm.closed ? "closed" : "open"}</span> for
submissions.
</Switch.Description>
</span>
{loading ? (
<TailSpin color="#1f2937" height={30} width={30} />
) : (
<Switch
checked={noCodeForm.closed}
onChange={() => toggleClose()}
className={classNames(
noCodeForm.closed ? "bg-red-600" : "bg-gray-200",
"relative inline-flex h-6 w-11 flex-shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out focus:outline-none focus:ring-2 focus:ring-red-500 focus:ring-offset-2"
)}>
<span
aria-hidden="true"
className={classNames(
noCodeForm.closed ? "translate-x-5" : "translate-x-0",
"pointer-events-none inline-block h-5 w-5 transform rounded-full bg-white shadow ring-0 transition duration-200 ease-in-out"
)}
/>
</Switch>
)}
</Switch.Group>
</div>
</div>
</Dialog.Panel>
</Transition.Child>
</div>
</div>
</Dialog>
</Transition.Root>
);
}

View File

@@ -1,108 +0,0 @@
/* This example requires Tailwind CSS v2.0+ */
import { Dialog, Transition } from "@headlessui/react";
import { InformationCircleIcon, XMarkIcon } from "@heroicons/react/24/outline";
import { toast } from "react-toastify";
import { Fragment } from "react";
import { useNoCodeForm } from "../../lib/noCodeForm";
import Loading from "../Loading";
export default function ShareModal({ open, setOpen, formId }) {
const { noCodeForm, isLoadingNoCodeForm } = useNoCodeForm(formId);
const getPublicFormUrl = () => {
if (process.browser) {
return `${window.location.protocol}//${window.location.host}/f/${formId}/`;
}
};
if (isLoadingNoCodeForm) {
return <Loading />;
}
return (
<Transition.Root show={open} as={Fragment}>
<Dialog as="div" className="relative z-10" onClose={setOpen}>
<Transition.Child
as={Fragment}
enter="ease-out duration-300"
enterFrom="opacity-0"
enterTo="opacity-100"
leave="ease-in duration-200"
leaveFrom="opacity-100"
leaveTo="opacity-0">
<div className="fixed inset-0 bg-gray-500 bg-opacity-75 transition-opacity" />
</Transition.Child>
<div className="fixed inset-0 z-10 overflow-y-auto">
<div className="flex min-h-full items-end justify-center p-4 text-center sm:items-center sm:p-0">
<Transition.Child
as={Fragment}
enter="ease-out duration-300"
enterFrom="opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95"
enterTo="opacity-100 translate-y-0 sm:scale-100"
leave="ease-in duration-200"
leaveFrom="opacity-100 translate-y-0 sm:scale-100"
leaveTo="opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95">
<Dialog.Panel className="relative transform overflow-hidden rounded-lg bg-white px-4 pt-5 pb-4 text-left shadow-xl transition-all sm:my-8 sm:w-full sm:max-w-4xl sm:p-6">
<div className="absolute top-0 right-0 hidden pt-4 pr-4 sm:block">
<button
type="button"
className="rounded-md bg-white text-gray-400 hover:text-gray-500 focus:outline-none focus:ring-2 focus:ring-red-500 focus:ring-offset-2"
onClick={() => setOpen(false)}>
<span className="sr-only">Close</span>
<XMarkIcon className="h-6 w-6" aria-hidden="true" />
</button>
</div>
{!noCodeForm.published ? (
<div className="bg-ui-gray-light rounded-md border border-gray-700 p-4">
<div className="flex">
<div className="flex-shrink-0">
<InformationCircleIcon className="h-5 w-5 text-blue-400" aria-hidden="true" />
</div>
<div className="ml-3 flex-1 md:flex md:justify-between">
<p className="text-sm text-gray-700">
You haven&apos;t published this form yet. Please publish this form to share it with
others and get the first submissions.
</p>
</div>
</div>
</div>
) : (
<div className="px-4 py-5 sm:p-6">
<h3 className="text-lg font-medium leading-6 text-gray-900">Share your form</h3>
<div className="mt-2 max-w-xl text-sm text-gray-500">
<p>Let your participants fill out your form by accessing it via the public link.</p>
</div>
<div className="mt-5 sm:flex sm:items-center">
<div className="w-full sm:max-w-xs">
<label htmlFor="surveyLink" className="sr-only">
Public link
</label>
<input
id="surveyLink"
type="text"
placeholder="Enter your email"
className="block w-full rounded-md border-gray-300 shadow-sm focus:border-red-500 focus:ring-red-500 sm:text-sm"
value={getPublicFormUrl()}
disabled
/>
</div>
<button
onClick={() => {
navigator.clipboard.writeText(getPublicFormUrl());
toast("Link copied to clipboard 🙌");
}}
className="mt-3 inline-flex w-full items-center justify-center rounded-md border border-transparent bg-gray-800 px-4 py-2 font-medium text-white shadow-sm hover:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-gray-500 focus:ring-offset-2 sm:mt-0 sm:ml-3 sm:w-auto sm:text-sm">
Copy
</button>
</div>
</div>
)}
</Dialog.Panel>
</Transition.Child>
</div>
</div>
</Dialog>
</Transition.Root>
);
}

View File

@@ -1,124 +0,0 @@
/* eslint-disable react-hooks/exhaustive-deps */
import EditorJS from "@editorjs/editorjs";
import Header from "@editorjs/header";
import Paragraph from "@editorjs/paragraph";
import DragDrop from "editorjs-drag-drop";
import Undo from "editorjs-undo";
import { Fragment, useCallback, useEffect } from "react";
import { toast } from "react-toastify";
import { persistNoCodeForm, useNoCodeForm } from "../../lib/noCodeForm";
import Loading from "../Loading";
import EmailQuestion from "./tools/EmailQuestion";
import PageTransition from "./tools/PageTransition";
import MultipleChoiceQuestion from "./tools/MultipleChoiceQuestion";
import TextQuestion from "./tools/TextQuestion";
import WebsiteQuestion from "./tools/WebsiteQuestion";
import PhoneQuestion from "./tools/PhoneQuestion";
import NumberQuestion from "./tools/NumberQuestion";
import TextareaQuestion from "./tools/TextareaQuestion";
interface EditorProps {
id: string;
autofocus: boolean;
editorRef: { current: EditorJS | null };
formId: string;
initAction: (editor: EditorJS) => void;
}
const Editor = ({ id, autofocus = false, editorRef, formId, initAction }: EditorProps) => {
const { noCodeForm, isLoadingNoCodeForm, mutateNoCodeForm } = useNoCodeForm(formId);
const keyPressListener = useCallback((e) => {
if (e.key === "s" && (e.metaKey || e.ctrlKey)) {
e.preventDefault();
toast("snoopForms autosaves your work ✌️");
}
}, []);
useEffect(() => {
window.addEventListener("keydown", keyPressListener);
// Remove event listeners on cleanup
return () => {
window.removeEventListener("keydown", keyPressListener);
};
}, [keyPressListener]);
// This will run only once
useEffect(() => {
if (!isLoadingNoCodeForm) {
if (!editorRef.current) {
initEditor();
}
}
return () => {
destroyEditor();
};
async function destroyEditor() {
await editorRef.current.isReady;
editorRef.current.destroy();
editorRef.current = null;
}
}, [isLoadingNoCodeForm]);
const initEditor = () => {
const editor = new EditorJS({
minHeight: 0,
holder: id,
data: { blocks: noCodeForm.blocksDraft },
onReady: () => {
editorRef.current = editor;
new DragDrop(editor);
new Undo({ editor });
if (editor.blocks.getBlocksCount() === 1) {
initAction(editor);
}
},
onChange: async () => {
let content = await editor.saver.save();
const newNoCodeForm = JSON.parse(JSON.stringify(noCodeForm));
newNoCodeForm.blocksDraft = content.blocks;
await persistNoCodeForm(newNoCodeForm);
mutateNoCodeForm(newNoCodeForm);
},
autofocus: autofocus,
defaultBlock: "paragraph",
tools: {
textQuestion: TextQuestion,
textareaQuestion: TextareaQuestion,
emailQuestion: EmailQuestion,
multipleChoiceQuestion: MultipleChoiceQuestion,
numberQuestion: NumberQuestion,
phoneQuestion: PhoneQuestion,
websiteQuestion: WebsiteQuestion,
pageTransition: PageTransition,
paragraph: {
class: Paragraph,
inlineToolbar: true,
config: {
placeholder: "Start with your content or hit tab-key to insert block",
},
},
header: {
class: Header,
config: {
placeholder: "Enter a header",
levels: [1, 2, 3],
defaultLevel: 1,
},
},
},
});
};
if (isLoadingNoCodeForm) {
return <Loading />;
}
return (
<Fragment>
<div id={id} />
</Fragment>
);
};
export default Editor;

View File

@@ -1,102 +0,0 @@
import { API, BlockTool, BlockToolData, ToolConfig } from "@editorjs/editorjs";
import ReactDOM from "react-dom";
import EmailQuestionComponent from "./EmailQuestionComponent";
export interface EmailQuestionData extends BlockToolData {
label: string;
help: string;
placeholder: string;
required: boolean;
}
export default class EmailQuestion implements BlockTool {
settings: { name: string; icon: string }[];
api: API;
data: EmailQuestionData;
nodes: { holder: HTMLElement };
config: ToolConfig;
static get toolbox(): { icon: string; title?: string } {
return {
icon: `<svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" viewBox="0 0 20 20" fill="currentColor">
<path fill-rule="evenodd" d="M14.243 5.757a6 6 0 10-.986 9.284 1 1 0 111.087 1.678A8 8 0 1118 10a3 3 0 01-4.8 2.401A4 4 0 1114 10a1 1 0 102 0c0-1.537-.586-3.07-1.757-4.243zM12 10a2 2 0 10-4 0 2 2 0 004 0z" clip-rule="evenodd" />
</svg>`,
title: "Email Question",
};
}
constructor({ api, config, data }: { api: API; config?: ToolConfig; data?: EmailQuestionData }) {
this.api = api;
this.config = config;
this.settings = [
{
name: "required",
icon: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 480 512" class="w-3 h-3"><path d="M471.99 334.43L336.06 256l135.93-78.43c7.66-4.42 10.28-14.2 5.86-21.86l-32.02-55.43c-4.42-7.65-14.21-10.28-21.87-5.86l-135.93 78.43V16c0-8.84-7.17-16-16.01-16h-64.04c-8.84 0-16.01 7.16-16.01 16v156.86L56.04 94.43c-7.66-4.42-17.45-1.79-21.87 5.86L2.15 155.71c-4.42 7.65-1.8 17.44 5.86 21.86L143.94 256 8.01 334.43c-7.66 4.42-10.28 14.21-5.86 21.86l32.02 55.43c4.42 7.65 14.21 10.27 21.87 5.86l135.93-78.43V496c0 8.84 7.17 16 16.01 16h64.04c8.84 0 16.01-7.16 16.01-16V339.14l135.93 78.43c7.66 4.42 17.45 1.8 21.87-5.86l32.02-55.43c4.42-7.65 1.8-17.43-5.86-21.85z"/></svg>`,
},
];
this.data = {
label: data.label || "",
help: data.help || "",
placeholder: data.placeholder || "your email",
required: data.required || false,
};
this.nodes = {
holder: null,
};
}
renderSettings(): HTMLElement {
const wrapper = document.createElement("div");
this.settings.forEach((tune) => {
let button = document.createElement("div");
button.classList.add("cdx-settings-button");
button.classList.toggle("cdx-settings-button--active", this.data[tune.name]);
button.innerHTML = tune.icon;
wrapper.appendChild(button);
button.addEventListener("click", () => {
this._toggleTune(tune.name);
button.classList.toggle("cdx-settings-button--active");
});
});
return wrapper;
}
/**
* @private
* Click on the Settings Button
* @param {string} tune — tune name from this.settings
*/
_toggleTune(tune: string) {
if (tune === "required") {
this.data.required = !this.data.required;
}
}
render(): HTMLElement {
const rootNode = document.createElement("div");
this.nodes.holder = rootNode;
const onDataChange = (newData: EmailQuestionData) => {
this.data = {
...newData,
};
};
ReactDOM.render(<EmailQuestionComponent onDataChange={onDataChange} data={this.data} />, rootNode);
return this.nodes.holder;
}
save() {
return this.data;
}
}

View File

@@ -1,84 +0,0 @@
/* eslint-disable react-hooks/exhaustive-deps */
import { EnvelopeIcon } from "@heroicons/react/24/solid";
import { default as React } from "react";
import { type EmailQuestionData } from "./EmailQuestion";
const DEFAULT_INITIAL_DATA = () => {
return {
label: "",
placeholder: "",
help: "",
required: false,
};
};
type Props = {
data: EmailQuestionData;
onDataChange: (newData: EmailQuestionData) => void;
};
const EmailQuestionComponent = (props: Props) => {
const [data, setData] = React.useState(props.data ? props.data : DEFAULT_INITIAL_DATA);
const updateData = (newData: EmailQuestionData) => {
setData(newData);
if (props.onDataChange) {
props.onDataChange(newData);
}
};
const onInputChange = (fieldName: string) => {
return (e: React.FormEvent<HTMLInputElement>) => {
const newData = {
...data,
};
newData[fieldName] = e.currentTarget.value;
updateData(newData);
};
};
return (
<div className="pb-5">
<div className="text-md relative font-bold leading-7 text-gray-800 sm:truncate">
<input
type="text"
id="label"
defaultValue={data.label}
className="w-full border-0 border-transparent p-0 ring-0 placeholder:text-gray-300 focus:ring-0"
placeholder="Your Question"
onChange={onInputChange("label")}
/>
{data.required && (
<div className="pointer-events-none absolute inset-y-0 right-0 flex items-center pr-3 text-red-500">
*
</div>
)}
</div>
<div className="relative mt-1 max-w-sm rounded-md shadow-sm">
<div className="pointer-events-none absolute inset-y-0 left-0 flex items-center pl-3">
<EnvelopeIcon className="h-5 w-5 text-gray-400" aria-hidden="true" />
</div>
<input
type="text"
name="email"
className="block w-full rounded-md border-gray-300 pl-10 text-gray-300 sm:text-sm"
defaultValue={data.placeholder}
onChange={onInputChange("placeholder")}
/>
</div>
<input
type="text"
id="help-text"
defaultValue={data.help}
className="mt-2 block w-full max-w-sm border-0 border-transparent p-0 text-sm font-light text-gray-500 ring-0 placeholder:text-gray-300 focus:ring-0"
placeholder="optional help text"
onChange={onInputChange("help")}
/>
</div>
);
};
export default EmailQuestionComponent;

View File

@@ -1,129 +0,0 @@
import { API, BlockTool, BlockToolData, ToolConfig } from "@editorjs/editorjs";
import { default as React } from "react";
import ReactDOM from "react-dom";
import MultipleChoiceQuestionComponent from "./MultipleChoiceQuestionComponent";
interface MultipleChoiceQuestionData extends BlockToolData {
label: string;
help: string;
options: string[];
required: boolean;
}
export default class MultipleChoiceQuestion implements BlockTool {
settings: { name: string; icon: string }[];
api: API;
config: ToolConfig;
data: any;
readOnly: boolean;
block: any;
wrapper: undefined | HTMLElement;
nodes: { holder: HTMLElement };
static get toolbox(): { icon: string; title?: string } {
return {
icon: `<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" width="16" height="16" viewBox="0 0 16 16">
<path fill="#000000" d="M8 0c-4.418 0-8 3.582-8 8s3.582 8 8 8 8-3.582 8-8-3.582-8-8-8zM8 14c-3.314 0-6-2.686-6-6s2.686-6 6-6c3.314 0 6 2.686 6 6s-2.686 6-6 6zM5 8c0-1.657 1.343-3 3-3s3 1.343 3 3c0 1.657-1.343 3-3 3s-3-1.343-3-3z"/>
</svg>`,
title: "Multiple Choice Question",
};
}
static get isReadOnlySupported() {
return true;
}
constructor({
data,
config,
api,
readOnly,
}: {
api: API;
config?: ToolConfig;
data?: MultipleChoiceQuestionData;
block?: any;
readOnly: boolean;
}) {
this.api = api;
this.config = config;
this.readOnly = readOnly;
this.data = {
label: data.label || "",
help: data.help || "",
options: data.options || [],
required: data.required || false,
multipleChoice: data.multipleChoice || false,
};
this.settings = [
{
name: "required",
icon: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 480 512" class="w-3 h-3"><!-- Font Awesome Pro 5.15.4 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license (Commercial License) --><path d="M471.99 334.43L336.06 256l135.93-78.43c7.66-4.42 10.28-14.2 5.86-21.86l-32.02-55.43c-4.42-7.65-14.21-10.28-21.87-5.86l-135.93 78.43V16c0-8.84-7.17-16-16.01-16h-64.04c-8.84 0-16.01 7.16-16.01 16v156.86L56.04 94.43c-7.66-4.42-17.45-1.79-21.87 5.86L2.15 155.71c-4.42 7.65-1.8 17.44 5.86 21.86L143.94 256 8.01 334.43c-7.66 4.42-10.28 14.21-5.86 21.86l32.02 55.43c4.42 7.65 14.21 10.27 21.87 5.86l135.93-78.43V496c0 8.84 7.17 16 16.01 16h64.04c8.84 0 16.01-7.16 16.01-16V339.14l135.93 78.43c7.66 4.42 17.45 1.8 21.87-5.86l32.02-55.43c4.42-7.65 1.8-17.43-5.86-21.85z"/></svg>`,
},
];
this.nodes = {
holder: null,
};
}
renderSettings(): HTMLElement {
const wrapper = document.createElement("div");
this.settings.forEach((tune) => {
let button = document.createElement("div");
button.classList.add("cdx-settings-button");
button.classList.toggle("cdx-settings-button--active", this.data[tune.name]);
button.innerHTML = tune.icon;
wrapper.appendChild(button);
button.addEventListener("click", () => {
this._toggleTune(tune.name);
button.classList.toggle("cdx-settings-button--active");
});
});
return wrapper;
}
/**
* @private
* Click on the Settings Button
* @param {string} tune — tune name from this.settings
*/
_toggleTune(tune) {
//this.wrapper.classList.toggle(tune.name, !!this.data[tune.name]);
if (tune === "required") {
this.data.required = !this.data.required;
}
}
render() {
const rootNode = document.createElement("div");
//rootNode.setAttribute("class", this.CSS.wrapper);
this.nodes.holder = rootNode;
const onDataChange = (newData) => {
this.data = {
...newData,
};
};
ReactDOM.render(
<MultipleChoiceQuestionComponent
onDataChange={onDataChange}
readOnly={this.readOnly}
data={this.data}
/>,
rootNode
);
return this.nodes.holder;
}
save() {
return this.data;
}
}

View File

@@ -1,166 +0,0 @@
/* eslint-disable react-hooks/exhaustive-deps */
import { Switch } from "@headlessui/react";
import { TrashIcon } from "@heroicons/react/24/solid";
import { default as React } from "react";
import { v4 as uuidv4 } from "uuid";
import { classNames } from "../../../lib/utils";
const DEFAULT_INITIAL_DATA = () => {
return {
label: "",
help: "",
required: false,
multipleChoice: false,
options: [
{
id: uuidv4(),
label: "",
},
],
};
};
const SingleChoiceQuestion = (props) => {
const [choiceData, setChoiceData] = React.useState(
props.data.options.length > 0 ? props.data : DEFAULT_INITIAL_DATA
);
const updateData = (newData) => {
setChoiceData(newData);
if (props.onDataChange) {
// Inform editorjs about data change
props.onDataChange(newData);
}
};
const onAddOption = () => {
const newData = {
...choiceData,
};
newData.options.push({
id: uuidv4(),
label: "",
});
updateData(newData);
};
const onDeleteOption = (optionIdx) => {
const newData = {
...choiceData,
};
newData.options.splice(optionIdx, 1);
updateData(newData);
};
const onInputChange = (fieldName) => {
return (e) => {
const newData = {
...choiceData,
};
newData[fieldName] = e.currentTarget.value;
updateData(newData);
};
};
const onOptionChange = (index, fieldName) => {
return (e) => {
const newData = {
...choiceData,
};
newData.options[index][fieldName] = e.currentTarget.value;
updateData(newData);
};
};
return (
<div className="pb-5">
<div className="text-md relative font-bold leading-7 text-gray-800 sm:truncate">
<input
type="text"
id="label"
defaultValue={choiceData.label}
onBlur={onInputChange("label")}
className="w-full border-0 border-transparent p-0 ring-0 placeholder:text-gray-300 focus:ring-0"
placeholder="Your Question"
/>
{choiceData.required && (
<div className="pointer-events-none absolute inset-y-0 right-0 flex items-center pr-3 text-red-500">
*
</div>
)}
</div>
<div className="mt-2 space-y-2">
{choiceData.options.map((option, optionIdx) => (
<div key={option.label} className="relative flex items-start pr-2 hover:rounded hover:bg-gray-50">
<span className="flex w-full items-center text-sm ">
<span
className={classNames(
choiceData.multipleChoice ? "rounded-sm" : "rounded-full",
"flex h-4 w-4 items-center justify-center border border-gray-300"
)}
aria-hidden="true">
<span className="h-1.5 w-1.5 rounded-full" />
</span>
<input
type="text"
defaultValue={option.label}
onBlur={onOptionChange(optionIdx, "label")}
className="ml-3 w-full border-0 border-transparent bg-transparent p-0 font-medium text-gray-900 outline-none placeholder:text-gray-300 focus:outline-none focus:ring-0"
placeholder={`Option ${optionIdx + 1}`}
/>
{optionIdx !== 0 && (
<button onClick={() => onDeleteOption(optionIdx)} className="right-3 pl-4">
<TrashIcon className="h-4 w-4 text-gray-300" />
</button>
)}
</span>
</div>
))}
</div>
<input
type="text"
id="help-text"
defaultValue={choiceData.help}
onBlur={onInputChange("help")}
className="mt-2 block w-full max-w-sm border-0 border-transparent p-0 text-sm font-light text-gray-500 ring-0 placeholder:text-gray-300 focus:ring-0"
placeholder="optional help text"
/>
<div className="relative z-0 mt-2 flex divide-x divide-gray-200">
<button
className="mr-3 mt-2 inline-flex items-center justify-center rounded border border-gray-300 bg-white px-2.5 py-1.5 text-xs font-medium text-gray-700 shadow-sm hover:bg-gray-50 focus:outline-none"
onClick={onAddOption}>
Add option
</button>
<Switch.Group as="div" className="flex items-center pl-3">
<Switch
checked={choiceData.multipleChoice}
onChange={() => {
const newData = {
...choiceData,
};
newData.multipleChoice = !newData.multipleChoice;
updateData(newData);
}}
className={classNames(
choiceData.multipleChoice ? "bg-red-600" : "bg-gray-200",
"relative inline-flex h-4 w-7 flex-shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out focus:outline-none focus:ring-2 focus:ring-red-500 focus:ring-offset-2"
)}>
<span
aria-hidden="true"
className={classNames(
choiceData.multipleChoice ? "translate-x-3" : "translate-x-0",
"pointer-events-none inline-block h-3 w-3 transform rounded-full bg-white shadow ring-0 transition duration-200 ease-in-out"
)}
/>
</Switch>
<Switch.Label as="span" className="ml-3">
<span className="text-sm font-medium text-gray-700">Multiple Selection </span>
{/* <span className="text-sm text-gray-500">(Save 10%)</span> */}
</Switch.Label>
</Switch.Group>
</div>
</div>
);
};
export default SingleChoiceQuestion;

View File

@@ -1,101 +0,0 @@
import { API, BlockTool, BlockToolData, ToolConfig } from "@editorjs/editorjs";
import ReactDOM from "react-dom";
import NumberQuestionComponent from "./NumberQuestionComponent";
export interface NumberQuestionData extends BlockToolData {
label: string;
help: string;
placeholder: string;
required: boolean;
}
export default class NumberQuestion implements BlockTool {
settings: { name: string; icon: string }[];
api: API;
data: NumberQuestionData;
nodes: { holder: HTMLElement };
config: ToolConfig;
static get toolbox(): { icon: string; title?: string } {
return {
icon: `<svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" viewBox="0 0 20 20" fill="currentColor">
<path fill-rule="evenodd" d="M9.243 3.03a1 1 0 01.727 1.213L9.53 6h2.94l.56-2.243a1 1 0 111.94.486L14.53 6H17a1 1 0 110 2h-2.97l-1 4H15a1 1 0 110 2h-2.47l-.56 2.242a1 1 0 11-1.94-.485L10.47 14H7.53l-.56 2.242a1 1 0 11-1.94-.485L5.47 14H3a1 1 0 110-2h2.97l1-4H5a1 1 0 110-2h2.47l.56-2.243a1 1 0 011.213-.727zM9.03 8l-1 4h2.938l1-4H9.031z" clip-rule="evenodd" />
</svg>`,
title: "Number Question",
};
}
constructor({ api, config, data }: { api: API; config?: ToolConfig; data?: NumberQuestionData }) {
this.api = api;
this.config = config;
this.settings = [
{
name: "required",
icon: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 480 512" class="w-3 h-3"><!-- Font Awesome Pro 5.15.4 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license (Commercial License) --><path d="M471.99 334.43L336.06 256l135.93-78.43c7.66-4.42 10.28-14.2 5.86-21.86l-32.02-55.43c-4.42-7.65-14.21-10.28-21.87-5.86l-135.93 78.43V16c0-8.84-7.17-16-16.01-16h-64.04c-8.84 0-16.01 7.16-16.01 16v156.86L56.04 94.43c-7.66-4.42-17.45-1.79-21.87 5.86L2.15 155.71c-4.42 7.65-1.8 17.44 5.86 21.86L143.94 256 8.01 334.43c-7.66 4.42-10.28 14.21-5.86 21.86l32.02 55.43c4.42 7.65 14.21 10.27 21.87 5.86l135.93-78.43V496c0 8.84 7.17 16 16.01 16h64.04c8.84 0 16.01-7.16 16.01-16V339.14l135.93 78.43c7.66 4.42 17.45 1.8 21.87-5.86l32.02-55.43c4.42-7.65 1.8-17.43-5.86-21.85z"/></svg>`,
},
];
this.data = {
label: data.label || "",
help: data.help || "",
placeholder: data.placeholder || "",
required: data.required || false,
};
this.nodes = {
holder: null,
};
}
renderSettings(): HTMLElement {
const wrapper = document.createElement("div");
this.settings.forEach((tune) => {
let button = document.createElement("div");
button.classList.add("cdx-settings-button");
button.classList.toggle("cdx-settings-button--active", this.data[tune.name]);
button.innerHTML = tune.icon;
wrapper.appendChild(button);
button.addEventListener("click", () => {
this._toggleTune(tune.name);
button.classList.toggle("cdx-settings-button--active");
});
});
return wrapper;
}
render(): HTMLElement {
const rootNode = document.createElement("div");
this.nodes.holder = rootNode;
const onDataChange = (newData: NumberQuestionData) => {
this.data = {
...newData,
};
};
ReactDOM.render(<NumberQuestionComponent onDataChange={onDataChange} data={this.data} />, rootNode);
return this.nodes.holder;
}
save() {
return this.data;
}
/**
* @private
* Click on the Settings Button
* @param {string} tune — tune name from this.settings
*/
_toggleTune(tune: string) {
if (tune === "required") {
this.data.required = !this.data.required;
}
}
}

View File

@@ -1,77 +0,0 @@
import { useState } from "react";
import type { NumberQuestionData } from "./NumberQuestion";
const DEFAULT_INITIAL_DATA = (): NumberQuestionData => {
return {
label: "",
placeholder: "",
help: "",
required: false,
};
};
type Props = {
data: NumberQuestionData;
onDataChange: (newData: NumberQuestionData) => void;
};
const NumberQuestionComponent = (props: Props) => {
const [data, setData] = useState(props.data ? props.data : DEFAULT_INITIAL_DATA);
const updateData = (newData: NumberQuestionData) => {
setData(newData);
if (props.onDataChange) {
props.onDataChange(newData);
}
};
const onInputChange = (fieldName: string) => {
return (e: React.FormEvent<HTMLInputElement>) => {
const newData = {
...data,
};
newData[fieldName] = e.currentTarget.value;
updateData(newData);
};
};
return (
<div className="pb-5">
<div className="text-md relative font-bold leading-7 text-gray-800 sm:truncate">
<input
type="text"
id="label"
defaultValue={data.label}
className="w-full border-0 border-transparent p-0 ring-0 placeholder:text-gray-300 focus:ring-0"
placeholder="Your Question"
onChange={onInputChange("label")}
/>
{data.required && (
<div className="pointer-events-none absolute inset-y-0 right-0 flex items-center pr-3 text-red-500">
*
</div>
)}
</div>
<input
type="text"
className="mt-1 block w-full max-w-sm rounded-md border-gray-300 text-sm text-gray-400 shadow-sm placeholder:text-gray-300"
placeholder="optional placeholder"
defaultValue={data.placeholder}
onChange={onInputChange("placeholder")}
/>
<input
type="text"
id="help-text"
defaultValue={data.help}
className="mt-2 block w-full max-w-sm border-0 border-transparent p-0 text-sm font-light text-gray-500 ring-0 placeholder:text-gray-300 focus:ring-0"
placeholder="optional help text"
onChange={onInputChange("help")}
/>
</div>
);
};
export default NumberQuestionComponent;

View File

@@ -1,59 +0,0 @@
import { API, BlockTool, BlockToolData, ToolConfig } from "@editorjs/editorjs";
import ReactDOM from "react-dom";
//styles imports in angular.json
interface PageTransitionData extends BlockToolData {
submitLabel: string;
}
export default class PageTransition implements BlockTool {
submitLabel: string;
placeholder: string;
api: API;
/* static get toolbox(): { icon: string; title?: string } {
return {
icon: `<svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"> <path stroke-linecap="round" stroke-linejoin="round" d="M12 4v16m8-8H4" /> </svg>`,
title: "New Page",
};
} */
constructor({ data, api }: { api: API; config?: ToolConfig; data?: PageTransitionData }) {
this.api = api;
this.submitLabel = data.submitLabel || "Submit";
}
save(block: HTMLDivElement) {
return {
submitLabel: (block.firstElementChild.firstElementChild.firstElementChild as HTMLElement).innerHTML,
};
}
render(): HTMLElement {
const container = document.createElement("div");
const toolView = (
<div className="relative mt-16 mb-8">
<div className="left absolute -top-14 inline-flex items-center rounded-md border border-transparent bg-gray-700 px-4 py-3 text-sm font-medium text-white shadow-sm hover:bg-gray-900 focus:outline-none focus:ring-2 focus:ring-gray-500 focus:ring-offset-2">
<div
contentEditable
id="label"
defaultValue={this.submitLabel}
className="border-transparent bg-transparent p-0 ring-0 placeholder:text-opacity-5 focus:border-transparent focus:outline-none focus:ring-0 active:ring-0">
{this.submitLabel}
</div>
{/* <ArrowRightIcon className="w-5 h-5 ml-2 -mr-1" aria-hidden="true" /> */}
</div>
<div className="relative my-4">
<div className="absolute inset-0 flex items-center" aria-hidden="true">
<div className="w-full border-t border-gray-300" />
</div>
<div className="relative flex justify-center">
<span className="bg-white px-2 text-sm text-gray-500">Next Page</span>
</div>
</div>
</div>
);
ReactDOM.render(toolView, container);
return container;
}
}

View File

@@ -1,101 +0,0 @@
import { API, BlockTool, BlockToolData, ToolConfig } from "@editorjs/editorjs";
import ReactDOM from "react-dom";
import PhoneQuestionComponent from "./PhoneQuestionComponent";
export interface PhoneQuestionData extends BlockToolData {
label: string;
help: string;
placeholder: string;
required: boolean;
}
export default class PhoneQuestion implements BlockTool {
settings: { name: string; icon: string }[];
api: API;
data: PhoneQuestionData;
nodes: { holder: HTMLElement };
config: ToolConfig;
static get toolbox(): { icon: string; title?: string } {
return {
icon: `<svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" viewBox="0 0 20 20" fill="currentColor">
<path d="M2 3a1 1 0 011-1h2.153a1 1 0 01.986.836l.74 4.435a1 1 0 01-.54 1.06l-1.548.773a11.037 11.037 0 006.105 6.105l.774-1.548a1 1 0 011.059-.54l4.435.74a1 1 0 01.836.986V17a1 1 0 01-1 1h-2C7.82 18 2 12.18 2 5V3z" />
</svg>`,
title: "Phone Question",
};
}
constructor({ api, config, data }: { api: API; config?: ToolConfig; data?: PhoneQuestionData }) {
this.api = api;
this.config = config;
this.settings = [
{
name: "required",
icon: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 480 512" class="w-3 h-3"><path d="M471.99 334.43L336.06 256l135.93-78.43c7.66-4.42 10.28-14.2 5.86-21.86l-32.02-55.43c-4.42-7.65-14.21-10.28-21.87-5.86l-135.93 78.43V16c0-8.84-7.17-16-16.01-16h-64.04c-8.84 0-16.01 7.16-16.01 16v156.86L56.04 94.43c-7.66-4.42-17.45-1.79-21.87 5.86L2.15 155.71c-4.42 7.65-1.8 17.44 5.86 21.86L143.94 256 8.01 334.43c-7.66 4.42-10.28 14.21-5.86 21.86l32.02 55.43c4.42 7.65 14.21 10.27 21.87 5.86l135.93-78.43V496c0 8.84 7.17 16 16.01 16h64.04c8.84 0 16.01-7.16 16.01-16V339.14l135.93 78.43c7.66 4.42 17.45 1.8 21.87-5.86l32.02-55.43c4.42-7.65 1.8-17.43-5.86-21.85z"/></svg>`,
},
];
this.data = {
label: data.label || "",
help: data.help || "",
placeholder: data.placeholder || "+1 (555) 987-6543",
required: data.required || false,
};
this.nodes = {
holder: null,
};
}
renderSettings(): HTMLElement {
const wrapper = document.createElement("div");
this.settings.forEach((tune) => {
let button = document.createElement("div");
button.classList.add("cdx-settings-button");
button.classList.toggle("cdx-settings-button--active", this.data[tune.name]);
button.innerHTML = tune.icon;
wrapper.appendChild(button);
button.addEventListener("click", () => {
this._toggleTune(tune.name);
button.classList.toggle("cdx-settings-button--active");
});
});
return wrapper;
}
/**
* @private
* Click on the Settings Button
* @param {string} tune — tune name from this.settings
*/
_toggleTune(tune: string) {
if (tune === "required") {
this.data.required = !this.data.required;
}
}
render(): HTMLElement {
const rootNode = document.createElement("div");
this.nodes.holder = rootNode;
const onDataChange = (newData: PhoneQuestionData) => {
this.data = {
...newData,
};
};
ReactDOM.render(<PhoneQuestionComponent onDataChange={onDataChange} data={this.data} />, rootNode);
return this.nodes.holder;
}
save() {
return this.data;
}
}

View File

@@ -1,84 +0,0 @@
/* eslint-disable react-hooks/exhaustive-deps */
import { PhoneIcon } from "@heroicons/react/24/outline";
import { default as React } from "react";
import { type PhoneQuestionData } from "./PhoneQuestion";
const DEFAULT_INITIAL_DATA = () => {
return {
label: "",
placeholder: "",
help: "",
required: false,
};
};
type Props = {
data: PhoneQuestionData;
onDataChange: (newData: PhoneQuestionData) => void;
};
const PhoneQuestionComponent = (props: Props) => {
const [data, setData] = React.useState(props.data ? props.data : DEFAULT_INITIAL_DATA);
const updateData = (newData: PhoneQuestionData) => {
setData(newData);
if (props.onDataChange) {
props.onDataChange(newData);
}
};
const onInputChange = (fieldName: string) => {
return (e: React.FormEvent<HTMLInputElement>) => {
const newData = {
...data,
};
newData[fieldName] = e.currentTarget.value;
updateData(newData);
};
};
return (
<div className="pb-5">
<div className="text-md relative font-bold leading-7 text-gray-800 sm:truncate">
<input
type="text"
id="label"
defaultValue={data.label}
className="w-full border-0 border-transparent p-0 ring-0 placeholder:text-gray-300 focus:ring-0"
placeholder="Your Question"
onChange={onInputChange("label")}
/>
{data.required && (
<div className="pointer-events-none absolute inset-y-0 right-0 flex items-center pr-3 text-red-500">
*
</div>
)}
</div>
<div className="relative mt-1 max-w-sm rounded-md shadow-sm">
<div className="pointer-events-none absolute inset-y-0 left-0 flex items-center pl-3">
<PhoneIcon className="h-5 w-5 text-gray-400" aria-hidden="true" />
</div>
<input
type="text"
name="website"
className="block w-full rounded-md border-gray-300 pl-10 text-gray-300 sm:text-sm"
defaultValue={data.placeholder}
onChange={onInputChange("placeholder")}
/>
</div>
<input
type="text"
id="help-text"
defaultValue={data.help}
className="mt-2 block w-full max-w-sm border-0 border-transparent p-0 text-sm font-light text-gray-500 ring-0 placeholder:text-gray-300 focus:ring-0"
placeholder="optional help text"
onChange={onInputChange("help")}
/>
</div>
);
};
export default PhoneQuestionComponent;

View File

@@ -1,100 +0,0 @@
import { API, BlockTool, BlockToolData, ToolConfig } from "@editorjs/editorjs";
import ReactDOM from "react-dom";
import TextQuestionComponent from "./TextQuestionComponent";
export interface TextQuestionData extends BlockToolData {
label: string;
help: string;
placeholder: string;
required: boolean;
}
export default class TextQuestion implements BlockTool {
settings: { name: string; icon: string }[];
api: API;
data: TextQuestionData;
nodes: { holder: HTMLElement };
config: ToolConfig;
static get toolbox(): { icon: string; title?: string } {
return {
icon: `<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="w-6 h-6"> <path stroke-linecap="round" stroke-linejoin="round" d="M3.75 9h16.5m-16.5 6.75h16.5" /> </svg>`,
title: "Text Question",
};
}
constructor({ api, config, data }: { api: API; config?: ToolConfig; data?: TextQuestionData }) {
this.api = api;
this.config = config;
this.settings = [
{
name: "required",
icon: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 480 512" class="w-3 h-3"><path d="M471.99 334.43L336.06 256l135.93-78.43c7.66-4.42 10.28-14.2 5.86-21.86l-32.02-55.43c-4.42-7.65-14.21-10.28-21.87-5.86l-135.93 78.43V16c0-8.84-7.17-16-16.01-16h-64.04c-8.84 0-16.01 7.16-16.01 16v156.86L56.04 94.43c-7.66-4.42-17.45-1.79-21.87 5.86L2.15 155.71c-4.42 7.65-1.8 17.44 5.86 21.86L143.94 256 8.01 334.43c-7.66 4.42-10.28 14.21-5.86 21.86l32.02 55.43c4.42 7.65 14.21 10.27 21.87 5.86l135.93-78.43V496c0 8.84 7.17 16 16.01 16h64.04c8.84 0 16.01-7.16 16.01-16V339.14l135.93 78.43c7.66 4.42 17.45 1.8 21.87-5.86l32.02-55.43c4.42-7.65 1.8-17.43-5.86-21.85z"/></svg>`,
},
];
this.data = {
label: data.label || "",
help: data.help || "",
placeholder: data.placeholder || "",
required: data.required || false,
};
this.nodes = {
holder: null,
};
}
renderSettings(): HTMLElement {
const wrapper = document.createElement("div");
this.settings.forEach((tune) => {
let button = document.createElement("div");
button.classList.add("cdx-settings-button");
button.classList.toggle("cdx-settings-button--active", this.data[tune.name]);
button.innerHTML = tune.icon;
wrapper.appendChild(button);
button.addEventListener("click", () => {
this._toggleTune(tune.name);
button.classList.toggle("cdx-settings-button--active");
});
});
return wrapper;
}
render(): HTMLElement {
const rootNode = document.createElement("div");
this.nodes.holder = rootNode;
const onDataChange = (newData: TextQuestionData) => {
this.data = {
...newData,
};
};
ReactDOM.render(<TextQuestionComponent onDataChange={onDataChange} data={this.data} />, rootNode);
return this.nodes.holder;
}
save() {
return this.data;
}
/**
* @private
* Click on the Settings Button
* @param {string} tune — tune name from this.settings
*/
_toggleTune(tune) {
if (tune === "required") {
this.data.required = !this.data.required;
}
}
}

View File

@@ -1,79 +0,0 @@
/* eslint-disable react-hooks/exhaustive-deps */
import { default as React } from "react";
import { type TextQuestionData } from "./TextQuestion";
const DEFAULT_INITIAL_DATA = () => {
return {
label: "",
placeholder: "",
help: "",
required: false,
};
};
type Props = {
data: TextQuestionData;
onDataChange: (newData: TextQuestionData) => void;
};
const TextQuestionComponent = (props: Props) => {
const [data, setData] = React.useState(props.data ? props.data : DEFAULT_INITIAL_DATA);
const updateData = (newData: TextQuestionData) => {
setData(newData);
if (props.onDataChange) {
props.onDataChange(newData);
}
};
const onInputChange = (fieldName: string) => {
return (e: React.FormEvent<HTMLInputElement>) => {
const newData = {
...data,
};
newData[fieldName] = e.currentTarget.value;
updateData(newData);
};
};
return (
<div className="pb-5">
<div className="text-md relative font-bold leading-7 text-gray-800 sm:truncate">
<input
type="text"
id="label"
defaultValue={data.label}
className="w-full border-0 border-transparent p-0 ring-0 placeholder:text-gray-300 focus:ring-0"
placeholder="Your Question"
onChange={onInputChange("label")}
/>
{data.required && (
<div className="pointer-events-none absolute inset-y-0 right-0 flex items-center pr-3 text-red-500">
*
</div>
)}
</div>
<input
type="text"
className="mt-1 block w-full max-w-sm rounded-md border-gray-300 text-sm text-gray-400 shadow-sm placeholder:text-gray-300"
placeholder="optional placeholder"
defaultValue={data.placeholder}
onChange={onInputChange("placeholder")}
/>
<input
type="text"
id="help-text"
defaultValue={data.help}
className="mt-2 block w-full max-w-sm border-0 border-transparent p-0 text-sm font-light text-gray-500 ring-0 placeholder:text-gray-300 focus:ring-0"
placeholder="optional help text"
onChange={onInputChange("help")}
/>
</div>
);
};
export default TextQuestionComponent;

View File

@@ -1,118 +0,0 @@
import { API, BlockTool, BlockToolData, ToolConfig } from "@editorjs/editorjs";
import ReactDOM from "react-dom";
//styles imports in angular.json
interface TextareaQuestionData extends BlockToolData {
label: string;
help: string;
placeholder: string;
required: boolean;
}
export default class TextareaQuestion implements BlockTool {
settings: { name: string; icon: string }[];
api: API;
data: any;
wrapper: undefined | HTMLElement;
static get toolbox(): { icon: string; title?: string } {
return {
icon: `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-align-justify"><line x1="21" y1="10" x2="3" y2="10"></line><line x1="21" y1="6" x2="3" y2="6"></line><line x1="21" y1="14" x2="3" y2="14"></line><line x1="21" y1="18" x2="3" y2="18"></line></svg>`,
title: "Long Text Question",
};
}
constructor({ data }: { api: API; config?: ToolConfig; data?: TextareaQuestionData }) {
this.wrapper = undefined;
this.settings = [
{
name: "required",
icon: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 480 512" class="w-3 h-3"><!-- Font Awesome Pro 5.15.4 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license (Commercial License) --><path d="M471.99 334.43L336.06 256l135.93-78.43c7.66-4.42 10.28-14.2 5.86-21.86l-32.02-55.43c-4.42-7.65-14.21-10.28-21.87-5.86l-135.93 78.43V16c0-8.84-7.17-16-16.01-16h-64.04c-8.84 0-16.01 7.16-16.01 16v156.86L56.04 94.43c-7.66-4.42-17.45-1.79-21.87 5.86L2.15 155.71c-4.42 7.65-1.8 17.44 5.86 21.86L143.94 256 8.01 334.43c-7.66 4.42-10.28 14.21-5.86 21.86l32.02 55.43c4.42 7.65 14.21 10.27 21.87 5.86l135.93-78.43V496c0 8.84 7.17 16 16.01 16h64.04c8.84 0 16.01-7.16 16.01-16V339.14l135.93 78.43c7.66 4.42 17.45 1.8 21.87-5.86l32.02-55.43c4.42-7.65 1.8-17.43-5.86-21.85z"/></svg>`,
},
];
this.data = {
label: data.label || "",
help: data.help || "",
placeholder: data.placeholder || "",
required: data.required !== undefined ? data.required : true,
};
}
save(block: HTMLDivElement) {
return {
...this.data,
label: (block.firstElementChild.firstElementChild.firstElementChild as HTMLInputElement).value,
placeholder: (block.firstElementChild.childNodes[1] as HTMLInputElement).value,
help: (block.firstElementChild.lastElementChild as HTMLInputElement).value,
};
}
renderSettings(): HTMLElement {
const wrapper = document.createElement("div");
this.settings.forEach((tune) => {
let button = document.createElement("div");
button.classList.add("cdx-settings-button");
button.classList.toggle("cdx-settings-button--active", this.data[tune.name]);
button.innerHTML = tune.icon;
wrapper.appendChild(button);
button.addEventListener("click", () => {
this._toggleTune(tune.name);
button.classList.toggle("cdx-settings-button--active");
});
});
return wrapper;
}
/**
* @private
* Click on the Settings Button
* @param {string} tune — tune name from this.settings
*/
_toggleTune(tune) {
this.wrapper.classList.toggle(tune.name, !!this.data[tune.name]);
if (tune === "required") {
this.data.required = !this.data.required;
this.wrapper.childNodes[0].childNodes[0].childNodes[1].textContent = this.data.required ? "*" : "";
}
}
render(): HTMLElement {
this.wrapper = document.createElement("div");
const toolView = (
<div className="pb-5">
<div className="text-md relative font-bold leading-7 text-gray-800 sm:truncate">
<input
type="text"
id="label"
defaultValue={this.data.label}
className="w-full border-0 border-transparent p-0 ring-0 placeholder:text-gray-300 focus:ring-0"
placeholder="Your Question"
/>
<div className="pointer-events-none absolute inset-y-0 right-0 flex items-center pr-3 text-red-500">
*
</div>
</div>
<textarea
rows={4}
className="mt-1 block w-full max-w-sm rounded-md border-gray-300 text-sm text-gray-400 shadow-sm placeholder:text-gray-300"
placeholder="optional placeholder"
defaultValue={this.data.placeholder}
/>
<input
type="text"
id="help-text"
defaultValue={this.data.help}
className="mt-2 block w-full max-w-sm border-0 border-transparent p-0 text-sm font-light text-gray-500 ring-0 placeholder:text-gray-300 focus:ring-0"
placeholder="optional help text"
/>
</div>
);
ReactDOM.render(toolView, this.wrapper);
return this.wrapper;
}
}

View File

@@ -1,100 +0,0 @@
import { API, BlockTool, BlockToolData, ToolConfig } from "@editorjs/editorjs";
import ReactDOM from "react-dom";
import WebsiteQuestionComponent from "./WebsiteQuestionComponent";
export interface WebsiteQuestionData extends BlockToolData {
label: string;
help: string;
placeholder: string;
required: boolean;
}
export default class WebsiteQuestion implements BlockTool {
settings: { name: string; icon: string }[];
api: API;
data: WebsiteQuestionData;
nodes: { holder: HTMLElement };
config: ToolConfig;
static get toolbox(): { icon: string; title?: string } {
return {
icon: `<svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" viewBox="0 0 20 20" fill="currentColor">
<path fill-rule="evenodd" d="M4.083 9h1.946c.089-1.546.383-2.97.837-4.118A6.004 6.004 0 004.083 9zM10 2a8 8 0 100 16 8 8 0 000-16zm0 2c-.076 0-.232.032-.465.262-.238.234-.497.623-.737 1.182-.389.907-.673 2.142-.766 3.556h3.936c-.093-1.414-.377-2.649-.766-3.556-.24-.56-.5-.948-.737-1.182C10.232 4.032 10.076 4 10 4zm3.971 5c-.089-1.546-.383-2.97-.837-4.118A6.004 6.004 0 0115.917 9h-1.946zm-2.003 2H8.032c.093 1.414.377 2.649.766 3.556.24.56.5.948.737 1.182.233.23.389.262.465.262.076 0 .232-.032.465-.262.238-.234.498-.623.737-1.182.389-.907.673-2.142.766-3.556zm1.166 4.118c.454-1.147.748-2.572.837-4.118h1.946a6.004 6.004 0 01-2.783 4.118zm-6.268 0C6.412 13.97 6.118 12.546 6.03 11H4.083a6.004 6.004 0 002.783 4.118z" clip-rule="evenodd" />
</svg>`,
title: "Website Question",
};
}
constructor({ api, config, data }: { api: API; config?: ToolConfig; data?: WebsiteQuestionData }) {
this.api = api;
this.config = config;
this.settings = [
{
name: "required",
icon: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 480 512" class="w-3 h-3"><path d="M471.99 334.43L336.06 256l135.93-78.43c7.66-4.42 10.28-14.2 5.86-21.86l-32.02-55.43c-4.42-7.65-14.21-10.28-21.87-5.86l-135.93 78.43V16c0-8.84-7.17-16-16.01-16h-64.04c-8.84 0-16.01 7.16-16.01 16v156.86L56.04 94.43c-7.66-4.42-17.45-1.79-21.87 5.86L2.15 155.71c-4.42 7.65-1.8 17.44 5.86 21.86L143.94 256 8.01 334.43c-7.66 4.42-10.28 14.21-5.86 21.86l32.02 55.43c4.42 7.65 14.21 10.27 21.87 5.86l135.93-78.43V496c0 8.84 7.17 16 16.01 16h64.04c8.84 0 16.01-7.16 16.01-16V339.14l135.93 78.43c7.66 4.42 17.45 1.8 21.87-5.86l32.02-55.43c4.42-7.65 1.8-17.43-5.86-21.85z"/></svg>`,
},
];
this.data = {
label: data.label || "",
help: data.help || "",
placeholder: data.placeholder || "https://",
required: data.required || false,
};
this.nodes = {
holder: null,
};
}
renderSettings(): HTMLElement {
const wrapper = document.createElement("div");
this.settings.forEach((tune) => {
let button = document.createElement("div");
button.classList.add("cdx-settings-button");
button.classList.toggle("cdx-settings-button--active", this.data[tune.name]);
button.innerHTML = tune.icon;
wrapper.appendChild(button);
button.addEventListener("click", () => {
this._toggleTune(tune.name);
button.classList.toggle("cdx-settings-button--active");
});
});
return wrapper;
}
/**
* @private
* Click on the Settings Button
* @param {string} tune — tune name from this.settings
*/
_toggleTune(tune: string) {
if (tune === "required") {
this.data.required = !this.data.required;
}
}
render(): HTMLElement {
const rootNode = document.createElement("div");
this.nodes.holder = rootNode;
const onDataChange = (newData: WebsiteQuestionData) => {
this.data = {
...newData,
};
};
ReactDOM.render(<WebsiteQuestionComponent onDataChange={onDataChange} data={this.data} />, rootNode);
return this.nodes.holder;
}
save() {
return this.data;
}
}

View File

@@ -1,83 +0,0 @@
import { GlobeAltIcon } from "@heroicons/react/24/outline";
import { useState } from "react";
import { WebsiteQuestionData } from "./WebsiteQuestion";
const DEFAULT_INITIAL_DATA = (): WebsiteQuestionData => {
return {
label: "",
placeholder: "https://",
help: "",
required: false,
};
};
type Props = {
data: WebsiteQuestionData;
onDataChange: (newData: WebsiteQuestionData) => void;
};
const WebsiteQuestionComponent = (props: Props) => {
const [data, setData] = useState(props.data ? props.data : DEFAULT_INITIAL_DATA);
const updateData = (newData: WebsiteQuestionData) => {
setData(newData);
if (props.onDataChange) {
props.onDataChange(newData);
}
};
const onInputChange = (fieldName: string) => {
return (e: React.FormEvent<HTMLInputElement>) => {
const newData = {
...data,
};
newData[fieldName] = e.currentTarget.value;
updateData(newData);
};
};
return (
<div className="pb-5">
<div className="text-md relative font-bold leading-7 text-gray-800 sm:truncate">
<input
type="text"
id="label"
defaultValue={data.label}
className="w-full border-0 border-transparent p-0 ring-0 placeholder:text-gray-300 focus:ring-0"
placeholder="Your Question"
onChange={onInputChange("label")}
/>
{data.required && (
<div className="pointer-events-none absolute inset-y-0 right-0 flex items-center pr-3 text-red-500">
*
</div>
)}
</div>
<div className="relative mt-1 max-w-sm rounded-md shadow-sm">
<div className="pointer-events-none absolute inset-y-0 left-0 flex items-center pl-3">
<GlobeAltIcon className="h-5 w-5 text-gray-400" aria-hidden="true" />
</div>
<input
type="text"
name="website"
className="block w-full rounded-md border-gray-300 pl-10 text-gray-300 sm:text-sm"
defaultValue={data.placeholder}
onChange={onInputChange("placeholder")}
/>
</div>
<input
type="text"
id="help-text"
defaultValue={data.help}
className="mt-2 block w-full max-w-sm border-0 border-transparent p-0 text-sm font-light text-gray-500 ring-0 placeholder:text-gray-300 focus:ring-0"
placeholder="optional help text"
onChange={onInputChange("help")}
/>
</div>
);
};
export default WebsiteQuestionComponent;

View File

@@ -1,173 +0,0 @@
import { DocumentMagnifyingGlassIcon } from "@heroicons/react/24/outline";
import Link from "next/link";
import { FaReact, FaVuejs } from "react-icons/fa";
import { toast } from "react-toastify";
import { classNames } from "../../lib/utils";
import StandardButton from "../StandardButton";
export default function FormCode({ formId }) {
const libs = [
{
id: "react",
name: "React",
href: `/forms/${formId}/form/react`,
bgColor: "bg-blue",
version: "v0.1",
icon: FaReact,
},
{
id: "reactNative",
name: "React Native",
comingSoon: true,
href: "#",
bgColor: "bg-ui-gray-light",
icon: FaReact,
},
{
id: "vue",
name: "Vue.js",
comingSoon: true,
href: "#",
bgColor: "bg-ui-gray-light",
icon: FaVuejs,
},
{
id: "docs",
name: "Docs",
href: "https://docs.snoopforms.com",
bgColor: "bg-ui-gray-dark",
icon: DocumentMagnifyingGlassIcon,
target: "_blank",
},
];
return (
<>
<div className="mx-auto mt-8">
<h1 className="text-ui-gray-dark text-3xl font-bold leading-tight">Connect your form</h1>
</div>
<div className="mt-4 mb-12">
<p className="text-ui-gray-dark">
To send all form submissions to this dashboard, update the form ID in the{" "}
<code>{"<snoopForm>"}</code> component.
</p>
</div>
<div className="grid grid-cols-2 gap-10">
<div>
<label htmlFor="formId" className="text-ui-gray-dark block text-base">
Your form ID
</label>
<div className="mt-3">
<input
id="formId"
type="text"
className="text-md mb-3 w-full rounded-sm border-gray-300 shadow-sm disabled:bg-gray-100"
value={formId}
disabled
/>
<StandardButton
onClick={() => {
navigator.clipboard.writeText(formId);
toast("Copied form ID to clipboard");
}}
fullwidth>
copy
</StandardButton>
</div>
</div>
<div className="rounded-md bg-black p-8 font-light text-gray-200">
<p>
<code>
{"<"}
<span className="text-yellow-200">SnoopForm</span>
{""}
</code>
</p>
<p>
<code>{`domain="${window?.location.host}"`}</code>
</p>
<p>
<code>{`protocol="${window?.location.protocol.replace(":", "")}"`}</code>
</p>
<p>
<code>{`formId="${formId}"`}</code>
</p>
<p>
<code>{">"}</code>
</p>
<p>
<code>
<span className="text-gray-600">{`{...}`}</span>
</code>
</p>
<code>
{"</"}
<span className="text-yellow-200">SnoopForm</span>
{">"}
</code>
</div>
</div>
<div className="mt-16">
<h2 className="text-ui-gray-dark text-xl font-bold">Code your form</h2>
<div className="mt-4 mb-12">
<p className="text-ui-gray-dark">
Build your form with the code library of your choice. Manage your data in this dashboard.
</p>
</div>
<ul role="list" className="mt-3 grid grid-cols-1 gap-5 sm:grid-cols-2 sm:gap-6">
{libs.map((lib) => (
<Link
key={lib.id}
href={lib.href}
className="col-span-1 flex rounded-md shadow-sm"
target={lib.target || ""}
rel="noreferrer">
<li
className={classNames(
lib.comingSoon ? "text-ui-gray-medium" : "text-ui-gray-dark shadow-sm hover:text-black",
"col-span-1 flex w-full rounded-md"
)}>
<div
className={classNames(
lib.bgColor,
"flex w-20 flex-shrink-0 items-center justify-center rounded-l-md text-sm font-medium text-white"
)}>
<lib.icon
className={classNames(
lib.comingSoon ? "text-ui-gray-medium" : "stroke-1 text-white",
"h-10 w-10"
)}
/>
</div>
<div
className={classNames(
lib.comingSoon ? "border-dashed" : "",
"flex flex-1 items-center justify-between truncate rounded-r-md bg-white"
)}>
<div className="inline-flex truncate px-4 py-6 text-lg">
<p className="font-light">{lib.name}</p>
{lib.comingSoon && (
<div className="ml-3 rounded bg-green-100 p-1 px-3">
<p className="text-xs text-black">coming soon</p>
</div>
)}
</div>
</div>
</li>
</Link>
))}
</ul>
<div className="text-ui-gray-medium my-12 text-center font-light">
<p>
Your form is running? Go to{" "}
<Link href={`/forms/${formId}/preview`} className="text-red underline">
Pipelines
</Link>
</p>
</div>
</div>
</>
);
}

View File

@@ -1,178 +0,0 @@
/* This example requires Tailwind CSS v2.0+ */
import { Dialog, RadioGroup, Transition } from "@headlessui/react";
import { CheckCircleIcon, XMarkIcon } from "@heroicons/react/24/solid";
import { useRouter } from "next/router";
import { Fragment, useState } from "react";
import { BsPlus } from "react-icons/bs";
import { createForm } from "../../lib/forms";
import { createNoCodeForm } from "../../lib/noCodeForm";
import { classNames } from "../../lib/utils";
import StandardButton from "../StandardButton";
const formTypes = [
{
id: "NOCODE",
title: "No-Code Builder",
description: "Use the Notion-like builder to build your form without a single line of code.",
},
{
id: "CODE",
title: "Code",
description: "Use the snoopReact library to code the form yourself and manage the data here.",
additionalDescription: "",
},
];
type FormOnboardingModalProps = {
open: boolean;
setOpen: (v: boolean) => void;
};
export default function NewFormModal({ open, setOpen }: FormOnboardingModalProps) {
const router = useRouter();
const [name, setName] = useState("");
const [formType, setFormType] = useState(formTypes[0]);
const createFormAction = async (e) => {
e.preventDefault();
const form = await createForm({
name,
formType: formType.id,
});
if (form.formType === "NOCODE") {
await createNoCodeForm(form.id);
}
router.push(`/forms/${form.id}/form`);
};
return (
<Transition.Root show={open} as={Fragment}>
<Dialog as="div" className="relative z-10" onClose={setOpen}>
<Transition.Child
as={Fragment}
enter="ease-out duration-300"
enterFrom="opacity-0"
enterTo="opacity-100"
leave="ease-in duration-200"
leaveFrom="opacity-100"
leaveTo="opacity-0">
<div className="fixed inset-0 bg-gray-500 bg-opacity-30 backdrop-blur-md transition-opacity" />
</Transition.Child>
<div className="fixed inset-0 z-10 overflow-y-auto">
<div className="flex min-h-full items-end justify-center p-4 text-center sm:items-center sm:p-0">
<Transition.Child
as={Fragment}
enter="ease-out duration-300"
enterFrom="opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95"
enterTo="opacity-100 translate-y-0 sm:scale-100"
leave="ease-in duration-200"
leaveFrom="opacity-100 translate-y-0 sm:scale-100"
leaveTo="opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95">
<Dialog.Panel className="relative transform rounded-lg bg-white px-4 pt-5 pb-4 text-left shadow-xl transition-all sm:my-8 sm:w-full sm:max-w-lg sm:p-6">
<div className="absolute top-0 right-0 hidden pt-4 pr-4 sm:block">
<button
type="button"
className="rounded-md bg-white text-gray-400 hover:text-gray-500 focus:outline-none focus:ring-0 focus:ring-offset-2"
onClick={() => setOpen(false)}>
<span className="sr-only">Close</span>
<XMarkIcon className="h-6 w-6" aria-hidden="true" />
</button>
</div>
<div className="flex flex-row justify-between">
<h2 className="text-ui-gray-dark flex-none p-2 text-xl font-bold">Create new form</h2>
</div>
<form
onSubmit={(e) => createFormAction(e)}
className="inline-block w-full transform overflow-hidden p-2 text-left align-bottom transition-all sm:align-middle">
<div>
<label htmlFor="email" className="text-ui-gray-dark text-sm font-light">
Name your form
</label>
<div className="mt-2">
<input
type="text"
name="name"
className="bg-ui-gray-light focus:ring-red placeholder:text-ui-gray-medium mb-6 block w-full rounded border-none p-2 placeholder:font-extralight focus:ring-2 sm:text-sm"
placeholder="e.g. Customer Research Survey"
value={name}
onChange={(e) => setName(e.target.value)}
autoFocus
required
/>
</div>
</div>
<RadioGroup value={formType} onChange={setFormType}>
<RadioGroup.Label className="text-ui-gray-dark text-sm font-light">
How do you build your form?
</RadioGroup.Label>
<div className="mt-4 grid grid-cols-1 gap-y-6 sm:grid-cols-2 sm:gap-x-4">
{formTypes.map((formType) => (
<RadioGroup.Option
key={formType.id}
value={formType}
className={({ checked, active }) =>
classNames(
checked ? "border-transparent" : "",
active ? "border-red ring-red ring-2" : "bg-ui-gray-lighter",
"relative flex cursor-pointer rounded border bg-white p-4 shadow-sm focus:outline-none"
)
}>
{({ checked, active }) => (
<>
<span className="flex flex-1">
<span className="flex flex-col">
<RadioGroup.Label
as="span"
className="text-md text-ui-gray-dark block font-bold">
{formType.title}
</RadioGroup.Label>
<RadioGroup.Description
as="span"
className="text-ui-gray-dark mt-1 flex items-center whitespace-pre-wrap text-xs">
{formType.description}
</RadioGroup.Description>
</span>
</span>
<CheckCircleIcon
className={classNames(!checked ? "hidden" : "", "text-red h-5 w-5")}
aria-hidden="true"
/>
<div
className={classNames(
checked ? "hidden" : "",
"border-ui-gray-light h-4 w-4 rounded-full border-2"
)}
aria-hidden="true"
/>
<span
className={classNames(
active ? "border" : "border-2",
checked ? "border-red" : "border-transparent",
"pointer-events-none absolute -inset-px rounded"
)}
aria-hidden="true"
/>
</>
)}
</RadioGroup.Option>
))}
</div>
</RadioGroup>
<div className="mt-5 sm:mt-6">
<StandardButton fullwidth type="submit">
create form
<BsPlus className="ml-1 h-6 w-6"></BsPlus>
</StandardButton>
</div>
</form>
</Dialog.Panel>
</Transition.Child>
</div>
</div>
</Dialog>
</Transition.Root>
);
}

View File

@@ -1,184 +0,0 @@
import { GlobeAltIcon, EnvelopeIcon, PhoneIcon } from "@heroicons/react/24/solid";
import sanitizeHtml from "sanitize-html";
import { SnoopElement, SnoopForm, SnoopPage } from "@snoopforms/react";
import { useMemo } from "react";
import { generateId } from "../../lib/utils";
import Loading from "../Loading";
export default function App({ id = "", formId, blocks, localOnly = false }) {
const pages = useMemo(() => {
const pages = [];
let currentPage = {
id: formId, // give the first page the formId as id by default
blocks: [],
};
for (const block of blocks) {
if (block.type !== "pageTransition") {
currentPage.blocks.push(block);
} else {
currentPage.blocks.push({
id: generateId(10),
data: {
label: block.data.submitLabel,
},
type: "submitButton",
});
pages.push(currentPage);
currentPage = {
id: block.id,
blocks: [],
};
}
}
pages.push(currentPage);
return pages;
}, [blocks, formId]);
if (!pages) return <Loading />;
return (
<div className="w-full px-5 py-5">
<SnoopForm
key={id} // used to reset form
domain={window.location.host}
protocol={window.location.protocol === "http:" ? "http" : "https"}
formId={formId}
localOnly={localOnly}
className="mx-auto w-full max-w-3xl space-y-6">
{pages.map((page, pageIdx) => (
<SnoopPage key={page.id} name={page.id} thankyou={pageIdx === pages.length - 1}>
{page.blocks.map((block) => (
<div key={block.id}>
{block.type === "paragraph" ? (
<div
className="ce-paragraph"
dangerouslySetInnerHTML={{
__html: sanitizeHtml(block.data.text),
}}></div>
) : block.type === "header" ? (
block.data.level === 1 ? (
<h1 className="ce-header">{block.data.text}</h1>
) : block.level === 2 ? (
<h2 className="ce-header">{block.data.text}</h2>
) : block.data.level === 3 ? (
<h3 className="ce-header">{block.data.text}</h3>
) : null
) : block.type === "textQuestion" ? (
<SnoopElement
type="text"
name={block.id}
label={block.data.label}
help={block.data.help}
placeholder={block.data.placeholder}
classNames={{
label: "mt-4 mb-2 block text-lg font-bold leading-7 text-gray-800 sm:truncate",
}}
required={block.data.required}
/>
) : block.type === "textareaQuestion" ? (
<SnoopElement
type="textarea"
rows={4}
name={block.id}
label={block.data.label}
help={block.data.help}
placeholder={block.data.placeholder}
classNames={{
label: "mt-4 mb-2 block text-lg font-bold leading-7 text-gray-800 sm:truncate",
}}
required={block.data.required}
/>
) : block.type === "emailQuestion" ? (
<SnoopElement
type="email"
name={block.id}
label={block.data.label}
help={block.data.help}
placeholder={block.data.placeholder}
icon={<EnvelopeIcon className="h-5 w-5" />}
classNames={{
label: "mt-4 mb-2 block text-lg font-bold leading-7 text-gray-800 sm:truncate",
}}
required={block.data.required}
/>
) : block.type === "multipleChoiceQuestion" && block.data.multipleChoice ? (
<SnoopElement
type="checkbox"
name={block.id}
label={block.data.label}
help={block.data.help}
options={block.data.options.map((o) => o.label)}
classNames={{
label: "mt-4 mb-2 block text-lg font-bold leading-7 text-gray-800 sm:truncate",
}}
required={block.data.required}
/>
) : block.type === "multipleChoiceQuestion" && !block.data.multipleChoice ? (
<SnoopElement
type="radio"
name={block.id}
label={block.data.label}
help={block.data.help}
options={block.data.options.map((o) => o.label)}
classNames={{
label: "mt-4 mb-2 block text-lg font-bold leading-7 text-gray-800 sm:truncate",
}}
required={block.data.required}
/>
) : block.type === "numberQuestion" ? (
<SnoopElement
type="number"
name={block.id}
label={block.data.label}
help={block.data.help}
placeholder={block.data.placeholder}
classNames={{
label: "mt-4 mb-2 block text-lg font-bold leading-7 text-gray-800 sm:truncate",
}}
required={block.data.required}
/>
) : block.type === "phoneQuestion" ? (
<SnoopElement
type="phone"
name={block.id}
label={block.data.label}
help={block.data.help}
placeholder={block.data.placeholder}
icon={<PhoneIcon className="h-5 w-5" />}
classNames={{
label: "mt-4 mb-2 block text-lg font-bold leading-7 text-gray-800 sm:truncate",
}}
required={block.data.required}
/>
) : block.type === "submitButton" ? (
<SnoopElement
name="submit"
type="submit"
label={block.data.label}
classNames={{
button:
"inline-flex items-center px-4 py-3 text-sm font-medium text-white bg-gray-700 border border-transparent rounded-md shadow-sm hover:bg-gray-900 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-500",
}}
/>
) : block.type === "websiteQuestion" ? (
<SnoopElement
type="website"
name={block.id}
label={block.data.label}
help={block.data.help}
placeholder={block.data.placeholder}
icon={<GlobeAltIcon className="h-5 w-5" />}
classNames={{
label: "mt-4 mb-2 block text-lg font-bold leading-7 text-gray-800 sm:truncate",
}}
required={block.data.required}
/>
) : null}
</div>
))}
</SnoopPage>
))}
</SnoopForm>
</div>
);
}

View File

@@ -1,63 +0,0 @@
import Head from "next/head";
import { classNames } from "../../lib/utils";
import MenuBreadcrumbs from "./MenuBreadcrumbs";
import MenuProfile from "./MenuProfile";
import MenuSteps from "./MenuSteps";
import NewFormNavButton from "./NewFormNavButton";
interface BaseLayoutManagementProps {
title: string;
breadcrumbs: any;
steps?: any;
currentStep?: string;
children: React.ReactNode;
bgClass?: string;
limitHeightScreen?: boolean;
}
export default function BaseLayoutManagement({
title,
breadcrumbs,
steps,
currentStep,
children,
bgClass = "bg-ui-gray-lighter",
limitHeightScreen = false,
}: BaseLayoutManagementProps) {
return (
<>
<Head>
<title>{title}</title>
</Head>
<div
className={classNames(
bgClass,
limitHeightScreen ? "h-screen max-h-screen overflow-hidden" : "min-h-screen",
"flex h-full"
)}>
<div
className={classNames(limitHeightScreen ? "max-h-full" : "h-full", "flex w-full flex-1 flex-col")}>
<header className="w-full">
<div className="border-ui-gray-light relative z-10 flex h-16 flex-shrink-0 border-b bg-white shadow-sm">
<div className="grid w-full grid-cols-2 sm:grid-cols-3">
<div className="hidden flex-1 space-x-8 sm:flex">
<NewFormNavButton />
<MenuBreadcrumbs breadcrumbs={breadcrumbs} />
</div>
<div className="flex flex-1">
{steps && <MenuSteps steps={steps} currentStep={currentStep} />}
</div>
<div className="flex flex-1 items-center justify-end space-x-2 text-right sm:space-x-4">
<div className="mr-6">
<MenuProfile />
</div>
</div>
</div>
</div>
</header>
{children}
</div>
</div>
</>
);
}

View File

@@ -1,12 +0,0 @@
import Head from "next/head";
export default function BaseLayoutUnauthorized({ title, children }) {
return (
<>
<Head>
<title>{title}</title>
</Head>
{children}
</>
);
}

View File

@@ -1,40 +0,0 @@
import React from "react";
import StandardButton from "../StandardButton";
interface Props {
children: React.ReactNode;
onClick?: () => void;
alertText: string;
hintText: string;
buttonText?: string;
borderStyles?: string;
hasButton?: boolean;
}
const EmptyPageFiller: React.FC<Props> = ({
children,
onClick = () => {},
alertText,
hintText,
buttonText,
borderStyles,
hasButton = false,
}) => {
return (
<div
className={
`border-ui-gray-light mx-auto mt-8 rounded-lg border bg-white p-8 text-center ` + borderStyles
}>
{children}
<h3 className="text-ui-gray-medium mt-5 text-base font-bold">{alertText}</h3>
<p className="text-ui-gray-medium mt-1 text-xs font-light">{hintText}</p>
{hasButton && (
<div className="mt-6">
<StandardButton onClick={onClick}>{buttonText}</StandardButton>
</div>
)}
</div>
);
};
export default EmptyPageFiller;

View File

@@ -1,9 +0,0 @@
interface Props {
children?: React.ReactNode;
}
const FullWidth: React.FC<Props> = ({ children }) => {
return <main className="h-full w-full">{children}</main>;
};
export default FullWidth;

View File

@@ -1,55 +0,0 @@
import Head from "next/head";
import Link from "next/link";
import { ArrowLeftIcon, ArrowPathIcon } from "@heroicons/react/24/outline";
import { useSession, signIn } from "next-auth/react";
import Loading from "../Loading";
export default function LayoutShare({ formId, resetApp, children }) {
const { data: session, status } = useSession();
if (status === "loading") {
return <Loading />;
}
if (!session) {
signIn();
return <div>You need to be authenticated to view this page.</div>;
}
return (
<>
<Head>
<title>Form Preview</title>
</Head>
<div className="flex min-h-screen overflow-hidden bg-gray-50">
<div className="flex flex-1 flex-col overflow-hidden">
<header className="w-full">
<div className="border-ui-gray-light relative z-10 flex h-16 flex-shrink-0 border-b bg-white shadow-sm">
<div className="flex flex-1 px-4 sm:px-6">
<div className="flex flex-1 items-center">
<Link href={`/forms/${formId}/form`}>
<ArrowLeftIcon className="h-6 w-6" aria-hidden="true" />
</Link>
</div>
<p className="flex flex-1 items-center justify-center text-gray-600">Preview</p>
<div className="flex flex-1 items-center justify-end space-x-2 text-right sm:ml-6 sm:space-x-4">
<button
type="button"
onClick={() => resetApp()}
className="inline-flex items-center rounded-md border border-transparent bg-red-600 px-4 py-2 text-sm font-medium text-white shadow-sm hover:bg-red-700 focus:outline-none focus:ring-2 focus:ring-red-500 focus:ring-offset-2">
Restart
<ArrowPathIcon className="ml-2 -mr-1 h-5 w-5" aria-hidden="true" />
</button>
</div>
</div>
</div>
</header>
{/* Main content */}
{children}
</div>
</div>
</>
);
}

View File

@@ -1,9 +0,0 @@
interface Props {
children?: React.ReactNode;
}
const LimitedWidth: React.FC<Props> = ({ children }) => {
return <main className="mx-auto h-full w-full max-w-5xl">{children}</main>;
};
export default LimitedWidth;

View File

@@ -1,40 +0,0 @@
import { HomeIcon } from "@heroicons/react/24/outline";
import Link from "next/link";
export default function MenuBreadcrumbs({ breadcrumbs }) {
return (
<div className="hidden overflow-hidden text-ellipsis sm:flex sm:flex-1">
<nav className="hidden lg:flex" aria-label="Breadcrumb">
<ol className="flex items-center space-x-4">
<li>
<div>
<Link href="/forms/" className="text-ui-gray-dark hover:text-ui-gray-dark">
<HomeIcon className="h-5 w-5 flex-shrink-0" aria-hidden="true" />
<span className="sr-only">Home</span>
</Link>
</div>
</li>
{breadcrumbs.map((crumb) => (
<li key={crumb.name}>
<div className="flex items-center">
<svg
className="text-ui-gray-medium h-5 w-5 flex-shrink-0"
xmlns="http://www.w3.org/2000/svg"
fill="currentColor"
viewBox="0 0 20 20"
aria-hidden="true">
<path d="M5.555 17.776l8-16 .894.448-8 16-.894-.448z" />
</svg>
<a
href={crumb.href}
className="text-ui-gray-dark hover:text-ui-gray-dark ml-4 truncate text-sm font-medium">
{crumb.name}
</a>
</div>
</li>
))}
</ol>
</nav>
</div>
);
}

View File

@@ -1,58 +0,0 @@
import { Menu, Transition } from "@headlessui/react";
import { ArrowLeftOnRectangleIcon } from "@heroicons/react/24/solid";
import { signOut } from "next-auth/react";
import Image from "next/legacy/image";
import { Fragment } from "react";
import { classNames } from "../../lib/utils";
export default function MenuProfile({}) {
return (
<Menu as="div" className="relative z-50 flex-shrink-0">
{({ open }) => (
<>
<div className="inline-flex items-center ">
<Menu.Button className="ml-3 flex rounded-full bg-white text-sm focus:outline-none focus:ring-2 focus:ring-red-500 focus:ring-offset-2">
<span className="sr-only">Open user menu</span>
<div className="h-8 w-8">
<Image
className="rounded-full"
src="/img/avatar-placeholder.png"
alt="user avatar"
width={50}
height={50}
/>
</div>
</Menu.Button>
</div>
<Transition
show={open}
as={Fragment}
enter="transition ease-out duration-100"
enterFrom="transform opacity-0 scale-95"
enterTo="transform opacity-100 scale-100"
leave="transition ease-in duration-75"
leaveFrom="transform opacity-100 scale-100"
leaveTo="transform opacity-0 scale-95">
<Menu.Items
static
className="absolute right-0 mt-2 w-48 origin-top-right rounded-sm bg-white p-1 shadow-lg ring-1 ring-black ring-opacity-5 focus:outline-none">
<Menu.Item>
{({ active }) => (
<button
onClick={() => signOut({ callbackUrl: "/" })}
className={classNames(
active ? "bg-ui-gray-light text-ui-black rounded-sm" : "text-ui-gray-dark",
"flex w-full px-4 py-2 text-sm"
)}>
<ArrowLeftOnRectangleIcon className="text-ui-gray-dark mr-3 h-5 w-5" aria-hidden="true" />
Sign Out
</button>
)}
</Menu.Item>
</Menu.Items>
</Transition>
</>
)}
</Menu>
);
}

View File

@@ -1,60 +0,0 @@
import Link from "next/link";
import { useRouter } from "next/router";
import { classNames } from "../../lib/utils";
interface Step {
id: string;
name: string;
href: string;
}
type MenuStepsProps = {
steps: Step[];
currentStep: string;
};
export default function MenuSteps({ steps, currentStep }: MenuStepsProps) {
const router = useRouter();
return (
<div className="justify-left flex flex-1 items-center sm:justify-center">
<div className="w-full sm:hidden">
<label htmlFor="steps" className="sr-only">
Select a view
</label>
<select
id="steps"
name="steps"
className="border-ui-gray-medium focus:ring-red focus:border-red block w-full rounded-md py-2 pl-3 pr-10 text-base focus:outline-none sm:text-sm"
defaultValue={steps.find((step) => step.id === currentStep).name}
onChange={(e) => {
const stepId = e.target.children[e.target.selectedIndex].id;
router.push(steps.find((s) => s.id === stepId).href);
}}>
{steps.map((step) => (
<option key={step.name} id={step.id}>
{step.name}
</option>
))}
</select>
</div>
<div className="hidden sm:block">
<nav className="-mb-px flex space-x-8" aria-label="steps">
{steps.map((step) => (
<Link
key={step.name}
href={step.href}
className={classNames(
step.id === currentStep
? "border-red text-red"
: "text-ui-gray-dark hover:text-ui-gray-dark hover:border-ui-gray-medium border-transparent",
"whitespace-nowrap border-b-2 py-5 px-1 text-sm font-medium"
)}
aria-current={step.id === currentStep ? "page" : undefined}>
{step.name}
</Link>
))}
</nav>
</div>
</div>
);
}

View File

@@ -1,27 +0,0 @@
import { PlusIcon } from "@heroicons/react/24/outline";
import { useState } from "react";
import NewFormModal from "../form/NewFormModal";
export default function NewFormNavButton({}) {
const [openNewFormModal, setOpenNewFormModal] = useState(false);
return (
<>
<button
type="button"
className="border-ui-gray-light bg-ui-gray-lighter text-ui-gray-dark hidden items-center border-r text-sm hover:bg-red-500 hover:text-white sm:flex"
onClick={() => setOpenNewFormModal(true)}>
<nav className="hidden sm:flex" aria-label="Breadcrumb">
<ol className="flex items-center space-x-4">
<li>
<div className="inline-flex items-center border border-transparent bg-transparent px-6 py-2 text-sm font-medium leading-4 hover:text-white focus:outline-none">
<PlusIcon className="-ml-0.5 mr-2 h-4 w-4" aria-hidden="true" />
create form
</div>
</li>
</ol>
</nav>
</button>
<NewFormModal open={openNewFormModal} setOpen={setOpenNewFormModal} />
</>
);
}

View File

@@ -1,46 +0,0 @@
import React from "react";
import { classNames } from "../../lib/utils";
interface NavItem {
id: string;
onClick: () => void;
Icon?: React.ElementType;
label?: string;
disabled?: boolean;
}
interface Props {
navItems: NavItem[];
currentItemId?: string;
}
// button component, consuming props
const SecondNavBar: React.FC<Props> = ({ navItems, currentItemId }) => {
return (
<div className="border-ui-gray-light bg-ui-gray-lighter flex flex-shrink-0 items-center justify-center border-b">
<nav className="flex space-x-10" aria-label="resultModes">
{navItems.map((navItem) => (
<button
key={navItem.id}
className={classNames(
`h-16 border-b-2 border-transparent text-xs`,
!navItem.disabled &&
(navItem.id === currentItemId
? "text-red border-red border-b-2"
: "text-ui-gray-dark hover:text-red bg-transparent hover:border-gray-300"),
navItem.disabled
? "text-ui-gray-medium"
: "hover:border-red text-ui-gray-dark hover:text-red hover:border-b-2"
)}
onClick={navItem.onClick}
disabled={navItem.disabled}>
{navItem.Icon && <navItem.Icon className="mx-auto mb-1 h-6 w-6 stroke-1" />}
{navItem.label}
</button>
))}
</nav>
</div>
);
};
export default SecondNavBar;

View File

@@ -1,21 +0,0 @@
import { signIn, useSession } from "next-auth/react";
import Loading from "../Loading";
const withAuthentication = (Component) =>
function WithAuth(props) {
const { status } = useSession({
required: true,
onUnauthenticated() {
// The user is not authenticated, handle it here.
return signIn();
},
});
if (status === "loading") {
return <Loading />;
}
return <Component {...props} />;
};
export default withAuthentication;

View File

@@ -1,101 +0,0 @@
/* This example requires Tailwind CSS v2.0+ */
import { useRouter } from "next/router";
import { useEffect, useState } from "react";
import { createPipeline, usePipelines } from "../../lib/pipelines";
import Modal from "../Modal";
import { webhook } from "./webhook";
import { emailNotification } from "./emailNotification";
import PipelineSettings from "./PipelineSettings";
const availablePipelines = [webhook, emailNotification];
const getEmptyPipeline = () => {
return { name: "", type: null, events: [], data: {} };
};
export default function AddPipelineModal({ open, setOpen }) {
const router = useRouter();
const formId = router.query.id.toString();
const [typeId, setTypeId] = useState(null);
const [pipeline, setPipeline] = useState(getEmptyPipeline());
const { pipelines, mutatePipelines } = usePipelines(formId);
useEffect(() => {
if (typeId !== pipeline.type) {
setPipeline({ ...pipeline, type: typeId });
}
}, [typeId, pipeline]);
useEffect(() => {
if (!open) {
setPipeline(getEmptyPipeline());
setTypeId(null);
}
}, [open]);
const handleSubmit = async (e) => {
e.preventDefault();
const newPipeline = await createPipeline(router.query.id, pipeline);
const newPipelines = JSON.parse(JSON.stringify(pipelines));
newPipelines.push(newPipeline);
mutatePipelines(newPipelines);
setOpen(false);
};
return (
<Modal open={open} setOpen={setOpen}>
<>
{typeId === null ? (
<>
<h2 className="text-ui-gray-dark mb-6 text-xl font-bold">
Please choose a pipeline you want to add
</h2>
{availablePipelines.map((pipeline) => (
<div
className="border-ui-gray-light mb-5 w-full border bg-white shadow sm:rounded"
key={pipeline.title}>
<div className="px-4 py-5 sm:p-6">
<h3 className="text-lg font-medium leading-6 text-gray-900">{pipeline.title}</h3>
<div className="mt-2 sm:flex sm:items-start sm:justify-between">
<div className="max-w-xl text-sm text-gray-500">
<p>{pipeline.description}</p>
</div>
<div className="mt-5 sm:mt-0 sm:ml-6 sm:flex sm:flex-shrink-0 sm:items-center">
<button
type="button"
onClick={() => {
setTypeId(pipeline.typeId);
}}
className="inline-flex items-center rounded-md border border-transparent bg-red-600 px-4 py-2 font-medium text-white shadow-sm hover:bg-red-700 focus:outline-none focus:ring-2 focus:ring-red-500 focus:ring-offset-2 sm:text-sm">
Select
</button>
</div>
</div>
</div>
</div>
))}
</>
) : (
<form className="w-full space-y-8 divide-y divide-gray-200" onSubmit={handleSubmit}>
<PipelineSettings typeId={typeId} pipeline={pipeline} setPipeline={setPipeline} />
<div className="pt-5">
<div className="flex justify-end">
<button
type="button"
onClick={() => setOpen(false)}
className="rounded-md border border-gray-300 bg-white px-4 py-2 text-sm font-medium text-gray-700 shadow-sm hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-red-500 focus:ring-offset-2">
Cancel
</button>
<button
type="submit"
className="ml-3 inline-flex justify-center rounded-md border border-transparent bg-red-600 px-4 py-2 text-sm font-medium text-white shadow-sm hover:bg-red-700 focus:outline-none focus:ring-2 focus:ring-red-500 focus:ring-offset-2">
Create
</button>
</div>
</div>
</form>
)}
</>
</Modal>
);
}

View File

@@ -1,16 +0,0 @@
import { EmailNotificationSettings } from "./emailNotification";
import { WebhookSettings } from "./webhook";
const PipelineSettings = ({ typeId, pipeline, setPipeline }) => {
switch (typeId) {
case "WEBHOOK":
return <WebhookSettings pipeline={pipeline} setPipeline={setPipeline} />;
break;
case "EMAIL_NOTIFICATION":
return <EmailNotificationSettings pipeline={pipeline} setPipeline={setPipeline} />;
default:
return <></>;
}
};
export default PipelineSettings;

View File

@@ -1,52 +0,0 @@
import { persistPipeline, usePipeline, usePipelines } from "../../lib/pipelines";
import Loading from "../Loading";
import Modal from "../Modal";
import PipelineSettings from "./PipelineSettings";
export default function UpdatePipelineModal({ open, setOpen, formId, pipelineId }) {
const { pipeline, isLoadingPipeline, mutatePipeline } = usePipeline(formId, pipelineId);
const { pipelines, mutatePipelines } = usePipelines(formId);
const handleSubmit = async (e) => {
e.preventDefault();
await persistPipeline(pipeline);
const newPipelines = JSON.parse(JSON.stringify(pipelines));
const pipelineIdx = pipelines.findIndex((p) => p.id === pipelineId);
if (pipelineIdx > -1) {
newPipelines[pipelineIdx] = pipeline;
mutatePipelines(newPipelines);
}
setOpen(false);
};
return (
<Modal open={open} setOpen={setOpen}>
{isLoadingPipeline ? (
<Loading />
) : (
<form className="w-full space-y-8 divide-y divide-gray-200" onSubmit={handleSubmit}>
<PipelineSettings
typeId={pipeline.type}
pipeline={pipeline}
setPipeline={(p) => mutatePipeline(p, false)}
/>
<div className="pt-5">
<div className="flex justify-end">
<button
type="button"
onClick={() => setOpen(false)}
className="rounded-md border border-gray-300 bg-white px-4 py-2 text-sm font-medium text-gray-700 shadow-sm hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-red-500 focus:ring-offset-2">
Cancel
</button>
<button
type="submit"
className="ml-3 inline-flex justify-center rounded-md border border-transparent bg-red-600 px-4 py-2 text-sm font-medium text-white shadow-sm hover:bg-red-700 focus:outline-none focus:ring-2 focus:ring-red-500 focus:ring-offset-2">
Update
</button>
</div>
</div>
</form>
)}
</Modal>
);
}

View File

@@ -1,142 +0,0 @@
const eventTypes = [
{
id: "PAGE_SUBMISSION",
name: "Page Submission",
description: "every time a form page is submitted (partial submission)",
},
{
id: "FORM_COMPLETED",
name: "Form completed",
description: "each time the form is fully completed (total submission)",
},
];
export function EmailNotificationSettings({ pipeline, setPipeline }) {
const toggleEvent = (eventId) => {
const newPipeline = JSON.parse(JSON.stringify(pipeline));
const eventIdx = newPipeline.events.indexOf(eventId);
if (eventIdx !== -1) {
newPipeline.events.splice(eventIdx, 1);
} else {
newPipeline.events.push(eventId);
}
setPipeline(newPipeline);
};
const updateField = (field, value, parent = null) => {
const newPipeline = JSON.parse(JSON.stringify(pipeline));
if (parent) {
newPipeline[parent][field] = value;
} else {
newPipeline[field] = value;
}
setPipeline(newPipeline);
};
return (
<div className="space-y-8 divide-y divide-gray-200">
<div>
<h2 className="text-ui-gray-dark mb-3 text-xl font-bold">Configure Email notifications</h2>
<p className="mt-1 text-sm text-gray-500">
Configure Email notifications. To learn more about how email notifications work, please check out our docs.
</p>
<div className="mt-6 grid grid-cols-1 gap-y-6 gap-x-4 sm:grid-cols-6">
<div className="sm:col-span-4">
<label htmlFor="name" className="block text-sm font-medium text-gray-700">
Pipeline Name
</label>
<div className="mt-1">
<input
type="text"
name="name"
id="name"
value={pipeline.name || ""}
onChange={(e) => updateField("name", e.target.value)}
className="block w-full rounded-md border-gray-300 shadow-sm focus:border-red-500 focus:ring-red-500 sm:text-sm"
required
/>
</div>
</div>
<div className="sm:col-span-4">
<label htmlFor="endpointUrl" className="block text-sm font-medium text-gray-700">
Email address
</label>
<div className="mt-1">
<input
type="email"
// pattern="/^[^@]+@[^.]+\..+$/"
onInvalid={(e: any) => e.target.setCustomValidity("please provide a valid email")}
onInput={(e: any) => e.target.setCustomValidity("")}
name="email"
id="email"
value={pipeline.data.email || ""}
onChange={(e) => updateField("email", e.target.value, "data")}
className="block w-full rounded-md border-gray-300 shadow-sm focus:border-red-500 focus:ring-red-500 sm:text-sm"
required
/>
</div>
<p className="mt-2 text-xs text-gray-500" id="email-description">
The email address that will receive notifications when the form/page is completed
</p>
</div>
</div>
</div>
<div className="pt-8">
<div>
<h3 className="text-lg font-medium leading-6 text-gray-900">Advanced Settings</h3>
<p className="mt-1 text-sm text-gray-500">Set up this webhook to fit your needs.</p>
</div>
<div className="mt-6">
<fieldset>
<legend className="sr-only">Events</legend>
<div className="text-base font-medium text-gray-900" aria-hidden="true">
Events
</div>
<div className="mt-4 space-y-4">
{eventTypes.map((eventType) => (
<div key={eventType.id}>
<div className="relative flex items-start">
<div className="flex h-5 items-center">
<input
id={eventType.id}
name={eventType.name}
type="checkbox"
checked={pipeline.events.includes(eventType.id)}
onChange={() => toggleEvent(eventType.id)}
className="h-4 w-4 rounded-sm border-gray-300 text-red-600 focus:ring-red-500"
/>
</div>
<div className="ml-3 text-sm">
<label htmlFor={eventType.id} className="font-medium text-gray-700">
{eventType.name}
</label>
<p className="text-gray-500">{eventType.description}</p>
</div>
</div>
</div>
))}
</div>
</fieldset>
</div>
<div className="mt-6">
<fieldset>
<legend className="sr-only">Conditions</legend>
<div className="text-base font-medium text-gray-900" aria-hidden="true">
Conditions
</div>
<div className="mt-4 space-y-4">
<div className="rounded-sm border border-gray-100 bg-gray-50 px-2 py-5">
<p className="flex justify-center text-xs text-gray-600">
conditional data piping coming soon
</p>
</div>
</div>
</fieldset>
</div>
</div>
</div>
);
}

View File

@@ -1,8 +0,0 @@
export const emailNotification = {
typeId: "EMAIL_NOTIFICATION",
title: "Email Notification",
description: "Get an email notification when your form is completed",
};
export * from "./SettingsComponent";
// export * from "./handler";

View File

@@ -1,157 +0,0 @@
const eventTypes = [
{
id: "PAGE_SUBMISSION",
name: "Page Submission",
description: "every time a form page is submitted (partial submission)",
},
];
export function WebhookSettings({ pipeline, setPipeline }) {
const toggleEvent = (eventId) => {
const newPipeline = JSON.parse(JSON.stringify(pipeline));
const eventIdx = newPipeline.events.indexOf(eventId);
if (eventIdx !== -1) {
newPipeline.events.splice(eventIdx, 1);
} else {
newPipeline.events.push(eventId);
}
setPipeline(newPipeline);
};
const updateField = (field, value, parent = null) => {
const newPipeline = JSON.parse(JSON.stringify(pipeline));
if (parent) {
newPipeline[parent][field] = value;
} else {
newPipeline[field] = value;
}
setPipeline(newPipeline);
};
return (
<div className="space-y-8 divide-y divide-gray-200">
<div>
<h2 className="text-ui-gray-dark mb-3 text-xl font-bold">Configure Webhook</h2>
<p className="mt-1 text-sm text-gray-500">
Configure your webhook. To learn more about how webhooks work, please check out our docs.
</p>
<div className="mt-6 grid grid-cols-1 gap-y-6 gap-x-4 sm:grid-cols-6">
<div className="sm:col-span-4">
<label htmlFor="name" className="block text-sm font-medium text-gray-700">
Webhook Name
</label>
<div className="mt-1">
<input
type="text"
name="name"
id="name"
value={pipeline.name || ""}
onChange={(e) => updateField("name", e.target.value)}
className="block w-full rounded-md border-gray-300 shadow-sm focus:border-red-500 focus:ring-red-500 sm:text-sm"
required
/>
</div>
</div>
<div className="sm:col-span-4">
<label htmlFor="endpointUrl" className="block text-sm font-medium text-gray-700">
Endpoint URL
</label>
<div className="mt-1">
<input
type="url"
pattern="^https:\/\/(.*)"
onInvalid={(e: any) =>
e.target.setCustomValidity("please provide a valid website address with https")
}
onInput={(e: any) => e.target.setCustomValidity("")}
name="endpointUrl"
id="endpointUrl"
value={pipeline.data.endpointUrl || ""}
onChange={(e) => updateField("endpointUrl", e.target.value, "data")}
className="block w-full rounded-md border-gray-300 shadow-sm focus:border-red-500 focus:ring-red-500 sm:text-sm"
required
/>
</div>
<p className="mt-2 text-xs text-gray-500" id="email-description">
Your server URL to which the data should be sent (https required)
</p>
</div>
<div className="sm:col-span-4">
<label htmlFor="secret" className="block text-sm font-medium text-gray-700">
Secret
</label>
<div className="mt-1">
<input
type="text"
name="secret"
id="secret"
value={pipeline.data.secret || ""}
onChange={(e) => updateField("secret", e.target.value, "data")}
className="block w-full rounded-md border-gray-300 shadow-sm focus:border-red-500 focus:ring-red-500 sm:text-sm"
/>
</div>
<p className="mt-2 text-xs text-gray-500" id="email-description">
We sign all event notification payloads with a SHA256 signature using this secret
</p>
</div>
</div>
</div>
<div className="pt-8">
<div>
<h3 className="text-lg font-medium leading-6 text-gray-900">Advanced Settings</h3>
<p className="mt-1 text-sm text-gray-500">Set up this webhook to fit your needs.</p>
</div>
<div className="mt-6">
<fieldset>
<legend className="sr-only">Events</legend>
<div className="text-base font-medium text-gray-900" aria-hidden="true">
Events
</div>
<div className="mt-4 space-y-4">
{eventTypes.map((eventType) => (
<div key={eventType.id}>
<div className="relative flex items-start">
<div className="flex h-5 items-center">
<input
id="comments"
name="comments"
type="checkbox"
checked={pipeline.events.includes(eventType.id)}
onChange={() => toggleEvent(eventType.id)}
className="h-4 w-4 rounded-sm border-gray-300 text-red-600 focus:ring-red-500"
/>
</div>
<div className="ml-3 text-sm">
<label htmlFor="comments" className="font-medium text-gray-700">
{eventType.name}
</label>
<p className="text-gray-500">{eventType.description}</p>
</div>
</div>
</div>
))}
</div>
</fieldset>
</div>
<div className="mt-6">
<fieldset>
<legend className="sr-only">Conditions</legend>
<div className="text-base font-medium text-gray-900" aria-hidden="true">
Conditions
</div>
<div className="mt-4 space-y-4">
<div className="rounded-sm border border-gray-100 bg-gray-50 px-2 py-5">
<p className="flex justify-center text-xs text-gray-600">
conditional data piping coming soon
</p>
</div>
</div>
</fieldset>
</div>
</div>
</div>
);
}

View File

@@ -1,22 +0,0 @@
import crypto from "crypto";
import { ApiEvent } from "../../../lib/types";
export async function handleWebhook(pipeline, event: ApiEvent) {
if (pipeline.data.hasOwnProperty("endpointUrl") && pipeline.data.hasOwnProperty("secret")) {
if (event.type === "pageSubmission" && pipeline.events.includes("PAGE_SUBMISSION")) {
const webhookData = pipeline.data;
const body = { time: Math.floor(Date.now() / 1000), event };
fetch(webhookData.endpointUrl.toString(), {
method: "POST",
headers: {
"Content-Type": "application/json",
"X-Hub-Signature-256": `sha256=${crypto
.createHmac("sha256", webhookData.secret.toString())
.update(JSON.stringify(body))
.digest("base64")}`,
},
body: JSON.stringify(body),
});
}
}
}

View File

@@ -1,8 +0,0 @@
export const webhook = {
typeId: "WEBHOOK",
title: "Webhook",
description: "Notify an external endpoint when events happen in your form (e.g. a new submission).",
};
export * from "./SettingsComponent";
export * from "./handler";

View File

@@ -1,65 +0,0 @@
import { QuestionMarkCircleIcon } from "@heroicons/react/24/outline";
import { ArrowDownIcon, ArrowUpIcon } from "@heroicons/react/24/solid";
import React from "react";
import { classNames } from "../../lib/utils";
interface Props {
value: string | number;
label: string;
toolTipText: string;
trend?: number;
smallerText?: boolean;
}
const AnalyticsCard: React.FC<Props> = ({ value, label, toolTipText, trend, smallerText }) => {
return (
<div className="rounded-md bg-white shadow-md">
<div key={label} className="px-4 py-5 sm:p-6">
<dt className="has-tooltip inline-flex text-base font-normal text-gray-900">
{label}{" "}
{toolTipText && (
<QuestionMarkCircleIcon className="text-red hover:text-ui-gray-dark ml-1 h-4 w-4" />
)}
{toolTipText && (
<span className="tooltip -mt-6 -ml-8 flex grow rounded bg-gray-600 p-1 px-4 text-center text-xs text-white shadow-lg">
{toolTipText}
</span>
)}
</dt>
<dd className="mt-1 flex items-baseline justify-between md:block lg:flex">
<div
className={classNames(
smallerText ? "text-lg" : "text-xl",
"flex items-baseline text-xl font-semibold text-gray-800"
)}>
{value}
</div>
{trend && (
<div
className={classNames(
trend >= 0 ? "bg-green-100 text-green-800" : "bg-red-100 text-red-800",
"inline-flex items-baseline rounded-full px-2.5 py-0.5 text-sm font-medium md:mt-2 lg:mt-0"
)}>
{trend >= 0 ? (
<ArrowUpIcon
className="-ml-1 mr-0.5 h-5 w-5 flex-shrink-0 self-center text-green-500"
aria-hidden="true"
/>
) : (
<ArrowDownIcon
className="-ml-1 mr-0.5 h-5 w-5 flex-shrink-0 self-center text-red-500"
aria-hidden="true"
/>
)}
<span className="sr-only">{trend >= 0 ? "Increased" : "Decreased"} by</span>
{trend} %
</div>
)}
</dd>
</div>
</div>
);
};
export default AnalyticsCard;

View File

@@ -1,128 +0,0 @@
import { Menu, Transition } from "@headlessui/react";
import { ChevronDownIcon } from "@heroicons/react/24/solid";
import { parseAsync } from "json2csv";
import { Fragment } from "react";
import { useForm } from "../../lib/forms";
import { getSubmission, useSubmissionSessions } from "../../lib/submissionSessions";
import { Submission } from "../../lib/types";
import { slugify } from "../../lib/utils";
import Loading from "../Loading";
export default function DownloadResponses({ formId }) {
const { submissionSessions, isLoadingSubmissionSessions } = useSubmissionSessions(formId);
const { form, isLoadingForm } = useForm(formId);
const download = async (format: "csv" | "excel") => {
// build dict of answers in copy of answerSessions
const submissions: Submission[] = submissionSessions.map((s) => getSubmission(s, form.schema));
// build data fields for csv/excel file
const data = [];
for (const submission of submissions) {
const dataEntry = { createdAt: submission.createdAt };
for (const page of submission.pages) {
if (page.elements) {
for (const element of page.elements) {
if (element.type !== "submit") {
dataEntry[element.label] = element.value;
}
}
}
}
data.push(dataEntry);
}
// get fields
const fields: any = [
{
label: "Timestamp",
value: "createdAt",
},
];
for (const page of submissions[0].pages) {
for (const element of page.elements) {
if (element.type !== "submit") {
fields.push({
label: element.label,
value: element.label,
});
}
}
}
const opts: any = { fields };
if (format === "excel") {
opts.excelStrings = true;
}
const fileTypes = {
csv: { mimeType: "text/csv", fileExtension: "csv" },
excel: { mimeType: "application/vnd.ms-excel", fileExtension: "csv" },
};
try {
const csv = await parseAsync(data, opts);
// download
var blob = new Blob([csv], { type: fileTypes[format].mimeType });
const url = window.URL.createObjectURL(new Blob([blob]));
const link = document.createElement("a");
link.href = url;
link.setAttribute("download", `${slugify(form.name)}.${fileTypes[format].fileExtension}`);
document.body.appendChild(link);
link.click();
link.parentNode.removeChild(link);
} catch (err) {
console.error(err);
}
};
if (isLoadingSubmissionSessions || isLoadingForm) {
return <Loading />;
}
return (
<Menu as="div" className="relative z-10 inline-block w-full text-left">
<div>
<Menu.Button className="inline-flex w-full justify-center bg-gray-400 px-4 py-2 text-sm font-medium text-white focus:outline-none focus-visible:ring-2 focus-visible:ring-white focus-visible:ring-opacity-75">
Download
<ChevronDownIcon className="ml-2 -mr-1 h-5 w-5 text-white hover:text-gray-100" aria-hidden="true" />
</Menu.Button>
</div>
<Transition
as={Fragment}
enter="transition ease-out duration-100"
enterFrom="transform opacity-0 scale-95"
enterTo="transform opacity-100 scale-100"
leave="transition ease-in duration-75"
leaveFrom="transform opacity-100 scale-100"
leaveTo="transform opacity-0 scale-95">
<Menu.Items className="absolute right-0 mt-2 w-56 origin-top-right divide-y divide-gray-100 rounded-md bg-white shadow-lg ring-1 ring-black ring-opacity-5 focus:outline-none">
<div className="px-1 py-1 ">
<Menu.Item>
{({ active }) => (
<button
onClick={() => download("csv")}
className={`${
active ? "bg-red-500 text-white" : "text-gray-900"
} group flex w-full items-center rounded-md px-2 py-2 text-sm`}>
Download as CSV
</button>
)}
</Menu.Item>
{/* <Menu.Item>
{({ active }) => (
<button
onClick={() => download("excel")}
className={`${
active ? "bg-red-500 text-white" : "text-gray-900"
} group flex rounded-md items-center w-full px-2 py-2 text-sm`}
>
Download as Excel
</button>
)}
</Menu.Item> */}
</div>
</Menu.Items>
</Transition>
</Menu>
);
}

View File

@@ -1,87 +0,0 @@
import Image from "next/legacy/image";
import { useMemo } from "react";
import { getSubmissionAnalytics, useSubmissionSessions } from "../../lib/submissionSessions";
import { timeSince } from "../../lib/utils";
import Loading from "../Loading";
import AnalyticsCard from "./AnalyticsCard";
export default function ResultsAnalytics({ formId }) {
const { submissionSessions, isLoadingSubmissionSessions } = useSubmissionSessions(formId);
const analytics = useMemo(() => {
if (!isLoadingSubmissionSessions) {
return getSubmissionAnalytics(submissionSessions);
}
}, [isLoadingSubmissionSessions, submissionSessions]);
const stats = useMemo(() => {
if (analytics) {
return [
{
id: "totalSubmissions",
name: "Total Submissions",
stat: analytics.totalSubmissions || "--",
trend: undefined,
toolTipText: undefined,
},
{
id: "lastSubmission",
name: "Last Submission",
stat: analytics.lastSubmissionAt ? timeSince(analytics.lastSubmissionAt) : "--",
smallerText: true,
toolTipText: undefined,
},
];
}
}, [analytics]);
if (!stats || !analytics) {
return <Loading />;
}
return (
<div className="my-8">
<h2 className="text-ui-gray-dark text-xl font-bold">Analytics</h2>
<div>
<dl className="mt-8 grid grid-cols-1 gap-5 sm:grid-cols-2">
{stats.map((item) => (
<AnalyticsCard
key={item.id}
value={item.stat}
label={item.name}
toolTipText={item.toolTipText}
trend={item.trend}
smallerText={item.smallerText}
/>
))}
</dl>
</div>
<div className="flex items-end">
<h2 className="text-ui-gray-dark mt-16 text-xl font-bold">Optimize Form</h2>
<div className="ml-2 rounded-sm bg-green-50 px-3 py-2 text-xs text-green-800">
<p>coming soon</p>
</div>
</div>
<div className="mt-8 grid grid-cols-2 gap-10">
<div className="rounded-md bg-white p-5 shadow-md">
<Image
src="/../../img/drop-offs-v1.svg"
alt="drop-off"
layout="responsive"
width={500}
height={273}
/>
</div>
<div className="rounded-md bg-white p-5 shadow-md">
<Image
src="/../../img/a-b-test-v1.svg"
alt="drop-off"
layout="responsive"
width={500}
height={273}
/>
</div>
</div>
</div>
);
}

View File

@@ -1,191 +0,0 @@
import { useEffect, useState } from "react";
import { RadioGroup } from "@headlessui/react";
import { CheckIcon } from "@heroicons/react/24/solid";
import { getEventName } from "../../lib/events";
import { useSubmissionSessions } from "../../lib/submissionSessions";
import { SubmissionSession } from "../../lib/types";
import { convertDateTimeString, convertTimeString } from "../../lib/utils";
import SubmissionDisplay from "./SubmissionDisplay";
import DownloadResponses from "./DownloadResponses";
import Loading from "../Loading";
import { TrashIcon } from "@heroicons/react/24/outline";
import { toast } from "react-toastify";
function classNames(...classes) {
return classes.filter(Boolean).join(" ");
}
type ResultsResponseProps = {
formId: string;
};
export default function ResultsResponses({ formId }: ResultsResponseProps) {
const { submissionSessions, isLoadingSubmissionSessions, mutateSubmissionSessions } =
useSubmissionSessions(formId);
const [activeSubmissionSession, setActiveSubmissionSession] = useState<SubmissionSession | null>(null);
const handleDelete = async (submissionSession: SubmissionSession) => {
try {
await fetch(`/api/forms/${formId}/submissionSessions/${submissionSession.id}`, {
method: "DELETE",
});
await mutateSubmissionSessions();
setActiveSubmissionSession(null);
toast("Successfully deleted");
} catch (error) {
toast(error);
}
};
useEffect(() => {
if (!isLoadingSubmissionSessions && submissionSessions.length > 0) {
setActiveSubmissionSession(submissionSessions[0]);
}
}, [isLoadingSubmissionSessions, submissionSessions]);
if (isLoadingSubmissionSessions) {
return <Loading />;
}
return (
<div className="max-w-screen mx-auto flex h-full w-full flex-1 flex-col overflow-visible">
<div className="relative z-0 flex h-full flex-1 overflow-visible">
<main className="relative z-0 mb-32 flex-1 overflow-y-auto focus:outline-none xl:order-last">
<div className="overflow-visible sm:rounded-lg">
{!activeSubmissionSession ? (
<button
type="button"
className="relative mx-auto mt-8 block w-96 rounded-lg border-2 border-dashed border-gray-300 p-12 text-center hover:border-gray-400 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2">
<span className="mt-2 block text-sm font-medium text-gray-500">
Select a response on the left to see the details here
</span>
</button>
) : (
<>
<div className="bg-white px-4 py-5 shadow sm:px-12 sm:pb-4 sm:pt-12">
<div className="grid grid-cols-2 gap-8 divide-x">
<div className="flow-root">
<h1 className="mb-8 text-gray-700">
{convertDateTimeString(activeSubmissionSession.createdAt)}
</h1>
<SubmissionDisplay
key={activeSubmissionSession.id}
submissionSession={activeSubmissionSession}
formId={formId}
/>
</div>
<div className="hidden pl-10 md:flow-root">
<h1 className="mb-8 text-gray-700">Session Activity</h1>
<ul role="list" className="-mb-8">
{activeSubmissionSession.events.map((event, eventIdx) => (
<li key={event.id}>
<div className="relative pb-8">
{eventIdx !== activeSubmissionSession.events.length - 1 ? (
<span
className="bg-ui-gray-light absolute top-4 left-4 -ml-px h-full w-0.5"
aria-hidden="true"
/>
) : null}
<div className="relative flex space-x-3">
<div>
<span
className={classNames(
"bg-red-200",
"flex h-8 w-8 items-center justify-center rounded-full ring-8 ring-white"
)}>
<CheckIcon className="h-5 w-5 text-white" aria-hidden="true" />
</span>
</div>
<div className="flex min-w-0 flex-1 flex-wrap justify-between gap-4 pt-1.5">
<div>
<p className="text-sm text-gray-500">
{getEventName(event.type)}
{/* <span className="font-medium text-gray-900">
{event.data.pageName || ""}
</span> */}
</p>
</div>
<div className="whitespace-nowrap text-right text-sm text-gray-500">
<time dateTime={event.createdAt}>
{convertTimeString(event.createdAt)}
</time>
</div>
</div>
</div>
</div>
</li>
))}
</ul>
</div>
</div>
</div>
<div className="w-full">
<button
className="flex w-full items-center justify-center gap-2 border border-transparent bg-gray-300 px-4 py-2 text-sm font-medium text-white shadow-sm hover:bg-red-500 focus:outline-none"
onClick={() => {
if (
confirm("Are you sure you want to delete this submission? It will be gone forever!")
) {
handleDelete(activeSubmissionSession);
}
}}>
<TrashIcon className="h-4 w-4" />
Delete Submission
</button>
</div>
</>
)}
</div>
</main>
<aside className="border-ui-gray-light order-first flex h-full flex-1 flex-shrink-0 flex-col border-r md:w-96 md:flex-none">
<DownloadResponses formId={formId} />
<div className="pt-4 pb-2">
<h2 className="px-5 text-lg font-medium text-gray-900">Responses</h2>
</div>
{submissionSessions.length === 0 ? (
<p className="mt-3 px-5 text-sm text-gray-500">No responses yet</p>
) : (
<RadioGroup
value={activeSubmissionSession}
onChange={setActiveSubmissionSession}
className="mb-32 min-h-0 flex-1 overflow-y-auto shadow-inner"
as="div">
<div className="relative">
<ul className="divide-ui-gray-light relative z-0 divide-y">
{submissionSessions.map((submissionSession) => (
<RadioGroup.Option
key={submissionSession.id}
value={submissionSession}
className={({ checked }) =>
classNames(
checked ? "bg-gray-100" : "",
"relative flex items-center space-x-3 px-6 py-5 "
)
}>
<div className="min-w-0 flex-1">
<button
onClick={() => setActiveSubmissionSession(submissionSession)}
className="w-full text-left focus:outline-none">
{/* Extend touch target to entire panel */}
<span className="absolute inset-0" aria-hidden="true" />
<p className="text-sm font-medium text-gray-900">
{convertDateTimeString(submissionSession.createdAt)}
</p>
<p className="truncate text-sm text-gray-500">
{submissionSession.events.length} events
</p>
</button>
</div>
</RadioGroup.Option>
))}
</ul>
</div>
</RadioGroup>
)}
</aside>
</div>
</div>
);
}

View File

@@ -1,91 +0,0 @@
import { useMemo } from "react";
import { useForm } from "../../lib/forms";
import {
getSubmissionAnalytics,
getSubmissionSummary,
useSubmissionSessions,
} from "../../lib/submissionSessions";
import { SubmissionSummary } from "../../lib/types";
import { timeSince } from "../../lib/utils";
import AnalyticsCard from "./AnalyticsCard";
import Loading from "../Loading";
import TextResults from "./summary/TextResults";
import ChoiceResults from "./summary/ChoiceResults";
export default function ResultsSummary({ formId }) {
const { submissionSessions, isLoadingSubmissionSessions } = useSubmissionSessions(formId);
const { form, isLoadingForm } = useForm(formId);
const insights = useMemo(() => {
if (!isLoadingSubmissionSessions) {
return getSubmissionAnalytics(submissionSessions);
}
}, [isLoadingSubmissionSessions, submissionSessions]);
const summary: SubmissionSummary | undefined = useMemo(() => {
if (!isLoadingSubmissionSessions && !isLoadingForm) {
return getSubmissionSummary(submissionSessions, form?.schema);
}
}, [isLoadingSubmissionSessions, submissionSessions, isLoadingForm, form]);
const stats = useMemo(() => {
if (insights) {
return [
{
id: "totalSubmissions",
name: "Total Submissions",
stat: insights.totalSubmissions || "--",
trend: undefined,
toolTipText: undefined,
},
{
id: "lastSubmission",
name: "Last Submission",
stat: insights.lastSubmissionAt ? timeSince(insights.lastSubmissionAt) : "--",
smallerText: true,
toolTipText: undefined,
},
];
}
}, [insights]);
if (!summary || !insights) {
return <Loading />;
}
return (
<>
<h2 className="text-ui-gray-dark mt-8 text-xl font-bold">Responses Overview</h2>
<dl className="mt-8 grid grid-cols-1 gap-5 sm:grid-cols-2">
{stats.map((item) => (
<AnalyticsCard
key={item.id}
value={item.stat}
label={item.name}
toolTipText={item.toolTipText}
trend={item.trend}
smallerText={item.smallerText}
/>
))}
</dl>
<div>
{summary?.pages &&
summary.pages.map(
(page) =>
page.type === "form" && (
<div key={page.name}>
{page.elements.map((element) =>
["email", "number", "phone", "text", "textarea", "website"].includes(element.type) ? (
<TextResults element={element} />
) : ["checkbox", "radio"].includes(element.type) ? (
<ChoiceResults element={element} />
) : null
)}
</div>
)
)}
</div>
</>
);
}

View File

@@ -1,68 +0,0 @@
import { useMemo } from "react";
import { useForm } from "../../lib/forms";
import { convertDateTimeString } from "../../lib/utils";
import Loading from "../Loading";
export default function Submission({ formId, submissionSession }) {
const { form, isLoadingForm } = useForm(formId);
// fill the schema with the values provided by the user
const getSubmission = (submissionSession, schema) => {
if (!schema) return {};
const submission = JSON.parse(JSON.stringify(schema));
submission.id = submissionSession.id;
submission.createdAt = submissionSession.createdAt;
if (submissionSession.events.length > 0) {
for (const page of submission.pages) {
if (page.type === "form") {
const pageSubmission = submissionSession.events.find(
(s) => s.type === "pageSubmission" && s.data?.pageName === page.name
);
if (typeof pageSubmission !== "undefined") {
for (const element of page.elements) {
if (element.type !== "submit") {
if (element.name in pageSubmission.data?.submission) {
element.value = pageSubmission.data.submission[element.name];
}
}
}
}
}
}
}
return submission;
};
const submission = useMemo(() => {
if (form && submissionSession) {
return getSubmission(submissionSession, form.schema);
}
}, [form, submissionSession]);
if (isLoadingForm) {
return <Loading />;
}
return (
<div className="max-w- bg-white shadow sm:rounded-lg">
<div className="px-4 py-5 sm:p-6">
<div className="text-ui-gray-dark-600">
<p className="text-sm">{convertDateTimeString(submission.createdAt)}</p>
{submission.pages.map((page) => (
<div key={page.name}>
{page.elements?.map(
(element) =>
element.type !== "submit" && (
<div key={element.name}>
<p className="text-red font-semibold">{element.label}</p>
<p className="font-normal">{element.value || "[not provided]"}</p>
</div>
)
)}
</div>
))}
</div>
</div>
</div>
);
}

View File

@@ -1,45 +0,0 @@
import { useMemo } from "react";
import { useForm } from "../../lib/forms";
import { getSubmission } from "../../lib/submissionSessions";
import { Submission } from "../../lib/types";
import { classNames } from "../../lib/utils";
import Loading from "../Loading";
export default function SubmissionDisplay({ formId, submissionSession }) {
const { form, isLoadingForm } = useForm(formId);
const submission: Submission = useMemo(() => {
if (form && submissionSession) {
return getSubmission(submissionSession, form.schema);
}
}, [form, submissionSession]);
if (isLoadingForm) {
return <Loading />;
}
return (
<div className="flow-root">
<ul role="list" className="divide-ui-gray-light divide-y">
{submission.pages.map((page) =>
page.elements?.map(
(element) =>
element.type !== "submit" && (
<li key={element.name} className="py-5">
<p className="text-sm font-semibold text-gray-800">{element.label}</p>
<p
className={classNames(
element.value ? "text-gray-600" : "text-gray-400",
"whitespace-pre-line pt-1 text-sm text-gray-600"
)}>
{element.value || "[not provided]"}
</p>
</li>
)
)
)}
</ul>
</div>
);
}

View File

@@ -1,70 +0,0 @@
import {
AtSymbolIcon,
CheckCircleIcon,
GlobeAltIcon,
HashtagIcon,
Bars4Icon,
PhoneIcon,
} from "@heroicons/react/24/outline";
import { IoMdRadioButtonOn } from "react-icons/io";
import { classNames } from "../../../lib/utils";
export const elementTypes = [
{
type: "email",
icon: AtSymbolIcon,
},
{
type: "number",
icon: HashtagIcon,
},
{
type: "phone",
icon: PhoneIcon,
},
{
type: "text",
icon: Bars4Icon,
},
{
type: "textarea",
icon: Bars4Icon,
},
{
type: "checkbox",
icon: CheckCircleIcon,
},
{
type: "radio",
icon: IoMdRadioButtonOn,
},
{
type: "website",
icon: GlobeAltIcon,
},
];
export const getElementTypeIcon = (type) => {
const elementType = elementTypes.find((e) => e.type === type);
return elementType ? (
<span className={classNames(`text-white`, `bg-red-500`, "inline-flex rounded-lg p-3 ring-4 ring-white")}>
<elementType.icon className="h-4 w-4" aria-hidden="true" />
</span>
) : null;
};
export default function BaseResults({ element, children }) {
return (
<div className="my-8 overflow-hidden rounded-lg bg-white shadow">
<div className="px-4 py-5 sm:p-6">
<div className="flex items-center">
<div className="flex-shrink-0">{getElementTypeIcon(element.type)}</div>
<div className="ml-4">
<h3 className="text-md font-medium leading-6 text-gray-900">{element.label}</h3>
</div>
</div>
</div>
{children}
</div>
);
}

View File

@@ -1,47 +0,0 @@
import "chart.js/auto";
import { Chart } from "react-chartjs-2";
import BaseResults from "./BaseResults";
export default function ChoiceResults({ element }) {
const data = {
//labels: element.data.options,
labels: element.options.map((o) => o.label),
datasets: [
{
//data: getDataset(element, elementAnswers),
data: element.options.map((o) => o.summary || 0),
backgroundColor: ["rgba(245, 59, 87, 0.7)"],
borderColor: ["rgba(245, 59, 87, 1)"],
borderWidth: 1,
},
],
};
const options: any = {
indexAxis: "y",
responsive: true,
plugins: {
legend: {
display: false,
},
},
scales: {
yAxis: [
{
ticks: {
min: 1,
precision: 0,
},
},
],
},
};
return (
<BaseResults element={element}>
<div className="my-4 mt-6 flow-root px-8 text-center">
<Chart type="bar" data={data} options={options} height={75} />
</div>
</BaseResults>
);
}

View File

@@ -1,26 +0,0 @@
import BaseResults from "./BaseResults";
export default function TextResults({ element }) {
return (
<BaseResults element={element}>
<div className="my-4 mt-6 flow-root h-44 max-h-64 overflow-y-scroll px-8 text-center">
<ul className="divide-ui-gray-light -my-5 divide-y">
{element?.summary?.map((answer) => (
<li key={answer} className="py-4">
<div className="relative focus-within:ring-2 focus-within:ring-indigo-500">
<h3 className="text-sm text-gray-700">
{/* Extend touch target to entire panel */}
<span className="absolute inset-0" aria-hidden="true" />
{answer}
</h3>
{/* <p className="mt-1 text-xs text-gray-300 line-clamp-2">
{timeSince(answer.createdAt.toISOString())}
</p> */}
</div>
</li>
))}
</ul>
</div>
</BaseResults>
);
}

View File

@@ -1,22 +0,0 @@
import { prisma } from "@formbricks/database";
export const formHasOwnership = async (session, formId) => {
try {
const form = await prisma.form.findUnique({
where: { id: formId },
include: {
owner: {
select: { email: true },
},
},
});
if (form.owner.email === session.user.email) {
return true;
} else {
return false;
}
} catch (e) {
console.error(`can't verify ownership: ${e}`);
return false;
}
};

View File

@@ -1,140 +0,0 @@
import { handleWebhook } from "../components/pipelines/webhook";
import { sendFormSubmissionEmail, sendPageSubmissionEmail } from "./email";
import { capturePosthogEvent } from "./posthog";
import { prisma } from "@formbricks/database";
import { sendTelemetry } from "./telemetry";
import { ApiEvent, Schema } from "./types";
type validationError = {
status: number;
message: string;
};
export const validateEvents = (events: ApiEvent[]): validationError | undefined => {
if (!Array.isArray(events)) {
return { status: 400, message: `"events" needs to be a list` };
}
for (const event of events) {
if (
!["createSubmissionSession", "pageSubmission", "formCompleted", "updateSchema"].includes(event.type)
) {
return {
status: 400,
message: `event type ${event.type} is not suppported`,
};
}
return;
}
};
export const processApiEvent = async (event: ApiEvent, formId) => {
const form = await prisma.form.findUnique({
where: {
id: formId,
},
select: {
owner: true,
schema: true,
id: true,
createdAt: true,
updatedAt: true,
noCodeForm: true,
name: true,
formType: true,
},
});
// save submission
if (event.type === "pageSubmission") {
const schema = form.schema as Schema;
const { pageName } = event.data;
await prisma.sessionEvent.create({
data: {
type: "pageSubmission",
data: {
pageName: event.data.pageName,
submission: event.data.submission,
},
submissionSession: { connect: { id: event.data.submissionSessionId } },
},
});
capturePosthogEvent(form.owner.id, "pageSubmission received", {
formId,
formType: form.formType,
});
sendTelemetry("pageSubmission received");
if ("pages" in schema) {
const pages = schema.pages.filter((page) => page.type === "form");
const indexOfPage = pages.findIndex((page) => page.name === pageName);
if (indexOfPage === pages.length - 1) {
processApiEvent(
{
...event,
type: "formCompleted",
data: {
submissionSessionId: event.data.submissionSessionId,
},
},
formId
);
}
}
} else if (event.type === "formCompleted") {
await prisma.sessionEvent.create({
data: {
type: "formCompleted",
data: {},
submissionSession: { connect: { id: event.data.submissionSessionId } },
},
});
capturePosthogEvent(form.owner.id, "pageSubmission received", {
formId,
formType: form.formType,
});
sendTelemetry("formCompleted received");
} else if (event.type === "updateSchema") {
const data = { schema: event.data, updatedAt: new Date() };
await prisma.form.update({
where: { id: formId },
data,
});
} else {
throw Error(`apiEvents: unsupported event type in event ${JSON.stringify(event)}`);
}
// handle integrations
const pipelines = await prisma.pipeline.findMany({
where: {
form: { id: formId },
enabled: true,
},
orderBy: [
{
createdAt: "desc",
},
],
});
for (const pipeline of pipelines) {
if (pipeline.type === "WEBHOOK") {
handleWebhook(pipeline, event);
}
if (pipeline.type === "EMAIL_NOTIFICATION") {
if (!pipeline.data.hasOwnProperty("email")) return;
const { email } = pipeline.data.valueOf() as { email: string };
if (event.type === "pageSubmission" && pipeline.events.includes("PAGE_SUBMISSION")) {
await sendPageSubmissionEmail(email, form.name, pipeline.formId);
} else if (event.type === "formCompleted" && pipeline.events.includes("FORM_COMPLETED")) {
await sendFormSubmissionEmail(email, form.name, pipeline.formId);
}
}
}
};

View File

@@ -1,28 +0,0 @@
import { compare, hash } from "bcryptjs";
export async function hashPassword(password: string) {
const hashedPassword = await hash(password, 12);
return hashedPassword;
}
export async function verifyPassword(password: string, hashedPassword: string) {
const isValid = await compare(password, hashedPassword);
return isValid;
}
export function requireAuthentication(gssp) {
return async (context) => {
const { req, resolvedUrl } = context;
const token = req.cookies.userToken;
if (!token) {
return {
redirect: {
destination: `/auth/signin?callbackUrl=${encodeURIComponent(resolvedUrl)}`,
statusCode: 302,
},
};
}
return await gssp(context); // Continue on to call `getServerSideProps` logic
};
}

View File

@@ -1,98 +0,0 @@
import { createToken } from "./jwt";
const nodemailer = require("nodemailer");
interface sendEmailData {
to: string;
subject: string;
text?: string;
html: string;
}
export const sendEmail = async (emailData: sendEmailData) => {
let transporter = nodemailer.createTransport({
host: process.env.SMTP_HOST,
port: process.env.SMTP_PORT,
secure: process.env.SMTP_SECURE_ENABLED === "1", // true for 465, false for other ports
auth: {
user: process.env.SMTP_USER,
pass: process.env.SMTP_PASSWORD,
},
// logger: true,
// debug: true,
});
const emailDefaults = {
from: `snoopForms <${process.env.MAIL_FROM || "noreply@snoopforms.com"}>`,
};
await transporter.sendMail({ ...emailDefaults, ...emailData });
};
export const sendVerificationEmail = async (user) => {
const token = createToken(user.id, user.email, {
expiresIn: "1d",
});
const verifyLink = `${process.env.NEXTAUTH_URL}/auth/verify?token=${encodeURIComponent(token)}`;
const verificationRequestLink = `${
process.env.NEXTAUTH_URL
}/auth/verification-requested?email=${encodeURIComponent(user.email)}`;
await sendEmail({
to: user.email,
subject: "Welcome to snoopForms",
html: `Welcome to snoopForms!<br/><br/>To verify your email address and start using snoopForms please click this link:<br/>
<a href="${verifyLink}">${verifyLink}</a><br/>
<br/>
The link is valid for one day. If it has expired please request a new token here:<br/>
<a href="${verificationRequestLink}">${verificationRequestLink}</a><br/>
<br/>
Your snoopForms Team`,
});
};
export const sendForgotPasswordEmail = async (user) => {
const token = createToken(user.id, user.email, {
expiresIn: "1d",
});
const verifyLink = `${process.env.NEXTAUTH_URL}/auth/reset-password?token=${encodeURIComponent(token)}`;
await sendEmail({
to: user.email,
subject: "Reset your snoopForms password",
html: `You have requested a link to change your password. You can do this through the link below:<br/>
<a href="${verifyLink}">${verifyLink}</a><br/>
<br/>
The link is valid for 24 hours. If you didn't request this, please ignore this email.<br/>
<br/>
Your password won't change until you access the link above and create a new one.<br/>
<br/>
Your snoopForms Team`,
});
};
export const sendPasswordResetNotifyEmail = async (user) => {
await sendEmail({
to: user.email,
subject: "Your snoopForms password has been changed",
html: `We're contacting you to notify you that your password has been changed.<br/>
<br/>
Your snoopForms Team`,
});
};
export const sendPageSubmissionEmail = async (email: string, formName: string, formId: string) => {
await sendEmail({
to: email,
subject: `${formName} new page submission`,
html: `Hey, someone just filled out a page of ${formName} in Formbricks.<br/>
Click <a href="${process.env.NEXTAUTH_URL}/forms/${formId}/results/responses">here</a> to see new submission`,
});
};
export const sendFormSubmissionEmail = async (email: string, formName: string, formId: string) => {
await sendEmail({
to: email,
subject: `${formName} new submission`,
html: `Hey, someone just filled out ${formName} in Formbricks.<br/>
<br/>
Click <a href="${process.env.NEXTAUTH_URL}/forms/${formId}/results/responses">here</a> to see new submission`,
});
};

View File

@@ -1,10 +0,0 @@
export const getEventName = (eventType: string) => {
switch (eventType) {
case "pageSubmission":
return "Page Submission";
case "formCompleted":
return "Form Completed";
default:
return eventType;
}
};

View File

@@ -1,91 +0,0 @@
import useSWR from "swr";
import { fetcher } from "./utils";
export const useForms = () => {
const { data, error, mutate } = useSWR(`/api/forms/`, fetcher);
return {
forms: data,
isLoadingForms: !error && !data,
isErrorForms: error,
mutateForms: mutate,
};
};
export const useForm = (id: string) => {
const { data, error, mutate } = useSWR(`/api/forms/${id}/`, fetcher);
return {
form: data,
isLoadingForm: !error && !data,
isErrorForm: error,
mutateForm: mutate,
};
};
export const persistForm = async (form) => {
try {
await fetch(`/api/forms/${form.id}/`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(form),
});
} catch (error) {
console.error(error);
}
};
export const createForm = async (form = {}) => {
try {
const res = await fetch(`/api/forms`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(form),
});
return await res.json();
} catch (error) {
console.error(error);
throw Error(`createForm: unable to create form: ${error.message}`);
}
};
export const getFormElementFieldSetter = (
form: any,
mutateForm: (any, boolean?) => void,
pageId: string,
elementId: string
) => {
return (input, field, parentField = "") =>
setFormElementField(form, mutateForm, pageId, elementId, input, field, parentField);
};
export const setFormElementField = (
form: any,
mutateForm: (any, boolean?) => void,
pageId: string,
elementId: string,
input: string | number,
field: string,
parentField: string = ""
) => {
const updatedForm = JSON.parse(JSON.stringify(form));
const elementIdx = getFormPage(updatedForm, pageId).elements.findIndex((e) => e.id === elementId);
if (typeof elementIdx === "undefined") {
throw Error(`setFormElementField: unable to find element with id ${elementId}`);
}
if (parentField !== "") {
getFormPage(updatedForm, pageId).elements[elementIdx][parentField][field] = input;
} else {
getFormPage(updatedForm, pageId).elements[elementIdx][field] = input;
}
mutateForm(updatedForm, false);
return updatedForm;
};
export const getFormPage = (form, pageId) => {
const page = form.pages.find((p) => p.id === pageId);
if (typeof page === "undefined") {
throw Error(`getFormPage: unable to find page with id ${pageId}`);
}
return page;
};

View File

@@ -1,24 +0,0 @@
import jwt from "jsonwebtoken";
import { prisma } from "@formbricks/database";
export function createToken(userId, userEmail, options = {}) {
return jwt.sign({ id: userId }, process.env.NEXTAUTH_SECRET + userEmail, options);
}
export async function verifyToken(token, userEmail = "") {
if (!userEmail) {
const { id } = jwt.decode(token);
const foundUser = await prisma.user.findUnique({
where: { id },
});
if (!foundUser) {
return null;
}
userEmail = foundUser.email;
}
return jwt.verify(token, process.env.NEXTAUTH_SECRET + userEmail);
}

View File

@@ -1,47 +0,0 @@
import { DocumentMagnifyingGlassIcon, CommandLineIcon } from "@heroicons/react/24/outline";
import { useRouter } from "next/router";
import { FaReact } from "react-icons/fa";
export const useCodeSecondNavigation = (formId) => {
const router = useRouter();
return [
{
id: "formId",
onClick: () => {
router.push(`/forms/${formId}/form`);
},
Icon: CommandLineIcon,
label: "Form ID",
},
{
id: "react",
onClick: () => {
router.push(`/forms/${formId}/form/react`);
},
Icon: FaReact,
label: "React",
},
{
id: "reactNative",
onClick: () => {},
Icon: FaReact,
label: "React Native",
disabled: true,
},
{
id: "vueJs",
onClick: () => {},
Icon: CommandLineIcon,
label: "VueJs",
disabled: true,
},
{
id: "docs",
onClick: () => {
window.open("https://docs.snoopforms.com", "_ blank");
},
Icon: DocumentMagnifyingGlassIcon,
label: "Docs",
},
];
};

View File

@@ -1,17 +0,0 @@
export const useFormMenuSteps = (formId) => [
{
id: "form",
name: "Form",
href: `/forms/${formId}/form`,
},
{
id: "pipelines",
name: "Pipelines",
href: `/forms/${formId}/pipelines`,
},
{
id: "results",
name: "Results",
href: `/forms/${formId}/results/summary`,
},
];

View File

@@ -1,32 +0,0 @@
import { ChartBarIcon, InboxIcon, ArrowTrendingUpIcon } from "@heroicons/react/24/outline";
import { useRouter } from "next/router";
export const useFormResultsSecondNavigation = (formId) => {
const router = useRouter();
return [
{
id: "summary",
onClick: () => {
router.push(`/forms/${formId}/results/summary`);
},
Icon: ChartBarIcon,
label: "Summary",
},
{
id: "responses",
onClick: () => {
router.push(`/forms/${formId}/results/responses`);
},
Icon: InboxIcon,
label: "Responses",
},
{
id: "insights",
onClick: () => {
router.push(`/forms/${formId}/results/insights`);
},
Icon: ArrowTrendingUpIcon,
label: "Insights",
},
];
};

View File

@@ -1,50 +0,0 @@
import useSWR from "swr";
import { fetcher } from "./utils";
export const useNoCodeForm = (formId) => {
const { data, error, mutate } = useSWR(`/api/forms/${formId}/nocodeform`, fetcher);
return {
noCodeForm: data,
isLoadingNoCodeForm: !error && !data,
isErrorNoCodeForm: error,
mutateNoCodeForm: mutate,
};
};
export const useNoCodeFormPublic = (formId) => {
const { data, error, mutate } = useSWR(`/api/public/forms/${formId}/nocodeform`, fetcher);
return {
noCodeForm: data,
isLoadingNoCodeForm: !error && !data,
isErrorNoCodeForm: error,
mutateNoCodeForm: mutate,
};
};
export const createNoCodeForm = async (formId) => {
try {
const res = await fetch(`/api/forms/${formId}/nocodeform`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({}),
});
return await res.json();
} catch (error) {
console.error(error);
throw Error(`createNoCodeForm: unable to create noCodeForm: ${error.message}`);
}
};
export const persistNoCodeForm = async (noCodeForm) => {
try {
await fetch(`/api/forms/${noCodeForm.formId}/nocodeform`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(noCodeForm),
});
} catch (error) {
console.error(error);
}
};

View File

@@ -1,62 +0,0 @@
import useSWR from "swr";
import { fetcher } from "./utils";
export const usePipeline = (formId: string, pipelineId: string) => {
const { data, error, mutate } = useSWR(() => `/api/forms/${formId}/pipelines/${pipelineId}`, fetcher);
return {
pipeline: data,
isLoadingPipeline: !error && !data,
isErrorPipeline: error,
mutatePipeline: mutate,
};
};
export const usePipelines = (formId: string) => {
const { data, error, mutate } = useSWR(() => `/api/forms/${formId}/pipelines`, fetcher);
return {
pipelines: data,
isLoadingPipelines: !error && !data,
isErrorPipelines: error,
mutatePipelines: mutate,
};
};
export const persistPipeline = async (pipeline) => {
try {
await fetch(`/api/forms/${pipeline.formId}/pipelines/${pipeline.id}`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(pipeline),
});
} catch (error) {
console.error(error);
}
};
export const createPipeline = async (formId, pipeline) => {
try {
const res = await fetch(`/api/forms/${formId}/pipelines`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(pipeline),
});
return await res.json();
} catch (error) {
console.error(error);
throw Error(`create Pipeline: unable to create pipeline: ${error.message}`);
}
};
export const deletePipeline = async (formId, pipelineId) => {
try {
const res = await fetch(`/api/forms/${formId}/pipelines/${pipelineId}`, {
method: "DELETE",
});
return await res.json();
} catch (error) {
console.error(error);
throw Error(`delete Pipeline: unable to delete pipeline: ${error.message}`);
}
};

View File

@@ -1,27 +0,0 @@
import { hashString } from "./utils";
const enabled =
process.env.NODE_ENV === "production" && process.env.POSTHOG_API_HOST && process.env.POSTHOG_API_KEY;
export const capturePosthogEvent = async (userId, eventName, properties = {}) => {
if (!enabled) {
return;
}
try {
await fetch(`${process.env.POSTHOG_API_HOST}/capture/`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
api_key: process.env.POSTHOG_API_KEY,
event: eventName,
properties: {
distinct_id: hashString(userId.toString()),
...properties,
},
timestamp: new Date().toISOString(),
}),
});
} catch (error) {
console.error("error sending posthog event:", error);
}
};

View File

@@ -1,122 +0,0 @@
import useSWR from "swr";
import { Schema, SubmissionSession, SubmissionSummary } from "./types";
import { fetcher } from "./utils";
export const useSubmissionSessions = (formId: string) => {
const { data, error, mutate } = useSWR(() => `/api/forms/${formId}/submissionSessions`, fetcher);
return {
submissionSessions: data,
isLoadingSubmissionSessions: !error && !data,
isErrorSubmissionSessions: error,
mutateSubmissionSessions: mutate,
};
};
// fill the schema with the values provided by the user
export const getSubmission = (submissionSession, schema) => {
if (!schema) return {};
// create new submission
const submission = {
id: submissionSession.id,
createdAt: submissionSession.createdAt,
pages: [],
};
if (submissionSession.events.length > 0) {
// iterate through schema pages to fill submission
for (const page of schema.pages) {
// new submission page
const submissionPage = {
name: page.name,
type: page.type,
elements: page.elements ? JSON.parse(JSON.stringify(page.elements)) : [],
};
// search for elements in schema pages of type "form" and fill their value into the submission
if (page.type === "form") {
const pageSubmission = submissionSession.events.find(
(s) => s.type === "pageSubmission" && s.data?.pageName === page.name
);
if (typeof pageSubmission !== "undefined") {
for (const [elementIdx, element] of page.elements.entries()) {
if (element.type !== "submit") {
if ("submission" in pageSubmission.data && element.name in pageSubmission.data?.submission) {
submissionPage.elements[elementIdx].value = pageSubmission.data.submission[element.name];
}
}
}
}
}
submission.pages.push(submissionPage);
}
}
return submission;
};
export const getSubmissionAnalytics = (submissionSessions: SubmissionSession[]) => {
let totalSubmissions = 0;
let lastSubmissionAt = null;
for (const submissionSession of submissionSessions) {
// collect unique users
if (submissionSession.events.length > 0) {
totalSubmissions += 1;
const lastSubmission = submissionSession.events[submissionSession.events.length - 1];
if (!lastSubmissionAt) {
lastSubmissionAt = lastSubmission.createdAt;
} else if (Date.parse(lastSubmission.createdAt) > Date.parse(lastSubmissionAt)) {
lastSubmissionAt = lastSubmission.createdAt;
}
}
}
return {
lastSubmissionAt,
totalSubmissions: totalSubmissions,
};
};
export const getSubmissionSummary = (submissionSessions: SubmissionSession[], schema: Schema) => {
if (!schema) return;
const summary: SubmissionSummary = JSON.parse(JSON.stringify(schema));
// iterate through SubmissionSessions and add values to summary
for (const submissionSession of submissionSessions) {
for (const submissionEvent of submissionSession.events) {
if (submissionEvent.type === "pageSubmission") {
const summaryPage = summary.pages.find((p) => p.name === submissionEvent.data.pageName);
if (summaryPage.type === "form" && submissionEvent.data.submission) {
for (const [elementName, elementValue] of Object.entries(submissionEvent.data.submission)) {
const elementInSummary = summaryPage.elements.find((e) => e.name === elementName);
if (typeof elementInSummary !== "undefined") {
if (
["email", "number", "phone", "text", "textarea", "website"].includes(elementInSummary.type)
) {
if (!("summary" in elementInSummary)) {
elementInSummary.summary = [];
}
elementInSummary.summary.push(elementValue);
} else if (elementInSummary.type === "checkbox") {
// checkbox values are a list of values
for (const value of elementValue) {
const optionInSummary = elementInSummary.options.find((o) => o.value === value);
if (typeof optionInSummary !== "undefined") {
if (!("summary" in optionInSummary)) {
optionInSummary.summary = 0;
}
optionInSummary.summary += 1;
}
}
} else if (elementInSummary.type === "radio") {
const optionInSummary = elementInSummary.options.find((o) => o.value === elementValue);
if (typeof optionInSummary !== "undefined") {
if (!("summary" in optionInSummary)) {
optionInSummary.summary = 0;
}
optionInSummary.summary += 1;
}
}
}
}
}
}
}
}
return summary;
};

View File

@@ -1,31 +0,0 @@
import { hashString } from "./utils";
/* We use this telemetry service to better understand how snoopForms is being used
and how we can improve it. All data including the IP address is collected anonymously
and we cannot trace anything back to you or your customers. If you still want to
disable telemetry, set the environment variable TELEMETRY_DISABLED=1 */
export const sendTelemetry = async (eventName: string) => {
if (
process.env.TELEMETRY_DISABLED !== "1" &&
process.env.NODE_ENV === "production" &&
process.env.NEXTAUTH_URL !== "http://localhost:3000"
) {
try {
await fetch("https://posthog.snoopforms.com/capture/", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
api_key: "phc_BTq4eagaCzPyUSURXVYwlScTQRvcmBDXjYh7OG6kiqw",
event: eventName,
properties: {
distinct_id: hashString(process.env.NEXTAUTH_URL),
},
timestamp: new Date().toISOString(),
}),
});
} catch (error) {
console.log("error sending telemetry:", error);
}
}
};

View File

@@ -1,145 +0,0 @@
export type Form = {
id: string;
createdAt: string;
updatedAt: string;
title: string;
finishedOnboarding: boolean;
published: boolean;
colorPrimary: string;
owner: string;
elements: [Element];
elementsDraft: [Element];
};
export type AnswerSession = {
id: string;
createdAt: Date;
updatedAt: Date;
answers: Answer[];
};
export type Answer = {
id: string;
createdAt: Date;
updatedAt: Date;
elementId: string;
data: AnswerData;
};
export type AnswerData = {
value: string | string[];
};
export type Schema = {
pages: SchemaPage[];
};
export type SchemaPage = {
type: "form" | "thankyou";
name: string;
elements: SchemaElement[];
};
export type SnoopType =
| "checkbox"
| "email"
| "number"
| "phone"
| "radio"
| "submit"
| "text"
| "textarea"
| "website";
export type SchemaElement = {
name: string;
type: SnoopType;
label?: string;
options?: SchemaOption[];
};
export type SchemaOption = {
label: string;
value: string;
};
export type SubmissionSummary = {
pages: SubmissionSummaryPage[];
};
export type SubmissionSummaryPage = {
type: "form" | "thankyou";
name: string;
elements: SubmissionSummaryElement[];
};
export type SubmissionSummaryElement = {
name: string;
type: SnoopType;
label?: string;
summary?: string[];
options?: SubmissionSummaryOption[];
};
export type SubmissionSummaryOption = {
label: string;
value: string;
summary: number;
};
export type submissionEvent = {
id: string;
createdAt: string;
updatedAt: string;
type: "pageSubmission";
data: {
submissionSessionId: string;
pageName: string;
submission: { [key: string]: string };
};
};
export type formCompletedEvent = {
id: string;
createdAt: string;
updatedAt: string;
type: "formCompleted";
data: {
submissionSessionId: string;
};
};
export type updateSchemaEvent = {
id: string;
createdAt: string;
updatedAt: string;
type: "updateSchema";
data: Schema;
};
export type ApiEvent = submissionEvent | formCompletedEvent | updateSchemaEvent;
export type WebhookEvent = Event & { formId: string; timestamp: string };
export type SubmissionSession = {
id: string;
createdAt: string;
updatedAt: string;
form?: any;
userFingerprint: string;
events: ApiEvent[];
};
export type Submission = {
id?: string;
createdAt?: string;
pages?: SubmissionPage[];
};
type SubmissionPage = {
name: string;
type: string;
elements: SubmissionPageElement[];
};
type SubmissionPageElement = SchemaElement & { value: string };

View File

@@ -1,83 +0,0 @@
import { hashPassword } from "./auth";
export const createUser = async (firstname, lastname, email, password) => {
const hashedPassword = await hashPassword(password);
try {
const res = await fetch(`/api/public/users`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
firstname,
lastname,
email,
password: hashedPassword,
}),
});
if (res.status !== 200) {
const json = await res.json();
throw Error(json.error);
}
return await res.json();
} catch (error) {
throw Error(`${error.message}`);
}
};
export const resendVerificationEmail = async (email) => {
try {
const res = await fetch(`/api/public/users/verification-email`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
email,
}),
});
if (res.status !== 200) {
const json = await res.json();
throw Error(json.error);
}
return await res.json();
} catch (error) {
throw Error(`${error.message}`);
}
};
export const forgotPassword = async (email: string) => {
try {
const res = await fetch(`/api/public/users/forgot-password`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
email,
}),
});
if (res.status !== 200) {
const json = await res.json();
throw Error(json.error);
}
return await res.json();
} catch (error) {
throw Error(`${error.message}`);
}
};
export const resetPassword = async (token, password) => {
const hashedPassword = await hashPassword(password);
try {
const res = await fetch(`/api/public/users/reset-password`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
token,
hashedPassword,
}),
});
if (res.status !== 200) {
const json = await res.json();
throw Error(json.error);
}
return await res.json();
} catch (error) {
throw Error(`${error.message}`);
}
};

View File

@@ -1,130 +0,0 @@
import intlFormat from "date-fns/intlFormat";
import { formatDistance } from "date-fns";
import crypto from "crypto";
export const fetcher = async (url) => {
const res = await fetch(url);
// If the status code is not in the range 200-299,
// we still try to parse and throw it.
if (!res.ok) {
const error: any = new Error("An error occurred while fetching the data.");
// Attach extra info to the error object.
error.info = await res.json();
error.status = res.status;
throw error;
}
return res.json();
};
export const shuffle = (array) => {
array = [...array];
let currentIndex = array.length,
randomIndex;
while (0 !== currentIndex) {
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex--;
[array[currentIndex], array[randomIndex]] = [array[randomIndex], array[currentIndex]];
}
return array;
};
export const classNames = (...classes) => {
return classes.filter(Boolean).join(" ");
};
export const slugify = (...args: (string | number)[]): string => {
const value = args.join(" ");
return value
.normalize("NFD") // split an accented letter in the base letter and the acent
.replace(/[\u0300-\u036f]/g, "") // remove all previously split accents
.toLowerCase()
.trim()
.replace(/[^a-z0-9 ]/g, "") // remove all chars not letters, numbers and spaces (to be replaced)
.replace(/\s+/g, "-"); // separator
};
export const getFieldSetter = (obj, objSetter) => {
return (input, field) => setField(obj, objSetter, input, field);
};
export const setField = (obj, objSetter, input, field) => {
let newData = JSON.parse(JSON.stringify(obj));
newData[field] = input;
objSetter(newData, false);
return newData;
};
export const convertDateString = (dateString: string) => {
const date = new Date(dateString);
return intlFormat(
date,
{
year: "numeric",
month: "long",
day: "numeric",
},
{
locale: "en",
}
);
};
export const convertDateTimeString = (dateString: string) => {
const date = new Date(dateString);
return intlFormat(
date,
{
weekday: "long",
year: "numeric",
month: "long",
day: "numeric",
hour: "numeric",
minute: "2-digit",
},
{
locale: "en",
}
);
};
export const convertTimeString = (dateString: string) => {
const date = new Date(dateString);
return intlFormat(
date,
{
hour: "numeric",
minute: "2-digit",
second: "2-digit",
},
{
locale: "en",
}
);
};
export const timeSince = (dateString: string) => {
const date = new Date(dateString);
return formatDistance(date, new Date(), {
addSuffix: true,
});
};
export const generateId = (length) => {
let result = "";
const characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
const charactersLength = characters.length;
for (let i = 0; i < length; i++) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));
}
return result;
};
export const hashString = (string: string) => {
return crypto.createHash("sha256").update(string).digest("hex");
};

View File

@@ -1,5 +0,0 @@
/// <reference types="next" />
/// <reference types="next/image-types/global" />
// NOTE: This file should not be edited
// see https://nextjs.org/docs/basic-features/typescript for more information.

View File

@@ -1,31 +0,0 @@
/** @type {import('next').NextConfig} */
var path = require("path");
const nextConfig = {
reactStrictMode: false,
output: "standalone",
experimental: {
outputFileTracingRoot: path.join(__dirname, "../../"),
},
async redirects() {
return [
{
source: "/",
destination: "/forms/",
permanent: false,
},
{
source: "/forms/:id",
destination: "/forms/:id/form",
permanent: false,
},
];
},
webpack: (config, { buildId, dev, isServer, defaultLoaders, webpack }) => {
config.resolve.alias["react"] = path.resolve("./node_modules/react");
// Important: return the modified config
return config;
},
};
module.exports = nextConfig;

View File

@@ -1,65 +0,0 @@
{
"name": "@formbricks/web",
"version": "1.0.1",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint"
},
"overrides": {
"@types/react": "^18.0.21"
},
"dependencies": {
"@editorjs/editorjs": "^2.25.0",
"@editorjs/header": "^2.6.2",
"@editorjs/paragraph": "^2.8.0",
"@formbricks/ui": "workspace:*",
"@headlessui/react": "^1.7.3",
"@heroicons/react": "^2.0.12",
"@snoopforms/react": "workspace:*",
"@vercel/analytics": "^0.1.1",
"bcryptjs": "^2.4.3",
"chart.js": "^3.9.1",
"crypto": "^1.0.1",
"date-fns": "^2.29.3",
"editorjs-drag-drop": "^1.1.7",
"editorjs-undo": "^2.0.9",
"highlight.js": "^11.6.0",
"json2csv": "^5.0.7",
"jsonwebtoken": "^8.5.1",
"next": "13.0.0",
"next-auth": "^4.14.0",
"nextjs-cors": "^2.1.1",
"nodemailer": "^6.8.0",
"react": "18.2.0",
"react-chartjs-2": "^4.3.1",
"react-dom": "18.2.0",
"react-icons": "^4.6.0",
"react-loader-spinner": "^5.3.4",
"react-toastify": "^9.0.8",
"sanitize-html": "^2.7.2",
"sharp": "^0.31.1",
"swr": "^1.3.0",
"uuid": "^9.0.0"
},
"devDependencies": {
"@formbricks/database": "workspace:*",
"@formbricks/tailwind-config": "workspace:*",
"@formbricks/tsconfig": "workspace:*",
"@tailwindcss/forms": "^0.5.3",
"@tailwindcss/line-clamp": "^0.4.2",
"@tailwindcss/typography": "^0.5.7",
"@types/bcryptjs": "^2.4.2",
"@types/node": "18.11.0",
"@types/react": "^18.0.21",
"autoprefixer": "^10.4.12",
"eslint": "8.25.0",
"eslint-config-formbricks": "workspace:*",
"postcss": "^8.4.18",
"tailwindcss": "^3.1.8",
"ts-node": "^10.9.1",
"typescript": "4.8.4"
}
}

View File

@@ -1,30 +0,0 @@
import Image from "next/legacy/image";
import BaseLayoutUnauthorized from "../components/layout/BaseLayoutUnauthorized";
import Link from "next/link";
export default function Error404Page() {
return (
<BaseLayoutUnauthorized title="Page not found">
<div className="bg-ui-gray-light flex min-h-screen">
<div className="mx-auto flex flex-1 flex-col justify-center px-4 py-12 sm:px-6 lg:flex-none lg:px-20 xl:px-24">
<div className="mx-auto w-full max-w-sm p-8 lg:w-96">
<div>
<Image src="/img/snoopforms-logo.svg" alt="snoopForms logo" width={500} height={89} />
</div>
<div className="mt-8">
<h1 className="leading-2 mb-4 text-center font-bold">This page does not exist!</h1>
<p className="text-center">
Sorry, the page you were looking for could not be found. Please make sure the URL is correct
or{" "}
<span className="underline">
<Link href="/">go back to the homepage</Link>
</span>
.
</p>
</div>
</div>
</div>
</div>
</BaseLayoutUnauthorized>
);
}

View File

@@ -1,20 +0,0 @@
import { Analytics } from "@vercel/analytics/react";
import "highlight.js/styles/tokyo-night-dark.css";
import { SessionProvider } from "next-auth/react";
import { ToastContainer } from "react-toastify";
import "../styles/editorjs.css";
// import "@formbricks/ui/styles.css";
import "../styles/globals.css";
import "../styles/toastify.css";
function SnoopApp({ Component, pageProps: { session, ...pageProps } }) {
return (
<SessionProvider session={session}>
<Component {...pageProps} />
<ToastContainer />
<Analytics />
</SessionProvider>
);
}
export default SnoopApp;

View File

@@ -1,20 +0,0 @@
import { Html, Head, Main, NextScript } from "next/document";
export default function Document() {
return (
<Html className="scroll-smooth">
<Head>
<link rel="icon" type="image/png" sizes="32x32" href="/favicons/favicon-32x32.png" />
<link rel="icon" type="image/png" sizes="16x16" href="/favicons/favicon-16x16.png" />
<link rel="apple-touch-icon" sizes="180x180" href="/favicons/apple-touch-icon.png" />
<link rel="manifest" href="/favicons/site.webmanifest" />
<link rel="mask-icon" href="/favicons/safari-pinned-tab.svg" color="#5bbad5" />
<meta name="theme-color" content="#0D0010" />
</Head>
<body>
<Main />
<NextScript />
</body>
</Html>
);
}

View File

@@ -1,138 +0,0 @@
import { NextApiRequest, NextApiResponse } from "next";
import NextAuth from "next-auth";
import CredentialsProvider from "next-auth/providers/credentials";
import { prisma } from "@formbricks/database";
import { verifyPassword } from "../../../lib/auth";
import { verifyToken } from "../../../lib/jwt";
export default async function auth(req: NextApiRequest, res: NextApiResponse) {
return await NextAuth(req, res, {
providers: [
CredentialsProvider({
id: "credentials",
// The name to display on the sign in form (e.g. "Sign in with...")
name: "Credentials",
// The credentials is used to generate a suitable form on the sign in page.
// You can specify whatever fields you are expecting to be submitted.
// e.g. domain, username, password, 2FA token, etc.
// You can pass any HTML attribute to the <input> tag through the object.
credentials: {
email: {
label: "Email Address",
type: "email",
placeholder: "Your email address",
},
password: {
label: "Password",
type: "password",
placeholder: "Your password",
},
},
async authorize(credentials, _req) {
let user;
try {
user = await prisma.user.findUnique({
where: {
email: credentials?.email,
},
});
} catch (e) {
console.error(e);
throw Error("Internal server error. Please try again later");
}
if (!user) {
throw new Error("User not found");
}
if (!credentials) {
throw new Error("No credentials");
}
if (!user.password) {
throw new Error("Incorrect password");
}
const isValid = await verifyPassword(credentials.password, user.password);
if (!isValid) {
throw new Error("Incorrect password");
}
return {
id: user.id,
email: user.email,
firstname: user.firstname,
lastname: user.firstname,
emailVerified: user.emailVerified,
};
},
}),
CredentialsProvider({
id: "token",
// The name to display on the sign in form (e.g. "Sign in with...")
name: "Token",
// The credentials is used to generate a suitable form on the sign in page.
// You can specify whatever fields you are expecting to be submitted.
// e.g. domain, username, password, 2FA token, etc.
// You can pass any HTML attribute to the <input> tag through the object.
credentials: {
token: {
label: "Verification Token",
type: "string",
},
},
async authorize(credentials, _req) {
let user;
try {
const { id } = await verifyToken(credentials?.token);
user = await prisma.user.findUnique({
where: {
id: id,
},
});
} catch (e) {
console.error(e);
throw new Error("Token is not valid or expired");
}
if (!user) {
throw new Error("User not found");
}
if (user.emailVerified) {
throw new Error("Email already verified");
}
user = await prisma.user.update({
where: {
id: user.id,
},
data: { emailVerified: new Date().toISOString() },
});
return {
id: user.id,
email: user.email,
firstname: user.firstname,
lastname: user.firstname,
emailVerified: user.emailVerified,
};
},
}),
],
callbacks: {
async signIn({ user }: any) {
if (user.emailVerified || process.env.NEXT_PUBLIC_EMAIL_VERIFICATION_DISABLED === "1") {
return true;
} else {
// Return false to display a default error message or you can return a URL to redirect to
return `/auth/verification-requested?email=${encodeURIComponent(user.email)}`;
}
},
},
pages: {
signIn: "/auth/signin",
signOut: "/auth/logout",
error: "/auth/signin", // Error code passed in query string as ?error=
},
});
}

View File

@@ -1,47 +0,0 @@
import type { NextApiRequest, NextApiResponse } from "next";
import NextCors from "nextjs-cors";
import { processApiEvent, validateEvents } from "../../../../lib/apiEvents";
///api/submissionSession
export default async function handle(req: NextApiRequest, res: NextApiResponse) {
await NextCors(req, res, {
// Options
methods: ["GET", "HEAD", "PUT", "PATCH", "POST", "DELETE"],
origin: "*",
optionsSuccessStatus: 200, // some legacy browsers (IE11, various SmartTVs) choke on 204
});
const formId = req.query.id.toString();
// POST /api/forms/:id/schema
// Updates a form schema
// Required fields in body: schema
// Optional fields in body: -
if (req.method === "POST") {
const { events } = req.body;
const error = validateEvents(events);
if (error) {
const { status, message } = error;
return res.status(status).json({ error: message });
}
for (const event of events) {
fetch(
`${
process.env.VERCEL_URL ? `https://${process.env.VERCEL_URL}` : process.env.NEXTAUTH_URL
}/api/forms/${formId}/handleEvent`,
{
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
event,
}),
}
);
}
res.json({ success: true });
}
// Unknown HTTP Method
else {
throw new Error(`The HTTP ${req.method} method is not supported by this route.`);
}
}

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