commit 0bcefa0b61827129e1d0b8b50cac45c84b742c97 Author: Auric Vente Date: Thu Aug 1 22:12:44 2024 -0600 first commit diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..e84b963 --- /dev/null +++ b/.gitignore @@ -0,0 +1,24 @@ +*/venv/* +output/* +*.pyc +__pycache__/ +.mypy_cache/ +build/ +dist/ +main.spec +run.spec +decomp/ +*.tar.gz +*.zip +*.xml +*.iml +*.idea +curls.db +.directory +captcha_key.txt +captcha_cheat.txt +bundle.js +bundle.*.js +node_modules/ +package-lock.json +export.json \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..be3f7b2 --- /dev/null +++ b/LICENSE @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + 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. + + + Copyright (C) + + 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 . + +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 +. diff --git a/README.md b/README.md new file mode 100644 index 0000000..ef0aa04 --- /dev/null +++ b/README.md @@ -0,0 +1,139 @@ +# Curls + +![](https://i.imgur.com/VjrgPIL.gif) + +(Notice in this demo how each color has their own set of curls) + +(Also notice the $ picker to switch between curls you own) + +--- + +## What is this? + +This is a text status host. + +Users claim a `curl` and get a key to be able to update it. + +For instance `https://curls.merkoba.com/funone` would return the current text of the `funone` curl. + +The response is always pure text, there is no json or anything. + +There is no history, or any other features except hosting the current text. + +To view and change a curl there's some html pages available but you are encouraged to use your own tools to view and change. + +--- + +Change one: + +``` +curl -X POST -d "curl=mycurl&key=mykey&text=mytext" https://curls.merkoba.com/change +``` + +If the change was successful it will return "ok". + +--- + +Get current status of one: + +``` +curl https://curls.merkoba.com/[curl] +``` + +--- + +Get data of one or more (json response): + +``` +curl -X POST -d "curl=somecurl&curl=othercurl" https://curls.merkoba.com/curls +``` + +--- + +## Intended Use + +How I think this can be used is by users sharing their curls to others and then they add them to a program. The program would update every added curl every 5 minutes to check for changes. So a user gets an overview of the status of many people. + +The status of the people you choose can serve as calls of action or to know about interesting activities happening in real time. + +Yes it's similar to Twitter except there's no history or other kind of privacy invading mechanisms in place. And there's no CORS restrictions, reading and changing the curl status should be as easy as possible, from within any application. + +It can also serve for software to point to pieces of dynamic text. + +--- + +## Accounts + +There are no accounts. You claim a curl once, you are given the key once. + +There are no mechanisms to recover a lost key. + +--- + +## Dashboard + +I have my own implementation of a program that uses curls. + +It is located at: `https://curls.merkoba.com/dashboard` + +The html template is found [here](https://github.com/madprops/curls/blob/main/server/templates/dashboard.html). + +The code is found [here](https://github.com/madprops/curls/tree/main/server/static/dashboard). + +### Colors + +Each color has their own set of curls. You can use them as profiles. + +### Picker + +When you make a successful change to a curl, the curl is saved to your picker list. + +So you can easily switch between them by clicking the $ button. + +--- + +## Installing + +Everything happens inside `/server` + +Create a `virtual env` and install dependencies using `requirements.txt` + +Run `init_db.sh` to create the sqlite3 database. + +Create `captcha_key.txt` and fill it with a secret key for the captcha. + +### Development + +To run a dev server use `venv/bin/python -m flask run --debug` + +To debug quickly create `captcha_cheat.txt` and fill it to use as the captcha. + +### Production + +Use `gunicorn` to run it in production. + +Set up a reverse proxy on `apache`. + +Make a `systemd` service to start gunicorn with a non-root user. + +### Bundle + +The js files in static/dashboard/js get bundled into `bundle.js` when the server starts. + +There is a `bundle.py` file that can be called directly to force a bundle. + +--- + +## Rate Limiter + +There is a rate limiter to limit all API endpoints to x requests per minute. + +This depends on `redis`. + +--- + +## Schema + +You can see the current schema [here](https://github.com/madprops/curls/blob/main/server/schema.sql). + +It's supposed to remain very simple. \ No newline at end of file diff --git a/server/app.py b/server/app.py new file mode 100644 index 0000000..220eff6 --- /dev/null +++ b/server/app.py @@ -0,0 +1,112 @@ +from __future__ import annotations + +# Standard +from typing import Any + +# Libraries +from flask import Flask, render_template, request, Response # type: ignore +from flask_cors import CORS # type: ignore +from flask_simple_captcha import CAPTCHA # type: ignore +from flask_limiter import Limiter # type: ignore +from flask_limiter.util import get_remote_address # type: ignore + +# Modules +import db as DB +import config as Config +import procs as Procs +import bundle as Bundle + + +# --- + + +app = Flask(__name__) + +# Enable all cross origin requests +CORS(app) + +DB.init_app(app) + +simple_captcha = CAPTCHA(config=Config.captcha) +app = simple_captcha.init_app(app) +rate_limit = f"{Config.rate_limit} per minute" +rate_limit_change = f"{Config.rate_limit_change} per minute" + +limiter = Limiter( + get_remote_address, + app=app, + default_limits=[rate_limit], + storage_uri="redis://localhost:6379", + strategy="fixed-window", +) + +Bundle.bundle_dashboard() + + +# --- + + +invalid = "Error: Invalid request" + + +@app.route("/", methods=["GET"]) # type: ignore +@limiter.limit(rate_limit) # type: ignore +def index() -> Any: + return render_template("index.html") + + +@app.route("/dashboard", methods=["GET"]) # type: ignore +@limiter.limit(rate_limit) # type: ignore +def dashboard() -> Any: + version = Config.manifest.get("version", "0.0.0") + return render_template("dashboard.html", version=version) + + +@app.route("/claim", methods=["POST", "GET"]) # type: ignore +@limiter.limit(rate_limit) # type: ignore +def claim() -> Any: + if request.method == "POST": + try: + message = Procs.claim_proc(request) + return render_template("message.html", message=message) + except Exception as e: + print(e) + return Response(invalid, mimetype=Config.text_mtype) + + captcha = simple_captcha.create() + return render_template("claim.html", captcha=captcha) + + +@app.route("/change", methods=["POST", "GET"]) # type: ignore +@limiter.limit(rate_limit_change) # type: ignore +def change() -> Any: + if request.method == "POST": + try: + ans = Procs.change_proc(request) + return Response(ans, mimetype=Config.text_mtype) + except Exception as e: + print(e) + return Response(invalid, mimetype=Config.text_mtype) + + return render_template("change.html") + + +@app.route("/", methods=["GET"]) # type: ignore +@limiter.limit(rate_limit) # type: ignore +def get_curl(curl) -> Any: + try: + ans = Procs.curl_proc(curl) + return Response(ans, mimetype=Config.text_mtype) + except Exception as e: + print(e) + return Response(invalid, mimetype=Config.text_mtype) + + +@app.route("/curls", methods=["POST"]) # type: ignore +@limiter.limit(rate_limit) # type: ignore +def get_curls() -> Any: + try: + return Procs.curls_proc(request) + except Exception as e: + print(e) + return Response(invalid, mimetype=Config.text_mtype) diff --git a/server/bundle.py b/server/bundle.py new file mode 100644 index 0000000..f144255 --- /dev/null +++ b/server/bundle.py @@ -0,0 +1,44 @@ +from __future__ import annotations + +# Standard +from pathlib import Path + + +def get_files(path: str, ext: str) -> list[str]: + files = Path(path).glob(f"*.{ext}") + return [str(f) for f in files] + + +def bundle_dashboard_js(what: str, first: list[str], last: list[str]) -> None: + files = get_files(f"static/dashboard/js/{what}", "js") + + def get_path(f: str) -> Path: + return Path(f"static/dashboard/js/{what}/{f}.js") + + with Path(f"static/dashboard/js/bundle.{what}.js").open("w") as f: + for file_ in first: + with get_path(file_).open("r") as js: + f.write(js.read()) + f.write("\n\n") + + for file_ in files: + file = Path(file_) + + if (file.stem not in first) and (file.stem not in last): + with file.open("r") as js: + f.write(js.read()) + f.write("\n\n") + + for file_ in last: + with get_path(file_).open("r") as js: + f.write(js.read()) + f.write("\n\n") + + +def bundle_dashboard() -> None: + bundle_dashboard_js("libs", [], []) + bundle_dashboard_js("main", ["app", "utils"], ["load"]) + + +if __name__ == "__main__": + bundle_dashboard() diff --git a/server/config.py b/server/config.py new file mode 100644 index 0000000..d361592 --- /dev/null +++ b/server/config.py @@ -0,0 +1,43 @@ +from __future__ import annotations + +# Standard +import json +import string +from pathlib import Path + + +curl_max_length = 20 +key_length = 22 +status_max_length = 500 +max_curls = 100 +rate_limit = 12 +rate_limit_change = 3 +captcha_key = "changeMe" +captcha_cheat = "" +text_mtype = "text/plain" +captcha_key_file = Path("captcha_key.txt") +captcha_cheat_file = Path("captcha_cheat.txt") +manifest_file = Path("manifest.json") +manifest = {} + +if captcha_key_file.is_file(): + with captcha_key_file.open("r") as f: + captcha_key = f.read().strip() + +if captcha_cheat_file.is_file(): + with captcha_cheat_file.open("r") as f: + captcha_cheat = f.read().strip() + +if manifest_file.is_file(): + with manifest_file.open("r") as f: + manifest = json.loads(f.read().strip()) + +captcha = { + "SECRET_CAPTCHA_KEY": captcha_key, + "CAPTCHA_LENGTH": 10, + "CAPTCHA_DIGITS": False, + "EXPIRE_SECONDS": 60, + "CAPTCHA_IMG_FORMAT": "JPEG", + "ONLY_UPPERCASE": False, + "CHARACTER_POOL": string.ascii_lowercase, +} diff --git a/server/curls.py b/server/curls.py new file mode 100644 index 0000000..bbab4d8 --- /dev/null +++ b/server/curls.py @@ -0,0 +1,189 @@ +from __future__ import annotations + +# Standard +import random +import string +import datetime +from typing import Any + +# Modules +import db as DB +import config as Config + + +def get_value(curl: str, what: str) -> Any: + dbase = DB.get_db() + cursor = dbase.cursor() + db_string = f"SELECT {what} FROM curls WHERE curl = ?" + cursor.execute(db_string, (curl,)) + return cursor.fetchone() + + +def add_curl(curl: str, key: str) -> None: + dbase = DB.get_db() + cursor = dbase.cursor() + + db_string = """ + INSERT INTO curls (created, updated, curl, key, status) + VALUES (?, ?, ?, ?, ?) + """ + + now = date_now() + cursor.execute(db_string, (now, now, curl, key, "")) + dbase.commit() + + +def make_key(curl: str) -> str: + characters = string.ascii_letters + string.digits + chars = "".join(random.choice(characters) for i in range(Config.key_length)) + start = curl[:3] + rest = len(start) + 1 + return f"{start}_{chars[rest:]}" + + +def check_key(curl: str, key: str) -> bool: + if not key: + return False + + if len(key) > Config.key_length: + return False + + result = get_value(curl, "key") + return bool(result) and (result[0] == key) + + +def change_status(curl: str, status: str) -> None: + current = get_status(curl, False) + + if current and (current == status): + return + + dbase = DB.get_db() + cursor = dbase.cursor() + + db_string = """ + UPDATE curls + SET status = ?, updated = ?, changes = changes + 1 + WHERE curl = ? + """ + + now = date_now() + cursor.execute(db_string, (status, now, curl)) + dbase.commit() + + +def curl_exists(curl: str) -> bool: + result = get_value(curl, "curl") + return bool(result) + + +def get_status(curl: str, fill: bool = True) -> str: + result = get_value(curl, "status") + + if fill: + return fill_status(result) + + if result: + return str(result[0]) + + return "" + + +def get_curl_list(curls: list[str]) -> list[dict[str, Any]]: + dbase = DB.get_db() + cursor = dbase.cursor() + + db_string = """ + SELECT created, curl, status, updated, changes + FROM curls + WHERE curl IN ({}) + """.format(",".join("?" * len(curls))) + + cursor.execute(db_string, curls) + results = cursor.fetchall() + items = [] + + for result in results: + if not result: + continue + + created = str(result[0]) or "" + curl = result[1] + status = result[2] + updated = str(result[3]) or "" + changes = result[4] or 0 + + items.append( + { + "created": created, + "curl": curl, + "status": status, + "updated": updated, + "changes": changes, + } + ) + + return items + + +def fill_status(result: Any) -> str: + if not result: + return "Not claimed yet" + + status = result[0] + + if not status: + return "Not updated yet" + + return str(status) + + +def curl_too_long() -> str: + return f"Error: Curl is too long (Max is {Config.curl_max_length} characters)" + + +def status_too_long() -> str: + return f"Error: Text is too long (Max is {Config.status_max_length} characters)" + + +def too_many_curls() -> str: + return f"Error: Too many curls (Max is {Config.max_curls})" + + +def check_curl(curl: str) -> bool: + if not curl: + return False + + if len(curl) > Config.curl_max_length: + return False + + if not curl.isalnum(): + return False + + return True + + +def check_status(status: str) -> bool: + if not status: + return False + + if len(status) > Config.status_max_length: + return False + + return True + + +def date_now() -> datetime.datetime: + return datetime.datetime.now(datetime.timezone.utc) + + +def clean_curl(curl: str) -> str: + return str(curl).strip().lower() + + +def clean_key(key: str) -> str: + return str(key).strip() + + +def clean_status(status: str) -> str: + return str(status).strip() diff --git a/server/db.py b/server/db.py new file mode 100644 index 0000000..c823098 --- /dev/null +++ b/server/db.py @@ -0,0 +1,44 @@ +# Standard +import sqlite3 +from typing import Any + +# Libraries +import click +from flask import current_app, g # type: ignore + + +DATABASE = "curls.db" + + +def get_db() -> Any: + if "db" not in g: + g.db = sqlite3.connect(DATABASE, detect_types=sqlite3.PARSE_DECLTYPES) + + g.db.row_factory = sqlite3.Row + + return g.db + + +def close_db(e: Any) -> None: + db = g.pop("db", None) + + if db is not None: + db.close() + + +@click.command("init-db") +def init_db_command() -> None: + init_db() + click.echo("Initialized the database.") + + +def init_db() -> None: + db = get_db() + + with current_app.open_resource("schema.sql") as f: + db.executescript(f.read().decode("utf8")) + + +def init_app(app: Any) -> None: + app.teardown_appcontext(close_db) + app.cli.add_command(init_db_command) diff --git a/server/eslint.config.mjs b/server/eslint.config.mjs new file mode 100644 index 0000000..89ec2e6 --- /dev/null +++ b/server/eslint.config.mjs @@ -0,0 +1,25 @@ +import globals from "globals"; +import pluginJs from "@eslint/js"; + +export default [ + pluginJs.configs.recommended, + + {languageOptions: {globals: globals.browser}}, + + { + rules: { + "semi": "off", + "no-undef": "off", + "no-unused-vars": "off", + "indent": ["error", 4], + "linebreak-style": ["error", "unix"], + "quotes": ["error", "backtick"], + "no-console": "error", + "space-before-function-paren": ["error", { + "anonymous": "always", + "named": "never", + "asyncArrow": "always" + }], + }, + } +] \ No newline at end of file diff --git a/server/fill.py b/server/fill.py new file mode 100644 index 0000000..687b29f --- /dev/null +++ b/server/fill.py @@ -0,0 +1,93 @@ +import sys +import datetime +import random +import json +import sqlite3 +from sqlite3 import Error + + +def create_connection(db_file: str) -> sqlite3.Connection | None: + conn = None + + try: + conn = sqlite3.connect(db_file) + print(sqlite3.version) + except Error as e: + print(e) + + return conn + + +def clean_db(conn: sqlite3.Connection) -> None: + sql = "DELETE FROM curls" + cur = conn.cursor() + cur.execute(sql) + conn.commit() + + +def insert_into_db(conn: sqlite3.Connection, curl: str, status: str) -> None: + sql = """ INSERT INTO curls(created, updated, curl, key, status) + VALUES(?,?,?,?,?) """ + cur = conn.cursor() + now = ( + date_now() + ) # assuming date_now() is a function that returns current date and time + cur.execute(sql, (now, now, curl, "pass", status)) + conn.commit() + + +def date_now() -> datetime.datetime: + return datetime.datetime.now(datetime.timezone.utc) + + +def get_random_items(file: str, num: int) -> list[str]: + with open(file) as f: + names = json.load(f) + return random.sample(names, num) + + +def clean_items(names: list[str]) -> list[str]: + clean = [] + + for word in names: + clean.append("".join(filter(str.isalpha, word))) + + clean = [x.lower() for x in clean] + return clean + + +if __name__ == "__main__": + num = 140 + colors = ["red", "green", "blue", "yellow", "purple", "white"] + names = get_random_items("names.json", num) + names = clean_items(names) + + obj: dict[str, list[str]] = {} + d = 20 + n1 = 0 + n2 = d + + for color in colors: + obj[color] = [] + + for name in names[n1:n2]: + obj[color].append(name) + + n1 += d + n2 += d + + with open("export.json", "w") as f: + json.dump(obj, f, indent=4) + + sents = get_random_items("sentences.json", num) + conn = create_connection("curls.db") + + if not conn: + print("Error: Could not connect to database.") + sys.exit(1) + + with conn: + clean_db(conn) + + for i, name in enumerate(names): + insert_into_db(conn, name, sents[i]) diff --git a/server/init_db.sh b/server/init_db.sh new file mode 100755 index 0000000..ec291ff --- /dev/null +++ b/server/init_db.sh @@ -0,0 +1,2 @@ +#!/usr/bin/env bash +venv/bin/python -m flask init-db \ No newline at end of file diff --git a/server/manifest.json b/server/manifest.json new file mode 100644 index 0000000..3661741 --- /dev/null +++ b/server/manifest.json @@ -0,0 +1,6 @@ +{ + "version": "23.0.0", + "title": "Curls", + "repo": "github.com/madprops/curls", + "description": "Text status hosting" +} diff --git a/server/names.json b/server/names.json new file mode 100644 index 0000000..bfd03a8 --- /dev/null +++ b/server/names.json @@ -0,0 +1,1002 @@ +[ + "Jacob", + "Michael", + "Matthew", + "Joshua", + "Christopher", + "Nicholas", + "Andrew", + "Joseph", + "Daniel", + "Tyler", + "William", + "Brandon", + "Ryan", + "John", + "Zachary", + "David", + "Anthony", + "James", + "Justin", + "Alexander", + "Jonathan", + "Christian", + "Austin", + "Dylan", + "Ethan", + "Benjamin", + "Noah", + "Samuel", + "Robert", + "Nathan", + "Cameron", + "Kevin", + "Thomas", + "Jose", + "Hunter", + "Jordan", + "Kyle", + "Caleb", + "Jason", + "Logan", + "Aaron", + "Eric", + "Brian", + "Gabriel", + "Adam", + "Jack", + "Isaiah", + "Juan", + "Luis", + "Connor", + "Charles", + "Elijah", + "Isaac", + "Steven", + "Evan", + "Jared", + "Sean", + "Timothy", + "Luke", + "Cody", + "Nathaniel", + "Alex", + "Seth", + "Mason", + "Richard", + "Carlos", + "Angel", + "Patrick", + "Devin", + "Bryan", + "Cole", + "Jackson", + "Ian", + "Garrett", + "Trevor", + "Jesus", + "Chase", + "Adrian", + "Mark", + "Blake", + "Sebastian", + "Antonio", + "Lucas", + "Jeremy", + "Gavin", + "Miguel", + "Julian", + "Dakota", + "Alejandro", + "Jesse", + "Dalton", + "Bryce", + "Tanner", + "Kenneth", + "Stephen", + "Jake", + "Victor", + "Spencer", + "Marcus", + "Paul", + "Brendan", + "Jeremiah", + "Xavier", + "Jeffrey", + "Tristan", + "Jalen", + "Jorge", + "Edward", + "Riley", + "Colton", + "Wyatt", + "Joel", + "Maxwell", + "Aidan", + "Travis", + "Shane", + "Colin", + "Dominic", + "Carson", + "Vincent", + "Derek", + "Oscar", + "Grant", + "Eduardo", + "Peter", + "Henry", + "Parker", + "Collin", + "Hayden", + "George", + "Bradley", + "Mitchell", + "Devon", + "Ricardo", + "Shawn", + "Taylor", + "Nicolas", + "Gregory", + "Francisco", + "Liam", + "Kaleb", + "Preston", + "Erik", + "Alexis", + "Owen", + "Omar", + "Diego", + "Dustin", + "Corey", + "Fernando", + "Clayton", + "Carter", + "Ivan", + "Jaden", + "Javier", + "Alec", + "Johnathan", + "Scott", + "Manuel", + "Cristian", + "Alan", + "Raymond", + "Brett", + "Andres", + "Max", + "Gage", + "Mario", + "Dawson", + "Dillon", + "Cesar", + "Wesley", + "Levi", + "Jakob", + "Chandler", + "Martin", + "Malik", + "Edgar", + "Sergio", + "Trenton", + "Josiah", + "Nolan", + "Marco", + "Peyton", + "Harrison", + "Hector", + "Micah", + "Roberto", + "Drew", + "Brady", + "Erick", + "Conner", + "Jonah", + "Casey", + "Jayden", + "Edwin", + "Emmanuel", + "Andre", + "Phillip", + "Brayden", + "Landon", + "Giovanni", + "Bailey", + "Ronald", + "Braden", + "Damian", + "Donovan", + "Ruben", + "Andy", + "Frank", + "Pedro", + "Gerardo", + "Chance", + "Abraham", + "Calvin", + "Trey", + "Cade", + "Donald", + "Derrick", + "Payton", + "Darius", + "Enrique", + "Keith", + "Raul", + "Jaylen", + "Troy", + "Jonathon", + "Cory", + "Eli", + "Marc", + "Rafael", + "Skyler", + "Trent", + "Griffin", + "Colby", + "Johnny", + "Chad", + "Armando", + "Kobe", + "Marcos", + "Caden", + "Cooper", + "Elias", + "Brenden", + "Israel", + "Avery", + "Zane", + "Dante", + "Josue", + "Zackary", + "Allen", + "Mathew", + "Dennis", + "Leonardo", + "Ashton", + "Philip", + "Julio", + "Miles", + "Damien", + "Ty", + "Gustavo", + "Drake", + "Jaime", + "Simon", + "Jerry", + "Curtis", + "Kameron", + "Lance", + "Brock", + "Bryson", + "Alberto", + "Dominick", + "Jimmy", + "Kaden", + "Douglas", + "Gary", + "Brennan", + "Zachery", + "Randy", + "Louis", + "Larry", + "Albert", + "Nickolas", + "Tony", + "Fabian", + "Keegan", + "Danny", + "Saul", + "Tucker", + "Myles", + "Damon", + "Arturo", + "Corbin", + "Deandre", + "Ricky", + "Kristopher", + "Lane", + "Pablo", + "Darren", + "Jarrett", + "Zion", + "Alfredo", + "Micheal", + "Angelo", + "Carl", + "Oliver", + "Kyler", + "Tommy", + "Walter", + "Dallas", + "Jace", + "Quinn", + "Theodore", + "Grayson", + "Lorenzo", + "Joe", + "Arthur", + "Roman", + "Bryant", + "Brent", + "Russell", + "Ramon", + "Lawrence", + "Moises", + "Aiden", + "Quentin", + "Jay", + "Tyrese", + "Tristen", + "Emanuel", + "Salvador", + "Terry", + "Morgan", + "Jeffery", + "Esteban", + "Tyson", + "Braxton", + "Marvin", + "Branden", + "Brody", + "Craig", + "Ismael", + "Rodney", + "Isiah", + "Marshall", + "Maurice", + "Ernesto", + "Emilio", + "Brendon", + "Eddie", + "Kody", + "Malachi", + "Abel", + "Keaton", + "Jon", + "Shaun", + "Skylar", + "Ezekiel", + "Nikolas", + "Santiago", + "Kendall", + "Axel", + "Camden", + "Trevon", + "Bobby", + "Conor", + "Jamal", + "Lukas", + "Malcolm", + "Zackery", + "Jayson", + "Javon", + "Roger", + "Reginald", + "Zachariah", + "Desmond", + "Dean", + "Felix", + "Johnathon", + "Quinton", + "Ali", + "Davis", + "Gerald", + "Rodrigo", + "Demetrius", + "Billy", + "Rene", + "Reece", + "Leo", + "Kelvin", + "Justice", + "Chris", + "Guillermo", + "Kevon", + "Steve", + "Frederick", + "Clay", + "Weston", + "Dorian", + "Hugo", + "Roy", + "Orlando", + "Terrance", + "Kai", + "Khalil", + "Graham", + "Noel", + "Willie", + "Nathanael", + "Terrell", + "Tyrone", + "Camron", + "Mauricio", + "Amir", + "Nelson", + "Darian", + "Jarod", + "Kade", + "Reese", + "Kristian", + "Garret", + "Rodolfo", + "Marquis", + "Dane", + "Felipe", + "Todd", + "Elian", + "Walker", + "Mateo", + "Jaylon", + "Ezra", + "Kenny", + "Bruce", + "Damion", + "Ross", + "Francis", + "Tate", + "Reid", + "Warren", + "Byron", + "Randall", + "Bennett", + "Jermaine", + "Triston", + "Harley", + "Jaquan", + "Jessie", + "Duncan", + "Franklin", + "Reed", + "Charlie", + "Blaine", + "Braeden", + "Holden", + "Ahmad", + "Melvin", + "Alvin", + "Issac", + "Moses", + "Kendrick", + "Sam", + "Sawyer", + "Solomon", + "Cedric", + "Jaylin", + "Mohammad", + "Jordon", + "Beau", + "Elliot", + "Lee", + "Darrell", + "Jarred", + "Mohamed", + "Davion", + "Wade", + "Tomas", + "Uriel", + "Jaxon", + "Maximilian", + "Deven", + "Gilberto", + "Rogelio", + "Ronnie", + "Allan", + "Julius", + "Joey", + "Brayan", + "Deshawn", + "Terrence", + "Noe", + "Alfonso", + "Ahmed", + "Tyree", + "Tyrell", + "Jerome", + "Neil", + "Devan", + "Ramiro", + "Pierce", + "Davon", + "Leon", + "Devonte", + "Jamie", + "Adan", + "Eugene", + "Stanley", + "Wayne", + "Marlon", + "Leonard", + "Quincy", + "Will", + "Jonas", + "Harry", + "Alvaro", + "Ernest", + "Addison", + "Ray", + "Alonzo", + "Jadon", + "Mohammed", + "Keyshawn", + "Rolando", + "Tristin", + "Donte", + "Leonel", + "Dominique", + "Wilson", + "Gilbert", + "Kieran", + "Coby", + "Dangelo", + "Colten", + "Keenan", + "Koby", + "Jarrod", + "Toby", + "Dale", + "Dwayne", + "Harold", + "Elliott", + "Osvaldo", + "Cyrus", + "Kolby", + "Sage", + "Coleman", + "Declan", + "Adolfo", + "Rudy", + "Ariel", + "Brennen", + "Darryl", + "Trace", + "Shamar", + "Efrain", + "Orion", + "Keshawn", + "Darien", + "Ulises", + "Braydon", + "Ben", + "Vicente", + "Nasir", + "Dayton", + "Joaquin", + "Karl", + "Dandre", + "Isaias", + "Cullen", + "Rylan", + "Sterling", + "Quintin", + "Stefan", + "Brice", + "Lewis", + "Gunnar", + "Humberto", + "Alfred", + "Nigel", + "Asher", + "Agustin", + "Daquan", + "Easton", + "Salvatore", + "Jaron", + "Ralph", + "Nathanial", + "Everett", + "Tobias", + "Hudson", + "Marquise", + "Antoine", + "Glenn", + "Jasper", + "Elvis", + "Kane", + "Sidney", + "Aron", + "Ezequiel", + "Tylor", + "Dashawn", + "Devyn", + "Mike", + "Silas", + "Jaiden", + "Jayce", + "Deonte", + "Romeo", + "Deon", + "Cristopher", + "Freddy", + "Kurt", + "Kolton", + "River", + "August", + "Clarence", + "Roderick", + "Derick", + "Jamar", + "Muhammad", + "Raphael", + "Kareem", + "Rohan", + "Demarcus", + "Sheldon", + "Cayden", + "Markus", + "Luca", + "Tre", + "Jean", + "Titus", + "Jamison", + "Rory", + "Brad", + "Clinton", + "Emiliano", + "Jaylan", + "Jevon", + "Julien", + "Lamar", + "Alonso", + "Cordell", + "Gordon", + "Ignacio", + "Cruz", + "Jett", + "Keon", + "Baby", + "Rashad", + "Tariq", + "Armani", + "Milton", + "Deangelo", + "Geoffrey", + "Elisha", + "Moshe", + "Asa", + "Bernard", + "Bret", + "Darion", + "Darnell", + "Izaiah", + "Irvin", + "Jairo", + "Norman", + "Howard", + "Aldo", + "Zechariah", + "Ayden", + "Garrison", + "Stuart", + "Travon", + "Kellen", + "Shemar", + "Dillan", + "Junior", + "Darrius", + "Rhett", + "Barry", + "Kamron", + "Jude", + "Perry", + "Rigoberto", + "Amari", + "Jovan", + "Octavio", + "Hassan", + "Kole", + "Misael", + "Jaren", + "Latrell", + "Roland", + "Quinten", + "German", + "Ibrahim", + "Justus", + "Gonzalo", + "Nehemiah", + "Forrest", + "Leroy", + "Mackenzie", + "Talon", + "Anton", + "Chaz", + "Guadalupe", + "Winston", + "Antwan", + "Austen", + "Brooks", + "Conrad", + "Greyson", + "Dion", + "Lincoln", + "Earl", + "Jaydon", + "Landen", + "Gunner", + "Brenton", + "Jefferson", + "Fredrick", + "Kurtis", + "Maximillian", + "Stephan", + "Stone", + "Shannon", + "Shayne", + "Stephon", + "Karson", + "Nestor", + "Tristian", + "Frankie", + "Gianni", + "Keagan", + "Dimitri", + "Kory", + "Zakary", + "Daryl", + "Donavan", + "Draven", + "Jameson", + "Clifton", + "Emmett", + "Cortez", + "Destin", + "Jamari", + "Dallin", + "Estevan", + "Grady", + "Davin", + "Santos", + "Marcel", + "Carlton", + "Dylon", + "Mitchel", + "Clifford", + "Syed", + "Dexter", + "Adonis", + "Keyon", + "Reynaldo", + "Devante", + "Arnold", + "Clark", + "Kasey", + "Sammy", + "Thaddeus", + "Glen", + "Jarvis", + "Nick", + "Ulysses", + "Garett", + "Infant", + "Keanu", + "Kenyon", + "Dwight", + "Kent", + "Denzel", + "Houston", + "Lamont", + "Reuben", + "Layne", + "Darin", + "Jorden", + "Anderson", + "Kayden", + "Khalid", + "Antony", + "Deondre", + "Ellis", + "Marquez", + "Ari", + "Cornelius", + "Austyn", + "Brycen", + "Abram", + "Remington", + "Braedon", + "Hamza", + "Ryder", + "Zaire", + "Kelly", + "Terence", + "Guy", + "Jamel", + "Porter", + "Tevin", + "Alexandro", + "Dario", + "Jordy", + "Trever", + "Jackie", + "Judah", + "Keven", + "Raymundo", + "Cristobal", + "Josef", + "Paris", + "Colt", + "Giancarlo", + "Rahul", + "Savion", + "Vernon", + "Deshaun", + "Josh", + "Korey", + "Gerard", + "Jacoby", + "Lonnie", + "Reilly", + "Seamus", + "Don", + "Giovanny", + "Jamil", + "Kristofer", + "Samir", + "Benny", + "Dominik", + "Finn", + "Jan", + "Kaiden", + "Cale", + "Irving", + "Jaxson", + "Marcelo", + "Nico", + "Rashawn", + "Aubrey", + "Gaven", + "Jabari", + "Kirk", + "Sincere", + "Elmer", + "Heath", + "Maximus", + "Mikel", + "Davonte", + "Justyn", + "Kadin", + "Alden", + "Kelton", + "Brandan", + "Courtney", + "Duane", + "Camren", + "Dewayne", + "Maverick", + "Darrin", + "Darrion", + "Nikhil", + "Sonny", + "Abdullah", + "Chaim", + "Nathen", + "Xzavier", + "Bronson", + "Aden", + "Efren", + "Gideon", + "Jovani", + "Phoenix", + "Reagan", + "Blaze", + "Luciano", + "Royce", + "Tyrek", + "Tyshawn", + "Deontae", + "Fidel", + "Gaige", + "Neal", + "Ronaldo", + "Matteo", + "Prince", + "Rickey", + "Deion", + "Denver", + "Benito", + "London", + "Samson", + "Bernardo", + "Raven", + "Simeon", + "Turner", + "Carlo", + "Gino", + "Johan", + "Rocky", + "Ryley", + "Amos", + "Domenic", + "Hugh", + "Trystan", + "Emerson", + "Joan", + "Trevion", + "Heriberto", + "Marques", + "Raheem", + "Tyreek", + "Vaughn", + "Clint", + "Nash", + "Mariano", + "Myron", + "Ladarius", + "Lloyd", + "Omari", + "Pierre", + "Keshaun", + "Rick", + "Xander", + "Eliseo", + "Jeff", + "Bradly", + "Dan", + "Freddie", + "Kavon", + "Mekhi", + "Sabastian", + "Shea", + "Alessandro", + "Johnnie", + "Adrien", + "Blaise", + "Harvey", + "Isai", + "Kian", + "Maximiliano", + "Paxton", + "Rasheed", + "Brodie", + "Donnie", + "Isidro", + "Jaeden", + "Javion", + "Jimmie", + "Kennedy", + "Tyrique", + "Valentin", + "Andreas", + "Augustus", + "Jalon", + "Jamir", + "Korbin", + "Lawson", + "Maxim", + "Fred", + "Herbert", + "Bruno", + "Donavon", + "Javonte", + "Ean", + "Kamren", + "Rowan", + "Alek", + "Brandyn", + "Demarco", + "Hernan", + "Alexzander", + "Bo", + "Branson", + "Brennon", + "Genaro", + "Jamarcus", + "Aric", + "Barrett", + "Rey", + "Braiden", + "Brant", + "Dontae", + "Jovany", + "Kale", + "Nicklaus", + "Zander", + "Dillion", + "Donnell", + "Kylan", + "Treyvon", + "Vincenzo", + "Dayne", + "Francesco", + "Isaak" +] \ No newline at end of file diff --git a/server/package.json b/server/package.json new file mode 100644 index 0000000..74f5a43 --- /dev/null +++ b/server/package.json @@ -0,0 +1,16 @@ +{ + "name": "Dashboard", + "version": "1.0.0", + "description": "Curls Dashboard", + "main": "eslint.config.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "author": "", + "license": "AGPL-3.0-only", + "devDependencies": { + "@eslint/js": "^9.4.0", + "eslint": "^9.4.0", + "globals": "^15.4.0" + } + } \ No newline at end of file diff --git a/server/procs.py b/server/procs.py new file mode 100644 index 0000000..4e69923 --- /dev/null +++ b/server/procs.py @@ -0,0 +1,93 @@ +from __future__ import annotations + +# Standard +from flask import jsonify, Response # type: ignore +from typing import Any + +# Modules +import app as App +import config as Config +import curls as Curls + + +invalid_curl = "Error: Invalid curl" +invalid_key = "Error: Invalid key" +invalid_status = "Error: Invalid status" + + +def claim_proc(request: Any) -> str: + c_hash = request.form.get("captcha-hash", "") + c_text = request.form.get("captcha-text", "") + curl = Curls.clean_curl(request.form.get("curl", "")) + + check_catpcha = True + + if Config.captcha_cheat and (c_text == Config.captcha_cheat): + check_catpcha = False + + if check_catpcha: + if not App.simple_captcha.verify(c_text, c_hash): + return "Error: Failed captcha" + + if not Curls.check_curl(curl): + return invalid_curl + + if Curls.curl_exists(curl): + return "Error: Curl already exists" + + key = Curls.make_key(curl) + Curls.add_curl(curl, key) + + lines = [ + f"Your curl is: {curl}", + f"Your key is: {key}", + "The key is secret and shouldn't be shared.", + "Save the key somewhere so it doesn't get lost.", + "There is no way to recover a lost key.", + ] + + return "
".join(lines) + + +def change_proc(request: Any) -> str: + curl = Curls.clean_curl(request.form.get("curl", "")) + key = Curls.clean_key(request.form.get("key", "")) + status = Curls.clean_status(request.form.get("status", "")) + + if (not curl) or (not key) or (not status): + return "Error: Empty fields" + + if not Curls.check_curl(curl): + return invalid_curl + + if not Curls.check_status(status): + return invalid_status + + if not Curls.check_key(curl, key): + return invalid_key + + Curls.change_status(curl, status) + return "ok" + + +def curl_proc(curl: str) -> str: + if not Curls.check_curl(curl): + return invalid_curl + + return Curls.get_status(curl) + + +def curls_proc(request: Any) -> Any: + curls = request.form.getlist("curl") + + if len(curls) > Config.max_curls: + ans = Curls.too_many_curls() + return Response(ans, mimetype=Config.text_mtype) + + for curl in curls: + if not Curls.check_curl(curl): + ans = invalid_curl + return Response(ans, mimetype=Config.text_mtype) + + results = Curls.get_curl_list(curls) + return jsonify(results) diff --git a/server/requirements.txt b/server/requirements.txt new file mode 100644 index 0000000..33575e3 --- /dev/null +++ b/server/requirements.txt @@ -0,0 +1,6 @@ +Flask == 3.0.3 +Flask-Cors == 4.0.1 +Flask-Limiter == 3.7.0 +flask-simple-captcha == 5.5.5 +gunicorn == 22.0.0 +redis == 5.0.6 \ No newline at end of file diff --git a/server/ruff.toml b/server/ruff.toml new file mode 100644 index 0000000..39d4ce0 --- /dev/null +++ b/server/ruff.toml @@ -0,0 +1,46 @@ +[lint] + +select = [ + "T", + "Q", + "W", + "B", + "N", + "F", + "FA", + "RET", + "PTH", + "ERA", + "PLW", + "PERF", + "RUF", + "FLY", + "PT", + "PYI", + "PIE", + "ICN", + "UP", + "TRY", + "C4", + "E401", + "E713", + "E721", + "S101", + "S113", + "SIM103", + "SIM114", + "SIM118", + "SIM210", + "PLR5501", + "PLR1711", +] + +ignore = [ + "T201", + "N812", +] + +exclude = [ + "pyperclip.py", + "tests.py", +] \ No newline at end of file diff --git a/server/schema.sql b/server/schema.sql new file mode 100644 index 0000000..d509410 --- /dev/null +++ b/server/schema.sql @@ -0,0 +1,24 @@ +DROP TABLE IF EXISTS curls; + +CREATE TABLE curls ( + -- Internal ID of the curl + id INTEGER PRIMARY KEY AUTOINCREMENT, + + -- The date when the curl was created + created TIMESTAMP NOT NULL, + + -- The date when the curl was last changed + updated TIMESTAMP NOT NULL, + + -- The public name of the curl + curl TEXT NOT NULL UNIQUE, + + -- The secret key of the curl + key TEXT NOT NULL, + + -- The current text of the curl + status TEXT NOT NULL, + + -- The total number of changes made + changes INTEGER NOT NULL DEFAULT 0 +); \ No newline at end of file diff --git a/server/sentences.json b/server/sentences.json new file mode 100644 index 0000000..7b14025 --- /dev/null +++ b/server/sentences.json @@ -0,0 +1,156 @@ +[ + "All your base are belong to us", + "It's not just a game, it's a life", + "I'm not bad. I'm just drawn that way", + "The cake is a lie!", + "It does so with all deliberate speed", + "All gurls are the same", + "You shall not pass... into this cave, that is", + "I am the one who knocks..", + "Why so serious?", + "Get over here!", + "Carry the One", + "You are not prepared", + "I am Error", + "The path of righteousness will be yours to choose..", + "It's over, man. It's all over", + "Are you ready for this?", + "Life is like a game, full of bugs", + "The greatest trick the Devil ever pulled was convincing the world he didn't exist", + "I'd rather be playing D&D", + "You are cordially invited to visit... your own grave", + "Gotta catch 'em all!", + "Time waits for no man, not even a hero", + "I'm just a simple game developer trying to make a difference..", + "It doesn't matter how many lives you have left, it matters how well you play them", + "This is the end... and this is the beginning", + "The truth is not in here", + "I'm a little tea pot short and stout..", + "When you're fast, be faster. When you're clever, be more clever", + "You will never be able to find peace", + "We're all just pawns in a game... and we don't even know the rules!", + "Do you have what it takes to save the world?", + "I'm not sure I want to go, but I have to", + "It's only a game", + "I'm a hero, and you're just a pawn!", + "The future is not set in stone, it's a puzzle that needs to be solved", + "You know what I like about this game? It's a game..", + "It doesn't matter if you're a man or a woman... it matters how well you play the game", + "You are not worthy!", + "It's time to make things right, and take back what's yours!", + "You're not going anywhere", + "Life is a series of choices... choose wisely", + "I'm not afraid of death; I just don't want to die yet", + "In a world where time has no meaning, what's the point?", + "You know the drill... you gotta be prepared for anything!", + "I'm not sure I believe in fate... but I do believe in my abilities", + "It's over, it's finally over... or is it?", + "You're a warrior, a hero... but you're also a pawn", + "I don't want to be a hero... I just want to live my life", + "The game's not over yet!", + "I'm the only one who can save this world..", + "You're too slow, you're too weak, and you're no match for me!", + "Life is but a game... and I am the player", + "It's not about winning or losing, it's about playing the game", + "You know what they say... 'all's fair in love and war'..", + "I'm a hero, but I'm also a villain", + "It's time to put an end to this game", + "You're not alone... you have me", + "Life is full of choices... choose wisely, and always remember the consequences", + "I'm not a hero... I'm just a man who's trying to make a difference", + "You're going down, pal!", + "It's time for me to take my leave... but the game is far from over", + "I'm not sure what the future holds... but I know it won't be easy", + "The game is afoot!", + "It's time to put an end to this war... and bring peace to the land", + "You're not going anywhere, at least not yet..", + "Life is but a dream... or is it?", + "I'm not sure what the future holds... but I know I'll face it head-on", + "You're not alone... you have me, and together we can make a difference!", + "It's time to take back what's rightfully yours..", + "I'm a hero, but I'm also a villain... and sometimes it's hard to tell the difference", + "You're not going anywhere... at least not yet..", + "Life is full of choices... choose wisely, and always remember the consequences", + "I'm not sure what the future holds... but I know it won't be easy", + "The game is afoot!", + "It's time to put an end to this war... and bring peace to the land", + "You're not going anywhere, at least not yet..", + "Life is but a dream... or is it?", + "I'm not sure what the future holds... but I know I'll face it head-on", + "I'll be back", + "You had me at 'hello'", + "I see dead people", + "Fasten your seatbelts. It's going to be a bumpy night", + "You're gonna need a bigger boat", + "We're gonna make him an offer he can't refuse", + "All right, Mr. DeMille, I'm ready for my close-up", + "Nobody puts Baby in the corner!", + "You talking to me?", + "It's not the years, honey. It's the mileage", + "I am serious... and don't call me Shirley", + "Fat guy in a little coat!", + "Nobody moves. Nobody talks. Nobody breathes. Just listen", + "We're on a mission from God", + "You had my curiosity, but not my interest", + "May the Force be with you", + "Show me the money!", + "You keep using that word. I do not think it means what you think it means", + "I'll get you, and your little dog too!", + "I'm gonna make him an offer he can't refuse. And if he doesn't accept it, there's going to be a war", + "It's alive! It's alive!", + "You're only given a little spark of madness. You mustn't lose it", + "E.T. phone home", + "I'm the king of the world!", + "Say hello to my little friend!", + "Do you feel lucky, punk? Do you?", + "Fasten your seatbelts. It's going to be a bumpy ride", + "Nobody knows anything", + "It's only after we've lost everything that we're free to do anything", + "I'm not bad. I'm just drawn that way", + "What you see before me is the real thing", + "You don't know what it means, do you?", + "I find your lack of faith disturbing", + "Hasta la vista, baby!", + "Get to the chopper!", + "You're gonna need a bigger map", + "I'll never let go. I'll never let go", + "That's not my nose! That's my face!", + "Life moves pretty fast. If you don't stop and look around once in a while, you could miss it", + "You had me at 'hello'", + "It's not the size of the dog in the fight, it's the size of the fight in the dog", + "I am serious... and don't call me Shirley", + "Fat guy in a little coat!", + "Nobody puts Baby in the corner!", + "You talking to me?", + "May the Force be with you", + "I'll never let go. I'll never let go", + "It's only after we've lost everything that we're free to do anything", + "All right, Mr. DeMille, I'm ready for my close-up", + "We're on a mission from God", + "Nobody knows anything", + "Get to the chopper!", + "Do you feel lucky, punk? Do you?", + "Fasten your seatbelts. It's going to be a bumpy ride", + "That's not my nose! That's my face!", + "It's alive! It's alive!", + "Say hello to my little friend!", + "What you see before me is the real thing", + "I'm the king of the world!", + "E.T. phone home", + "Hasta la vista, baby!", + "You're only given a little spark of madness. You mustn't lose it", + "It's not the years, honey. It's the mileage", + "Show me the money!", + "I find your lack of faith disturbing", + "We're gonna make him an offer he can't refuse", + "Nobody moves. Nobody talks. Nobody breathes. Just listen", + "Do you know what I am?", + "You're gonna need a bigger boat", + "Fasten your seatbelts. It's going to be a bumpy night", + "May the Force be with you", + "I'll get you, and your little dog too!", + "You're only given a little spark of madness. You mustn't lose it", + "Get off my lawn!", + "Nobody puts Baby in the corner!", + "It's not the size of the dog in the fight, it's the size of the fight in the dog." +] \ No newline at end of file diff --git a/server/static/dashboard/css/style.css b/server/static/dashboard/css/style.css new file mode 100644 index 0000000..576cab2 --- /dev/null +++ b/server/static/dashboard/css/style.css @@ -0,0 +1,429 @@ +:root { + --background: rgb(12, 12, 12); + --vertical_padding: 0.74rem; + --horizontal_padding: 0.66rem; + --alt_background_color: rgb(18, 18, 18); +} + +body, +html +{ + margin: 0; + padding: 0; + width: 100%; + height: 100%; + font-family: var(--font); + background-color: var(--background); + color: var(--color); + font-size: 18px; +} + +#main { + display: flex; + flex-direction: column; + gap: 0.8rem; + width: 100vw; + height: 100vh; + padding-left: var(--horizontal_padding); + padding-right: var(--horizontal_padding); + padding-top: var(--vertical_padding); + box-sizing: border-box; +} + +#container_outer { + display: flex; + flex-direction: column; + width: 100%; + height: 100%; + overflow-x: hidden; + overflow-y: auto; +} + +#container { + display: table; + border-collapse: collapse; + table-layout: fixed; + width: 100%; + box-sizing: border-box; + outline: none; +} + +#infobar { + cursor: default; + user-select: none; + display: flex; + flex-direction: row; + align-items: center; + justify-content: center; + gap: 1rem; +} + +#infobar_curls, +#infobar_date +{ + cursor: pointer; +} + +.infobar_separator { + opacity: 0.5; +} + +.item { + display: table-row; + border: var(--border); + cursor: default; +} + +.item_icon, +.item_curl, +.item_status, +.item_updated +{ + display: table-cell; + padding-top: 0.8rem; + padding-bottom: 0.8rem; + vertical-align: middle; +} + +.item_icon { + width: 2.5rem; + justify-content: center; + cursor: pointer; + text-align: left; +} + +.item_icon_canvas { + display: flex; + width: 100%; + height: auto; + text-align: left; + align-items: center; + justify-content: center; +} + +.item_icon:hover .item_icon_canvas { + filter: brightness(1.5); +} + +.item_curl { + width: 150px; + max-width: 150px; + color: var(--color); + text-align: left; + white-space: nowrap; + overflow: hidden; +} + +.item_status { + text-align: left; + padding-right: 0.8rem; + padding-left: 0.8rem; + word-break: break-word; + white-space: pre-wrap; +} + +.item_status.nowrap { + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} + +.item_updated { + width: 225px; + max-width: 225px; + color: var(--color); + white-space: nowrap; + text-align: right; + padding-right: 0.5rem; +} + +.item:hover { + background-color: var(--color_alpha_0); +} + +.item.selected { + background-color: var(--color_alpha_1); +} + +/* */ + +#controls { + display: flex; + flex-direction: row; + margin-bottom: 0.5rem; + row-gap: 0.8rem; + column-gap: 1.2rem; + flex-wrap: wrap; +} + +.control_bar +{ + display: flex; + flex-direction: row; + align-items: center; + gap: 1.2rem; +} + +.control_section { + display: flex; + flex-direction: row; + gap: 0.66rem; + align-items: center; + justify-content: center; + border: 1px solid var(--color_alpha_2); + padding: 0.5rem; +} + +a:visited, +a:link, +a:hover { + color: var(--color); +} + +.pointer { + cursor: pointer; + user-select: none; +} + +input[type="text"], +input[type="password"] +{ + background-color: var(--background); + color: var(--color); + border: 1px solid var(--color_alpha_2); + padding: 0.09rem; + padding-left: 0.25rem; + outline: none; + width: 8rem; + font-size: 1rem; + font: var(--font); +} + +.button { + background-color: var(--background); + color: var(--color); + border: 1px solid var(--color_alpha_2); + cursor: pointer; + outline: none; + font-size: 1rem; + padding: 0.05rem; + padding-left: 0.25rem; + padding-right: 0.25rem; + user-select: none; + white-space: nowrap; + min-width: 1rem; + display: flex; + align-items: center; + justify-content: center; +} + +.button:hover { + background-color: var(--color); + color: var(--background); +} + +.hidden { + display: none !important; +} + +@keyframes blink { + 0% { + opacity: 1; + } + + 50% { + opacity: 0; + } + + 100% { + opacity: 1; + } +} + +.blink { + animation: blink 500ms infinite; +} + +@keyframes colorchange { + 0% { + border-color: rgb(255, 102, 102); + } + + 25% { + border-color: rgb(125, 255, 125); + } + + 50% { + border-color: rgb(157, 157, 255); + } + + 100% { + border-color: white; + } +} + +.button.active { + animation: colorchange 1s infinite; + border-radius: 8px; +} + +.glow:hover { + text-shadow: 0 0 10px var(--color), 0 0 20px var(--color), 0 0 30px var(--color), 0 0 40px var(--color), 0 0 50px var(--color), 0 0 60px var(--color); +} + +.glow_white:hover { + text-shadow: 0 0 10px white, 0 0 20px white, 0 0 30px white, 0 0 40px white, 0 0 50px white, 0 0 60px white; +} + +.glow { + cursor: pointer; +} + +.glow_white { + cursor: pointer; +} + +.noselect { + user-select: none; +} + +#claim { + text-align: center; +} + +#footer { + display: flex; + flex-direction: row; + align-items: center; + justify-content: flex-start; + border-top: 1px solid var(--color_alpha_2); + margin-top: 0.35rem; + padding-top: 0.5rem; + padding-bottom: var(--vertical_padding); + gap: 1.25rem; +} + +.footer_item { + display: flex; + flex-direction: row; + gap: 0.5rem; + align-items: center; + justify-content: center; + user-select: none; +} + +#version { + margin-left: auto; +} + +.disabled { + pointer-events: none; + opacity: 0.6; +} + +.modal_message { + max-width: 30rem; + white-space: pre-wrap; + cursor: auto; +} + +.modal_button { + display: flex; + align-items: center; + justify-content: center; + border: 1px solid var(--color_alpha_2); + padding-left: 0.4rem; + padding-right: 0.4rem; + padding-top: 0.05rem; + padding-bottom: 0.05rem; + cursor: pointer; + user-select: none; + outline: none; + white-space: nowrap; +} + +.modal_button:hover { + border: 1px solid var(--color); +} + +.modal_items { + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + gap: 1rem; +} + +#alert_buttons { + display: flex; + flex-direction: row; + align-items: center; + justify-content: center; + gap: 1rem; +} + +#alert_message_container { + max-height: 14rem; + overflow-x: hidden; + overflow-y: auto; +} + +#prompt_input { + width: 14rem; + padding: 0.2rem; + text-align: center; +} + +#needcontext-main { + background-color: rgba(0, 0, 0, 0.44) !important; +} + +#needcontext-container { + background-color: var(--alt_background_color) !important; + border: 2px solid var(--color_alpha_2) !important; + color: var(--color) !important; +} + +.needcontext-text { + max-width: 300px !important; + white-space: wrap !important; +} + +.needcontext-item-selected { + background-color: var(--color_alpha_1) !important; +} + +.needcontext-text { + font-family: var(--font) !important; +} + +.Msg-window { + color: var(--color) !important; + background-color: var(--alt_background_color) !important; + border: 2px solid var(--color_alpha_2) !important; +} + +.Msg-titlebar { + color: var(--color) !important; + background-color: rgb(42, 42, 42) !important; + font-family: var(--font) !important; +} + +.Msg-progressbar { + background-color: var(--color_alpha_2) !important; +} + +.Msg-titlebar { + padding-top: 0.24rem !important; + padding-bottom: 0.24rem !important; + padding-left: 0.8rem !important; + padding-right: 0.8rem !important; +} + +.Msg-window-inner-x:hover { + background-color: var(--color_alpha_1) !important; +} + +.Msg-content-modal { + padding: 0.8rem !important; +} \ No newline at end of file diff --git a/server/static/dashboard/js/libs/dateformat.js b/server/static/dashboard/js/libs/dateformat.js new file mode 100644 index 0000000..8de6b26 --- /dev/null +++ b/server/static/dashboard/js/libs/dateformat.js @@ -0,0 +1,125 @@ +/* +* Date Format 1.2.3 +* (c) 2007-2009 Steven Levithan +* MIT license +* +* Includes enhancements by Scott Trenda +* and Kris Kowal +* +* Accepts a date, a mask, or a date and a mask. +* Returns a formatted version of the given date. +* The date defaults to the current date/time. +* The mask defaults to dateFormat.masks.default. +*/ + +var dateFormat = function () { + var token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g, + timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g, + timezoneClip = /[^-+\dA-Z]/g, + pad = function (val, len) { + val = String(val); + len = len || 2; + while (val.length < len) val = "0" + val; + return val; + }; + + // Regexes and supporting functions are cached through closure + return function (date, mask, utc) { + var dF = dateFormat; + + // You can't provide utc if you skip other args (use the "UTC:" mask prefix) + if (arguments.length == 1 && Object.prototype.toString.call(date) == "[object String]" && !/\d/.test(date)) { + mask = date; + date = undefined; + } + + // Passing date through Date applies Date.parse, if necessary + date = date ? new Date(date) : new Date; + if (isNaN(date)) throw SyntaxError("invalid date"); + + mask = String(dF.masks[mask] || mask || dF.masks["default"]); + + // Allow setting the utc argument via the mask + if (mask.slice(0, 4) == "UTC:") { + mask = mask.slice(4); + utc = true; + } + + var _ = utc ? "getUTC" : "get", + d = date[_ + "Date"](), + D = date[_ + "Day"](), + m = date[_ + "Month"](), + y = date[_ + "FullYear"](), + H = date[_ + "Hours"](), + M = date[_ + "Minutes"](), + s = date[_ + "Seconds"](), + L = date[_ + "Milliseconds"](), + o = utc ? 0 : date.getTimezoneOffset(), + flags = { + d: d, + dd: pad(d), + ddd: dF.i18n.dayNames[D], + dddd: dF.i18n.dayNames[D + 7], + m: m + 1, + mm: pad(m + 1), + mmm: dF.i18n.monthNames[m], + mmmm: dF.i18n.monthNames[m + 12], + yy: String(y).slice(2), + yyyy: y, + h: H % 12 || 12, + hh: pad(H % 12 || 12), + H: H, + HH: pad(H), + M: M, + MM: pad(M), + s: s, + ss: pad(s), + l: pad(L, 3), + L: pad(L > 99 ? Math.round(L / 10) : L), + t: H < 12 ? "a" : "p", + tt: H < 12 ? "am" : "pm", + T: H < 12 ? "A" : "P", + TT: H < 12 ? "AM" : "PM", + Z: utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""), + o: (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4), + S: ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10] + }; + + return mask.replace(token, function ($0) { + return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1); + }); + }; +} (); + +// Some common format strings +dateFormat.masks = { + "default": "ddd mmm dd yyyy HH:MM:ss", + shortDate: "m/d/yy", + mediumDate: "mmm d, yyyy", + longDate: "mmmm d, yyyy", + fullDate: "dddd, mmmm d, yyyy", + shortTime: "h:MM TT", + mediumTime: "h:MM:ss TT", + longTime: "h:MM:ss TT Z", + isoDate: "yyyy-mm-dd", + isoTime: "HH:MM:ss", + isoDateTime: "yyyy-mm-dd'T'HH:MM:ss", + isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'" +}; + +// Internationalization strings +dateFormat.i18n = { + dayNames: [ + "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", + "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" + ], + monthNames: [ + "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", + "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" + ] +}; + +// For convenience... +Date.prototype.format = function (mask, utc) { + return dateFormat(this, mask, utc); +}; diff --git a/server/static/dashboard/js/libs/dom.js b/server/static/dashboard/js/libs/dom.js new file mode 100644 index 0000000..31c815e --- /dev/null +++ b/server/static/dashboard/js/libs/dom.js @@ -0,0 +1,143 @@ +// DOM v1.0.0 +const DOM = {} +DOM.dataset_obj = {} +DOM.dataset_id = 0 + +// Select a single element +DOM.el = (query, root = document) => { + return root.querySelector(query) +} + +// Select an array of elements +DOM.els = (query, root = document) => { + return Array.from(root.querySelectorAll(query)) +} + +// Select a single element or self +DOM.el_or_self = (query, root = document) => { + let el = root.querySelector(query) + + if (!el) { + if (root.classList.contains(query.replace(`.`, ``))) { + el = root + } + } + + return el +} + +// Select an array of elements or self +DOM.els_or_self = (query, root = document) => { + let els = Array.from(root.querySelectorAll(query)) + + if (els.length === 0) { + if (root.classList.contains(query.replace(`.`, ``))) { + els = [root] + } + } + + return els +} + +// Clone element +DOM.clone = (el) => { + return el.cloneNode(true) +} + +// Clone element children +DOM.clone_children = (query) => { + let items = [] + let children = Array.from(DOM.el(query).children) + + for (let c of children) { + items.push(DOM.clone(c)) + } + + return items +} + +// Data set manager +DOM.dataset = (el, value, setvalue) => { + if (!el) { + return + } + + let id = el.dataset.dataset_id + + if (!id) { + id = DOM.dataset_id + DOM.dataset_id += 1 + el.dataset.dataset_id = id + DOM.dataset_obj[id] = {} + } + + if (setvalue !== undefined) { + DOM.dataset_obj[id][value] = setvalue + } + else { + return DOM.dataset_obj[id][value] + } +} + +// Create an html element +DOM.create = (type, classes = ``, id = ``) => { + let el = document.createElement(type) + + if (classes) { + let classlist = classes.split(` `).filter(x => x != ``) + + for (let cls of classlist) { + el.classList.add(cls) + } + } + + if (id) { + el.id = id + } + + return el +} + +// Add an event listener +DOM.ev = (element, event, callback, extra) => { + element.addEventListener(event, callback, extra) +} + +// Add multiple event listeners +DOM.evs = (element, events, callback, extra) => { + for (let event of events) { + element.addEventListener(event, callback, extra) + } +} + +// Like jQuery's nextAll +DOM.next_all = function* (e, selector) { + while (e = e.nextElementSibling) { + if (e.matches(selector)) { + yield e; + } + } +} + +// Get item index +DOM.index = (el) => { + return Array.from(el.parentNode.children).indexOf(el) +} + +// Show an element +DOM.show = (item) => { + if (typeof item === `string`) { + item = DOM.el(item) + } + + item.classList.remove(`hidden`) +} + +// Hide an element +DOM.hide = (item) => { + if (typeof item === `string`) { + item = DOM.el(item) + } + + item.classList.add(`hidden`) +} \ No newline at end of file diff --git a/server/static/dashboard/js/libs/jdenticon.js b/server/static/dashboard/js/libs/jdenticon.js new file mode 100644 index 0000000..7aa850e --- /dev/null +++ b/server/static/dashboard/js/libs/jdenticon.js @@ -0,0 +1,1507 @@ +/** + * Jdenticon 3.3.0 + * http://jdenticon.com + * + * Built: 2024-05-10T09:48:41.921Z + * + * MIT License + * + * Copyright (c) 2014-2024 Daniel Mester Pirttijärvi + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +(function (umdGlobal, factory) { + var jdenticon = factory(umdGlobal); + + // Node.js + if (typeof module !== "undefined" && "exports" in module) { + module["exports"] = jdenticon; + } + // RequireJS + else if (typeof define === "function" && define["amd"]) { + define([], function () { return jdenticon; }); + } + // No module loader + else { + umdGlobal["jdenticon"] = jdenticon; + } +})(typeof self !== "undefined" ? self : this, function (umdGlobal) { +'use strict'; + +/** + * Parses a substring of the hash as a number. + * @param {number} startPosition + * @param {number=} octets + */ +function parseHex(hash, startPosition, octets) { + return parseInt(hash.substr(startPosition, octets), 16); +} + +function decToHex(v) { + v |= 0; // Ensure integer value + return v < 0 ? "00" : + v < 16 ? "0" + v.toString(16) : + v < 256 ? v.toString(16) : + "ff"; +} + +function hueToRgb(m1, m2, h) { + h = h < 0 ? h + 6 : h > 6 ? h - 6 : h; + return decToHex(255 * ( + h < 1 ? m1 + (m2 - m1) * h : + h < 3 ? m2 : + h < 4 ? m1 + (m2 - m1) * (4 - h) : + m1)); +} + +/** + * @param {string} color Color value to parse. Currently hexadecimal strings on the format #rgb[a] and #rrggbb[aa] are supported. + * @returns {string} + */ +function parseColor(color) { + if (/^#[0-9a-f]{3,8}$/i.test(color)) { + var result; + var colorLength = color.length; + + if (colorLength < 6) { + var r = color[1], + g = color[2], + b = color[3], + a = color[4] || ""; + result = "#" + r + r + g + g + b + b + a + a; + } + if (colorLength == 7 || colorLength > 8) { + result = color; + } + + return result; + } +} + +/** + * Converts a hexadecimal color to a CSS3 compatible color. + * @param {string} hexColor Color on the format "#RRGGBB" or "#RRGGBBAA" + * @returns {string} + */ +function toCss3Color(hexColor) { + var a = parseHex(hexColor, 7, 2); + var result; + + if (isNaN(a)) { + result = hexColor; + } else { + var r = parseHex(hexColor, 1, 2), + g = parseHex(hexColor, 3, 2), + b = parseHex(hexColor, 5, 2); + result = "rgba(" + r + "," + g + "," + b + "," + (a / 255).toFixed(2) + ")"; + } + + return result; +} + +/** + * Converts an HSL color to a hexadecimal RGB color. + * @param {number} hue Hue in range [0, 1] + * @param {number} saturation Saturation in range [0, 1] + * @param {number} lightness Lightness in range [0, 1] + * @returns {string} + */ +function hsl(hue, saturation, lightness) { + // Based on http://www.w3.org/TR/2011/REC-css3-color-20110607/#hsl-color + var result; + + if (saturation == 0) { + var partialHex = decToHex(lightness * 255); + result = partialHex + partialHex + partialHex; + } + else { + var m2 = lightness <= 0.5 ? lightness * (saturation + 1) : lightness + saturation - lightness * saturation, + m1 = lightness * 2 - m2; + result = + hueToRgb(m1, m2, hue * 6 + 2) + + hueToRgb(m1, m2, hue * 6) + + hueToRgb(m1, m2, hue * 6 - 2); + } + + return "#" + result; +} + +/** + * Converts an HSL color to a hexadecimal RGB color. This function will correct the lightness for the "dark" hues + * @param {number} hue Hue in range [0, 1] + * @param {number} saturation Saturation in range [0, 1] + * @param {number} lightness Lightness in range [0, 1] + * @returns {string} + */ +function correctedHsl(hue, saturation, lightness) { + // The corrector specifies the perceived middle lightness for each hue + var correctors = [ 0.55, 0.5, 0.5, 0.46, 0.6, 0.55, 0.55 ], + corrector = correctors[(hue * 6 + 0.5) | 0]; + + // Adjust the input lightness relative to the corrector + lightness = lightness < 0.5 ? lightness * corrector * 2 : corrector + (lightness - 0.5) * (1 - corrector) * 2; + + return hsl(hue, saturation, lightness); +} + +/* global umdGlobal */ + +// In the future we can replace `GLOBAL` with `globalThis`, but for now use the old school global detection for +// backward compatibility. +var GLOBAL = umdGlobal; + +/** + * @typedef {Object} ParsedConfiguration + * @property {number} colorSaturation + * @property {number} grayscaleSaturation + * @property {string} backColor + * @property {number} iconPadding + * @property {function(number):number} hue + * @property {function(number):number} colorLightness + * @property {function(number):number} grayscaleLightness + */ + +var CONFIG_PROPERTIES = { + G/*GLOBAL*/: "jdenticon_config", + n/*MODULE*/: "config", +}; + +var rootConfigurationHolder = {}; + +/** + * Defines the deprecated `config` property on the root Jdenticon object without printing a warning in the console + * when it is being used. + * @param {!Object} rootObject + */ +function defineConfigProperty(rootObject) { + rootConfigurationHolder = rootObject; +} + +/** + * Sets a new icon style configuration. The new configuration is not merged with the previous one. * + * @param {Object} newConfiguration - New configuration object. + */ +function configure(newConfiguration) { + if (arguments.length) { + rootConfigurationHolder[CONFIG_PROPERTIES.n/*MODULE*/] = newConfiguration; + } + return rootConfigurationHolder[CONFIG_PROPERTIES.n/*MODULE*/]; +} + +/** + * Gets the normalized current Jdenticon color configuration. Missing fields have default values. + * @param {Object|number|undefined} paddingOrLocalConfig - Configuration passed to the called API method. A + * local configuration overrides the global configuration in it entirety. This parameter can for backward + * compatibility also contain a padding value. A padding value only overrides the global padding, not the + * entire global configuration. + * @param {number} defaultPadding - Padding used if no padding is specified in neither the configuration nor + * explicitly to the API method. + * @returns {ParsedConfiguration} + */ +function getConfiguration(paddingOrLocalConfig, defaultPadding) { + var configObject = + typeof paddingOrLocalConfig == "object" && paddingOrLocalConfig || + rootConfigurationHolder[CONFIG_PROPERTIES.n/*MODULE*/] || + GLOBAL[CONFIG_PROPERTIES.G/*GLOBAL*/] || + { }, + + lightnessConfig = configObject["lightness"] || { }, + + // In versions < 2.1.0 there was no grayscale saturation - + // saturation was the color saturation. + saturation = configObject["saturation"] || { }, + colorSaturation = "color" in saturation ? saturation["color"] : saturation, + grayscaleSaturation = saturation["grayscale"], + + backColor = configObject["backColor"], + padding = configObject["padding"]; + + /** + * Creates a lightness range. + */ + function lightness(configName, defaultRange) { + var range = lightnessConfig[configName]; + + // Check if the lightness range is an array-like object. This way we ensure the + // array contain two values at the same time. + if (!(range && range.length > 1)) { + range = defaultRange; + } + + /** + * Gets a lightness relative the specified value in the specified lightness range. + */ + return function (value) { + value = range[0] + value * (range[1] - range[0]); + return value < 0 ? 0 : value > 1 ? 1 : value; + }; + } + + /** + * Gets a hue allowed by the configured hue restriction, + * provided the originally computed hue. + */ + function hueFunction(originalHue) { + var hueConfig = configObject["hues"]; + var hue; + + // Check if 'hues' is an array-like object. This way we also ensure that + // the array is not empty, which would mean no hue restriction. + if (hueConfig && hueConfig.length > 0) { + // originalHue is in the range [0, 1] + // Multiply with 0.999 to change the range to [0, 1) and then truncate the index. + hue = hueConfig[0 | (0.999 * originalHue * hueConfig.length)]; + } + + return typeof hue == "number" ? + + // A hue was specified. We need to convert the hue from + // degrees on any turn - e.g. 746° is a perfectly valid hue - + // to turns in the range [0, 1). + ((((hue / 360) % 1) + 1) % 1) : + + // No hue configured => use original hue + originalHue; + } + + return { + X/*hue*/: hueFunction, + p/*colorSaturation*/: typeof colorSaturation == "number" ? colorSaturation : 0.5, + H/*grayscaleSaturation*/: typeof grayscaleSaturation == "number" ? grayscaleSaturation : 0, + q/*colorLightness*/: lightness("color", [0.4, 0.8]), + I/*grayscaleLightness*/: lightness("grayscale", [0.3, 0.9]), + J/*backColor*/: parseColor(backColor), + Y/*iconPadding*/: + typeof paddingOrLocalConfig == "number" ? paddingOrLocalConfig : + typeof padding == "number" ? padding : + defaultPadding + } +} + +var ICON_TYPE_SVG = 1; + +var ICON_TYPE_CANVAS = 2; + +var ATTRIBUTES = { + t/*HASH*/: "data-jdenticon-hash", + o/*VALUE*/: "data-jdenticon-value" +}; + +var IS_RENDERED_PROPERTY = "jdenticonRendered"; + +var ICON_SELECTOR = "[" + ATTRIBUTES.t/*HASH*/ +"],[" + ATTRIBUTES.o/*VALUE*/ +"]"; + +var documentQuerySelectorAll = /** @type {!Function} */ ( + typeof document !== "undefined" && document.querySelectorAll.bind(document)); + +function getIdenticonType(el) { + if (el) { + var tagName = el["tagName"]; + + if (/^svg$/i.test(tagName)) { + return ICON_TYPE_SVG; + } + + if (/^canvas$/i.test(tagName) && "getContext" in el) { + return ICON_TYPE_CANVAS; + } + } +} + +function whenDocumentIsReady(/** @type {Function} */ callback) { + function loadedHandler() { + document.removeEventListener("DOMContentLoaded", loadedHandler); + window.removeEventListener("load", loadedHandler); + setTimeout(callback, 0); // Give scripts a chance to run + } + + if (typeof document !== "undefined" && + typeof window !== "undefined" && + typeof setTimeout !== "undefined" + ) { + if (document.readyState === "loading") { + document.addEventListener("DOMContentLoaded", loadedHandler); + window.addEventListener("load", loadedHandler); + } else { + // Document already loaded. The load events above likely won't be raised + setTimeout(callback, 0); + } + } +} + +function observer(updateCallback) { + if (typeof MutationObserver != "undefined") { + var mutationObserver = new MutationObserver(function onmutation(mutations) { + for (var mutationIndex = 0; mutationIndex < mutations.length; mutationIndex++) { + var mutation = mutations[mutationIndex]; + var addedNodes = mutation.addedNodes; + + for (var addedNodeIndex = 0; addedNodes && addedNodeIndex < addedNodes.length; addedNodeIndex++) { + var addedNode = addedNodes[addedNodeIndex]; + + // Skip other types of nodes than element nodes, since they might not support + // the querySelectorAll method => runtime error. + if (addedNode.nodeType == 1) { + if (getIdenticonType(addedNode)) { + updateCallback(addedNode); + } + else { + var icons = /** @type {Element} */(addedNode).querySelectorAll(ICON_SELECTOR); + for (var iconIndex = 0; iconIndex < icons.length; iconIndex++) { + updateCallback(icons[iconIndex]); + } + } + } + } + + if (mutation.type == "attributes" && getIdenticonType(mutation.target)) { + updateCallback(mutation.target); + } + } + }); + + mutationObserver.observe(document.body, { + "childList": true, + "attributes": true, + "attributeFilter": [ATTRIBUTES.o/*VALUE*/, ATTRIBUTES.t/*HASH*/, "width", "height"], + "subtree": true, + }); + } +} + +/** + * Represents a point. + */ +function Point(x, y) { + this.x = x; + this.y = y; +} + +/** + * Translates and rotates a point before being passed on to the canvas context. This was previously done by the canvas context itself, + * but this caused a rendering issue in Chrome on sizes > 256 where the rotation transformation of inverted paths was not done properly. + */ +function Transform(x, y, size, rotation) { + this.u/*_x*/ = x; + this.v/*_y*/ = y; + this.K/*_size*/ = size; + this.Z/*_rotation*/ = rotation; +} + +/** + * Transforms the specified point based on the translation and rotation specification for this Transform. + * @param {number} x x-coordinate + * @param {number} y y-coordinate + * @param {number=} w The width of the transformed rectangle. If greater than 0, this will ensure the returned point is of the upper left corner of the transformed rectangle. + * @param {number=} h The height of the transformed rectangle. If greater than 0, this will ensure the returned point is of the upper left corner of the transformed rectangle. + */ +Transform.prototype.L/*transformIconPoint*/ = function transformIconPoint (x, y, w, h) { + var right = this.u/*_x*/ + this.K/*_size*/, + bottom = this.v/*_y*/ + this.K/*_size*/, + rotation = this.Z/*_rotation*/; + return rotation === 1 ? new Point(right - y - (h || 0), this.v/*_y*/ + x) : + rotation === 2 ? new Point(right - x - (w || 0), bottom - y - (h || 0)) : + rotation === 3 ? new Point(this.u/*_x*/ + y, bottom - x - (w || 0)) : + new Point(this.u/*_x*/ + x, this.v/*_y*/ + y); +}; + +var NO_TRANSFORM = new Transform(0, 0, 0, 0); + + + +/** + * Provides helper functions for rendering common basic shapes. + */ +function Graphics(renderer) { + /** + * @type {Renderer} + * @private + */ + this.M/*_renderer*/ = renderer; + + /** + * @type {Transform} + */ + this.A/*currentTransform*/ = NO_TRANSFORM; +} +var Graphics__prototype = Graphics.prototype; + +/** + * Adds a polygon to the underlying renderer. + * @param {Array} points The points of the polygon clockwise on the format [ x0, y0, x1, y1, ..., xn, yn ] + * @param {boolean=} invert Specifies if the polygon will be inverted. + */ +Graphics__prototype.g/*addPolygon*/ = function addPolygon (points, invert) { + var this$1 = this; + + var di = invert ? -2 : 2, + transformedPoints = []; + + for (var i = invert ? points.length - 2 : 0; i < points.length && i >= 0; i += di) { + transformedPoints.push(this$1.A/*currentTransform*/.L/*transformIconPoint*/(points[i], points[i + 1])); + } + + this.M/*_renderer*/.g/*addPolygon*/(transformedPoints); +}; + +/** + * Adds a polygon to the underlying renderer. + * Source: http://stackoverflow.com/a/2173084 + * @param {number} x The x-coordinate of the upper left corner of the rectangle holding the entire ellipse. + * @param {number} y The y-coordinate of the upper left corner of the rectangle holding the entire ellipse. + * @param {number} size The size of the ellipse. + * @param {boolean=} invert Specifies if the ellipse will be inverted. + */ +Graphics__prototype.h/*addCircle*/ = function addCircle (x, y, size, invert) { + var p = this.A/*currentTransform*/.L/*transformIconPoint*/(x, y, size, size); + this.M/*_renderer*/.h/*addCircle*/(p, size, invert); +}; + +/** + * Adds a rectangle to the underlying renderer. + * @param {number} x The x-coordinate of the upper left corner of the rectangle. + * @param {number} y The y-coordinate of the upper left corner of the rectangle. + * @param {number} w The width of the rectangle. + * @param {number} h The height of the rectangle. + * @param {boolean=} invert Specifies if the rectangle will be inverted. + */ +Graphics__prototype.i/*addRectangle*/ = function addRectangle (x, y, w, h, invert) { + this.g/*addPolygon*/([ + x, y, + x + w, y, + x + w, y + h, + x, y + h + ], invert); +}; + +/** + * Adds a right triangle to the underlying renderer. + * @param {number} x The x-coordinate of the upper left corner of the rectangle holding the triangle. + * @param {number} y The y-coordinate of the upper left corner of the rectangle holding the triangle. + * @param {number} w The width of the triangle. + * @param {number} h The height of the triangle. + * @param {number} r The rotation of the triangle (clockwise). 0 = right corner of the triangle in the lower left corner of the bounding rectangle. + * @param {boolean=} invert Specifies if the triangle will be inverted. + */ +Graphics__prototype.j/*addTriangle*/ = function addTriangle (x, y, w, h, r, invert) { + var points = [ + x + w, y, + x + w, y + h, + x, y + h, + x, y + ]; + points.splice(((r || 0) % 4) * 2, 2); + this.g/*addPolygon*/(points, invert); +}; + +/** + * Adds a rhombus to the underlying renderer. + * @param {number} x The x-coordinate of the upper left corner of the rectangle holding the rhombus. + * @param {number} y The y-coordinate of the upper left corner of the rectangle holding the rhombus. + * @param {number} w The width of the rhombus. + * @param {number} h The height of the rhombus. + * @param {boolean=} invert Specifies if the rhombus will be inverted. + */ +Graphics__prototype.N/*addRhombus*/ = function addRhombus (x, y, w, h, invert) { + this.g/*addPolygon*/([ + x + w / 2, y, + x + w, y + h / 2, + x + w / 2, y + h, + x, y + h / 2 + ], invert); +}; + +/** + * @param {number} index + * @param {Graphics} g + * @param {number} cell + * @param {number} positionIndex + */ +function centerShape(index, g, cell, positionIndex) { + index = index % 14; + + var k, m, w, h, inner, outer; + + !index ? ( + k = cell * 0.42, + g.g/*addPolygon*/([ + 0, 0, + cell, 0, + cell, cell - k * 2, + cell - k, cell, + 0, cell + ])) : + + index == 1 ? ( + w = 0 | (cell * 0.5), + h = 0 | (cell * 0.8), + + g.j/*addTriangle*/(cell - w, 0, w, h, 2)) : + + index == 2 ? ( + w = 0 | (cell / 3), + g.i/*addRectangle*/(w, w, cell - w, cell - w)) : + + index == 3 ? ( + inner = cell * 0.1, + // Use fixed outer border widths in small icons to ensure the border is drawn + outer = + cell < 6 ? 1 : + cell < 8 ? 2 : + (0 | (cell * 0.25)), + + inner = + inner > 1 ? (0 | inner) : // large icon => truncate decimals + inner > 0.5 ? 1 : // medium size icon => fixed width + inner, // small icon => anti-aliased border + + g.i/*addRectangle*/(outer, outer, cell - inner - outer, cell - inner - outer)) : + + index == 4 ? ( + m = 0 | (cell * 0.15), + w = 0 | (cell * 0.5), + g.h/*addCircle*/(cell - w - m, cell - w - m, w)) : + + index == 5 ? ( + inner = cell * 0.1, + outer = inner * 4, + + // Align edge to nearest pixel in large icons + outer > 3 && (outer = 0 | outer), + + g.i/*addRectangle*/(0, 0, cell, cell), + g.g/*addPolygon*/([ + outer, outer, + cell - inner, outer, + outer + (cell - outer - inner) / 2, cell - inner + ], true)) : + + index == 6 ? + g.g/*addPolygon*/([ + 0, 0, + cell, 0, + cell, cell * 0.7, + cell * 0.4, cell * 0.4, + cell * 0.7, cell, + 0, cell + ]) : + + index == 7 ? + g.j/*addTriangle*/(cell / 2, cell / 2, cell / 2, cell / 2, 3) : + + index == 8 ? ( + g.i/*addRectangle*/(0, 0, cell, cell / 2), + g.i/*addRectangle*/(0, cell / 2, cell / 2, cell / 2), + g.j/*addTriangle*/(cell / 2, cell / 2, cell / 2, cell / 2, 1)) : + + index == 9 ? ( + inner = cell * 0.14, + // Use fixed outer border widths in small icons to ensure the border is drawn + outer = + cell < 4 ? 1 : + cell < 6 ? 2 : + (0 | (cell * 0.35)), + + inner = + cell < 8 ? inner : // small icon => anti-aliased border + (0 | inner), // large icon => truncate decimals + + g.i/*addRectangle*/(0, 0, cell, cell), + g.i/*addRectangle*/(outer, outer, cell - outer - inner, cell - outer - inner, true)) : + + index == 10 ? ( + inner = cell * 0.12, + outer = inner * 3, + + g.i/*addRectangle*/(0, 0, cell, cell), + g.h/*addCircle*/(outer, outer, cell - inner - outer, true)) : + + index == 11 ? + g.j/*addTriangle*/(cell / 2, cell / 2, cell / 2, cell / 2, 3) : + + index == 12 ? ( + m = cell * 0.25, + g.i/*addRectangle*/(0, 0, cell, cell), + g.N/*addRhombus*/(m, m, cell - m, cell - m, true)) : + + // 13 + ( + !positionIndex && ( + m = cell * 0.4, w = cell * 1.2, + g.h/*addCircle*/(m, m, w) + ) + ); +} + +/** + * @param {number} index + * @param {Graphics} g + * @param {number} cell + */ +function outerShape(index, g, cell) { + index = index % 4; + + var m; + + !index ? + g.j/*addTriangle*/(0, 0, cell, cell, 0) : + + index == 1 ? + g.j/*addTriangle*/(0, cell / 2, cell, cell / 2, 0) : + + index == 2 ? + g.N/*addRhombus*/(0, 0, cell, cell) : + + // 3 + ( + m = cell / 6, + g.h/*addCircle*/(m, m, cell - 2 * m) + ); +} + +/** + * Gets a set of identicon color candidates for a specified hue and config. + * @param {number} hue + * @param {ParsedConfiguration} config + */ +function colorTheme(hue, config) { + hue = config.X/*hue*/(hue); + return [ + // Dark gray + correctedHsl(hue, config.H/*grayscaleSaturation*/, config.I/*grayscaleLightness*/(0)), + // Mid color + correctedHsl(hue, config.p/*colorSaturation*/, config.q/*colorLightness*/(0.5)), + // Light gray + correctedHsl(hue, config.H/*grayscaleSaturation*/, config.I/*grayscaleLightness*/(1)), + // Light color + correctedHsl(hue, config.p/*colorSaturation*/, config.q/*colorLightness*/(1)), + // Dark color + correctedHsl(hue, config.p/*colorSaturation*/, config.q/*colorLightness*/(0)) + ]; +} + +/** + * Draws an identicon to a specified renderer. + * @param {Renderer} renderer + * @param {string} hash + * @param {Object|number=} config + */ +function iconGenerator(renderer, hash, config) { + var parsedConfig = getConfiguration(config, 0.08); + + // Set background color + if (parsedConfig.J/*backColor*/) { + renderer.m/*setBackground*/(parsedConfig.J/*backColor*/); + } + + // Calculate padding and round to nearest integer + var size = renderer.k/*iconSize*/; + var padding = (0.5 + size * parsedConfig.Y/*iconPadding*/) | 0; + size -= padding * 2; + + var graphics = new Graphics(renderer); + + // Calculate cell size and ensure it is an integer + var cell = 0 | (size / 4); + + // Since the cell size is integer based, the actual icon will be slightly smaller than specified => center icon + var x = 0 | (padding + size / 2 - cell * 2); + var y = 0 | (padding + size / 2 - cell * 2); + + function renderShape(colorIndex, shapes, index, rotationIndex, positions) { + var shapeIndex = parseHex(hash, index, 1); + var r = rotationIndex ? parseHex(hash, rotationIndex, 1) : 0; + + renderer.O/*beginShape*/(availableColors[selectedColorIndexes[colorIndex]]); + + for (var i = 0; i < positions.length; i++) { + graphics.A/*currentTransform*/ = new Transform(x + positions[i][0] * cell, y + positions[i][1] * cell, cell, r++ % 4); + shapes(shapeIndex, graphics, cell, i); + } + + renderer.P/*endShape*/(); + } + + // AVAILABLE COLORS + var hue = parseHex(hash, -7) / 0xfffffff, + + // Available colors for this icon + availableColors = colorTheme(hue, parsedConfig), + + // The index of the selected colors + selectedColorIndexes = []; + + var index; + + function isDuplicate(values) { + if (values.indexOf(index) >= 0) { + for (var i = 0; i < values.length; i++) { + if (selectedColorIndexes.indexOf(values[i]) >= 0) { + return true; + } + } + } + } + + for (var i = 0; i < 3; i++) { + index = parseHex(hash, 8 + i, 1) % availableColors.length; + if (isDuplicate([0, 4]) || // Disallow dark gray and dark color combo + isDuplicate([2, 3])) { // Disallow light gray and light color combo + index = 1; + } + selectedColorIndexes.push(index); + } + + // ACTUAL RENDERING + // Sides + renderShape(0, outerShape, 2, 3, [[1, 0], [2, 0], [2, 3], [1, 3], [0, 1], [3, 1], [3, 2], [0, 2]]); + // Corners + renderShape(1, outerShape, 4, 5, [[0, 0], [3, 0], [3, 3], [0, 3]]); + // Center + renderShape(2, centerShape, 1, null, [[1, 1], [2, 1], [2, 2], [1, 2]]); + + renderer.finish(); +} + +/** + * Computes a SHA1 hash for any value and returns it as a hexadecimal string. + * + * This function is optimized for minimal code size and rather short messages. + * + * @param {string} message + */ +function sha1(message) { + var HASH_SIZE_HALF_BYTES = 40; + var BLOCK_SIZE_WORDS = 16; + + // Variables + // `var` is used to be able to minimize the number of `var` keywords. + var i = 0, + f = 0, + + // Use `encodeURI` to UTF8 encode the message without any additional libraries + // We could use `unescape` + `encodeURI` to minimize the code, but that would be slightly risky + // since `unescape` is deprecated. + urlEncodedMessage = encodeURI(message) + "%80", // trailing '1' bit padding + + // This can be changed to a preallocated Uint32Array array for greater performance and larger code size + data = [], + dataSize, + + hashBuffer = [], + + a = 0x67452301, + b = 0xefcdab89, + c = ~a, + d = ~b, + e = 0xc3d2e1f0, + hash = [a, b, c, d, e], + + blockStartIndex = 0, + hexHash = ""; + + /** + * Rotates the value a specified number of bits to the left. + * @param {number} value Value to rotate + * @param {number} shift Bit count to shift. + */ + function rotl(value, shift) { + return (value << shift) | (value >>> (32 - shift)); + } + + // Message data + for ( ; i < urlEncodedMessage.length; f++) { + data[f >> 2] = data[f >> 2] | + ( + ( + urlEncodedMessage[i] == "%" + // Percent encoded byte + ? parseInt(urlEncodedMessage.substring(i + 1, i += 3), 16) + // Unencoded byte + : urlEncodedMessage.charCodeAt(i++) + ) + + // Read bytes in reverse order (big endian words) + << ((3 - (f & 3)) * 8) + ); + } + + // f is now the length of the utf8 encoded message + // 7 = 8 bytes (64 bit) for message size, -1 to round down + // >> 6 = integer division with block size + dataSize = (((f + 7) >> 6) + 1) * BLOCK_SIZE_WORDS; + + // Message size in bits. + // SHA1 uses a 64 bit integer to represent the size, but since we only support short messages only the least + // significant 32 bits are set. -8 is for the '1' bit padding byte. + data[dataSize - 1] = f * 8 - 8; + + // Compute hash + for ( ; blockStartIndex < dataSize; blockStartIndex += BLOCK_SIZE_WORDS) { + for (i = 0; i < 80; i++) { + f = rotl(a, 5) + e + ( + // Ch + i < 20 ? ((b & c) ^ ((~b) & d)) + 0x5a827999 : + + // Parity + i < 40 ? (b ^ c ^ d) + 0x6ed9eba1 : + + // Maj + i < 60 ? ((b & c) ^ (b & d) ^ (c & d)) + 0x8f1bbcdc : + + // Parity + (b ^ c ^ d) + 0xca62c1d6 + ) + ( + hashBuffer[i] = i < BLOCK_SIZE_WORDS + // Bitwise OR is used to coerse `undefined` to 0 + ? (data[blockStartIndex + i] | 0) + : rotl(hashBuffer[i - 3] ^ hashBuffer[i - 8] ^ hashBuffer[i - 14] ^ hashBuffer[i - 16], 1) + ); + + e = d; + d = c; + c = rotl(b, 30); + b = a; + a = f; + } + + hash[0] = a = ((hash[0] + a) | 0); + hash[1] = b = ((hash[1] + b) | 0); + hash[2] = c = ((hash[2] + c) | 0); + hash[3] = d = ((hash[3] + d) | 0); + hash[4] = e = ((hash[4] + e) | 0); + } + + // Format hex hash + for (i = 0; i < HASH_SIZE_HALF_BYTES; i++) { + hexHash += ( + ( + // Get word (2^3 half-bytes per word) + hash[i >> 3] >>> + + // Append half-bytes in reverse order + ((7 - (i & 7)) * 4) + ) + // Clamp to half-byte + & 0xf + ).toString(16); + } + + return hexHash; +} + +/** + * Inputs a value that might be a valid hash string for Jdenticon and returns it + * if it is determined valid, otherwise a falsy value is returned. + */ +function isValidHash(hashCandidate) { + return /^[0-9a-f]{11,}$/i.test(hashCandidate) && hashCandidate; +} + +/** + * Computes a hash for the specified value. Currently SHA1 is used. This function + * always returns a valid hash. + */ +function computeHash(value) { + return sha1(value == null ? "" : "" + value); +} + + + +/** + * Renderer redirecting drawing commands to a canvas context. + * @implements {Renderer} + */ +function CanvasRenderer(ctx, iconSize) { + var canvas = ctx.canvas; + var width = canvas.width; + var height = canvas.height; + + ctx.save(); + + if (!iconSize) { + iconSize = Math.min(width, height); + + ctx.translate( + ((width - iconSize) / 2) | 0, + ((height - iconSize) / 2) | 0); + } + + /** + * @private + */ + this.l/*_ctx*/ = ctx; + this.k/*iconSize*/ = iconSize; + + ctx.clearRect(0, 0, iconSize, iconSize); +} +var CanvasRenderer__prototype = CanvasRenderer.prototype; + +/** + * Fills the background with the specified color. + * @param {string} fillColor Fill color on the format #rrggbb[aa]. + */ +CanvasRenderer__prototype.m/*setBackground*/ = function setBackground (fillColor) { + var ctx = this.l/*_ctx*/; + var iconSize = this.k/*iconSize*/; + + ctx.fillStyle = toCss3Color(fillColor); + ctx.fillRect(0, 0, iconSize, iconSize); +}; + +/** + * Marks the beginning of a new shape of the specified color. Should be ended with a call to endShape. + * @param {string} fillColor Fill color on format #rrggbb[aa]. + */ +CanvasRenderer__prototype.O/*beginShape*/ = function beginShape (fillColor) { + var ctx = this.l/*_ctx*/; + ctx.fillStyle = toCss3Color(fillColor); + ctx.beginPath(); +}; + +/** + * Marks the end of the currently drawn shape. This causes the queued paths to be rendered on the canvas. + */ +CanvasRenderer__prototype.P/*endShape*/ = function endShape () { + this.l/*_ctx*/.fill(); +}; + +/** + * Adds a polygon to the rendering queue. + * @param points An array of Point objects. + */ +CanvasRenderer__prototype.g/*addPolygon*/ = function addPolygon (points) { + var ctx = this.l/*_ctx*/; + ctx.moveTo(points[0].x, points[0].y); + for (var i = 1; i < points.length; i++) { + ctx.lineTo(points[i].x, points[i].y); + } + ctx.closePath(); +}; + +/** + * Adds a circle to the rendering queue. + * @param {Point} point The upper left corner of the circle bounding box. + * @param {number} diameter The diameter of the circle. + * @param {boolean} counterClockwise True if the circle is drawn counter-clockwise (will result in a hole if rendered on a clockwise path). + */ +CanvasRenderer__prototype.h/*addCircle*/ = function addCircle (point, diameter, counterClockwise) { + var ctx = this.l/*_ctx*/, + radius = diameter / 2; + ctx.moveTo(point.x + radius, point.y + radius); + ctx.arc(point.x + radius, point.y + radius, radius, 0, Math.PI * 2, counterClockwise); + ctx.closePath(); +}; + +/** + * Called when the icon has been completely drawn. + */ +CanvasRenderer__prototype.finish = function finish () { + this.l/*_ctx*/.restore(); +}; + +/** + * Draws an identicon to a context. + * @param {CanvasRenderingContext2D} ctx - Canvas context on which the icon will be drawn at location (0, 0). + * @param {*} hashOrValue - A hexadecimal hash string or any value that will be hashed by Jdenticon. + * @param {number} size - Icon size in pixels. + * @param {Object|number=} config - Optional configuration. If specified, this configuration object overrides any + * global configuration in its entirety. For backward compatibility a padding value in the range [0.0, 0.5) can be + * specified in place of a configuration object. + */ +function drawIcon(ctx, hashOrValue, size, config) { + if (!ctx) { + throw new Error("No canvas specified."); + } + + iconGenerator(new CanvasRenderer(ctx, size), + isValidHash(hashOrValue) || computeHash(hashOrValue), + config); + + var canvas = ctx.canvas; + if (canvas) { + canvas[IS_RENDERED_PROPERTY] = true; + } +} + +/** + * Prepares a measure to be used as a measure in an SVG path, by + * rounding the measure to a single decimal. This reduces the file + * size of the generated SVG with more than 50% in some cases. + */ +function svgValue(value) { + return ((value * 10 + 0.5) | 0) / 10; +} + +/** + * Represents an SVG path element. + */ +function SvgPath() { + /** + * This property holds the data string (path.d) of the SVG path. + * @type {string} + */ + this.B/*dataString*/ = ""; +} +var SvgPath__prototype = SvgPath.prototype; + +/** + * Adds a polygon with the current fill color to the SVG path. + * @param points An array of Point objects. + */ +SvgPath__prototype.g/*addPolygon*/ = function addPolygon (points) { + var dataString = ""; + for (var i = 0; i < points.length; i++) { + dataString += (i ? "L" : "M") + svgValue(points[i].x) + " " + svgValue(points[i].y); + } + this.B/*dataString*/ += dataString + "Z"; +}; + +/** + * Adds a circle with the current fill color to the SVG path. + * @param {Point} point The upper left corner of the circle bounding box. + * @param {number} diameter The diameter of the circle. + * @param {boolean} counterClockwise True if the circle is drawn counter-clockwise (will result in a hole if rendered on a clockwise path). + */ +SvgPath__prototype.h/*addCircle*/ = function addCircle (point, diameter, counterClockwise) { + var sweepFlag = counterClockwise ? 0 : 1, + svgRadius = svgValue(diameter / 2), + svgDiameter = svgValue(diameter), + svgArc = "a" + svgRadius + "," + svgRadius + " 0 1," + sweepFlag + " "; + + this.B/*dataString*/ += + "M" + svgValue(point.x) + " " + svgValue(point.y + diameter / 2) + + svgArc + svgDiameter + ",0" + + svgArc + (-svgDiameter) + ",0"; +}; + + + +/** + * Renderer producing SVG output. + * @implements {Renderer} + */ +function SvgRenderer(target) { + /** + * @type {SvgPath} + * @private + */ + this.C/*_path*/; + + /** + * @type {Object.} + * @private + */ + this.D/*_pathsByColor*/ = { }; + + /** + * @type {SvgElement|SvgWriter} + * @private + */ + this.R/*_target*/ = target; + + /** + * @type {number} + */ + this.k/*iconSize*/ = target.k/*iconSize*/; +} +var SvgRenderer__prototype = SvgRenderer.prototype; + +/** + * Fills the background with the specified color. + * @param {string} fillColor Fill color on the format #rrggbb[aa]. + */ +SvgRenderer__prototype.m/*setBackground*/ = function setBackground (fillColor) { + var match = /^(#......)(..)?/.exec(fillColor), + opacity = match[2] ? parseHex(match[2], 0) / 255 : 1; + this.R/*_target*/.m/*setBackground*/(match[1], opacity); +}; + +/** + * Marks the beginning of a new shape of the specified color. Should be ended with a call to endShape. + * @param {string} color Fill color on format #xxxxxx. + */ +SvgRenderer__prototype.O/*beginShape*/ = function beginShape (color) { + this.C/*_path*/ = this.D/*_pathsByColor*/[color] || (this.D/*_pathsByColor*/[color] = new SvgPath()); +}; + +/** + * Marks the end of the currently drawn shape. + */ +SvgRenderer__prototype.P/*endShape*/ = function endShape () { }; + +/** + * Adds a polygon with the current fill color to the SVG. + * @param points An array of Point objects. + */ +SvgRenderer__prototype.g/*addPolygon*/ = function addPolygon (points) { + this.C/*_path*/.g/*addPolygon*/(points); +}; + +/** + * Adds a circle with the current fill color to the SVG. + * @param {Point} point The upper left corner of the circle bounding box. + * @param {number} diameter The diameter of the circle. + * @param {boolean} counterClockwise True if the circle is drawn counter-clockwise (will result in a hole if rendered on a clockwise path). + */ +SvgRenderer__prototype.h/*addCircle*/ = function addCircle (point, diameter, counterClockwise) { + this.C/*_path*/.h/*addCircle*/(point, diameter, counterClockwise); +}; + +/** + * Called when the icon has been completely drawn. + */ +SvgRenderer__prototype.finish = function finish () { + var this$1 = this; + + var pathsByColor = this.D/*_pathsByColor*/; + for (var color in pathsByColor) { + // hasOwnProperty cannot be shadowed in pathsByColor + // eslint-disable-next-line no-prototype-builtins + if (pathsByColor.hasOwnProperty(color)) { + this$1.R/*_target*/.S/*appendPath*/(color, pathsByColor[color].B/*dataString*/); + } + } +}; + +var SVG_CONSTANTS = { + T/*XMLNS*/: "http://www.w3.org/2000/svg", + U/*WIDTH*/: "width", + V/*HEIGHT*/: "height", +}; + +/** + * Renderer producing SVG output. + */ +function SvgWriter(iconSize) { + /** + * @type {number} + */ + this.k/*iconSize*/ = iconSize; + + /** + * @type {string} + * @private + */ + this.F/*_s*/ = + ''; +} +var SvgWriter__prototype = SvgWriter.prototype; + +/** + * Fills the background with the specified color. + * @param {string} fillColor Fill color on the format #rrggbb. + * @param {number} opacity Opacity in the range [0.0, 1.0]. + */ +SvgWriter__prototype.m/*setBackground*/ = function setBackground (fillColor, opacity) { + if (opacity) { + this.F/*_s*/ += ''; + } +}; + +/** + * Writes a path to the SVG string. + * @param {string} color Fill color on format #rrggbb. + * @param {string} dataString The SVG path data string. + */ +SvgWriter__prototype.S/*appendPath*/ = function appendPath (color, dataString) { + this.F/*_s*/ += ''; +}; + +/** + * Gets the rendered image as an SVG string. + */ +SvgWriter__prototype.toString = function toString () { + return this.F/*_s*/ + ""; +}; + +/** + * Draws an identicon as an SVG string. + * @param {*} hashOrValue - A hexadecimal hash string or any value that will be hashed by Jdenticon. + * @param {number} size - Icon size in pixels. + * @param {Object|number=} config - Optional configuration. If specified, this configuration object overrides any + * global configuration in its entirety. For backward compatibility a padding value in the range [0.0, 0.5) can be + * specified in place of a configuration object. + * @returns {string} SVG string + */ +function toSvg(hashOrValue, size, config) { + var writer = new SvgWriter(size); + iconGenerator(new SvgRenderer(writer), + isValidHash(hashOrValue) || computeHash(hashOrValue), + config); + return writer.toString(); +} + +/** + * Creates a new element and adds it to the specified parent. + * @param {Element} parentNode + * @param {string} name + * @param {...(string|number)} keyValuePairs + */ +function SvgElement_append(parentNode, name) { + var keyValuePairs = [], len = arguments.length - 2; + while ( len-- > 0 ) keyValuePairs[ len ] = arguments[ len + 2 ]; + + var el = document.createElementNS(SVG_CONSTANTS.T/*XMLNS*/, name); + + for (var i = 0; i + 1 < keyValuePairs.length; i += 2) { + el.setAttribute( + /** @type {string} */(keyValuePairs[i]), + /** @type {string} */(keyValuePairs[i + 1]) + ); + } + + parentNode.appendChild(el); +} + + +/** + * Renderer producing SVG output. + */ +function SvgElement(element) { + // Don't use the clientWidth and clientHeight properties on SVG elements + // since Firefox won't serve a proper value of these properties on SVG + // elements (https://bugzilla.mozilla.org/show_bug.cgi?id=874811) + // Instead use 100px as a hardcoded size (the svg viewBox will rescale + // the icon to the correct dimensions) + var iconSize = this.k/*iconSize*/ = Math.min( + (Number(element.getAttribute(SVG_CONSTANTS.U/*WIDTH*/)) || 100), + (Number(element.getAttribute(SVG_CONSTANTS.V/*HEIGHT*/)) || 100) + ); + + /** + * @type {Element} + * @private + */ + this.W/*_el*/ = element; + + // Clear current SVG child elements + while (element.firstChild) { + element.removeChild(element.firstChild); + } + + // Set viewBox attribute to ensure the svg scales nicely. + element.setAttribute("viewBox", "0 0 " + iconSize + " " + iconSize); + element.setAttribute("preserveAspectRatio", "xMidYMid meet"); +} +var SvgElement__prototype = SvgElement.prototype; + +/** + * Fills the background with the specified color. + * @param {string} fillColor Fill color on the format #rrggbb. + * @param {number} opacity Opacity in the range [0.0, 1.0]. + */ +SvgElement__prototype.m/*setBackground*/ = function setBackground (fillColor, opacity) { + if (opacity) { + SvgElement_append(this.W/*_el*/, "rect", + SVG_CONSTANTS.U/*WIDTH*/, "100%", + SVG_CONSTANTS.V/*HEIGHT*/, "100%", + "fill", fillColor, + "opacity", opacity); + } +}; + +/** + * Appends a path to the SVG element. + * @param {string} color Fill color on format #xxxxxx. + * @param {string} dataString The SVG path data string. + */ +SvgElement__prototype.S/*appendPath*/ = function appendPath (color, dataString) { + SvgElement_append(this.W/*_el*/, "path", + "fill", color, + "d", dataString); +}; + +/** + * Updates all canvas elements with the `data-jdenticon-hash` or `data-jdenticon-value` attribute. + */ +function updateAll() { + if (documentQuerySelectorAll) { + update(ICON_SELECTOR); + } +} + +/** + * Updates all canvas elements with the `data-jdenticon-hash` or `data-jdenticon-value` attribute that have not already + * been rendered. + */ +function updateAllConditional() { + if (documentQuerySelectorAll) { + /** @type {NodeListOf} */ + var elements = documentQuerySelectorAll(ICON_SELECTOR); + + for (var i = 0; i < elements.length; i++) { + var el = elements[i]; + if (!el[IS_RENDERED_PROPERTY]) { + update(el); + } + } + } +} + +/** + * Updates the identicon in the specified `` or `` elements. + * @param {(string|Element)} el - Specifies the container in which the icon is rendered as a DOM element of the type + * `` or ``, or a CSS selector to such an element. + * @param {*=} hashOrValue - Optional hash or value to be rendered. If not specified, the `data-jdenticon-hash` or + * `data-jdenticon-value` attribute will be evaluated. + * @param {Object|number=} config - Optional configuration. If specified, this configuration object overrides any + * global configuration in its entirety. For backward compability a padding value in the range [0.0, 0.5) can be + * specified in place of a configuration object. + */ +function update(el, hashOrValue, config) { + renderDomElement(el, hashOrValue, config, function (el, iconType) { + if (iconType) { + return iconType == ICON_TYPE_SVG ? + new SvgRenderer(new SvgElement(el)) : + new CanvasRenderer(/** @type {HTMLCanvasElement} */(el).getContext("2d")); + } + }); +} + +/** + * Updates the identicon in the specified canvas or svg elements. + * @param {(string|Element)} el - Specifies the container in which the icon is rendered as a DOM element of the type + * `` or ``, or a CSS selector to such an element. + * @param {*} hashOrValue - Optional hash or value to be rendered. If not specified, the `data-jdenticon-hash` or + * `data-jdenticon-value` attribute will be evaluated. + * @param {Object|number|undefined} config + * @param {function(Element,number):Renderer} rendererFactory - Factory function for creating an icon renderer. + */ +function renderDomElement(el, hashOrValue, config, rendererFactory) { + if (typeof el === "string") { + if (documentQuerySelectorAll) { + var elements = documentQuerySelectorAll(el); + for (var i = 0; i < elements.length; i++) { + renderDomElement(elements[i], hashOrValue, config, rendererFactory); + } + } + return; + } + + // Hash selection. The result from getValidHash or computeHash is + // accepted as a valid hash. + var hash = + // 1. Explicit valid hash + isValidHash(hashOrValue) || + + // 2. Explicit value (`!= null` catches both null and undefined) + hashOrValue != null && computeHash(hashOrValue) || + + // 3. `data-jdenticon-hash` attribute + isValidHash(el.getAttribute(ATTRIBUTES.t/*HASH*/)) || + + // 4. `data-jdenticon-value` attribute. + // We want to treat an empty attribute as an empty value. + // Some browsers return empty string even if the attribute + // is not specified, so use hasAttribute to determine if + // the attribute is specified. + el.hasAttribute(ATTRIBUTES.o/*VALUE*/) && computeHash(el.getAttribute(ATTRIBUTES.o/*VALUE*/)); + + if (!hash) { + // No hash specified. Don't render an icon. + return; + } + + var renderer = rendererFactory(el, getIdenticonType(el)); + if (renderer) { + // Draw icon + iconGenerator(renderer, hash, config); + el[IS_RENDERED_PROPERTY] = true; + } +} + +/** + * Renders an identicon for all matching supported elements. + * + * @param {*} hashOrValue - A hexadecimal hash string or any value that will be hashed by Jdenticon. If not + * specified the `data-jdenticon-hash` and `data-jdenticon-value` attributes of each element will be + * evaluated. + * @param {Object|number=} config - Optional configuration. If specified, this configuration object overrides any global + * configuration in its entirety. For backward compatibility a padding value in the range [0.0, 0.5) can be + * specified in place of a configuration object. + */ +function jdenticonJqueryPlugin(hashOrValue, config) { + this["each"](function (index, el) { + update(el, hashOrValue, config); + }); + return this; +} + +// This file is compiled to dist/jdenticon.js and dist/jdenticon.min.js + +var jdenticon = updateAll; + +defineConfigProperty(jdenticon); + +// Export public API +jdenticon["configure"] = configure; +jdenticon["drawIcon"] = drawIcon; +jdenticon["toSvg"] = toSvg; +jdenticon["update"] = update; +jdenticon["updateCanvas"] = update; +jdenticon["updateSvg"] = update; + +/** + * Specifies the version of the Jdenticon package in use. + * @type {string} + */ +jdenticon["version"] = "3.3.0"; + +/** + * Specifies which bundle of Jdenticon that is used. + * @type {string} + */ +jdenticon["bundle"] = "browser-umd"; + +// Basic jQuery plugin +var jQuery = GLOBAL["jQuery"]; +if (jQuery) { + jQuery["fn"]["jdenticon"] = jdenticonJqueryPlugin; +} + +/** + * This function is called once upon page load. + */ +function jdenticonStartup() { + var replaceMode = ( + jdenticon[CONFIG_PROPERTIES.n/*MODULE*/] || + GLOBAL[CONFIG_PROPERTIES.G/*GLOBAL*/] || + { } + )["replaceMode"]; + + if (replaceMode != "never") { + updateAllConditional(); + + if (replaceMode == "observe") { + observer(update); + } + } +} + +// Schedule to render all identicons on the page once it has been loaded. +whenDocumentIsReady(jdenticonStartup); + +return jdenticon; + +}); \ No newline at end of file diff --git a/server/static/dashboard/js/libs/msg.js b/server/static/dashboard/js/libs/msg.js new file mode 100644 index 0000000..75444f5 --- /dev/null +++ b/server/static/dashboard/js/libs/msg.js @@ -0,0 +1,2339 @@ +/* Msg v14.2.2 https://github.com/Merkoba/Msg */ + +const Msg = {} +Msg.num_created = 0 + +Msg.el = (query, root = document) => { + return root.querySelector(query) +} + +Msg.els = (query, root = document) => { + return Array.from(root.querySelectorAll(query)) +} + +Msg.ev = (element, action, callback, extra) => { + element.addEventListener(action, callback, extra) +} + +Msg.insert = (element_1, element_2, position = `beforeend`) => { + element_1.insertAdjacentHTML(position, element_2) +} + +Msg.factory = (options = {}) => { + const instance = {} + instance.stack_pos_top = undefined + instance.stack_pos_bottom = undefined + instance.stack_pos_left = undefined + instance.stack_pos_right = undefined + instance.stack_width = undefined + instance.stack_height = undefined + instance.options = options + + instance.check_options = () => { + if (instance.options.preset !== undefined) { + if (instance.options.preset === `popup`) { + if (instance.options.class === undefined) + instance.options.class = `green` + if (instance.options.enable_overlay === undefined) + instance.options.enable_overlay = false + if (instance.options.position === undefined) + instance.options.position = `bottomright` + if (instance.options.remove_after_close === undefined) + instance.options.remove_after_close = true + if (instance.options.zStack_level === undefined) + instance.options.zStack_level = 1 + if (instance.options.window_width === undefined) + instance.options.window_width = `460px` + if (instance.options.lock === undefined) instance.options.lock = false + } + else if (instance.options.preset === `popup_autoclose`) { + if (instance.options.class === undefined) + instance.options.class = `green` + if (instance.options.enable_overlay === undefined) + instance.options.enable_overlay = false + if (instance.options.position === undefined) + instance.options.position = `bottomright` + if (instance.options.autoclose === undefined) + instance.options.autoclose = true + if (instance.options.enable_progressbar === undefined) + instance.options.enable_progressbar = true + if (instance.options.remove_after_close === undefined) + instance.options.remove_after_close = true + if (instance.options.zStack_level === undefined) + instance.options.zStack_level = 1 + if (instance.options.window_width === undefined) + instance.options.window_width = `460px` + if (instance.options.lock === undefined) instance.options.lock = false + } + else if (instance.options.preset === `window`) { + if (instance.options.window_height === undefined) + instance.options.window_height = `100vh` + if (instance.options.window_min_height === undefined) + instance.options.window_min_height = `100vh` + if (instance.options.window_max_height === undefined) + instance.options.window_max_height = `100vh` + if (instance.options.window_width === undefined) + instance.options.window_width = `100vw` + if (instance.options.window_min_width === undefined) + instance.options.window_min_width = `100vw` + if (instance.options.window_max_width === undefined) + instance.options.window_max_width = `100vw` + if (instance.options.disable_transformations === undefined) + instance.options.disable_transformations = true + if (instance.options.disable_content_padding === undefined) + instance.options.disable_content_padding = true + if (instance.options.full_content === undefined) + instance.options.full_content = true + if (instance.options.window_x === undefined) + instance.options.window_x = `none` + } + } + + if (instance.options.id === undefined) { + instance.options.id = Msg.num_created + 1 + } + + if (instance.options.class === undefined) { + instance.options.class = `default` + } + + if (instance.options.lock === undefined) { + instance.options.lock = true + } + + if (instance.options.closeable === undefined) { + instance.options.closeable = true + } + + if (instance.options.enable_overlay === undefined) { + instance.options.enable_overlay = true + } + + if (instance.options.close_on_overlay_click === undefined) { + instance.options.close_on_overlay_click = true + } + + if (instance.options.enable_titlebar === undefined) { + instance.options.enable_titlebar = false + } + + if (instance.options.center_titlebar === undefined) { + instance.options.center_titlebar = false + } + + if (instance.options.window_x === undefined) { + if (instance.options.enable_titlebar) { + instance.options.window_x = `inner_right` + } + else { + instance.options.window_x = `floating_right` + } + } + + if (instance.options.overlay_x === undefined) { + instance.options.overlay_x = `none` + } + + if (instance.options.close_on_escape === undefined) { + instance.options.close_on_escape = true + } + + if (instance.options.clear_editables === undefined) { + instance.options.clear_editables = false + } + + if (instance.options.before_show === undefined) { + instance.options.before_show = () => {} + } + + if (instance.options.after_show === undefined) { + instance.options.after_show = () => {} + } + + if (instance.options.before_set === undefined) { + instance.options.before_set = () => {} + } + + if (instance.options.after_set === undefined) { + instance.options.after_set = () => {} + } + + if (instance.options.before_set_title === undefined) { + instance.options.before_set_title = () => {} + } + + if (instance.options.after_set_title === undefined) { + instance.options.after_set_title = () => {} + } + + if (instance.options.before_set_progress === undefined) { + instance.options.before_set_progress = () => {} + } + + if (instance.options.after_set_progress === undefined) { + instance.options.after_set_progress = () => {} + } + + if (instance.options.before_close === undefined) { + instance.options.before_close = () => {} + } + + if (instance.options.after_close === undefined) { + instance.options.after_close = () => {} + } + + if (instance.options.after_last_closed === undefined) { + instance.options.after_last_closed = () => {} + } + + if (instance.options.before_toggle === undefined) { + instance.options.before_toggle = () => {} + } + + if (instance.options.after_toggle === undefined) { + instance.options.after_toggle = () => {} + } + + if (instance.options.before_create === undefined) { + instance.options.before_create = () => {} + } + + if (instance.options.after_create === undefined) { + instance.options.after_create = () => {} + } + + if (instance.options.before_destroy === undefined) { + instance.options.before_destroy = () => {} + } + + if (instance.options.after_destroy === undefined) { + instance.options.after_destroy = () => {} + } + + if (instance.options.on_click === undefined) { + instance.options.on_click = () => {} + } + + if (instance.options.on_middle_click === undefined) { + instance.options.on_middle_click = () => {} + } + + if (instance.options.on_wheel_down === undefined) { + instance.options.on_wheel_down = () => {} + } + + if (instance.options.on_wheel_up === undefined) { + instance.options.on_wheel_up = () => {} + } + + if (instance.options.on_overlay_click === undefined) { + instance.options.on_overlay_click = () => {} + } + + if (instance.options.on_titlebar_click === undefined) { + instance.options.on_titlebar_click = () => {} + } + + if (instance.options.on_x_button_click === undefined) { + instance.options.on_x_button_click = () => {} + } + + if (instance.options.autoclose === undefined) { + instance.options.autoclose = false + } + + if (instance.options.autoclose_delay === undefined) { + instance.options.autoclose_delay = 5000 + } + else { + instance.options.autoclose_delay = parseInt(instance.options.autoclose_delay) + } + + if (instance.options.persistent === undefined) { + instance.options.persistent = true + } + + if (instance.options.remove_after_close === undefined) { + instance.options.remove_after_close = false + } + + if (instance.options.position === undefined) { + instance.options.position = `center` + } + + if (instance.options.enable_progressbar === undefined) { + instance.options.enable_progressbar = false + } + + if (instance.options.bind_progressbar_to_autoclose === undefined) { + instance.options.bind_progressbar_to_autoclose = true + } + + if (instance.options.reverse_autoclose_progressbar === undefined) { + instance.options.reverse_autoclose_progressbar = false + } + + if (instance.options.edge_padding_x === undefined) { + instance.options.edge_padding_x = 20 + } + else { + instance.options.edge_padding_x = parseInt(instance.options.edge_padding_x) + } + + if (instance.options.edge_padding_y === undefined) { + instance.options.edge_padding_y = 20 + } + else { + instance.options.edge_padding_y = parseInt(instance.options.edge_padding_y) + } + + if (instance.options.sideStack_padding === undefined) { + instance.options.sideStack_padding = 20 + } + + if (instance.options.sideStack_padding === undefined) { + instance.options.sideStack_padding = 20 + } + else { + instance.options.sideStack_padding = parseInt(instance.options.sideStack_padding) + } + + if (instance.options.sideStack === undefined) { + instance.options.sideStack = `vertical` + } + + if (instance.options.sideStack_collapse === undefined) { + instance.options.sideStack_collapse = true + } + + if (instance.options.zStack_level === undefined) { + instance.options.zStack_level = 2 + } + else { + instance.options.zStack_level = parseInt(instance.options.zStack_level) + } + + if (instance.options.window_width === undefined) { + instance.options.window_width = `auto` + } + + if (instance.options.window_height === undefined) { + instance.options.window_height = `auto` + } + + if (instance.options.window_min_width === undefined) { + instance.options.window_min_width = `auto` + } + + if (instance.options.window_min_height === undefined) { + instance.options.window_min_height = `auto` + } + + if (instance.options.window_max_width === undefined) { + instance.options.window_max_width = `80vw` + } + + if (instance.options.window_max_height === undefined) { + instance.options.window_max_height = `80vh` + } + + if (instance.options.window_cursor === undefined) { + instance.options.window_cursor = `default` + } + + if (instance.options.titlebar_cursor === undefined) { + instance.options.titlebar_cursor = `default` + } + + if (instance.options.window_unselectable === undefined) { + instance.options.window_unselectable = false + } + + if (instance.options.replace_linebreaks === undefined) { + instance.options.replace_linebreaks = false + } + + if (instance.options.close_others_on_show === undefined) { + instance.options.close_others_on_show = false + } + + if (instance.options.scroll_on_show === undefined) { + instance.options.scroll_on_show = true + } + + if (instance.options.locked_element === undefined) { + instance.options.locked_element = `body` + } + + if (instance.options.disable_transformations === undefined) { + instance.options.disable_transformations = false + } + + if (instance.options.disable_content_padding === undefined) { + instance.options.disable_content_padding = false + } + + if (instance.options.full_content === undefined) { + instance.options.full_content = false + } + } + + instance.check_options() + + instance.created = () => { + if (instance.container === undefined) { + return false + } + + return true + } + + instance.close = () => { + if (!instance.is_open()) { + return + } + + if (!instance.options.closeable) { + return + } + + if (instance.options.before_close(instance) === false) { + return + } + + instance.container.style.display = `none` + + if (instance.overlay !== undefined) { + instance.overlay.style.zIndex = -1000 + } + + instance.collapse_vStack() + instance.collapse_hStack() + instance.window.style.zIndex = -1000 + instance.clear_autoclose_progressbar_interval() + instance.check_remove_overflow_hidden() + + if (!instance.options.persistent) { + instance.destroy() + } + + instance.options.after_close(instance) + + if (instance.num_open() === 0) { + instance.options.after_last_closed(instance) + } + + if (instance.options.remove_after_close) { + instance.remove() + } + } + + instance.set = (html) => { + if (html === undefined) { + return + } + + instance.create() + + if (instance.options.before_set(instance) === false) { + return + } + + if (typeof html === `object`) { + if (html instanceof Element) { + instance.content.innerHTML = `` + instance.content.appendChild(html) + } + } + else { + html = html.toString() + + if (instance.options.replace_linebreaks) { + html = html.replace(/(\n)/g, `
`) + } + + instance.content.innerHTML = html + } + + instance.fix_stacks() + instance.options.after_set(instance) + } + + instance.set_title = (html) => { + if (html === undefined) { + return + } + + instance.create() + + if (instance.titlebar === undefined) { + return + } + + if (instance.options.before_set_title(instance) === false) { + return + } + + if (typeof html === `object`) { + if (html instanceof Element) { + instance.titlebar.innerHTML = `` + instance.titlebar.appendChild(html) + } + } + else { + html = html.toString() + + if (instance.options.replace_linebreaks) { + html = html.replace(/(\n)/g, `
`) + } + + instance.titlebar.innerHTML = html + } + + instance.fix_stacks() + instance.options.after_set_title(instance) + } + + instance.hide_titlebar = () => { + if (!instance.topbar) { + return + } + + instance.topbar.style.display = `none` + } + + instance.show_titlebar = () => { + if (!instance.topbar) { + return + } + + instance.topbar.style.display = `flex` + } + + instance.set_or_show = (html,) => { + if (instance.is_highest()) { + instance.set(html) + } + else { + instance.show(html) + } + } + + instance.show = (content) => { + if (instance.options.close_on_show && instance.is_open()) { + instance.close() + instance.show(content) + return + } + + let title + let html + + if (typeof content === `object` && !(content instanceof Element)) { + title = content[0] + html = content[1] + } + else { + html = content + } + + instance.create() + + if (instance.options.before_show(instance) === false) { + return + } + + if (html !== undefined) { + instance.set(html) + } + + if (title !== undefined) { + instance.set_title(title) + } + + instance.reset_timers() + + if (!instance.is_open()) { + if (instance.options.close_others_on_show) { + instance.close_all() + } + + instance.container.style.display = `block` + instance.check_add_overflow_hidden() + instance.set_default_positions() + instance.reset_props() + + if (instance.options.sideStack === `vertical`) { + instance.check_vStack() + } + else if (instance.options.sideStack === `horizontal`) { + instance.check_hStack() + } + } + + instance.to_top() + + if (instance.options.scroll_on_show) { + instance.content_container.scrollTop = 0 + } + + if (instance.options.autoclose) { + instance.autoclose_timer() + + if (instance.options.enable_progressbar && instance.options.bind_progressbar_to_autoclose) { + instance.animate_autoclose_progressbar() + } + } + + instance.options.after_show(instance) + } + + instance.toggle = () => { + instance.create() + + if (instance.options.before_toggle(instance) === false) { + return + } + + instance.is_open() ? instance.close() : instance.show() + instance.options.after_toggle(instance) + } + + instance.create = () => { + if (instance.created()) { + return + } + + if (Msg.el(`#Msg-container-${instance.options.id}`) !== null) { + throw `Msg Error: The html elements for this id have already been created. Use a different id.` + } + + if (instance.options.before_create(instance) === false) { + return + } + + let styles = {} + + styles.container = ` + display: none; + ` + + styles.overlay = ` + position: fixed; + opacity: 1; + top: 0; + left: 0; + height: 100%; + width: 100%; + z-index: -1000; + user-select: none; + ` + + styles.overlay_x = ` + cursor: pointer; + float: ${instance.options.overlay_x}; + font-size: 28px; + font-family: sans-serif; + -webkit-touch-callout: none; + -webkit-user-select: none; + -khtml-user-select: none; + -moz-user-select: none; + -ms-user-select: none; + user-select: none; + padding-left: 0.6em; + padding-right: 0.6em; + padding-top: 0.035em; + padding-bottom: 0.2em; + ` + + let p = instance.options.position + let edge_x = instance.options.edge_padding_x + let edge_y = instance.options.edge_padding_y + let win_x, win_y, win_trans + + if (instance.options.disable_transformations) { + win_x = `left: 0;` + win_y = `top: 0;` + win_trans = `transform: initial;` + + instance.vStackable = false + instance.hStackable = false + } + else if (p === `top`) { + win_x = `left: 50%;` + win_y = `top: ${edge_y}px;` + win_trans = `transform: translateX(-50%);` + + instance.vStackable = true + instance.hStackable = false + } + else if (p === `bottom`) { + win_x = `left: 50%;` + win_y = `bottom: ${edge_y}px;` + win_trans = `transform: translateX(-50%);` + + instance.vStackable = true + instance.hStackable = false + } + else if (p === `left`) { + win_x = `left: ${edge_x}px;` + win_y = `top: 50%;` + win_trans = `transform: translateY(-50%);` + + instance.vStackable = false + instance.hStackable = true + } + else if (p === `right`) { + win_x = `right: ${edge_x}px;` + win_y = `top: 50%;` + win_trans = `transform: translateY(-50%);` + + instance.vStackable = false + instance.hStackable = true + } + else if (p === `topleft`) { + win_x = `left: ${edge_x}px;` + win_y = `top: ${edge_y}px;` + win_trans = `` + + instance.vStackable = true + instance.hStackable = true + } + else if (p === `topright`) { + win_x = `right: ${edge_x}px;` + win_y = `top: ${edge_y}px;` + win_trans = `` + + instance.vStackable = true + instance.hStackable = true + } + else if (p === `bottomleft`) { + win_x = `left: ${edge_x}px;` + win_y = `bottom: ${edge_y}px;` + win_trans = `` + + instance.vStackable = true + instance.hStackable = true + } + else if (p === `bottomright`) { + win_x = `right: ${edge_x}px;` + win_y = `bottom: ${edge_y}px;` + win_trans = `` + + instance.vStackable = true + instance.hStackable = true + } + else { + win_x = `left: 50%;` + win_y = `top: 50%;` + win_trans = `transform: translate(-50%, -50%);` + + instance.vStackable = false + instance.hStackable = false + } + + let wun + + if (instance.options.window_unselectable) { + wun = `user-select: none;` + } + else { + wun = `` + } + + styles.window = ` + display: flex; + flex-direction: column; + opacity: 1; + ${win_x} + ${win_y} + position: fixed; + width: ${instance.options.window_width}; + height: ${instance.options.window_height}; + min-width: ${instance.options.window_min_width}; + min-height: ${instance.options.window_min_height}; + max-width: ${instance.options.window_max_width}; + max-height: ${instance.options.window_max_height}; + ${win_trans} + outline: 0; + ${wun} + cursor: ${instance.options.window_cursor}; + z-index: -1000; + ` + + styles.topbar = ` + overflow: hidden; + flex-shrink: 0; + display: flex; + flex-direction: row; + ` + let padl = `padding-left: 0.4em;` + let padr = `padding-right: 0.4em;` + let justcnt = `` + + if (instance.options.center_titlebar) { + justcnt = `justify-content: center` + } + + if (instance.options.center_titlebar && instance.options.window_x === `inner_right`) { + padl = `padding-left: 50.78px;` + padr = `padding-right: 10.78px;` + } + + if (instance.options.center_titlebar && instance.options.window_x === `inner_left`) { + padl = `padding-left: 10.78px;` + padr = `padding-right: 50.78px;` + } + + styles.titlebar = ` + display: flex; + align-items: center; + ${justcnt}; + overflow: hidden; + order: 2; + flex-grow: 1; + ${padl} + ${padr} + min-height: 27px; + font-size: 16px; + font-family: sans-serif; + font-weight: bold; + white-space: nowrap; + cursor:${instance.options.titlebar_cursor}; + ` + + let ix_order, ix_margin + + if (instance.options.window_x.includes(`left`)) { + ix_order = `1` + ix_margin = `` + } + else { + ix_order = `3` + ix_margin = `auto` + } + + styles.window_inner_x = ` + cursor: pointer; + margin-left: ${ix_margin}; + font-size: 24px; + font-family: sans-serif; + -webkit-touch-callout: none; + -webkit-user-select: none; + -khtml-user-select: none; + -moz-user-select: none; + -ms-user-select: none; + user-select: none; + overflow: hidden; + order: ${ix_order}; + padding-left: 0.6em; + padding-right: 0.6em; + padding-top: 0.035em; + padding-bottom: 0.2em; + ` + + let fs, fms + + if (instance.options.window_x.includes(`left`)) { + fs = `left: 0px;` + fms = `margin-left: -10px;` + } + else { + fs = `right: 0px;` + fms = `margin-right: -10px;` + } + + styles.window_floating_x = ` + cursor: pointer; + position: absolute; + top: 0px; + ${fs} + margin-top: -10px; + ${fms} + font-size: 16px; + font-family: sans-serif; + height: 22px; + width: 22px; + -webkit-touch-callout: none; + -webkit-user-select: none; + -khtml-user-select: none; + -moz-user-select: none; + -ms-user-select: none; + user-select: none; + overflow: hidden; + z-index: 9999999999999999; + display: block; + box-sizing: border-box; + border-width: 3px; + border-style: solid; + border-color: #2B2D30; + border-radius: 100%; + background: linear-gradient(-45deg, transparent 0%, transparent 46%, white 46%, white 56%,transparent 56%, transparent 100%), linear-gradient(45deg, transparent 0%, transparent 46%, white 46%, white 56%,transparent 56%, transparent 100%); + background-color: #2B2D30; + box-shadow: 0px 0px 5px 2px rgba(0,0,0,0.5); + transition: all 0.3s ease; + ` + + let overflow_y = `auto` + + if (instance.options.preset === `window`) { + overflow_y = `hidden` + } + + styles.content_container = ` + overflow-y: ${overflow_y}; + overflow-x: hidden; + border: none; + outline: 0; + margin: 0; + flex-grow: 1; + ` + + let pad + + if (instance.options.disable_content_padding) { + pad = `padding: 0;` + } + else { + pad = `padding: 1.2rem;` + } + + let cwid, chgt + + if (instance.options.full_content) { + cwid = `width: 100%;` + chgt = `height: 100%;` + } + else { + cwid = `` + chgt = `` + } + + styles.content = ` + font-size: 16px; + text-align: center; + overflow-wrap: break-word; + ${pad} + ${cwid} + ${chgt} + ` + + styles.progressbar_container = ` + height: 11px; + width: 100%; + ` + + styles.progressbar = ` + height: 100%; + width: 0%; + ` + + let container_class = + instance.options.container_class !== undefined + ? instance.options.container_class + : instance.options.class + let overlay_class = + instance.options.overlay_class !== undefined + ? instance.options.overlay_class + : instance.options.class + let overlay_x_class = + instance.options.overlay_x_class !== undefined + ? instance.options.overlay_x_class + : instance.options.class + let window_class = + instance.options.window_class !== undefined + ? instance.options.window_class + : instance.options.class + let topbar_class = + instance.options.topbar_class !== undefined + ? instance.options.topbar_class + : instance.options.class + let titlebar_class = + instance.options.titlebar_class !== undefined + ? instance.options.titlebar_class + : instance.options.class + let window_inner_x_class = + instance.options.window_inner_x_class !== undefined + ? instance.options.window_inner_x_class + : instance.options.class + let window_floating_x_class = + instance.options.window_floating_x_class !== undefined + ? instance.options.window_floating_x_class + : instance.options.class + let content_container_class = + instance.options.content_container_class !== undefined + ? instance.options.content_container_class + : instance.options.class + let content_class = + instance.options.content_class !== undefined + ? instance.options.content_class + : instance.options.class + let progressbar_container_class = + instance.options.progressbar_container_class !== undefined + ? instance.options.progressbar_container_class + : instance.options.class + let progressbar_class = + instance.options.progressbar_class !== undefined + ? instance.options.progressbar_class + : instance.options.class + + container_class = container_class + .split(/\s+/) + .map((w) => (w.startsWith(`!`) ? w.substring(1) : `Msg-container-${w}`)) + .join(` `) + overlay_class = overlay_class + .split(/\s+/) + .map((w) => (w.startsWith(`!`) ? w.substring(1) : `Msg-overlay-${w}`)) + .join(` `) + overlay_x_class = overlay_x_class + .split(/\s+/) + .map((w) => (w.startsWith(`!`) ? w.substring(1) : `Msg-overlay-x-${w}`)) + .join(` `) + window_class = window_class + .split(/\s+/) + .map((w) => (w.startsWith(`!`) ? w.substring(1) : `Msg-window-${w}`)) + .join(` `) + topbar_class = topbar_class + .split(/\s+/) + .map((w) => (w.startsWith(`!`) ? w.substring(1) : `Msg-topbar-${w}`)) + .join(` `) + titlebar_class = titlebar_class + .split(/\s+/) + .map((w) => (w.startsWith(`!`) ? w.substring(1) : `Msg-titlebar-${w}`)) + .join(` `) + window_inner_x_class = window_inner_x_class + .split(/\s+/) + .map((w) => + w.startsWith(`!`) ? w.substring(1) : `Msg-window-inner-x-${w}` + ) + .join(` `) + window_floating_x_class = window_floating_x_class + .split(/\s+/) + .map((w) => + w.startsWith(`!`) ? w.substring(1) : `Msg-window-floating-x-${w}` + ) + .join(` `) + content_container_class = content_container_class + .split(/\s+/) + .map((w) => + w.startsWith(`!`) ? w.substring(1) : `Msg-content-container-${w}` + ) + .join(` `) + content_class = content_class + .split(/\s+/) + .map((w) => (w.startsWith(`!`) ? w.substring(1) : `Msg-content-${w}`)) + .join(` `) + progressbar_container_class = progressbar_container_class + .split(/\s+/) + .map((w) => + w.startsWith(`!`) ? w.substring(1) : `Msg-progressbar-container-${w}` + ) + .join(` `) + progressbar_class = progressbar_class + .split(/\s+/) + .map((w) => (w.startsWith(`!`) ? w.substring(1) : `Msg-progressbar-${w}`)) + .join(` `) + + let container_html = `
` + let overlay_html = `
` + let overlay_x_html = `
x
` + let window_html = `
` + let topbar_html = `
` + let titlebar_html = `
` + let window_inner_x_html = `
x
` + let window_floating_x_html = `
` + let content_container_html = `
` + let content_html = `
` + let progressbar_container_html = `
` + let progressbar_html = `
` + + Msg.insert(document.body, container_html) + instance.container = Msg.el(`#Msg-container-${instance.options.id}`) + + if (instance.options.enable_overlay) { + Msg.insert(instance.container, overlay_html) + instance.overlay = Msg.el(`#Msg-overlay-${instance.options.id}`) + + if (instance.options.overlay_x !== `none`) { + Msg.insert(instance.overlay, overlay_x_html) + instance.overlay_x = Msg.el(`#Msg-overlay-x-${instance.options.id}`) + } + } + + Msg.insert(instance.container, window_html) + instance.window = Msg.el(`#Msg-window-${instance.options.id}`) + + if (instance.options.enable_titlebar || instance.options.window_x.includes(`inner`)) { + Msg.insert(instance.window, topbar_html) + instance.topbar = Msg.el(`#Msg-topbar-${instance.options.id}`) + + if (instance.options.enable_titlebar) { + Msg.insert(instance.topbar, titlebar_html) + instance.titlebar = Msg.el(`#Msg-titlebar-${instance.options.id}`) + } + + if (instance.options.window_x.includes(`inner`)) { + Msg.insert(instance.topbar, window_inner_x_html) + instance.window_inner_x = Msg.el(`#Msg-window-inner-x-${instance.options.id}`) + } + } + + if (instance.options.window_x.includes(`floating`)) { + Msg.insert(instance.window, window_floating_x_html, `afterbegin`) + instance.window_floating_x = Msg.el(`#Msg-window-floating-x-${instance.options.id}`) + } + + Msg.insert(instance.window, content_container_html) + instance.content_container = Msg.el(`#Msg-content-container-${instance.options.id}`) + Msg.insert(instance.content_container, content_html) + instance.content = Msg.el(`#Msg-content-${instance.options.id}`) + + if (instance.options.enable_progressbar) { + Msg.insert(instance.window, progressbar_container_html) + instance.progressbar_container = Msg.el(`#Msg-progressbar-container-${instance.options.id}`) + Msg.insert(instance.progressbar_container, progressbar_html) + instance.progressbar = Msg.el(`#Msg-progressbar-${instance.options.id}`) + } + + if (instance.overlay !== undefined) { + Msg.ev(instance.overlay, `click`, () => { + if (instance.options.close_on_overlay_click) { + instance.options.on_overlay_click(instance) + instance.close() + } + }) + } + + if (instance.titlebar !== undefined) { + Msg.ev(instance.titlebar, `click`, () => { + if (instance.options.close_on_titlebar_click) { + instance.options.on_titlebar_click(instance) + instance.close() + } + }) + } + + Msg.ev(instance.window, `click`, (e) => { + instance.options.on_click(instance) + }) + + Msg.ev(instance.window, `wheel`, (e) => { + let direction = e.deltaY > 0 ? `down` : `up` + + if (direction === `down`) { + instance.options.on_wheel_down(instance) + } + else if (direction === `up`) { + instance.options.on_wheel_up(instance) + } + }) + + Msg.ev(instance.window, `auxclick`, (e) => { + if (e.which === 2) { + instance.options.on_middle_click(instance) + } + }) + + if (instance.window_inner_x !== undefined) { + Msg.ev(instance.window_inner_x, `click`, (e) => { + instance.options.on_x_button_click(instance) + instance.close() + e.stopPropagation() + }) + + } + + if (instance.window_floating_x !== undefined) { + Msg.ev(instance.window_floating_x, `click`, (e) => { + instance.options.on_x_button_click(instance) + instance.close() + e.stopPropagation() + }) + + } + + if (instance.overlay_x !== undefined) { + Msg.ev(instance.overlay_x, `click`, (e) => { + instance.options.on_x_button_click(instance) + instance.close() + e.stopPropagation() + }) + + } + + instance.options.after_create(instance) + } + + instance.recreate = () => { + instance.destroy() + instance.create() + } + + instance.destroy = () => { + if (instance.created()) { + if (instance.options.before_destroy(instance) === false) { + return + } + + instance.check_remove_overflow_hidden() + instance.container.parentNode.removeChild(instance.container) + + instance.container = undefined + instance.overlay = undefined + instance.overlay_x = undefined + instance.window = undefined + instance.topbar = undefined + instance.titlebar = undefined + instance.window_inner_x = undefined + instance.window_floating_x = undefined + instance.content_container = undefined + instance.content = undefined + instance.progressbar_container = undefined + instance.progressbar = undefined + + instance.options.after_destroy(instance) + } + } + + instance.is_open = () => { + if (!instance.created() || instance.container.style.display === `none`) { + return false + } + else { + return true + } + } + + instance.any_open = () => { + for (let inst of Msg.instances) { + if (inst.is_open()) { + return true + } + } + + return false + } + + instance.any_higher_open = () => { + for (let inst of Msg.instances) { + if (inst.options.zStack_level === 2) { + if (inst.is_open()) { + return true + } + } + } + + return false + } + + instance.any_lower_open = () => { + for (let inst of Msg.instances) { + if (inst.options.zStack_level === 1) { + if (inst.is_open()) { + return true + } + } + } + + return false + } + + instance.num_open = () => { + let num_open = 0 + + for (let inst of Msg.instances) { + if (inst.is_open()) { + num_open += 1 + } + } + + return num_open + } + + instance.num_open_higher = () => { + let num_open = 0 + + for (let inst of Msg.instances) { + if (inst.is_open()) { + if (inst.options.zStack_level === 2) { + num_open += 1 + } + } + } + + return num_open + } + + instance.num_open_lower = () => { + let num_open = 0 + + for (let inst of Msg.instances) { + if (inst.is_open()) { + if (inst.options.zStack_level === 1) { + num_open += 1 + } + } + } + + return num_open + } + + instance.show_all = () => { + for (let i = 0; i < Msg.instances.length; i++) { + Msg.instances[i].show() + } + } + + instance.close_all = () => { + if (!instance.any_open()) { + return false + } + + for (let i = 0; i < Msg.instances.length; i++) { + Msg.instances[i].close() + } + } + + instance.close_all_higher = () => { + if (!instance.any_higher_open()) { + return false + } + + for (let higher of instance.higher_instances()) { + higher.close() + } + } + + instance.close_all_lower = () => { + if (!instance.any_lower_open()) { + return false + } + + for (let lower of instance.lower_instances()) { + lower.close() + } + } + + instance.create_all = () => { + for (let i = 0; i < Msg.instances.length; i++) { + Msg.instances[i].create() + } + } + + instance.recreate_all = () => { + for (let i = 0; i < Msg.instances.length; i++) { + Msg.instances[i].recreate() + } + } + + instance.destroy_all = () => { + for (let i = 0; i < Msg.instances.length; i++) { + Msg.instances[i].destroy() + } + } + + instance.common_zIndex = (zIndex) => { + zIndex = parseInt(zIndex) + let common + + if (zIndex > 0) { + common = parseInt(zIndex.toString().substring(1)) + } + else { + common = -2000 + } + + return common + } + + instance.highest_zIndex = () => { + let highest = -2000 + let windows = Msg.els(`.Msg-window`) + + for (let i = 0; i < windows.length; i++) { + let zIndex = parseInt(windows[i].style.zIndex) + + if (zIndex > highest) { + highest = zIndex + } + } + + return parseInt(highest) + } + + instance.highest_instance = () => { + let zIndex = instance.highest_zIndex() + + if (zIndex < 0) { + return false + } + + for (let i of Msg.instances) { + if (i.window !== undefined) { + if (parseInt(i.window.style.zIndex) === zIndex) { + return i + } + } + } + + return false + } + + instance.highest_common_zIndex = () => { + let highest = -2000 + let windows = Msg.els(`.Msg-window`) + + for (let i = 0; i < windows.length; i++) { + let zIndex = instance.common_zIndex(windows[i].style.zIndex) + + if (zIndex > highest) { + highest = zIndex + } + } + + return highest + } + + instance.is_highest = () => { + if (instance.is_open()) { + let zIndex = instance.highest_zIndex() + + if (parseInt(instance.window.style.zIndex) === zIndex) { + return true + } + } + + return false + } + + instance.html = () => { + if (instance.created()) { + return instance.content.innerHTML + } + + return `` + } + + instance.title_html = () => { + if (instance.titlebar !== undefined) { + return instance.titlebar.innerHTML + } + + return `` + } + + instance.check_add_overflow_hidden = () => { + if (instance.options.lock) { + document + .querySelector(instance.options.locked_element) + .classList.add(`Msg-overflow-hidden`) + } + } + + instance.check_remove_overflow_hidden = () => { + for (let i of Msg.instances) { + if (i.is_open()) { + if (i.options.lock) { + return + } + } + } + + document + .querySelector(instance.options.locked_element) + .classList.remove(`Msg-overflow-hidden`) + } + + instance.to_top = () => { + if (instance.is_open()) { + let zIndex = parseInt(instance.window.style.zIndex) + let highest_common = instance.highest_common_zIndex() + let highest + + if (instance.options.zStack_level === 1) { + highest = Math.max(5000000, 5000000 + highest_common) + } + else { + highest = Math.max(50000000, 50000000 + highest_common) + } + + if (highest > zIndex) { + if (instance.overlay !== undefined) { + instance.overlay.style.zIndex = highest + 1 + } + + instance.window.style.zIndex = highest + 2 + } + } + } + + instance.instances = () => { + return Msg.instances + } + + instance.higher_instances = () => { + let instances = [] + + for (let inst of Msg.instances) { + if (inst.options.zStack_level === 2) { + instances.push(inst) + } + } + + return instances + } + + instance.lower_instances = () => { + let instances = [] + + for (let inst of Msg.instances) { + if (inst.options.zStack_level === 1) { + instances.push(inst) + } + } + + return instances + } + + instance.get_instance_by_id = (id) => { + for (let i of Msg.instances) { + if (i.options.id == id) { + return i + } + } + } + + instance.autoclose_timer = () => { + instance.autoclose_timeout = setTimeout(() => { + instance.close() + }, instance.options.autoclose_delay) + } + + instance.reset_timers = () => { + clearTimeout(instance.autoclose_timeout) + } + + instance.clear_autoclose_progressbar_interval = () => { + clearInterval(instance.progressbar_animation) + } + + instance.animate_autoclose_progressbar = () => { + instance.clear_autoclose_progressbar_interval() + + if (instance.options.reverse_autoclose_progressbar) { + let percentage = 0 + instance.progressbar.style.width = `0%` + + instance.progressbar_animation = setInterval(() => { + if (!instance.created()) { + clearInterval(instance.progressbar_animation) + } + + percentage += 1 + + instance.set_progress(percentage) + + if (percentage >= 100) { + clearInterval(instance.progressbar_animation) + } + }, instance.options.autoclose_delay / 100) + } + else { + let percentage = 100 + instance.progressbar.style.width = `100%` + + instance.progressbar_animation = setInterval(() => { + if (!instance.created()) { + clearInterval(instance.progressbar_animation) + } + + percentage -= 1 + + instance.set_progress(percentage) + + if (percentage <= 0) { + clearInterval(instance.progressbar_animation) + } + }, instance.options.autoclose_delay / 100) + } + } + + instance.set_progress = (percentage) => { + if (percentage === undefined) { + return + } + + instance.create() + + if (instance.progressbar === undefined) { + return + } + + if (instance.options.before_set_progress(instance) === false) { + return + } + + if (percentage > 100) { + percentage = 100 + } + + if (percentage < 0) { + percentage = 0 + } + + instance.progressbar.style.width = `${percentage}%` + instance.options.after_set_progress(instance) + } + + instance.get_progress = () => { + if (instance.progressbar === undefined) { + return + } + + return Math.round((instance.progressbar.offsetWidth / instance.window.offsetWidth) * 100) + } + + instance.reset_props = () => { + if (instance.overlay !== undefined) { + instance.overlay.style.opacity = 1 + } + + instance.window.style.opacity = 1 + instance.window.style.zoom = 1 + } + + instance.stack_pos_top_sort = (a, b) => { + return a.stack_pos_top - b.stack_pos_top + } + + instance.stack_pos_top_sort2 = (a, b) => { + return b.stack_pos_top - a.stack_pos_top + } + + instance.stack_pos_bottom_sort = (a, b) => { + return a.stack_pos_bottom - b.stack_pos_bottom + } + + instance.stack_pos_bottom_sort2 = (a, b) => { + return b.stack_pos_bottom - a.stack_pos_bottom + } + + instance.stack_pos_left_sort = (a, b) => { + return a.stack_pos_left - b.stack_pos_left + } + + instance.stack_pos_left_sort2 = (a, b) => { + return b.stack_pos_left - a.stack_pos_left + } + + instance.stack_pos_right_sort = (a, b) => { + return a.stack_pos_right - b.stack_pos_right + } + + instance.stack_pos_right_sort2 = (a, b) => { + return b.stack_pos_right - a.stack_pos_right + } + + instance.highest_in_position = (mode) => { + let highest = -2000 + let highest_ins + let p = instance.options.position + + for (let i of Msg.instances) { + if (i.is_open()) { + if (i.options.position === p) { + let pos + + if (mode === `vertical`) { + if (p.includes(`top`)) { + pos = i.stack_pos_top + } + else if (p.includes(`bottom`)) { + pos = i.stack_pos_bottom + } + } + else if (mode === `horizontal`) { + if (p.includes(`left`)) { + pos = i.stack_pos_left + } + else if (p.includes(`right`)) { + pos = i.stack_pos_right + } + } + + if (pos !== undefined) { + if (pos > highest) { + highest = pos + highest_ins = i + } + } + } + } + } + + return highest_ins + } + + instance.lowest_in_position = (mode) => { + let lowest = 200000000 + let lowest_ins + let p = instance.options.position + + for (let i of Msg.instances) { + if (i.is_open()) { + if (i.options.position === p) { + let pos + + if (mode === `vertical`) { + if (p.includes(`top`)) { + pos = i.stack_pos_top + } + else if (p.includes(`bottom`)) { + pos = i.stack_pos_bottom + } + } + else if (mode === `horizontal`) { + if (p.includes(`left`)) { + pos = i.stack_pos_left + } + else if (p.includes(`right`)) { + pos = i.stack_pos_right + } + } + + if (pos !== undefined) { + if (pos < lowest) { + lowest = pos + lowest_ins = i + } + } + } + } + } + + return lowest_ins + } + + instance.above_in_position = (ins, mode) => { + let ins_above = [] + let p = ins.options.position + + for (let i of Msg.instances) { + if (i.is_open()) { + if (i.options.position === p) { + if (mode === `vertical`) { + if (p.includes(`top`)) { + if (i.stack_pos_top > ins.stack_pos_top) { + ins_above.push(i) + } + } + else if (p.includes(`bottom`)) { + if (i.stack_pos_bottom > ins.stack_pos_bottom) { + ins_above.push(i) + } + } + } + else if (mode === `horizontal`) { + if (p.includes(`left`)) { + if (i.stack_pos_left > ins.stack_pos_left) { + ins_above.push(i) + } + } + else if (p.includes(`right`)) { + if (i.stack_pos_right > ins.stack_pos_right) { + ins_above.push(i) + } + } + } + } + } + } + + if (mode === `vertical`) { + if (p.includes(`top`)) { + ins_above.sort(instance.stack_pos_top_sort) + } + else if (p.includes(`bottom`)) { + ins_above.sort(instance.stack_pos_bottom_sort) + } + } + else if (mode === `horizontal`) { + if (p.includes(`left`)) { + ins_above.sort(instance.stack_pos_left_sort) + } + else if (p.includes(`right`)) { + ins_above.sort(instance.stack_pos_right_sort) + } + } + + return ins_above + } + + instance.nextbelow_in_position = (ins, mode) => { + let ins_below = [] + + let p = ins.options.position + + for (let i of Msg.instances) { + if (i.is_open()) { + let ip = i.options.position + + if (ip === p) { + if (mode === `vertical`) { + let sp + + if (ip.includes(`left`)) { + sp = i.stack_pos_left + } + else if (ip.includes(`right`)) { + sp = i.stack_pos_right + } + + if (sp !== undefined) { + if ((sp > i.options.edge_padding_x + 2) || (sp < i.options.edge_padding_x - 2)) { + continue + } + } + + if (p.includes(`top`)) { + if (i.stack_pos_top < ins.stack_pos_top) { + ins_below.push(i) + } + } + else if (p.includes(`bottom`)) { + if (i.stack_pos_bottom < ins.stack_pos_bottom) { + ins_below.push(i) + } + } + } + else if (mode === `horizontal`) { + if (p.includes(`left`)) { + if (i.stack_pos_left < ins.stack_pos_left) { + ins_below.push(i) + } + } + else if (p.includes(`right`)) { + if (i.stack_pos_right < ins.stack_pos_right) { + ins_below.push(i) + } + } + } + } + } + } + + if (mode === `vertical`) { + if (p.includes(`top`)) { + ins_below.sort(instance.stack_pos_top_sort2) + } + else if (p.includes(`bottom`)) { + ins_below.sort(instance.stack_pos_bottom_sort2) + } + } + else if (mode === `horizontal`) { + if (p.includes(`left`)) { + ins_below.sort(instance.stack_pos_left_sort2) + } + else if (p.includes(`right`)) { + ins_below.sort(instance.stack_pos_right_sort2) + } + } + + return ins_below[0] + } + + instance.check_vStack = () => { + if (instance.vStackable) { + let p = instance.options.position + + if (p.includes(`top`)) { + instance.stack_pos_top = -1000000 + } + else if (p.includes(`bottom`)) { + instance.stack_pos_bottom = -1000000 + } + + let highest = instance.highest_in_position(`vertical`) + + let new_top, new_bottom + + if (highest !== undefined && highest !== instance) { + if (p.includes(`top`)) { + new_top = + highest.stack_pos_top + + highest.stack_height + + instance.options.sideStack_padding + + instance.window.style.top = new_top + `px` + } + else if (p.includes(`bottom`)) { + new_bottom = + highest.stack_pos_bottom + + highest.stack_height + + instance.options.sideStack_padding + + instance.window.style.bottom = new_bottom + `px` + } + } + else { + if (p.includes(`top`)) { + new_top = instance.options.edge_padding_y + instance.window.style.top = new_top + `px` + } + else if (p.includes(`bottom`)) { + new_bottom = instance.options.edge_padding_y + instance.window.style.bottom = new_bottom + `px` + } + } + + if (p.includes(`top`)) { + instance.stack_pos_top = new_top + } + else if (p.includes(`bottom`)) { + instance.stack_pos_bottom = new_bottom + } + } + } + + instance.collapse_vStack = () => { + let p = instance.options.position + let ins_above = instance.above_in_position(instance, `vertical`) + + for (let i of ins_above) { + if (!i.options.sideStack_collapse || i.options.sideStack !== `vertical`) { + continue + } + + let below = instance.nextbelow_in_position(i, `vertical`) + + let new_top, new_bottom + + if (below !== undefined) { + if (p.includes(`top`)) { + new_top = + below.stack_pos_top + + below.window.offsetHeight + + i.options.sideStack_padding + + i.window.style.top = new_top + `px` + } + else if (p.includes(`bottom`)) { + new_bottom = + below.stack_pos_bottom + + below.window.offsetHeight + + i.options.sideStack_padding + + i.window.style.bottom = new_bottom + `px` + } + } + else { + if (p.includes(`top`)) { + new_top = i.options.edge_padding_y + i.window.style.top = new_top + `px` + } + else if (p.includes(`bottom`)) { + new_bottom = i.options.edge_padding_y + i.window.style.bottom = new_bottom + `px` + } + } + + if (p.includes(`top`)) { + i.stack_pos_top = new_top + } + else if (p.includes(`bottom`)) { + i.stack_pos_bottom = new_bottom + } + } + } + + instance.fix_vStack = () => { + let p = instance.options.position + let below = instance.lowest_in_position(`vertical`) + let new_top, new_bottom + + if (below !== undefined) { + let above = instance.above_in_position(below, `vertical`) + + for (let i of above) { + if (p.includes(`top`)) { + new_top = + below.stack_pos_top + + below.window.offsetHeight + + i.options.sideStack_padding + + i.window.style.top = new_top + `px` + i.stack_pos_top = new_top + } + else if (p.includes(`bottom`)) { + new_bottom = + below.stack_pos_bottom + + below.window.offsetHeight + + i.options.sideStack_padding + + i.window.style.bottom = new_bottom + `px` + i.stack_pos_bottom = new_bottom + } + + below = i + } + } + } + + instance.check_hStack = () => { + if (instance.hStackable) { + let p = instance.options.position + + if (p.includes(`left`)) { + instance.stack_pos_left = -1000000 + } + else if (p.includes(`right`)) { + instance.stack_pos_right = -1000000 + } + + let highest = instance.highest_in_position(`horizontal`) + let new_left, new_right + + if (highest !== undefined && highest !== instance) { + if (p.includes(`left`)) { + new_left = + highest.stack_pos_left + + highest.stack_width + + instance.options.sideStack_padding + + instance.window.style.left = new_left + `px` + } + else if (p.includes(`right`)) { + new_right = + highest.stack_pos_right + + highest.stack_width + + instance.options.sideStack_padding + + instance.window.style.right = new_right + `px` + } + } + else { + if (p.includes(`left`)) { + new_left = instance.options.edge_padding_x + instance.window.style.left = new_left + `px` + } + else if (p.includes(`right`)) { + new_right = instance.options.edge_padding_x + instance.window.style.right = new_right + `px` + } + } + + if (p.includes(`left`)) { + instance.stack_pos_left = new_left + } + else if (p.includes(`right`)) { + instance.stack_pos_right = new_right + } + } + } + + instance.collapse_hStack = () => { + let p = instance.options.position + let ins_above = instance.above_in_position(instance, `horizontal`) + + for (let i of ins_above) { + if (!i.options.sideStack_collapse || i.options.sideStack !== `horizontal`) { + continue + } + + let below = instance.nextbelow_in_position(i, `horizontal`) + let new_left, new_right + + if (below !== undefined) { + if (p.includes(`left`)) { + new_left = + below.stack_pos_left + + below.window.offsetWidth + + i.options.sideStack_padding + + i.window.style.left = new_left + `px` + } + else if (p.includes(`right`)) { + new_right = + below.stack_pos_right + + below.window.offsetWidth + + i.options.sideStack_padding + + i.window.style.right = new_right + `px` + } + } + else { + if (p.includes(`left`)) { + new_left = i.options.edge_padding_x + i.window.style.left = new_left + `px` + } + else if (p.includes(`right`)) { + new_right = i.options.edge_padding_x + i.window.style.right = new_right + `px` + } + } + + if (p.includes(`left`)) { + i.stack_pos_left = new_left + } + else if (p.includes(`right`)) { + i.stack_pos_right = new_right + } + } + } + + instance.fix_hStack = () => { + let p = instance.options.position + + let below = instance.lowest_in_position(`horizontal`) + + if (below !== undefined) { + let above = instance.above_in_position(below, `horizontal`) + + let new_left, new_right + + for (let i of above) { + if (p.includes(`left`)) { + new_left = + below.stack_pos_left + + below.window.offsetWidth + + i.options.sideStack_padding + + i.window.style.left = new_left + `px` + i.stack_pos_left = new_left + } + else if (p.includes(`right`)) { + new_right = + below.stack_pos_right + + below.window.offsetWidth + + i.options.sideStack_padding + + i.window.style.right = new_right + `px` + i.stack_pos_right = new_right + } + + below = i + } + } + } + + instance.fix_stacks = () => { + if (instance.is_open()) { + instance.fix_vStack() + instance.fix_hStack() + } + } + + instance.set_default_positions = () => { + let p = instance.options.position + let edge_x = instance.options.edge_padding_x + let edge_y = instance.options.edge_padding_y + + if (p === `top`) { + instance.stack_pos_top = edge_y + instance.stack_pos_bottom = undefined + instance.stack_pos_left = undefined + instance.stack_pos_right = undefined + } + else if (p === `bottom`) { + instance.stack_pos_top = undefined + instance.stack_pos_bottom = edge_y + instance.stack_pos_left = undefined + instance.stack_pos_right = undefined + } + else if (p === `left`) { + instance.stack_pos_top = undefined + instance.stack_pos_bottom = undefined + instance.stack_pos_left = edge_x + instance.stack_pos_right = undefined + } + else if (p === `right`) { + instance.stack_pos_top = undefined + instance.stack_pos_bottom = undefined + instance.stack_pos_left = undefined + instance.stack_pos_right = edge_x + } + else if (p === `topleft`) { + instance.stack_pos_top = edge_y + instance.stack_pos_bottom = undefined + instance.stack_pos_left = edge_x + instance.stack_pos_right = undefined + } + else if (p === `topright`) { + instance.stack_pos_top = edge_y + instance.stack_pos_bottom = undefined + instance.stack_pos_left = undefined + instance.stack_pos_right = edge_x + } + else if (p === `bottomleft`) { + instance.stack_pos_top = undefined + instance.stack_pos_bottom = edge_y + instance.stack_pos_left = edge_x + instance.stack_pos_right = undefined + } + else if (p === `bottomright`) { + instance.stack_pos_top = undefined + instance.stack_pos_bottom = edge_y + instance.stack_pos_left = undefined + instance.stack_pos_right = edge_x + } + else { + instance.stack_pos_top = undefined + instance.stack_pos_bottom = undefined + instance.stack_pos_left = undefined + instance.stack_pos_right = undefined + } + + instance.stack_width = instance.window.offsetWidth + instance.stack_height = instance.window.offsetHeight + } + + instance.remove = () => { + instance.destroy() + + for (let i = 0; i < Msg.instances.length; i++) { + if (Msg.instances[i].options.id === instance.options.id) { + Msg.instances.splice(i, 1) + break + } + } + } + + instance.is_textbox = (element) => { + let tag_name = element.tagName.toLowerCase() + if (tag_name === `textarea`) return true + if (tag_name !== `input`) return false + let type = element.getAttribute(`type`) + + if (!type) { + return false + } + + let input_types = [ + `text`, + `password`, + `number`, + `email`, + `tel`, + `url`, + `search`, + `date`, + `datetime`, + `datetime-local`, + `time`, + `month`, + `week`, + ] + + return input_types.includes(type.toLowerCase()) + } + + if (Msg.msg === undefined && instance.options.id !== `__internal_instance__`) { + Msg.msg = Msg.factory({ id: `__internal_instance__` }) + let style = document.createElement(`style`) + + let css = ` + .Msg-overflow-hidden{overflow: hidden} + + .Msg-overlay{background-color: rgba(0, 0, 0, 0.7)} + .Msg-window{background-color: white;color: #222222} + .Msg-titlebar{background-color: #c8c8c8;color: #222222} + .Msg-progressbar{background-color: #c8c8c8} + .Msg-window-inner-x:hover{background-color: #cacaca} + .Msg-window-floating-x{background-color: #3a3a3a;color: white} + .Msg-window-floating-x:hover{background-color: #2a2a2a} + .Msg-overlay-x{color: white} + .Msg-overlay-x:hover{background-color: #686868} + + .Msg-overlay-blue{background-color: rgba(101, 107, 124, 0.7)} + .Msg-window-blue{background-color: #4f84b8;color: white} + .Msg-titlebar-blue{background-color: #43729f;color: white} + .Msg-progressbar-blue{background-color: #43729f} + .Msg-window-inner-x-blue:hover{background-color: #476b8f} + .Msg-overlay-x-blue{color: white} + .Msg-overlay-x-blue:hover{background-color: #747484} + + .Msg-overlay-red{background-color: rgba(104, 64, 64, 0.7)} + .Msg-window-red{background-color: #ca4e4e;color: white} + .Msg-titlebar-red{background-color: #af3f3f;color: white} + .Msg-progressbar-red{background-color: #af3f3f} + .Msg-window-inner-x-red:hover{background-color: #9d4d4d} + .Msg-overlay-x-red{color: white} + .Msg-overlay-x-red:hover{background-color: #805e5e} + + .Msg-overlay-green{background-color: rgba(121, 159, 133, 0.7)} + .Msg-window-green{background-color: #58a564;color: white} + .Msg-titlebar-green{background-color: #52935c;color: white} + .Msg-progressbar-green{background-color: #52935c} + .Msg-window-inner-x-green:hover{background-color: #4e8456} + .Msg-overlay-x-green{color: white} + .Msg-overlay-x-green:hover{background-color: #7c957c} + + .Msg-overlay-black{background-color: rgba(121, 121, 121, 0.7)} + .Msg-window-black{background-color: #1D1F21;color: white} + .Msg-titlebar-black{background-color: #3c3c3c;color: white} + .Msg-progressbar-black{background-color: #3c3c3c} + .Msg-window-inner-x-black:hover{background-color: #424242} + .Msg-overlay-x-black{color: white} + .Msg-overlay-x-black:hover{background-color: #686868} + ` + + style.innerHTML = css + document.head.appendChild(style) + + Msg.ev(document, `keydown`, (e) => { + let highest = Msg.msg.highest_instance() + if (!highest) return + + if (e.key === `Escape`) { + let highest = Msg.msg.highest_instance() + if (!highest) return + + if (highest.options.clear_editables) { + let el = document.activeElement + + if (highest.is_textbox(el)) { + if (!el.readOnly && !el.disabled) { + if (el.value.trim() !== ``) { + let split = el.value.trimEnd().split(` `) + let new_value = split.slice(0, -1).join(` `) + ` ` + + if (new_value.trim() === ``) { + new_value = `` + } + + el.value = new_value + + let event = new Event(`input`, { + bubbles: true, + cancelable: true, + }) + + el.dispatchEvent(event) + + return + } + } + } + } + + if (highest.options.close_on_escape) { + highest.close() + } + } + }) + } + + if (instance.options.id !== `__internal_instance__`) { + Msg.instances.push(instance) + Msg.num_created += 1 + } + + return instance +} + +Msg.instances = [] + +try { + module.exports = Msg +} +catch (e) {} \ No newline at end of file diff --git a/server/static/dashboard/js/libs/needcontext.js b/server/static/dashboard/js/libs/needcontext.js new file mode 100644 index 0000000..1ba7626 --- /dev/null +++ b/server/static/dashboard/js/libs/needcontext.js @@ -0,0 +1,1019 @@ +// NeedContext v6.0 + +// Main object +const NeedContext = {} +NeedContext.created = false + +// Overridable function to perform after show +NeedContext.after_show = () => {} + +// Overridable function to perform after hide +NeedContext.after_hide = () => {} + +// Minimum menu width and height +NeedContext.min_width = `25px` +NeedContext.min_height = `25px` +NeedContext.back_icon = `⬅️` +NeedContext.back_text = `Back` +NeedContext.clear_text = `Clear` +NeedContext.item_sep = `4px` +NeedContext.layers = {} +NeedContext.level = 0 +NeedContext.gap = `0.5rem` +NeedContext.side_padding = `0.5rem` +NeedContext.center_top = 20 +NeedContext.dragging = false + +// Set defaults +NeedContext.set_defaults = () => { + NeedContext.open = false + NeedContext.mousedown = false + NeedContext.first_mousedown = false + NeedContext.keydown = false + NeedContext.filtered = false + NeedContext.last_x = 0 + NeedContext.last_y = 0 + NeedContext.layers = {} +} + +// Clear the filter +NeedContext.clear_filter = () => { + NeedContext.filter.value = `` + NeedContext.do_filter() + NeedContext.filter.focus() +} + +// Filter from keyboard input +NeedContext.do_filter = () => { + let value = NeedContext.filter.value + let cleaned = NeedContext.remove_spaces(value).toLowerCase() + let selected = false + + for (let el of document.querySelectorAll(`.needcontext-separator`)) { + if (cleaned) { + el.classList.add(`needcontext-hidden`) + } + else { + el.classList.remove(`needcontext-hidden`) + } + } + + for (let text_el of document.querySelectorAll(`.needcontext-text`)) { + let el = text_el.closest(`.needcontext-item`) + let text = text_el.textContent.toLowerCase() + text = NeedContext.remove_spaces(text) + + if (text.includes(cleaned)) { + el.classList.remove(`needcontext-hidden`) + + if (!selected) { + NeedContext.select_item(parseInt(el.dataset.index)) + selected = true + } + } + else { + el.classList.add(`needcontext-hidden`) + } + } + + let back = document.querySelector(`#needcontext-back`) + let clear = document.querySelector(`#needcontext-clear`) + NeedContext.filtered = cleaned !== `` + + if (NeedContext.filtered) { + let text = document.querySelector(`#needcontext-clear-text`) + text.textContent = value.trim() + clear.classList.remove(`needcontext-hidden`) + + if (back) { + back.classList.add(`needcontext-hidden`) + } + } + else { + clear.classList.add(`needcontext-hidden`) + + if (back) { + back.classList.remove(`needcontext-hidden`) + } + } + + NeedContext.scroll_to_selected() +} + +// Fill arg objects +NeedContext.def_args = (def, args) => { + for (let key in def) { + if ((args[key] === undefined) && (def[key] !== undefined)) { + args[key] = def[key] + } + } +} + +// Show the menu +NeedContext.show = (args = {}) => { + let def_args = { + root: true, + expand: false, + picker_mode: false, + margin: 0, + } + + NeedContext.def_args(def_args, args) + + if (!NeedContext.created) { + NeedContext.create() + } + + if (args.e && args.e.clientX !== undefined && args.e.clientY !== undefined) { + args.x = args.e.clientX + args.y = args.e.clientY + } + else if (args.element) { + let rect = args.element.getBoundingClientRect() + args.x = rect.left + args.y = rect.top + args.margin + } + + if (args.root) { + NeedContext.level = 0 + } + + let center = args.x === undefined || args.y === undefined + args.items = args.items.slice(0) + + if (args.index === undefined) { + let items = args.items.filter(x => !x.separator) + + for (let [i, item] of items.entries()) { + if (item.selected) { + args.index = i + break + } + } + } + + if (args.index === undefined) { + args.index = 0 + } + + let selected_index + let layer = NeedContext.get_layer() + + if (layer) { + selected_index = layer.last_index + } + else { + selected_index = args.index + } + + selected_index = selected_index || 0 + + for (let [i, item] of args.items.entries()) { + if (i === selected_index) { + item.selected = true + } + else { + item.selected = false + } + } + + let c = NeedContext.container + c.innerHTML = `` + let index = 0 + + if (args.title) { + let title = document.createElement(`div`) + title.id = `needcontext-title` + + if (args.title_icon) { + let icon = document.createElement(`div`) + icon.classList.add(`needcontext-title-icon`) + title.append(args.title_icon) + } + + let text = document.createElement(`div`) + text.textContent = args.title.trim() + title.append(text) + c.append(title) + + if (args.title_number) { + let number = document.createElement(`div`) + number.classList.add(`needcontext-title-number`) + title.append(number) + } + + c.classList.add(`with_title`) + c.classList.remove(`without_title`) + } + else { + c.classList.remove(`with_title`) + c.classList.add(`without_title`) + } + + if (!args.root) { + c.append(NeedContext.back_button()) + } + + c.append(NeedContext.clear_button()) + let normal_items = [] + + for (let item of args.items) { + let el = document.createElement(`div`) + el.classList.add(`needcontext-item`) + + if (item.separator) { + el.classList.add(`needcontext-separator`) + } + else { + el.classList.add(`needcontext-normal`) + + if (item.image) { + let image = document.createElement(`img`) + image.loading = `lazy` + + image.addEventListener(`error`, (e) => { + e.target.classList.add(`needcontext-hidden`) + }) + + image.classList.add(`needcontext-image`) + image.src = item.image + el.append(image) + } + + if (item.icon) { + let icon = document.createElement(`div`) + icon.classList.add(`needcontext-icon`) + + if (item.icon_action) { + icon.addEventListener(`click`, (e) => { + item.icon_action(e, icon) + }) + } + + icon.append(item.icon) + el.append(icon) + } + + if (item.text) { + let text = document.createElement(`div`) + text.classList.add(`needcontext-text`) + text.textContent = item.text.trim() + el.append(text) + } + + if (item.info) { + el.title = item.info.trim() + } + + if (item.bold) { + el.classList.add(`needcontext-bold`) + } + + el.dataset.index = index + item.index = index + + el.addEventListener(`mousemove`, () => { + let index = parseInt(el.dataset.index) + + if (NeedContext.index !== index) { + NeedContext.select_item(index) + } + }) + + index += 1 + normal_items.push(item) + } + + if (args.on_drag) { + el.draggable = true + } + + item.element = el + item.picked = false + c.append(el) + } + + NeedContext.layers[NeedContext.level] = { + root: args.root, + items: args.items, + normal_items: normal_items, + last_index: selected_index, + x: args.x, + y: args.y, + } + + NeedContext.main.classList.remove(`needcontext-hidden`) + + if (center) { + c.style.left = `50%` + c.style.transform = `translateX(-50%)` + args.y = NeedContext.center_top + } + + if (args.y < 5) { + args.y = 5 + } + + if (args.x < 5) { + args.x = 5 + } + + if ((args.y + c.offsetHeight) + 5 > window.innerHeight) { + args.y = window.innerHeight - c.offsetHeight - 5 + } + + if ((args.x + c.offsetWidth) + 5 > window.innerWidth) { + args.x = window.innerWidth - c.offsetWidth - 5 + } + + NeedContext.last_x = args.x + NeedContext.last_y = args.y + args.x = Math.max(args.x, 0) + args.y = Math.max(args.y, 0) + c.style.top = `${args.y}px` + + if (!center) { + c.style.left = `${args.x}px` + c.style.transform = `unset` + } + + NeedContext.filter.value = `` + NeedContext.filter.focus() + let container = document.querySelector(`#needcontext-container`) + + if (args.expand && args.element) { + container.style.minWidth = `${args.element.clientWidth}px` + } + else { + container.style.minWidth = NeedContext.min_width + } + + container.style.minHeight = NeedContext.min_height + NeedContext.select_item(selected_index) + NeedContext.update_title() + NeedContext.scroll_to_selected() + NeedContext.open = true + NeedContext.after_show() + + if (args.root) { + NeedContext.args = args + } +} + +// Hide the menu +NeedContext.hide = (e) => { + if (NeedContext.open) { + NeedContext.main.classList.add(`needcontext-hidden`) + NeedContext.set_defaults() + NeedContext.after_hide() + + if (NeedContext.args.after_hide) { + NeedContext.args.after_hide(e) + } + } +} + +// Select an item by index +NeedContext.select_item = (index) => { + let els = Array.from(document.querySelectorAll(`.needcontext-normal`)) + + for (let el of els) { + let i = parseInt(el.dataset.index) + + if (i === index) { + el.classList.add(`needcontext-item-selected`) + } + else { + el.classList.remove(`needcontext-item-selected`) + } + } + + NeedContext.index = index +} + +NeedContext.scroll_to_selected = (block = `center`) => { + let el = document.querySelector(`.needcontext-item-selected`) + + if (el) { + el.scrollIntoView({block: block}) + } +} + +// Select an item above or below +NeedContext.select_next = (direction = `down`, bounce = false) => { + let waypoint = false + let first_visible + let items = NeedContext.get_layer().normal_items.slice(0) + items = items.filter(x => !x.removed) + + if (direction === `up`) { + items.reverse() + } + + for (let item of items) { + if (!NeedContext.is_visible(item.element)) { + continue + } + + if (first_visible === undefined) { + first_visible = item.index + } + + if (waypoint) { + NeedContext.select_item(item.index) + NeedContext.scroll_to_selected(`nearest`) + return + } + + if (item.index === NeedContext.index) { + waypoint = true + } + } + + if (!bounce) { + NeedContext.select_item(first_visible) + NeedContext.scroll_to_selected(`nearest`) + return true + } + else { + NeedContext.select_next(`up`) + } +} + +// Do the selected action +NeedContext.select_action = async (e, index = NeedContext.index, mode = `mouse`) => { + if (mode === `mouse`) { + if (!e.target.closest(`.needcontext-normal`)) { + return + } + } + + let x = NeedContext.last_x + let y = NeedContext.last_y + let item = NeedContext.get_layer().normal_items[index] + + function show_below (items) { + NeedContext.get_layer().last_index = index + NeedContext.level += 1 + + if (e.clientY) { + y = e.clientY + } + + NeedContext.show({x: x, y: y, items: items, root: false}) + } + + function do_items (items) { + if (items.length === 1 && items[0].direct) { + NeedContext.action(items[0], e) + } + else { + show_below(items) + } + + return + } + + async function check_item () { + if (item.action) { + NeedContext.action(item, e) + return + } + else if (item.items) { + do_items(item.items) + } + else if (item.get_items) { + let items = await item.get_items() + do_items(items) + } + } + + if (mode === `keyboard`) { + check_item() + return + } + + if (e.button === 0) { + check_item() + } + else if (e.button === 1) { + if (item.alt_action) { + NeedContext.alt_action(item, e) + } + } + else if (e.button === 2) { + if (item.context_action) { + NeedContext.context_action(item, e) + } + } +} + +// Check if item is hidden +NeedContext.is_visible = (el) => { + return !el.classList.contains(`needcontext-hidden`) +} + +// Remove all spaces from text +NeedContext.remove_spaces = (text) => { + return text.replace(/[\s-]+/g, ``) +} + +// Prepare css and events +NeedContext.init = () => { + let style = document.createElement(`style`) + + let css = ` + #needcontext-main { + position: fixed; + z-index: 999999999; + width: 100%; + height: 100%; + top: 0; + left: 0; + } + + .needcontext-hidden { + display: none !important; + } + + #needcontext-container { + z-index: 2; + position: absolute; + background-color: white; + color: black; + font-size: 16px; + font-family: sans-serif; + display: flex; + flex-direction: column; + user-select: none; + border: 1px solid #2B2F39; + border-radius: 5px; + padding-bottom: 5px; + max-height: 80vh; + overflow-y: auto; + overflow-x: hidden; + text-align: left; + max-width: 98%; + } + + #needcontext-container.without_title { + padding-top: 5px; + } + + #needcontext-title { + font-weight: bold; + padding-left: ${NeedContext.side_padding}; + padding-right: ${NeedContext.side_padding}; + background-color: rgba(67, 220, 255, 0.47); + padding-top: 4px; + padding-bottom: 4px; + margin-bottom: 2px; + display: flex; + flex-direction: row; + gap: ${NeedContext.gap}; + align-items: center; + justify-content: flex-start; + } + + #needcontext-filter { + opacity: 0; + } + + .needcontext-item { + white-space: nowrap; + display: flex; + flex-direction: row; + align-items: center; + gap: ${NeedContext.gap}; + } + + .needcontext-normal { + padding-left: ${NeedContext.side_padding}; + padding-right: ${NeedContext.side_padding}; + padding-top: ${NeedContext.item_sep}; + padding-bottom: ${NeedContext.item_sep}; + cursor: pointer; + } + + .needcontext-picked .needcontext-text { + text-decoration: line-through; + opacity: 0.7; + } + + .needcontext-button { + padding-left: ${NeedContext.side_padding}; + padding-right: ${NeedContext.side_padding}; + padding-top: ${NeedContext.item_sep}; + padding-bottom: ${NeedContext.item_sep}; + display: flex; + flex-direction: row; + align-items: center; + gap: ${NeedContext.gap}; + cursor: pointer; + } + + .needcontext-button:hover { + text-shadow: 0 0 1rem currentColor; + } + + .needcontext-separator { + border-top: 1px solid currentColor; + margin-left: ${NeedContext.side_padding}; + margin-right: ${NeedContext.side_padding}; + margin-top: ${NeedContext.item_sep}; + margin-bottom: ${NeedContext.item_sep}; + opacity: 0.7; + } + + .needcontext-item-selected { + background-color: rgba(0, 0, 0, 0.18); + } + + .needcontext-icon { + display: flex; + align-items: center; + justify-content: center; + } + + .needcontext-image { + width: 1.11rem; + height: 1.11rem; + object-fit: contain; + margin-right: 0.1rem; + } + + .needcontext-bold { + font-weight: bold; + } + ` + + style.innerText = css + document.head.appendChild(style) + + document.addEventListener(`mousedown`, (e) => { + if (!NeedContext.open || !e.target) { + return + } + + NeedContext.first_mousedown = true + + if (e.target.closest(`#needcontext-container`)) { + NeedContext.mousedown = true + } + }) + + document.addEventListener(`mouseup`, (e) => { + if (!NeedContext.open || !e.target) { + return + } + + if (!e.target.closest(`#needcontext-container`)) { + if (NeedContext.first_mousedown) { + NeedContext.dismiss(e) + } + } + else if (e.target.closest(`.needcontext-back`)) { + if (e.button === 0) { + NeedContext.go_back() + } + } + else if (e.target.closest(`.needcontext-clear`)) { + if (e.button === 0) { + NeedContext.clear_filter() + } + } + else if (NeedContext.mousedown) { + NeedContext.select_action(e) + } + + NeedContext.mousedown = false + }) + + document.addEventListener(`keydown`, (e) => { + if (!NeedContext.open) { + return + } + + if (NeedContext.modkey(e)) { + return + } + + NeedContext.keydown = true + + if (e.key === `ArrowUp`) { + NeedContext.select_next(`up`) + e.preventDefault() + } + else if (e.key === `ArrowDown`) { + NeedContext.select_next() + e.preventDefault() + } + else if (e.key === `Backspace`) { + if (!NeedContext.filtered) { + NeedContext.go_back() + e.preventDefault() + } + } + }) + + document.addEventListener(`keyup`, (e) => { + if (!NeedContext.open) { + return + } + + if (!NeedContext.keydown) { + return + } + + if (NeedContext.modkey(e)) { + return + } + + NeedContext.keydown = false + + if (e.key === `Escape`) { + NeedContext.dismiss(e) + e.preventDefault() + } + else if (e.key === `Enter`) { + NeedContext.select_action(e, undefined, `keyboard`) + e.preventDefault() + } + }) + + NeedContext.set_defaults() +} + +// Create elements +NeedContext.create = () => { + NeedContext.main = document.createElement(`div`) + NeedContext.main.id = `needcontext-main` + NeedContext.main.classList.add(`needcontext-hidden`) + NeedContext.container = document.createElement(`div`) + NeedContext.container.id = `needcontext-container` + NeedContext.filter = document.createElement(`input`) + NeedContext.filter.id = `needcontext-filter` + NeedContext.filter.type = `text` + NeedContext.filter.autocomplete = `off` + NeedContext.filter.spellcheck = false + NeedContext.filter.placeholder = `Filter` + + NeedContext.filter.addEventListener(`input`, (e) => { + NeedContext.do_filter() + }) + + NeedContext.main.addEventListener(`contextmenu`, (e) => { + e.preventDefault() + }) + + NeedContext.container.addEventListener(`dragstart`, (e) => { + NeedContext.dragging = true + NeedContext.dragstart_action(e) + }) + + NeedContext.container.addEventListener(`dragenter`, (e) => { + NeedContext.dragenter_action(e) + }) + + NeedContext.container.addEventListener(`dragend`, (e) => { + NeedContext.dragging = false + NeedContext.dragend_action(e) + }) + + NeedContext.main.append(NeedContext.filter) + NeedContext.main.append(NeedContext.container) + document.body.appendChild(NeedContext.main) + NeedContext.created = true +} + +// Drag start +NeedContext.dragstart_action = (e) => { + if (NeedContext) + NeedContext.dragged_item = e.target + let list = NeedContext.container + let items = Array.from(list.querySelectorAll(`.needcontext-item`)) + NeedContext.dragged_index = items.indexOf(e.target) +} + +// Drag enter +NeedContext.dragenter_action = (e) => { + let dragged = NeedContext.dragged_item + + if (dragged === e.target) { + return + } + + let list = NeedContext.container + let items = Array.from(list.querySelectorAll(`.needcontext-item`)) + let index_dragged = items.indexOf(dragged) + let index_target = items.indexOf(e.target) + + if ((index_dragged < 0) || (index_target < 0)) { + return + } + + if (index_dragged < index_target) { + list.insertBefore(dragged, e.target.nextSibling) + } + else { + list.insertBefore(dragged, e.target) + } + + NeedContext.select_item(index_target) +} + +// Drag end +NeedContext.dragend_action = (e) => { + let list = NeedContext.container + let dragged = NeedContext.dragged_item + let items = Array.from(list.querySelectorAll(`.needcontext-item`)) + let index_end = items.indexOf(dragged) + NeedContext.hide(e) + NeedContext.args.on_drag(NeedContext.dragged_index, index_end) +} + +// Current layer +NeedContext.get_layer = () => { + return NeedContext.layers[NeedContext.level] +} + +// Previous layer +NeedContext.prev_layer = () => { + return NeedContext.layers[NeedContext.level - 1] +} + +// Go back to previous layer +NeedContext.go_back = () => { + if (NeedContext.level === 0) { + return + } + + let layer = NeedContext.prev_layer() + NeedContext.level -= 1 + NeedContext.show({x: layer.x, y: layer.y, items: layer.items, root: layer.root}) +} + +// Create back button +NeedContext.back_button = () => { + let el = document.createElement(`div`) + el.id = `needcontext-back` + el.classList.add(`needcontext-back`) + el.classList.add(`needcontext-button`) + let icon = document.createElement(`div`) + icon.append(NeedContext.back_icon) + let text = document.createElement(`div`) + text.textContent = NeedContext.back_text.trim() + el.append(icon) + el.append(text) + el.title = `Shortcut: Backspace` + return el +} + +// Create clear button +NeedContext.clear_button = () => { + let el = document.createElement(`div`) + el.id = `needcontext-clear` + el.classList.add(`needcontext-clear`) + el.classList.add(`needcontext-button`) + el.classList.add(`needcontext-hidden`) + let icon = document.createElement(`div`) + icon.append(NeedContext.back_icon) + let text = document.createElement(`div`) + text.id = `needcontext-clear-text` + text.textContent = NeedContext.clear_text.trim() + el.append(icon) + el.append(text) + el.title = `Type to filter. Click to clear` + return el +} + +// Return true if a mod key is pressed +NeedContext.modkey = (e) => { + return e.ctrlKey || e.altKey || e.shiftKey || e.metaKey +} + +// Do an action +NeedContext.action = (item, e) => { + if (item.element) { + if (!NeedContext.is_visible(item.element)) { + return + } + + if (e.target.closest(`.needcontext-icon`)) { + if (item.icon_action) { + return + } + } + } + + let args = NeedContext.args + let after_action = NeedContext.args.after_action + + if (args.picker_mode) { + item.element.classList.add(`needcontext-picked`) + NeedContext.filter.focus() + item.picked = true + let all_picked = true + + for (let item of args.items) { + if (!item.picked) { + all_picked = false + break + } + } + + if (all_picked) { + NeedContext.hide(e) + } + } + else { + NeedContext.hide(e) + } + + item.action(e) + + if (after_action) { + after_action(e) + } +} + +// Dismissed by clicking the overlay or Escape +NeedContext.dismiss = (e) => { + if (NeedContext.args.after_dismiss) { + NeedContext.args.after_dismiss(e) + } + + NeedContext.hide(e) +} + +// Alternative action +NeedContext.alt_action = (item, e) => { + if (item.element) { + if (!NeedContext.is_visible(item.element)) { + return + } + } + + if (NeedContext.args.after_alt_action) { + NeedContext.args.after_alt_action(e) + } + + if (NeedContext.args.alt_action_remove) { + NeedContext.remove_item(item) + } + else { + NeedContext.hide(e) + } + + item.alt_action(e) +} + +// Context (right click) action +NeedContext.context_action = (item, e) => { + if (item.element) { + if (!NeedContext.is_visible(item.element)) { + return + } + } + + if (NeedContext.args.after_context_action) { + NeedContext.args.after_context_action(e) + } + + NeedContext.hide(e) + item.context_action(e) +} + +// Remove an item +NeedContext.remove_item = (item) => { + NeedContext.select_next(`down`, true) + item.removed = true + item.element.remove() + NeedContext.update_title() +} + +// Update the title +NeedContext.update_title = () => { + let title = document.querySelector(`#needcontext-title`) + + if (!title) { + return + } + + let number = title.querySelector(`.needcontext-title-number`) + + if (!number) { + return + } + + let num_items = NeedContext.count_items() + number.textContent = `(${num_items})` +} + +// Count the number of items +NeedContext.count_items = () => { + items = NeedContext.get_layer().normal_items + items = items.filter(x => !x.removed) + items = items.filter(x => !x.fake) + return items.length +} \ No newline at end of file diff --git a/server/static/dashboard/js/main/app.js b/server/static/dashboard/js/main/app.js new file mode 100644 index 0000000..b0da1a0 --- /dev/null +++ b/server/static/dashboard/js/main/app.js @@ -0,0 +1,81 @@ +const App = {} + +App.setup = () => { + NeedContext.init() + + Block.setup() + Curls.setup() + Colors.setup() + Infobar.setup() + Container.setup() + Select.setup() + Drag.setup() + Move.setup() + Update.setup() + Sort.setup() + Change.setup() + Picker.setup() + Status.setup() + Filter.setup() + Menu.setup() + More.setup() + Font.setup() + Border.setup() + Dates.setup() + Controls.setup() + Windows.setup() + Footer.setup() + Intro.setup() + Storage.setup() + + App.start_mouse() + App.update_autocomplete() + + Update.do_update() +} + +App.update_title = () => { + let color = Utils.capitalize(Colors.mode) + document.title = `Curls - ${color}` +} + +App.start_mouse = () => { + DOM.evs(DOM.el(`#main`), [`mousedown`], (e) => { + App.check_selection(e) + }) + + DOM.ev(window, `mouseup`, (e) => { + Select.mouseup() + }) +} + +App.update_autocomplete = () => { + let data_list = DOM.el(`#curls_datalist`) + data_list.innerHTML = `` + + for (let word of Curls.get_curls()) { + var option = document.createElement(`option`) + option.value = word + data_list.append(option) + } +} + +App.check_selection = (e) => { + if (e.ctrlKey || e.shiftKey) { + return + } + + if (e.button !== 0) { + return + } + + if (e.target.closest(`.item_icon`)) { + return + } + + if (e.target.closest(`#infobar_curls`)) { + return + } + + Select.deselect_all() +} \ No newline at end of file diff --git a/server/static/dashboard/js/main/block.js b/server/static/dashboard/js/main/block.js new file mode 100644 index 0000000..bafc0d9 --- /dev/null +++ b/server/static/dashboard/js/main/block.js @@ -0,0 +1,48 @@ +/* + +This is used to rate limit certain operations +Every operation adds 1 charge to a registered instance +If the charge is above the limit, the operation is blocked +Charges are decreased over time + +*/ + +class Block { + static instances = [] + static interval_delay = 2000 + static date_delay = 500 + static relief = 0.1 + + constructor(limit = 180) { + this.limit = limit + this.charge = 0 + this.date = 0 + Block.instances.push(this) + } + + static setup() { + setInterval(() => { + for (let block of Block.instances) { + if ((Utils.now() - block.date) < this.date_delay) { + continue + } + + if (block.charge > 0) { + let dec = Math.max(1, Math.round(block.charge * this.relief)) + block.charge -= parseInt(dec) + } + } + }, this.interval_delay) + } + + add_charge(num = 1) { + this.date = Utils.now() + + if (this.charge >= this.limit) { + return true + } + + this.charge += num + return false + } +} \ No newline at end of file diff --git a/server/static/dashboard/js/main/border.js b/server/static/dashboard/js/main/border.js new file mode 100644 index 0000000..8455fca --- /dev/null +++ b/server/static/dashboard/js/main/border.js @@ -0,0 +1,68 @@ +/* + +The border between the items of the container + +*/ + +class Border { + static default_mode = `solid` + static ls_name = `border` + + static modes = [ + {value: `solid`, name: `Solid`, info: `Normal solid border`}, + {value: `dotted`, name: `Dotted`, info: `Dotted border`}, + {value: `dashed`, name: `Dashed`, info: `Dashed border`}, + {value: Utils.separator}, + {value: `none`, name: `None`, info: `No border`}, + ] + + static setup() { + let border = DOM.el(`#border`) + this.mode = this.load_border() + + this.combo = new Combo({ + title: `Border Modes`, + items: this.modes, + value: this.mode, + element: border, + default: this.default_mode, + action: (value) => { + this.change(value) + this.apply() + }, + get: () => { + return this.mode + }, + }) + + this.apply() + } + + static change(value) { + this.mode = value + Utils.save(this.ls_name, value) + } + + static apply() { + let border + + if (this.mode === `solid`) { + border = `1px solid var(--color_alpha_2)` + } + else if (this.mode === `dotted`) { + border = `2px dotted var(--color_alpha_2)` + } + else if (this.mode === `dashed`) { + border = `2px dashed var(--color_alpha_2)` + } + else { + border = `none` + } + + document.documentElement.style.setProperty(`--border`, border) + } + + static load_border() { + return Utils.load_modes(this.ls_name, this.modes, this.default_mode) + } +} \ No newline at end of file diff --git a/server/static/dashboard/js/main/change.js b/server/static/dashboard/js/main/change.js new file mode 100644 index 0000000..051f136 --- /dev/null +++ b/server/static/dashboard/js/main/change.js @@ -0,0 +1,164 @@ +/* + +This changes the status of a curl + +*/ + +class Change { + static debouncer_delay = 250 + static changing = false + static clear_delay = 800 + static status_max_length = 500 + static key_length = 22 + + static setup() { + let curl = DOM.el(`#change_curl`) + let key = DOM.el(`#change_key`) + let submit = DOM.el(`#change_submit`) + + DOM.ev(submit, `click`, () => { + this.change() + }) + + this.debouncer = Utils.create_debouncer(() => { + this.do_change() + }, this.debouncer_delay) + + DOM.ev(curl, `keyup`, (e) => { + if (e.key === `Enter`) { + this.change() + } + }) + + DOM.ev(curl, `focus`, (e) => { + let value = curl.value + + if (value) { + Select.curl(value) + } + }) + + DOM.ev(curl, `blur`, (e) => { + Select.deselect_all() + }) + + DOM.ev(curl, `wheel`, (e) => { + Utils.scroll_wheel(e) + }) + + DOM.ev(key, `keyup`, (e) => { + if (e.key === `Enter`) { + this.change() + } + }) + + DOM.ev(key, `wheel`, (e) => { + Utils.scroll_wheel(e) + }) + } + + static change() { + this.debouncer.call() + } + + static do_change() { + this.debouncer.cancel() + Utils.info(`Change: Trigger`) + + if (this.changing) { + Utils.error(`Slow down`) + return + } + + let curl = DOM.el(`#change_curl`).value.toLowerCase() + let key = DOM.el(`#change_key`).value + let status = DOM.el(`#change_status`).value.trim() + + if (!curl || !key || !status) { + return + } + + if (curl.length > Curls.max_length) { + Utils.error(Utils.curl_too_long) + Windows.alert({title: `Error`, message: Utils.curl_too_long}) + return + } + + if (key.length > this.key_length) { + Utils.error(Utils.key_too_long) + Windows.alert({title: `Error`, message: Utils.key_too_long}) + return + } + + if (status.length > this.status_max_length) { + Utils.error(Utils.status_too_long) + Windows.alert({title: `Error`, message: Utils.status_too_long}) + return + } + + let url = `/change` + let params = new URLSearchParams() + + params.append(`curl`, curl) + params.append(`key`, key) + params.append(`status`, status) + + this.show_changing() + Status.save(status) + this.changing = true + Utils.info(`Change: Request ${Utils.network}`) + + fetch(url, { + method: `POST`, + headers: { + "Content-Type": `application/x-www-form-urlencoded` + }, + body: params, + }) + .then(response => response.text()) + .then(ans => { + Utils.info(`Response: ${ans}`) + this.clear_changing() + + if (ans === `ok`) { + this.clear_status() + Update.update({ curls: [curl] }) + Curls.add_owned(curl) + Picker.add() + } + else { + let lines = [ + `You might have hit the rate limit`, + `Or the curl and key you used are incorrect` + ] + + let msg = lines.join(`\n`) + Windows.alert({message: msg}) + } + }) + .catch(e => { + Utils.error(`Failed to change`) + Utils.error(e) + this.clear_changing() + }) + } + + static clear_status() { + DOM.el(`#change_status`).value = `` + } + + static show_changing() { + let button = DOM.el(`#change_submit`) + clearTimeout(this.clear_changing_timeout) + button.classList.add(`active`) + } + + static clear_changing() { + this.changing = false + + this.clear_changing_timeout = setTimeout(() => { + let button = DOM.el(`#change_submit`) + button.classList.remove(`active`) + }, this.clear_delay) + } +} \ No newline at end of file diff --git a/server/static/dashboard/js/main/colors.js b/server/static/dashboard/js/main/colors.js new file mode 100644 index 0000000..0d8a0e4 --- /dev/null +++ b/server/static/dashboard/js/main/colors.js @@ -0,0 +1,188 @@ +/* + +Color functions + +*/ + +class Colors { + static default_mode = `green` + static ls_name = `color` + static alpha_0 = {} + static alpha_1 = {} + static alpha_2 = {} + + static modes = [ + {value: `green`, name: `Green`, info: `Go to Green`, icon: `🟢`}, + {value: `blue`, name: `Blue`, info: `Go to Blue`, icon: `🔵`}, + {value: `red`, name: `Red`, info: `Go to Red`, icon: `🔴`}, + {value: `yellow`, name: `Yellow`, info: `Go to Yellow`, icon: `🟡`}, + {value: `purple`, name: `Purple`, info: `Go to Purple`, icon: `🟣`}, + {value: `white`, name: `White`, info: `Go to White`, icon: `⚪`}, + ] + + static colors = { + red: `rgb(255, 89, 89)`, + green: `rgb(87, 255, 87)`, + blue: `rgb(118, 120, 255)`, + yellow: `rgb(255, 219, 78)`, + purple: `rgb(193, 56, 255)`, + white: `rgb(255, 255, 255)`, + } + + static setup() { + let color = DOM.el(`#color`) + this.mode = this.load_color() + + this.combo = new Combo({ + title: `Color Modes`, + items: this.modes, + value: this.mode, + element: color, + default: this.default_mode, + action: (value) => { + this.change(value) + }, + get: () => { + return this.mode + }, + extra_title: `Ctrl Left/Right to cycle`, + }) + + this.make_alpha(this.alpha_0, `0.055`) + this.make_alpha(this.alpha_1, `0.18`) + this.make_alpha(this.alpha_2, `0.5`) + + this.apply() + } + + static make_alpha(obj, a) { + for (let color in this.colors) { + let numbers = this.colors[color].match(/\d+/g) + let rgba = `rgba(${numbers[0]}, ${numbers[1]}, ${numbers[2]}, ${a})` + obj[color] = rgba + } + } + + static set_value(value) { + if (this.mode === value) { + return + } + + this.combo.set_value(value) + } + + static change(value) { + if (this.mode === value) { + return + } + + this.mode = value + Utils.save(this.ls_name, value) + this.apply() + Items.reset() + Container.show_loading() + Infobar.hide() + Update.update() + } + + static load_color() { + return Utils.load_modes(this.ls_name, this.modes, this.default_mode) + } + + static apply() { + let normal = this.colors[this.mode] + + let alpha_0 = this.alpha_0[this.mode] + let alpha_1 = this.alpha_1[this.mode] + let alpha_2 = this.alpha_2[this.mode] + + document.documentElement.style.setProperty(`--color`, normal) + document.documentElement.style.setProperty(`--color_alpha_0`, alpha_0) + document.documentElement.style.setProperty(`--color_alpha_1`, alpha_1) + document.documentElement.style.setProperty(`--color_alpha_2`, alpha_2) + + App.update_title() + } + + static move(curls, e) { + let items = [] + + let add = (mode) => { + if (this.mode === mode.value) { + return + } + + items.push({ + text: mode.name, + action: () => { + this.do_move(mode.value, curls) + }, + icon: mode.icon, + }) + } + + for (let key in this.modes) { + add(this.modes[key]) + } + + Utils.context({items: items, e: e}) + } + + static do_move(color, curls) { + let current = Curls.get_curls() + let cleaned = [] + + for (let curl of current) { + if (!curls.includes(curl)) { + cleaned.push(curl) + } + } + + let cleaned_items = [] + + for (let item of Items.list) { + if (!curls.includes(item.curl)) { + cleaned_items.push(item) + } + } + + Items.list = cleaned_items + Curls.save_curls(cleaned) + let new_curls = Curls.get_curls(color) + + for (let curl of curls) { + if (new_curls.includes(curl)) { + continue + } + + new_curls.unshift(curl) + } + + Curls.save_curls(new_curls, color) + Container.update() + } + + static prev() { + let index = this.modes.findIndex(x => x.value === this.mode) + let prev = index - 1 + + if (prev < 0) { + prev = this.modes.length - 1 + } + + let value = this.modes[prev].value + this.set_value(value) + } + + static next() { + let index = this.modes.findIndex(x => x.value === this.mode) + let next = index + 1 + + if (next >= this.modes.length) { + next = 0 + } + + let value = this.modes[next].value + this.set_value(value) + } +} \ No newline at end of file diff --git a/server/static/dashboard/js/main/combo.js b/server/static/dashboard/js/main/combo.js new file mode 100644 index 0000000..a26c1f8 --- /dev/null +++ b/server/static/dashboard/js/main/combo.js @@ -0,0 +1,130 @@ +/* + +This is a button widget +It can be used to cycle through a list of items +It uses NeedContext to show the menu +It's similar to a select widget + +*/ + +class Combo { + constructor(args) { + this.args = args + this.prepare() + } + + prepare() { + DOM.evs(this.args.element, [`click`, `contextmenu`], (e) => { + this.show_menu(e) + e.preventDefault() + }) + + DOM.ev(this.args.element, `auxclick`, (e) => { + if (e.button === 1) { + this.reset() + } + }) + + DOM.ev(this.args.element, `wheel`, (e) => { + let direction = Utils.wheel_direction(e) + this.cycle(direction) + e.preventDefault() + }) + + let lines = [ + this.args.title, + `Click to pick option`, + `Wheel to cycle option`, + `Middle Click to reset`, + ] + + this.args.element.title = lines.join(`\n`) + + if (this.args.extra_title) { + this.args.element.title += `\n${this.args.extra_title}` + } + + this.block = new Block() + this.update_text() + } + + get_item() { + return this.args.items.find(x => x.value === this.args.get()) + } + + update_text() { + let item = this.get_item(this.args) + this.args.element.textContent = item.name + } + + show_menu(e) { + let items = [] + let current = this.args.get() + + for (let item of this.args.items) { + if (item.value === Utils.separator) { + items.push({ separator: true }) + } + else { + items.push({ + text: item.name, + action: () => { + this.action(item.value) + }, + selected: item.value === current, + info: item.info, + icon: item.icon, + }) + } + } + + Utils.context({ items: items, e: e, input: this.args.input }) + } + + action(value) { + this.args.action(value) + this.update_text() + } + + reset() { + this.action(this.args.default) + } + + get_values() { + return this.args.items + .filter(x => x.value !== Utils.separator) + .filter(x => !x.skip) + .map(x => x.value) + } + + cycle(direction) { + if (this.block.add_charge()) { + return + } + + let value = this.args.get() + let values = this.get_values(this.args) + let index = values.indexOf(value) + + if (direction === `up`) { + index -= 1 + } + else if (direction === `down`) { + index += 1 + } + + if (index < 0) { + index = values.length - 1 + } + else if (index >= values.length) { + index = 0 + } + + let new_value = values[index] + this.action(new_value) + } + + set_value(value) { + this.action(value) + } +} \ No newline at end of file diff --git a/server/static/dashboard/js/main/container.js b/server/static/dashboard/js/main/container.js new file mode 100644 index 0000000..c77c67e --- /dev/null +++ b/server/static/dashboard/js/main/container.js @@ -0,0 +1,452 @@ +/* + +This is the main container widget with the vertical items +Most action happens here + +*/ + +class Container { + static wrap_enabled = true + static ls_wrap = `wrap_enabled` + static scroll_step = 100 + + static setup() { + this.empty_info = [ + `Add some curls to the list by using the menu.`, + `These will be monitored for status changes.`, + `Above you can change the status of your own curls.`, + `Each color has its own set of curls.`, + ].join(`
`) + + let outer = this.get_outer() + let container = this.get_container() + + DOM.ev(container, `mousedown`, (e) => { + if (e.ctrlKey || e.shiftKey) { + e.preventDefault() + } + }) + + DOM.ev(container, `click`, (e) => { + let item = this.extract_item(e) + + if (!item) { + return + } + + if (this.extract_updated(e)) { + Dates.change_mode() + return + } + + this.focus() + let is_icon = this.extract_icon(e) + + if (e.shiftKey) { + Select.range(item) + e.preventDefault() + } + else if (e.ctrlKey) { + Select.toggle(item) + e.preventDefault() + } + else { + if (is_icon) { + Select.single(item) + e.preventDefault() + } + } + }) + + DOM.ev(container, `auxclick`, (e) => { + let item = this.extract_item(e) + + if (!item) { + return + } + + if (e.button == 1) { + let curl = this.extract_curl(item) + Select.check(item) + Curls.remove_selected(curl) + } + }) + + DOM.ev(container, `contextmenu`, (e) => { + let item = this.extract_item(e) + + if (!item) { + return + } + + let curl = this.extract_curl(item) + Select.check(item) + Items.show_menu({curl: curl, e: e}) + e.preventDefault() + }) + + DOM.ev(outer, `contextmenu`, (e) => { + let item = this.extract_item(e) + e.preventDefault() + + if (item) { + return + } + + Menu.show(e) + }) + + DOM.ev(outer, `click`, (e) => { + this.focus() + }) + + DOM.ev(outer, `mousedown`, (e) => { + Select.mousedown(e) + }) + + DOM.ev(outer, `mouseup`, () => { + Select.mouseup() + }) + + DOM.ev(outer, `mouseover`, (e) => { + Select.mouseover(e) + }) + + this.wrap_enabled = this.load_wrap_enabled() + this.setup_keyboard() + this.focus() + } + + static clear() { + let container = this.get_container() + container.innerHTML = `` + } + + static show_empty() { + Infobar.hide() + this.set_info(this.empty_info) + } + + static check_empty() { + let els = this.get_items() + + if (!els || !els.length) { + this.show_empty() + } + } + + static show_loading() { + this.set_info(`Loading...`) + } + + static set_info(info) { + let container = this.get_container() + let item = DOM.create(`div`, `info_item`) + item.innerHTML = info + container.innerHTML = `` + container.append(item) + Utils.deselect() + } + + static get_items() { + return DOM.els(`#container .item`) + } + + static scroll_top() { + let item = this.get_items()[0] + Utils.scroll_element({item: item, behavior: `smooth`, block: `center`}) + } + + static scroll_bottom() { + let item = Utils.last(this.get_items()) + Utils.scroll_element({item: item, behavior: `smooth`, block: `center`}) + } + + static save_wrap_enabled() { + Utils.save(this.ls_wrap, this.wrap_enabled) + } + + static load_wrap_enabled() { + return Utils.load_boolean(this.ls_wrap) + } + + static add(items, curls) { + let normal = Items.list.filter(item => !item.missing) + Items.list = [...items] + + for (let item of normal) { + if (Items.list.find(x => x.curl === item.curl)) { + continue + } + + Items.list.push(item) + } + + let missing = Items.find_missing() + Items.list.push(...missing) + Items.fill() + this.update({select: curls}) + } + + static insert(items) { + Items.list = items + Items.list.map(x => x.missing = false) + let missing = Items.find_missing() + Items.list.push(...missing) + Items.fill() + this.update() + } + + static update(args = {}) { + let def_args = { + items: Items.list, + check_filter: true, + select: [], + } + + Utils.def_args(def_args, args) + Utils.info(`Updating Container`) + this.clear() + Sort.sort(args.items) + + for (let item of args.items) { + this.create_element(item) + } + + Utils.deselect() + this.check_empty() + + if (args.check_filter) { + Filter.check() + } + + if (args.select.length) { + Select.curls(args.select) + } + + Infobar.update() + } + + static create_element(item) { + let container = this.get_container() + let el = DOM.create(`div`, `item`) + let item_icon = DOM.create(`div`, `item_icon`) + item_icon.draggable = true + + let lines = [ + `Click to select`, + `Ctrl Click to toggle`, + `Shift Click to select range`, + `Middle Click to remove`, + `Drag to reorder`, + ] + + item_icon.title = lines.join(`\n`) + + let canvas = DOM.create(`canvas`, `item_icon_canvas`) + jdenticon.update(canvas, item.curl) + item_icon.append(canvas) + + let item_curl = DOM.create(`div`, `item_curl`) + let item_status = DOM.create(`div`, `item_status`) + + if (!this.wrap_enabled) { + item_status.classList.add(`nowrap`) + } + + item_curl.textContent = item.curl + item_curl.title = item.curl + let status = item.status || `Not updated yet` + item_status.innerHTML = Utils.sanitize(status) + Utils.urlize(item_status) + let item_updated = DOM.create(`div`, `item_updated glow`) + + let dates = [ + `Updated: ${item.updated_text}`, + `Added: ${item.added_text}`, + `Created: ${item.created_text}`, + ] + + let date_text = dates.join(`\n`) + + if (Dates.enabled) { + item_status.title = status + + if (item.missing) { + item_updated.textContent = `No Date` + item_updated.title = `No date information available` + } + else { + item_updated.textContent = item.updated_text + + let lines_2 = [ + date_text, + `Click to toggle between 12 and 24 hours`, + ] + + item_updated.title = lines_2.join(`\n`) + } + } + else { + item_status.title = `${status}\n${date_text}` + item_updated.classList.add(`hidden`) + } + + if (!item.missing) { + item_status.title += `\nChanges: ${item.changes}` + } + + el.append(item_icon) + el.append(item_curl) + el.append(item_status) + el.append(item_updated) + + el.dataset.curl = item.curl + el.dataset.selected_id = 0 + + container.append(el) + container.append(el) + + item.element = el + } + + static extract_curl(item) { + return item.dataset.curl + } + + static setup_keyboard() { + let container = this.get_container() + + DOM.ev(container, `keydown`, (e) => { + if (e.key === `Delete`) { + Curls.remove_selected() + e.preventDefault() + } + else if (e.key === `ArrowUp`) { + if (e.ctrlKey) { + Move.up() + } + else { + Select.vertical(`up`, e.shiftKey) + } + + e.preventDefault() + } + else if (e.key === `ArrowDown`) { + if (e.ctrlKey) { + Move.down() + } + else { + Select.vertical(`down`, e.shiftKey) + } + + e.preventDefault() + } + else if (e.key === `ArrowLeft`) { + if (e.ctrlKey) { + Colors.prev() + e.preventDefault() + } + } + else if (e.key === `ArrowRight`) { + if (e.ctrlKey) { + Colors.next() + e.preventDefault() + } + } + else if (e.key === `Escape`) { + Select.deselect_all() + e.preventDefault() + } + else if (e.key === `a`) { + if (e.ctrlKey) { + Select.all() + e.preventDefault() + } + } + }) + } + + static is_visible(item) { + return !item.classList.contains(`hidden`) + } + + static get_visible() { + let items = this.get_items() + return items.filter(x => this.is_visible(x)) + } + + static get_curls() { + let items = this.get_items() + return items.map(item => Container.extract_curl(item)) + } + + static get_item(curl) { + let items = this.get_items() + return items.find(x => x.dataset.curl === curl) + } + + static focus() { + this.get_container().focus() + } + + static get_outer() { + return DOM.el(`#container_outer`) + } + + static get_container() { + return DOM.el(`#container`) + } + + static extract_item(e) { + return e.target.closest(`.item`) + } + + static extract_icon(e) { + return e.target.closest(`.item_icon`) + } + + static extract_updated(e) { + return e.target.closest(`.item_updated`) + } + + static scroll_up() { + let outer = this.get_outer() + outer.scrollBy(0, -this.scroll_step) + } + + static scroll_down() { + let outer = this.get_outer() + outer.scrollBy(0, this.scroll_step) + } + + static scroller() { + let outer = this.get_outer() + let height = outer.clientHeight + let scroll = outer.scrollHeight + let scrolltop = outer.scrollTop + + if (scrolltop < (scroll - height)) { + this.scroll_bottom() + } + else { + this.scroll_top() + } + } + + static scroll(e) { + let direction = Utils.wheel_direction(e) + + if (direction === `up`) { + Container.scroll_up() + } + else { + Container.scroll_down() + } + } + + static save_curls() { + let curls = Container.get_curls() + return Curls.save_curls(curls) + } +} \ No newline at end of file diff --git a/server/static/dashboard/js/main/controls.js b/server/static/dashboard/js/main/controls.js new file mode 100644 index 0000000..140b73f --- /dev/null +++ b/server/static/dashboard/js/main/controls.js @@ -0,0 +1,32 @@ +/* + +This shows or hides the controls + +*/ + +class Controls { + static enabled = true + static ls_name = `controls_enabled` + + static setup() { + this.enabled = this.load_enabled() + this.check_enabled() + } + + static save_enabled() { + Utils.save(this.ls_name, this.enabled) + } + + static load_enabled() { + return Utils.load_boolean(this.ls_name) + } + + static check_enabled() { + if (this.enabled) { + DOM.show(`#controls`) + } + else { + DOM.hide(`#controls`) + } + } +} \ No newline at end of file diff --git a/server/static/dashboard/js/main/curls.js b/server/static/dashboard/js/main/curls.js new file mode 100644 index 0000000..d724034 --- /dev/null +++ b/server/static/dashboard/js/main/curls.js @@ -0,0 +1,521 @@ +/* + +These are curl operations +This takes care of storing curl data + +*/ + +class Curls { + static max_curls = 100 + static max_length = 20 + static old_delay = Utils.YEAR * 1 + static colors = {} + + static setup() { + this.fill_colors() + } + + static fill_colors() { + for (let color in Colors.colors) { + this.colors[color] = this.load_curls(color) + + if (this.fill(this.colors[color])) { + this.save(this.colors[color], color, true) + } + } + } + + static add() { + Windows.prompt({title: `Add Curls`, callback: (value) => { + this.add_submit(value) + }, message: `Enter one or more curls`}) + } + + static add_submit(curls) { + if (!curls) { + return + } + + let added = Utils.smart_list(curls) + + if (!added.length) { + return + } + + this.prepend(added) + } + + static prepend(added) { + added = added.filter(x => this.check(x)) + + if (!added.length) { + return + } + + let curls = this.get_curls() + let new_curls = Array.from(new Set([...added, ...curls])) + + if (this.save_curls(new_curls)) { + added.reverse() + Update.update({ curls: added }) + } + } + + static new_item(curl) { + return { + curl: curl, + added: this.default_added(), + } + } + + static add_owned(curl) { + let curls = this.get_curls() + + if (curls.includes(curl)) { + return + } + + this.prepend([curl]) + } + + static to_top(curls) { + let cleaned = [...curls] + + for (let curl of this.get_curls()) { + if (cleaned.includes(curl)) { + continue + } + + cleaned.push(curl) + } + + this.after_move(cleaned, curls) + } + + static to_bottom(curls) { + let cleaned = [] + + for (let curl of this.get_curls()) { + if (cleaned.includes(curl)) { + continue + } + + if (curls.includes(curl)) { + continue + } + + cleaned.push(curl) + } + + cleaned.push(...curls) + this.after_move(cleaned, curls) + } + + static after_move(new_curls, curls) { + this.save_curls(new_curls) + Sort.set_value(`order`) + Sort.sort_if_order() + Select.deselect_all() + + for (let curl of curls) { + Select.curl(curl) + } + } + + static save(items, color = Colors.mode, force = false) { + items = this.clean(items) + let same = true + let current = this.get(color) + + if (current.length !== items.length) { + same = false + } + + if (same) { + for (let i = 0; i < current.length; i++) { + if (current[i].curl !== items[i].curl) { + same = false + break + } + } + } + + if (same && !force) { + return false + } + + let name = this.get_name(color) + this.colors[color] = [...items] + Utils.save(name, JSON.stringify(items)) + return true + } + + static default_added() { + return Utils.now() + } + + static fill(items) { + let filled = false + + for (let item of items) { + if (item.added === undefined) { + item.added = this.default_added() + filled = true + } + } + + return filled + } + + static get(color = Colors.mode) { + return this.colors[color] + } + + static get_curls(color = Colors.mode) { + return this.get(color).map(x => x.curl) + } + + static load_curls(color = Colors.mode) { + let name = this.get_name(color) + let saved = Utils.load_array(name) + return this.clean(saved) + } + + static replace() { + Windows.prompt({title: `Replace Curls`, callback: (value) => { + this.replace_submit(value) + }, message: `Replace the entire list with this`}) + } + + static replace_submit(curls) { + if (!curls) { + return + } + + let units = curls.split(` `).filter(x => x) + + if (!units.length) { + return + } + + this.clear() + let added = [] + + for (let curl of units) { + if (this.check(curl)) { + added.push(curl) + } + } + + if (added) { + if (this.save_curls(added)) { + Update.update() + } + } + } + + static clear(color = Colors.mode) { + this.save([], color) + } + + static edit(curl) { + Windows.prompt({title: `Edit Curl`, callback: (value) => { + this.edit_submit(curl, value) + }, value: curl, message: `Change the name of this curl`}) + } + + static edit_submit(curl, new_curl) { + if (!new_curl) { + return + } + + this.do_edit(curl, new_curl) + } + + static do_edit(curl, new_curl) { + if (!this.check(new_curl)) { + return + } + + if (curl === new_curl) { + return + } + + let curls = this.get_curls().slice() + let index = curls.indexOf(curl) + + if (index === -1) { + return + } + + curls[index] = new_curl + + if (this.save_curls(curls)) { + Items.remove_curl(curl) + Update.update({ curls: [new_curl] }) + } + } + + static check(curl) { + if (!curl) { + return false + } + + if (curl.length > this.max_length) { + return false + } + + if (!/^[a-zA-Z0-9]+$/.test(curl)) { + return false + } + + return true + } + + static clean(items) { + let cleaned = [] + + for (let item of items) { + if (cleaned.some(x => x.curl === item.curl)) { + continue + } + + if (!this.check(item.curl)) { + continue + } + + cleaned.push(item) + + if (cleaned.length >= this.max_curls) { + break + } + } + + return cleaned + } + + static get_name(color) { + return `curls_${color}` + } + + static remove(curls) { + let cleaned = [] + let removed = [] + + for (let curl of this.get_curls()) { + if (!curls.includes(curl)) { + cleaned.push(curl) + } + else { + removed.push(curl) + } + } + + if (!removed.length) { + return + } + + this.save_cleaned(cleaned, removed) + } + + static remove_selected(curl = ``) { + let curls = Select.get_curls() + + if (curl) { + if (!curls.includes(curl)) { + curls = [curl] + } + } + + this.remove(curls) + } + + static remove_all() { + Windows.confirm({title: `Remove All Curls`, ok: () => { + this.clear() + Container.show_empty() + }, message: `Remove all curls in the current color`}) + } + + static show_remove_menu(e) { + let items = [ + { + text: `Remove One`, + action: () => { + this.remove_one() + } + }, + { + text: `Remove Not Found`, + action: () => { + this.remove_not_found() + } + }, + { + text: `Remove Empty`, + action: () => { + this.remove_empty() + } + }, + { + text: `Remove Old`, + action: () => { + this.remove_old() + } + }, + { + text: `Remove All`, + action: () => { + this.remove_all() + } + }, + ] + + Utils.context({items: items, e: e}) + } + + static remove_one() { + Windows.prompt({title: `Remove Curl`, callback: (value) => { + this.remove_one_submit(value) + }, message: `Enter the curl to remove`}) + } + + static remove_one_submit(curl) { + if (!curl) { + return + } + + this.do_remove(curl) + } + + static do_remove(curl, remove_item = true) { + let cleaned = [] + + for (let curl_ of this.get_curls()) { + if (curl_ !== curl) { + cleaned.push(curl_) + } + } + + this.save_curls(cleaned) + + if (remove_item) { + Items.remove([curl]) + } + } + + static remove_not_found() { + let missing = Items.get_missing().map(x => x.curl) + let cleaned = [] + let removed = [] + + for (let curl of this.get_curls()) { + if (!missing.includes(curl)) { + cleaned.push(curl) + } + else { + removed.push(curl) + } + } + + if (!removed.length) { + return + } + + this.save_cleaned(cleaned, removed) + } + + static remove_empty() { + let cleaned = [] + let removed = [] + + for (let curl of this.get_curls()) { + let item = Items.get(curl) + + if (!item) { + continue + } + + if (!item.status) { + removed.push(curl) + continue + } + + cleaned.push(curl) + } + + if (!removed.length) { + return + } + + this.save_cleaned(cleaned, removed) + } + + static remove_old() { + let now = Utils.now() + let cleaned = [] + let removed = [] + + for (let curl of this.get_curls()) { + let item = Items.get(curl) + + if (!item) { + continue + } + + let date = item.updated + + if (date) { + let datetime = new Date(date + `Z`).getTime() + + if ((now - datetime) > (this.old_delay)) { + removed.push(curl) + continue + } + } + + cleaned.push(curl) + } + + if (!removed.length) { + return + } + + this.save_cleaned(cleaned, removed) + } + + static save_cleaned(cleaned, removed) { + let s = Utils.plural(removed.length, `Curl`, `Curls`) + let curls = removed.join(`, `) + + Windows.confirm({title: `Remove ${removed.length} ${s}`, ok: () => { + this.save_curls(cleaned) + Items.remove(removed) + }, message: curls}) + } + + static copy() { + let curls = this.get_curls() + let text = curls.join(` `) + Utils.copy_to_clipboard(text) + } + + static save_curls(curls, color = Colors.mode) { + let current = this.get(color) + let items = [] + + for (let curl of curls) { + let item = current.find(x => x.curl === curl) + + if (item) { + items.push(item) + } + else { + item = this.new_item(curl) + items.push(item) + } + } + + return this.save(items, color) + } +} \ No newline at end of file diff --git a/server/static/dashboard/js/main/dates.js b/server/static/dashboard/js/main/dates.js new file mode 100644 index 0000000..c2e9eff --- /dev/null +++ b/server/static/dashboard/js/main/dates.js @@ -0,0 +1,80 @@ +/* + +This manages the dates shown in the container + +*/ + +class Dates { + static ls_mode = `date_mode` + static ls_enabled = `date_enabled` + static default_mode = `12` + + static setup() { + this.mode = this.load_mode() + this.enabled = this.load_enabled() + } + + static change_mode() { + let selected = window.getSelection().toString() + + if (selected) { + return + } + + this.mode = this.mode === `12` ? `24` : `12` + Utils.save(this.ls_mode, this.mode) + Items.fill() + Container.update() + } + + static load_mode() { + return Utils.load_string(this.ls_mode, this.default_mode) + } + + static save_enabled() { + Utils.save(this.ls_enabled, this.enabled) + } + + static load_enabled() { + return Utils.load_boolean(this.ls_enabled) + } + + static fill(item) { + // Updated + let date = new Date(item.updated + `Z`) + let s_date + + if (this.mode === `12`) { + s_date = dateFormat(date, `dd/mmm/yy - h:MM tt`) + } + else if (this.mode === `24`) { + s_date = dateFormat(date, `dd/mmm/yy - HH:MM`) + } + + item.updated_text = s_date + + // Created + date = new Date(item.created + `Z`) + + if (this.mode === `12`) { + s_date = dateFormat(date, `dd/mmm/yy - h:MM tt`) + } + else if (this.mode === `24`) { + s_date = dateFormat(date, `dd/mmm/yy - HH:MM`) + } + + item.created_text = s_date + + // Added + date = new Date(item.added + `Z`) + + if (this.mode === `12`) { + s_date = dateFormat(item.added, `dd/mmm/yy - h:MM tt`) + } + else if (this.mode === `24`) { + s_date = dateFormat(item.added, `dd/mmm/yy - HH:MM`) + } + + item.added_text = s_date + } +} \ No newline at end of file diff --git a/server/static/dashboard/js/main/drag.js b/server/static/dashboard/js/main/drag.js new file mode 100644 index 0000000..f7fc258 --- /dev/null +++ b/server/static/dashboard/js/main/drag.js @@ -0,0 +1,74 @@ +/* + +Controls dragging of items in the container + +*/ + +class Drag { + static drag_items = [] + static drag_y = 0 + + static setup() { + let container = Container.get_container() + + DOM.ev(container, `dragstart`, (e) => { + this.drag_start(e) + }) + + DOM.ev(container, `dragenter`, (e) => { + this.drag_enter(e) + }) + + DOM.ev(container, `dragend`, (e) => { + this.drag_end(e) + }) + } + + static drag_start(e) { + let item = Container.extract_item(e) + let curl = Container.extract_curl(item) + this.drag_y = e.clientY + + e.dataTransfer.setData(`text`, curl) + e.dataTransfer.setDragImage(new Image(), 0, 0) + + let selected = Select.get() + + if (selected.length && selected.includes(item)) { + this.drag_items = selected + } + else { + if (!selected.includes(item)) { + Select.single(item) + } + + this.drag_items = [item] + } + } + + static drag_enter(e) { + let items = Container.get_items() + let item = Container.extract_item(e) + let index = items.indexOf(item) + + if (index === -1) { + return + } + + let direction = (e.clientY > this.drag_y) ? `down` : `up` + this.drag_y = e.clientY + + if (direction === `up`) { + item.before(...this.drag_items) + } + else if (direction === `down`) { + item.after(...this.drag_items) + } + } + + static drag_end(e) { + if (Container.save_curls()) { + Sort.set_value(`order`) + } + } +} \ No newline at end of file diff --git a/server/static/dashboard/js/main/filter.js b/server/static/dashboard/js/main/filter.js new file mode 100644 index 0000000..1a269c9 --- /dev/null +++ b/server/static/dashboard/js/main/filter.js @@ -0,0 +1,278 @@ +/* + +This is the filter for the container + +*/ + +class Filter { + static debouncer_delay = 250 + static default_mode = `all` + static timeout_delay = Utils.SECOND * 3 + static ls_items = `filter_items` + static max_items = 100 + + static modes = [ + { value: `all`, name: `All`, info: `Show all curls` }, + { value: Utils.separator }, + { value: `today`, name: `Today`, info: `Show the curls that changed today` }, + { value: `week`, name: `Week`, info: `Show the curls that changed this week` }, + { value: `month`, name: `Month`, info: `Show the curls that changed this month` }, + { value: Utils.separator }, + { value: `curl`, name: `Curl`, info: `Filter by curl` }, + { value: `status`, name: `Status`, info: `Filter by status` }, + { value: `date`, name: `Date`, info: `Filter by date` }, + { value: Utils.separator }, + { value: `owned`, name: `Owned`, info: `Show the curls that you control` }, + ] + + static setup() { + let filter = this.get_filter() + + DOM.ev(filter, `keydown`, (e) => { + this.filter() + }) + + this.debouncer = Utils.create_debouncer(() => { + this.do_filter() + }, this.debouncer_delay) + + filter.value = `` + + let lines = [ + `Filter the items`, + `Press Escape to clear`, + ] + + filter.title = lines.join(`\n`) + let modes_button = DOM.el(`#filter_modes`) + this.mode = this.default_mode + + this.combo = new Combo({ + title: `Filter Modes`, + items: this.modes, + value: this.filer_mode, + element: modes_button, + default: this.default_mode, + input: filter, + action: (value) => { + this.change(value) + }, + get: () => { + return this.mode + }, + }) + + let button = DOM.el(`#filter_button`) + + DOM.ev(filter, `wheel`, (e) => { + Utils.scroll_wheel(e) + }) + + this.list = new List( + button, + filter, + this.ls_items, + this.max_items, + (value) => { + this.action(value) + }, + () => { + this.clear() + }, + ) + } + + static change(value) { + if (this.mode === value) { + return + } + + this.mode = value + this.do_filter() + } + + static unfilter() { + let els = DOM.els(`#container .item`) + + if (!els.length) { + return + } + + for (let el of els) { + DOM.show(el) + } + + this.after() + } + + static clear() { + this.get_filter().value = `` + this.unfilter() + } + + static filter() { + this.debouncer.call() + } + + static do_filter() { + this.debouncer.cancel() + let els = Container.get_items() + + if (!els.length) { + return + } + + let value = this.get_value() + let is_special = false + let special = [] + let scope = `all` + + if (this.mode === `owned`) { + special = Items.get_owned() + is_special = true + } + else if (this.mode === `today`) { + special = Items.get_today() + is_special = true + } + else if (this.mode === `week`) { + special = Items.get_week() + is_special = true + } + else if (this.mode === `month`) { + special = Items.get_month() + is_special = true + } + else if (this.mode === `curl`) { + scope = `curl` + is_special = true + } + else if (this.mode === `status`) { + scope = `status` + is_special = true + } + else if (this.mode === `date`) { + scope = `date` + is_special = true + } + + if (!value && !is_special) { + this.unfilter() + return + } + + if ((scope !== `all`) && !value) { + this.unfilter() + return + } + + let check = (curl, status, updated) => { + return curl.includes(value) || status.includes(value) || updated.includes(value) + } + + let hide = (el) => { + DOM.hide(el) + } + + let show = (el) => { + DOM.show(el) + } + + for (let el of els) { + let item = Items.get(el.dataset.curl) + let curl = item.curl.toLowerCase() + let status = item.status.toLowerCase() + let updated = item.updated_text.toLowerCase() + + if (scope === `curl`) { + if (curl.includes(value)) { + show(el) + } + else { + hide(el) + } + } + else if (scope === `status`) { + if (status.includes(value)) { + show(el) + } + else { + hide(el) + } + } + else if (scope === `date`) { + if (updated.includes(value)) { + show(el) + } + else { + hide(el) + } + } + else if (is_special) { + if (special.find(s => s.curl === item.curl)) { + if (check(curl, status, updated)) { + show(el) + } + else { + hide(el) + } + } + else { + hide(el) + } + } + else { + if (check(curl, status, updated)) { + show(el) + } + else { + hide(el) + } + } + } + + this.after() + } + + static check() { + let filter = this.get_filter() + + if (filter.value || (this.mode !== this.default_mode)) { + this.do_filter() + } + } + + static after() { + clearTimeout(this.timeout) + + this.timeout = setTimeout(() => { + this.save() + }, this.timeout_delay) + + Infobar.update_curls() + } + + static save() { + let value = this.get_value() + this.list.save(value) + } + + static get_items() { + return Utils.load_array(this.ls_items) + } + + static get_value() { + return this.get_filter().value.toLowerCase().trim() + } + + static get_filter() { + return DOM.el(`#filter`) + } + + static action(value) { + let filter = this.get_filter() + filter.value = value + filter.focus() + this.filter() + } +} \ No newline at end of file diff --git a/server/static/dashboard/js/main/font.js b/server/static/dashboard/js/main/font.js new file mode 100644 index 0000000..8ebfe4f --- /dev/null +++ b/server/static/dashboard/js/main/font.js @@ -0,0 +1,52 @@ +/* + +The font of the interface + +*/ + +class Font { + static default_mode = `sans-serif` + static ls_name = `font` + + static modes = [ + {value: `sans-serif`, name: `Sans`, info: `Use Sans-Serif as the font`}, + {value: `serif`, name: `Serif`, info: `Use Serif as the font`}, + {value: `monospace`, name: `Mono`, info: `Use Monospace as the font`}, + {value: `cursive`, name: `Cursive`, info: `Use Cursive as the font`}, + ] + + static setup() { + let font = DOM.el(`#font`) + this.mode = this.load_font() + + this.combo = new Combo({ + title: `Font Modes`, + items: this.modes, + value: this.mode, + element: font, + default: this.default_mode, + action: (value) => { + this.change(value) + this.apply() + }, + get: () => { + return this.mode + }, + }) + + this.apply() + } + + static change(value) { + this.mode = value + Utils.save(this.ls_name, value) + } + + static apply() { + document.documentElement.style.setProperty(`--font`, this.mode) + } + + static load_font() { + return Utils.load_modes(this.ls_name, this.modes, this.default_mode) + } +} \ No newline at end of file diff --git a/server/static/dashboard/js/main/footer.js b/server/static/dashboard/js/main/footer.js new file mode 100644 index 0000000..3cb310d --- /dev/null +++ b/server/static/dashboard/js/main/footer.js @@ -0,0 +1,49 @@ +class Footer { + static setup() { + let footer = DOM.el(`#footer`) + + DOM.ev(footer, `contextmenu`, (e) => { + e.preventDefault() + Menu.show(e) + }) + + DOM.ev(footer, `dblclick`, (e) => { + if (e.target !== footer) { + return + } + + Curls.add() + }) + + DOM.ev(footer, `wheel`, (e) => { + if (e.target !== footer) { + return + } + + Container.scroll(e) + }) + + let lines = [ + `Right Click to show the main menu`, + `Double Click to add curls`, + `Wheel to scroll the container`, + ] + + footer.title = lines.join(`\n`) + let scroller = DOM.el(`#scroller`) + + DOM.ev(scroller, `click`, () => { + Container.scroller() + }) + + DOM.ev(scroller, `wheel`, (e) => { + Container.scroll(e) + }) + + let version = DOM.el(`#version`) + + DOM.ev(version, `click`, () => { + Intro.show() + }) + } +} \ No newline at end of file diff --git a/server/static/dashboard/js/main/infobar.js b/server/static/dashboard/js/main/infobar.js new file mode 100644 index 0000000..d217a58 --- /dev/null +++ b/server/static/dashboard/js/main/infobar.js @@ -0,0 +1,131 @@ +class Infobar { + static interval_delay = Utils.SECOND * 30 + static curls_debouncer_delay = 100 + static date_debouncer_delay = 100 + + static setup() { + let infobar = DOM.el(`#infobar`) + this.hide() + + DOM.ev(infobar, `click`, () => { + Container.scroll_top() + }) + + DOM.ev(infobar, `contextmenu`, (e) => { + e.preventDefault() + Menu.show(e) + }) + + DOM.ev(infobar, `auxclick`, (e) => { + if (e.button === 1) { + Container.scroll_bottom() + } + }) + + DOM.ev(infobar, `wheel`, (e) => { + Container.scroll(e) + }) + + this.start_interval() + + this.curls_debouncer = Utils.create_debouncer(() => { + this.do_update_curls() + }, this.curls_debouncer_delay) + + this.date_debouncer = Utils.create_debouncer(() => { + this.do_update_date() + }, this.date_debouncer_delay) + + let curls = DOM.el(`#infobar_curls`) + curls.title = `Number of curls being monitored\nClick to select all` + + DOM.ev(curls, `click`, () => { + this.curls_action() + }) + + let date = DOM.el(`#infobar_date`) + date.title = `How long ago items were updated\nClick to update now` + + DOM.ev(date, `click`, () => { + this.date_action() + }) + } + + static start_interval() { + clearInterval(this.interval) + + this.interval = setInterval(() => { + this.update_date() + }, this.interval_delay) + } + + static update() { + if (!Items.list.length) { + this.hide() + return + } + + this.show() + this.do_update_curls() + this.do_update_date() + this.start_interval() + } + + static update_curls() { + this.curls_debouncer.call() + } + + static do_update_curls() { + this.curls_debouncer.cancel() + let el = DOM.el(`#infobar_curls`) + let visible = Container.get_visible() + let selected = Select.get() + let text + + if (visible.length === Items.list.length) { + text = `${Items.list.length} Curls` + } + else { + text = `${visible.length} / ${Items.list.length} Curls` + } + + if (selected.length) { + if (selected.length === visible.length) { + text += ` (All)` + } + else { + text += ` (${selected.length})` + } + } + + el.textContent = text + } + + static update_date() { + this.date_debouncer.call() + } + + static do_update_date() { + this.date_debouncer.cancel() + let el = DOM.el(`#infobar_date`) + let ago = Utils.timeago(Update.last_update) + el.textContent = ago + } + + static hide() { + DOM.hide(`#infobar`) + } + + static show() { + DOM.show(`#infobar`) + } + + static curls_action() { + Select.toggle_all() + } + + static date_action() { + DOM.el(`#infobar_date`).textContent = `Updating` + Update.update() + } +} \ No newline at end of file diff --git a/server/static/dashboard/js/main/intro.js b/server/static/dashboard/js/main/intro.js new file mode 100644 index 0000000..9033fe0 --- /dev/null +++ b/server/static/dashboard/js/main/intro.js @@ -0,0 +1,40 @@ +/* + +This shows an intro on the first visit + +*/ + +class Intro { + static ls_name = `intro_shown` + + static setup() { + this.intro = [ + `Curls are pointers to text that you control.`, + `You can claim your own curl and receive a key.`, + `With this key you can change the status of the curl.`, + `The key can't be recovered and should be saved securely.`, + `In this Dashboard you can monitor the curls you want.`, + `Each color has its own set of curls.`, + `You are limited to 100 curls per color.`, + ].join(`\n`) + + let shown = this.load_intro() + + if (!shown) { + this.show() + this.save() + } + } + + static save() { + Utils.save(this.ls_name, true) + } + + static load_intro() { + return Utils.load_boolean(this.ls_name, false) + } + + static show() { + Windows.alert({title: `Curls ${App.version}`, message: this.intro}) + } +} \ No newline at end of file diff --git a/server/static/dashboard/js/main/items.js b/server/static/dashboard/js/main/items.js new file mode 100644 index 0000000..3364ab8 --- /dev/null +++ b/server/static/dashboard/js/main/items.js @@ -0,0 +1,240 @@ +/* + +This manages the item list + +*/ + +class Items { + static list = [] + + static get(curl) { + return this.list.find(item => item.curl === curl) + } + + static find_missing() { + let used = Curls.get_curls() + let curls = used.filter(curl => !this.list.find(item => item.curl === curl)) + let missing = [] + + for (let curl of curls) { + missing.push({ + curl: curl, + status: `Not found`, + created: `0`, + updated: `0`, + changes: 0, + missing: true, + }) + } + + return missing + } + + static get_missing() { + return this.list.filter(item => item.missing) + } + + static get_owned() { + let picker_items = Picker.get_items() + + return this.list.filter(item => picker_items.find( + picker => picker.curl === item.curl)) + } + + static get_by_date(what) { + let cleaned = [] + let now = Utils.now() + + for (let item of this.list) { + let date = new Date(item.updated + `Z`) + let diff = now - date + + if (diff < what) { + cleaned.push(item) + } + } + + return cleaned + } + + static get_today() { + return this.get_by_date(Utils.DAY) + } + + static get_week() { + return this.get_by_date(Utils.WEEK) + } + + static get_month() { + return this.get_by_date(Utils.MONTH) + } + + static reset() { + this.list = [] + } + + static copy(curl) { + let blink = (icon) => { + if (!icon) { + return + } + + icon.classList.add(`blink`) + + setTimeout(() => { + icon.classList.remove(`blink`) + }, 1000) + } + + let curls = Select.get_curls() + + if (!curls.includes(curl)) { + curls = [curl] + } + + let msgs = [] + + for (let curl of curls) { + let item = this.get(curl) + msgs.push(`${item.curl}\n${item.status}\n${item.updated_text}`) + blink(DOM.el(`.item_icon`, item.element)) + } + + let msg = msgs.join(`\n\n`) + Utils.copy_to_clipboard(msg) + } + + static show_menu(args = {}) { + let items = [] + let curls = Select.get_curls() + + if (curls.length > 1) { + items = [ + { + text: `Copy`, + action: () => { + this.copy(args.curl) + } + }, + { + text: `Move`, + action: () => { + Colors.move(curls, args.e) + } + }, + { + text: `Remove`, + action: () => { + Curls.remove_selected() + } + }, + { + separator: true, + }, + { + text: `To Top`, + action: () => { + Curls.to_top(curls) + } + }, + { + text: `To Bottom`, + action: () => { + Curls.to_bottom(curls) + } + }, + ] + } + else { + items = [ + { + text: `Copy`, + action: () => { + this.copy(args.curl) + } + }, + { + text: `Edit`, + action: () => { + Curls.edit(args.curl) + } + }, + { + text: `Move`, + action: () => { + Colors.move([args.curl], args.e) + } + }, + { + text: `Remove`, + action: () => { + Curls.remove([args.curl]) + } + }, + { + separator: true, + }, + { + text: `To Top`, + action: () => { + Curls.to_top([args.curl]) + } + }, + { + text: `To Bottom`, + action: () => { + Curls.to_bottom([args.curl]) + } + }, + ] + } + + Utils.context({items: items, e: args.e}) + } + + static remove_curl(curl) { + let cleaned = [] + + for (let item of this.list) { + if (item.curl !== curl) { + cleaned.push(item) + } + } + + this.list = cleaned + } + + static remove(removed) { + for (let curl of removed) { + let item = this.get(curl) + let el = item.element + + if (el) { + el.remove() + } + + let index = this.list.indexOf(item) + this.list.splice(index, 1) + } + + Container.check_empty() + Infobar.update_curls() + } + + static fill() { + let items = Curls.get() + + for (let item of Items.list) { + let item_ = items.find(x => x.curl === item.curl) + + if (item_ && item_.added) { + item.added = item_.added + } + else { + item.added = `0` + } + + Dates.fill(item) + } + } +} \ No newline at end of file diff --git a/server/static/dashboard/js/main/list.js b/server/static/dashboard/js/main/list.js new file mode 100644 index 0000000..e815762 --- /dev/null +++ b/server/static/dashboard/js/main/list.js @@ -0,0 +1,190 @@ +class List { + constructor(button, input, ls_items, max_items, action, clear_action) { + this.button = button + this.input = input + this.ls_items = ls_items + this.max_items = max_items + this.action = action + this.clear_action = clear_action + this.menu_max_length = 110 + this.prepare() + } + + prepare() { + DOM.ev(this.button, `click`, (e) => { + this.show_menu(e) + }) + + DOM.ev(this.button, `auxclick`, (e) => { + if (e.button === 1) { + this.clear_action() + } + }) + + DOM.ev(this.button, `wheel`, (e) => { + this.cycle(e) + }) + + DOM.ev(this.input, `keydown`, (e) => { + if ((e.key === `ArrowUp`) || (e.key === `ArrowDown`)) { + e.preventDefault() + } + else if (e.key === `Escape`) { + this.input.value = `` + e.preventDefault() + } + }) + + DOM.ev(this.input, `keyup`, (e) => { + if ((e.key === `ArrowUp`) || (e.key === `ArrowDown`)) { + this.show_menu() + e.preventDefault() + } + }) + + let lines = [ + `Use previous items`, + `Middle Click to clear input`, + `Middle Click items to remove`, + `Wheel to cycle`, + ] + + this.button.title = lines.join(`\n`) + } + + get_items() { + return Utils.load_array(this.ls_items) + } + + show_menu(e, show_empty = true) { + let list = this.get_items() + + if (!list.length) { + if (show_empty) { + Windows.alert({ + title: `Empty List`, + message: `Items appear here after you use them`, + }) + } + + return + } + + let items = [] + + for (let item of list) { + items.push({ + text: item.substring(0, this.menu_max_length), + action: () => { + this.action(item) + }, + alt_action: () => { + this.remove(item) + }, + + }) + } + + items.push({ + separator: true, + }) + + items.push({ + text: `Clear`, + action: () => { + this.clear() + }, + }) + + this.last_e = e + + Utils.context({ + e: e, + items: items, + element: this.button, + }) + } + + save(value) { + value = value.trim() + + if (!value) { + return + } + + let cleaned = [] + + for (let item of this.get_items()) { + if (item !== value) { + cleaned.push(item) + } + } + + let list = [value, ...cleaned].slice(0, this.max_items) + Utils.save(this.ls_items, JSON.stringify(list)) + } + + remove(status) { + let cleaned = [] + + for (let status_ of this.get_items()) { + if (status_ === status) { + continue + } + + cleaned.push(status_) + } + + Utils.save(this.ls_items, JSON.stringify(cleaned)) + this.show_menu(this.last_e, false) + } + + clear() { + Windows.confirm({title: `Clear List`, ok: () => { + Utils.save(this.ls_items, `[]`) + }, message: `Remove all items from the list`}) + } + + cycle(e) { + let direction = Utils.wheel_direction(e) + + if (direction === `up`) { + this.action(this.get_prev()) + } + else { + this.action(this.get_next()) + } + } + + get_next() { + let list = this.get_items() + let current = this.input.value.trim() + let index = list.indexOf(current) + + if (index === -1) { + return list[0] + } + + if (index === list.length - 1) { + return list[0] + } + + return list[index + 1] + } + + get_prev() { + let list = this.get_items() + let current = this.input.value.trim() + let index = list.indexOf(current) + + if (index === -1) { + return Utils.last(list) + } + + if (index === 0) { + return list[list.length - 1] + } + + return list[index - 1] + } +} \ No newline at end of file diff --git a/server/static/dashboard/js/main/load.js b/server/static/dashboard/js/main/load.js new file mode 100644 index 0000000..fff5466 --- /dev/null +++ b/server/static/dashboard/js/main/load.js @@ -0,0 +1,3 @@ +window.onload = () => { + App.setup() +} \ No newline at end of file diff --git a/server/static/dashboard/js/main/menu.js b/server/static/dashboard/js/main/menu.js new file mode 100644 index 0000000..adca1c9 --- /dev/null +++ b/server/static/dashboard/js/main/menu.js @@ -0,0 +1,154 @@ +class Menu { + static setup() { + let menu = DOM.el(`#menu`) + + DOM.ev(menu, `click`, (e) => { + this.show(e) + }) + } + + static show(e) { + let curls = Curls.get_curls() + let items + + let data = [ + { + separator: true, + }, + { + text: `Export`, + action: (e) => { + this.export(e) + } + }, + { + text: `Import`, + action: () => { + this.import() + } + }, + ] + + if (curls.length) { + items = [ + { + text: `Add`, + action: () => { + Curls.add() + } + }, + { + separator: true, + }, + { + text: `Copy`, + action: () => { + Curls.copy() + } + }, + { + text: `Replace`, + action: () => { + Curls.replace() + } + }, + { + text: `Remove`, + action: (e) => { + Curls.show_remove_menu(e) + } + }, + ...data, + ] + } + else { + items = [ + { + text: `Add`, + action: () => { + Curls.add() + } + }, + ...data, + ] + } + + items.push({ + separator: true, + }) + + items.push({ + text: `Claim`, + action: () => { + this.claim() + } + }) + + Utils.context({items: items, e: e}) + } + + static export() { + let colors = {} + + for (let color in Colors.colors) { + let curls = Curls.get_curls(color) + + if (!curls.length) { + continue + } + + colors[color] = curls + } + + if (!Object.keys(colors).length) { + Windows.alert({message: `No curls to export`}) + return + } + + Windows.alert_export(colors) + } + + static import() { + Windows.prompt({title: `Paste Data`, callback: (value) => { + this.import_submit(value) + }, message: `You get this data in Export`}) + } + + static import_submit(data) { + if (!data) { + return + } + + try { + let colors = JSON.parse(data) + let modified = false + + for (let color in colors) { + let curls = colors[color] + + if (!curls.length) { + continue + } + + Curls.clear(color) + Curls.save_curls(curls, color) + modified = true + } + + if (!modified) { + Windows.alert({message: `No curls to import`}) + return + } + + Update.update() + } + catch (err) { + Utils.error(err) + Windows.alert({title: `Error`, message: err}) + } + } + + static claim() { + window.open(`/claim`, `_blank`) + } +} \ No newline at end of file diff --git a/server/static/dashboard/js/main/more.js b/server/static/dashboard/js/main/more.js new file mode 100644 index 0000000..eeb2728 --- /dev/null +++ b/server/static/dashboard/js/main/more.js @@ -0,0 +1,166 @@ +/* + +This is a button that sits on the footer +It is used to toggle some options + +*/ + +class More { + static setup() { + let button = DOM.el(`#footer_more`) + + DOM.ev(button, `click`, (e) => { + this.show_menu(e) + }) + + DOM.ev(button, `auxclick`, (e) => { + if (e.button == 1) { + this.reset(e) + } + }) + + let lines = [ + `More options`, + `Middle Click to reset`, + ] + + button.title = lines.join(`\n`) + } + + static change_wrap(what, actions = true) { + if (Container.wrap_enabled == what) { + return + } + + Container.wrap_enabled = what + Container.save_wrap_enabled() + + if (actions) { + Container.update() + } + + this.popup(`Wrap`, what) + } + + static change_controls(what, actions = true) { + if (Controls.enabled == what) { + return + } + + Controls.enabled = what + Controls.save_enabled() + + if (actions) { + Controls.check_enabled() + } + + this.popup(`Controls`, what) + } + + static change_dates(what, actions = true) { + if (Dates.enabled == what) { + return + } + + Dates.enabled = what + Dates.save_enabled() + + if (actions) { + Container.update() + } + + this.popup(`Dates`, what) + } + + static show_menu(e) { + let items = [] + + if (Container.wrap_enabled) { + items.push({ + text: `Disable Wrap`, + action: () => { + this.change_wrap(false) + }, + info: `Disable text wrapping in the container`, + }) + } + else { + items.push({ + text: `Enable Wrap`, + action: () => { + this.change_wrap(true) + }, + info: `Enable text wrapping in the container`, + }) + } + + if (Dates.enabled) { + items.push({ + text: `Disable Dates`, + action: () => { + this.change_dates(false) + }, + info: `Disable dates in the container`, + }) + } + else { + items.push({ + text: `Enable Dates`, + action: () => { + this.change_dates(true) + }, + info: `Enable dates in the container`, + }) + } + + if (Controls.enabled) { + items.push({ + text: `Disable Controls`, + action: () => { + this.change_controls(false) + }, + info: `Disable the controls`, + }) + } + else { + items.push({ + text: `Enable Controls`, + action: () => { + this.change_controls(true) + }, + info: `Enable the controls`, + }) + } + + Utils.context({items: items, e: e}) + } + + static reset() { + let vars = [ + Container.wrap_enabled, + Dates.enabled, + Controls.enabled, + ] + + if (vars.every((x) => x)) { + return + } + + Windows.confirm({title: `Reset Options`, ok: () => { + this.do_reset() + }, message: `Reset all options to default`}) + } + + static do_reset() { + this.change_wrap(true, false) + this.change_controls(true, false) + this.change_dates(true, false) + Controls.check_enabled() + Container.update() + } + + static popup(what, value) { + let text = `${what} ${value ? `Enabled` : `Disabled`}` + Windows.popup(text) + } +} \ No newline at end of file diff --git a/server/static/dashboard/js/main/move.js b/server/static/dashboard/js/main/move.js new file mode 100644 index 0000000..39e95c8 --- /dev/null +++ b/server/static/dashboard/js/main/move.js @@ -0,0 +1,54 @@ +/* + +Moves items up and down in the container + +*/ + +class Move { + static setup() { + this.block = new Block() + } + + static up() { + if (this.block.add_charge()) { + return + } + + let items = Container.get_visible() + let selected = Select.get() + let first_index = items.indexOf(selected[0]) + + if (first_index > 0) { + first_index -= 1 + } + + let prev = items[first_index] + prev.before(...selected) + Utils.scroll_element({item: selected[0]}) + this.save() + } + + static down() { + if (this.block.add_charge()) { + return + } + + let items = Container.get_visible() + let selected = Select.get() + let last_index = items.indexOf(Utils.last(selected)) + + if (last_index < (items.length - 1)) { + last_index += 1 + } + + let next = items[last_index] + next.after(...selected) + Utils.scroll_element({item: Utils.last(selected)}) + this.save() + } + + static save() { + Container.save_curls() + Sort.set_value(`order`) + } +} \ No newline at end of file diff --git a/server/static/dashboard/js/main/picker.js b/server/static/dashboard/js/main/picker.js new file mode 100644 index 0000000..bec586f --- /dev/null +++ b/server/static/dashboard/js/main/picker.js @@ -0,0 +1,165 @@ +/* + +The picker stores owned curls + +*/ + +class Picker { + static max_items = 1000 + static ls_name = `picker` + + static setup() { + let picker = DOM.el(`#picker`) + + DOM.ev(picker, `click`, (e) => { + this.show(e) + }) + + let items = this.get_items() + + if (items.length) { + let first = items[0] + DOM.el(`#change_curl`).value = first.curl + DOM.el(`#change_key`).value = first.key + } + + let curl = DOM.el(`#change_curl`) + + DOM.ev(curl, `keydown`, (e) => { + if ((e.key === `ArrowUp`) || (e.key === `ArrowDown`)) { + e.preventDefault() + } + }) + + DOM.ev(curl, `keyup`, (e) => { + if ((e.key === `ArrowUp`) || (e.key === `ArrowDown`)) { + this.show(e) + e.preventDefault() + } + }) + } + + static get_items() { + return Utils.load_array(this.ls_name) + } + + static add() { + let curl = DOM.el(`#change_curl`).value.toLowerCase() + let key = DOM.el(`#change_key`).value + let cleaned = [{curl, key}] + + for (let item of this.get_items()) { + if (item.curl === curl) { + continue + } + + cleaned.push(item) + + if (cleaned.length >= this.max_items) { + break + } + } + + Utils.save(this.ls_name, JSON.stringify(cleaned)) + } + + static show(e) { + let items = [] + let picker_items = this.get_items() + + if (!picker_items.length) { + items.push({ + text: `Import`, + action: () => { + this.import() + }, + }) + } + else { + for (let item of picker_items) { + items.push({ + text: item.curl, + action: () => { + let curl = DOM.el(`#change_curl`) + let key = DOM.el(`#change_key`) + curl.value = item.curl + key.value = item.key + curl.focus() + this.add() + }, + alt_action: () => { + this.remove_item(item.curl) + }, + }) + } + + if (items.length) { + items.push({ + separator: true, + }) + } + + items.push({ + text: `Export`, + action: () => { + this.export() + }, + }) + + items.push({ + text: `Import`, + action: () => { + this.import() + }, + }) + } + + let el = DOM.el(`#picker`) + Utils.context({items: items, element: el, e: e}) + } + + static export() { + Windows.alert_export(this.get_items()) + } + + static import() { + Windows.prompt({title: `Paste Data`, callback: (value) => { + this.import_submit(value) + }, message: `You get this data in Export`}) + } + + static import_submit(data) { + if (!data) { + return + } + + try { + let items = JSON.parse(data) + Utils.save(this.ls_name, JSON.stringify(items)) + } + catch (err) { + Utils.error(err) + Windows.alert({title: `Error`, message: err}) + } + } + + static remove_item(curl) { + Windows.confirm({title: `Remove Picker Item`, ok: () => { + this.do_remove_item(curl) + }, message: curl}) + } + + static do_remove_item(curl) { + let cleaned = [] + + for (let item of this.get_items()) { + if (item.curl === curl) { + continue + } + + cleaned.push(item) + } + + Utils.save(this.ls_name, JSON.stringify(cleaned)) + } +} \ No newline at end of file diff --git a/server/static/dashboard/js/main/select.js b/server/static/dashboard/js/main/select.js new file mode 100644 index 0000000..56baadf --- /dev/null +++ b/server/static/dashboard/js/main/select.js @@ -0,0 +1,379 @@ +/* + +Used for selecting items in the container + +*/ + +class Select { + static selected_class = `selected` + static selected_id = 0 + static mouse_down = false + static mouse_selected = false + + static setup() { + this.block = new Block() + } + + static curl(curl) { + let item = Container.get_item(curl) + + if (item) { + this.select(item) + } + } + + static curls(curls) { + for (let curl of curls) { + this.curl(curl) + } + } + + static check(item) { + let selected = this.get() + + if (!selected.includes(item)) { + this.single(item) + } + } + + static range(item) { + let selected = this.get() + + if (!selected.length) { + this.single(item) + return + } + + let items = Container.get_visible() + + if (items.length <= 1) { + return + } + + let history = this.history() + let prev = history[0] + let prev_prev = history[1] || prev + + if (item === prev) { + return + } + + let index = items.indexOf(item) + let prev_index = items.indexOf(prev) + let prev_prev_index = items.indexOf(prev_prev) + let direction + + if (prev_index === prev_prev_index) { + if (index < prev_index) { + direction = `up` + } + else { + direction = `down` + } + } + else if (prev_index < prev_prev_index) { + direction = `up` + } + else { + direction = `down` + } + + let action = (a, b) => { + this.do_range(a, b, direction) + } + + if (direction === `up`) { + if (index < prev_index) { + action(index, prev_index) + } + else { + action(index, prev_prev_index) + } + } + else if (direction === `down`) { + if (index > prev_index) { + action(prev_index, index) + } + else { + action(prev_prev_index, index) + } + } + + this.id_item(item) + } + + static do_range(start, end, direction) { + let items = Container.get_visible() + let select = [] + + for (let i = 0; i < items.length; i++) { + if (i < start) { + if (direction === `up`) { + this.deselect(items[i]) + } + + continue + } + + if (i > end) { + if (direction === `down`) { + this.deselect(items[i]) + } + + continue + } + + select.push(items[i]) + } + + if (direction === `up`) { + select.reverse() + } + + for (let item of select) { + this.select(item) + } + } + + static vertical(direction, shift) { + if (this.block.add_charge()) { + return + } + + let items = Container.get_visible() + + if (!items.length) { + return + } + + if (items.length === 1) { + this.single(items[0]) + return + } + + let selected = this.get() + let history = this.history() + let prev = history[0] + let prev_index = items.indexOf(prev) + let first_index = items.indexOf(selected[0]) + + if (!selected.length) { + let item + + if (direction === `up`) { + item = Utils.last(items) + } + else if (direction === `down`) { + item = items[0] + } + + this.single(item) + return + } + + if (direction === `up`) { + if (shift) { + let item = items[prev_index - 1] + + if (!item) { + return + } + + this.range(item) + } + else { + let item + + if (selected.length > 1) { + item = selected[0] + } + else { + let index = first_index - 1 + + if (index < 0) { + index = items.length - 1 + } + + item = items[index] + } + + if (!item) { + return + } + + this.single(item) + } + } + else if (direction === `down`) { + if (shift) { + let item = items[prev_index + 1] + + if (!item) { + return + } + + this.range(item) + } + else { + let item + + if (selected.length > 1) { + item = Utils.last(selected) + } + else { + let index = first_index + 1 + + if (index >= items.length) { + index = 0 + } + + item = items[index] + } + + if (!item) { + return + } + + this.single(item) + } + } + } + + static history() { + let items = this.get() + + items = items.filter(item => { + return parseInt(item.dataset.selected_id) > 0 + }) + + items.sort((a, b) => { + return parseInt(b.dataset.selected_id) - parseInt(a.dataset.selected_id) + }) + + return items + } + + static get() { + return DOM.els(`#container .item.${this.selected_class}`) + } + + static get_curls() { + let selected = this.get() + return selected.map(item => Container.extract_curl(item)) + } + + static id_item(item) { + this.selected_id += 1 + item.dataset.selected_id = this.selected_id + } + + static select(item, set_id = false) { + item.classList.add(this.selected_class) + + if (set_id) { + this.id_item(item) + } + + Utils.scroll_element({item: item}) + Infobar.update_curls() + } + + static deselect(item) { + item.classList.remove(this.selected_class) + item.dataset.selected_id = 0 + Infobar.update_curls() + } + + static toggle(item) { + if (item.classList.contains(this.selected_class)) { + this.deselect(item) + } + else { + this.select(item, true) + } + } + + static deselect_all() { + let items = this.get() + + for (let item of items) { + this.deselect(item) + } + + this.selected_id = 0 + } + + static single(item) { + this.deselect_all() + this.selected_id = 0 + this.select(item, true) + } + + static mousedown(e) { + let item = Container.extract_item(e) + + if (item) { + return + } + + this.mouse_down = true + this.mouse_selected = false + e.preventDefault() + } + + static mouseup() { + this.mouse_down = false + this.mouse_selected = false + } + + static mouseover(e) { + if (!this.mouse_down) { + return + } + + let item = Container.extract_item(e) + + if (!item) { + return + } + + let items = Container.get_visible() + let index = items.indexOf(item) + + for (let i = 0; i < items.length; i++) { + if (i < index) { + this.deselect(items[i]) + } + else { + this.select(items[i]) + } + } + + this.id_item(item) + } + + static all() { + let items = Container.get_items() + + for (let item of items) { + if (Container.is_visible(item)) { + this.select(item) + } + else { + this.deselect(item) + } + } + } + + static toggle_all() { + let visible = Container.get_visible() + let selected = this.get() + + if (selected.length === visible.length) { + this.deselect_all() + } + else { + this.all() + } + } +} diff --git a/server/static/dashboard/js/main/sort.js b/server/static/dashboard/js/main/sort.js new file mode 100644 index 0000000..5da1e9f --- /dev/null +++ b/server/static/dashboard/js/main/sort.js @@ -0,0 +1,127 @@ +/* + +This sorts the container + +*/ + +class Sort { + static default_mode = `recent` + static ls_name = `sort` + + static modes = [ + {value: `order`, name: `Order`, info: `Keep the custom order of items`}, + {value: Utils.separator}, + {value: `recent`, name: `Recent`, info: `Sort by the date when curls were last updated`}, + {value: `added`, name: `Added`, info: `Sort by the date when curls were added by you`}, + {value: Utils.separator}, + {value: `curls`, name: `Curls`, info: `Sort curls alphabetically`}, + {value: `status`, name: `Status`, info: `Sort status alphabetically`}, + {value: Utils.separator}, + {value: `active`, name: `Active`, info: `Sort by the number of changes`}, + ] + + static setup() { + let sort = DOM.el(`#sort`) + this.mode = this.load_sort() + + this.combo = new Combo({ + title: `Sort Modes`, + items: this.modes, + value: this.mode, + element: sort, + default: this.default_mode, + action: (value) => { + this.change(value) + }, + get: () => { + return this.mode + }, + }) + } + + static set_value(value) { + if (this.mode === value) { + return + } + + this.combo.set_value(value) + } + + static change(value) { + if (this.mode === value) { + return + } + + this.mode = value + Utils.save(this.ls_name, value) + + if (this.mode === `order`) { + Container.save_curls() + } + else { + Container.update() + } + } + + static sort_if_order() { + if (this.mode == `order`) { + Container.update() + } + } + + static sort(items) { + let mode = this.mode + + if (mode === `order`) { + let curls = Curls.get_curls() + + items.sort((a, b) => { + let a_index = curls.indexOf(a.curl) + let b_index = curls.indexOf(b.curl) + return a_index - b_index + }) + } + else if (mode === `recent`) { + items.sort((a, b) => { + let compare = b.updated.localeCompare(a.updated) + return compare !== 0 ? compare : a.curl.localeCompare(b.curl) + }) + } + else if (mode === `added`) { + let items_ = Curls.get() + + items.sort((a, b) => { + let item_a = Utils.find_item(items_, `curl`, a.curl) + let item_b = Utils.find_item(items_, `curl`, b.curl) + let diff = item_b.added - item_a.added + + if (diff !== 0) { + return diff + } + + return a.curl.localeCompare(b.curl) + }) + } + else if (mode === `curls`) { + items.sort((a, b) => { + return a.curl.localeCompare(b.curl) + }) + } + else if (mode === `status`) { + items.sort((a, b) => { + let compare = a.status.localeCompare(b.status) + return compare !== 0 ? compare : a.curl.localeCompare(b.curl) + }) + } + else if (mode === `active`) { + items.sort((a, b) => { + let compare = b.changes - a.changes + return compare !== 0 ? compare : a.curl.localeCompare(b.curl) + }) + } + } + + static load_sort() { + return Utils.load_modes(this.ls_name, this.modes, this.default_mode) + } +} \ No newline at end of file diff --git a/server/static/dashboard/js/main/status.js b/server/static/dashboard/js/main/status.js new file mode 100644 index 0000000..e1834ce --- /dev/null +++ b/server/static/dashboard/js/main/status.js @@ -0,0 +1,74 @@ +/* + +This stores status items + +*/ + +class Status { + static max_items = 100 + static ls_items = `status_items` + + static setup() { + let status = this.get_status() + let button = DOM.el(`#status_button`) + + DOM.ev(status, `keyup`, (e) => { + if (e.key === `Enter`) { + Change.change() + } + }) + + DOM.ev(status, `wheel`, (e) => { + Utils.scroll_wheel(e) + }) + + status.value = `` + + let lines = [ + `Enter the new status of the curl`, + `Press Enter to submit the change`, + `Press Escape to clear`, + ] + + status.title = lines.join(`\n`) + + this.list = new List( + button, + status, + this.ls_items, + this.max_items, + (value) => { + this.action(value) + }, + () => { + this.clear() + }, + ) + } + + static save(status) { + this.list.save(status) + } + + static get_items() { + return Utils.load_array(this.ls_items) + } + + static focus() { + this.get_status().focus() + } + + static clear() { + this.get_status().value = `` + } + + static get_status() { + return DOM.el(`#change_status`) + } + + static action(value) { + let status = this.get_status() + status.value = value + status.focus() + } +} \ No newline at end of file diff --git a/server/static/dashboard/js/main/storage.js b/server/static/dashboard/js/main/storage.js new file mode 100644 index 0000000..7c1df1f --- /dev/null +++ b/server/static/dashboard/js/main/storage.js @@ -0,0 +1,24 @@ +class Storage { + static debouncer_delay = 250 + + static setup = () => { + this.debouncer = Utils.create_debouncer((key) => { + this.do_check(key) + }, this.debouncer_delay) + + window.addEventListener(`storage`, (e) => { + this.check(e.key) + }) + } + + static check = (key) => { + this.debouncer.call(key) + } + + static do_check = (key) => { + if (key.startsWith(`curls_data`)) { + Curls.fill_colors() + Update.update() + } + } +} \ No newline at end of file diff --git a/server/static/dashboard/js/main/update.js b/server/static/dashboard/js/main/update.js new file mode 100644 index 0000000..f3234b9 --- /dev/null +++ b/server/static/dashboard/js/main/update.js @@ -0,0 +1,209 @@ +/* + +Update manager + +*/ + +class Update { + static default_mode = `minutes_5` + static enabled = false + static delay = Utils.MINUTE * 5 + static debouncer_delay = 250 + static updating = false + static clear_delay = 800 + static ls_name = `update` + static last_update = 0 + + static modes = [ + {value: `now`, name: `Update`, skip: true, info: `Update now`}, + {value: Utils.separator}, + {value: `minutes_1`}, + {value: `minutes_5`}, + {value: `minutes_10`}, + {value: `minutes_20`}, + {value: `minutes_30`}, + {value: `minutes_60`}, + {value: Utils.separator}, + {value: `disabled`, name: `Disabled`, info: `Do not update automatically`}, + ] + + static setup() { + let updater = DOM.el(`#updater`) + this.mode = this.load_update() + this.fill_modes() + + this.combo = new Combo({ + title: `Update Modes`, + items: this.modes, + value: this.mode, + element: updater, + default: this.default_mode, + action: (value) => { + this.change(value) + }, + get: () => { + return this.mode + }, + }) + + this.debouncer = Utils.create_debouncer(async (args) => { + await this.do_update(args) + this.restart() + }, this.debouncer_delay) + + this.check() + } + + static load_update() { + return Utils.load_modes(this.ls_name, this.modes, this.default_mode) + } + + static check() { + let mode = this.mode + + if (mode.startsWith(`minutes_`)) { + let minutes = parseInt(mode.split(`_`)[1]) + this.delay = Utils.MINUTE * minutes + this.enabled = true + } + else { + this.enabled = false + } + + this.restart() + } + + static restart() { + clearTimeout(this.timeout) + + if (this.enabled) { + this.start_timeout() + } + } + + static start_timeout() { + this.timeout = setTimeout(() => { + this.update() + }, this.delay) + } + + static update(args) { + this.debouncer.call(args) + } + + static async do_update(args = {}) { + this.debouncer.cancel() + + let def_args = { + curls: [], + } + + Utils.def_args(def_args, args) + Utils.info(`Update: Trigger`) + + if (this.updating) { + Utils.error(`Slow down`) + return + } + + let add = false + + if (args.curls.length) { + add = true + } + else { + args.curls = Curls.get_curls() + } + + if (!args.curls.length) { + Container.show_empty() + return + } + + let url = `/curls` + let params = new URLSearchParams() + + for (let curl of args.curls) { + params.append(`curl`, curl); + } + + this.show_updating() + let response = `` + this.updating = true + Utils.info(`Update: Request ${Utils.network} (${args.curls.length})`) + + if (!Items.list.length) { + Container.show_loading() + } + + try { + response = await fetch(url, { + method: `POST`, + headers: { + "Content-Type": `application/x-www-form-urlencoded` + }, + body: params, + }) + } + catch (e) { + Utils.error(`Failed to update`) + this.hide_updating() + return + } + + try { + let items = await response.json() + this.last_update = Utils.now() + + if (add) { + Container.add(items, args.curls) + } + else { + Container.insert(items) + } + } + catch (e) { + Utils.error(`Failed to parse response`) + Utils.error(e) + } + + this.hide_updating() + } + + static show_updating() { + let button = DOM.el(`#updater`) + clearTimeout(this.clear_timeout) + button.classList.add(`active`) + } + + static hide_updating() { + this.updating = false + + this.clear_timeout = setTimeout(() => { + let button = DOM.el(`#updater`) + button.classList.remove(`active`) + }, this.clear_delay) + } + + static change(mode) { + if (mode === `now`) { + this.update() + return + } + + this.mode = mode + Utils.save(this.ls_name, mode) + this.check() + } + + static fill_modes() { + for (let mode of this.modes) { + if (mode.value.startsWith(`minutes_`)) { + let minutes = parseInt(mode.value.split(`_`)[1]) + let word = Utils.plural(minutes, `minute`, `minutes`) + mode.name = `${minutes} ${word}` + mode.info = `Update automatically every ${minutes} ${word}` + } + } + } +} \ No newline at end of file diff --git a/server/static/dashboard/js/main/utils.js b/server/static/dashboard/js/main/utils.js new file mode 100644 index 0000000..002a82d --- /dev/null +++ b/server/static/dashboard/js/main/utils.js @@ -0,0 +1,287 @@ +/* + +These are some utility functions + +*/ + +class Utils { + static console_logs = true + static SECOND = 1000 + static MINUTE = this.SECOND * 60 + static HOUR = this.MINUTE * 60 + static DAY = this.HOUR * 24 + static WEEK = this.DAY * 7 + static MONTH = this.DAY * 30 + static YEAR = this.DAY * 365 + static scroll_wheel_step = 25 + + static network = `🛜` + static separator = `__separator__` + static curl_too_long = `Curl is too long` + static key_too_long = `Key is too long` + static status_too_long = `Status is too long` + + static deselect() { + window.getSelection().removeAllRanges() + } + + static plural(n, singular, plural) { + if (n === 1) { + return singular + } + else { + return plural + } + } + + static info(msg) { + if (this.console_logs) { + // eslint-disable-next-line no-console + console.info(`💡 ${msg}`) + } + } + + static error(msg) { + if (this.console_logs) { + // eslint-disable-next-line no-console + console.info(`❌ ${msg}`) + } + } + + static sanitize(s) { + return s.replace(//g, `>`) + } + + static urlize(el) { + let html = el.innerHTML + let urlRegex = /(https?:\/\/[^\s]+)/g + let replacedText = html.replace(urlRegex, `$1`) + el.innerHTML = replacedText + } + + static create_debouncer(func, delay) { + if (typeof func !== `function`) { + this.error(`Invalid debouncer function`) + return + } + + if (!delay) { + this.error(`Invalid debouncer delay`) + return + } + + let timer + let obj = {} + + let clear = () => { + clearTimeout(timer) + } + + let run = (...args) => { + func(...args) + } + + obj.call = (...args) => { + clear() + + timer = setTimeout(() => { + run(...args) + }, delay) + } + + obj.now = (...args) => { + clear() + run(...args) + } + + obj.cancel = () => { + clear() + } + + return obj + } + + static wheel_direction(e) { + if (e.deltaY > 0) { + return `down` + } + else { + return `up` + } + } + + static capitalize(s) { + return s.charAt(0).toUpperCase() + s.slice(1) + } + + static now() { + return Date.now() + } + + static copy_to_clipboard(text) { + navigator.clipboard.writeText(text) + } + + static smart_list(string) { + return string.split(/[\s,;]+/).filter(Boolean) + } + + static clean_modes(modes) { + return modes.filter(x => x.value !== Utils.separator) + } + + static def_args(def, args) { + for (let key in def) { + if ((args[key] === undefined) && (def[key] !== undefined)) { + args[key] = def[key] + } + } + } + + static scroll_element(args = {}) { + let def_args = { + behavior: `instant`, + block: `nearest`, + } + + if (!args.item) { + return + } + + this.def_args(def_args, args) + args.item.scrollIntoView({ behavior: args.behavior, block: args.block }) + window.scrollTo(0, window.scrollY) + } + + static last(list) { + return list.slice(-1)[0] + } + + static load_modes(name, modes, def_value) { + let saved = localStorage.getItem(name) || def_value + let values = this.clean_modes(modes).map(x => x.value) + + if (!values.includes(saved)) { + saved = def_value + } + + return saved + } + + static load_boolean(name, positive = true) { + let value = positive ? `true` : `false` + let saved = localStorage.getItem(name) || value + return saved === `true` + } + + static load_array(name) { + try { + return JSON.parse(localStorage.getItem(name) || `[]`) + } + catch (err) { + this.error(err) + return [] + } + } + + static load_string(name, def_value = ``) { + return localStorage.getItem(name) || def_value + } + + static save(name, value) { + localStorage.setItem(name, value) + } + + static context(args) { + let def_args = { + focus: true, + } + + this.def_args(def_args, args) + + if (args.focus) { + args.after_hide = () => { + if (args.input) { + args.input.focus() + } + else { + Container.focus() + } + } + } + + NeedContext.show({ + e: args.e, + items: args.items, + element: args.element, + after_hide: args.after_hide, + }) + } + + static timeago = (date) => { + let diff = this.now() - date + let decimals = true + + let n = 0 + let m = `` + + if (diff < this.SECOND) { + return `Just Now` + } + else if (diff < this.MINUTE) { + n = diff / this.SECOND + m = [`second`, `seconds`] + decimals = false + } + else if (diff < this.HOUR) { + n = diff / this.MINUTE + m = [`minute`, `minutes`] + decimals = false + } + else if (diff >= this.HOUR && diff < this.DAY) { + n = diff / this.HOUR + m = [`hour`, `hours`] + } + else if (diff >= this.DAY && diff < this.MONTH) { + n = diff / this.DAY + m = [`day`, `days`] + } + else if (diff >= this.MONTH && diff < this.YEAR) { + n = diff / this.MONTH + m = [`month`, `months`] + } + else if (diff >= this.YEAR) { + n = diff / this.YEAR + m = [`year`, `years`] + } + + if (decimals) { + n = this.round(n, 1) + } + else { + n = Math.round(n) + } + + let w = this.plural(n, m[0], m[1]) + return `${n} ${w} ago` + } + + static round = (n, decimals) => { + return Math.round(n * Math.pow(10, decimals)) / Math.pow(10, decimals) + } + + static find_item(items, key, value) { + return items.find(x => x[key] === value) + } + + static scroll_wheel(e) { + let direction = this.wheel_direction(e) + + if (direction === `up`) { + e.target.scrollLeft -= this.scroll_wheel_step + } + else { + e.target.scrollLeft += this.scroll_wheel_step + } + } +} \ No newline at end of file diff --git a/server/static/dashboard/js/main/windows.js b/server/static/dashboard/js/main/windows.js new file mode 100644 index 0000000..3b26a9c --- /dev/null +++ b/server/static/dashboard/js/main/windows.js @@ -0,0 +1,213 @@ +/* + +This creates and shows modal windows + +*/ + +class Windows { + static max_items = 1000 + static popup_delay = 2750 + + static setup() { + this.make_alert() + this.make_prompt() + this.make_confirm() + } + + static create() { + let common = { + enable_titlebar: true, + center_titlebar: true, + window_x: `none`, + after_close: () => { + Container.focus() + }, + } + + return Msg.factory(Object.assign({}, common, { + class: `modal`, + })) + } + + static make_alert() { + this.alert_window = this.create() + let template = DOM.el(`#alert_template`) + let html = template.innerHTML + this.alert_window.set(html) + let copy = DOM.el(`#alert_copy`) + + DOM.ev(copy, `click`, () => { + this.alert_copy() + }) + + let ok = DOM.el(`#alert_ok`) + + DOM.ev(ok, `click`, (e) => { + this.alert_window.close() + }) + } + + static make_prompt() { + this.prompt_window = this.create() + let template = DOM.el(`#prompt_template`) + let html = template.innerHTML + this.prompt_window.set(html) + this.prompt_window.set_title(`Prompt`) + let submit = DOM.el(`#prompt_submit`) + let input = DOM.el(`#prompt_input`) + + DOM.ev(submit, `click`, () => { + this.prompt_submit() + }) + + DOM.ev(input, `keydown`, (e) => { + if (e.key === `Enter`) { + this.prompt_submit() + } + }) + + DOM.ev(input, `wheel`, (e) => { + Utils.scroll_wheel(e) + }) + } + + static make_confirm() { + this.confirm_window = this.create() + let template = DOM.el(`#confirm_template`) + let html = template.innerHTML + this.confirm_window.set(html) + let ok = DOM.el(`#confirm_ok`) + + DOM.ev(ok, `click`, () => { + this.confirm_ok() + this.confirm_window.close() + }) + + DOM.ev(ok, `keydown`, (e) => { + if (e.key === `Enter`) { + this.confirm_ok() + this.confirm_window.close() + } + }) + } + + static alert(args = {}) { + let def_args = { + title: `Information`, + message: ``, + copy: false, + ok: true, + } + + Utils.def_args(def_args, args) + this.alert_window.set_title(args.title) + let msg = DOM.el(`#alert_message`) + + if (args.message) { + DOM.show(msg) + msg.textContent = args.message + } + else { + DOM.hide(msg) + } + + let copy = DOM.el(`#alert_copy`) + + if (args.copy) { + DOM.show(copy) + } + else { + DOM.hide(copy) + } + + let ok = DOM.el(`#alert_ok`) + + if (args.ok) { + DOM.show(ok) + } + else { + DOM.hide(ok) + } + + this.alert_window.show() + } + + static alert_copy() { + let text = DOM.el(`#alert_message`) + Utils.copy_to_clipboard(text.textContent) + this.alert_window.close() + } + + static confirm(args = {}) { + let def_args = { + message: ``, + } + + Utils.def_args(def_args, args) + this.confirm_ok = args.ok + this.confirm_window.set_title(args.title) + this.confirm_window.show() + DOM.el(`#confirm_ok`).focus() + let msg = DOM.el(`#confirm_message`) + + if (args.message) { + msg.textContent = args.message + DOM.show(msg) + } + else { + DOM.hide(msg) + } + } + + static prompt_submit() { + let value = DOM.el(`#prompt_input`).value.trim() + this.prompt_callback(value) + this.prompt_window.close() + } + + static prompt(args = {}) { + let def_args = { + value: ``, + message: ``, + } + + Utils.def_args(def_args, args) + this.prompt_callback = args.callback + let input = DOM.el(`#prompt_input`) + input.value = args.value + this.prompt_window.set_title(args.title) + let msg = DOM.el(`#prompt_message`) + + if (args.message) { + msg.textContent = args.message + DOM.show(msg) + } + else { + DOM.hide(msg) + } + + this.prompt_window.show() + input.focus() + } + + static alert_export(data) { + let data_str = Utils.sanitize(JSON.stringify(data)) + this.alert({title: `Copy the data below`, message: data_str, copy: true, ok: false}) + } + + static popup(message) { + let popup = Msg.factory({ + preset: `popup_autoclose`, + position: `bottomright`, + window_x: `none`, + enable_titlebar: true, + center_titlebar: true, + autoclose_delay: this.popup_delay, + class: `popup`, + }) + + popup.set(message) + popup.set_title(`Information`) + popup.show() + } +} \ No newline at end of file diff --git a/server/static/icon.jpg b/server/static/icon.jpg new file mode 100644 index 0000000..64cd0f3 Binary files /dev/null and b/server/static/icon.jpg differ diff --git a/server/templates/base.html b/server/templates/base.html new file mode 100644 index 0000000..3ebc287 --- /dev/null +++ b/server/templates/base.html @@ -0,0 +1,60 @@ + + + + {% block title %}{% endblock %} + + + + + + + {% block body %}{% endblock %} + \ No newline at end of file diff --git a/server/templates/change.html b/server/templates/change.html new file mode 100644 index 0000000..dd927ec --- /dev/null +++ b/server/templates/change.html @@ -0,0 +1,34 @@ +{% extends "base.html" %} + +{% block title %} +Change Curl +{% endblock %} + +{% block body %} +
+
+
Change
+ + + + + +

