Initial commit

This commit is contained in:
Nariman Jelveh 2024-03-02 18:39:14 -08:00
commit fa42b0871e
290 changed files with 99553 additions and 0 deletions

2
.gitattributes vendored Normal file
View File

@ -0,0 +1,2 @@
# Auto detect text files and perform LF normalization
* text=auto

5
.gitignore vendored Normal file
View File

@ -0,0 +1,5 @@
.DS_Store
node_modules/
*.zip
*.tgz
license.config.json

661
LICENSE.txt Normal file
View File

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

78
README.md Normal file
View File

@ -0,0 +1,78 @@
<h3 align="center"><img width="80" alt="Puter.com, The Personal Cloud Computer: All your files, apps, and games in one place accessible from anywhere at any time." src="https://github.com/HeyPuter/gui/assets/1715019/ffdc7427-4ed7-41c0-b539-ae7285bd0ffe"></h3>
<h3 align="center">Desktop Environment in the Browser!</h3>
<p align="center">
<a href="https://puter.com/"><strong>« LIVE DEMO »</strong></a>
<br />
<br />
<a href="https://puter.com">Puter.com</a>
·
<a href="https://docs.puter.com" target="_blank">SDK</a>
·
<a href="https://discord.com/invite/PQcx7Teh8u">Discord</a>
·
<a href="https://reddit.com/r/puter">Reddit</a>
·
<a href="https://twitter.com/HeyPuter">X (Twitter)</a>
</p>
<h3 align="center"><img width="700" style="border-radius:5px;" alt="screenshot" src="https://github.com/HeyPuter/gui/assets/1715019/a1579d6a-6a42-4fec-9af2-ca0a31326850"></h3>
<br/>
## Getting Started
```bash
git clone https://github.com/HeyPuter/puter.com
cd puter.com
npm install
npm start
```
This will launch Puter in development mode at http://localhost:4000 (or the next available port).
<br/>
## Deploy to Production
Here's a detailed guide on how to run Puter in production: [docs/prod.md](docs/prod.md)
<br/>
## FAQ
### ❓ What's the use case for Puter?
Puter can be used as:
- An alternative to Dropbox, Google Drive, OneDrive, etc. with a fresh interface and powerful features.
- Remote desktop environment for remote servers and workstations.
- A platform for building and hosting websites, web apps, and games.
- A friendly, open-source project and community to learn about web development, cloud computing, distributed systems, and much more!
### ❓ Why isn't Puter built with React, Angular, Vue, etc.?
For performance reasons, Puter is built with vanilla JavaScript and jQuery. Additionally, we'd like to avoid complex abstractions and to remain in control of the entire stack, as much as possible.
Also partly inspired by some of our favorite projects that are not built with frameworks: [VSCode](https://github.com/microsoft/vscode), [Photopea](https://www.photopea.com/), and [OnlyOffice](https://www.onlyoffice.com/).
### ❓ Why jQuery?
Puter interacts directly with the DOM and jQuery provides an elegant yet powerful API to manipulate the DOM, handle events, and much more. It's also fast, mature, and battle-tested.
<br/>
## Credits
The default wallpaper is created by [Milad Fakurian](https://unsplash.com/photos/blue-orange-and-yellow-wallpaper-E8Ufcyxz514) and published on [Unsplash](https://unsplash.com/).
Icons by [Papirus](https://github.com/PapirusDevelopmentTeam/papirus-icon-theme) under GPL-3.0 license.
Icons by [Iconoir](https://iconoir.com/) under MIT license.
Icons by [Elementary Icons](https://github.com/elementary/icons) under GPL-3.0 license.
Icons by [Tabler Icons](https://tabler.io/) under MIT license.
Icons by [bootstrap-icons](https://icons.getbootstrap.com/) under MIT license.

3
build.js Normal file
View File

@ -0,0 +1,3 @@
const {build} = require("./utils.js")
build();

57
dev-server.js Normal file
View File

@ -0,0 +1,57 @@
const express = require("express");
const { generateDevHtml, build } = require("./utils.js");
const { argv } = require('node:process');
const chalk = require('chalk');
const app = express();
let port = 4000; // Starting port
const maxAttempts = 10; // Maximum number of ports to try
const env = argv[2] ?? "dev";
const startServer = (attempt) => {
if (attempt > maxAttempts) {
console.error(chalk.red(`ERROR: Unable to find an available port after ${maxAttempts} attempts.`));
return;
}
app.listen(port, () => {
console.log("\n-----------------------------------------------------------\n");
console.log(`Puter is now live at: `, chalk.underline.blue(`http://localhost:${port}`));
console.log("\n-----------------------------------------------------------\n");
}).on('error', (err) => {
if (err.code === 'EADDRINUSE') { // Check if the error is because the port is already in use
console.error(chalk.red(`ERROR: Port ${port} is already in use. Trying next port...`));
port++; // Increment the port number
startServer(attempt + 1); // Try the next port
}
});
};
// Start the server with the first attempt
startServer(1);
// build the GUI
build();
app.get(["/", "/app/*", "/action/*"], (req, res) => {
res.send(generateDevHtml({
env: env,
api_origin: "https://api.puter.com",
title: "Puter",
max_item_name_length: 150,
require_email_verification_to_publish_website: false,
short_description: `Puter is a privacy-first personal cloud that houses all your files, apps, and games in one private and secure place, accessible from anywhere at any time.`,
}));
})
app.use(express.static('./'));
if(env === "prod"){
// make sure to serve the ./dist/ folder maps to the root of the website
app.use(express.static('./dist/'));
}
if(env === "dev"){
app.use(express.static('./src/'));
}
module.exports = app;

8
dist/browserconfig.xml vendored Normal file
View File

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="utf-8"?>
<browserconfig>
<msapplication>
<tile>
<square70x70logo src="./favicons/ms-icon-70x70.png"/>
<square150x150logo src="./favicons/ms-icon-150x150.png"/>
<square310x310logo src="./favicons/ms-icon-310x310.png"/>
<TileColor>#ffffff</TileColor></tile></msapplication></browserconfig>

21
dist/bundle.min.css vendored Normal file

File diff suppressed because one or more lines are too long

323
dist/bundle.min.js vendored Normal file

File diff suppressed because one or more lines are too long

BIN
dist/favicon.ico vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

BIN
dist/favicons/android-icon-144x144.png vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.5 KiB

BIN
dist/favicons/android-icon-192x192.png vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

BIN
dist/favicons/android-icon-36x36.png vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.1 KiB

BIN
dist/favicons/android-icon-48x48.png vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.8 KiB

BIN
dist/favicons/android-icon-72x72.png vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.3 KiB

BIN
dist/favicons/android-icon-96x96.png vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.7 KiB

BIN
dist/favicons/apple-icon-114x114.png vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.8 KiB

BIN
dist/favicons/apple-icon-120x120.png vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.2 KiB

BIN
dist/favicons/apple-icon-144x144.png vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.5 KiB

BIN
dist/favicons/apple-icon-152x152.png vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

BIN
dist/favicons/apple-icon-180x180.png vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

BIN
dist/favicons/apple-icon-57x57.png vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.3 KiB

BIN
dist/favicons/apple-icon-60x60.png vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.5 KiB

BIN
dist/favicons/apple-icon-72x72.png vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.3 KiB

BIN
dist/favicons/apple-icon-76x76.png vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.5 KiB

BIN
dist/favicons/apple-icon-precomposed.png vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

BIN
dist/favicons/apple-icon.png vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

2
dist/favicons/browserconfig.xml vendored Normal file
View File

@ -0,0 +1,2 @@
<?xml version="1.0" encoding="utf-8"?>
<browserconfig><msapplication><tile><square70x70logo src="/ms-icon-70x70.png"/><square150x150logo src="/ms-icon-150x150.png"/><square310x310logo src="/ms-icon-310x310.png"/><TileColor>#ffffff</TileColor></tile></msapplication></browserconfig>

BIN
dist/favicons/favicon-16x16.png vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

BIN
dist/favicons/favicon-32x32.png vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 KiB

BIN
dist/favicons/favicon-96x96.png vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.7 KiB

BIN
dist/favicons/favicon.ico vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

41
dist/favicons/manifest.json vendored Normal file
View File

@ -0,0 +1,41 @@
{
"name": "App",
"icons": [
{
"src": "\/android-icon-36x36.png",
"sizes": "36x36",
"type": "image\/png",
"density": "0.75"
},
{
"src": "\/android-icon-48x48.png",
"sizes": "48x48",
"type": "image\/png",
"density": "1.0"
},
{
"src": "\/android-icon-72x72.png",
"sizes": "72x72",
"type": "image\/png",
"density": "1.5"
},
{
"src": "\/android-icon-96x96.png",
"sizes": "96x96",
"type": "image\/png",
"density": "2.0"
},
{
"src": "\/android-icon-144x144.png",
"sizes": "144x144",
"type": "image\/png",
"density": "3.0"
},
{
"src": "\/android-icon-192x192.png",
"sizes": "192x192",
"type": "image\/png",
"density": "4.0"
}
]
}

BIN
dist/favicons/ms-icon-144x144.png vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.5 KiB

BIN
dist/favicons/ms-icon-150x150.png vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

BIN
dist/favicons/ms-icon-310x310.png vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 31 KiB

BIN
dist/favicons/ms-icon-70x70.png vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.2 KiB

127
dist/gui.js vendored Normal file
View File

@ -0,0 +1,127 @@
window.gui_env="prod";
window.puter_gui_enabled = true;
/**
* Initializes and configures the GUI (Graphical User Interface) settings based on the provided options.
*
* The function sets global variables in the window object for various settings such as origins and domain names.
* It also handles loading different resources depending on the environment (development or production).
*
* @param {Object} options - Configuration options to initialize the GUI.
* @param {string} [options.gui_origin='https://puter.com'] - The origin URL for the GUI.
* @param {string} [options.api_origin='https://api.puter.com'] - The origin URL for the API.
* @param {number} [options.max_item_name_length=500] - Maximum allowed length for an item name.
* @param {boolean} [options.require_email_verification_to_publish_website=true] - Flag to decide whether email verification is required to publish a website.
*
* @property {string} [options.app_domain] - Extracted domain name from gui_origin. It's derived automatically if not provided.
* @property {string} [window.gui_env] - The environment in which the GUI is running (e.g., "dev" or "prod").
*
* @returns {Promise<void>} Returns a promise that resolves when initialization and resource loading are complete.
*
* @example
* window.gui({
* gui_origin: 'https://myapp.com',
* api_origin: 'https://myapi.com',
* max_item_name_length: 250
* });
*/
window.gui = async function(options){
options = options ?? {};
// app_origin is deprecated, use gui_origin instead
window.gui_origin = options.gui_origin ?? options.app_origin ?? `https://puter.com`;
window.app_domain = options.app_domain ?? new URL(window.gui_origin).hostname;
window.hosting_domain = options.hosting_domain ?? 'puter.site';
window.api_origin = options.api_origin ?? "https://api.puter.com";
window.max_item_name_length = options.max_item_name_length ?? 500;
window.require_email_verification_to_publish_website = options.require_email_verification_to_publish_website ?? true;
// Add Puter.JS
await loadScript('https://js.puter.com/v2/');
// DEV: Load the initgui.js file if we are in development mode
if(!window.gui_env || window.gui_env === "dev"){
await loadScript('/initgui.js', {isModule: true});
}
// PROD: load the minified bundles if we are in production mode
// note: the order of the bundles is important
// note: Build script will prepend `window.gui_env="prod"` to the top of the file
else if(gui_env === "prod"){
// Load the minified bundles
await loadCSS('/dist/bundle.min.css');
await loadScript('/dist/bundle.min.js');
}
// 🚀 Launch the GUI 🚀
initgui();
}
/**
* Dynamically loads an external JavaScript file.
* @param {string} url The URL of the external script to load.
* @param {Object} [options] Optional configuration for the script.
* @param {boolean} [options.isModule] Whether the script is a module.
* @param {boolean} [options.defer] Whether the script should be deferred.
* @param {Object} [options.dataAttributes] An object containing data attributes to add to the script element.
* @returns {Promise} A promise that resolves once the script has loaded, or rejects on error.
*/
window.loadScript = async function(url, options = {}) {
return new Promise((resolve, reject) => {
const script = document.createElement('script');
script.src = url;
// Set default script loading behavior
script.async = true;
// Handle if it is a module
if (options.isModule) {
script.type = 'module';
}
// Handle defer attribute
if (options.defer) {
script.defer = true;
script.async = false; // When "defer" is true, "async" should be false as they are mutually exclusive
}
// Add arbitrary data attributes
if (options.dataAttributes && typeof options.dataAttributes === 'object') {
for (const [key, value] of Object.entries(options.dataAttributes)) {
script.setAttribute(`data-${key}`, value);
}
}
// Resolve the promise when the script is loaded
script.onload = () => resolve();
// Reject the promise if there's an error during load
script.onerror = (error) => reject(new Error(`Failed to load script at url: ${url}`));
// Append the script to the body
document.body.appendChild(script);
});
};
/**
* Dynamically loads an external CSS file.
* @param {string} url The URL of the external CSS to load.
* @returns {Promise} A promise that resolves once the CSS has loaded, or rejects on error.
*/
window.loadCSS = async function(url) {
return new Promise((resolve, reject) => {
const link = document.createElement('link');
link.rel = 'stylesheet';
link.href = url;
link.onload = () => {
resolve();
};
link.onerror = (error) => {
reject(new Error(`Failed to load CSS at url: ${url}`));
};
document.head.appendChild(link);
});
}

BIN
dist/images/screenshot.png vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 MiB

BIN
dist/images/wallpaper.webp vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 175 KiB

41
dist/manifest.json vendored Normal file
View File

@ -0,0 +1,41 @@
{
"name": "App",
"icons": [
{
"src": "/favicons/android-icon-36x36.png",
"sizes": "36x36",
"type": "image/png",
"density": "0.75"
},
{
"src": "/favicons/android-icon-48x48.png",
"sizes": "48x48",
"type": "image/png",
"density": "1.0"
},
{
"src": "/favicons/android-icon-72x72.png",
"sizes": "72x72",
"type": "image/png",
"density": "1.5"
},
{
"src": "/favicons/android-icon-96x96.png",
"sizes": "96x96",
"type": "image/png",
"density": "2.0"
},
{
"src": "/favicons/android-icon-144x144.png",
"sizes": "144x144",
"type": "image/png",
"density": "3.0"
},
{
"src": "/favicons/android-icon-192x192.png",
"sizes": "192x192",
"type": "image/png",
"density": "4.0"
}
]
}

137
docs/prod.md Normal file
View File

@ -0,0 +1,137 @@
# Puter in Production
## Building
```bash
npm run build
```
## Usage
Will build Puter in the `dist` directory. Include the generated `./dist/gui.js` file in your HTML page and call `gui()` when the page is loaded:
```html
<script type="text/javascript" src="./dist/gui.js"></script>
<script type="text/javascript">
window.addEventListener('load', function() {
// Initialize the GUI. All options are optional!
gui({
// The origin of the app. This is the base URL of the GUI.
gui_origin: "https://puter.com",
// The origin of the API. This is the base URL of the API endpoints that the GUI will call for all its operations.
api_origin: "https://api.puter.com",
// The domain under which user websites are hosted.
hosting_domain: "puter.site",
// The maximum length of file/directory names.
max_item_name_length: 500,
// If GUI has to enforce email verification before allowing user to publish a website.
require_email_verification_to_publish_website: true,
})
});
</script>
```
## Full Production Example
Assuming the following directory structure in production:
```
.
├── dist/
│ ├── favicons/
│ ├── images/
│ ├── bundle.min.css
│ ├── bundle.min.js
│ ├── gui.js
│ └── ...
└── index.html
```
The `index.html` file below will load Puter and all the necessary meta tags, favicons, and branding assets:
```html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Puter</title>
<meta name="author" content="Puter Technologies Inc.">
<meta name="description" content="Puter is a privacy-first personal cloud to keep all your files, apps, and games in one private and secure place, accessible from anywhere at any time.">
<meta name="facebook-domain-verification" content="e29w3hjbnnnypf4kzk2cewcdaxym1y" />
<link rel="canonical" href="https://puter.com">
<!-- Meta meta tags -->
<meta property="og:url" content="https://puter.com">
<meta property="og:type" content="website">
<meta property="og:title" content="Puter">
<meta property="og:description" content="Puter is a privacy-first personal cloud to keep all your files, apps, and games in one private and secure place, accessible from anywhere at any time.">
<meta property="og:image" content="./dist/images/screenshot.png">
<!-- Twitter meta tags -->
<meta name="twitter:card" content="summary_large_image">
<meta property="twitter:domain" content="puter.com">
<meta property="twitter:url" content="https://puter.com">
<meta name="twitter:title" content="Puter">
<meta name="twitter:description" content="Puter is a privacy-first personal cloud to keep all your files, apps, and games in one private and secure place, accessible from anywhere at any time.">
<meta name="twitter:image" content="./dist/images/screenshot.png">
<!-- favicons -->
<link rel="apple-touch-icon" sizes="57x57" href="./dist/favicons/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="./dist/favicons/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="./dist/favicons/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="./dist/favicons/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="./dist/favicons/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="./dist/favicons/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="./dist/favicons/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="./dist/favicons/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="./dist/favicons/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192" href="./dist/favicons/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="./dist/favicons/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="./dist/favicons/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="./dist/favicons/favicon-16x16.png">
<link rel="manifest" href="./dist/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="./dist/favicons/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">
<!-- Preload images when applicable -->
<link rel="preload" as="image" href="./dist/images/wallpaper.webp">
</head>
<body>
<!-- Load the GUI script -->
<script type="text/javascript" src="./dist/gui.js"></script>
<!-- Initialize GUI when document is loaded -->
<script type="text/javascript">
window.addEventListener('load', function() {
gui()
});
</script>
</body>
</html>
```
### Server settings
The GUI is a single page application (SPA) and as best practice any route under root (`/*`) should preferably load the `index.html` file. However, there are situations where we want to load a custom page for a specific route: for example, the `/privacy` route may need to load a page that contains your privacy policy and has nothing to do with the GUI application. In these cases it is ok to load a custom page as long as the following essential GUI routes are loaded with the GUI (i.e. `index.html` file):
- `/app/*`
- `/action/*`
In other words, consider the routes above as "reserved" for Puter.
### Best Practices
- The `title` tags and meta tags (`<title></title>`, `<meta property="og:title"`, `<meta name="twitter:title"`, ...) should be dynamically set by the server. For example, if the URL is of an app (e.g. `https://puter.com/app/editor`) the `title` tags and meta tags should contain the app's title rather than the generic Puter title.
- The `description` meta tags (`<meta name="description"`, `<meta property="og:description"`, `<meta name="twitter:description"`, ...) should be dynamically set by the server. For example, if the URL is of an app (e.g. `https://puter.com/app/editor`) the `description` meta tags should contain the app's description rather than the generic Puter description.
- Make sure to escape any HTML code that is dynamically added to the HTML page. For example, if the app's description is `Puter is a <b>privacy-first</b> personal cloud to keep all your files, apps, and games in one private and secure place, accessible from anywhere at any time.` the `<b>` tag should be escaped to `&lt;b&gt;` so that the browser doesn't interpret it as an HTML tag.
- Make sure to replace all new line characters with space when dynamically adding text to the HTML page.
- Generally, for UX and SEO reasons make sure that the tags are filled with relevant information about the state the URL is representing. E.g. is the user on the desktop or an app?

2510
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

33
package.json Normal file
View File

@ -0,0 +1,33 @@
{
"name": "puter.com",
"version": "1.0.0",
"author": "Puter Technologies Inc.",
"license": "AGPL-3.0-only",
"description": "Desktop environment in the browser!",
"homepage": "https://puter.com",
"directories": {
"lib": "lib"
},
"devDependencies": {
"chalk": "^4.1.0",
"clean-css": "^5.3.2",
"html-entities": "^2.3.3",
"webpack": "^5.88.2",
"express": "^4.18.2",
"nodemon": "^2.0.22",
"uglify-js": "^3.17.4",
"webpack-cli": "^5.1.1"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "nodemon --exec \"node dev-server.js\" ",
"build": "node ./build.js"
},
"nodemonConfig": {
"ext": "js, json, mjs, jsx, svg, css",
"ignore": [
"./dist/",
"./node_modules/"
]
}
}

953
src/IPC.js Normal file
View File

@ -0,0 +1,953 @@
import UIAlert from './UI/UIAlert.js';
import UIWindow from './UI/UIWindow.js';
import UIWindowSignup from './UI/UIWindowSignup.js';
import UIWindowRequestPermission from './UI/UIWindowRequestPermission.js';
import UIItem from './UI/UIItem.js'
import UIWindowFontPicker from './UI/UIWindowFontPicker.js';
import UIWindowColorPicker from './UI/UIWindowColorPicker.js';
import UIPrompt from './UI/UIPrompt.js';
import download from './helpers/download.js';
import path from "./lib/path.js";
/**
* In Puter, apps are loaded in iframes and communicate with the graphical user interface (GUI) aand each other using the postMessage API.
* The following sets up an Inter-Process Messaging System between apps and the GUI that enables communication
* for various tasks such as displaying alerts, prompts, managing windows, handling file operations, and more.
*
* The system listens for 'message' events on the window object, handling different types of messages from the app (which is loaded in an iframe),
* such as ALERT, createWindow, showOpenFilePicker, ...
* Each message handler performs specific actions, including creating UI windows, handling file saves and reads, and responding to user interactions.
*
* Precautions are taken to ensure proper usage of appInstanceIDs and other sensitive information.
*/
window.addEventListener('message', async (event) => {
const app_env = event.data?.env ?? 'app';
// Only process messages from apps
if(app_env !== 'app')
return;
// --------------------------------------------------------
// A response to a GUI message received from the app.
// --------------------------------------------------------
if (typeof event.data.original_msg_id !== "undefined" && typeof appCallbackFunctions[event.data.original_msg_id] !== "undefined") {
// Execute callback
appCallbackFunctions[event.data.original_msg_id](event.data);
// Remove this callback function since it won't be needed again
delete appCallbackFunctions[event.data.original_msg_id];
// Done
return;
}
// --------------------------------------------------------
// Message from apps
// --------------------------------------------------------
// `data` and `msg` are required
if(!event.data || !event.data.msg){
return;
}
// `appInstanceID` is required
if(!event.data.appInstanceID){
console.log(`appInstanceID is needed`);
return;
}
const $el_parent_window = $(`.window[data-element_uuid="${event.data.appInstanceID}"]`);
const parent_window_id = $el_parent_window.attr('data-id');
const $el_parent_disable_mask = $el_parent_window.find('.window-disable-mask');
const target_iframe = $(`.window[data-element_uuid="${event.data.appInstanceID}"]`).find('.window-app-iframe').get(0);
const msg_id = event.data.uuid;
const app_name = $(target_iframe).attr('data-app');
const app_uuid = $el_parent_window.attr('data-app_uuid');
// todo validate all event.data stuff coming from the client (e.g. event.data.message, .msg, ...)
//-------------------------------------------------
// READY
//-------------------------------------------------
if(event.data.msg === 'READY'){
$(target_iframe).attr('data-appUsesSDK', 'true');
}
//-------------------------------------------------
// windowFocused
//-------------------------------------------------
else if(event.data.msg === 'windowFocused'){
console.log('windowFocused');
}
//--------------------------------------------------------
// ALERT
//--------------------------------------------------------
else if(event.data.msg === 'ALERT' && event.data.message !== undefined){
const alert_resp = await UIAlert({
message: html_encode(event.data.message),
buttons: event.data.buttons,
type: event.data.options?.type,
window_options: {
parent_uuid: event.data.appInstanceID,
disable_parent_window: true,
}
})
target_iframe.contentWindow.postMessage({
original_msg_id: msg_id,
msg: 'alertResponded',
response: alert_resp,
}, '*');
}
//--------------------------------------------------------
// PROMPT
//--------------------------------------------------------
else if(event.data.msg === 'PROMPT' && event.data.message !== undefined){
const prompt_resp = await UIPrompt({
message: html_encode(event.data.message),
placeholder: html_encode(event.data.placeholder),
window_options: {
parent_uuid: event.data.appInstanceID,
disable_parent_window: true,
}
})
target_iframe.contentWindow.postMessage({
original_msg_id: msg_id,
msg: 'promptResponded',
response: prompt_resp,
}, '*');
}
//--------------------------------------------------------
// env
//--------------------------------------------------------
else if(event.data.msg === 'env'){
target_iframe.contentWindow.postMessage({
original_msg_id: msg_id,
}, '*');
}
//--------------------------------------------------------
// createWindow
//--------------------------------------------------------
else if(event.data.msg === 'createWindow'){
// todo: validate as many of these as possible
if(event.data.options){
UIWindow({
title: event.data.options.title,
disable_parent_window: event.data.options.disable_parent_window,
width: event.data.options.width,
height: event.data.options.height,
is_resizable: event.data.options.is_resizable,
has_head: event.data.options.has_head,
center: event.data.options.center,
show_in_taskbar: event.data.options.show_in_taskbar,
iframe_srcdoc: event.data.options.content,
iframe_url: event.data.options.url,
parent_uuid: event.data.appInstanceID,
})
}
}
//--------------------------------------------------------
// setItem
//--------------------------------------------------------
else if(event.data.msg === 'setItem' && event.data.key && event.data.value){
// todo: validate key and value to avoid unnecessary api calls
return await $.ajax({
url: api_origin + "/setItem",
type: 'POST',
data: JSON.stringify({
app: app_uuid,
key: event.data.key,
value: event.data.value,
}),
async: true,
contentType: "application/json",
headers: {
"Authorization": "Bearer "+auth_token
},
statusCode: {
401: function () {
logout();
},
},
success: function (fsentry){
}
})
}
//--------------------------------------------------------
// getItem
//--------------------------------------------------------
else if(event.data.msg === 'getItem' && event.data.key){
// todo: validate key to avoid unnecessary api calls
$.ajax({
url: api_origin + "/getItem",
type: 'POST',
data: JSON.stringify({
key: event.data.key,
app: app_uuid,
}),
async: true,
contentType: "application/json",
headers: {
"Authorization": "Bearer "+auth_token
},
statusCode: {
401: function () {
logout();
},
},
success: function (result){
// send confirmation to requester window
target_iframe.contentWindow.postMessage({
original_msg_id: msg_id,
msg: 'getItemSucceeded',
value: result ? result.value : null,
}, '*');
}
})
}
//--------------------------------------------------------
// removeItem
//--------------------------------------------------------
else if(event.data.msg === 'removeItem' && event.data.key){
// todo: validate key to avoid unnecessary api calls
$.ajax({
url: api_origin + "/removeItem",
type: 'POST',
data: JSON.stringify({
key: event.data.key,
app: app_uuid,
}),
async: true,
contentType: "application/json",
headers: {
"Authorization": "Bearer "+auth_token
},
statusCode: {
401: function () {
logout();
},
},
success: function (result){
// send confirmation to requester window
target_iframe.contentWindow.postMessage({
original_msg_id: msg_id,
}, '*');
}
})
}
//--------------------------------------------------------
// showOpenFilePicker
//--------------------------------------------------------
else if(event.data.msg === 'showOpenFilePicker'){
// Auth
if(!is_auth() && !(await UIWindowSignup({referrer: app_name})))
return;
// Disable parent window
$el_parent_window.addClass('window-disabled')
$el_parent_disable_mask.show();
$el_parent_disable_mask.css('z-index', parseInt($el_parent_window.css('z-index')) + 1);
$(target_iframe).blur();
// Allowed_file_types
let allowed_file_types = "";
if(event.data.options && event.data.options.accept)
allowed_file_types = event.data.options.accept;
// selectable_body
let is_selectable_body = false;
if(event.data.options && event.data.options.multiple && event.data.options.multiple === true)
is_selectable_body = true;
// Open dialog
UIWindow({
allowed_file_types: allowed_file_types,
path: '/' + window.user.username + '/Desktop',
// this is the uuid of the window to which this dialog will return
parent_uuid: event.data.appInstanceID,
show_maximize_button: false,
show_minimize_button: false,
title: 'Open',
is_dir: true,
is_openFileDialog: true,
selectable_body: is_selectable_body,
iframe_msg_uid: msg_id,
initiating_app_uuid: app_uuid,
center: true,
});
}
//--------------------------------------------------------
// showDirectoryPicker
//--------------------------------------------------------
else if(event.data.msg === 'showDirectoryPicker'){
// Auth
if(!is_auth() && !(await UIWindowSignup({referrer: app_name})))
return;
// Disable parent window
$el_parent_window.addClass('window-disabled')
$el_parent_disable_mask.show();
$el_parent_disable_mask.css('z-index', parseInt($el_parent_window.css('z-index')) + 1);
$(target_iframe).blur();
// allowed_file_types
let allowed_file_types = "";
if(event.data.options && event.data.options.accept)
allowed_file_types = event.data.options.accept;
// selectable_body
let is_selectable_body = false;
if(event.data.options && event.data.options.multiple && event.data.options.multiple === true)
is_selectable_body = true;
// open dialog
UIWindow({
path: '/' + window.user.username + '/Desktop',
// this is the uuid of the window to which this dialog will return
parent_uuid: event.data.appInstanceID,
show_maximize_button: false,
show_minimize_button: false,
title: 'Open',
is_dir: true,
is_directoryPicker: true,
selectable_body: is_selectable_body,
iframe_msg_uid: msg_id,
center: true,
initiating_app_uuid: app_uuid,
});
}
//--------------------------------------------------------
// setWindowTitle
//--------------------------------------------------------
else if(event.data.msg === 'setWindowTitle' && event.data.new_title !== undefined){
const el_window = $(`.window[data-element_uuid="${event.data.appInstanceID}"]`).get(0);
// set window title
$(el_window).find(`.window-head-title`).html(html_encode(event.data.new_title));
// send confirmation to requester window
target_iframe.contentWindow.postMessage({
original_msg_id: msg_id,
}, '*');
}
//--------------------------------------------------------
// watchItem
//--------------------------------------------------------
else if(event.data.msg === 'watchItem' && event.data.item_uid !== undefined){
if(!window.watchItems[event.data.item_uid])
window.watchItems[event.data.item_uid] = [];
window.watchItems[event.data.item_uid].push(event.data.appInstanceID);
}
//--------------------------------------------------------
// openItem
//--------------------------------------------------------
else if(event.data.msg === 'openItem'){
// check if readURL returns 200
$.ajax({
url: event.data.metadataURL + '&return_suggested_apps=true&return_path=true',
type: 'GET',
headers: {
"Authorization": "Bearer "+auth_token
},
success: async function(metadata){
$.ajax({
url: api_origin + "/open_item",
type: 'POST',
contentType: "application/json",
data: JSON.stringify({
uid: metadata.uid ?? undefined,
path: metadata.path ?? undefined,
}),
headers: {
"Authorization": "Bearer "+auth_token
},
statusCode: {
401: function () {
logout();
},
},
success: function(open_item_meta){
setTimeout(function(){
launch_app({
name: metadata.name,
file_path: metadata.path,
app_obj: open_item_meta.suggested_apps[0],
window_title: metadata.name,
file_uid: metadata.uid,
file_signature: open_item_meta.signature,
});
// todo: this is done because sometimes other windows such as openFileDialog
// bring focus to their apps and steal the focus from the newly-opened app
}, 800);
},
});
}
})
}
//--------------------------------------------------------
// launchApp
//--------------------------------------------------------
else if(event.data.msg === 'launchApp'){
// launch app
launch_app({
name: event.data.app_name ?? app_name,
args: event.data.args ?? {},
});
// send confirmation to requester window
target_iframe.contentWindow.postMessage({
original_msg_id: msg_id,
}, '*');
}
//--------------------------------------------------------
// readAppDataFile
//--------------------------------------------------------
else if(event.data.msg === 'readAppDataFile' && event.data.path !== undefined){
// resolve path to absolute
event.data.path = path.resolve(event.data.path);
// join with appdata dir
const file_path = path.join(appdata_path, app_uuid, event.data.path);
puter.fs.sign(app_uuid, {
path: file_path,
action: 'write',
},
function(signature){
signature = signature.items;
signature.signatures = signature.signatures ?? [signature];
if(signature.signatures.length > 0 && signature.signatures[0].path){
signature.signatures[0].path = `~/` + signature.signatures[0].path.split('/').slice(2).join('/')
// send confirmation to requester window
target_iframe.contentWindow.postMessage({
msg: "readAppDataFileSucceeded",
original_msg_id: msg_id,
item: signature.signatures[0],
}, '*');
}else{
// send error to requester window
target_iframe.contentWindow.postMessage({
msg: "readAppDataFileFailed",
original_msg_id: msg_id,
}, '*');
}
}
)
}
//--------------------------------------------------------
// getAppData
//--------------------------------------------------------
// todo appdata should be provided from the /open_item api call
else if(event.data.msg === 'getAppData'){
if(appdata_signatures[app_uuid]){
target_iframe.contentWindow.postMessage({
msg: "getAppDataSucceeded",
original_msg_id: msg_id,
item: appdata_signatures[app_uuid],
}, '*');
}
// make app directory if it doesn't exist
puter.fs.mkdir({
path: path.join( appdata_path, app_uuid),
rename: false,
overwrite: false,
success: function(dir){
puter.fs.sign(app_uuid, {
uid: dir.uid,
action: 'write',
success: function(signature){
signature = signature.items;
appdata_signatures[app_uuid] = signature;
// send confirmation to requester window
target_iframe.contentWindow.postMessage({
msg: "getAppDataSucceeded",
original_msg_id: msg_id,
item: signature,
}, '*');
}
})
},
error: function(err){
if(err.existing_fsentry || err.code === 'path_exists'){
puter.fs.sign(app_uuid, {
uid: err.existing_fsentry.uid,
action: 'write',
success: function(signature){
signature = signature.items;
appdata_signatures[app_uuid] = signature;
// send confirmation to requester window
target_iframe.contentWindow.postMessage({
msg: "getAppDataSucceeded",
original_msg_id: msg_id,
item: signature,
}, '*');
}
})
}
}
});
}
//--------------------------------------------------------
// requestPermission
//--------------------------------------------------------
else if(event.data.msg === 'requestPermission'){
// auth
if(!is_auth() && !(await UIWindowSignup({referrer: app_name})))
return;
// options must be an object
if(event.data.options === undefined || typeof event.data.options !== 'object')
event.data.options = {};
// clear window_options for security reasons
event.data.options.window_options = {}
// Set app as parent window of font picker window
event.data.options.window_options.parent_uuid = event.data.appInstanceID;
// disable parent window
event.data.options.window_options.disable_parent_window = true;
let granted = await UIWindowRequestPermission({
origin: event.origin,
permission: event.data.options.permission,
window_options: event.data.options.window_options,
});
// send selected font to requester window
target_iframe.contentWindow.postMessage({
msg: "permissionGranted",
granted: granted,
original_msg_id: msg_id,
}, '*');
$(target_iframe).get(0).focus({preventScroll:true});
}
//--------------------------------------------------------
// showFontPicker
//--------------------------------------------------------
else if(event.data.msg === 'showFontPicker'){
// auth
if(!is_auth() && !(await UIWindowSignup({referrer: app_name})))
return;
// set options
event.data.options = event.data.options ?? {};
// clear window_options for security reasons
event.data.options.window_options = {}
// Set app as parent window of font picker window
event.data.options.window_options.parent_uuid = event.data.appInstanceID;
// Open font picker
let selected_font = await UIWindowFontPicker(event.data.options);
// send selected font to requester window
target_iframe.contentWindow.postMessage({
msg: "fontPicked",
original_msg_id: msg_id,
font: selected_font,
}, '*');
$(target_iframe).get(0).focus({preventScroll:true});
}
//--------------------------------------------------------
// showColorPicker
//--------------------------------------------------------
else if(event.data.msg === 'showColorPicker'){
// Auth
if(!is_auth() && !(await UIWindowSignup({referrer: app_name})))
return;
// set options
event.data.options = event.data.options ?? {};
// Clear window_options for security reasons
event.data.options.window_options = {}
// Set app as parent window of the font picker window
event.data.options.window_options.parent_uuid = event.data.appInstanceID;
// Open color picker
let selected_color = await UIWindowColorPicker(event.data.options);
// Send selected color to requester window
target_iframe.contentWindow.postMessage({
msg: "colorPicked",
original_msg_id: msg_id,
color: selected_color ? selected_color.color : undefined,
}, '*');
$(target_iframe).get(0).focus({preventScroll:true});
}
//--------------------------------------------------------
// setWallpaper
//--------------------------------------------------------
else if(event.data.msg === 'setWallpaper'){
// Auth
if(!is_auth() && !(await UIWindowSignup({referrer: app_name})))
return;
// No options?
if(!event.data.options)
event.data.options = {};
// /set-desktop-bg
try{
await $.ajax({
url: api_origin + "/set-desktop-bg",
type: 'POST',
data: JSON.stringify({
url: event.data.readURL,
fit: event.data.options.fit ?? 'cover',
color: event.data.options.color,
}),
async: true,
contentType: "application/json",
headers: {
"Authorization": "Bearer "+auth_token
},
statusCode: {
401: function () {
logout();
},
},
});
// Set wallpaper
window.set_desktop_background({
url: event.data.readURL,
fit: event.data.options.fit ?? 'cover',
color: event.data.options.color,
})
// Send success to app
target_iframe.contentWindow.postMessage({
msg: "wallpaperSet",
original_msg_id: msg_id,
}, '*');
$(target_iframe).get(0).focus({preventScroll:true});
}catch(err){
console.error(err);
}
}
//--------------------------------------------------------
// showSaveFilePicker
//--------------------------------------------------------
else if(event.data.msg === 'showSaveFilePicker'){
//auth
if(!is_auth() && !(await UIWindowSignup({referrer: app_name})))
return;
//disable parent window
$el_parent_window.addClass('window-disabled')
$el_parent_disable_mask.show();
$el_parent_disable_mask.css('z-index', parseInt($el_parent_window.css('z-index')) + 1);
$(target_iframe).blur();
await UIWindow({
path: '/' + window.user.username + '/Desktop',
// this is the uuid of the window to which this dialog will return
parent_uuid: event.data.appInstanceID,
show_maximize_button: false,
show_minimize_button: false,
title: 'Save As…',
is_dir: true,
is_saveFileDialog: true,
saveFileDialog_default_filename: event.data.suggestedName ?? '',
selectable_body: false,
iframe_msg_uid: msg_id,
center: true,
initiating_app_uuid: app_uuid,
onSaveFileDialogSave: async function(target_path, el_filedialog_window){
$(el_filedialog_window).find('.window-disable-mask, .busy-indicator').show();
let busy_init_ts = Date.now();
// -------------------------------------
// URL
// -------------------------------------
if(event.data.url){
// download progress tracker
let dl_op_id = operation_id++;
// upload progress tracker defaults
window.progress_tracker[dl_op_id] = [];
window.progress_tracker[dl_op_id][0] = {};
window.progress_tracker[dl_op_id][0].total = 0;
window.progress_tracker[dl_op_id][0].ajax_uploaded = 0;
window.progress_tracker[dl_op_id][0].cloud_uploaded = 0;
let item_with_same_name_already_exists = true;
while(item_with_same_name_already_exists){
await download({
url: event.data.url,
name: path.basename(target_path),
dest_path: path.dirname(target_path),
auth_token: auth_token,
api_origin: api_origin,
dedupe_name: false,
overwrite: false,
operation_id: dl_op_id,
item_upload_id: 0,
success: function(res){
},
error: function(err){
UIAlert(err && err.message ? err.message : "Download failed.");
}
});
item_with_same_name_already_exists = false;
}
}
// -------------------------------------
// File
// -------------------------------------
else{
let overwrite = false;
let file_to_upload = new File([event.data.content], path.basename(target_path));
let item_with_same_name_already_exists = true;
while(item_with_same_name_already_exists){
// overwrite?
if(overwrite)
item_with_same_name_already_exists = false;
// upload
try{
const res = await puter.fs.write(
target_path,
file_to_upload,
{
dedupeName: false,
overwrite: overwrite
}
);
let file_signature = await puter.fs.sign(app_uuid, {uid: res.uid, action: 'write'});
file_signature = file_signature.items;
item_with_same_name_already_exists = false;
target_iframe.contentWindow.postMessage({
msg: "fileSaved",
original_msg_id: msg_id,
filename: res.name,
saved_file: {
name: file_signature.fsentry_name,
readURL: file_signature.read_url,
writeURL: file_signature.write_url,
metadataURL: file_signature.metadata_url,
type: file_signature.type,
uid: file_signature.uid,
path: `~/` + res.path.split('/').slice(2).join('/'),
},
}, '*');
$(target_iframe).get(0).focus({preventScroll:true});
// Update matching items on open windows
// todo don't blanket-update, mostly files with thumbnails really need to be updated
// first remove overwritten items
$(`.item[data-uid="${res.uid}"]`).removeItems();
// now add new items
UIItem({
appendTo: $(`.item-container[data-path="${html_encode(path.dirname(target_path))}" i]`),
immutable: res.immutable,
associated_app_name: res.associated_app?.name,
path: target_path,
icon: await item_icon(res),
name: path.basename(target_path),
uid: res.uid,
size: res.size,
modified: res.modified,
type: res.type,
is_dir: false,
is_shared: res.is_shared,
suggested_apps: res.suggested_apps,
});
// sort each window
$(`.item-container[data-path="${html_encode(path.dirname(target_path))}" i]`).each(function(){
sort_items(this, $(this).attr('data-sort_by'), $(this).attr('data-sort_order'))
});
$(el_filedialog_window).close();
show_save_account_notice_if_needed();
}
catch(err){
// item with same name exists
if(err.code === 'item_with_same_name_exists'){
const alert_resp = await UIAlert({
message: `<strong>${html_encode(err.entry_name)}</strong> already exists.`,
buttons:[
{
label: 'Replace',
value: 'replace',
type: 'primary',
},
{
label: 'Cancel',
value: 'cancel',
},
],
parent_uuid: $(el_filedialog_window).attr('data-element_uuid'),
})
if(alert_resp === 'replace'){
overwrite = true;
}else if(alert_resp === 'cancel'){
// enable parent window
$(el_filedialog_window).find('.window-disable-mask, .busy-indicator').hide();
return;
}
}
else{
// show error
await UIAlert({
message: err.message ?? "Upload failed.",
parent_uuid: $(el_filedialog_window).attr('data-element_uuid'),
});
// enable parent window
$(el_filedialog_window).find('.window-disable-mask, .busy-indicator').hide();
return;
}
}
}
}
// done
let busy_duration = (Date.now() - busy_init_ts);
if( busy_duration >= busy_indicator_hide_delay){
$(el_filedialog_window).close();
}else{
setTimeout(() => {
// close this dialog
$(el_filedialog_window).close();
}, Math.abs(busy_indicator_hide_delay - busy_duration));
}
}
});
}
//--------------------------------------------------------
// saveToPictures/Desktop/Documents/Videos/Audio/AppData
//--------------------------------------------------------
else if((event.data.msg === 'saveToPictures' || event.data.msg === 'saveToDesktop' || event.data.msg === 'saveToAppData' ||
event.data.msg === 'saveToDocuments' || event.data.msg === 'saveToVideos' || event.data.msg === 'saveToAudio')){
let target_path;
let create_missing_ancestors = false;
if(event.data.msg === 'saveToPictures')
target_path = path.join(pictures_path, event.data.filename);
else if(event.data.msg === 'saveToDesktop')
target_path = path.join(desktop_path, event.data.filename);
else if(event.data.msg === 'saveToDocuments')
target_path = path.join(documents_path, event.data.filename);
else if(event.data.msg === 'saveToVideos')
target_path = path.join(videos_path, event.data.filename);
else if(event.data.msg === 'saveToAudio')
target_path = path.join(audio_path, event.data.filename);
else if(event.data.msg === 'saveToAppData'){
target_path = path.join(appdata_path, app_uuid, event.data.filename);
create_missing_ancestors = true;
}
//auth
if(!is_auth() && !(await UIWindowSignup({referrer: app_name})))
return;
let item_with_same_name_already_exists = true;
let overwrite = false;
// -------------------------------------
// URL
// -------------------------------------
if(event.data.url){
let overwrite = false;
// download progress tracker
let dl_op_id = operation_id++;
// upload progress tracker defaults
window.progress_tracker[dl_op_id] = [];
window.progress_tracker[dl_op_id][0] = {};
window.progress_tracker[dl_op_id][0].total = 0;
window.progress_tracker[dl_op_id][0].ajax_uploaded = 0;
window.progress_tracker[dl_op_id][0].cloud_uploaded = 0;
let item_with_same_name_already_exists = true;
while(item_with_same_name_already_exists){
const res = await download({
url: event.data.url,
name: path.basename(target_path),
dest_path: path.dirname(target_path),
auth_token: auth_token,
api_origin: api_origin,
dedupe_name: true,
overwrite: false,
operation_id: dl_op_id,
item_upload_id: 0,
success: function(res){
},
error: function(err){
UIAlert(err && err.message ? err.message : "Download failed.");
}
});
item_with_same_name_already_exists = false;
}
}
// -------------------------------------
// File
// -------------------------------------
else{
let file_to_upload = new File([event.data.content], path.basename(target_path));
while(item_with_same_name_already_exists){
if(overwrite)
item_with_same_name_already_exists = false;
try{
const res = await puter.fs.write(target_path, file_to_upload, {
dedupeName: true,
overwrite: false,
createMissingAncestors: create_missing_ancestors,
});
item_with_same_name_already_exists = false;
let file_signature = await puter.fs.sign(app_uuid, {uid: res.uid, action: 'write'});
file_signature = file_signature.items;
target_iframe.contentWindow.postMessage({
msg: "fileSaved",
original_msg_id: msg_id,
filename: res.name,
saved_file: {
name: file_signature.fsentry_name,
readURL: file_signature.read_url,
writeURL: file_signature.write_url,
metadataURL: file_signature.metadata_url,
uid: file_signature.uid,
path: `~/` + res.path.split('/').slice(2).join('/'),
},
}, '*');
$(target_iframe).get(0).focus({preventScroll:true});
}
catch(err){
if(err.code === 'item_with_same_name_exists'){
const alert_resp = await UIAlert({
message: `<strong>${html_encode(err.entry_name)}</strong> already exists.`,
buttons:[
{
label: 'Replace',
type: 'primary',
},
{
label: 'Cancel'
},
],
parent_uuid: event.data.appInstanceID,
})
if(alert_resp === 'Replace'){
overwrite = true;
}else if(alert_resp === 'Cancel'){
item_with_same_name_already_exists = false;
}
}else{
break;
}
}
}
}
}
//--------------------------------------------------------
// exit
//--------------------------------------------------------
else if(event.data.msg === 'exit'){
$(`.window[data-element_uuid="${event.data.appInstanceID}"]`).close({bypass_iframe_messaging: true});
}
});

65
src/UI/PuterDialog.js Normal file

File diff suppressed because one or more lines are too long

96
src/UI/UIAlert.js Normal file
View File

@ -0,0 +1,96 @@
import UIWindow from './UIWindow.js'
function UIAlert(options){
// set sensible defaults
if(arguments.length > 0){
// if first argument is a string, then assume it is the message
if(isString(arguments[0])){
options = {};
options.message = arguments[0];
}
// if second argument is an array, then assume it is the buttons
if(arguments[1] && Array.isArray(arguments[1])){
options.buttons = arguments[1];
}
}
return new Promise(async (resolve) => {
// provide an 'OK' button if no buttons are provided
if(!options.buttons || options.buttons.length === 0){
options.buttons = [
{label: 'OK', value: true, type: 'primary'}
]
}
// set body icon
options.body_icon = options.body_icon ?? window.icons['warning-sign.svg'];
if(options.type === 'success')
options.body_icon = window.icons['c-check.svg'];
let h = '';
// icon
h += `<img class="window-alert-icon" src="${html_encode(options.body_icon)}">`;
// message
h += `<div class="window-alert-message">${options.message}</div>`;
// buttons
if(options.buttons && options.buttons.length > 0){
h += `<div style="overflow:hidden; margin-top:20px;">`;
for(let y=0; y<options.buttons.length; y++){
h += `<button class="button button-block button-${html_encode(options.buttons[y].type)} alert-resp-button"
data-label="${html_encode(options.buttons[y].label)}"
data-value="${html_encode(options.buttons[y].value ?? options.buttons[y].label)}"
${options.buttons[y].type === 'primary' ? 'autofocus' : ''}
>${html_encode(options.buttons[y].label)}</button>`;
}
h += `</div>`;
}
const el_window = await UIWindow({
title: null,
icon: null,
uid: null,
is_dir: false,
message: options.message,
body_icon: options.body_icon,
backdrop: options.backdrop ?? false,
is_resizable: false,
is_droppable: false,
has_head: false,
stay_on_top: options.stay_on_top ?? false,
selectable_body: false,
draggable_body: options.draggable_body ?? true,
allow_context_menu: false,
show_in_taskbar: false,
window_class: 'window-alert',
dominant: true,
body_content: h,
width: 350,
parent_uuid: options.parent_uuid,
...options.window_options,
window_css:{
height: 'initial',
},
body_css: {
width: 'initial',
padding: '20px',
'background-color': 'rgba(231, 238, 245, .95)',
'backdrop-filter': 'blur(3px)',
}
});
// focus to primary btn
$(el_window).find('.button-primary').focus();
// --------------------------------------------------------
// Button pressed
// --------------------------------------------------------
$(el_window).find('.alert-resp-button').on('click', async function(event){
event.preventDefault();
event.stopPropagation();
resolve($(this).attr('data-value'));
$(el_window).close();
return false;
})
})
}
export default UIAlert;

211
src/UI/UIContextMenu.js Normal file
View File

@ -0,0 +1,211 @@
function UIContextMenu(options){
$('.window-active .window-app-iframe').css('pointer-events', 'none');
const menu_id = global_element_id++;
let h = '';
h += `<div
id="context-menu-${menu_id}"
data-is-submenu="${options.is_submenu ? 'true' : 'false'}"
data-element-id="${menu_id}"
data-id="${options.id ?? ''}"
${options.parent_id ? `data-parent-id="${options.parent_id}"` : ``}
${!options.parent_id && options.parent_element ? `data-parent-id="${$(options.parent_element).attr('data-element-id')}"` : ``}
class="context-menu context-menu-active ${options.is_submenu ? 'context-menu-submenu-open' : ''}"
>`;
for(let i=0; i < options.items.length; i++){
// item
if(!options.items[i].is_divider && options.items[i] !== '-'){
// single item
if(options.items[i].items === undefined){
h += `<li data-action="${i}"
class="context-menu-item ${options.items[i].disabled ? ' context-menu-item-disabled' : ''}"
>`;
// icon
h += `<span class="context-menu-item-icon">${options.items[i].icon ?? ''}</span>`;
h += `<span class="context-menu-item-icon-active">${options.items[i].icon_active ?? (options.items[i].icon ?? '')}</span>`;
// label
h += `<span class="contextmenu-label">${options.items[i].html}</span>`;
h += `<span class="contextmenu-label-active">${options.items[i].html_active ?? options.items[i].html}</span>`;
h += `</li>`;
}
// submenu
else{
h += `<li data-action="${i}"
data-menu-id="${menu_id}-${i}"
data-has-submenu="true"
data-parent-element-id="${menu_id}"
class="context-menu-item-submenu context-menu-item${options.items[i].disabled ? ' context-menu-item-disabled' : ''}"
>`;
// icon
h += `<span class="context-menu-item-icon">${options.items[i].icon ?? ''}</span>`;
h += `<span class="context-menu-item-icon-active">${options.items[i].icon_active ?? (options.items[i].icon ?? '')}</span>`;
// label
h += `${html_encode(options.items[i].html)}`;
// arrow
h += `<img class="submenu-arrow" src="${html_encode(window.icons['chevron-right.svg'])}"><img class="submenu-arrow submenu-arrow-active" src="${html_encode(window.icons['chevron-right-active.svg'])}">`;
h += `</li>`;
}
}
// divider
else if(options.items[i].is_divider || options.items[i] === '-')
h += `<li class="context-menu-divider"><hr></li>`;
}
h += `</div>`
$('body').append(h)
const contextMenu = document.getElementById(`context-menu-${menu_id}`);
const menu_width = $(contextMenu).width();
const menu_height = $(contextMenu).outerHeight();
let start_x, start_y;
//--------------------------------
// Auto position
//--------------------------------
if(!options.position){
if(isMobile.phone || isMobile.tablet){
start_x = window.last_touch_x;
start_y = window.last_touch_y;
}else{
start_x = window.mouseX;
start_y = window.mouseY;
}
}
//--------------------------------
// custom position
//--------------------------------
else{
start_x = options.position.left;
start_y = options.position.top;
}
// X position
let x_pos;
if( start_x + menu_width > window.innerWidth){
x_pos = start_x - menu_width;
// if this is a child menu, the width of parent must be also considered
if(options.parent_id){
x_pos -= $(`.context-menu[data-element-id="${options.parent_id}"]`).width() + 30;
}
}else
x_pos = start_x
// Y position
let y_pos;
// is the menu going to go out of the window from the bottom?
if( (start_y + menu_height) > (window.innerHeight - taskbar_height - 10))
y_pos = window.innerHeight - menu_height - taskbar_height - 10;
else
y_pos = start_y;
// Show ContextMenu
$(contextMenu).delay(100).show(0)
// In the right position (the mouse)
.css({
top: y_pos + "px",
left: x_pos + "px"
});
// mark other context menus as inactive
$('.context-menu').not(contextMenu).removeClass('context-menu-active');
// An item is clicked
$(`#context-menu-${menu_id} > li:not(.context-menu-item-disabled)`).on('click', function (e) {
// onClick
if(options.items[$(this).attr("data-action")].onClick && typeof options.items[$(this).attr("data-action")].onClick === 'function'){
let event = e;
event.value = options.items[$(this).attr("data-action")]['val'] ?? undefined;
options.items[$(this).attr("data-action")].onClick(event);
}
// close menu and, if exists, its parent
if(!$(this).hasClass('context-menu-item-submenu')){
$(`#context-menu-${menu_id}, .context-menu[data-element-id="${$(this).closest('.context-menu').attr('data-parent-id')}"]`).fadeOut(200, function(){
$(contextMenu).remove();
});
}
return false;
});
// when mouse is over an item
$(contextMenu).find('.context-menu-item').on('mouseover', function (e) {
// mark other items as inactive
$(contextMenu).find('.context-menu-item').removeClass('context-menu-item-active');
// mark this item as active
$(this).addClass('context-menu-item-active');
// close any submenu that doesn't belong to this item
$(`.context-menu[data-parent-id="${menu_id}"]`).remove();
// mark this context menu as active
$(contextMenu).addClass('context-menu-active');
})
// open submenu if applicable
$(`#context-menu-${menu_id} > li.context-menu-item-submenu`).on('mouseover', function (e) {
// open submenu only if it's not already open
if($(`.context-menu[data-id="${menu_id}-${$(this).attr('data-action')}"]`).length === 0){
let item_rect_box = this.getBoundingClientRect();
// close other submenus
$(`.context-menu[parent-element-id="${menu_id}"]`).remove();
// open the new submenu
UIContextMenu({
items: options.items[parseInt($(this).attr('data-action'))].items,
parent_id: menu_id,
is_submenu: true,
id: menu_id + '-' + $(this).attr('data-action'),
position:{
top: item_rect_box.top - 5,
left: x_pos + item_rect_box.width + 15,
}
})
}
return false;
});
// useful in cases such as where a menue item is over a window, this prevents from the mousedown event
// reaching the window underneath
$(`#context-menu-${menu_id} > li:not(.context-menu-item-disabled)`).on('mousedown', function (e) {
e.preventDefault();
e.stopPropagation();
return false;
})
//disable parent scroll
if(options.parent_element){
$(options.parent_element).css('overflow', 'hidden');
$(options.parent_element).parent().addClass('children-have-open-contextmenu');
$(options.parent_element).addClass('has-open-contextmenu');
}
$(contextMenu).on("remove", function () {
// when removing, make parent scrollable again
if(options.parent_element){
$(options.parent_element).parent().removeClass('children-have-open-contextmenu');
$(options.parent_element).css('overflow', 'scroll');
$(options.parent_element).removeClass('has-open-contextmenu');
if($(options.parent_element).hasClass('taskbar-item')){
make_taskbar_sortable()
}
}
})
$(contextMenu).on("contextmenu", function (e) {
e.preventDefault();
e.stopPropagation();
return false;
})
}
window.select_ctxmenu_item = function ($ctxmenu_item){
// remove active class from other items
$($ctxmenu_item).siblings('.context-menu-item').removeClass('context-menu-item-active');
// add active class to the selected item
$($ctxmenu_item).addClass('context-menu-item-active');
}
export default UIContextMenu;

1428
src/UI/UIDesktop.js Normal file

File diff suppressed because it is too large Load Diff

1602
src/UI/UIItem.js Normal file

File diff suppressed because it is too large Load Diff

57
src/UI/UINotification.js Normal file
View File

@ -0,0 +1,57 @@
function UINotification(options){
global_element_id++;
options.content = options.content ?? '';
let h = '';
h += `<div id="ui-notification__${global_element_id}" class="notification antialiased animate__animated animate__fadeInRight animate__slow">`;
h += `<img class="notification-close" src="${html_encode(window.icons['close.svg'])}">`;
h += options.content;
h += `</div>`;
$('body').append(h);
const el_notification = document.getElementById(`ui-notification__${global_element_id}`);
$(el_notification).show(0, function(e){
// options.onAppend()
if(options.onAppend && typeof options.onAppend === 'function'){
options.onAppend(el_notification);
}
})
// Show Notification
$(el_notification).delay(100).show(0).
// In the right position (the mouse)
css({
top: toolbar_height + 15,
});
return el_notification;
}
$(document).on('click', '.notification', function(e){
if($(e.target).hasClass('notification')){
if(options.click && typeof options.click === 'function'){
options.click(e);
}
window.close_notification(e.target);
}else{
window.close_notification($(e.target).closest('.notification'));
}
});
$(document).on('click', '.notification-close', function(e){
window.close_notification($(e.target).closest('.notification'));
});
window.close_notification = function(el_notification){
$(el_notification).addClass('animate__fadeOutRight');
setTimeout(function(){
$(el_notification).remove();
}, 500);
}
export default UINotification;

85
src/UI/UIPopover.js Normal file
View File

@ -0,0 +1,85 @@
// todo change to apps popover or sth
function UIPopover(options){
// skip if popover already open
if(options.parent_element && $(options.parent_element).hasClass('has-open-popover'))
return;
$('.window-active .window-app-iframe').css('pointer-events', 'none');
global_element_id++;
options.content = options.content ?? '';
let h = '';
h += `<div id="popover-${global_element_id}" class="popover">`;
h += options.content;
h += `</div>`;
$('body').append(h);
const el_popover = document.getElementById(`popover-${global_element_id}`);
$(el_popover).show(0, function(e){
// options.onAppend()
if(options.onAppend && typeof options.onAppend === 'function'){
options.onAppend(el_popover);
}
})
let x_pos;
let y_pos;
if(options.parent_element){
$(options.parent_element).addClass('has-open-popover');
}
$(el_popover).on("remove", function () {
if(options.parent_element){
$(options.parent_element).removeClass('has-open-popover');
}
})
function position_popover(){
// X position
const popover_width = options.width ?? $(el_popover).width();
if(options.center_horizontally){
x_pos = window.innerWidth/2 - popover_width/2 - 15;
}else{
if(options.position === 'bottom' || options.position === 'top')
x_pos = options.left ?? ($(options.snapToElement).offset().left - (popover_width/ 2) + 10);
else
x_pos = options.left ?? ($(options.snapToElement).offset().left + 5);
}
// Y position
const popover_height = options.height ?? $(el_popover).height();
if(options.center_horizontally){
y_pos = options.top ?? (window.innerHeight - (taskbar_height + popover_height + 10));
}else{
y_pos = options.top ?? ($(options.snapToElement).offset().top + $(options.snapToElement).height() + 5);
}
$(el_popover).css({
left: x_pos + "px",
top: y_pos + "px",
});
}
position_popover();
// If the window is resized, reposition the popover
$(window).on('resize', function(){
position_popover();
});
// Show Popover
$(el_popover).delay(100).show(0).
// In the right position (the mouse)
css({
left: x_pos + "px",
top: y_pos + "px",
});
return el_popover;
}
export default UIPopover;

103
src/UI/UIPrompt.js Normal file
View File

@ -0,0 +1,103 @@
import UIWindow from './UIWindow.js'
function UIPrompt(options){
// set sensible defaults
if(arguments.length > 0){
// if first argument is a string, then assume it is the message
if(isString(arguments[0])){
options = {};
options.message = arguments[0];
}
// if second argument is an array, then assume it is the buttons
if(arguments[1] && Array.isArray(arguments[1])){
options.buttons = arguments[1];
}
}
return new Promise(async (resolve) => {
// provide an 'OK' button if no buttons are provided
if(!options.buttons || options.buttons.length === 0){
options.buttons = [
{label: 'Cancel', value: false, type: 'default'},
{label: 'OK', value: true, type: 'primary'},
]
}
let h = '';
// message
h += `<div class="window-prompt-message">${options.message}</div>`;
// prompt
h += `<div class="window-alert-prompt" style="margin-top: 20px;">`;
h += `<input type="text" class="prompt-input" placeholder="${options.placeholder ?? ''}" value="${options.value ?? ''}">`;
h += `</div>`;
// buttons
if(options.buttons && options.buttons.length > 0){
h += `<div style="overflow:hidden; margin-top:20px; float:right;">`;
h += `<button class="button button-default prompt-resp-button prompt-resp-btn-cancel" data-label="Cancel" style="padding: 0 20px;">Cancel</button>`;
h += `<button class="button button-primary prompt-resp-button prompt-resp-btn-ok" data-label="OK" data-value="true" autofocus>OK</button>`;
h += `</div>`;
}
const el_window = await UIWindow({
title: null,
icon: null,
uid: null,
is_dir: false,
message: options.message,
backdrop: options.backdrop ?? false,
is_resizable: false,
is_droppable: false,
has_head: false,
stay_on_top: options.stay_on_top ?? false,
selectable_body: false,
draggable_body: true,
allow_context_menu: false,
show_in_taskbar: false,
window_class: 'window-alert',
dominant: true,
body_content: h,
width: 450,
parent_uuid: options.parent_uuid,
onAppend: function(this_window){
setTimeout(function(){
$(this_window).find('.prompt-input').get(0).focus({preventScroll:true});
}, 30);
},
...options.window_options,
window_css:{
height: 'initial',
},
body_css: {
width: 'initial',
padding: '20px',
'background-color': 'rgba(231, 238, 245, .95)',
'backdrop-filter': 'blur(3px)',
}
});
// focus to primary btn
$(el_window).find('.button-primary').focus();
// --------------------------------------------------------
// Button pressed
// --------------------------------------------------------
$(el_window).find('.prompt-resp-button').on('click', async function(event){
event.preventDefault();
event.stopPropagation();
if($(this).attr('data-value') === 'true'){
resolve($(el_window).find('.prompt-input').val());
}else{
resolve(false);
}
$(el_window).close();
return false;
})
$(el_window).find('.prompt-input').on('keyup', async function(e){
if(e.keyCode === 13){
$(el_window).find('.prompt-resp-btn-ok').click();
}
})
})
}
export default UIPrompt;

286
src/UI/UITaskbar.js Normal file
View File

@ -0,0 +1,286 @@
import UITaskbarItem from './UITaskbarItem.js'
import UIPopover from './UIPopover.js'
async function UITaskbar(options){
global_element_id++;
options = options ?? {};
options.content = options.content ?? '';
// get launch apps
$.ajax({
url: api_origin + "/get-launch-apps",
type: 'GET',
async: true,
contentType: "application/json",
headers: {
"Authorization": "Bearer "+auth_token
},
success: function (apps){
window.launch_apps = apps;
}
});
let h = '';
h += `<div id="ui-taskbar_${global_element_id}" class="taskbar" style="height:${window.taskbar_height}px;"><span id='clock'></span></div>`;
$('.desktop').append(h);
//---------------------------------------------
// add `Start` to taskbar
//---------------------------------------------
UITaskbarItem({
icon: window.icons['start.svg'],
name: 'Start',
sortable: false,
keep_in_taskbar: true,
disable_context_menu: true,
onClick: async function(item){
// skip if popover already open
if($(item).hasClass('has-open-popover'))
return;
// show popover
let popover = UIPopover({
content: `<div class="launch-popover hide-scrollbar"><span class="close-launch-popover">✕</span></div>`,
snapToElement: item,
parent_element: item,
width: 500,
height: 500,
center_horizontally: true,
});
// In the rare case that launch_apps is not populated yet, get it from the server
// then populate the popover
if(!launch_apps || !launch_apps.recent || launch_apps.recent.length === 0){
// get launch apps
launch_apps = await $.ajax({
url: api_origin + "/get-launch-apps",
type: 'GET',
async: true,
contentType: "application/json",
headers: {
"Authorization": "Bearer "+auth_token
},
});
}
let apps_str = '';
apps_str += `<div style="margin-bottom: 10px; padding: 5px; position: relative;">`
apps_str += `<input style="background-image:url(${window.icons['magnifier-outline.svg']});" class="launch-search">`;
apps_str += `<img class="launch-search-clear" src="${window.icons['close.svg']}">`;
apps_str += `</div>`;
// -------------------------------------------
// Recent apps
// -------------------------------------------
if(launch_apps.recent.length > 0){
// heading
apps_str += `<h1 class="start-section-heading start-section-heading-recent">Recent</h1>`;
// apps
apps_str += `<div class="launch-apps-recent">`;
for (let index = 0; index < window.launch_recent_apps_count && index < launch_apps.recent.length; index++) {
const app_info = launch_apps.recent[index];
apps_str += `<div title="${html_encode(app_info.title)}" data-name="${html_encode(app_info.name)}" class="start-app-card">`;
apps_str += `<div class="start-app" data-app-name="${html_encode(app_info.name)}" data-app-uuid="${html_encode(app_info.uuid)}" data-app-icon="${html_encode(app_info.icon)}" data-app-title="${html_encode(app_info.title)}">`;
apps_str += `<img class="start-app-icon" src="${html_encode(app_info.icon ? app_info.icon : window.icons['app.svg'])}">`;
apps_str += `<span class="start-app-title">${html_encode(app_info.title)}</span>`;
apps_str += `</div>`;
apps_str += `</div>`;
}
apps_str += `</div>`;
}
// -------------------------------------------
// Reccomended apps
// -------------------------------------------
if(launch_apps.recommended.length > 0){
// heading
apps_str += `<h1 class="start-section-heading start-section-heading-recommended" style="${launch_apps.recent.length > 0 ? 'padding-top: 30px;' : ''}">Recommended</h1>`;
// apps
apps_str += `<div class="launch-apps-recommended">`;
for (let index = 0; index < launch_apps.recommended.length; index++) {
const app_info = launch_apps.recommended[index];
apps_str += `<div title="${html_encode(app_info.title)}" data-name="${html_encode(app_info.name)}" class="start-app-card">`;
apps_str += `<div class="start-app" data-app-name="${html_encode(app_info.name)}" data-app-uuid="${html_encode(app_info.uuid)}" data-app-icon="${html_encode(app_info.icon)}" data-app-title="${html_encode(app_info.title)}">`;
apps_str += `<img class="start-app-icon" src="${html_encode(app_info.icon ? app_info.icon : window.icons['app.svg'])}">`;
apps_str += `<span class="start-app-title">${html_encode(app_info.title)}</span>`;
apps_str += `</div>`;
apps_str += `</div>`;
}
apps_str += `</div>`;
}
// add apps to popover
$(popover).find('.launch-popover').append(apps_str);
// focus on search input only if not on mobile
if(!isMobile.phone)
$(popover).find('.launch-search').focus();
// make apps draggable
$(popover).find('.start-app').draggable({
appendTo: "body",
helper: "clone",
revert: "invalid",
connectToSortable: ".taskbar",
//containment: "document",
zIndex: parseInt($(popover).css('z-index')) + 1,
scroll: false,
distance: 5,
revertDuration: 100,
helper: 'clone',
cursorAt: { left: 18, top: 20 },
start: function(event, ui){
},
drag: function(event, ui){
},
stop: function(){
}
});
}
});
//---------------------------------------------
// add `Explorer` to the taskbar
//---------------------------------------------
UITaskbarItem({
icon: window.icons['folders.svg'],
app: 'explorer',
name: 'Explorer',
sortable: false,
keep_in_taskbar: true,
lock_keep_in_taskbar: true,
onClick: function(){
let open_window_count = parseInt($(`.taskbar-item[data-app="explorer"]`).attr('data-open-windows'));
if(open_window_count === 0){
launch_app({ name: 'explorer', path: window.home_path});
}else{
return false;
}
}
})
//---------------------------------------------
// Add other useful apps to the taskbar
//---------------------------------------------
if(window.user.taskbar_items && window.user.taskbar_items.length > 0){
for (let index = 0; index < window.user.taskbar_items.length; index++) {
const app_info = window.user.taskbar_items[index];
// add taskbar item for each app
UITaskbarItem({
icon: app_info.icon,
app: app_info.name,
name: app_info.title,
keep_in_taskbar: true,
onClick: function(){
let open_window_count = parseInt($(`.taskbar-item[data-app="${app_info.name}"]`).attr('data-open-windows'));
if(open_window_count === 0){
launch_app({
name: app_info.name,
})
}else{
return false;
}
}
});
}
}
//---------------------------------------------
// add `Trash` to the taskbar
//---------------------------------------------
const trash = await puter.fs.stat(trash_path);
if(window.socket){
window.socket.emit('trash.is_empty', {is_empty: trash.is_empty});
}
UITaskbarItem({
icon: trash.is_empty ? window.icons['trash.svg'] : window.icons['trash-full.svg'],
app: 'trash',
name: 'Trash',
sortable: false,
keep_in_taskbar: true,
lock_keep_in_taskbar: true,
onClick: function(){
let open_windows = $(`.window[data-path="${html_encode(trash_path)}"]`);
if(open_windows.length === 0){
launch_app({ name: 'explorer', path: window.trash_path});
}else{
open_windows.focusWindow();
}
},
onItemsDrop: function(items){
move_items(items, trash_path);
}
})
make_taskbar_sortable();
}
window.make_taskbar_sortable = function(){
//-------------------------------------------
// Taskbar is sortable
//-------------------------------------------
$('.taskbar').sortable({
axis: "x",
items: '.taskbar-item-sortable:not(.has-open-contextmenu)',
cancel: '.has-open-contextmenu',
placeholder: "taskbar-item-sortable-placeholder",
helper : 'clone',
distance: 5,
revert: 10,
receive: function(event, ui){
if(!$(ui.item).hasClass('taskbar-item')){
// if app is already in taskbar, cancel
if($(`.taskbar-item[data-app="${$(ui.item).attr('data-app-name')}"]`).length !== 0){
$(this).sortable('cancel');
$('.taskbar .start-app').remove();
return;
}else{
}
}
},
update: function(event, ui){
if(!$(ui.item).hasClass('taskbar-item')){
// if app is already in taskbar, cancel
if($(`.taskbar-item[data-app="${$(ui.item).attr('data-app-name')}"]`).length !== 0){
$(this).sortable('cancel');
$('.taskbar .start-app').remove();
return;
}
let item = UITaskbarItem({
icon: $(ui.item).attr('data-app-icon'),
app: $(ui.item).attr('data-app-name'),
name: $(ui.item).attr('data-app-title'),
append_to_taskbar: false,
keep_in_taskbar: true,
onClick: function(){
let open_window_count = parseInt($(`.taskbar-item[data-app="${$(ui.item).attr('data-app-name')}"]`).attr('data-open-windows'));
if(open_window_count === 0){
launch_app({
name: $(ui.item).attr('data-app-name'),
})
}else{
return false;
}
}
});
let el = ($(item).detach())
$(el).insertAfter(ui.item);
// $(ui.item).insertBefore(`<h1>Hello!</h1>`);
$(el).show();
$(ui.item).removeItems();
update_taskbar();
}
// only proceed to update DB if the item sorted was a pinned item otherwise no point in updating the taskbar in DB
else if($(ui.item).attr('data-keep-in-taskbar') === 'true'){
update_taskbar();
}
},
});
}
export default UITaskbar;

346
src/UI/UITaskbarItem.js Normal file
View File

@ -0,0 +1,346 @@
import UIContextMenu from './UIContextMenu.js';
let tray_item_id = 1;
function UITaskbarItem(options){
let h = ``;
tray_item_id++;
options.sortable = options.sortable ?? true;
options.open_windows_count = options.open_windows_count ?? 0;
options.lock_keep_in_taskbar = options.lock_keep_in_taskbar ?? false;
options.append_to_taskbar = options.append_to_taskbar ?? true;
const element_id = global_element_id++;
h += `<div class = "taskbar-item ${options.sortable ? 'taskbar-item-sortable' : ''} disable-user-select"
id = "taskbar-item-${tray_item_id}"
data-taskbar-item-id = "${tray_item_id}"
data-element-id = "${html_encode(element_id)}"
data-name = "${html_encode(options.name)}"
data-app = "${html_encode(options.app)}"
data-keep-in-taskbar = "${html_encode(options.keep_in_taskbar ?? 'false')}"
data-open-windows="${(options.open_windows_count)}"
title = "${html_encode(options.name)}"
style= "${options.style ? html_encode(options.style) : ''}"
>`;
let icon = options.icon ? options.icon : window.icons['app.svg'];
if(options.app === 'explorer')
icon = window.icons['folders.svg'];
// taskbar icon
h += `<div class="taskbar-icon">`;
h += `<img src="${html_encode(icon)}" style="${options.group === 'apps' ? 'filter:none;' : ''}">`;
h += `</div>`;
// active indicator
if(options.app !== 'apps')
h += `<span class="active-taskbar-indicator"></span>`;
h += `</div>`;
if(options.append_to_taskbar)
$('.taskbar').append(h);
else
$('body').prepend(h);
const el_taskbar_item = document.querySelector(`#taskbar-item-${tray_item_id}`);
// fade in the taskbar item
$(el_taskbar_item).show(50);
$(el_taskbar_item).on("click", function(){
// If this item has an open context menu, don't do anything
if($(el_taskbar_item).hasClass('has-open-contextmenu'))
return;
if(options.onClick === undefined || options.onClick(el_taskbar_item) === false){
// re-show each window in this app group
$(`.window[data-app="${options.app}"]`).showWindow();
}
})
$(el_taskbar_item).on('contextmenu taphold', function(e){
// seems like the only way to stop sortable is to destroy it
if(options.sortable) {
$('.taskbar').sortable('destroy');
}
e.preventDefault();
e.stopPropagation();
// If context menu is disabled on this item, return
if(options.disable_context_menu)
return;
// don't allow context menu to open if it's already open
if($(el_taskbar_item).hasClass('has-open-contextmenu'))
return;
const menu_items =[];
const open_windows = parseInt($(el_taskbar_item).attr('data-open-windows'));
// -------------------------------------------
// List of open windows belonging to this app
// -------------------------------------------
$(`.window[data-app="${options.app}"]`).each(function(){
menu_items.push({
html: $(this).find(`.window-head-title`).html(),
val: $(this).attr('data-id'),
onClick: function(e){
$(`.window[data-id="${e.value}"]`).showWindow();
}
})
})
// -------------------------------------------
// divider
// -------------------------------------------
if(menu_items.length > 0)
menu_items.push('-');
//------------------------------------------
// New Window
//------------------------------------------
if(options.app){
menu_items.push({
html: 'New Window',
val: $(this).attr('data-id'),
onClick: function(){
launch_app({
name: options.app,
maximized: (isMobile.phone || isMobile.tablet),
})
}
})
}
//------------------------------------------
// Empty Trash
//------------------------------------------
if(options.app === 'trash' && options.name === 'Trash'){
// divider
menu_items.push('-');
// Empty Trash menu item
menu_items.push({
html: 'Empty Trash',
val: $(this).attr('data-id'),
onClick: async function(){
empty_trash();
}
})
}
//------------------------------------------
// Remove from Taskbar
//------------------------------------------
if(options.keep_in_taskbar && !options.lock_keep_in_taskbar){
menu_items.push({
html: 'Remove from Taskbar',
val: $(this).attr('data-id'),
onClick: function(){
$(el_taskbar_item).attr('data-keep-in-taskbar', 'false');
if($(el_taskbar_item).attr('data-open-windows') === '0'){
remove_taskbar_item(el_taskbar_item);
}
update_taskbar();
options.keep_in_taskbar = false;
}
})
}
//------------------------------------------
// Keep in Taskbar
//------------------------------------------
else if(!options.keep_in_taskbar){
menu_items.push({
html: 'Keep in Taskbar',
val: $(this).attr('data-id'),
onClick: function(){
$(el_taskbar_item).attr('data-keep-in-taskbar', 'true');
update_taskbar();
options.keep_in_taskbar = true;
}
})
}
if(open_windows > 0){
// -------------------------------------------
// divider
// -------------------------------------------
menu_items.push('-');
// -------------------------------------------
// Show All Windows
// -------------------------------------------
menu_items.push({
html: "Show All Windows",
onClick: function(){
if(open_windows > 0)
$(el_taskbar_item).trigger('click');
}
})
// -------------------------------------------
// Hide All Windows
// -------------------------------------------
menu_items.push({
html: "Hide All Windows",
onClick: function(){
if(open_windows > 0)
$(`.window[data-app="${options.app}"]`).hideWindow();
}
})
// -------------------------------------------
// Close All Windows
// -------------------------------------------
menu_items.push({
html: "Close All Windows",
onClick: function(){
$(`.window[data-app="${options.app}"]`).close();
}
})
}
const pos = el_taskbar_item.getBoundingClientRect();
UIContextMenu({
parent_element: el_taskbar_item,
position: {top: pos.top - 15, left: pos.left+5},
items: menu_items
});
return false;
});
$( el_taskbar_item ).tooltip({
items: ".taskbar:not(.children-have-open-contextmenu) .taskbar-item",
position: {
my: "center bottom-20",
at: "center top",
using: function( position, feedback ) {
$( this ).css( position );
$( "<div>" )
.addClass( "arrow" )
.addClass( feedback.vertical )
.addClass( feedback.horizontal )
.appendTo( this );
}
}
});
// --------------------------------------------------------
// Droppable
// --------------------------------------------------------
$(el_taskbar_item).droppable({
accept: '.item',
// 'pointer' is very important because of active window tracking is based on the position of cursor.
tolerance: 'pointer',
drop: async function( event, ui ) {
// Check if hovering over an item that is VISIBILE
if($(event.target).closest('.window').attr('data-id') !== $(mouseover_window).attr('data-id'))
return;
// If ctrl is pressed and source is Trashed, cancel whole operation
if(event.ctrlKey && path.dirname($(ui.draggable).attr('data-path')) === window.trash_path)
return;
const items_to_move = []
// First item
items_to_move.push(ui.draggable);
// All subsequent items
const cloned_items = document.getElementsByClassName('item-selected-clone');
for(let i =0; i<cloned_items.length; i++){
const source_item = document.getElementById('item-' + $(cloned_items[i]).attr('data-id'));
if(source_item !== null)
items_to_move.push(source_item);
}
// --------------------------------------------------------
// If `options.onItemsDrop` is set, call it with the items to move
//--------------------------------------------------------
if(options.onItemsDrop && typeof options.onItemsDrop === 'function'){
options.onItemsDrop(items_to_move);
return;
}
// --------------------------------------------------------
// If dropped on an app, open the app with the dropped item as an argument
//--------------------------------------------------------
else if(options.app){
// an array that hold the items to sign
const items_to_sign = [];
// prepare items to sign
for(let i=0; i < items_to_move.length; i++){
items_to_sign.push({
name: $(items_to_move[i]).attr('data-name'),
uid: $(items_to_move[i]).attr('data-uid'),
action: 'write',
path: $(items_to_move[i]).attr('data-path')
});
}
// open each item
for (let i = 0; i < items_to_sign.length; i++) {
const item = items_to_sign[i];
launch_app({
name: options.app,
file_path: item.path,
// app_obj: open_item_meta.suggested_apps[0],
window_title: item.name,
file_uid: item.uid,
// file_signature: item,
});
}
// deselect dragged item
for(let i=0; i < items_to_move.length; i++)
$(items_to_move[i]).removeClass('item-selected');
}
// Unselect directory/app if item is dropped
if(options.is_dir || options.app){
$(el_taskbar_item).removeClass('active');
$(el_taskbar_item).tooltip('close');
$('.ui-draggable-dragging .item-name, .item-selected-clone .item-name').css('opacity', 'initial')
$('.item-container').removeClass('item-container-transparent-border')
}
// Re-enable droppable on all item-container
$('.item-container').droppable('enable')
return false;
},
over: function(event, ui){
// Check hovering over an item that is VISIBILE
const $event_parent_win = $(event.target).closest('.window')
if( $event_parent_win.length > 0 && $event_parent_win.attr('data-id') !== $(mouseover_window).attr('data-id'))
return;
// Don't do anything if the dragged item is NOT a UIItem
if(!$(ui.draggable).hasClass('item'))
return;
// If this is a directory or an app, and an item was dragged over it, highlight it.
if(options.is_dir || options.app){
$(el_taskbar_item).addClass('active');
// show tooltip of this item
$(el_taskbar_item).tooltip().mouseover();
// make item name partially transparent
$('.ui-draggable-dragging .item-name, .item-selected-clone .item-name').css('opacity', 0.1)
// remove all item-container active borders
$('.item-container').addClass('item-container-transparent-border')
}
// Disable all window bodies
$('.item-container').droppable( 'disable' )
},
out: function(event, ui){
// Don't do anything if the dragged item is NOT a UIItem
if(!$(ui.draggable).hasClass('item'))
return;
// Unselect directory/app if item is dragged out
if(options.is_dir || options.app){
$(el_taskbar_item).removeClass('active');
$(el_taskbar_item).tooltip('close');
$('.ui-draggable-dragging .item-name, .item-selected-clone .item-name').css('opacity', 'initial')
$('.item-container').removeClass('item-container-transparent-border')
}
$('.item-container').droppable( 'enable' )
}
});
return el_taskbar_item;
}
export default UITaskbarItem

3233
src/UI/UIWindow.js Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,110 @@
import UIWindow from './UIWindow.js'
async function UIWindowChangePassword(){
const internal_id = window.uuidv4();
let h = '';
h += `<div class="change-password" style="padding: 20px; border-bottom: 1px solid #ced7e1;">`;
// error msg
h += `<div class="form-error-msg"></div>`;
// success msg
h += `<div class="form-success-msg"></div>`;
// current password
h += `<div style="overflow: hidden; margin-bottom: 20px;">`;
h += `<label for="current-password-${internal_id}">Current Password</label>`;
h += `<input id="current-password-${internal_id}" class="current-password" type="password" name="current-password" autocomplete="current-password" />`;
h += `</div>`;
// new password
h += `<div style="overflow: hidden; margin-top: 20px; margin-bottom: 20px;">`;
h += `<label for="new-password-${internal_id}">New Password</label>`;
h += `<input id="new-password-${internal_id}" type="password" class="new-password" name="new-password" autocomplete="off" />`;
h += `</div>`;
// confirm new password
h += `<div style="overflow: hidden; margin-top: 20px; margin-bottom: 20px;">`;
h += `<label for="confirm-new-password-${internal_id}">Confirm New Password</label>`;
h += `<input id="confirm-new-password-${internal_id}" type="password" name="confirm-new-password" class="confirm-new-password" autocomplete="off" />`;
h += `</div>`;
// Change Password
h += `<button class="change-password-btn button button-primary button-block button-normal">Change Password</button>`;
h += `</div>`;
const el_window = await UIWindow({
title: 'Change Password',
app: 'change-passowrd',
single_instance: true,
icon: null,
uid: null,
is_dir: false,
body_content: h,
draggable_body: false,
has_head: true,
selectable_body: false,
draggable_body: false,
allow_context_menu: false,
is_resizable: false,
is_droppable: false,
init_center: true,
allow_native_ctxmenu: false,
allow_user_select: false,
width: 350,
height: 'auto',
dominant: true,
show_in_taskbar: false,
onAppend: function(this_window){
$(this_window).find(`.current-password`).get(0).focus({preventScroll:true});
},
window_class: 'window-publishWebsite',
body_css: {
width: 'initial',
height: '100%',
'background-color': 'rgb(245 247 249)',
'backdrop-filter': 'blur(3px)',
}
})
$(el_window).find('.change-password-btn').on('click', function(e){
const current_password = $(el_window).find('.current-password').val();
const new_password = $(el_window).find('.new-password').val();
const confirm_new_password = $(el_window).find('.confirm-new-password').val();
let data;
if(current_password === '' || new_password === '' || confirm_new_password === ''){
$(el_window).find('.form-error-msg').html('All fields are required.');
$(el_window).find('.form-error-msg').fadeIn();
return;
}
else if(new_password !== confirm_new_password){
$(el_window).find('.form-error-msg').html('`New Password` and `Confirm New Password` do not match.');
$(el_window).find('.form-error-msg').fadeIn();
return;
}
$(el_window).find('.form-error-msg').hide();
$.ajax({
url: api_origin + "/passwd",
type: 'POST',
async: true,
headers: {
"Authorization": "Bearer "+auth_token
},
contentType: "application/json",
data: JSON.stringify({
old_pass: current_password,
new_pass: new_password,
}),
success: function (data){
$(el_window).find('.form-success-msg').html('Password changed successfully.');
$(el_window).find('.form-success-msg').fadeIn();
$(el_window).find('input').val('');
},
error: function (err){
$(el_window).find('.form-error-msg').html(err.responseText);
$(el_window).find('.form-error-msg').fadeIn();
}
});
})
}
export default UIWindowChangePassword

View File

@ -0,0 +1,111 @@
import UIWindow from './UIWindow.js'
import update_username_in_gui from '../helpers/update_username_in_gui.js'
async function UIWindowChangeUsername(){
const internal_id = window.uuidv4();
let h = '';
h += `<div class="change-username" style="padding: 20px; border-bottom: 1px solid #ced7e1;">`;
// error msg
h += `<div class="form-error-msg"></div>`;
// success msg
h += `<div class="form-success-msg"></div>`;
// new username
h += `<div style="overflow: hidden; margin-top: 10px; margin-bottom: 30px;">`;
h += `<label for="confirm-new-username-${internal_id}">New Username</label>`;
h += `<input id="confirm-new-username-${internal_id}" type="text" name="new-username" class="new-username" autocomplete="off" />`;
h += `</div>`;
// Change Username
h += `<button class="change-username-btn button button-primary button-block button-normal">Change Username</button>`;
h += `</div>`;
const el_window = await UIWindow({
title: 'Change Username',
app: 'change-username',
single_instance: true,
icon: null,
uid: null,
is_dir: false,
body_content: h,
draggable_body: false,
has_head: true,
selectable_body: false,
draggable_body: false,
allow_context_menu: false,
is_resizable: false,
is_droppable: false,
init_center: true,
allow_native_ctxmenu: false,
allow_user_select: false,
width: 350,
height: 'auto',
dominant: true,
show_in_taskbar: false,
onAppend: function(this_window){
$(this_window).find(`.new-username`).get(0)?.focus({preventScroll:true});
},
window_class: 'window-publishWebsite',
body_css: {
width: 'initial',
height: '100%',
'background-color': 'rgb(245 247 249)',
'backdrop-filter': 'blur(3px)',
}
})
$(el_window).find('.change-username-btn').on('click', function(e){
// hide previous error/success msg
$(el_window).find('.form-success-msg, .form-success-msg').hide();
const new_username = $(el_window).find('.new-username').val();
if(!new_username){
$(el_window).find('.form-error-msg').html('All fields are required.');
$(el_window).find('.form-error-msg').fadeIn();
return;
}
$(el_window).find('.form-error-msg').hide();
// disable button
$(el_window).find('.change-username-btn').addClass('disabled');
// disable input
$(el_window).find('.new-username').attr('disabled', true);
$.ajax({
url: api_origin + "/change_username",
type: 'POST',
async: true,
headers: {
"Authorization": "Bearer "+auth_token
},
contentType: "application/json",
data: JSON.stringify({
new_username: new_username,
}),
success: function (data){
$(el_window).find('.form-success-msg').html('Username updated successfully.');
$(el_window).find('.form-success-msg').fadeIn();
$(el_window).find('input').val('');
// update auth data
update_username_in_gui(new_username);
// update username
window.user.username = new_username;
// enable button
$(el_window).find('.change-username-btn').removeClass('disabled');
// enable input
$(el_window).find('.new-username').attr('disabled', false);
},
error: function (err){
$(el_window).find('.form-error-msg').html(html_encode(err.responseJSON?.message));
$(el_window).find('.form-error-msg').fadeIn();
// enable button
$(el_window).find('.change-username-btn').removeClass('disabled');
// enable input
$(el_window).find('.new-username').attr('disabled', false);
}
});
})
}
export default UIWindowChangeUsername

View File

@ -0,0 +1,55 @@
import UIWindow from './UIWindow.js'
import UIWindowSaveAccount from './UIWindowSaveAccount.js';
async function UIWindowClaimReferral(options){
let h = '';
h += `<div>`;
h += `<div class="qr-code-window-close-btn generic-close-window-button disable-user-select"> &times; </div>`;
h += `<img src="${window.icons['present.svg']}" style="width: 70px; margin: 20px auto 20px; display: block; margin-bottom: 20px;">`;
h += `<h1 style="font-weight: 400; padding: 0 10px; font-size: 21px; text-align: center; margin-bottom: 0; color: #60626d; -webkit-font-smoothing: antialiased;">You have been referred to Puter by a friend!</h1>`;
h += `<p style="text-align: center; font-size: 16px; padding: 20px; font-weight: 400; margin: -10px 10px 0px 10px; -webkit-font-smoothing: antialiased; color: #5f626d;">Create an account and confirm your email address to receive 1 GB of free storage. Your friend will get 1 GB of free storage too.</p>`;
h += `<button class="button button-primary button-block create-account-ref-btn" style="display: block;">Create Account</button>`;
h += `</div>`;
const el_window = await UIWindow({
title: `Refer a friend!`,
icon: null,
uid: null,
is_dir: false,
body_content: h,
has_head: false,
selectable_body: false,
draggable_body: true,
allow_context_menu: false,
is_draggable: true,
is_resizable: false,
is_droppable: false,
init_center: true,
allow_native_ctxmenu: true,
allow_user_select: true,
onAppend: function(el_window){
},
width: 400,
dominant: true,
window_css: {
height: 'initial',
},
body_css: {
padding: '10px',
width: 'initial',
'max-height': 'calc(100vh - 200px)',
'background-color': 'rgb(241 246 251)',
'backdrop-filter': 'blur(3px)',
'padding': '10px 20px 20px 20px',
'height': 'initial',
}
});
$(el_window).find('.create-account-ref-btn').on('click', function(e){
UIWindowSaveAccount();
$(el_window).close();
})
}
export default UIWindowClaimReferral

View File

@ -0,0 +1,110 @@
import UIWindow from './UIWindow.js'
async function UIWindowColorPicker(options){
// set sensible defaults
if(arguments.length > 0){
// if first argument is a string, then assume it is the default color
if(isString(arguments[0])){
options = {};
options.default = arguments[0];
}
}
options = options ?? {};
return new Promise(async (resolve) => {
let colorPicker;
let h = ``;
h += `<div>`;
h += `<div style="padding: 20px; border-bottom: 1px solid #ced7e1; width: 100%; box-sizing: border-box;">`;
// picker
h += `<div style="padding: 0; margin-bottom: 20px;">`;
h += `<div class="picker"></div>`;
h += `</div>`;
// Select button
h += `<button class="select-btn button button-primary button-block button-normal">Select</button>`
h += `</form>`;
h += `</div>`;
h += `</div>`;
const el_window = await UIWindow({
title: 'Select color…',
app: 'color-picker',
single_instance: true,
icon: null,
uid: null,
is_dir: false,
body_content: h,
draggable_body: false,
has_head: true,
selectable_body: false,
draggable_body: false,
allow_context_menu: false,
is_draggable: true,
is_droppable: false,
is_resizable: false,
stay_on_top: false,
allow_native_ctxmenu: true,
allow_user_select: true,
...options.window_options,
width: 350,
dominant: true,
on_close: async ()=>{
resolve(false)
},
onAppend: function(window){
colorPicker = new iro.ColorPicker($(window).find('.picker').get(0), {
layout: [
{
component: iro.ui.Box,
options: {
layoutDirection: 'horizontal',
width: 265,
height: 265,
}
},
{
component: iro.ui.Slider,
options: {
sliderType: 'alpha',
layoutDirection: 'horizontal',
height: 265,
width:265,
}
},
{
component: iro.ui.Slider,
options: {
sliderType: 'hue',
}
},
],
// Set the initial color to pure red
color: options.default ?? "#f00",
});
},
window_class: 'window-login',
window_css:{
height: 'initial',
},
body_css: {
width: 'initial',
padding: '0',
'background-color': 'rgba(231, 238, 245, .95)',
'backdrop-filter': 'blur(3px)',
}
})
$(el_window).find('.select-btn').on('click', function(e){
resolve({color: colorPicker.color.hex8String});
$(el_window).close();
})
$(el_window).find('.font-selector').on('click', function(e){
$(el_window).find('.font-selector').removeClass('font-selector-active');
$(this).addClass('font-selector-active');
})
})
}
export default UIWindowColorPicker

View File

@ -0,0 +1,73 @@
import UIWindow from './UIWindow.js'
// todo do this using uid rather than item_path, since item_path is way mroe expensive on the DB
async function UIWindowConfirmDownload(options){
return new Promise(async (resolve) => {
let h = '';
h += `<div>`;
// Confirm download
h +=`<div style="margin-bottom:20px; float:left; padding-top:3px; font-size:15px; overflow: hidden; width: calc(100% - 40px); text-overflow: ellipsis; white-space: nowrap;">`;
// Message
h += `<p style="font-weight:bold;">Do you want to download this file?</p>`;
h += `<div style="overflow:hidden; float:left; width: 100px; height: 100px; display:flex; display: flex; justify-content: center; align-items: center;">`;
h += `<img style="float:left; margin-right: 7px; width: 60px; height: 60px; filter: drop-shadow(0px 0px 1px rgba(102, 102, 102, 1));" src="${html_encode((await item_icon({is_dir: options.is_dir === '1' || options.is_dir === 'true', type: options.type, name: options.name})).image)}" />`;
h += `</div>`;
// Item information
h += `<div style="overflow:hidden;">`;
// Name
h += `<p style="text-overflow: ellipsis; overflow: hidden;"><span class="dl-conf-item-attr">Name:</span> ${options.name ?? options.url}</p>`;
// Type
h += `<p style="text-overflow: ellipsis; overflow: hidden;"><span class="dl-conf-item-attr">Type:</span> ${options.is_dir === '1' || options.is_dir === 'true' ? 'Folder' : options.type ?? 'Unknown File Type'}</p>`;
// Source
h += `<p style="text-overflow: ellipsis; overflow: hidden;"><span class="dl-conf-item-attr">From:</span> ${options.source}</p>`;
h += `</div>`;
h += `</div>`;
// Download
h += `<button style="float:right; margin-top: 15px; margin-right: -2px; margin-left:10px;" class="button button-small button-primary btn-download-confirm">Download</button>`;
// Cancel
h += `<button style="float:right; margin-top: 15px;" class="button button-small btn-download-cancel">Cancel</button>`;
h +=`</div>`;
const el_window = await UIWindow({
title: `Upload`,
icon: window.icons[`app-icon-uploader.svg`],
uid: null,
is_dir: false,
body_content: h,
draggable_body: false,
has_head: false,
selectable_body: false,
draggable_body: true,
allow_context_menu: false,
is_resizable: false,
is_droppable: false,
init_center: true,
allow_native_ctxmenu: false,
allow_user_select: false,
window_class: 'window-upload-progress',
width: 450,
dominant: true,
window_css:{
height: 'initial',
},
body_css: {
padding: '22px',
width: 'initial',
'background-color': 'rgba(231, 238, 245, .95)',
'backdrop-filter': 'blur(3px)',
}
});
$(el_window).find('.btn-download-confirm').on('click submit', function(e){
$(el_window).close();
resolve(true);
})
$(el_window).find('.btn-download-cancel').on('click submit', function(e){
$(el_window).close();
resolve(false);
})
})
}
export default UIWindowConfirmDownload

View File

@ -0,0 +1,63 @@
import UIWindow from './UIWindow.js'
// todo do this using uid rather than item_path, since item_path is way mroe expensive on the DB
async function UIWindowCopyProgress(options){
let h = '';
h += `<div data-copy-operation-id="${options.operation_id}">`;
h += `<div>`;
// spinner
h +=`<svg style="float:left; margin-right: 7px;" xmlns="http://www.w3.org/2000/svg" height="24" width="24" viewBox="0 0 24 24"><title>circle anim</title><g fill="#212121" class="nc-icon-wrapper"><g class="nc-loop-circle-24-icon-f"><path d="M12 24a12 12 0 1 1 12-12 12.013 12.013 0 0 1-12 12zm0-22a10 10 0 1 0 10 10A10.011 10.011 0 0 0 12 2z" fill="#212121" opacity=".4"></path><path d="M24 12h-2A10.011 10.011 0 0 0 12 2V0a12.013 12.013 0 0 1 12 12z" data-color="color-2"></path></g><style>.nc-loop-circle-24-icon-f{--animation-duration:0.5s;transform-origin:12px 12px;animation:nc-loop-circle-anim var(--animation-duration) infinite linear}@keyframes nc-loop-circle-anim{0%{transform:rotate(0)}100%{transform:rotate(360deg)}}</style></g></svg>`;
// Progress report
h +=`<div style="margin-bottom:20px; float:left; padding-top:3px; font-size:15px; overflow: hidden; width: calc(100% - 40px); text-overflow: ellipsis; white-space: nowrap;">`;
// msg
h += `<span class="copy-progress-msg">Copying </span>`;
h += `<span class="copy-from" style="font-weight:strong;"></span>`;
h += `</div>`;
// progress
h += `<div class="copy-progress-bar-container" style="clear:both; margin-top:20px; border-radius:3px;">`;
h += `<div class="copy-progress-bar"></div>`;
h += `</div>`;
// cancel
// h += `<button style="float:right; margin-top: 15px; margin-right: -2px;" class="button button-small copy-cancel-btn">Cancel</button>`;
h +=`</div>`;
h += `</div>`;
const el_window = await UIWindow({
title: `Copying`,
icon: window.icons[`app-icon-copying.svg`],
uid: null,
is_dir: false,
body_content: h,
draggable_body: false,
has_head: false,
selectable_body: false,
draggable_body: true,
allow_context_menu: false,
is_resizable: false,
is_droppable: false,
init_center: true,
allow_native_ctxmenu: false,
allow_user_select: false,
window_class: 'window-copy-progress',
width: 450,
dominant: true,
window_css:{
height: 'initial',
},
body_css: {
padding: '22px',
width: 'initial',
'background-color': 'rgba(231, 238, 245, .95)',
'backdrop-filter': 'blur(3px)',
}
});
$(el_window).find('.copy-cancel-btn').on('click', function(e){
operation_cancelled[options.operation_id] = true;
$(el_window).close();
})
return el_window;
}
export default UIWindowCopyProgress

View File

@ -0,0 +1,189 @@
import UIWindow from './UIWindow.js'
async function UIWindowDesktopBGSettings(){
return new Promise(async (resolve) => {
let h = '';
const original_background_css = $('body').attr('style');
let bg_url = window.desktop_bg_url,
bg_color = window.desktop_bg_color,
bg_fit = window.desktop_bg_fit;
h += `<div style="padding: 10px; border-bottom: 1px solid #ced7e1;">`;
// type
h += `<label>Background:</label>`;
h += `<select class="desktop-bg-type" style="width: 150px; margin-bottom: 20px;">`
h += `<option value="picture">Picture</option>`;
h += `<option value="color">Color</option>`;
h += `</select>`;
// Picture
h += `<div class="desktop-bg-settings-wrapper desktop-bg-settings-picture">`;
h += `<label>Image:</label>`;
h += `<button class="button button-default button-small browse">Browse</button>`;
h += `<label style="margin-top: 20px;">Fit:</label>`;
h += `<select class="desktop-bg-fit" style="width: 150px;">`
h += `<option value="cover">Cover</option>`;
h += `<option value="center">Center</option>`;
h += `<option value="contain">Contain</option>`;
h += `<option value="repeat">Repeat</option>`;
h += `</select>`;
h += `</div>`
// Color
h += `<div class="desktop-bg-settings-wrapper desktop-bg-settings-color">`;
h += `<label>Color:</label>`;
h += `<div class="desktop-bg-color-blocks">`;
h += `<div class="desktop-bg-color-block" data-color="#4F7BB5" style="background-color: #4F7BB5"></div>`;
h += `<div class="desktop-bg-color-block" data-color="#545554" style="background-color: #545554"></div>`;
h += `<div class="desktop-bg-color-block" data-color="#F5D3CE" style="background-color: #F5D3CE"></div>`;
h += `<div class="desktop-bg-color-block" data-color="#52A758" style="background-color: #52A758"></div>`;
h += `<div class="desktop-bg-color-block" data-color="#ad3983" style="background-color: #ad3983"></div>`;
h += `<div class="desktop-bg-color-block" data-color="#ffffff" style="background-color: #ffffff"></div>`;
h += `<div class="desktop-bg-color-block" data-color="#000000" style="background-color: #000000"></div>`;
h += `<div class="desktop-bg-color-block" data-color="#454545" style="background-color: #454545"></div>`;
h += `<div class="desktop-bg-color-block desktop-bg-color-block-palette" data-color="" style="background-image: url(${window.icons['palette.svg']});
background-repeat: no-repeat;
background-size: contain;
background-position: center;"><input type="color" style="width:25px; height: 25px; opacity:0;"></div>`;
h += `</div>`;
h += `</div>`;
h += `<div style="padding-top: 5px; overflow:hidden; margin-top: 25px; border-top: 1px solid #CCC;">`
h += `<button class="button button-primary apply" style="float:right;">Apply</button>`;
h += `<button class="button button-default cancel" style="float:right; margin-right: 10px;">Cancel</button>`;
h += `</div>`;
h += `</div>`;
const el_window = await UIWindow({
title: 'Change Desktop Background…',
icon: null,
uid: null,
is_dir: false,
body_content: h,
draggable_body: false,
has_head: true,
selectable_body: false,
draggable_body: false,
allow_context_menu: false,
is_resizable: false,
is_droppable: false,
init_center: true,
allow_native_ctxmenu: true,
allow_user_select: true,
onAppend: function(this_window){
$(this_window).find(`.access-recipient`).focus();
},
window_class: 'window-give-access',
width: 350,
window_css: {
height: 'initial',
},
body_css: {
width: 'initial',
height: '100%',
'background-color': 'rgb(245 247 249)',
'backdrop-filter': 'blur(3px)',
}
})
if(window.desktop_bg_url !== undefined && window.desktop_bg_url !== null){
$(el_window).find('.desktop-bg-settings-wrapper').hide();
$(el_window).find('.desktop-bg-settings-picture').show();
$(el_window).find('.desktop-bg-type').val('picture');
}else if(window.desktop_bg_color !== undefined && window.desktop_bg_color !== null){
$(el_window).find('.desktop-bg-settings-wrapper').hide();
$(el_window).find('.desktop-bg-settings-color').show();
$(el_window).find('.desktop-bg-type').val('color');
}else{
$(el_window).find('.desktop-bg-settings-wrapper').hide();
$(el_window).find('.desktop-bg-settings-picture').show();
$(el_window).find('.desktop-bg-type').val('picture');
}
$(el_window).find('.desktop-bg-color-block:not(.desktop-bg-color-block-palette').on('click', async function(e){
window.set_desktop_background({color: $(this).attr('data-color')})
})
$(el_window).find('.desktop-bg-color-block-palette input').on('change', async function(e){
window.set_desktop_background({color: $(this).val()})
})
$(el_window).on('file_opened', function(e){
let selected_file = Array.isArray(e.detail) ? e.detail[0] : e.detail;
const fit = $(el_window).find('.desktop-bg-fit').val();
bg_url = selected_file.read_url;
bg_fit = fit;
bg_color = undefined;
window.set_desktop_background({url: bg_url, fit: bg_fit})
})
$(el_window).find('.desktop-bg-fit').on('change', function(e){
const fit = $(this).val();
bg_fit = fit;
window.set_desktop_background({fit: fit})
})
$(el_window).find('.desktop-bg-type').on('change', function(e){
const type = $(this).val();
if(type === 'picture'){
$(el_window).find('.desktop-bg-settings-wrapper').hide();
$(el_window).find('.desktop-bg-settings-picture').show();
}else if(type==='color'){
$(el_window).find('.desktop-bg-settings-wrapper').hide();
$(el_window).find('.desktop-bg-settings-color').show();
}
})
$(el_window).find('.apply').on('click', async function(e){
// /set-desktop-bg
try{
$.ajax({
url: api_origin + "/set-desktop-bg",
type: 'POST',
data: JSON.stringify({
url: window.desktop_bg_url,
color: window.desktop_bg_color,
fit: window.desktop_bg_fit,
}),
async: true,
contentType: "application/json",
headers: {
"Authorization": "Bearer "+auth_token
},
statusCode: {
401: function () {
logout();
},
},
})
$(el_window).close();
resolve(true);
}catch(err){
}
})
$(el_window).find('.browse').on('click', function(){
// open dialog
UIWindow({
path: '/' + window.user.username + '/Desktop',
// this is the uuid of the window to which this dialog will return
parent_uuid: $(el_window).attr('data-element_uuid'),
allowed_file_types: ['image/*'],
show_maximize_button: false,
show_minimize_button: false,
title: 'Open',
is_dir: true,
is_openFileDialog: true,
selectable_body: false,
});
})
$(el_window).find('.cancel').on('click', function(){
$('body').attr('style', original_background_css);
$(el_window).close();
resolve(true);
})
})
}
export default UIWindowDesktopBGSettings

View File

@ -0,0 +1,53 @@
import UIWindow from './UIWindow.js'
async function UIWindowDownloadDirProg(options){
options = options ?? {};
let h = '';
// Loading spinner
h +=`<svg style="height: 40px; width: 40px; padding: 10px; display: block; float: left;" xmlns="http://www.w3.org/2000/svg" height="24" width="24" viewBox="0 0 24 24"><title>circle anim</title><g fill="#212121" class="nc-icon-wrapper"><g class="nc-loop-circle-24-icon-f"><path d="M12 24a12 12 0 1 1 12-12 12.013 12.013 0 0 1-12 12zm0-22a10 10 0 1 0 10 10A10.011 10.011 0 0 0 12 2z" fill="#212121" opacity=".4"></path><path d="M24 12h-2A10.011 10.011 0 0 0 12 2V0a12.013 12.013 0 0 1 12 12z" data-color="color-2"></path></g><style>.nc-loop-circle-24-icon-f{--animation-duration:0.5s;transform-origin:12px 12px;animation:nc-loop-circle-anim var(--animation-duration) infinite linear}@keyframes nc-loop-circle-anim{0%{transform:rotate(0)}100%{transform:rotate(360deg)}}</style></g></svg>`;
h += `<p style="text-align:left; padding-left:20px; padding-right:20px; overflow:hidden; width: 310px; text-overflow: ellipsis; white-space: nowrap; float:left; font-size:14px;" class="dir-dl-status">${options.defaultText ?? 'Preparing...'}</p>`;
const el_window = await UIWindow({
title: 'Instant Login!',
app: 'instant-login',
single_instance: true,
icon: null,
uid: null,
is_dir: false,
body_content: h,
draggable_body: false,
has_head: false,
selectable_body: false,
draggable_body: false,
allow_context_menu: false,
is_resizable: false,
is_droppable: false,
init_center: true,
allow_native_ctxmenu: false,
allow_user_select: false,
backdrop: false,
width: 460,
height: 'auto',
dominant: true,
show_in_taskbar: false,
draggable_body: true,
onAppend: function(this_window){
},
window_class: 'window-qr',
body_css: {
width: 'initial',
height: '100px',
'background-color': 'rgb(245 247 249)',
'backdrop-filter': 'blur(3px)',
'display': 'flex',
"flex-direction": 'row',
'justify-content': 'center',
'align-items': 'center',
}
})
return el_window;
}
export default UIWindowDownloadDirProg

View File

@ -0,0 +1,63 @@
import UIWindow from './UIWindow.js'
// todo do this using uid rather than item_path, since item_path is way mroe expensive on the DB
async function UIWindowDownloadProgress(options){
let h = '';
h += `<div data-download-operation-id="${options.operation_id}">`;
h += `<div>`;
// Spinner
h +=`<svg style="float:left; margin-right: 7px;" xmlns="http://www.w3.org/2000/svg" height="24" width="24" viewBox="0 0 24 24"><title>circle anim</title><g fill="#212121" class="nc-icon-wrapper"><g class="nc-loop-circle-24-icon-f"><path d="M12 24a12 12 0 1 1 12-12 12.013 12.013 0 0 1-12 12zm0-22a10 10 0 1 0 10 10A10.011 10.011 0 0 0 12 2z" fill="#212121" opacity=".4"></path><path d="M24 12h-2A10.011 10.011 0 0 0 12 2V0a12.013 12.013 0 0 1 12 12z" data-color="color-2"></path></g><style>.nc-loop-circle-24-icon-f{--animation-duration:0.5s;transform-origin:12px 12px;animation:nc-loop-circle-anim var(--animation-duration) infinite linear}@keyframes nc-loop-circle-anim{0%{transform:rotate(0)}100%{transform:rotate(360deg)}}</style></g></svg>`;
// Progress report
h +=`<div style="margin-bottom:20px; float:left; padding-top:3px; font-size:15px; overflow: hidden; width: calc(100% - 40px); text-overflow: ellipsis; white-space: nowrap;">`;
// msg
h += `<span class="upload-progress-msg">Downloading <strong>${options.item_name ?? ''}</strong></span>`;
h += `</div>`;
// Progress
h += `<div class="download-progress-bar-container" style="clear:both; margin-top:20px; border-radius:3px;">`;
h += `<div class="download-progress-bar"></div>`;
h += `</div>`;
// Cancel
h += `<button style="float:right; margin-top: 15px; margin-right: -2px;" class="button button-small download-cancel-btn">Cancel</button>`;
h +=`</div>`;
h += `</div>`;
const el_window = await UIWindow({
title: `Upload`,
icon: window.icons[`app-icon-uploader.svg`],
uid: null,
is_dir: false,
body_content: h,
draggable_body: false,
has_head: false,
selectable_body: false,
draggable_body: true,
allow_context_menu: false,
is_resizable: false,
is_droppable: false,
init_center: true,
allow_native_ctxmenu: false,
allow_user_select: false,
window_class: 'window-upload-progress',
width: 450,
dominant: true,
window_css:{
height: 'initial',
},
body_css: {
padding: '22px',
width: 'initial',
'background-color': 'rgba(231, 238, 245, .95)',
'backdrop-filter': 'blur(3px)',
}
});
// cancel download button clicked
$(el_window).find('.download-cancel-btn').on('click', function(){
operation_cancelled[options.operation_id] = true;
$(el_window).close();
})
return el_window;
}
export default UIWindowDownloadProgress

View File

@ -0,0 +1,258 @@
import UIWindow from './UIWindow.js'
import UIAlert from './UIAlert.js'
function UIWindowEmailConfirmationRequired(options){
return new Promise(async (resolve) => {
options = options ?? {};
let final_code = '';
let is_checking_code = false;
const submit_btn_txt = 'Confirm Email'
let h = '';
h += `<div class="qr-code-window-close-btn generic-close-window-button"> &times; </div>`;
h += `<div style="-webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; color: #3e5362;">`;
h += `<img src="${html_encode(window.icons['mail.svg'])}" style="display:block; margin:10px auto 10px;">`;
h += `<h3 style="text-align:center; font-weight: 500; font-size: 20px;">Confirm Your Email Address</h3>`;
h += `<form>`;
h += `<p style="text-align:center; padding: 0 20px;">To continue, please enter the 6-digit confirmation code sent to <strong style="font-weight: 500;">${window.user.email}</strong></p>`;
h += `<div class="error"></div>`;
h += ` <fieldset name="number-code" style="border: none; padding:0;" data-number-code-form>
<input class="digit-input" type="number" min='0' max='9' name='number-code-0' data-number-code-input='0' required />
<input class="digit-input" type="number" min='0' max='9' name='number-code-1' data-number-code-input='1' required />
<input class="digit-input" type="number" min='0' max='9' name='number-code-2' data-number-code-input='2' required />
<span class="email-confirm-code-hyphen">-</span>
<input class="digit-input" type="number" min='0' max='9' name='number-code-3' data-number-code-input='3' required />
<input class="digit-input" type="number" min='0' max='9' name='number-code-4' data-number-code-input='4' required />
<input class="digit-input" type="number" min='0' max='9' name='number-code-5' data-number-code-input='5' required />
</fieldset>`;
h += `<button type="submit" class="button button-block button-primary email-confirm-btn" style="margin-top:10px;" disabled>${submit_btn_txt}</button>`;
h += `</form>`;
h += `<div style="text-align:center; padding:10px; font-size:14px; margin-top:10px;">`;
h += `<span class="send-conf-email">Re-send Confirmation Code</span>`;
if(options.logout_in_footer){
h += ` &bull; `;
h += `<span class="conf-email-log-out">Log Out</span>`;
}
h += `</div>`;
h += `</div>`;
const el_window = await UIWindow({
title: null,
backdrop: options.backdrop ?? false,
icon: null,
uid: null,
is_dir: false,
body_content: h,
draggable_body: false,
has_head: false,
selectable_body: false,
draggable_body: true,
allow_context_menu: false,
is_draggable: options.is_draggable ?? true,
is_droppable: false,
is_resizable: false,
stay_on_top: options.stay_on_top ?? false,
allow_native_ctxmenu: true,
allow_user_select: true,
backdrop: true,
width: 390,
dominant: true,
onAppend: function(el_window){
$(el_window).find('.digit-input').first().focus();
},
window_class: 'window-item-properties',
window_css:{
height: 'initial',
},
body_css: {
padding: '30px',
width: 'initial',
height: 'initial',
'background-color': 'rgb(247 251 255)',
'backdrop-filter': 'blur(3px)',
}
})
$(el_window).find('.digit-input').first().focus();
$(el_window).find('.email-confirm-btn').on('click submit', function(e){
e.preventDefault();
e.stopPropagation();
$(el_window).find('.email-confirm-btn').prop('disabled', true);
$(el_window).find('.error').hide();
// Check if already checking code to prevent multiple requests
if(is_checking_code)
return;
// Confirm button
is_checking_code = true;
// set animation
$(el_window).find('.email-confirm-btn').html(`<svg style="width:20px; margin-top: 5px;" xmlns="http://www.w3.org/2000/svg" height="24" width="24" viewBox="0 0 24 24"><title>circle anim</title><g fill="#fff" class="nc-icon-wrapper"><g class="nc-loop-circle-24-icon-f"><path d="M12 24a12 12 0 1 1 12-12 12.013 12.013 0 0 1-12 12zm0-22a10 10 0 1 0 10 10A10.011 10.011 0 0 0 12 2z" fill="#eee" opacity=".4"></path><path d="M24 12h-2A10.011 10.011 0 0 0 12 2V0a12.013 12.013 0 0 1 12 12z" data-color="color-2"></path></g><style>.nc-loop-circle-24-icon-f{--animation-duration:0.5s;transform-origin:12px 12px;animation:nc-loop-circle-anim var(--animation-duration) infinite linear}@keyframes nc-loop-circle-anim{0%{transform:rotate(0)}100%{transform:rotate(360deg)}}</style></g></svg>`);
setTimeout(() => {
$.ajax({
url: api_origin + "/confirm-email",
type: 'POST',
data: JSON.stringify({
code: final_code,
}),
async: true,
contentType: "application/json",
headers: {
"Authorization": "Bearer "+auth_token
},
statusCode: {
401: function () {
logout();
},
},
success: function (res){
if(res.email_confirmed){
$(el_window).close();
refresh_user_data(window.auth_token)
resolve(true);
}else{
$(el_window).find('.error').html('Invalid confirmation code.');
$(el_window).find('.error').fadeIn();
$(el_window).find('.digit-input').val('');
$(el_window).find('.digit-input').first().focus();
$(el_window).find('.email-confirm-btn').prop('disabled', false);
$(el_window).find('.email-confirm-btn').html(submit_btn_txt);
}
},
error: function(res){
$(el_window).find('.error').html(res.responseJSON.error);
$(el_window).find('.error').fadeIn();
$(el_window).find('.digit-input').val('');
$(el_window).find('.digit-input').first().focus();
$(el_window).find('.email-confirm-btn').prop('disabled', false);
$(el_window).find('.email-confirm-btn').html(submit_btn_txt);
},
complete: function(){
is_checking_code = false;
}
})
}, 1000);
})
// send email confirmation
$(el_window).find('.send-conf-email').on('click', function(e){
$.ajax({
url: api_origin + "/send-confirm-email",
type: 'POST',
async: true,
contentType: "application/json",
headers: {
"Authorization": "Bearer "+auth_token
},
statusCode: {
401: function () {
logout();
},
},
success: async function (res){
await UIAlert({
message: `A new confirmation code has been sent to <strong>${window.user.email}</strong>.`,
body_icon: window.icons['c-check.svg'],
stay_on_top: true,
backdrop: true,
})
$(el_window).find('.digit-input').first().focus();
},
complete: function(){
}
})
})
// logout
$(el_window).find('.conf-email-log-out').on('click', function(e){
logout();
$(el_window).close();
})
// Elements
const numberCodeForm = document.querySelector('[data-number-code-form]');
const numberCodeInputs = [...numberCodeForm.querySelectorAll('[data-number-code-input]')];
// Event listeners
numberCodeForm.addEventListener('input', ({ target }) => {
if(!target.value.length) { return target.value = null; }
const inputLength = target.value.length;
let currentIndex = Number(target.dataset.numberCodeInput);
if(inputLength === 2){
const inputValues = target.value.split('');
target.value = inputValues[0];
}
else if (inputLength > 1) {
const inputValues = target.value.split('');
inputValues.forEach((value, valueIndex) => {
const nextValueIndex = currentIndex + valueIndex;
if (nextValueIndex >= numberCodeInputs.length) { return; }
numberCodeInputs[nextValueIndex].value = value;
});
currentIndex += inputValues.length - 2;
}
const nextIndex = currentIndex + 1;
if (nextIndex < numberCodeInputs.length) {
numberCodeInputs[nextIndex].focus();
}
// Concatenate all inputs into one string to create the final code
final_code = '';
for(let i=0; i< numberCodeInputs.length; i++){
final_code += numberCodeInputs[i].value;
}
// Automatically submit if 6 digits entered
if(final_code.length === 6){
$(el_window).find('.email-confirm-btn').prop('disabled', false);
$(el_window).find('.email-confirm-btn').trigger('click');
}
});
numberCodeForm.addEventListener('keydown', (e) => {
const { code, target } = e;
const currentIndex = Number(target.dataset.numberCodeInput);
const previousIndex = currentIndex - 1;
const nextIndex = currentIndex + 1;
const hasPreviousIndex = previousIndex >= 0;
const hasNextIndex = nextIndex <= numberCodeInputs.length - 1
switch (code) {
case 'ArrowLeft':
case 'ArrowUp':
if (hasPreviousIndex) {
numberCodeInputs[previousIndex].focus();
}
e.preventDefault();
break;
case 'ArrowRight':
case 'ArrowDown':
if (hasNextIndex) {
numberCodeInputs[nextIndex].focus();
}
e.preventDefault();
break;
case 'Backspace':
if (!e.target.value.length && hasPreviousIndex) {
numberCodeInputs[previousIndex].value = null;
numberCodeInputs[previousIndex].focus();
}
break;
default:
break;
}
});
})
}
export default UIWindowEmailConfirmationRequired

View File

@ -0,0 +1,80 @@
import UIWindow from './UIWindow.js'
async function UIWindowQR(options){
return new Promise(async (resolve) => {
options = options ?? {};
let h = '';
h += `<div style="padding: 20px; margin-top: 0;">`;
// success
h += `<div class="feedback-sent-success">`;
h += `<img src="${html_encode(window.icons['c-check.svg'])}" style="width:50px; height:50px; display: block; margin:10px auto;">`;
h += `<p style="text-align:center; margin-bottom:10px; color: #005300; padding: 10px;">Thank you for contacting us. If you have an email associated with your account, you will hear back from us as soon as possible.</p>`;
h+= `</div>`;
// form
h += `<div class="feedback-form">`;
h += `<p style="margin-top:0; font-size: 15px; -webkit-font-smoothing: antialiased;">Please use the form below to send us your feedback, comments, and bug reports.</p>`;
h += `<textarea class="feedback-message" style="width:100%; height: 200px; padding: 10px; box-sizing: border-box;"></textarea>`;
h += `<button class="button button-primary send-feedback-btn" style="float: right; margin-bottom: 15px; margin-top: 10px;">Send</button>`;
h += `</div>`;
h += `</div>`;
const el_window = await UIWindow({
title: 'Contact Us',
app: 'feedback',
single_instance: true,
icon: null,
uid: null,
is_dir: false,
body_content: h,
draggable_body: false,
has_head: true,
selectable_body: false,
draggable_body: false,
allow_context_menu: false,
is_resizable: false,
is_droppable: false,
init_center: true,
allow_native_ctxmenu: false,
allow_user_select: false,
width: 350,
height: 'auto',
dominant: true,
show_in_taskbar: false,
onAppend: function(this_window){
$(this_window).find('.feedback-message').get(0).focus({preventScroll:true});
},
window_class: 'window-feedback',
body_css: {
width: 'initial',
height: '100%',
'background-color': 'rgb(245 247 249)',
'backdrop-filter': 'blur(3px)',
}
})
$(el_window).find('.send-feedback-btn').on('click', function(e){
const message = $(el_window).find('.feedback-message').val();
if(message)
$(this).prop('disabled', true);
$.ajax({
url: api_origin + "/contactUs",
type: 'POST',
async: true,
contentType: "application/json",
headers: {
"Authorization": "Bearer "+auth_token
},
data: JSON.stringify({
message: message,
}),
success: async function (data){
$(el_window).find('.feedback-form').hide();
$(el_window).find('.feedback-sent-success').show(100);
}
})
})
})
}
export default UIWindowQR

View File

@ -0,0 +1,103 @@
import UIWindow from './UIWindow.js'
let fontAvailable = new Set();
const font_list = new Set([
// Windows 10
'Arial', 'Arial Black', 'Bahnschrift', 'Calibri', 'Cambria', 'Cambria Math', 'Candara', 'Comic Sans MS', 'Consolas', 'Constantia', 'Corbel', 'Courier New', 'Ebrima', 'Franklin Gothic Medium', 'Gabriola', 'Gadugi', 'Georgia', 'HoloLens MDL2 Assets', 'Impact', 'Ink Free', 'Javanese Text', 'Leelawadee UI', 'Lucida Console', 'Lucida Sans Unicode', 'Malgun Gothic', 'Marlett', 'Microsoft Himalaya', 'Microsoft JhengHei', 'Microsoft New Tai Lue', 'Microsoft PhagsPa', 'Microsoft Sans Serif', 'Microsoft Tai Le', 'Microsoft YaHei', 'Microsoft Yi Baiti', 'MingLiU-ExtB', 'Mongolian Baiti', 'MS Gothic', 'MV Boli', 'Myanmar Text', 'Nirmala UI', 'Palatino Linotype', 'Segoe MDL2 Assets', 'Segoe Print', 'Segoe Script', 'Segoe UI', 'Segoe UI Historic', 'Segoe UI Emoji', 'Segoe UI Symbol', 'SimSun', 'Sitka', 'Sylfaen', 'Symbol', 'Tahoma', 'Times New Roman', 'Trebuchet MS', 'Verdana', 'Webdings', 'Wingdings', 'Yu Gothic',
// macOS
'American Typewriter', 'Andale Mono', 'Arial', 'Arial Black', 'Arial Narrow', 'Arial Rounded MT Bold', 'Arial Unicode MS', 'Avenir', 'Avenir Next', 'Avenir Next Condensed', 'Baskerville', 'Big Caslon', 'Bodoni 72', 'Bodoni 72 Oldstyle', 'Bodoni 72 Smallcaps', 'Bradley Hand', 'Brush Script MT', 'Chalkboard', 'Chalkboard SE', 'Chalkduster', 'Charter', 'Cochin', 'Comic Sans MS', 'Copperplate', 'Courier', 'Courier New', 'Didot', 'DIN Alternate', 'DIN Condensed', 'Futura', 'Geneva', 'Georgia', 'Gill Sans', 'Helvetica', 'Helvetica Neue', 'Herculanum', 'Hoefler Text', 'Impact', 'Lucida Grande', 'Luminari', 'Marker Felt', 'Menlo', 'Microsoft Sans Serif', 'Monaco', 'Noteworthy', 'Optima', 'Palatino', 'Papyrus', 'Phosphate', 'Rockwell', 'Savoye LET', 'SignPainter', 'Skia', 'Snell Roundhand', 'Tahoma', 'Times', 'Times New Roman', 'Trattatello', 'Trebuchet MS', 'Verdana', 'Zapfino',
].sort());
// filter through available system fonts
(async () => {
await document.fonts.ready;
for (const font of font_list.values()) {
if (document.fonts.check(`12px "${font}"`)) {
fontAvailable.add(font);
}
}
})();
async function UIWindowFontPicker(options){
// set sensible defaults
if(arguments.length > 0){
// if first argument is a string, then assume it is the default color
if(isString(arguments[0])){
options = {};
options.default = arguments[0];
}
}
options = options || {};
return new Promise(async (resolve) => {
let h = ``;
h += `<div>`;
h += `<div style="padding: 20px; border-bottom: 1px solid #ced7e1; width: 100%; box-sizing: border-box;">`;
h += `<div class="font-list" style="margin-bottom: 10px; height: 200px; overflow-y: scroll; background-color: white; padding: 0 10px;">`;
fontAvailable.forEach(element => {
h += `<p class="font-selector disable-user-select ${options.default === element ? 'font-selector-active' : ''}" style="font-family: '${html_encode(element)}';" data-font-family="${html_encode(element)}">${element}</p>`; // 👉️ one, two, three, four
});
h += `</div>`;
// Select
h += `<button class="select-btn button button-primary button-block button-normal">Select</button>`
h += `</form>`;
h += `</div>`;
h += `</div>`;
const el_window = await UIWindow({
title: 'Select font…',
app: 'font-picker',
single_instance: true,
icon: null,
uid: null,
is_dir: false,
body_content: h,
draggable_body: false,
has_head: true,
selectable_body: false,
draggable_body: false,
allow_context_menu: false,
is_draggable: true,
is_droppable: false,
is_resizable: false,
stay_on_top: false,
allow_native_ctxmenu: true,
allow_user_select: true,
...options.window_options,
width: 350,
dominant: true,
on_close: ()=>{
resolve(false)
},
onAppend: function(window){
let active_font = $(window).find('.font-selector-active');
if(active_font.length > 0){
scrollParentToChild($(window).find('.font-list').get(0), active_font.get(0));
}
},
window_class: 'window-login',
window_css:{
height: 'initial',
},
body_css: {
width: 'initial',
padding: '0',
'background-color': 'rgba(231, 238, 245, .95)',
'backdrop-filter': 'blur(3px)',
}
})
$(el_window).find('.select-btn').on('click', function(e){
resolve({fontFamily: $(el_window).find('.font-selector-active').attr('data-font-family')});
$(el_window).close();
})
$(el_window).find('.font-selector').on('click', function(e){
$(el_window).find('.font-selector').removeClass('font-selector-active');
$(this).addClass('font-selector-active');
})
})
}
export default UIWindowFontPicker

View File

@ -0,0 +1,100 @@
import UIWindow from './UIWindow.js'
import UIPopover from './UIPopover.js'
async function UIWindowGetCopyLink(options){
let h = '';
let copy_btn_text = 'Copy Link';
let copied_btn_text = 'Copied!';
const signature = await puter.fs.sign(null, {uid: options.uid, action: 'read'})
const url = `${gui_origin}/?name=${encodeURIComponent(options.name)}&is_dir=${encodeURIComponent(options.is_dir)}&download=${encodeURIComponent(signature.items.read_url)}`;
h += `<div>`;
h += `<p style="font-size: 15px; font-weight: 400; -webkit-font-smoothing: antialiased; color: #474a57;">Share the following link with anyone and they will be able to receive a copy of <strong>${html_encode(options.name)}</strong></p>`;
h += `<input type="text" style="margin-bottom:10px;" class="downloadable-link" readonly />`;
h += `<button class="button button-primary copy-downloadable-link" style="width:130px;">${copy_btn_text}</button>`
h += `<img class="share-copy-link-on-social" src="${window.icons['share-outline.svg']}">`;
h += `</div>`;
const el_window = await UIWindow({
title: `Get Copy Link`,
icon: null,
uid: null,
is_dir: false,
body_content: h,
draggable_body: false,
has_head: true,
selectable_body: false,
draggable_body: false,
allow_context_menu: false,
is_resizable: false,
is_droppable: false,
init_center: true,
allow_native_ctxmenu: true,
allow_user_select: true,
onAppend: function(el_window){
},
width: 500,
dominant: true,
window_css: {
height: 'initial',
},
body_css: {
padding: '10px',
width: 'initial',
'max-height': 'calc(100vh - 200px)',
'background-color': 'rgb(241 246 251)',
'backdrop-filter': 'blur(3px)',
'padding': '10px 20px 20px 20px',
'height': 'initial',
}
});
$(el_window).find('.window-body .downloadable-link').val(url);
$(el_window).find('.window-body .share-copy-link-on-social').on('click', function(e){
const social_links = socialLink({url: url, title: `Get a copy of '${options.name}' on Puter.com!`, description: `Get a copy of '${options.name}' on Puter.com!`});
let social_links_html = ``;
social_links_html += `<div style="padding: 10px;">`;
social_links_html += `<p style="margin: 0; text-align: center; margin-bottom: 6px; color: #484a57; font-weight: bold; font-size: 14px;">Share to</p>`
social_links_html += `<a class="copy-link-social-btn" target="_blank" href="${social_links.twitter}" style=""><svg viewBox="0 0 24 24" aria-hidden="true" style="opacity: 0.7;"><g><path d="M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231zm-1.161 17.52h1.833L7.084 4.126H5.117z"></path></g></svg></a>`
social_links_html += `<a class="copy-link-social-btn" target="_blank" href="${social_links.whatsapp}" style=""><img src="${window.icons['logo-whatsapp.svg']}"></a>`
social_links_html += `<a class="copy-link-social-btn" target="_blank" href="${social_links.facebook}" style=""><img src="${window.icons['logo-facebook.svg']}"></a>`
social_links_html += `<a class="copy-link-social-btn" target="_blank" href="${social_links.linkedin}" style=""><img src="${window.icons['logo-linkedin.svg']}"></a>`
social_links_html += `<a class="copy-link-social-btn" target="_blank" href="${social_links.reddit}" style=""><img src="${window.icons['logo-reddit.svg']}"></a>`
social_links_html += `<a class="copy-link-social-btn" target="_blank" href="${social_links['telegram.me']}" style=""><img src="${window.icons['logo-telegram.svg']}"></a>`
social_links_html += '</div>';
UIPopover({
content: social_links_html,
snapToElement: this,
parent_element: this,
// width: 300,
height: 100,
position: 'bottom',
});
})
$(el_window).find('.window-body .copy-downloadable-link').on('click', async function(e){
var copy_btn = this;
if (navigator.clipboard) {
// Get link text
const selected_text = $(el_window).find('.window-body .downloadable-link').val();
// copy selected text to clipboard
await navigator.clipboard.writeText(selected_text);
}
else{
// Get the text field
$(el_window).find('.window-body .downloadable-link').select();
// Copy the text inside the text field
document.execCommand('copy');
}
$(this).html(copied_btn_text);
setTimeout(function(){
$(copy_btn).html(copy_btn_text);
}, 1000);
});
}
export default UIWindowGetCopyLink

View File

@ -0,0 +1,226 @@
import UIWindow from './UIWindow.js'
// todo do this using uid rather than item_path, since item_path is way mroe expensive on the DB
async function UIWindowItemProperties(item_name, item_path, item_uid, left, top, width, height){
let h = '';
h += `<div class="item-props-tabview" style="display: flex; flex-direction: column; height: 100%;">`;
// tabs
h += `<div class="item-props-tab">`;
h += `<div class="item-props-tab-btn antialiased disable-user-select item-props-tab-selected" data-tab="general">General</div>`;
h += `<div class="item-props-tab-btn antialiased disable-user-select item-props-tab-btn-versions" data-tab="versions">Versions</div>`;
h += `</div>`;
h+= `<div class="item-props-tab-content item-props-tab-content-selected" data-tab="general" style="border-top-left-radius:0;">`;
h += `<table class="item-props-tbl">`;
h += `<tr><td class="item-prop-label">Name</td><td class="item-prop-val item-prop-val-name"></td></tr>`;
h += `<tr><td class="item-prop-label">Path</td><td class="item-prop-val item-prop-val-path"></td></tr>`;
h += `<tr class="item-prop-original-name"><td class="item-prop-label">Original Name</td><td class="item-prop-val item-prop-val-original-name"></td></tr>`;
h += `<tr class="item-prop-original-path"><td class="item-prop-label">Original Path</td><td class="item-prop-val item-prop-val-original-path"></td></tr>`;
h += `<tr><td class="item-prop-label">Shortcut to</td><td class="item-prop-val item-prop-val-shortcut-to"></td></tr>`;
h += `<tr><td class="item-prop-label">UID</td><td class="item-prop-val item-prop-val-uid"></td></tr>`;
h += `<tr><td class="item-prop-label">Type</td><td class="item-prop-val item-prop-val-type"></td></tr>`;
h += `<tr><td class="item-prop-label">Size</td><td class="item-prop-val item-prop-val-size"></td></tr>`;
h += `<tr><td class="item-prop-label">Modified</td><td class="item-prop-val item-prop-val-modified"></td></tr>`;
h += `<tr><td class="item-prop-label">Created</td><td class="item-prop-val item-prop-val-created"></td></tr>`;
h += `<tr><td class="item-prop-label">Versions</td><td class="item-prop-val item-prop-val-versions"></td></tr>`;
h += `<tr><td class="item-prop-label">Associated Websites</td><td class="item-prop-val item-prop-val-websites">`;
h += `</td></tr>`;
h += `<tr><td class="item-prop-label">Access Granted To</td><td class="item-prop-val item-prop-val-permissions"></td></tr>`;
h += `</table>`;
h += `</div>`;
h += `<div class="item-props-tab-content" data-tab="versions" style="padding: 20px;">`
h += `<div class="item-props-version-list">`;
h += `</div>`;
h += `</div>`;
h += `</div>`;
const el_window = await UIWindow({
title: `${item_name} properties`,
app: item_uid+'-account',
single_instance: true,
icon: null,
uid: null,
is_dir: false,
body_content: h,
draggable_body: false,
has_head: true,
selectable_body: false,
draggable_body: false,
allow_context_menu: false,
is_resizable: false,
is_droppable: false,
init_center: true,
allow_native_ctxmenu: true,
allow_user_select: true,
left: left,
top: top,
width: width,
height: height,
onAppend: function(el_window){
},
width: 450,
window_class: 'window-item-properties',
window_css:{
// height: 'initial',
},
body_css: {
padding: '10px',
width: 'initial',
height: 'calc(100% - 50px)',
'background-color': 'rgb(241 242 246)',
'backdrop-filter': 'blur(3px)',
'content-box': 'content-box',
}
})
// item props tab click handler
$(el_window).find('.item-props-tab-btn').click(function(e){
// unselect all tabs
$(el_window).find('.item-props-tab-btn').removeClass('item-props-tab-selected');
// select this tab
$(this).addClass('item-props-tab-selected');
// unselect all tab contents
$(el_window).find('.item-props-tab-content').removeClass('item-props-tab-content-selected');
// select this tab content
$(el_window).find(`.item-props-tab-content[data-tab="${$(this).attr('data-tab')}"]`).addClass('item-props-tab-content-selected');
})
// /stat
puter.fs.stat({
uid: item_uid,
returnSubdomains: true,
returnPermissions: true,
returnVersions: true,
returnSize: true,
success: function (fsentry){
// hide versions tab if item is a directory
if(fsentry.is_dir){
$(el_window).find('[data-tab="versions"]').hide();
}
// name
$(el_window).find('.item-prop-val-name').html(fsentry.name);
// path
$(el_window).find('.item-prop-val-path').html(item_path);
// original name & path
if(fsentry.metadata){
try{
let metadata = JSON.parse(fsentry.metadata);
if(metadata.original_name){
$(el_window).find('.item-prop-val-original-name').html(metadata.original_name);
$(el_window).find('.item-prop-original-name').show();
}
if(metadata.original_path){
$(el_window).find('.item-prop-val-original-path').html(metadata.original_path);
$(el_window).find('.item-prop-original-path').show();
}
}catch(e){}
}
// shortcut to
if(fsentry.shortcut_to && fsentry.shortcut_to_path){
$(el_window).find('.item-prop-val-shortcut-to').html(fsentry.shortcut_to_path);
}
// uid
$(el_window).find('.item-prop-val-uid').html(fsentry.id);
// type
$(el_window).find('.item-prop-val-type').html(fsentry.is_dir ? 'Directory' : (fsentry.type === null ? '-' : fsentry.type));
// size
$(el_window).find('.item-prop-val-size').html(fsentry.size === null || fsentry.size === undefined ? '-' : byte_format(fsentry.size));
// modified
$(el_window).find('.item-prop-val-modified').html(fsentry.modified === 0 ? '-' : timeago.format(fsentry.modified*1000));
// created
$(el_window).find('.item-prop-val-created').html(fsentry.created === 0 ? '-' : timeago.format(fsentry.created*1000));
// subdomains
if(fsentry.subdomains && fsentry.subdomains.length > 0 ){
fsentry.subdomains.forEach(subdomain => {
$(el_window).find('.item-prop-val-websites').append(`<p class="item-prop-website-entry" data-uuid="${subdomain.uuid}" style="margin-bottom:5px; margin-top:5px;"><a target="_blank" href="${subdomain.address}">${subdomain.address}</a> (<span class="disassociate-website-link" data-uuid="${subdomain.uuid}" data-subdomain="${extractSubdomain(subdomain.address)}">disassociate</span>)</p>`);
});
}
else{
$(el_window).find('.item-prop-val-websites').append('-');
}
// versions
if(fsentry.versions && fsentry.versions.length > 0 ){
fsentry.versions.reverse().forEach(version => {
$(el_window).find('.item-props-version-list')
.append(`<div class="item-prop-version-entry">${version.user? version.user.username : ''} &bull; ${timeago.format(version.timestamp*1000)}<p style="font-size:10px;">${version.id}</p></div>`);
});
}
else{
$(el_window).find('.item-props-version-list').append('-');
}
// owner
$(el_window).find('.item-prop-val-permissions').append(`<p class="item-prop-perm-entry" style="margin-bottom:5px; margin-top:5px;">${(fsentry.owner.email === undefined || fsentry.owner.email === null) ? fsentry.owner.username : fsentry.owner.email} (owner)</p>`);
// other users with access
if(fsentry.permissions && fsentry.permissions.length > 0 ){
fsentry.permissions.forEach(perm => {
let h = ``;
// username/email
h += `<p class="item-prop-perm-entry" data-perm-uid="${perm.uid}" style="margin-bottom:5px; margin-top:5px;">${perm.email ?? perm.username} `;
// remove
h += `(<span class="remove-permission-link" data-perm-uid="${perm.uid}">remove</span>)`;
$(el_window).find('.item-prop-val-permissions').append(h);
});
}
else{
$(el_window).find('.item-prop-val-permissions').append('-');
}
$(el_window).find(`.disassociate-website-link`).on('click', function(e){
puter.hosting.update(
$(e.target).attr('data-subdomain'),
null).then(()=>{
$(el_window).find(`.item-prop-website-entry[data-uuid="${$(e.target).attr('data-uuid')}"]`).remove();
if($(el_window).find(`.item-prop-website-entry`).length === 0){
$(el_window).find(`.item-prop-val-websites`).html('-');
// remove the website badge from all instances of the dir
$(`.item[data-uid="${item_uid}"]`).find('.item-has-website-badge').fadeOut(200);
}
}
)
})
$(el_window).find('.remove-permission-link').on('click', function(e){
const el_remove_perm_link= this;
const perm_uid = $(el_remove_perm_link).attr('data-perm-uid');
$.ajax({
url: api_origin + "/remove-perm",
type: 'POST',
async: true,
contentType: "application/json",
data: JSON.stringify({
uid: perm_uid,
}),
headers: {
"Authorization": "Bearer "+auth_token
},
statusCode: {
401: function () {
logout();
},
},
success: async function (res){
$(el_window).find(`.item-prop-perm-entry[data-perm-uid="${perm_uid}"]`).remove();
if($(el_window).find(`.item-prop-perm-entry`).length === 0){
$(el_window).find(`.item-prop-val-permissions`).html('-');
// todo is it better to combine the following two queriesinto one css selector?
$(`.item[data-uid="${item_uid}"]`).find(`.item-is-shared`).fadeOut(200);
// todo optim do this only if item is a directory
// todo this has to be case-insensitive but the `i` selector doesn't work on ^=
$(`.item[data-path^="${item_path}/"]`).find(`.item-is-shared`).fadeOut(200);
}
},
complete: function(){
}
})
})
}
})
}
export default UIWindowItemProperties

171
src/UI/UIWindowLogin.js Normal file
View File

@ -0,0 +1,171 @@
import UIWindow from './UIWindow.js'
import UIWindowSignup from './UIWindowSignup.js'
import UIWindowRecoverPassword from './UIWindowRecoverPassword.js'
async function UIWindowLogin(options){
options = options ?? {};
options.reload_on_success = options.reload_on_success ?? false;
options.has_head = options.has_head ?? true;
options.send_confirmation_code = options.send_confirmation_code ?? false;
return new Promise(async (resolve) => {
const internal_id = window.uuidv4();
let h = ``;
h += `<div style="max-width: 500px; min-width: 340px;">`;
if(!options.has_head && options.show_close_button !== false)
h += `<div class="generic-close-window-button"> &times; </div>`;
h += `<div style="padding: 20px; border-bottom: 1px solid #ced7e1; width: 100%; box-sizing: border-box;">`;
// title
h += `<h1 class="login-form-title">Log In</h1>`;
// login form
h += `<form class="login-form">`;
// error msg
h += `<div class="login-error-msg"></div>`;
// username/email
h += `<div style="overflow: hidden;">`;
h += `<label for="email_or_username-${internal_id}">Email or Username</label>`;
h += `<input id="email_or_username-${internal_id}" class="email_or_username" type="text" name="email_or_username" spellcheck="false" autocorrect="off" autocapitalize="off" data-gramm_editor="false" autocomplete="username"/>`;
h += `</div>`;
// password
h += `<div style="overflow: hidden; margin-top: 20px; margin-bottom: 20px;">`;
h += `<label for="password-${internal_id}">Password</label>`;
h += `<input id="password-${internal_id}" class="password" type="password" name="password" autocomplete="current-password" />`;
h += `</div>`;
// login
h += `<button class="login-btn button button-primary button-block button-normal">Log in</button>`;
// password recovery
h += `<p style="text-align:center; margin-bottom: 0;"><span class="forgot-password-link">Forgot password?</span></p>`;
h += `</form>`;
h += `</div>`;
// create account link
if(options.show_signup_button === undefined || options.show_signup_button){
h += `<div class="c2a-wrapper" style="padding:20px;">`;
h += `<button class="signup-c2a-clickable">Create Free Account</button>`;
h += `</div>`;
}
h += `</div>`;
const el_window = await UIWindow({
title: null,
app: 'login',
single_instance: true,
icon: null,
uid: null,
is_dir: false,
body_content: h,
draggable_body: false,
has_head: true,
selectable_body: false,
draggable_body: false,
allow_context_menu: false,
is_draggable: options.is_draggable ?? true,
is_droppable: false,
is_resizable: false,
stay_on_top: false,
allow_native_ctxmenu: true,
allow_user_select: true,
...options.window_options,
width: 350,
dominant: true,
on_close: ()=>{
resolve(false)
},
onAppend: function(this_window){
$(this_window).find(`.email_or_username`).get(0).focus({preventScroll:true});
},
window_class: 'window-login',
window_css:{
height: 'initial',
},
body_css: {
width: 'initial',
padding: '0',
'background-color': 'rgb(255 255 255)',
'backdrop-filter': 'blur(3px)',
'display': 'flex',
'flex-direction': 'column',
'justify-content': 'center',
'align-items': 'center',
}
})
$(el_window).find('.forgot-password-link').on('click', function(e){
UIWindowRecoverPassword({
window_options: {
backdrop: true,
close_on_backdrop_click: false,
}
});
})
$(el_window).find('.login-btn').on('click', function(e){
const email_username = $(el_window).find('.email_or_username').val();
const password = $(el_window).find('.password').val();
let data;
if(is_email(email_username)){
data = JSON.stringify({
email: email_username,
password: password
})
}else{
data = JSON.stringify({
username: email_username,
password: password
})
}
$(el_window).find('.login-error-msg').hide();
let headers = {};
if(window.custom_headers)
headers = window.custom_headers;
$.ajax({
url: gui_origin + "/login",
type: 'POST',
async: false,
headers: headers,
contentType: "application/json",
data: data,
success: function (data){
update_auth_data(data.token, data.user);
if(options.reload_on_success){
window.onbeforeunload = null;
window.location.replace('/');
}else
resolve(true);
$(el_window).close();
},
error: function (err){
$(el_window).find('.login-error-msg').html(err.responseText);
$(el_window).find('.login-error-msg').fadeIn();
}
});
})
$(el_window).find('.login-form').on('submit', function(e){
e.preventDefault();
e.stopPropagation();
return false;
})
$(el_window).find('.signup-c2a-clickable').on('click', async function(e){
//destroy this window
$(el_window).close();
// create Signup window
const signup = await UIWindowSignup({
referrer: options.referrer,
show_close_button: options.show_close_button,
reload_on_success: options.reload_on_success,
window_options: options.window_options,
send_confirmation_code: options.send_confirmation_code,
});
if(signup)
resolve(true);
})
})
}
export default UIWindowLogin

View File

@ -0,0 +1,59 @@
import UIWindow from './UIWindow.js'
async function UIWindowLoginInProgress(options){
return new Promise(async (resolve) => {
options = options ?? {};
let h = '';
h += `<div class="login-progress">`;
h += `<h1 style="text-align: center;
font-size: 20px;
padding: 10px;
font-weight: 300; margin: -10px 10px 20px 10px;">Logging in as <strong>${options.user_info.email === null ? options.user_info.username : options.user_info.email}</strong></h1>`;
// spinner
h +=`<svg style="float:left; margin-right: 7px;" xmlns="http://www.w3.org/2000/svg" height="24" width="24" viewBox="0 0 24 24"><title>circle anim</title><g fill="#212121" class="nc-icon-wrapper"><g class="nc-loop-circle-24-icon-f"><path d="M12 24a12 12 0 1 1 12-12 12.013 12.013 0 0 1-12 12zm0-22a10 10 0 1 0 10 10A10.011 10.011 0 0 0 12 2z" fill="#212121" opacity=".4"></path><path d="M24 12h-2A10.011 10.011 0 0 0 12 2V0a12.013 12.013 0 0 1 12 12z" data-color="color-2"></path></g><style>.nc-loop-circle-24-icon-f{--animation-duration:0.5s;transform-origin:12px 12px;animation:nc-loop-circle-anim var(--animation-duration) infinite linear}@keyframes nc-loop-circle-anim{0%{transform:rotate(0)}100%{transform:rotate(360deg)}}</style></g></svg>`;
h += `</div>`;
const el_window = await UIWindow({
title: 'Instant Login!',
app: 'change-passowrd',
single_instance: true,
icon: null,
uid: null,
is_dir: false,
body_content: h,
draggable_body: false,
has_head: false,
selectable_body: false,
draggable_body: false,
allow_context_menu: false,
is_resizable: false,
is_droppable: false,
init_center: true,
allow_native_ctxmenu: false,
allow_user_select: false,
width: 350,
height: 'auto',
dominant: true,
show_in_taskbar: false,
backdrop: true,
stay_on_top: true,
onAppend: function(this_window){
},
window_class: 'window-login-progress',
body_css: {
width: 'initial',
height: '100%',
'background-color': 'rgb(245 247 249)',
'backdrop-filter': 'blur(3px)',
}
})
setTimeout(() => {
$(el_window).close();
}, 3000);
})
}
export default UIWindowLoginInProgress

View File

@ -0,0 +1,63 @@
import UIWindow from './UIWindow.js'
// todo do this using uid rather than item_path, since item_path is way mroe expensive on the DB
async function UIWindowMoveProgress(options){
let h = '';
h += `<div data-move-operation-id="${options.operation_id}">`;
h += `<div>`;
// spinner
h +=`<svg style="float:left; margin-right: 7px;" xmlns="http://www.w3.org/2000/svg" height="24" width="24" viewBox="0 0 24 24"><title>circle anim</title><g fill="#212121" class="nc-icon-wrapper"><g class="nc-loop-circle-24-icon-f"><path d="M12 24a12 12 0 1 1 12-12 12.013 12.013 0 0 1-12 12zm0-22a10 10 0 1 0 10 10A10.011 10.011 0 0 0 12 2z" fill="#212121" opacity=".4"></path><path d="M24 12h-2A10.011 10.011 0 0 0 12 2V0a12.013 12.013 0 0 1 12 12z" data-color="color-2"></path></g><style>.nc-loop-circle-24-icon-f{--animation-duration:0.5s;transform-origin:12px 12px;animation:nc-loop-circle-anim var(--animation-duration) infinite linear}@keyframes nc-loop-circle-anim{0%{transform:rotate(0)}100%{transform:rotate(360deg)}}</style></g></svg>`;
// Progress report
h +=`<div style="margin-bottom:20px; float:left; padding-top:3px; font-size:15px; overflow: hidden; width: calc(100% - 40px); text-overflow: ellipsis; white-space: nowrap;">`;
// msg
h += `<span class="move-progress-msg">Moving </span>`;
h += `<span class="move-from" style="font-weight:strong;"></span>`;
h += `</div>`;
// progress
h += `<div class="move-progress-bar-container" style="clear:both; margin-top:20px; border-radius:3px;">`;
h += `<div class="move-progress-bar"></div>`;
h += `</div>`;
// cancel
// h += `<button style="float:right; margin-top: 15px; margin-right: -2px;" class="button button-small move-cancel-btn">Cancel</button>`;
h +=`</div>`;
h += `</div>`;
const el_window = await UIWindow({
title: `moveing`,
icon: window.icons[`app-icon-moveing.svg`],
uid: null,
is_dir: false,
body_content: h,
draggable_body: false,
has_head: false,
selectable_body: false,
draggable_body: true,
allow_context_menu: false,
is_resizable: false,
is_droppable: false,
init_center: true,
allow_native_ctxmenu: false,
allow_user_select: false,
window_class: 'window-move-progress',
width: 450,
dominant: true,
window_css:{
height: 'initial',
},
body_css: {
padding: '22px',
width: 'initial',
'background-color': 'rgba(231, 238, 245, .95)',
'backdrop-filter': 'blur(3px)',
}
});
$(el_window).find('.move-cancel-btn').on('click', function(e){
operation_cancelled[options.operation_id] = true;
$(el_window).close();
})
return el_window;
}
export default UIWindowMoveProgress

View File

@ -0,0 +1,178 @@
import UIWindow from './UIWindow.js'
import UIContextMenu from './UIContextMenu.js'
import UIAlert from './UIAlert.js'
async function UIWindowMyWebsites(options){
let h = '';
h += `<div>`;
h += `</div>`;
const el_window = await UIWindow({
title: `My Websites`,
app: 'my-websites',
single_instance: true,
icon: null,
uid: null,
is_dir: false,
body_content: h,
draggable_body: false,
has_head: true,
selectable_body: false,
draggable_body: false,
allow_context_menu: false,
is_resizable: false,
is_droppable: false,
init_center: true,
allow_native_ctxmenu: true,
allow_user_select: true,
width: 400,
dominant: true,
onAppend: function(el_window){
},
window_css:{
},
body_css: {
padding: '10px',
width: 'initial',
'background-color': 'rgba(231, 238, 245)',
'backdrop-filter': 'blur(3px)',
'padding-bottom': 0,
'height': '351px',
'box-sizing': 'border-box',
}
});
// /sites
let init_ts = Date.now();
let loading = setTimeout(function(){
$(el_window).find('.window-body').html(`<p style="text-align: center;
margin-top: 40px;
margin-bottom: 50px;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
color: #596c7c;">Loading...</p>`);
}, 1000);
puter.hosting.list().then(function (sites){
setTimeout(function(){
// clear loading
clearTimeout(loading);
// user has sites
if(sites.length > 0){
let h ='';
for(let i=0; i< sites.length; i++){
h += `<div class="mywebsites-card" data-uuid="${sites[i].uid}">`;
h += `<a class="mywebsites-address-link" href="https://${sites[i].subdomain}.puter.site" target="_blank">${sites[i].subdomain}.puter.site</a>`;
h += `<img class="mywebsites-site-setting" data-site-uuid="${sites[i].uid}" src="${html_encode(window.icons['cog.svg'])}">`;
// there is a directory associated with this site
if(sites[i].root_dir){
h += `<p class="mywebsites-dir-path" data-path="${html_encode(sites[i].root_dir.path)}" data-name="${sites[i].root_dir.name}" data-uuid="${sites[i].root_dir.id}">`;
h+= `<img src="${html_encode(window.icons['folder.svg'])}">`;
h+= `${sites[i].root_dir.path}`;
h += `</p>`;
h += `<p style="margin-bottom:0; margin-top: 20px; font-size: 13px;">`;
h += `<span class="mywebsites-dis-dir" data-dir-uuid="${sites[i].root_dir.id}" data-site-uuid="${sites[i].uid}">`;
h += `<img style="width: 16px; margin-bottom: -2px; margin-right: 4px;" src="${html_encode(window.icons['plug.svg'])}">Disassociate Folder</span>`;
h += `</p>`;
}
h += `<p class="mywebsites-no-dir-notice" data-site-uuid="${sites[i].uid}" style="${sites[i].root_dir ? `display:none;` : `display:block;`}">No directory associated with this address.</p>`;
h += `</div>`;
}
$(el_window).find('.window-body').html(h);
}
// has no sites
else{
$(el_window).find('.window-body').html(`<p style="text-align: center;
margin-top: 40px;
margin-bottom: 50px;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
color: #596c7c;">You haven't published any websites!</p>`);
}
}, Date.now() - init_ts < 1000 ? 0 : 2000);
})
}
$(document).on('click', '.mywebsites-dir-path', function(e){
e = e.target;
UIWindow({
path: $(e).attr('data-path'),
title: $(e).attr('data-name'),
icon: window.icons['folder.svg'],
uid: $(e).attr('data-uuid'),
is_dir: true,
app: 'explorer',
});
})
$(document).on('click', '.mywebsites-site-setting', function(e){
const pos = e.target.getBoundingClientRect();
UIContextMenu({
parent_element: e.target,
position: {top: pos.top+25, left: pos.left-193},
items: [
//--------------------------------------------------
// Release Address
//--------------------------------------------------
{
html: `Release Address`,
onClick: async function(){
const alert_resp = await UIAlert({
message: `Are you sure you want to release this address?`,
buttons:[
{
label: 'Yes, Release It',
type: 'primary',
},
{
label: 'Cancel'
},
]
})
if(alert_resp !== 'Yes, Release It'){
return;
}
$.ajax({
url: api_origin + "/delete-site",
type: 'POST',
data: JSON.stringify({
site_uuid: $(e.target).attr('data-site-uuid'),
}),
async: false,
contentType: "application/json",
headers: {
"Authorization": "Bearer "+auth_token
},
statusCode: {
401: function () {
logout();
},
},
success: function (){
$(`.mywebsites-card[data-uuid="${$(e.target).attr('data-site-uuid')}"]`).fadeOut();
}
})
}
}
]
});
})
$(document).on('click', '.mywebsites-dis-dir', function(e){
puter.hosting.delete(
// dir
$(e.target).attr('data-dir-uuid'),
// hostname
$(e.target).attr('data-site-uuid'),
// success
function (){
$(`.mywebsites-no-dir-notice[data-site-uuid="${$(e.target).attr('data-site-uuid')}"]`).show();
$(`.mywebsites-dir-path[data-uuid="${$(e.target).attr('data-dir-uuid')}"]`).remove();
// remove the website badge from all instances of the dir
$(`.item[data-uid="${$(e.target).attr('data-dir-uuid')}"]`).find('.item-has-website-badge').fadeOut(300);
$(e.target).hide();
}
)
})
export default UIWindowMyWebsites

View File

@ -0,0 +1,56 @@
import UIWindow from './UIWindow.js'
// todo do this using uid rather than item_path, since item_path is way mroe expensive on the DB
async function UIWindowNewFolderProgress(options){
let h = '';
h += `<div data-newfolder-operation-id="${options.operation_id}">`;
h += `<div>`;
// spinner
h +=`<svg style="float:left; margin-right: 7px;" xmlns="http://www.w3.org/2000/svg" height="24" width="24" viewBox="0 0 24 24"><title>circle anim</title><g fill="#212121" class="nc-icon-wrapper"><g class="nc-loop-circle-24-icon-f"><path d="M12 24a12 12 0 1 1 12-12 12.013 12.013 0 0 1-12 12zm0-22a10 10 0 1 0 10 10A10.011 10.011 0 0 0 12 2z" fill="#212121" opacity=".4"></path><path d="M24 12h-2A10.011 10.011 0 0 0 12 2V0a12.013 12.013 0 0 1 12 12z" data-color="color-2"></path></g><style>.nc-loop-circle-24-icon-f{--animation-duration:0.5s;transform-origin:12px 12px;animation:nc-loop-circle-anim var(--animation-duration) infinite linear}@keyframes nc-loop-circle-anim{0%{transform:rotate(0)}100%{transform:rotate(360deg)}}</style></g></svg>`;
// message
h +=`<div style="margin-bottom:20px; float:left; padding-top:3px; font-size:15px; overflow: hidden; width: calc(100% - 40px); text-overflow: ellipsis; white-space: nowrap;">`;
// text
h += `<span class="newfolder-progress-msg">Taking a little longer than usual. Please wait...</span>`;
h += `</div>`;
h +=`</div>`;
h += `</div>`;
const el_window = await UIWindow({
title: `Creating New Folder`,
icon: window.icons[`app-icon-newfolder.svg`],
uid: null,
is_dir: false,
body_content: h,
draggable_body: false,
has_head: false,
selectable_body: false,
draggable_body: true,
allow_context_menu: false,
is_resizable: false,
is_droppable: false,
init_center: true,
allow_native_ctxmenu: false,
allow_user_select: false,
window_class: 'window-newfolder-progress',
width: 450,
dominant: true,
window_css:{
height: 'initial',
},
body_css: {
padding: '22px',
width: 'initial',
'background-color': 'rgba(231, 238, 245, .95)',
'backdrop-filter': 'blur(3px)',
}
});
$(el_window).find('.newfolder-cancel-btn').on('click', function(e){
operation_cancelled[options.operation_id] = true;
$(el_window).close();
})
return el_window;
}
export default UIWindowNewFolderProgress

View File

@ -0,0 +1,126 @@
import UIWindow from './UIWindow.js'
import UIAlert from './UIAlert.js'
import UIWindowLogin from './UIWindowLogin.js'
async function UIWindowNewPassword(options){
return new Promise(async (resolve) => {
options = options ?? {};
const internal_id = window.uuidv4();
let h = '';
h += `<div class="change-password" style="padding: 20px; border-bottom: 1px solid #ced7e1;">`;
// error msg
h += `<div class="form-error-msg"></div>`;
// success msg
h += `<div class="form-success-msg"></div>`;
// new password
h += `<div style="overflow: hidden; margin-top: 20px; margin-bottom: 20px;">`;
h += `<label for="new-password-${internal_id}">New Password</label>`;
h += `<input class="new-password" id="new-password-${internal_id}" type="password" name="new-password" autocomplete="off" />`;
h += `</div>`;
// confirm new password
h += `<div style="overflow: hidden; margin-top: 20px; margin-bottom: 20px;">`;
h += `<label for="confirm-new-password-${internal_id}">Confirm New Password</label>`;
h += `<input class="confirm-new-password" id="confirm-new-password-${internal_id}" type="password" name="confirm-new-password" autocomplete="off" />`;
h += `</div>`;
// Change Password
h += `<button class="change-password-btn button button-primary button-block button-normal">Set New Password</button>`;
h += `</div>`;
const el_window = await UIWindow({
title: 'Set New Password',
app: 'change-passowrd',
single_instance: true,
icon: null,
uid: null,
is_dir: false,
body_content: h,
draggable_body: false,
has_head: true,
selectable_body: false,
draggable_body: false,
allow_context_menu: false,
is_resizable: false,
is_droppable: false,
init_center: true,
allow_native_ctxmenu: false,
allow_user_select: false,
width: 350,
height: 'auto',
dominant: true,
show_in_taskbar: false,
onAppend: function(this_window){
$(this_window).find(`.new-password`).get(0)?.focus({preventScroll:true});
},
window_class: 'window-publishWebsite',
body_css: {
width: 'initial',
height: '100%',
'background-color': 'rgb(245 247 249)',
'backdrop-filter': 'blur(3px)',
}
})
$(el_window).find('.change-password-btn').on('click', function(e){
const new_password = $(el_window).find('.new-password').val();
const confirm_new_password = $(el_window).find('.confirm-new-password').val();
if(new_password === '' || confirm_new_password === ''){
$(el_window).find('.form-error-msg').html('All fields are required.');
$(el_window).find('.form-error-msg').fadeIn();
return;
}
else if(new_password !== confirm_new_password){
$(el_window).find('.form-error-msg').html('`New Password` and `Confirm New Password` do not match.');
$(el_window).find('.form-error-msg').fadeIn();
return;
}
$(el_window).find('.form-error-msg').hide();
$.ajax({
url: api_origin + "/set-pass-using-token",
type: 'POST',
async: true,
contentType: "application/json",
data: JSON.stringify({
password: new_password,
token: options.token,
user_id: options.user,
}),
success: async function (data){
$(el_window).close();
await UIAlert({
message: 'Password changed successfully.',
body_icon: window.icons['c-check.svg'],
stay_on_top: true,
backdrop: true,
buttons:[
{
label: 'Proceed to Login',
type: 'primary',
},
],
window_options: {
backdrop: true,
close_on_backdrop_click: false,
}
})
await UIWindowLogin({
reload_on_success: true,
window_options:{
has_head: false
}
});
},
error: function (err){
$(el_window).find('.form-error-msg').html(err.responseText);
$(el_window).find('.form-error-msg').fadeIn();
}
});
})
})
}
export default UIWindowNewPassword

View File

@ -0,0 +1,56 @@
import UIWindow from './UIWindow.js'
// todo do this using uid rather than item_path, since item_path is way mroe expensive on the DB
async function UIWindowProgressEmptyTrash(options){
let h = '';
h += `<div data-newfolder-operation-id="${options.operation_id}">`;
h += `<div>`;
// spinner
h +=`<svg style="float:left; margin-right: 7px;" xmlns="http://www.w3.org/2000/svg" height="24" width="24" viewBox="0 0 24 24"><title>circle anim</title><g fill="#212121" class="nc-icon-wrapper"><g class="nc-loop-circle-24-icon-f"><path d="M12 24a12 12 0 1 1 12-12 12.013 12.013 0 0 1-12 12zm0-22a10 10 0 1 0 10 10A10.011 10.011 0 0 0 12 2z" fill="#212121" opacity=".4"></path><path d="M24 12h-2A10.011 10.011 0 0 0 12 2V0a12.013 12.013 0 0 1 12 12z" data-color="color-2"></path></g><style>.nc-loop-circle-24-icon-f{--animation-duration:0.5s;transform-origin:12px 12px;animation:nc-loop-circle-anim var(--animation-duration) infinite linear}@keyframes nc-loop-circle-anim{0%{transform:rotate(0)}100%{transform:rotate(360deg)}}</style></g></svg>`;
// message
h +=`<div style="margin-bottom:20px; float:left; padding-top:3px; font-size:15px; overflow: hidden; width: calc(100% - 40px); text-overflow: ellipsis; white-space: nowrap;">`;
// text
h += `<span class="newfolder-progress-msg">Emptying the Trash...</span>`;
h += `</div>`;
h +=`</div>`;
h += `</div>`;
const el_window = await UIWindow({
title: `Creating New Folder`,
icon: window.icons[`app-icon-newfolder.svg`],
uid: null,
is_dir: false,
body_content: h,
draggable_body: false,
has_head: false,
selectable_body: false,
draggable_body: true,
allow_context_menu: false,
is_resizable: false,
is_droppable: false,
init_center: true,
allow_native_ctxmenu: false,
allow_user_select: false,
window_class: 'window-newfolder-progress',
width: 450,
dominant: true,
window_css:{
height: 'initial',
},
body_css: {
padding: '22px',
width: 'initial',
'background-color': 'rgba(231, 238, 245, .95)',
'backdrop-filter': 'blur(3px)',
}
});
$(el_window).find('.newfolder-cancel-btn').on('click', function(e){
operation_cancelled[options.operation_id] = true;
$(el_window).close();
})
return el_window;
}
export default UIWindowProgressEmptyTrash

View File

@ -0,0 +1,116 @@
import UIWindow from './UIWindow.js'
import UIWindowMyWebsites from './UIWindowMyWebsites.js'
async function UIWindowPublishWebsite(target_dir_uid, target_dir_name, target_dir_path){
let h = '';
h += `<div class="window-publishWebsite-content" style="padding: 20px; border-bottom: 1px solid #ced7e1;">`;
// success
h += `<div class="window-publishWebsite-success">`;
h += `<img src="${html_encode(window.icons['c-check.svg'])}" style="width:80px; height:80px; display: block; margin:10px auto;">`;
h += `<p style="text-align:center;"><strong>${target_dir_name}</strong> has been published to:<p>`;
h += `<p style="text-align:center;"><a class="publishWebsite-published-link" target="_blank"></a><img class="publishWebsite-published-link-icon" src="${html_encode(window.icons['launch.svg'])}"></p>`;
h += `<button class="button button-normal button-block button-primary publish-window-ok-btn" style="margin-top:20px;">OK</button>`;
h+= `</div>`;
// form
h += `<form class="window-publishWebsite-form">`;
// error msg
h += `<div class="publish-website-error-msg"></div>`;
// subdomain
h += `<div style="overflow: hidden;">`;
h += `<label style="margin-bottom: 10px;">Pick a name for your website:</label>`;
h += `<div style="font-family: monospace;">https://<input class="publish-website-subdomain" style="width:235px;" type="text" autocomplete="subdomain" spellcheck="false" autocorrect="off" autocapitalize="off" data-gramm_editor="false"/>.${window.hosting_domain}</div>`;
h += `</div>`;
// uid
h += `<input class="publishWebsiteTargetDirUID" type="hidden" value="${target_dir_uid}"/>`;
// Publish
h += `<button class="publish-btn button button-action button-block button-normal">Publish</button>`
h += `</form>`;
h += `</div>`;
const el_window = await UIWindow({
title: 'Publish Website',
icon: null,
uid: null,
is_dir: false,
body_content: h,
draggable_body: false,
has_head: true,
selectable_body: false,
draggable_body: false,
allow_context_menu: false,
is_resizable: false,
is_droppable: false,
init_center: true,
allow_native_ctxmenu: true,
allow_user_select: true,
width: 450,
dominant: true,
onAppend: function(this_window){
$(this_window).find(`.publish-website-subdomain`).val(generate_identifier());
$(this_window).find(`.publish-website-subdomain`).get(0).focus({preventScroll:true});
},
window_class: 'window-publishWebsite',
window_css:{
height: 'initial'
},
body_css: {
width: 'initial',
height: '100%',
'background-color': 'rgb(245 247 249)',
'backdrop-filter': 'blur(3px)',
}
})
$(el_window).find('.publish-btn').on('click', function(e){
// todo do some basic validation client-side
//Subdomain
let subdomain = $(el_window).find('.publish-website-subdomain').val();
// disable 'Publish' button
$(el_window).find('.publish-btn').prop('disabled', true);
puter.hosting.create(
subdomain,
target_dir_path).then((res)=>{
$(el_window).find('.window-publishWebsite-form').hide(100, function(){
let url = 'https://' + subdomain + '.' + window.hosting_domain + '/';
$(el_window).find('.publishWebsite-published-link').attr('href', url);
$(el_window).find('.publishWebsite-published-link').text(url);
$(el_window).find('.window-publishWebsite-success').show(100)
$(`.item[data-uid="${target_dir_uid}"] .item-has-website-badge`).show();
});
// find all items whose path starts with target_dir_path
$(`.item[data-path^="${target_dir_path}"]`).each(function(){
// show the link badge
$(this).find('.item-has-website-url-badge').show();
// update item's website_url attribute
$(this).attr('data-website_url', url + $(this).attr('data-path').substring(target_dir_path.length));
})
update_sites_cache();
}).catch((err)=>{
$(el_window).find('.publish-website-error-msg').html(
err.message + (
err.code === 'subdomain_limit_reached' ?
' <span class="manage-your-websites-link">Manage Your Subdomains</span>' : ''
)
);
$(el_window).find('.publish-website-error-msg').fadeIn();
// re-enable 'Publish' button
$(el_window).find('.publish-btn').prop('disabled', false);
})
})
$(el_window).find('.publish-window-ok-btn').on('click', function(){
$(el_window).close();
})
}
$(document).on('click', '.manage-your-websites-link', async function(e){
UIWindowMyWebsites();
})
export default UIWindowPublishWebsite

61
src/UI/UIWindowQR.js Normal file
View File

@ -0,0 +1,61 @@
import UIWindow from './UIWindow.js'
async function UIWindowQR(options){
return new Promise(async (resolve) => {
options = options ?? {};
let h = '';
// close button containing the multiplication sign
h += `<div class="qr-code-window-close-btn generic-close-window-button"> &times; </div>`;
h += `<div class="otp-qr-code">`;
h += `<h1 style="text-align: center; font-size: 16px; padding: 10px; font-weight: 400; margin: -10px 10px 20px 10px; -webkit-font-smoothing: antialiased; color: #5f626d;">Scan the code below to log into this session from other devices</h1>`;
h += `</div>`;
const el_window = await UIWindow({
title: 'Instant Login!',
app: 'instant-login',
single_instance: true,
icon: null,
uid: null,
is_dir: false,
body_content: h,
draggable_body: false,
has_head: false,
selectable_body: false,
draggable_body: false,
allow_context_menu: false,
is_resizable: false,
is_droppable: false,
init_center: true,
allow_native_ctxmenu: false,
allow_user_select: false,
backdrop: true,
width: 350,
height: 'auto',
dominant: true,
show_in_taskbar: false,
draggable_body: true,
onAppend: function(this_window){
},
window_class: 'window-qr',
body_css: {
width: 'initial',
height: '100%',
'background-color': 'rgb(245 247 249)',
'backdrop-filter': 'blur(3px)',
}
})
// generate auth token QR code
new QRCode($(el_window).find('.otp-qr-code').get(0), {
text: window.gui_origin + '?auth_token=' + window.auth_token,
width: 155,
height: 155,
colorDark : "#000000",
colorLight : "#ffffff",
correctLevel : QRCode.CorrectLevel.H
});
})
}
export default UIWindowQR

View File

@ -0,0 +1,110 @@
import UIWindow from './UIWindow.js'
import UIAlert from './UIAlert.js'
function UIWindowRecoverPassword(options){
return new Promise(async (resolve) => {
options = options ?? {};
let h = '';
h += `<div style="-webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; color: #3e5362;">`;
h += `<h3 style="text-align:center; font-weight: 400; font-size: 20px;">Recover Password</h3>`;
h += `<form class="pass-recovery-form">`;
h += `<p style="text-align:center; padding: 0 20px;"></p>`;
h += `<div class="error"></div>`;
h += `<label>Email or Username</label>`;
h += `<input class="pass-recovery-username-or-email" type="text"/>`;
h += `<button type="submit" class="send-recovery-email button button-block button-primary" style="margin-top:10px;">Send Recovery Email</button>`;
h += `</form>`;
h += `</div>`;
const el_window = await UIWindow({
title: null,
backdrop: options.backdrop ?? false,
icon: null,
uid: null,
is_dir: false,
body_content: h,
draggable_body: false,
has_head: options.has_head ?? true,
selectable_body: false,
draggable_body: true,
allow_context_menu: false,
is_draggable: options.is_draggable ?? true,
is_droppable: false,
is_resizable: false,
stay_on_top: options.stay_on_top ?? false,
allow_native_ctxmenu: true,
allow_user_select: true,
width: 350,
dominant: true,
...options.window_options,
onAppend: function(el_window){
$(el_window).find('.pass-recovery-username-or-email').first().focus();
},
window_class: 'window-item-properties',
window_css:{
height: 'initial',
},
body_css: {
padding: '10px',
width: 'initial',
height: 'initial',
'background-color': 'rgba(231, 238, 245)',
'backdrop-filter': 'blur(3px)',
}
})
$(el_window).find('.pass-recovery-form').on('submit', function(e){
e.preventDefault();
e.stopPropagation();
return false;
})
// Send recovery email
$(el_window).find('.send-recovery-email').on('click', function(e){
let email, username;
let input = $(el_window).find('.pass-recovery-username-or-email').val();
if(is_email(input))
email = input;
else
username = input;
// todo validation before sending
$.ajax({
url: api_origin + "/send-pass-recovery-email",
type: 'POST',
async: true,
contentType: "application/json",
data: JSON.stringify({
email: email,
username: username,
}),
statusCode: {
401: function () {
logout();
},
},
success: async function (res){
$(el_window).close();
await UIAlert({
message: res.message,
body_icon: window.icons['c-check.svg'],
stay_on_top: true,
backdrop: true,
window_options: {
backdrop: true,
close_on_backdrop_click: false,
}
})
},
error: function (err){
$(el_window).find('.error').html(err.responseText);
$(el_window).find('.error').fadeIn();
},
complete: function(){
}
})
})
})
}
export default UIWindowRecoverPassword

102
src/UI/UIWindowRefer.js Normal file
View File

@ -0,0 +1,102 @@
import UIWindow from './UIWindow.js'
import UIPopover from './UIPopover.js'
async function UIWindowRefer(options){
let h = '';
let copy_btn_text = 'Copy Link';
let copied_btn_text = 'Copied!';
const url = `${gui_origin}/?r=${user.referral_code}`;
h += `<div>`;
h += `<div class="qr-code-window-close-btn generic-close-window-button disable-user-select"> &times; </div>`;
h += `<img src="${window.icons['present.svg']}" style="width: 70px; margin: 20px auto 20px; display: block; margin-bottom: 20px;">`;
h += `<p style="text-align: center; font-size: 16px; padding: 20px; font-weight: 400; margin: -10px 10px 20px 10px; -webkit-font-smoothing: antialiased; color: #5f626d;">Get 1 GB for every friend who creates and confirms an account on Puter. Your friend will get 1 GB too!</p>`;
h += `<label style="font-weight: bold;">Invite link</label>`;
h += `<input type="text" style="margin-bottom:10px;" class="downloadable-link" readonly />`;
h += `<button class="button button-primary copy-downloadable-link" style="width:130px;">${copy_btn_text}</button>`
h += `<img class="share-copy-link-on-social" src="${window.icons['share-outline.svg']}">`;
h += `</div>`;
const el_window = await UIWindow({
title: `Refer a friend!`,
icon: null,
uid: null,
is_dir: false,
body_content: h,
has_head: false,
selectable_body: false,
draggable_body: true,
allow_context_menu: false,
is_draggable: true,
is_resizable: false,
is_droppable: false,
init_center: true,
allow_native_ctxmenu: true,
allow_user_select: true,
onAppend: function(el_window){
},
width: 500,
dominant: true,
window_css: {
height: 'initial',
},
body_css: {
padding: '10px',
width: 'initial',
'max-height': 'calc(100vh - 200px)',
'background-color': 'rgb(241 246 251)',
'backdrop-filter': 'blur(3px)',
'padding': '10px 20px 20px 20px',
'height': 'initial',
}
});
$(el_window).find('.window-body .downloadable-link').val(url);
$(el_window).find('.window-body .share-copy-link-on-social').on('click', function(e){
const social_links = socialLink({url: url, title: `Get 1 GB of free storage on Puter.com!`, description: `Get 1 GB of free storage on Puter.com!`});
let social_links_html = ``;
social_links_html += `<div style="padding: 10px;">`;
social_links_html += `<p style="margin: 0; text-align: center; margin-bottom: 6px; color: #484a57; font-weight: bold; font-size: 14px;">Share to</p>`
social_links_html += `<a class="copy-link-social-btn" target="_blank" href="${social_links.twitter}" style=""><svg viewBox="0 0 24 24" aria-hidden="true" style="opacity: 0.7;"><g><path d="M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231zm-1.161 17.52h1.833L7.084 4.126H5.117z"></path></g></svg></a>`
social_links_html += `<a class="copy-link-social-btn" target="_blank" href="${social_links.whatsapp}" style=""><img src="${window.icons['logo-whatsapp.svg']}"></a>`
social_links_html += `<a class="copy-link-social-btn" target="_blank" href="${social_links.facebook}" style=""><img src="${window.icons['logo-facebook.svg']}"></a>`
social_links_html += `<a class="copy-link-social-btn" target="_blank" href="${social_links.linkedin}" style=""><img src="${window.icons['logo-linkedin.svg']}"></a>`
social_links_html += `<a class="copy-link-social-btn" target="_blank" href="${social_links.reddit}" style=""><img src="${window.icons['logo-reddit.svg']}"></a>`
social_links_html += `<a class="copy-link-social-btn" target="_blank" href="${social_links['telegram.me']}" style=""><img src="${window.icons['logo-telegram.svg']}"></a>`
social_links_html += '</div>';
UIPopover({
content: social_links_html,
snapToElement: this,
parent_element: this,
// width: 300,
height: 100,
position: 'bottom',
});
})
$(el_window).find('.window-body .copy-downloadable-link').on('click', async function(e){
var copy_btn = this;
if (navigator.clipboard) {
// Get link text
const selected_text = $(el_window).find('.window-body .downloadable-link').val();
// copy selected text to clipboard
await navigator.clipboard.writeText(selected_text);
}
else{
// Get the text field
$(el_window).find('.window-body .downloadable-link').select();
// Copy the text inside the text field
document.execCommand('copy');
}
$(this).html(copied_btn_text);
setTimeout(function(){
$(copy_btn).html(copy_btn_text);
}, 1000);
});
}
export default UIWindowRefer

View File

@ -0,0 +1,75 @@
import UIWindow from './UIWindow.js'
async function UIWindowRequestFiles(options){
let h = '';
h += `<div>`;
h += `<h3 style="margin-bottom: 0;">File Request Link:</h3>`;
h += `<p style="word-break: break-all;" class="filereq-link"></p>`;
h += `</div>`;
const el_window = await UIWindow({
title: `Request Files`,
icon: null,
uid: null,
is_dir: false,
body_content: h,
draggable_body: false,
has_head: true,
selectable_body: false,
draggable_body: false,
allow_context_menu: false,
is_resizable: false,
is_droppable: false,
init_center: true,
allow_native_ctxmenu: true,
allow_user_select: true,
width: 400,
dominant: true,
onAppend: function(el_window){
},
window_class: 'window-item-properties',
window_css:{
height: 'initial',
},
body_css: {
padding: '10px',
width: 'initial',
'max-height': 'calc(100vh - 200px)',
'background-color': 'rgba(231, 238, 245)',
'backdrop-filter': 'blur(3px)',
'padding-bottom': 0,
'height': 'initial',
}
});
//check if there is a fr token available
let stat = await puter.fs.stat(options.dir_path);
if(stat.file_request_url !== undefined && stat.file_request_url !== null && stat.file_request_url !== ''){
$(el_window).find('.filereq-link').html(stat.file_request_url);
}
// generate new fr url
else{
$.ajax({
url: api_origin + "/filereq",
type: 'POST',
data: JSON.stringify({
dir_path: options.dir_path
}),
async: true,
contentType: "application/json",
headers: {
"Authorization": "Bearer "+auth_token
},
statusCode: {
401: function (){
logout();
},
},
success: function (filereq){
$(el_window).find('.filereq-link').html(filereq.url);
}
});
}
}
export default UIWindowRequestFiles

View File

@ -0,0 +1,125 @@
import UIWindow from './UIWindow.js'
async function UIWindowRequestPermission(options){
options = options ?? {};
options.reload_on_success = options.reload_on_success ?? false;
return new Promise(async (resolve) => {
let drivers = [
{
name: 'puter-chat-completion',
human_name: 'AI Chat Completion',
description: 'This app wants to generate text using AI. This may incur costs on your behalf.',
},
{
name: 'puter-image-generation',
human_name: 'AI Image Generation',
description: 'This app wants to generate images using AI. This may incur costs on your behalf.',
},
{
name: 'puter-kvstore',
human_name: 'Puter Storage',
description: 'This app wants to securely store data in your Puter account. This app will not be able to access your personal data or data stored by other apps.',
}
]
let parts = options.permission.split(":");
let driver_name = parts[1];
let action_name = parts[2];
function findDriverByName(driverName) {
return drivers.find(driver => driver.name === driverName);
}
let driver = findDriverByName(driver_name);
if(driver === undefined){
resolve(false);
return;
}
let h = ``;
h += `<div>`;
h += `<div style="padding: 20px; width: 100%; box-sizing: border-box;">`;
// title
h += `<h1 class="perm-title">"<span style="word-break: break-word;">${html_encode(options.app_uid ?? options.origin)}</span>" would Like to use ${html_encode(driver.human_name)}</h1>`;
// todo show the real description of action
h += `<p class="perm-description">${html_encode(driver.description)}</p>`;
// Allow/Don't Allow
h += `<button type="button" class="app-auth-allow button button-primary button-block" style="margin-top: 10px;">Allow</button>`;
h += `<button type="button" class="app-auth-dont-allow button button-default button-block" style="margin-top: 10px;">Don't Allow</button>`;
h += `</div>`;
h += `</div>`;
const el_window = await UIWindow({
title: null,
app: 'request-authorization',
single_instance: true,
icon: null,
uid: null,
is_dir: false,
body_content: h,
draggable_body: false,
has_head: true,
selectable_body: false,
draggable_body: true,
allow_context_menu: false,
is_draggable: true,
is_droppable: false,
is_resizable: false,
stay_on_top: false,
allow_native_ctxmenu: true,
allow_user_select: true,
...options.window_options,
width: 350,
dominant: true,
on_close: ()=>{
resolve(false)
},
onAppend: function(this_window){
},
window_class: 'window-login',
window_css:{
height: 'initial',
},
body_css: {
width: 'initial',
padding: '0',
'background-color': 'rgba(231, 238, 245, .95)',
'backdrop-filter': 'blur(3px)',
}
})
$(el_window).find('.app-auth-allow').on('click', async function(e){
$(this).addClass('disabled');
try{
const res = await fetch( window.api_origin + "/auth/grant-user-app", {
"headers": {
"Content-Type": "application/json",
"Authorization": "Bearer " + window.auth_token,
},
"body": JSON.stringify({
app_uid: options.app_uid,
origin: options.origin,
permission: options.permission
}),
"method": "POST",
});
}catch(err){
console.error(err);
resolve(err);
}
resolve(true);
})
$(el_window).find('.app-auth-dont-allow').on('click', function(e){
$(this).addClass('disabled');
$(el_window).close();
resolve(false);
})
})
}
export default UIWindowRequestPermission

View File

@ -0,0 +1,167 @@
import UIWindow from './UIWindow.js'
import UIWindowEmailConfirmationRequired from './UIWindowEmailConfirmationRequired.js'
async function UIWindowSaveAccount(options){
const internal_id = window.uuidv4();
options = options ?? {};
options.reload_on_success = options.reload_on_success ?? false;
options.send_confirmation_code = options.send_confirmation_code ?? false;
return new Promise(async (resolve) => {
let h = '';
h += `<div>`;
// success
h += `<div class="save-account-success">`;
h += `<img src="${html_encode(window.icons['c-check.svg'])}" style="width:50px; height:50px; display: block; margin:10px auto;">`;
h += `<p style="text-align:center; margin-bottom:10px;">Thank you for creating an account. This session has been saved.</p>`;
h += `<button class="button button-action button-block save-account-success-ok-btn">OK</button>`
h+= `</div>`;
// form
h += `<div class="save-account-form" style="padding: 20px; border-bottom: 1px solid #ced7e1; width: 100%; box-sizing: border-box;">`;
// title
h += `<h1 class="signup-form-title" style="margin-bottom:0;">Create Account</h1>`;
// description
h += `<p class="create-account-desc">${options.message ?? 'Create an account to save your current session and avoid losing your work.'}</p>`;
// signup form
h += `<form class="signup-form">`;
// error msg
h += `<div class="signup-error-msg"></div>`;
// username
h += `<div style="overflow: hidden;">`;
h += `<label for="username-${internal_id}">Username</label>`;
h += `<input id="username-${internal_id}" class="username" value="${options.default_username ?? ''}" type="text" autocomplete="username" spellcheck="false" autocorrect="off" autocapitalize="off" data-gramm_editor="false"/>`;
h += `</div>`;
// email
h += `<div style="overflow: hidden; margin-top: 20px;">`;
h += `<label for="email-${internal_id}">Email</label>`;
h += `<input id="email-${internal_id}" class="email" type="email" autocomplete="email" spellcheck="false" autocorrect="off" autocapitalize="off" data-gramm_editor="false"/>`;
h += `</div>`;
// password
h += `<div style="overflow: hidden; margin-top: 20px; margin-bottom: 20px;">`;
h += `<label for="password-${internal_id}">Password</label>`;
h += `<input id="password-${internal_id}" class="password" type="password" name="password" autocomplete="new-password" />`;
h += `</div>`;
// bot trap - if this value is submitted server will ignore the request
h += `<input type="text" name="p102xyzname" class="p102xyzname" value="">`;
// Create Account
h += `<button class="signup-btn button button-primary button-block button-normal">Create Account</button>`
h += `</form>`;
h += `</div>`;
h += `</div>`;
const el_window = await UIWindow({
title: null,
icon: null,
uid: null,
app: 'save-account',
single_instance: true,
is_dir: false,
body_content: h,
has_head: true,
selectable_body: false,
draggable_body: true,
allow_context_menu: false,
is_draggable: true,
is_droppable: false,
is_resizable: false,
stay_on_top: false,
allow_native_ctxmenu: true,
allow_user_select: true,
width: 350,
dominant: true,
show_in_taskbar: false,
...options.window_options,
onAppend: function(this_window){
if(options.default_username)
$(this_window).find('.email').get(0).focus({preventScroll:true});
else
$(this_window).find('.username').get(0).focus({preventScroll:true});
},
window_class: 'window-save-account',
window_css:{
height: 'initial',
},
on_close: ()=>{
resolve(false)
},
body_css: {
width: 'initial',
'background-color': 'rgba(231, 238, 245, .95)',
'backdrop-filter': 'blur(3px)',
}
})
$(el_window).find('.signup-btn').on('click', function(e){
// todo do some basic validation client-side
//Username
let username = $(el_window).find('.username').val();
//Email
let email = $(el_window).find('.email').val();
//Password
let password = $(el_window).find('.password').val();
// disable 'Create Account' button
$(el_window).find('.signup-btn').prop('disabled', true);
$.ajax({
url: api_origin + "/save_account",
type: 'POST',
async: true,
contentType: "application/json",
data: JSON.stringify({
username: username,
email: email,
password: password,
referrer: options.referrer,
send_confirmation_code: options.send_confirmation_code,
}),
headers: {
"Authorization": "Bearer "+auth_token
},
success: async function (data){
update_auth_data(data.token, data.user)
//close this window
if(data.user.email_confirmation_required){
let is_verified = await UIWindowEmailConfirmationRequired({
stay_on_top: true,
has_head: true
});
resolve(is_verified);
}else{
resolve(true);
}
$(el_window).find('.save-account-form').hide(100, ()=>{
$(el_window).find('.save-account-success').show(100);
})
},
error: function (err){
$(el_window).find('.signup-error-msg').html(err.responseText);
$(el_window).find('.signup-error-msg').fadeIn();
// re-enable 'Create Account' button
$(el_window).find('.signup-btn').prop('disabled', false);
}
});
})
$(el_window).find('.signup-form').on('submit', function(e){
e.preventDefault();
e.stopPropagation();
return false;
})
$(el_window).find('.save-account-success-ok-btn').on('click', ()=>{
$(el_window).close();
})
//remove login window
$(el_window).find('.signup-c2a-clickable').parents('.window').close();
})
}
export default UIWindowSaveAccount

View File

@ -0,0 +1,92 @@
import UIWindow from './UIWindow.js'
async function UIWindowSelfhostedWaitlist(options){
options = options ?? {};
options.reload_on_success = options.reload_on_success ?? false;
return new Promise(async (resolve) => {
getItem({
key: "joined_selfhosted_waitlist",
success: async function(resp){
if(resp.value){
$(el_window).find('.join-waitlist-btn').hide();
$(el_window).find('.waitlist-success-msg').show();
}else{
$(el_window).find('.join-waitlist-btn').show();
$(el_window).find('.waitlist-success-msg').hide();
}
}
})
let h = ``;
h += `<div>`;
h += `<div style="padding: 20px; width: 100%; box-sizing: border-box;">`;
// title
h += `<svg style="width: 70px; height: 70px; margin: 0 auto; display: block;" id="Icons" height="512" viewBox="0 0 60 60" width="512" xmlns="http://www.w3.org/2000/svg"><path d="m45 19v29a3 3 0 0 1 -3 3h-34a3 3 0 0 1 -3-3v-29l20-15z" fill="#cce2ed"/><path d="m10 13.32v-8.66a1.656 1.656 0 0 1 1.66-1.66h2.68a1.656 1.656 0 0 1 1.66 1.66v4.34z" fill="#30649d"/><path d="m2.2 20.607a.861.861 0 0 0 1.226.23l21.083-15.179a.831.831 0 0 1 .982 0l21.08 15.179a.861.861 0 0 0 1.226-.23l1.056-1.574a.877.877 0 0 0 -.206-1.19l-23.156-16.683a.834.834 0 0 0 -.982 0l-23.156 16.683a.877.877 0 0 0 -.206 1.19z" fill="#3b7ac8"/><path d="m59 40v5a3 3 0 0 1 -3 3v1h-32v-1a3 3 0 0 1 -3-3v-5a3 3 0 0 1 3-3v-1h32v1a3 3 0 0 1 3 3z" fill="#30649d"/><rect fill="#3b7ac8" height="11" rx="3" width="38" x="21" y="26"/><rect fill="#3b7ac8" height="11" rx="3" width="38" x="21" y="48"/><path d="m26 55a1 1 0 0 1 -1-1v-1a1 1 0 0 1 2 0v1a1 1 0 0 1 -1 1z" fill="#76e4c1"/><path d="m30 55a1 1 0 0 1 -1-1v-1a1 1 0 0 1 2 0v1a1 1 0 0 1 -1 1z" fill="#76e4c1"/><g fill="#30649d"><path d="m47 55a1 1 0 0 1 -1-1v-1a1 1 0 0 1 2 0v1a1 1 0 0 1 -1 1z"/><path d="m43 55a1 1 0 0 1 -1-1v-1a1 1 0 0 1 2 0v1a1 1 0 0 1 -1 1z"/><path d="m51 55a1 1 0 0 1 -1-1v-1a1 1 0 0 1 2 0v1a1 1 0 0 1 -1 1z"/><path d="m55 55a1 1 0 0 1 -1-1v-1a1 1 0 0 1 2 0v1a1 1 0 0 1 -1 1z"/></g><path d="m26 44a1 1 0 0 1 -1-1v-1a1 1 0 0 1 2 0v1a1 1 0 0 1 -1 1z" fill="#76e4c1"/><path d="m30 44a1 1 0 0 1 -1-1v-1a1 1 0 0 1 2 0v1a1 1 0 0 1 -1 1z" fill="#76e4c1"/><path d="m47 44a1 1 0 0 1 -1-1v-1a1 1 0 0 1 2 0v1a1 1 0 0 1 -1 1z" fill="#23527c"/><path d="m43 44a1 1 0 0 1 -1-1v-1a1 1 0 0 1 2 0v1a1 1 0 0 1 -1 1z" fill="#23527c"/><path d="m51 44a1 1 0 0 1 -1-1v-1a1 1 0 0 1 2 0v1a1 1 0 0 1 -1 1z" fill="#23527c"/><path d="m55 44a1 1 0 0 1 -1-1v-1a1 1 0 0 1 2 0v1a1 1 0 0 1 -1 1z" fill="#23527c"/><path d="m26 33a1 1 0 0 1 -1-1v-1a1 1 0 0 1 2 0v1a1 1 0 0 1 -1 1z" fill="#76e4c1"/><path d="m30 33a1 1 0 0 1 -1-1v-1a1 1 0 0 1 2 0v1a1 1 0 0 1 -1 1z" fill="#76e4c1"/><path d="m47 33a1 1 0 0 1 -1-1v-1a1 1 0 0 1 2 0v1a1 1 0 0 1 -1 1z" fill="#30649d"/><path d="m43 33a1 1 0 0 1 -1-1v-1a1 1 0 0 1 2 0v1a1 1 0 0 1 -1 1z" fill="#30649d"/><path d="m51 33a1 1 0 0 1 -1-1v-1a1 1 0 0 1 2 0v1a1 1 0 0 1 -1 1z" fill="#30649d"/><path d="m55 33a1 1 0 0 1 -1-1v-1a1 1 0 0 1 2 0v1a1 1 0 0 1 -1 1z" fill="#30649d"/></svg>`;
h += `<h1 class="login-form-title" style="margin-bottom: 0; margin-top: 15px; font-size: 18px;">Self-Hosted Puter is Coming soon!</h1>`;
h += `<p style=" text-align:center; font-size: 15px; -webkit-font-smoothing: antialiased;padding: 0 10px; color: #2d3847; margin-top:0; margin-bottom: 0;">Join the waitlist for the launch of Self-Hosted Puter!</p>`;
// error msg
h += `<div class="login-error-msg"></div>`;
// success
h += `<div class="waitlist-success-msg form-success-msg" style="background-color: #cafbe4; margin-top:10px; margin-bottom: 0;">You've been added to the waitlist and will receive a notification when it's your turn.</div>`;
// waitlist
h += `<button type="button" class="join-waitlist-btn button button-primary button-block" style="margin-top: 10px; display:none;">Join Waitlist!</button>`;
h += `</div>`;
h += `</div>`;
const el_window = await UIWindow({
title: null,
app: 'waitlist',
single_instance: true,
icon: null,
uid: null,
is_dir: false,
body_content: h,
draggable_body: false,
has_head: true,
selectable_body: false,
draggable_body: true,
allow_context_menu: false,
is_draggable: true,
is_droppable: false,
is_resizable: false,
stay_on_top: false,
allow_native_ctxmenu: true,
allow_user_select: true,
...options.window_options,
width: 350,
dominant: true,
on_close: ()=>{
resolve(false)
},
onAppend: function(this_window){
},
window_class: 'window-login',
window_css:{
height: 'initial',
},
body_css: {
width: 'initial',
padding: '0',
height: 245,
'background-color': 'rgba(231, 238, 245, .95)',
'backdrop-filter': 'blur(3px)',
}
})
$(el_window).find('.join-waitlist-btn').on('click', function(e){
$(this).addClass('disabled');
setItem({
key: "joined_selfhosted_waitlist",
value: true,
success: async function(){
$(el_window).find('.join-waitlist-btn').hide();
$(el_window).find('.waitlist-success-msg').show();
}
})
})
})
}
export default UIWindowSelfhostedWaitlist

View File

@ -0,0 +1,138 @@
import UIWindow from './UIWindow.js'
import UIWindowLogin from './UIWindowLogin.js'
import UIWindowSignup from './UIWindowSignup.js'
async function UIWindowSessionList(options){
options = options ?? {};
options.reload_on_success = options.reload_on_success ?? true;
return new Promise(async (resolve) => {
let h = '';
h += `<div style="margin:10px;">`;
h += `<div class="loading">Signing in...</div>`
h += `<div style="overflow-y: scroll; max-width: 400px; margin: 0 auto;">`;
h += `<h1 style="text-align: center; font-size: 18px; font-weight: normal; color: #757575;"><img src="${icons['logo-white.svg']}" style="padding: 4px; background-color: blue; border-radius: 5px; width: 25px; box-sizing: border-box; margin-bottom: -6px; margin-right: 6px;">Sign in with Puter</h1>`
for (let index = 0; index < logged_in_users.length; index++) {
const l_user = logged_in_users[index];
h += `<div data-uuid="${l_user.uuid}" class="session-entry">${l_user.username}</div>`;
}
h += `</div>`;
h += `<div style="margin-top: 20px; margin-bottom: 20px; text-align:center;"><span class="login-c2a-session-list">Log Into Another Account</span> &bull; <span class="signup-c2a-session-list">Create Account</span></div>`;
h += `</div>`;
const el_window = await UIWindow({
title: 'Session List!',
app: 'session-list',
single_instance: true,
icon: null,
uid: null,
is_dir: false,
body_content: h,
has_head: false,
selectable_body: false,
draggable_body: options.draggable_body ?? true,
allow_context_menu: false,
is_resizable: false,
is_droppable: false,
init_center: true,
allow_native_ctxmenu: false,
allow_user_select: false,
width: 350,
height: 'auto',
dominant: true,
show_in_taskbar: false,
update_window_url: false,
cover_page: options.cover_page ?? false,
onAppend: function(this_window){
},
window_class: 'window-session-list',
body_css: {
width: 'initial',
height: '100%',
'background-color': 'rgb(245 247 249)',
'backdrop-filter': 'blur(3px)',
'display': 'flex',
'flex-direction': 'column',
'justify-content': 'center',
}
})
$(el_window).find('.login-c2a-session-list').on('click', async function(e){
const login = await UIWindowLogin({
referrer: options.referrer,
reload_on_success: options.reload_on_success,
window_options: options.window_options,
cover_page: options.cover_page ?? false,
has_head: options.has_head,
send_confirmation_code: options.send_confirmation_code,
window_options: {
has_head: false,
cover_page: options.cover_page ?? false,
}
});
if(login){
if(options.reload_on_success){
// disable native browser exit confirmation
window.onbeforeunload = null;
// refresh
location.reload();
}else{
resolve(login);
}
}
})
$(el_window).find('.signup-c2a-session-list').on('click', async function(e){
$('.signup-c2a-clickable').parents('.window').close();
// create Signup window
const signup = await UIWindowSignup({
referrer: options.referrer,
reload_on_success: options.reload_on_success,
window_options: options.window_options,
send_confirmation_code: options.send_confirmation_code,
window_options: {
has_head: false,
cover_page: options.cover_page ?? false,
}
});
if(signup){
if(options.reload_on_success){
// disable native browser exit confirmation
window.onbeforeunload = null;
// refresh
location.reload();
}else{
resolve(signup);
}
}
})
$(el_window).find('.session-entry').on('click', function(e){
$(el_window).find('.loading').css({display: 'flex'});
setTimeout(() => {
let selected_uuid = $(this).attr('data-uuid');
let selected_user;
for (let index = 0; index < window.logged_in_users.length; index++) {
const l_user = logged_in_users[index];
if(l_user.uuid === selected_uuid){
selected_user = l_user;
}
}
// new logged in user
update_auth_data(selected_user.auth_token, selected_user);
if(options.reload_on_success){
// disable native browser exit confirmation
window.onbeforeunload = null;
// refresh
location.reload();
}else{
resolve(true);
}
}, 500);
})
})
}
export default UIWindowSessionList

186
src/UI/UIWindowSignup.js Normal file
View File

@ -0,0 +1,186 @@
import UIWindow from './UIWindow.js'
import UIWindowLogin from './UIWindowLogin.js'
import UIWindowEmailConfirmationRequired from './UIWindowEmailConfirmationRequired.js'
function UIWindowSignup(options){
options = options ?? {};
options.reload_on_success = options.reload_on_success ?? false;
options.has_head = options.has_head ?? true;
options.send_confirmation_code = options.send_confirmation_code ?? false;
return new Promise(async (resolve) => {
const internal_id = window.uuidv4();
let h = '';
h += `<div style="margin: 0 auto; max-width: 500px; min-width: 400px;">`;
// logo
h += `<img src="${window.icons['logo-white.svg']}" style="width: 40px; height: 40px; margin: 0 auto; display: block; padding: 15px; background-color: blue; border-radius: 5px;">`;
// close button
if(!options.has_head && options.show_close_button !== false)
h += `<div class="generic-close-window-button"> &times; </div>`;
// Form
h += `<div style="padding: 20px; border-bottom: 1px solid #ced7e1;">`;
// title
h += `<h1 class="signup-form-title">Create Free Account</h1>`;
// signup form
h += `<form class="signup-form">`;
// error msg
h += `<div class="signup-error-msg"></div>`;
// username
h += `<div style="overflow: hidden;">`;
h += `<label for="username-${internal_id}">Username</label>`;
h += `<input id="username-${internal_id}" class="username" type="text" autocomplete="username" spellcheck="false" autocorrect="off" autocapitalize="off" data-gramm_editor="false"/>`;
h += `</div>`;
// email
h += `<div style="overflow: hidden; margin-top: 20px;">`;
h += `<label for="email-${internal_id}">Email</label>`;
h += `<input id="email-${internal_id}" class="email" type="email" autocomplete="email" spellcheck="false" autocorrect="off" autocapitalize="off" data-gramm_editor="false"/>`;
h += `</div>`;
// password
h += `<div style="overflow: hidden; margin-top: 20px; margin-bottom: 20px;">`;
h += `<label for="password-${internal_id}">Password</label>`;
h += `<input id="password-${internal_id}" class="password" type="password" name="password" autocomplete="new-password" />`;
h += `</div>`;
// bot trap - if this value is submitted server will ignore the request
h += `<input type="text" name="p102xyzname" class="p102xyzname" value="">`;
// terms and privacy
h += `<p class="signup-terms">By clicking 'Create Free Account' you agree to Puter's <a href="https://puter.com/terms" target="_blank">Terms of Service</a> and <a href="https://puter.com/privacy" target="_blank">Privacy Policy</a>.</p>`;
// Create Account
h += `<button class="signup-btn button button-primary button-block button-normal">Create Free Account</button>`
h += `</form>`;
h += `</div>`;
// login link
// create account link
h += `<div class="c2a-wrapper" style="padding:20px;">`;
h += `<button class="login-c2a-clickable">Log In</button>`;
h += `</div>`;
h += `</div>`;
const el_window = await UIWindow({
title: null,
app: 'signup',
single_instance: true,
icon: null,
uid: null,
is_dir: false,
body_content: h,
draggable_body: false,
has_head: true,
selectable_body: false,
allow_context_menu: false,
is_draggable: false,
is_droppable: false,
is_resizable: false,
stay_on_top: false,
allow_native_ctxmenu: true,
allow_user_select: true,
...options.window_options,
// width: 350,
dominant: false,
center: true,
onAppend: function(el_window){
$(el_window).find(`.username`).get(0).focus({preventScroll:true});
},
window_class: 'window-signup',
window_css:{
height: 'initial',
},
body_css: {
width: 'initial',
'background-color': 'white',
'backdrop-filter': 'blur(3px)',
'display': 'flex',
'flex-direction': 'column',
'justify-content': 'center',
'align-items': 'center',
padding: '30px 10px 10px 10px',
}
})
$(el_window).find('.login-c2a-clickable').on('click', async function(e){
$('.login-c2a-clickable').parents('.window').close();
const login = await UIWindowLogin({
referrer: options.referrer,
reload_on_success: options.reload_on_success,
window_options: options.window_options,
show_close_button: options.show_close_button,
send_confirmation_code: options.send_confirmation_code,
});
if(login)
resolve(true);
})
$(el_window).find('.signup-btn').on('click', function(e){
// todo do some basic validation client-side
//Username
let username = $(el_window).find('.username').val();
//Email
let email = $(el_window).find('.email').val();
//Password
let password = $(el_window).find('.password').val();
//xyzname
let p102xyzname = $(el_window).find('.p102xyzname').val();
// disable 'Create Account' button
$(el_window).find('.signup-btn').prop('disabled', true);
let headers = {};
if(window.custom_headers)
headers = window.custom_headers;
$.ajax({
url: gui_origin + "/signup",
type: 'POST',
async: true,
headers: headers,
contentType: "application/json",
data: JSON.stringify({
username: username,
referral_code: window.referral_code,
email: email,
password: password,
referrer: options.referrer ?? window.referrerStr,
send_confirmation_code: options.send_confirmation_code,
p102xyzname: p102xyzname,
}),
success: async function (data){
update_auth_data(data.token, data.user)
//send out the login event
if(options.reload_on_success){
window.onbeforeunload = null;
window.location.replace('/');
}else if(options.send_confirmation_code){
$(el_window).close();
let is_verified = await UIWindowEmailConfirmationRequired({stay_on_top: true, has_head: true});
resolve(is_verified);
}else{
resolve(true);
}
},
error: function (err){
$(el_window).find('.signup-error-msg').html(err.responseText);
$(el_window).find('.signup-error-msg').fadeIn();
// re-enable 'Create Account' button
$(el_window).find('.signup-btn').prop('disabled', false);
}
});
})
$(el_window).find('.signup-form').on('submit', function(e){
e.preventDefault();
e.stopPropagation();
return false;
})
//remove login window
$('.signup-c2a-clickable').parents('.window').close();
})
}
export default UIWindowSignup

View File

@ -0,0 +1,57 @@
import UIWindow from './UIWindow.js'
// todo do this using uid rather than item_path, since item_path is way mroe expensive on the DB
async function UIWindowUploadProgress(options){
let h = '';
h += `<div data-upload-operation-id="${options.operation_id}">`;
h += `<div>`;
// spinner
h +=`<svg style="float:left; margin-right: 7px;" xmlns="http://www.w3.org/2000/svg" height="24" width="24" viewBox="0 0 24 24"><title>circle anim</title><g fill="#212121" class="nc-icon-wrapper"><g class="nc-loop-circle-24-icon-f"><path d="M12 24a12 12 0 1 1 12-12 12.013 12.013 0 0 1-12 12zm0-22a10 10 0 1 0 10 10A10.011 10.011 0 0 0 12 2z" fill="#212121" opacity=".4"></path><path d="M24 12h-2A10.011 10.011 0 0 0 12 2V0a12.013 12.013 0 0 1 12 12z" data-color="color-2"></path></g><style>.nc-loop-circle-24-icon-f{--animation-duration:0.5s;transform-origin:12px 12px;animation:nc-loop-circle-anim var(--animation-duration) infinite linear}@keyframes nc-loop-circle-anim{0%{transform:rotate(0)}100%{transform:rotate(360deg)}}</style></g></svg>`;
// Progress report
h +=`<div style="margin-bottom:20px; float:left; padding-top:3px; font-size:15px; overflow: hidden; width: calc(100% - 40px); text-overflow: ellipsis; white-space: nowrap;">`;
// msg
h += `<span class="upload-progress-msg">Preparing for upload...</span>`;
h += `</div>`;
// progress
h += `<div class="upload-progress-bar-container" style="clear:both; margin-top:20px; border-radius:3px;">`;
h += `<div class="upload-progress-bar"></div>`;
h += `</div>`;
// cancel
h += `<button style="float:right; margin-top: 15px; margin-right: -2px;" class="button button-small upload-cancel-btn">Cancel</button>`;
h +=`</div>`;
h += `</div>`;
const el_window = await UIWindow({
title: `Upload`,
icon: window.icons[`app-icon-uploader.svg`],
uid: null,
is_dir: false,
body_content: h,
draggable_body: false,
has_head: false,
selectable_body: false,
draggable_body: true,
allow_context_menu: false,
is_resizable: false,
is_droppable: false,
init_center: true,
allow_native_ctxmenu: false,
allow_user_select: false,
window_class: 'window-upload-progress',
width: 450,
dominant: true,
window_css:{
height: 'initial',
},
body_css: {
padding: '22px',
width: 'initial',
'background-color': 'rgba(231, 238, 245, .95)',
'backdrop-filter': 'blur(3px)',
}
});
return el_window;
}
export default UIWindowUploadProgress

8
src/browserconfig.xml Normal file
View File

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="utf-8"?>
<browserconfig>
<msapplication>
<tile>
<square70x70logo src="./favicons/ms-icon-70x70.png"/>
<square150x150logo src="./favicons/ms-icon-150x150.png"/>
<square310x310logo src="./favicons/ms-icon-310x310.png"/>
<TileColor>#ffffff</TileColor></tile></msapplication></browserconfig>

349
src/css/normalize.css vendored Normal file
View File

@ -0,0 +1,349 @@
/*! normalize.css v8.0.1 | MIT License | github.com/necolas/normalize.css */
/* Document
========================================================================== */
/**
* 1. Correct the line height in all browsers.
* 2. Prevent adjustments of font size after orientation changes in iOS.
*/
html {
line-height: 1.15; /* 1 */
-webkit-text-size-adjust: 100%; /* 2 */
}
/* Sections
========================================================================== */
/**
* Remove the margin in all browsers.
*/
body {
margin: 0;
}
/**
* Render the `main` element consistently in IE.
*/
main {
display: block;
}
/**
* Correct the font size and margin on `h1` elements within `section` and
* `article` contexts in Chrome, Firefox, and Safari.
*/
h1 {
font-size: 2em;
margin: 0.67em 0;
}
/* Grouping content
========================================================================== */
/**
* 1. Add the correct box sizing in Firefox.
* 2. Show the overflow in Edge and IE.
*/
hr {
box-sizing: content-box; /* 1 */
height: 0; /* 1 */
overflow: visible; /* 2 */
}
/**
* 1. Correct the inheritance and scaling of font size in all browsers.
* 2. Correct the odd `em` font sizing in all browsers.
*/
pre {
font-family: monospace, monospace; /* 1 */
font-size: 1em; /* 2 */
}
/* Text-level semantics
========================================================================== */
/**
* Remove the gray background on active links in IE 10.
*/
a {
background-color: transparent;
}
/**
* 1. Remove the bottom border in Chrome 57-
* 2. Add the correct text decoration in Chrome, Edge, IE, Opera, and Safari.
*/
abbr[title] {
border-bottom: none; /* 1 */
text-decoration: underline; /* 2 */
text-decoration: underline dotted; /* 2 */
}
/**
* Add the correct font weight in Chrome, Edge, and Safari.
*/
b,
strong {
font-weight: bolder;
}
/**
* 1. Correct the inheritance and scaling of font size in all browsers.
* 2. Correct the odd `em` font sizing in all browsers.
*/
code,
kbd,
samp {
font-family: monospace, monospace; /* 1 */
font-size: 1em; /* 2 */
}
/**
* Add the correct font size in all browsers.
*/
small {
font-size: 80%;
}
/**
* Prevent `sub` and `sup` elements from affecting the line height in
* all browsers.
*/
sub,
sup {
font-size: 75%;
line-height: 0;
position: relative;
vertical-align: baseline;
}
sub {
bottom: -0.25em;
}
sup {
top: -0.5em;
}
/* Embedded content
========================================================================== */
/**
* Remove the border on images inside links in IE 10.
*/
img {
border-style: none;
}
/* Forms
========================================================================== */
/**
* 1. Change the font styles in all browsers.
* 2. Remove the margin in Firefox and Safari.
*/
button,
input,
optgroup,
select,
textarea {
font-family: inherit; /* 1 */
font-size: 100%; /* 1 */
line-height: 1.15; /* 1 */
margin: 0; /* 2 */
}
/**
* Show the overflow in IE.
* 1. Show the overflow in Edge.
*/
button,
input { /* 1 */
overflow: visible;
}
/**
* Remove the inheritance of text transform in Edge, Firefox, and IE.
* 1. Remove the inheritance of text transform in Firefox.
*/
button,
select { /* 1 */
text-transform: none;
}
/**
* Correct the inability to style clickable types in iOS and Safari.
*/
button,
[type="button"],
[type="reset"],
[type="submit"] {
-webkit-appearance: button;
}
/**
* Remove the inner border and padding in Firefox.
*/
button::-moz-focus-inner,
[type="button"]::-moz-focus-inner,
[type="reset"]::-moz-focus-inner,
[type="submit"]::-moz-focus-inner {
border-style: none;
padding: 0;
}
/**
* Restore the focus styles unset by the previous rule.
*/
button:-moz-focusring,
[type="button"]:-moz-focusring,
[type="reset"]:-moz-focusring,
[type="submit"]:-moz-focusring {
outline: 1px dotted ButtonText;
}
/**
* Correct the padding in Firefox.
*/
fieldset {
padding: 0.35em 0.75em 0.625em;
}
/**
* 1. Correct the text wrapping in Edge and IE.
* 2. Correct the color inheritance from `fieldset` elements in IE.
* 3. Remove the padding so developers are not caught out when they zero out
* `fieldset` elements in all browsers.
*/
legend {
box-sizing: border-box; /* 1 */
color: inherit; /* 2 */
display: table; /* 1 */
max-width: 100%; /* 1 */
padding: 0; /* 3 */
white-space: normal; /* 1 */
}
/**
* Add the correct vertical alignment in Chrome, Firefox, and Opera.
*/
progress {
vertical-align: baseline;
}
/**
* Remove the default vertical scrollbar in IE 10+.
*/
textarea {
overflow: auto;
}
/**
* 1. Add the correct box sizing in IE 10.
* 2. Remove the padding in IE 10.
*/
[type="checkbox"],
[type="radio"] {
box-sizing: border-box; /* 1 */
padding: 0; /* 2 */
}
/**
* Correct the cursor style of increment and decrement buttons in Chrome.
*/
[type="number"]::-webkit-inner-spin-button,
[type="number"]::-webkit-outer-spin-button {
height: auto;
}
/**
* 1. Correct the odd appearance in Chrome and Safari.
* 2. Correct the outline style in Safari.
*/
[type="search"] {
-webkit-appearance: textfield; /* 1 */
outline-offset: -2px; /* 2 */
}
/**
* Remove the inner padding in Chrome and Safari on macOS.
*/
[type="search"]::-webkit-search-decoration {
-webkit-appearance: none;
}
/**
* 1. Correct the inability to style clickable types in iOS and Safari.
* 2. Change font properties to `inherit` in Safari.
*/
::-webkit-file-upload-button {
-webkit-appearance: button; /* 1 */
font: inherit; /* 2 */
}
/* Interactive
========================================================================== */
/*
* Add the correct display in Edge, IE 10+, and Firefox.
*/
details {
display: block;
}
/*
* Add the correct display in all browsers.
*/
summary {
display: list-item;
}
/* Misc
========================================================================== */
/**
* Add the correct display in IE 10+.
*/
template {
display: none;
}
/**
* Add the correct display in IE 10.
*/
[hidden] {
display: none;
}

3226
src/css/style.css Normal file

File diff suppressed because one or more lines are too long

BIN
src/favicon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.2 KiB

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