+ + You can also do this using the terminal: + +

+ +
+ curl -X POST -d "curl=mycurl&key=mykey&status=mystatus" https://this.website/change +
+
+
+ + +{% endblock %} diff --git a/server/templates/claim.html b/server/templates/claim.html new file mode 100644 index 0000000..f9e8edc --- /dev/null +++ b/server/templates/claim.html @@ -0,0 +1,43 @@ +{% extends "base.html" %} + +{% block title %} +Claim Curl +{% endblock %} + +{% block body %} +
+
+
Claim
+ +
+ Curls are single lower-case words. Letters and/or numbers. +
+ +
+ You will receive a key to be able to control the following curl: +
+ + + +
+ Solve this slightly annoying captcha: +
+ +
+ {{ captcha_html(captcha)|safe }} +
+ + +
+
+ + +{% endblock %} \ No newline at end of file diff --git a/server/templates/dashboard.html b/server/templates/dashboard.html new file mode 100644 index 0000000..2efdae9 --- /dev/null +++ b/server/templates/dashboard.html @@ -0,0 +1,102 @@ + + + + Curls Dashboard + + + + + + + + + +
+
+
+
+ +
+ +
+
+
+
+
+ +
+
F
+ +
Filters
+
+
+ +
+
+
C
+ + +
+ +
+
S
+ +
>
+
+
+
+ +
+
+
+ + +
+ + + + + + + + + diff --git a/server/templates/index.html b/server/templates/index.html new file mode 100644 index 0000000..40ba3de --- /dev/null +++ b/server/templates/index.html @@ -0,0 +1,41 @@ +{% extends "base.html" %} + +{% block title %} +Curls +{% endblock %} + +{% block body %} +
+
+
Curls
+ +
A curl is a text status that only you can update.
+ +

+ +
There is no history, comments, or anything, it's just text that you update.
+ +
+ + Claim your own curl + Change the status of a curl you already own + Monitor curls in the Dashboard + +
+ +
To view a curl from a browser: + +
Go to: https://this.website/[curl]
+ +
+ +
To view a curl from the terminal:
+ +
curl https://this.website/[curl]
+ +
+ + The response is pure text. +
+ +{% endblock %} diff --git a/server/templates/message.html b/server/templates/message.html new file mode 100644 index 0000000..e95411e --- /dev/null +++ b/server/templates/message.html @@ -0,0 +1,9 @@ +{% extends "base.html" %} + +{% block title %} +Curls Feedback +{% endblock %} + +{% block body %} +{{message|safe}} +{% endblock %} \ No newline at end of file diff --git a/utils/count.sh b/utils/count.sh new file mode 100755 index 0000000..8502af5 --- /dev/null +++ b/utils/count.sh @@ -0,0 +1,10 @@ +#!/usr/bin/env bash +# Count the total number of lines + +cd server/ +echo "Python:" +wc -l app.py procs.py db.py bundle.py | awk 'END {print $1}' + +cd static/dashboard/js/main/ +echo "Javascript:" +find . -type f -name "*.js" -exec wc -l {} \; | awk '{t+=$1} END {print t}' \ No newline at end of file diff --git a/utils/tag.rb b/utils/tag.rb new file mode 100755 index 0000000..1f1f5d0 --- /dev/null +++ b/utils/tag.rb @@ -0,0 +1,13 @@ +#!/usr/bin/env ruby + +require "git" +require "json" + +file = File.read("server/manifest.json") +manifest = JSON.parse(file) +version = manifest["version"] +name = "v#{version}" +repo = Git.open(".") +repo.add_tag(name) +repo.push("origin", name) +puts "Created tag: #{name}" \ No newline at end of file