diff --git a/.prettierignore b/.prettierignore new file mode 100644 index 0000000..95f18a0 --- /dev/null +++ b/.prettierignore @@ -0,0 +1,10 @@ +libraries/* +*.md + +addon/* +images/* +inject/l10n.js +l10n/* +_locales/* + +.github/workflows/* diff --git a/.prettierrc.json b/.prettierrc.json new file mode 100644 index 0000000..41c8d6c --- /dev/null +++ b/.prettierrc.json @@ -0,0 +1,4 @@ +{ + "printWidth": 120, + "endOfLine": "lf" +} diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..f288702 --- /dev/null +++ b/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 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 General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is 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. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + 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. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + 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 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. Use with the GNU Affero General Public License. + + 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 Affero 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 special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU 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 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 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 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 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 General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + 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 GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/_locales/en/messages.json b/_locales/en/messages.json new file mode 100644 index 0000000..4aa4e95 --- /dev/null +++ b/_locales/en/messages.json @@ -0,0 +1,8 @@ +{ + "extensionName": { + "message": "Scratch 3 Developer Tools" + }, + "extensionDescription": { + "message": "Scratch 3 Developer Tools to enhance your Scratch Editing Experience on https://scratch.mit.edu" + } +} \ No newline at end of file diff --git a/addon/BlockInstance.js b/addon/BlockInstance.js new file mode 100644 index 0000000..5ade803 --- /dev/null +++ b/addon/BlockInstance.js @@ -0,0 +1,9 @@ +/** + * Encapsulates a block (either in this sprite or another / Blockly, or native JSON block + */ +export default class BlockInstance { + constructor(target, block) { + this.targetId = target.id; + this.id = block.id; + } +} diff --git a/addon/BlockItem.js b/addon/BlockItem.js new file mode 100644 index 0000000..3752020 --- /dev/null +++ b/addon/BlockItem.js @@ -0,0 +1,34 @@ +export default class BlockItem { + constructor(cls, procCode, labelID, y) { + this.cls = cls; + this.procCode = procCode; + this.labelID = labelID; + this.y = y; + this.lower = procCode.toLowerCase(); + /** + * An Array of block ids + * @type {Array.} + */ + this.clones = null; + this.eventName = null; + } + + /** + * True if the blockID matches a black represented by this BlockItem + * @param id + * @returns {boolean} + */ + matchesID(id) { + if (this.labelID === id) { + return true; + } + if (this.clones) { + for (const cloneID of this.clones) { + if (cloneID === id) { + return true; + } + } + } + return false; + } +} diff --git a/addon/DevTools.js b/addon/DevTools.js new file mode 100644 index 0000000..15fd334 --- /dev/null +++ b/addon/DevTools.js @@ -0,0 +1,2294 @@ +// import ShowBroadcast from "./show-broadcast.js"; +import Utils from "./blockly/Utils.js"; +import DomHelpers from "./DomHelpers.js"; +import BlockInstance from "./BlockInstance.js"; +import XML from "./XML.js"; +import BlockItem from "./BlockItem.js"; +import UndoGroup from "./blockly/UndoGroup.js"; + +export default class DevTools { + constructor(addon, msg, m, helpHTML) { + this.addon = addon; + this.msg = msg; + this.m = m; + /** + * @type {VirtualMachine} + */ + this.vm = addon.tab.traps.vm; + this.utils = new Utils(addon); + this.domHelpers = new DomHelpers(addon); + this.multi = new Multi(this.utils); + + this._helpHTML = helpHTML; + this.find = null; + this.findInp = null; + this.ddOut = null; + this.dd = null; + this.codeTab = null; + this.costTab = null; + this.costTabBody = null; + this.selVarID = null; + this.floatInp = null; + this.blockCursor = null; + this.canShare = false; + + this.mouseXY = { x: 0, y: 0 }; + } + + init() { + setTimeout(() => this.initInner(), 500); + } + + isScriptEditor() { + return this.codeTab.className.indexOf("gui_is-selected") >= 0; + } + + isCostumeEditor() { + return this.costTab.className.indexOf("gui_is-selected") >= 0; + } + + eventClickHelp(e) { + if (!document.getElementById("s3devHelpPop")) { + document.body.insertAdjacentHTML("beforeend", this._helpHTML); + document.getElementById("s3devHelpPop").addEventListener("mousedown", function (e) { + if (e.target.id === "s3devHelpPop") { + e.target.remove(); + } + }); + } + e.preventDefault(); + } + + getScratchCostumes() { + let costumes = this.costTabBody.querySelectorAll("div[class^='sprite-selector-item_sprite-name']"); + // this.costTab[0].click(); + + let myBlocks = []; + let myBlocksByProcCode = {}; + + /** + * @param cls + * @param txt + * @param root + * @returns BlockItem + */ + function addBlock(cls, txt, root) { + let id = root.className; + let items = new BlockItem(cls, txt, id, 0); + myBlocks.push(items); + myBlocksByProcCode[txt] = items; + return items; + } + + let i = 0; + for (const costume of costumes) { + addBlock("costume", costume.innerText, costume).y = i; + i++; + } + + return { procs: myBlocks }; + } + + /** + * Fetch the scratch 3 block list + * @returns jsonFetch object + */ + getScratchBlocks() { + // Access Blockly! + + let myBlocks = []; + let myBlocksByProcCode = {}; + + // todo - get blockyly from an svg??? + + let wksp = this.utils.getWorkspace(); + let topBlocks = wksp.getTopBlocks(); + + // console.log(topBlocks); + + /** + * @param cls + * @param txt + * @param root + * @returns BlockItem + */ + function addBlock(cls, txt, root) { + let id = root.id ? root.id : root.getId ? root.getId() : null; + let clone = myBlocksByProcCode[txt]; + if (clone) { + if (!clone.clones) { + clone.clones = []; + } + clone.clones.push(id); + return clone; + } + let items = new BlockItem(cls, txt, id, 0); + items.y = root.getRelativeToSurfaceXY ? root.getRelativeToSurfaceXY().y : null; + myBlocks.push(items); + myBlocksByProcCode[txt] = items; + return items; + } + + function getDescFromField(root) { + let fields = root.inputList[0]; + let desc; + for (const fieldRow of fields.fieldRow) { + desc = (desc ? desc + " " : "") + fieldRow.getText(); + } + return desc; + } + + for (const root of topBlocks) { + if (root.type === "procedures_definition") { + let fields = root.inputList[0]; + let typeDesc = fields.fieldRow[0].getText(); + let label = root.getChildren()[0]; + let procCode = label.getProcCode(); + if (!procCode) { + continue; + } + addBlock("define", typeDesc + " " + procCode, root); + continue; + } + + if (root.type === "event_whenflagclicked") { + addBlock("flag", getDescFromField(root), root); // "When Flag Clicked" + continue; + } + + if (root.type === "event_whenbroadcastreceived") { + try { + // let wksp2 = Blockly.getMainWorkspace().getTopBlocks()[2].inputList[0].fieldRow[1]; + let fields = root.inputList[0]; + // let typeDesc = fields.fieldRow[0].getText(); + let eventName = fields.fieldRow[1].getText(); + // addBlock('receive', typeDesc + ' ' + eventName, root).eventName = eventName; + addBlock("receive", "event " + eventName, root).eventName = eventName; + } catch (e) { + // eat + } + continue; + } + + if (root.type.substr(0, 10) === "event_when") { + addBlock("event", getDescFromField(root), root); // "When Flag Clicked" + continue; + } + + if (root.type === "control_start_as_clone") { + addBlock("event", getDescFromField(root), root); // "when I start as a clone" + continue; + } + } + + let map = wksp.getVariableMap(); + + let vars = map.getVariablesOfType(""); + for (const row of vars) { + addBlock(row.isLocal ? "var" : "VAR", (row.isLocal ? "var " : "VAR ") + row.name, row); + } + + let lists = map.getVariablesOfType("list"); + for (const row of lists) { + addBlock(row.isLocal ? "list" : "LIST", (row.isLocal ? "list " : "LIST ") + row.name, row); + } + + const events = this.getCallsToEvents(); + for (const event of events) { + addBlock("receive", "event " + event.eventName, event.block).eventName = event.eventName; + } + + /* + const runtime = vm.runtime; + // Now let's also add event broadcasts (not just hat blocks) + const target = runtime.getEditingTarget(); + const blocks = target.blocks; + if (blocks._blocks) { + for (const id in blocks._blocks) { + if (!blocks._blocks.hasOwnProperty(id)) { + continue; + } + const block = blocks._blocks[id]; + if (block.opcode === 'event_broadcast_menu') { + + debugger; + + // Now get the parent block that is the actual broadcast or broadcast and wait + const broadcastBlock = blocks.getBlock(block.parent); + let b = new BlockInstance(target, broadcastBlock); + + const fieldName = block.fields.BROADCAST_OPTION.value; + addBlock('receive', 'event ' + fieldName, b).eventName = broadcastBlock.eventName; + + // + // let fields = root.inputList[0]; + // let typeDesc = fields.fieldRow[0].getText(); + // let eventName = fields.fieldRow[1].getText(); + // addBlock('receive', 'event ' + eventName, root).eventName = eventName; + } + } + } + */ + + const clsOrder = { flag: 0, receive: 1, event: 2, define: 3, var: 4, VAR: 5, list: 6, LIST: 7 }; + + myBlocks.sort((a, b) => { + let t = clsOrder[a.cls] - clsOrder[b.cls]; + if (t !== 0) { + return t; + } + if (a.lower < b.lower) { + return -1; + } + if (a.lower > b.lower) { + return 1; + } + return a.y - b.y; + }); + + return { procs: myBlocks }; + } + + showDropDown(e, focusID, instanceBlock) { + clearTimeout(rhdd); + rhdd = 0; + + if (!focusID && this.ddOut.classList.contains("vis")) { + return; + } + + // special '' vs null... - null forces a reevaluation + prevVal = focusID ? "" : null; // Clear the previous value of the input search + + this.ddOut.classList.add("vis"); + let scratchBlocks = this.isCostumeEditor() ? this.getScratchCostumes() : this.getScratchBlocks(); + + this.dom_removeChildren(this.dd); + + let foundLi = null; + /** + * @type {[BlockItem]} + */ + const procs = scratchBlocks.procs; + for (const proc of procs) { + let li = document.createElement("li"); + li.innerText = proc.procCode; + li.data = proc; + li.className = proc.cls; + if (focusID) { + if (proc.matchesID(focusID)) { + foundLi = li; + li.classList.add("sel"); + } else { + li.style.display = "none"; + } + } + this.dd.appendChild(li); + } + + let label = document.getElementById("s3devFindLabel"); + this.utils.offsetX = this.ddOut.getBoundingClientRect().right - label.getBoundingClientRect().left + 26; + this.utils.offsetY = 32; + + if (foundLi) { + this.clickDropDownRow(foundLi, this.utils.getWorkspace(), instanceBlock); + } + } + + hideDropDown() { + clearTimeout(rhdd); + rhdd = setTimeout(() => this.reallyHideDropDown(), 250); + } + + reallyHideDropDown() { + // Check focus of find box + if (this.findInp === document.activeElement) { + this.hideDropDown(); + return; + } + + // document.getElementById('s3devReplace').classList.add('s3devHide'); + + this.ddOut.classList.remove("vis"); + rhdd = 0; + } + + hideFloatDropDown() { + clearTimeout(rhdd2); + rhdd2 = setTimeout(() => this.reallyHideFloatDropDown(), 50); + } + + reallyHideFloatDropDown(force) { + // Check focus of find box + if (!force && this.floatInp === document.activeElement) { + this.hideFloatDropDown(); + return; + } + + let float = document.getElementById("s3devFloatingBar"); + if (float) { + float.remove(); + } + this.floatInp = null; + rhdd2 = 0; + } + + dom_removeChildren(myNode) { + while (myNode.firstChild) { + myNode.removeChild(myNode.firstChild); + } + } + + /** + * A nicely ordered version of the top blocks + * @returns {[Blockly.Block]} + */ + getTopBlocks() { + let result = this.getOrderedTopBlockColumns(); + let columns = result.cols; + /** + * @type {[[Blockly.Block]]} + */ + let topBlocks = []; + for (const col of columns) { + topBlocks = topBlocks.concat(col.blocks); + } + return topBlocks; + } + + hidePopups(wksp) { + // Fire fake mouse events to trick the popup into hiding. + const element = wksp.getToolbox().HtmlDiv; + element.dispatchEvent(new MouseEvent("mousedown", { relatedTarget: element, bubbles: true })); + element.dispatchEvent(new MouseEvent("mouseup", { relatedTarget: element, bubbles: true })); + } + + /** + * A much nicer way of laying out the blocks into columns + */ + doCleanUp(e) { + let workspace = this.utils.getWorkspace(); + if (e) { + e.cancelBubble = true; + e.preventDefault(); + this.hidePopups(workspace); + setTimeout(() => this.doCleanUp(), 0); + return; + } + + UndoGroup.startUndoGroup(workspace); + + let result = this.getOrderedTopBlockColumns(true); + let columns = result.cols; + let orphanCount = result.orphans.blocks.length; + if (orphanCount > 0) { + let message = this.msg("orphaned", { + count: orphanCount, + }); + if (confirm(message)) { + for (const block of result.orphans.blocks) { + block.dispose(); + } + } else { + columns.unshift(result.orphans); + } + } + + let cursorX = 48; + + let maxWidths = result.maxWidths; + + for (const column of columns) { + let cursorY = 64; + let maxWidth = 0; + + for (const block of column.blocks) { + let xy = block.getRelativeToSurfaceXY(); + if (cursorX - xy.x !== 0 || cursorY - xy.y !== 0) { + block.moveBy(cursorX - xy.x, cursorY - xy.y); + } + let heightWidth = block.getHeightWidth(); + cursorY += heightWidth.height + 72; + + let maxWidthWithComments = maxWidths[block.id] || 0; + maxWidth = Math.max(maxWidth, Math.max(heightWidth.width, maxWidthWithComments)); + } + + cursorX += maxWidth + 96; + } + + let topComments = workspace.getTopComments(); + for (const comment of topComments) { + if (comment.setVisible) { + comment.setVisible(false); + comment.needsAutoPositioning_ = true; + comment.setVisible(true); + } + } + + setTimeout(() => { + // Locate unused local variables... + let workspace = this.utils.getWorkspace(); + let map = workspace.getVariableMap(); + let vars = map.getVariablesOfType(""); + + let unusedLocals = []; + + for (const row of vars) { + if (row.isLocal) { + let usages = map.getVariableUsesById(row.getId()); + if (!usages || usages.length === 0) { + unusedLocals.push(row); + } + } + } + + if (unusedLocals.length > 0) { + const unusedCount = unusedLocals.length; + let message = this.msg("unused-var", { + count: unusedCount, + }); + for (let i = 0; i < unusedLocals.length; i++) { + let orphan = unusedLocals[i]; + if (i > 0) { + message += ", "; + } + message += orphan.name; + } + if (confirm(message)) { + for (const orphan of unusedLocals) { + workspace.deleteVariableById(orphan.getId()); + } + } + } + + UndoGroup.endUndoGroup(workspace); + }, 100); + } + + /** + * Badly Ophaned - might want to delete these! + * @param topBlock + * @returns {boolean} + */ + isBlockAnOrphan(topBlock) { + return !!topBlock.outputConnection; + } + + /** + * Split the top blocks into ordered columns + * @param separateOrphans true to keep all orphans separate + * @returns {{orphans: {blocks: [Block], x: number, count: number}, cols: [Col]}} + */ + getOrderedTopBlockColumns(separateOrphans) { + let w = this.utils.getWorkspace(); + let topBlocks = w.getTopBlocks(); + let maxWidths = {}; + + if (separateOrphans) { + let topComments = w.getTopComments(); + + // todo: tie comments to blocks... find widths and width of block stack row... + for (const comment of topComments) { + // comment.autoPosition_(); + // Hiding and showing repositions the comment right next to it's block - nice! + if (comment.setVisible) { + comment.setVisible(false); + comment.needsAutoPositioning_ = true; + comment.setVisible(true); + + // let bb = comment.block_.svgPath_.getBBox(); + let right = comment.getBoundingRectangle().bottomRight.x; + + // Get top block for stack... + let root = comment.block_.getRootBlock(); + let left = root.getBoundingRectangle().topLeft.x; + maxWidths[root.id] = Math.max(right - left, maxWidths[root.id] || 0); + } + } + } + + // Default scratch ordering is horrid... Lets try something more clever. + + /** + * @type {Col[]} + */ + let cols = []; + const TOLERANCE = 256; + let orphans = { x: -999999, count: 0, blocks: [] }; + + for (const topBlock of topBlocks) { + // let r = b.getBoundingRectangle(); + let position = topBlock.getRelativeToSurfaceXY(); + /** + * @type {Col} + */ + let bestCol = null; + let bestError = TOLERANCE; + + if (separateOrphans && this.isBlockAnOrphan(topBlock)) { + orphans.blocks.push(topBlock); + continue; + } + + // Find best columns + for (const col of cols) { + let err = Math.abs(position.x - col.x); + if (err < bestError) { + bestError = err; + bestCol = col; + } + } + + if (bestCol) { + // We found a column that we fitted into + bestCol.x = (bestCol.x * bestCol.count + position.x) / ++bestCol.count; // re-average the columns as more items get added... + bestCol.blocks.push(topBlock); + } else { + // Create a new column + cols.push(new Col(position.x, 1, [topBlock])); + } + } + + // if (orphans.blocks.length > 0) { + // cols.push(orphans); + // } + + // Sort columns, then blocks inside the columns + cols.sort((a, b) => a.x - b.x); + for (const col of cols) { + col.blocks.sort((a, b) => a.getRelativeToSurfaceXY().y - b.getRelativeToSurfaceXY().y); + } + + return { cols: cols, orphans: orphans, maxWidths: maxWidths }; + } + + /** + * Find all the uses of a named variable. + * @param {string} id ID of the variable to find. + * @return {!Array.} Array of block usages. + */ + getVariableUsesById(id) { + let uses = []; + + let topBlocks = this.getTopBlocks(true); // todo: Confirm this was the right getTopBlocks? + for (const topBlock of topBlocks) { + /** @type {!Array} */ + let kids = topBlock.getDescendants(); + for (const block of kids) { + /** @type {!Array} */ + let blockVariables = block.getVarModels(); + if (blockVariables) { + for (const blockVar of blockVariables) { + if (blockVar.getId() === id) { + uses.push(block); + } + } + } + } + } + + return uses; + } + + /** + * Find all the uses of a named procedure. + * @param {string} id ID of the variable to find. + * @return {!Array.} Array of block usages. + */ + getCallsToProcedureById(id) { + let w = this.utils.getWorkspace(); + let procBlock = w.getBlockById(id); + let label = procBlock.getChildren()[0]; + let procCode = label.getProcCode(); + + let uses = [procBlock]; // Definition First, then calls to it + let topBlocks = this.getTopBlocks(true); + for (const topBlock of topBlocks) { + /** @type {!Array} */ + let kids = topBlock.getDescendants(); + for (const block of kids) { + if (block.type === "procedures_call") { + if (block.getProcCode() === procCode) { + uses.push(block); + } + } + } + } + + return uses; + } + + /** + * Find all the uses of a named procedure. + * @param {string} name name of the variable to find. + * @return {!Array.} Array of block usages. + */ + getCallsToEventsByName(name) { + let uses = []; // Definition First, then calls to it + + const runtime = this.vm.runtime; + const targets = runtime.targets; // The sprites / stage + + for (const target of targets) { + if (!target.isOriginal) { + continue; // Skip clones + } + + const blocks = target.blocks; + if (!blocks._blocks) { + continue; + } + + // blocks._blocks is not iterable, have to do it using an 'in' + for (const id in blocks._blocks) { + if (!blocks._blocks.hasOwnProperty(id)) { + continue; + } + const block = blocks._blocks[id]; + // To find event broadcaster blocks, we look for the nested "event_broadcast_menu" blocks first that match the event name + if (block.opcode === "event_broadcast_menu" && block.fields.BROADCAST_OPTION.value === name) { + // Now get the parent block that is the actual broadcast or broadcast and wait + const broadcastBlock = blocks.getBlock(block.parent); + uses.push(new BlockInstance(target, broadcastBlock)); + } else if (block.opcode === "event_whenbroadcastreceived" && block.fields.BROADCAST_OPTION.value === name) { + uses.push(new BlockInstance(target, block)); + } + } + } + + return uses; + } + + /** + * Find all the evern broadcasters. + * @return {[{eventName:string, block:Block}]} Array of event names and blocks. + */ + getCallsToEvents() { + const uses = []; // Definition First, then calls to it + const found = {}; + + let topBlocks = this.getTopBlocks(true); + for (const topBlock of topBlocks) { + /** @type {!Array} */ + let kids = topBlock.getDescendants(); + for (const block of kids) { + if (block.type === "event_broadcast" || block.type === "event_broadcastandwait") { + const eventName = block.getChildren()[0].inputList[0].fieldRow[0].getText(); + if (!found[eventName]) { + found[eventName] = block; + uses.push({ eventName: eventName, block: block }); + } + } + } + } + + return uses; + } + + buildNavigationCarousel(nav, li, blocks, instanceBlock) { + if (nav && nav.parentNode === li) { + // Same control... click again to go to next + this.multi.navRight(); + } else { + if (nav) { + nav.remove(); + } + li.insertAdjacentHTML( + "beforeend", + ` + + + + ` + ); + document.getElementById("s3devMultiLeft").addEventListener("mousedown", (...e) => this.multi.navLeft(...e)); + document.getElementById("s3devMultiRight").addEventListener("mousedown", (...e) => this.multi.navRight(...e)); + + this.multi.idx = 0; + + if (instanceBlock) { + for (let i = 0; i < blocks.length; i++) { + const block = blocks[i]; + if (block.id === instanceBlock.id) { + this.multi.idx = i; + break; + } + } + // multi.idx = blocks.indexOf(instanceBlock); + } + + this.multi.blocks = blocks; + this.multi.update(); + + if (this.multi.idx < blocks.length) { + this.centerTop(blocks[this.multi.idx]); + } + } + } + + /** + * Move a costume to the top or bottom of the list + * @param top true for the top, false for the bottom + * @param selected optional parameter to pass in the costume div to be moved + */ + moveCostumeTo(top, selected) { + let isSelected = !selected || selected.className.indexOf("sprite-selector-item_is-selected") >= 0; + if (!selected) { + selected = this.costTabBody.querySelectorAll("div[class*='sprite-selector-item_is-selected']"); + if (selected.length === 0) { + return; + } + selected = selected[0].querySelectorAll("div[class^='sprite-selector-item_sprite-name']")[0]; + } + let costumes = this.costTabBody.querySelectorAll("div[class^='sprite-selector-item_sprite-name']"); + + // First scroll sprite view to reveal top or bottom otherwise this won't work. + let scroller = selected.closest("div[class*=selector_list-area]"); + let lastScroll = scroller.scrollTop; + scroller.scrollTop = top ? 0 : scroller.scrollHeight; + + this.domHelpers.triggerDragAndDrop(selected, costumes[top ? 0 : costumes.length - 1], undefined); + if (!isSelected) { + // Restore Scroll position + scroller.scrollTop = lastScroll; + } + } + + /** + * + * @param li + * @param workspace + * @param instanceBlock the instance to be highlighted (or null) + */ + clickDropDownRow(li, workspace, instanceBlock) { + let nav = document.getElementById("s3devMulti"); + + let cls = li.data.cls; + if (cls === "costume") { + // Viewing costumes - jump to selected costume + let costumes = this.costTabBody.querySelectorAll("div[class^='sprite-selector-item_sprite-name']"); + let costume = costumes[li.data.y]; + if (costume) { + costume.click(); + setTimeout(() => { + let wrapper = costume.closest("div[class*=gui_flex-wrapper]"); + costume.parentElement.parentElement.scrollIntoView({ + behavior: "auto", + block: "center", + inline: "start", + }); + wrapper.scrollTop = 0; + }, 10); + } + } else if (cls === "var" || cls === "VAR" || cls === "list" || cls === "LIST") { + // Search now for all instances + // let wksp = getWorkspace(); + // let blocks = wksp.getVariableUsesById(li.data.labelID); + let blocks = this.getVariableUsesById(li.data.labelID); + this.buildNavigationCarousel(nav, li, blocks, instanceBlock); + } else if (cls === "define") { + let blocks = this.getCallsToProcedureById(li.data.labelID); + this.buildNavigationCarousel(nav, li, blocks, instanceBlock); + } else if (cls === "receive") { + /* + let blocks = [workspace.getBlockById(li.data.labelID)]; + if (li.data.clones) { + for (const cloneID of li.data.clones) { + blocks.push(workspace.getBlockById(cloneID)) + } + } + blocks = blocks.concat(getCallsToEventsByName(li.data.eventName)); + */ + // Now, fetch the events from the scratch runtime instead of blockly + let blocks = this.getCallsToEventsByName(li.data.eventName); + if (!instanceBlock) { + // Can we start by selecting the first block on 'this' sprite + const currentTargetID = this.utils.getEditingTarget().id; + for (const block of blocks) { + if (block.targetId === currentTargetID) { + instanceBlock = block; + break; + } + } + } + this.buildNavigationCarousel(nav, li, blocks, instanceBlock); + } else if (li.data.clones) { + let blocks = [workspace.getBlockById(li.data.labelID)]; + for (const cloneID of li.data.clones) { + blocks.push(workspace.getBlockById(cloneID)); + } + this.buildNavigationCarousel(nav, li, blocks, instanceBlock); + } else { + this.multi.blocks = null; + this.centerTop(li.data.labelID); + if (nav) { + nav.remove(); + } + } + } + + dropDownClick(e) { + // console.log(e); + let workspace = this.utils.getWorkspace(); + + if (prevVal === null) { + prevVal = this.findInp.value; // Hack to stop filter change if not entered data into edt box, but clicked on row + } + + let li = e.target; + for (;;) { + if (!li || li === this.dd) { + return; + } + if (li.data) { + break; + } + li = li.parentNode; + } + + // If this was a mouse click, unselect the keyboard selection + // e.navKey is set when this is called from the keyboard handler... + if (!e.navKey) { + let sel = this.dd.getElementsByClassName("sel"); + sel = sel.length > 0 ? sel[0] : null; + if (sel && sel !== li) { + try { + sel.classList.remove("sel"); + } catch (e) { + console.log(sel); + console.error(e); + } + } + if (li !== sel) { + li.classList.add("sel"); + } + } + + this.clickDropDownRow(li, workspace); + if (e && e.preventDefault) { + e.preventDefault(); + e.cancelBubble = true; + } + return false; + } + + /** + * Based on wksp.centerOnBlock(li.data.labelID); + * @param e + * @param force if true, the view always moves, otherwise only move if the selected element is not entirely visible + */ + centerTop(e, force) { + this.utils.scrollBlockIntoView(e, force); + } + + inputChange(e) { + if (!this.ddOut.classList.contains("vis")) { + this.showDropDown(); + this.hideDropDown(); // Start timer to hide if not got focus + } + + // Filter the list... + let val = (this.findInp.value || "").toLowerCase(); + if (val === prevVal) { + // No change so don't re-filter + return; + } + + prevVal = val; + this.multi.blocks = null; + + // + // Hide items in list that do not contain filter text, and highlight the parts of words that match the filter text + + let listLI = this.dd.getElementsByTagName("li"); + for (const li of listLI) { + let procCode = li.data.procCode; + let i = li.data.lower.indexOf(val); + if (i >= 0) { + li.style.display = "block"; + this.dom_removeChildren(li); + if (i > 0) { + li.appendChild(document.createTextNode(procCode.substring(0, i))); + } + let bText = document.createElement("b"); + bText.appendChild(document.createTextNode(procCode.substr(i, val.length))); + li.appendChild(bText); + if (i + val.length < procCode.length) { + li.appendChild(document.createTextNode(procCode.substr(i + val.length))); + } + // li.innerHTML = enc(procCode.substring(0, i)) + '' + enc(procCode.substr(i, val.length)) + "" + enc(procCode.substr(i + val.length)); + } else { + li.style.display = "none"; + } + } + } + + /** + * Select previous or next item in the drop down filter list + * @param dir direction of navigation: -1=up, 1=down + */ + navigateFilter(dir) { + let sel = this.dd.getElementsByClassName("sel"); + let nxt; + if (sel.length > 0 && sel[0].style.display !== "none") { + nxt = dir === -1 ? sel[0].previousSibling : sel[sel.length - 1].nextSibling; + } else { + nxt = this.dd.children[0]; + dir = 1; + } + while (nxt && nxt.style.display === "none") { + nxt = dir === -1 ? nxt.previousSibling : nxt.nextSibling; + } + if (nxt) { + for (const i of sel) { + i.classList.remove("sel"); + } + nxt.classList.add("sel"); + this.dropDownClick({ target: nxt, navKey: true }); + // centerTop(nxt.data.labelID); + } + } + + inputKeyDown(e) { + // Up Arrow + if (e.keyCode === 38) { + this.navigateFilter(-1); + e.preventDefault(); + return; + } + + // Down Arrow + if (e.keyCode === 40) { + this.navigateFilter(1); + e.preventDefault(); + return; + } + + // Left Arrow + if (e.keyCode === 37) { + let sel = this.dd.getElementsByClassName("sel"); + if (sel && this.multi.blocks) { + this.multi.navLeft(e); + } + } + + // Right Arrow + if (e.keyCode === 39) { + let sel = this.dd.getElementsByClassName("sel"); + if (sel && this.multi.blocks) { + this.multi.navRight(e); + } + } + + // Enter + if (e.keyCode === 13) { + // Any selected on enter? if not select now + let sel = this.dd.getElementsByClassName("sel"); + if (sel.length === 0) { + this.navigateFilter(1); + } + document.activeElement.blur(); + e.preventDefault(); + return; + } + + // Escape + if (e.keyCode === 27) { + if (this.findInp.value.length > 0) { + this.findInp.value = ""; // Clear search first, then close on second press + this.inputChange(e); + } else { + document.activeElement.blur(); + } + e.preventDefault(); + return; + } + } + + /* + function deepSearch(e) { + document.body.insertAdjacentHTML( + "beforeend", + ` +
+
+ ` + ); + + let overlay = document.getElementById("s3devOverlay"); + overlay.addEventListener("click", function (e) { + overlay.remove(); + }); + + // todo: use scratch runtime instead! + + const runtime = vm.runtime; + const targets = runtime.targets; // The sprites / stage + + let dict = {}; + + for (const target of targets) { + if (!target.isOriginal) { + continue; // Skip clones + } + + const name = target.getName(); + const isStage = target.isStage; + const blocks = target.blocks; + const scripts = blocks.getScripts(); + + let divElement = document.createElement("div"); + divElement.appendChild(document.createTextNode("Searching in " + name)); + divElement.appendChild(document.createTextNode(", Top Scripts x" + scripts.length)); + overlay.appendChild(divElement); + + const sprite = (dict[name] = {}); + sprite.scripts = []; + + for (const script of scripts) { + const block = blocks.getBlock(script); + const top = { id: script, opcode: block.opcode, block: block }; + sprite.scripts.push(top); + } + } + + e.preventDefault(); + return true; + } + */ + + /** + * Quick and dirty replace all instances of one variable / list with another variable / list + * @param varId original variable name + * @param newVarName new variable name + * @param type type of variable ("" = variable, anything else is a list? + */ + doReplaceVariable(varId, newVarName, type) { + let wksp = this.utils.getWorkspace(); + let v = wksp.getVariable(newVarName, type); + if (!v) { + alert(this.msg("var-not-exist")); + return; + } + let newVId = v.getId(); + + UndoGroup.startUndoGroup(wksp); + let blocks = this.getVariableUsesById(varId); + for (const block of blocks) { + try { + if (type === "") { + block.getField("VARIABLE").setValue(newVId); + } else { + block.getField("LIST").setValue(newVId); + } + } catch (e) { + // ignore + } + } + UndoGroup.endUndoGroup(wksp); + } + + /* + function doInjectScripts(codeString) { + let w = getWorkspace(); + let xml = new XML(); // document.implementation.createDocument(null, "xml"); + let x = xml.xmlDoc.firstChild; + + let tree = math.parse(codeString); + console.log(tree); + + const binaryOperatorTypes = { + add: "operator_add", + subtract: "operator_subtract", + this.multiply: "operator_multiply", + divide: "operator_divide", + }; + + const BLOCK_TYPE = { + number: "math_number", + text: "text", + }; + + function translateMathToXml(x, tree, shadowType) { + let xShadowField = null; + if (shadowType) { + let xShadow = xml.newXml(x, "shadow", { type: shadowType }); + if (shadowType === BLOCK_TYPE.number) { + xShadowField = xml.newXml(xShadow, "field", { name: "NUM" }); + } else if (shadowType === BLOCK_TYPE.text) { + xShadowField = xml.newXml(xShadow, "field", { name: "TEXT" }); + } + } + + if (!tree || !tree.type) { + return; + } + + if (tree.type === "OperatorNode") { + let operatorType = binaryOperatorTypes[tree.fn]; + if (operatorType) { + let xOp = newXml(x, "block", { type: operatorType }); + translateMathToXml(xml.newXml(xOp, "value", { name: "NUM1" }), tree.args[0], BLOCK_TYPE.number); + translateMathToXml(xml.newXml(xOp, "value", { name: "NUM2" }), tree.args[1], BLOCK_TYPE.number); + return; + } + + return; + } + + if (tree.type === "ConstantNode") { + // number or text in quotes + if (xShadowField) { + xml.setAttr(xShadowField, { text: tree.value }); + } + return; + } + + if (tree.type === "SymbolNode") { + // variable + let xVar = xml.newXml(x, "block", { type: "data_variable" }); + xml.newXml(xVar, "field", { name: "VARIABLE", text: tree.name }); + return; + } + + if (tree.type === "FunctionNode") { + // Method Call + if (tree.fn.name === "join") { + let xOp = newXml(x, "block", { type: "operator_join" }); + translateMathToXml(xml.newXml(xOp, "value", { name: "STRING1" }), tree.args[0], BLOCK_TYPE.text); + translateMathToXml(xml.newXml(xOp, "value", { name: "STRING2" }), tree.args[1], BLOCK_TYPE.text); + return; + } + } + } + + translateMathToXml(x, tree); + console.log(x); + + let ids = Blockly.Xml.domToWorkspace(x, w); + console.log(ids); + } + */ + + /* + function clickCleanUp(e) { + // if (window.confirm('Griffpatch: Tidy up your scripts?')) { + doCleanUp(); + // } + e.preventDefault(); + return false; + } + */ + + /* + function clickInject(e) { + let codeString = window.prompt("Griffpatch: Enter an expression (i.e. a+2*3)"); + if (codeString) { + doInjectScripts(codeString); + } + e.preventDefault(); + return false; + } + */ + + /** + * Click Event Handler - User has clicked the replace variable option - ask for the variable to replace with... + * @param e the event + * @returns {boolean} cancelled? + */ + clickReplace(e) { + let wksp = this.utils.getWorkspace(); + this.hidePopups(wksp); + + setTimeout(() => { + let wksp = this.utils.getWorkspace(); + let v = wksp.getVariableById(this.selVarID); + let varName = window.prompt(this.msg("replace", { name: v.name })); + if (varName) { + this.doReplaceVariable(this.selVarID, varName, v.type); + } + }, 0); + e.preventDefault(); + return false; + } + + /** + * Returns a Set of the top blocks in this workspace / sprite + * @returns {Set} Set of top blocks + */ + getTopBlockIDs() { + let wksp = this.utils.getWorkspace(); + let topBlocks = wksp.getTopBlocks(); + let ids = new Set(); + for (const block of topBlocks) { + ids.add(block.id); + } + return ids; + } + + /** + * Initiates a drag event for all block stacks expect those in the set of ids. + * But why? - Because we know all the ids of the existing stacks before we paste / duplicate - so we can find the + * new stack by excluding all the known ones. + * @param ids Set of previously known ids + */ + beginDragOfNewBlocksNotInIDs(ids) { + let wksp = this.utils.getWorkspace(); + let topBlocks = wksp.getTopBlocks(); + for (const block of topBlocks) { + if (!ids.has(block.id)) { + // console.log("I found a new block!!! - " + block.id); + // todo: move the block to the mouse pointer? + let mouseXYClone = { x: this.mouseXY.x, y: this.mouseXY.y }; + this.domHelpers.triggerDragAndDrop(block.svgPath_, null, mouseXYClone); + } + } + } + + eventMouseMove(e) { + this.mouseXY.x = e.clientX; + this.mouseXY.y = e.clientY; + } + + eventKeyDown(e) { + function switchCostume(up) { + // todo: select previous costume + let selected = this.costTabBody.querySelector("div[class*='sprite-selector-item_is-selected']"); + let node = up ? selected.parentNode.previousSibling : selected.parentNode.nextSibling; + if (node) { + let wrapper = node.closest("div[class*=gui_flex-wrapper]"); + node.querySelector("div[class^='sprite-selector-item_sprite-name']").click(); + node.scrollIntoView({ + behavior: "auto", + block: "center", + inline: "start", + }); + wrapper.scrollTop = 0; + } + } + + if (document.URL.indexOf("editor") <= 0) { + return; + } + + let ctrlKey = e.ctrlKey || e.metaKey; + + if (e.key === "f" && ctrlKey) { + // Ctrl + F (Override default Ctrl+F find) + this.findInp.focus(); + this.findInp.select(); + e.cancelBubble = true; + e.preventDefault(); + return true; + } + + if (e.key === " " && ctrlKey) { + // Ctrl + Space (Inject Code) + this.middleClickWorkspace(e); + e.cancelBubble = true; + e.preventDefault(); + return true; + } + + if (e.keyCode === 37 && ctrlKey) { + // Ctrl + Left Arrow Key + if (document.activeElement.tagName === "INPUT") { + return; + } + if (this.isScriptEditor()) { + this.utils.navigationHistory.goBack(); + } else if (this.isCostumeEditor()) { + switchCostume(true); + } + e.cancelBubble = true; + e.preventDefault(); + return true; + } + + if (e.keyCode === 39 && ctrlKey) { + // Ctrl + Right Arrow Key + if (document.activeElement.tagName === "INPUT") { + return; + } + if (this.isScriptEditor()) { + this.utils.navigationHistory.goForward(); + } else if (this.isCostumeEditor()) { + switchCostume(false); + } + e.cancelBubble = true; + e.preventDefault(); + return true; + } + + if (e.keyCode === 86 && ctrlKey && !e.griff) { + // Ctrl + V + // Set a timeout so we can take control of the paste after the event + let ids = this.getTopBlockIDs(); + setTimeout(() => { + this.beginDragOfNewBlocksNotInIDs(ids); + }, 10); + } + + // if (e.keyCode === 220 && (!document.activeElement || document.activeElement.tagName === 'INPUT')) { + // + // } + } + + eventMouseDown(e) { + if (this.ddOut && this.ddOut.classList.contains("vis") && !e.target.closest("#s3devDDOut")) { + // If we click outside the dropdown, then instigate the hide code... + this.hideDropDown(); + } + + if (this.floatInp && !e.target.closest("#s3devIDDOut")) { + // If we click outside the dropdown, then instigate the hide code... + this.hideFloatDropDown(); + } + + if (e.button === 1) { + // Wheel button... + try { + this.middleClick(e); + } catch (x) { + console.error(x); + } + } else if (e.button === 2) { + // Right click... + let spriteSelector = e.target.closest("div[class*='sprite-selector-item_sprite-selector-item']"); + if (spriteSelector) { + let contextMenu = spriteSelector.getElementsByTagName("nav")[0]; + if (!contextMenu.querySelector("div.s3devSTT")) { + contextMenu.insertAdjacentHTML( + "beforeend", + ` + + + ` + ); + } + } + + let blockSvg = e.target.closest("[data-id]"); + let isBackground = !blockSvg && e.target.closest("svg.blocklySvg"); + if (blockSvg || isBackground) { + let dataId = blockSvg && blockSvg.getAttribute("data-id"); + if (dataId || isBackground) { + let devTools = this; + setTimeout(() => { + // Is there a popup menu to hi-jack? + let widget = document.querySelector("div.blocklyWidgetDiv"); + if (!widget) { + return; + } + let blocklyContextMenu = widget.querySelector("div.blocklyContextMenu"); + if (!blocklyContextMenu) { + return; + } + if (isBackground) { + let nodes = blocklyContextMenu.children; + for (const node of nodes) { + if (node.textContent === "Clean up Blocks") { + node.remove(); + } + } + blocklyContextMenu.insertAdjacentHTML( + "beforeend", + ` + + + ` + ); + } else { + let wksp = this.utils.getWorkspace(); + let block = wksp.getBlockById(dataId); + let isFlyOut = block.workspace.isFlyout; + + /* todo - look at this menu code ***** !!!!! + const BROADCAST_BLOCKS = ["event_whenbroadcastreceived", "event_broadcast", "event_broadcastandwait"]; + if (BROADCAST_BLOCKS.includes(block.type)) { + // Show Broadcast + const broadcastId = showBroadcastSingleton.getAssociatedBroadcastId(dataId); + if (broadcastId) { + for (const showKey of ["Senders", "Receivers"]) { + const googMenuItemContent = Object.assign(document.createElement("div"), { + textContent: this.msg(`show-${showKey}`.toLowerCase()), + style: "user-select: none;", + className: "goog-menuitem-content", + }); + const googMenuItem = Object.assign(document.createElement("div"), { + id: `s3devShow${showKey}`, + className: "goog-menuitem s3dev-mi", + role: "menuitem", + style: "user-select: none;", + }); + googMenuItem.addEventListener("click", () => { + hidePopups(wksp); + showBroadcastSingleton[`show${showKey}`](broadcastId); + }); + googMenuItem.appendChild(googMenuItemContent); + blocklyContextMenu.appendChild(googMenuItem); + } + } + } + */ + + if (!isFlyOut) { + blocklyContextMenu.insertAdjacentHTML( + "beforeend", + ` + + + + ` + ); + } + + // Is this a variable or a list? + if (block && (block.getCategory() === "data" || block.getCategory() === "data-lists")) { + blocklyContextMenu.insertAdjacentHTML( + "beforeend", + ` + + ` + ); + this.selVarID = block.getVars()[0]; + } + } + + if (blocklyContextMenu.children.length < 15) { + blocklyContextMenu.style.maxHeight = "none"; + widget.style.height = blocklyContextMenu.getBoundingClientRect().height + 12 + "px"; + blocklyContextMenu.style.maxHeight = ""; + } + + let copyDiv = blocklyContextMenu.querySelector("div#s3devCleanUp"); + if (copyDiv) { + copyDiv.addEventListener("click", (...e) => this.doCleanUp(...e)); + } + copyDiv = blocklyContextMenu.querySelector("div#s3devCopy"); + if (copyDiv) { + copyDiv.addEventListener("click", (...e) => eventCopyClick(...e)); + } + copyDiv = blocklyContextMenu.querySelector("div#s3devCopyBlock"); + if (copyDiv) { + copyDiv.addEventListener("click", (e) => { + eventCopyClick(e, 1); + }); + } + copyDiv = blocklyContextMenu.querySelector("div#s3devCutBlock"); + if (copyDiv) { + copyDiv.addEventListener("click", (e) => { + eventCopyClick(e, 2); + }); + } + copyDiv = blocklyContextMenu.querySelector("div#s3devReplaceAllVars"); + if (copyDiv) { + copyDiv.addEventListener("click", (...e) => this.clickReplace(...e)); + } + + let devTools = this; + function eventCopyClick(e, blockOnly) { + let wksp = devTools.utils.getWorkspace(); + devTools.hidePopups(wksp); + + let block = wksp.getBlockById(dataId); + if (block) { + block.select(); + let next = blockOnly ? block.getNextBlock() : null; + if (next) { + next.unplug(false); // setParent(null); + } + + // separate child temporarily + document.dispatchEvent(new KeyboardEvent("keydown", { keyCode: 67, ctrlKey: true })); + if (next || blockOnly === 2) { + setTimeout(() => { + if (next) { + wksp.undo(); // undo the unplug above... + } + if (blockOnly === 2) { + let block = wksp.getBlockById(dataId); + UndoGroup.startUndoGroup(wksp); + block.dispose(true); + UndoGroup.endUndoGroup(wksp); + } + }, 0); + } + } + } + + let pasteDiv = blocklyContextMenu.querySelector("div#s3devPaste"); + if (pasteDiv) { + pasteDiv.addEventListener("click", function () { + let wksp = devTools.utils.getWorkspace(); + devTools.hidePopups(wksp); + + let ids = devTools.getTopBlockIDs(); + + document.dispatchEvent( + new KeyboardEvent("keydown", { + keyCode: 86, + ctrlKey: true, + griff: true, + }) + ); + + setTimeout(() => { + devTools.beginDragOfNewBlocksNotInIDs(ids); + }, 10); + }); + } + }, 1); + } + } + } else { + let chk = e.target; + if (chk && chk.tagName !== "BUTTON" && chk.getAttribute && !chk.getAttribute("role")) { + chk = chk.parentNode; + if (chk && chk.tagName !== "BUTTON" && chk.getAttribute && !chk.getAttribute("role")) { + chk = chk.parentNode; + } + } + + if (chk && chk.className && chk.className.indexOf) { + if (chk.className.indexOf("see-inside-button") >= 0) { + // Try to re-inject GUI after rebuild + setTimeout(() => this.initInner(), 200); + } + + if (!this.canShare && chk.className.indexOf("share-button") >= 0) { + // Commented for ScratchAddons + /*e.cancelBubble = true; + e.preventDefault(); + + if (confirm("Griffpatch: Are you sure you want to share?")) { + // action the share! + canShare = true; + chk.click(); + }*/ + + return; + } + } + + chk = e.target.tagName === "SPAN" ? e.target.parentNode : e.target; + + if (chk.classList.contains("s3devSTT")) { + if (chk.textContent === this.m("top") || chk.textContent === this.m("bottom")) { + let spriteSelector = e.target.closest("div[class*='sprite-selector-item_sprite-selector-item']"); + this.moveCostumeTo(chk.textContent === this.m("top"), spriteSelector); + e.cancelBubble = true; + e.preventDefault(); + } + } + } + } + + middleClickWorkspace(e) { + if (!this.isScriptEditor()) { + return; + } + + e.cancelBubble = true; + e.preventDefault(); + + let floatBar = document.getElementById("s3devFloatingBar"); + if (floatBar) { + floatBar.remove(); + } + + // Popup new input box for block injection + document.body.insertAdjacentHTML( + "beforeend", + ` +
+ +
+ ` + ); + + floatBar = document.getElementById("s3devFloatingBar"); + floatBar.style.left = this.mouseXY.x + 16 + "px"; + floatBar.style.top = this.mouseXY.y - 8 + "px"; + + this.floatInp = document.getElementById("s3devIInp"); + this.floatInp.focus(); + + // Build Filter List... + + this.buildFloatingFilterList(e, floatBar); + + const ddOut = document.getElementById("s3devIDDOut"); + ddOut.addEventListener("mousedown", (...e) => this.dropDownFloatClick(...e)); + + this.floatInp.addEventListener("keyup", (...e) => this.floatInputChange(...e)); + this.floatInp.addEventListener("focus", (...e) => this.floatInputChange(...e)); + this.floatInp.addEventListener("keydown", (...e) => this.floatInputKeyDown(...e)); + } + + middleClick(e) { + // Intercept clicks to allow jump to...? + let blockSvg = e.target.closest("[data-id]"); + if (!blockSvg) { + // Ok, so no selection... are we at least clicking on the workspace? + if (e.target.closest("svg.blocklySvg")) { + this.blockCursor = null; // Clear the cursor if using the mouse + this.middleClickWorkspace(e); + } + return; + } + + let w = this.utils.getWorkspace(); + let dataId = blockSvg.getAttribute("data-id"); + let block = w.getBlockById(dataId); + if (!block) { + return; + } + + // Move outwards until we reach a block we can take action on + + for (; block; block = block.getSurroundParent()) { + if (block.type === "procedures_call") { + e.cancelBubble = true; + e.preventDefault(); + + // todo: navigate to definition + let findProcCode = block.getProcCode(); + + let wksp = this.utils.getWorkspace(); + let topBlocks = wksp.getTopBlocks(); + for (const root of topBlocks) { + if (root.type === "procedures_definition") { + let label = root.getChildren()[0]; + let procCode = label.getProcCode(); + if (procCode && procCode === findProcCode) { + // Found... navigate to it! + this.centerTop(root); + return; + } + } + } + } + + if (block.type === "procedures_definition") { + let id = block.id ? block.id : block.getId ? block.getId() : null; + + this.findInp.focus(); + this.showDropDown(null, id); + // findInp.select(); + + e.cancelBubble = true; + e.preventDefault(); + return; + } + + if ( + block.type === "data_variable" || + block.type === "data_changevariableby" || + block.type === "data_setvariableto" + ) { + let id = block.getVars()[0]; + + this.findInp.focus(); + this.showDropDown(null, id, block); + + // let button = document.getElementById('s3devReplace'); + + this.selVarID = id; + // button.classList.remove('s3devHide'); + + e.cancelBubble = true; + e.preventDefault(); + return; + } + + if ( + block.type === "event_whenbroadcastreceived" || + block.type === "event_broadcastandwait" || + block.type === "event_broadcast" + ) { + // todo: actually index the broadcasts...! + let id = block.id; + + this.findInp.focus(); + this.showDropDown(null, id, block); + + this.selVarID = id; + + e.cancelBubble = true; + e.preventDefault(); + return; + } + } + + e.cancelBubble = true; + e.preventDefault(); + } + + getEdgeTypeClass(block) { + switch (block.edgeShape_) { + case 1: + return "boolean"; + case 2: + return "reporter"; + default: + return block.startHat_ ? "hat" : "block"; + } + } + + buildFloatingFilterList(e, floatBar) { + // todo: Iterate through the toolbox? + + let options = []; + + let t = Blockly.getMainWorkspace().getToolbox(); + + let blocks = t.flyout_.getWorkspace().getTopBlocks(); + // 107 blocks, not in order... but we can sort by y value or description right :) + + let fullDom = Blockly.Xml.workspaceToDom(t.flyout_.getWorkspace()); + const doms = {}; + for (const x of fullDom.children) { + if (x.tagName === "BLOCK") { + // let type = x.getAttribute('type'); + let id = x.getAttribute("id"); + doms[id] = x; + } + } + + for (const block of blocks) { + this.getBlockText(block, options, doms); + } + + // Griffpatch - on second thoughts - lets sort blocks by length so that shortest ones appear at the top. + options.sort((a, b) => + a.desc.length < b.desc.length ? -1 : a.desc.length > b.desc.length ? 1 : a.desc.localeCompare(b.desc) + ); + + // Previous sort was just alphabetical + // options.sort((a, b) => a.desc.localeCompare(b.desc)); + + const dd = document.getElementById("s3devIDD"); + + let count = 0; + //DROPDOWN_BLOCK_LIST_MAX_ROWS + + for (const option of options) { + const li = document.createElement("li"); + const desc = option.desc; + + // bType = hat block reporter boolean + + let bType = this.getEdgeTypeClass(option.block); + + count++; + + li.innerText = desc; + li.data = { text: desc, lower: " " + desc.toLowerCase(), option: option }; + li.className = + "var " + (option.block.isScratchExtension ? "extension" : option.block.getCategory()) + " " + bType; // proc.cls; + if (count > DROPDOWN_BLOCK_LIST_MAX_ROWS) { + // Limit maximum number of rows to prevent lag when no filter is applied + li.style.display = "none"; + } + dd.appendChild(li); + } + + const ddOut = document.getElementById("s3devIDDOut"); + ddOut.classList.add("vis"); + + // console.log(options); + } + + /** + * Flesh out a blocks description - duplicate up blocks with contained picklists (like list drop downs) + * @param block + * @param options + * @param doms + * @returns {string} + */ + getBlockText(block, options, doms) { + // block.type; "looks_nextbackdrop" + + let desc; + let picklist, pickField; + + let dom = doms[block.id]; + + // dom = doms[block.type]; + + const process = (block) => { + for (const input of block.inputList) { + // input.name = "", input.type = 5 + let fields = input.fieldRow; + for (const field of fields) { + // field --- Blockly.FieldLabel .className = "blocklyText" + // Blockly.FieldDropdown --- .className = "blocklyText blocklyDropdownText" + + let text; + + if (!picklist && field.className_ === "blocklyText blocklyDropdownText") { + picklist = field.getOptions(); + pickField = field.name; + if (picklist && picklist.length > 0) { + text = "^^"; + } else { + text = field.getText(); + } + } else { + text = field.getText(); + } + + desc = (desc ? desc + " " : "") + text; + } + + if (input.connection) { + let innerBlock = input.connection.targetBlock(); + if (innerBlock) { + process(innerBlock); // Recursive process connected child blocks... + } + } + } + }; + + process(block); + + if (picklist) { + for (const item of picklist) { + let code = item[1]; + if (code === "DELETE_VARIABLE_ID" || code === "RENAME_VARIABLE_ID") { + continue; // Skip these + } + options.push({ + desc: desc.replace("^^", item[0]), + block: block, + dom: dom, + option: item, + pickField: pickField, + }); + } + } else { + options.push({ desc: desc, block: block, dom: dom }); + } + + return desc; + } + + floatInputKeyDown(e) { + if (e.keyCode === 38) { + this.navigateFloatFilter(-1); + e.preventDefault(); + return; + } + if (e.keyCode === 40) { + this.navigateFloatFilter(1); + e.preventDefault(); + return; + } + if (e.keyCode === 13) { + // Enter + let dd = document.getElementById("s3devIDD"); + let sel = dd.querySelector(".sel"); + if (sel) { + this.dropDownFloatClick(e); + } + e.cancelBubble = true; + e.preventDefault(); + return; + } + if (e.keyCode === 27) { + // Escape + let findInp = document.getElementById("s3devIInp"); + if (findInp.value.length > 0) { + findInp.value = ""; // Clear search first, then close on second press + this.floatInputChange(e); + } else { + this.reallyHideFloatDropDown(true); + } + e.preventDefault(); + return; + } + } + + navigateFloatFilter(dir) { + let dd = document.getElementById("s3devIDD"); + let sel = dd.getElementsByClassName("sel"); + let nxt; + if (sel.length > 0 && sel[0].style.display !== "none") { + nxt = dir === -1 ? sel[0].previousSibling : sel[sel.length - 1].nextSibling; + } else { + nxt = dd.children[0]; + dir = 1; + } + while (nxt && nxt.style.display === "none") { + nxt = dir === -1 ? nxt.previousSibling : nxt.nextSibling; + } + if (nxt) { + for (const i of sel) { + i.classList.remove("sel"); + } + nxt.classList.add("sel"); + // centerTop(nxt.data.labelID); + } + } + + /** + * This is a feature in progress - can we have a virtual cursor that allows the next injected element position be automated + * @param block a blockly block + * @param typ type + */ + findNextHole(block, typ) { + /* + const inputs = block.inputList; + if (inputs) { + /!** Blockly.Input *!/ + for (const input of inputs) { + const fieldRow = input.fieldRow; + if (fieldRow) { + /!** Blockly.FieldNumber *!/ + for (const field of fieldRow) { + if (field.argType_ && field.argType_.includes(typ)) { + } + } + } + } + } + */ + } + + /** + * Inject the selected block into the script + * @param e + */ + dropDownFloatClick(e) { + e.cancelBubble = true; + e.preventDefault(); + + let wksp = this.utils.getWorkspace(); + + let sel = e && e.target; + if (sel.tagName === "B") { + sel = sel.parentNode; + } + + if (e instanceof MouseEvent && sel.tagName !== "LI") { + // Mouse clicks need to be on a block... + return; + } + + if (!sel || !sel.data) { + let dd = document.getElementById("s3devIDD"); + sel = dd.querySelector(".sel"); + } + + if (!sel) { + return; + } + + const xml = new XML(); + let x = xml.xmlDoc.firstChild; + let option = sel.data.option; + // block:option.block, dom:option.dom, option:option.option + if (option.option) { + // We need to tweak the dropdown in this xml... + let field = option.dom.querySelector("field[name=" + option.pickField + "]"); + field.innerText = option.option[0]; + field.setAttribute("id", option.option[1] + "-" + option.option[0]); + } + + x.appendChild(option.dom); + + let ids = Blockly.Xml.domToWorkspace(x, wksp); + + this.reallyHideFloatDropDown(true); + + let block = wksp.getBlockById(ids[0]); + + if (this.blockCursor) { + // What sort of block did we just inject? + let typ = this.getEdgeTypeClass(option.block); + if (typ === "boolean") { + this.findNextHole(this.blockCursor, ""); + } else if (typ === "reporter") { + this.findNextHole(this.blockCursor, typ); + } + } + + this.domHelpers.triggerDragAndDrop(block.svgPath_, null, { x: this.mouseXY.x, y: this.mouseXY.y }); + + this.blockCursor = block; + } + + floatInputChange(e) { + let ddOut = document.getElementById("s3devIDDOut"); + + if (!ddOut.classList.contains("vis")) { + // showDropDown(); + // hideDropDown(); // Start timer to hide if not got focus + } + + let findInp = document.getElementById("s3devIInp"); + + // Filter the list... + let val = (findInp.value || "").toLowerCase(); + if (val === prevVal) { + return; + } + + prevVal = val; + this.multi.blocks = null; + + let dd = document.getElementById("s3devIDD"); + let p = dd.parentNode; + dd.remove(); + + let count = 0; + + let split = val.split(" "); + let listLI = dd.getElementsByTagName("li"); + for (const li of listLI) { + const procCode = li.data.text; + const lower = li.data.lower; + // let i = li.data.lower.indexOf(val); + // let array = regExp.exec(li.data.lower); + + let im = 0; + let match = []; + for (let si = 0; si < split.length; si++) { + let find = " " + split[si]; + let idx = lower.indexOf(find, im); + if (idx === -1) { + match = null; + break; + } + match.push(idx); + im = idx + find.length; + } + + if (count < DROPDOWN_BLOCK_LIST_MAX_ROWS && match) { + li.style.display = "block"; + this.dom_removeChildren(li); + + let i = 0; + + for (let iM = 0; iM < match.length; iM++) { + let im = match[iM]; + if (im > i) { + li.appendChild(document.createTextNode(procCode.substring(i, im))); + i = im; + } + let bText = document.createElement("b"); + let len = split[iM].length; + bText.appendChild(document.createTextNode(procCode.substr(i, len))); + li.appendChild(bText); + i += len; + } + + if (i < procCode.length) { + li.appendChild(document.createTextNode(procCode.substr(i))); + } + + if (count === 0) { + li.classList.add("sel"); + } else { + li.classList.remove("sel"); + } + count++; + } else { + li.style.display = "none"; + li.classList.remove("sel"); + } + } + p.append(dd); + } + + // Loop until the DOM is ready for us... + initInner() { + let root = document.querySelector("ul[class*=gui_tab-list_]"); + let guiTabs = root && root.childNodes; + if (!guiTabs || guiTabs.length < 3) { + setTimeout(() => this.initInner(), 1000); + return; + } + + if (this.codeTab && guiTabs[0] !== this.codeTab) { + // We have been CHANGED!!! - Happens when going to project page, and then back inside again!!! + this.domHelpers.unbindAllEvents(); + } + + this.codeTab = guiTabs[0]; + this.costTab = guiTabs[1]; + this.costTabBody = document.querySelector("div[aria-labelledby=" + this.costTab.id + "]"); + + if (!document.getElementById("s3devFind")) { + root.insertAdjacentHTML( + "beforeend", + ` +
+ + + +
+ ` + ); + + this.find = document.getElementById("s3devFind"); + this.findInp = document.getElementById("s3devInp"); + this.ddOut = document.getElementById("s3devDDOut"); + this.domHelpers.bindOnce(this.ddOut, "mousedown", (...e) => this.dropDownClick(...e), undefined); + this.dd = document.getElementById("s3devDD"); + + // bindOnce(find, 'mouseenter', showDropDown); + // bindOnce(find, 'mouseleave', hideDropDown); + this.domHelpers.bindOnce(this.findInp, "keyup", (...e) => this.inputChange(...e), undefined); + this.domHelpers.bindOnce(this.findInp, "keydown", (...e) => this.inputKeyDown(...e), undefined); + this.domHelpers.bindOnce(this.findInp, "focus", (...e) => this.inputChange(...e), undefined); + + this.domHelpers.bindOnce( + document.getElementById("s3devHelp"), + "click", + (...e) => this.eventClickHelp(...e), + undefined + ); + + this.domHelpers.bindOnce(document, "keydown", (...e) => this.eventKeyDown(...e), true); + } + + this.domHelpers.bindOnce(document, "mousemove", (...e) => this.eventMouseMove(...e), true); + this.domHelpers.bindOnce(document, "mousedown", (...e) => this.eventMouseDown(...e), true); // true to capture all mouse downs 'before' the dom events handle them + // bindOnce(document.getElementById("s3devDeep"), "click", deepSearch); + // bindOnce(document.getElementById('s3devCleanUp'),'click', clickCleanUp); + // bindOnce(document.getElementById("s3devInject"), "click", clickInject); + // bindOnce(document.getElementById('s3devReplace'), 'click', clickReplace); + } +} + +class Multi { + constructor(utils) { + this.idx = 0; + this.blocks = null; + this.selID = null; + /** + * @type {Utils} + */ + this.utils = utils; + } + + update() { + const count = document.getElementById("s3devMultiCount"); + count.innerText = this.blocks && this.blocks.length > 0 ? enc(this.idx + 1 + " / " + this.blocks.length) : "0"; + this.selID = this.idx < this.blocks.length ? this.blocks[this.idx].id : null; + } + + navLeft(e) { + return this.navSideways(e, -1); + } + + navRight(e) { + return this.navSideways(e, 1); + } + + navSideways(e, dir) { + if (this.blocks && this.blocks.length > 0) { + this.idx = (this.idx + dir + this.blocks.length) % this.blocks.length; // + length to fix negative modulo js issue. + this.update(); + this.utils.scrollBlockIntoView(this.blocks[this.idx]); + } + if (e) { + e.cancelBubble = true; + e.preventDefault(); + } + return false; + } +} + +class Col { + /** + * @param x {Number} x position (for ordering) + * @param count {Number} + * @param blocks {[Block]} + */ + constructor(x, count, blocks) { + /** + * x position (for ordering) + * @type {Number} + */ + this.x = x; + /** + * @type {Number} + */ + this.count = count; + /** + * @type {[Blockly.Block]} + */ + this.blocks = blocks; + } +} + +const DROPDOWN_BLOCK_LIST_MAX_ROWS = 25; + +let rhdd = 0; +let rhdd2 = 0; +let prevVal = ""; + +function enc(str) { + return String(str).replace(/&/g, "&").replace(//g, ">").replace(/"/g, """); +} diff --git a/addon/DomHelpers.js b/addon/DomHelpers.js new file mode 100644 index 0000000..037ac23 --- /dev/null +++ b/addon/DomHelpers.js @@ -0,0 +1,105 @@ +export default class DomHelpers { + constructor(addon) { + this.addon = addon; + this.vm = addon.tab.traps.vm; + /** + * @type {eventDetails[]} + */ + this.events = []; + } + + /** + * Simulate a drag and drop programmatically through javascript + * @param selectorDrag + * @param selectorDrop + * @param mouseXY + * @returns {boolean} + */ + triggerDragAndDrop(selectorDrag, selectorDrop, mouseXY) { + // function for triggering mouse events + let fireMouseEvent = function (type, elem, centerX, centerY) { + let evt = document.createEvent("MouseEvents"); + evt.initMouseEvent(type, true, true, window, 1, 1, 1, centerX, centerY, false, false, false, false, 0, elem); + elem.dispatchEvent(evt); + }; + + // fetch target elements + let elemDrag = selectorDrag; // document.querySelector(selectorDrag); + let elemDrop = selectorDrop; // document.querySelector(selectorDrop); + if (!elemDrag /* || !elemDrop*/) { + return false; + } + + // calculate positions + let pos = elemDrag.getBoundingClientRect(); + let center1X = Math.floor((pos.left + pos.right) / 2); + let center1Y = Math.floor((pos.top + pos.bottom) / 2); + + // mouse over dragged element and mousedown + fireMouseEvent("mouseover", elemDrag, center1X, center1Y); + fireMouseEvent("mousedown", elemDrag, center1X, center1Y); + + // start dragging process over to drop target + fireMouseEvent("dragstart", elemDrag, center1X, center1Y); + fireMouseEvent("drag", elemDrag, center1X, center1Y); + fireMouseEvent("mousemove", elemDrag, center1X, center1Y); + + if (!elemDrop) { + if (mouseXY) { + // console.log(mouseXY); + let center2X = mouseXY.x; + let center2Y = mouseXY.y; + fireMouseEvent("drag", elemDrag, center2X, center2Y); + fireMouseEvent("mousemove", elemDrag, center2X, center2Y); + } + return false; + } + + pos = elemDrop.getBoundingClientRect(); + let center2X = Math.floor((pos.left + pos.right) / 2); + let center2Y = Math.floor((pos.top + pos.bottom) / 2); + + fireMouseEvent("drag", elemDrag, center2X, center2Y); + fireMouseEvent("mousemove", elemDrop, center2X, center2Y); + + // trigger dragging process on top of drop target + fireMouseEvent("mouseenter", elemDrop, center2X, center2Y); + fireMouseEvent("dragenter", elemDrop, center2X, center2Y); + fireMouseEvent("mouseover", elemDrop, center2X, center2Y); + fireMouseEvent("dragover", elemDrop, center2X, center2Y); + + // release dragged element on top of drop target + fireMouseEvent("drop", elemDrop, center2X, center2Y); + fireMouseEvent("dragend", elemDrag, center2X, center2Y); + fireMouseEvent("mouseup", elemDrag, center2X, center2Y); + + return true; + } + + bindOnce(dom, event, func, capture) { + capture = !!capture; + dom.removeEventListener(event, func, capture); + dom.addEventListener(event, func, capture); + this.events.push(new eventDetails(dom, event, func, capture)); + } + + unbindAllEvents() { + console.log("Unbinding Events - gui has become dirty"); + for (const event of this.events) { + event.dom.removeEventListener(event.event, event.func, event.capture); + } + this.events = []; + } +} + +/** + * A record of an event + */ +class eventDetails { + constructor(dom, event, func, capture) { + this.dom = dom; + this.event = event; + this.func = func; + this.capture = capture; + } +} diff --git a/addon/XML.js b/addon/XML.js new file mode 100644 index 0000000..cb40edb --- /dev/null +++ b/addon/XML.js @@ -0,0 +1,27 @@ +/** + * A fake XML class to use in place of the real XML for faking things? + */ +export default class XML { + constructor() { + this.xmlDoc = document.implementation.createDocument(null, "xml"); + } + + newXml(x, tagName, attrs) { + let xAdd = this.xmlDoc.createElement(tagName); + x.appendChild(xAdd); + return this.setAttr(xAdd, attrs); + } + + setAttr(x, attrs) { + if (attrs) { + for (const key of Object.keys(attrs)) { + if (key === "text") { + x.appendChild(this.xmlDoc.createTextNode(attrs[key])); + } else { + x.setAttribute(key, attrs[key]); + } + } + } + return x; + } +} diff --git a/addon/addon.json b/addon/addon.json new file mode 100644 index 0000000..c01ae7f --- /dev/null +++ b/addon/addon.json @@ -0,0 +1,24 @@ +{ + "name": "Developer tools", + "description": "Adds a find box and new menu options to the editor: copy/paste blocks, better tidy up, go to custom block definition, and more!", + "credits": [ + { + "name": "griffpatch" + } + ], + "userscripts": [ + { + "url": "userscript.js", + "matches": ["https://scratch.mit.edu/projects/*"] + } + ], + "userstyles": [ + { + "url": "userscript.css", + "matches": ["https://scratch.mit.edu/projects/*"] + } + ], + "tags": ["editor", "recommended"], + "enabledByDefault": false, + "l10n": true +} diff --git a/addon/blockly/BlockFlasher.js b/addon/blockly/BlockFlasher.js new file mode 100644 index 0000000..ff0a00f --- /dev/null +++ b/addon/blockly/BlockFlasher.js @@ -0,0 +1,39 @@ +/** + * Helper class to flash a Blockly scratch block in the users workspace + */ +export default class BlockFlasher { + /** + * FLash a block 3 times + * @param block the block to flash + */ + static flash(block) { + if (myFlash.timerID > 0) { + clearTimeout(myFlash.timerID); + myFlash.block.setColour(myFlash.colour); + } + + let count = 4; + let flashOn = true; + myFlash.colour = block.getColour(); + myFlash.block = block; + + /** + * Internal method to switch the colour of a block between light yellow and it's original colour + * @private + */ + function _flash() { + myFlash.block.setColour(flashOn ? "#ffff80" : myFlash.colour); + flashOn = !flashOn; + count--; + if (count > 0) { + myFlash.timerID = setTimeout(_flash, 200); + } else { + myFlash.timerID = 0; + } + } + + _flash(); + } +} + +const myFlash = { block: null, timerID: null, colour: null }; diff --git a/addon/blockly/UndoGroup.js b/addon/blockly/UndoGroup.js new file mode 100644 index 0000000..c08d677 --- /dev/null +++ b/addon/blockly/UndoGroup.js @@ -0,0 +1,47 @@ +/** + * This class is dedicated to maintaining the Undo stack of Blockly + * It allows us to initiate an undo group such that all subsequent operations are recorded as a single + * undoable transaction. + */ +export default class UndoGroup { + /** + * Start an Undo group - begin recording + * @param workspace the workspace + */ + static startUndoGroup(workspace) { + const undoStack = workspace.undoStack_; + if (undoStack.length) { + undoStack[undoStack.length - 1]._devtoolsLastUndo = true; + } + } + + /** + * End an Undo group - stops recording + * @param workspace the workspace + */ + static endUndoGroup(workspace) { + const undoStack = workspace.undoStack_; + // Events (responsible for undoStack updates) are delayed with a setTimeout(f, 0) + // https://github.com/LLK/scratch-blocks/blob/f159a1779e5391b502d374fb2fdd0cb5ca43d6a2/core/events.js#L182 + setTimeout(() => { + const group = generateUID(); + for (let i = undoStack.length - 1; i >= 0 && !undoStack[i]._devtoolsLastUndo; i--) { + undoStack[i].group = group; + } + }, 0); + } +} + +/** + * https://github.com/LLK/scratch-blocks/blob/f159a1779e5391b502d374fb2fdd0cb5ca43d6a2/core/events.js#L182 + * @returns {string} + * @private + */ +function generateUID() { + const CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!#$%()*+,-./:;=?@[]^_`{|}~"; + let result = ""; + for (let i = 0; i < 20; i++) { + result += CHARACTERS[Math.floor(Math.random() * CHARACTERS.length)]; + } + return result; +} diff --git a/addon/blockly/Utils.js b/addon/blockly/Utils.js new file mode 100644 index 0000000..de94e11 --- /dev/null +++ b/addon/blockly/Utils.js @@ -0,0 +1,221 @@ +import BlockInstance from "../BlockInstance.js"; +import BlockFlasher from "./BlockFlasher.js"; + +// A file to split Editor Devtools by features. + +export default class Utils { + constructor(addon) { + this.addon = addon; + /** + * Scratch Virtual Machine + * @type {null|*} + */ + this.vm = this.addon.tab.traps.vm; + // this._myFlash = { block: null, timerID: null, colour: null }; + this.offsetX = 32; + this.offsetY = 32; + this.navigationHistory = new NavigationHistory(this); + /** + * The workspace + */ + this._workspace = null; + } + + /** + * Get the Scratch Editing Target + * @returns {?Target} the scratch editing target + */ + getEditingTarget() { + return this.vm.runtime.getEditingTarget(); + } + + /** + * Set the current workspace (switches sprites) + * @param targetID {string} + */ + setEditingTarget(targetID) { + if (this.getEditingTarget().id !== targetID) { + this.vm.setEditingTarget(targetID); + } + } + + /** + * Returns the main workspace + * @returns !Blockly.Workspace + */ + getWorkspace() { + const currentWorkspace = Blockly.getMainWorkspace(); + if (currentWorkspace.getToolbox()) { + // Sadly get get workspace does not always return the 'real' workspace... Not sure how to get that at the moment, + // but we can work out whether it's the right one by whether it hsa a toolbox. + this._workspace = currentWorkspace; + } + return this._workspace; + } + + /** + * Based on wksp.centerOnBlock(li.data.labelID); + * @param blockOrId {Blockly.Block|{id}|BlockInstance} A Blockly Block, a block id, or a BlockInstance + * @param [force] {boolean} if true, the view always moves, otherwise only move if the selected element is not entirely visible + */ + scrollBlockIntoView(blockOrId, force) { + let workspace = this.getWorkspace(); + /** @type {Blockly.Block} */ + let block; // or is it really a Blockly.BlockSvg? + + if (blockOrId instanceof BlockInstance) { + // Switch to sprite + this.setEditingTarget(blockOrId.targetId); + // Highlight the block! + block = workspace.getBlockById(blockOrId.id); + } else { + block = blockOrId && blockOrId.id ? blockOrId : workspace.getBlockById(blockOrId); + } + + if (!block) { + return; + } + + /** + * !Blockly.Block + */ + let root = block.getRootBlock(); + let base = this.getTopOfStackFor(block); + let ePos = base.getRelativeToSurfaceXY(), // Align with the top of the block + rPos = root.getRelativeToSurfaceXY(), // Align with the left of the block 'stack' + eSiz = block.getHeightWidth(), + scale = workspace.scale, + // x = (ePos.x + (workspace.RTL ? -1 : 1) * eSiz.width / 2) * scale, + x = rPos.x * scale, + y = ePos.y * scale, + xx = block.width + x, // Turns out they have their x & y stored locally, and they are the actual size rather than scaled or including children... + yy = block.height + y, + // xx = eSiz.width * scale + x, + // yy = eSiz.height * scale + y, + + s = workspace.getMetrics(); + if ( + x < s.viewLeft + this.offsetX - 4 || + xx > s.viewLeft + s.viewWidth || + y < s.viewTop + this.offsetY - 4 || + yy > s.viewTop + s.viewHeight + ) { + // sx = s.contentLeft + s.viewWidth / 2 - x, + let sx = x - s.contentLeft - this.offsetX, + // sy = s.contentTop - y + Math.max(Math.min(32, 32 * scale), (s.viewHeight - yh) / 2); + sy = y - s.contentTop - this.offsetY; + + this.navigationHistory.storeView(this.navigationHistory.peek(), 64); + + // workspace.hideChaff(), + workspace.scrollbar.set(sx, sy); + this.navigationHistory.storeView({ left: sx, top: sy }, 64); + } + BlockFlasher.flash(block); + } + + /** + * Find the top stack block of a stack + * @param block a block in a stack + * @returns {*} a block that is the top of the stack of blocks + */ + getTopOfStackFor(block) { + let base = block; + while (base.getOutputShape() && base.getSurroundParent()) { + base = base.getSurroundParent(); + } + return base; + } +} + +class NavigationHistory { + constructor(utils) { + this.utils = utils; + this.views = []; + this.forward = []; + } + + /** + * Keep a record of the scroll and zoom position + */ + storeView(next, dist) { + this.forward = []; + let workspace = this.utils.getWorkspace(), + s = workspace.getMetrics(); + + let pos = { left: s.viewLeft, top: s.viewTop }; + if (!next || distance(pos, next) > dist) { + this.views.push(pos); + } + } + + peek() { + return this.views.length > 0 ? this.views[this.views.length - 1] : null; + } + + goBack() { + const workspace = this.utils.getWorkspace(), + s = workspace.getMetrics(); + + let pos = { left: s.viewLeft, top: s.viewTop }; + let view = this.peek(); + if (!view) { + return; + } + if (distance(pos, view) < 64) { + // Go back to current if we are already far away from it + if (this.views.length > 1) { + this.views.pop(); + this.forward.push(view); + } + } + + view = this.peek(); + if (!view) { + return; + } + + let sx = view.left - s.contentLeft, + sy = view.top - s.contentTop; + + // transform.setTranslate(-600,0); + + workspace.scrollbar.set(sx, sy); + + /* + let blocklySvg = document.getElementsByClassName('blocklySvg')[0]; + let blocklyBlockCanvas = blocklySvg.getElementsByClassName('blocklyBlockCanvas')[0]; + let transform = blocklyBlockCanvas.transform.baseVal.getItem(0); + let scale = blocklyBlockCanvas.transform.baseVal.getItem(1); + + let transformMatrix = transform.matrix; + let scaleMatrix = scale.matrix; + + console.log('Transform - getMetrics', s); + console.log('sx, sy: ', sx, sy); + console.log('left, top: ', view.left, view.top); + console.log('contentLeft, right:', s.contentLeft, s.contentTop); + console.log('transform, scale matrix: ', transformMatrix, scaleMatrix); + */ + } + + goForward() { + let view = this.forward.pop(); + if (!view) { + return; + } + this.views.push(view); + + let workspace = this.utils.getWorkspace(), + s = workspace.getMetrics(); + + let sx = view.left - s.contentLeft, + sy = view.top - s.contentTop; + + workspace.scrollbar.set(sx, sy); + } +} + +function distance(pos, next) { + return Math.sqrt(Math.pow(pos.left - next.left, 2) + Math.pow(pos.top - next.top, 2)); +} diff --git a/addon/show-broadcast.js b/addon/show-broadcast.js new file mode 100644 index 0000000..8e062ef --- /dev/null +++ b/addon/show-broadcast.js @@ -0,0 +1,110 @@ +// A file to split Editor Devtools by features. +// Unlike userscript.js, this file mainly interacts with VM. +export default class ShowBroadcast { + constructor(addon) { + this.addon = addon; + this.vm = this.addon.tab.traps.vm; + this.highlights = { + timeoutId: 0, + callback: () => {}, + }; + } + + showSenders(broadcastId) { + this.highlightTargets(this.getTargetsWithSenders(broadcastId)); + } + + getTargetsWithSenders(broadcastId) { + const targetWithSenders = []; + for (const target of this.vm.runtime.targets) { + if (!target.isOriginal) return; + for (const blockId of Object.keys(target.blocks._blocks)) { + const block = target.blocks.getBlock(blockId); + if (block.inputs.BROADCAST_INPUT) { + const input = block.inputs.BROADCAST_INPUT; + // For results, blocks must NOT be inserted, for convenience. + if ( + input.block === input.shadow && + target.blocks.getBlock(input.shadow).fields.BROADCAST_OPTION.id === broadcastId + ) { + targetWithSenders.push(target); + break; + } + } + } + } + return targetWithSenders; + } + + showReceivers(broadcastId) { + this.highlightTargets(this.getTargetsWithReceivers(broadcastId)); + } + + getTargetsWithReceivers(broadcastId) { + const targetWithReceivers = []; + for (const target of this.vm.runtime.targets) { + if (!target.isOriginal) return; + for (const blockId of Object.keys(target.blocks._blocks)) { + const block = target.blocks.getBlock(blockId); + if (block.opcode === "event_whenbroadcastreceived" && block.fields.BROADCAST_OPTION.id === broadcastId) { + targetWithReceivers.push(target); + break; + } + } + } + return targetWithReceivers; + } + + highlightTargets(targets) { + if (this.highlights.timeoutId) { + this.highlights.callback(); + clearTimeout(this.highlights.timeoutId); + this.highlights = { + timeoutId: 0, + callback: () => {}, + }; + } + const elemPendingToRemoveHighlights = []; + for (const target of targets) { + let elem = null; + if (target.isStage) { + elem = document.querySelector('div[class*="stage-selector_header"]'); + } else if (target.isOriginal) { + // This is one of the most ridiculous code I've ever written. + // This essentially comparses sprite names to textContent so that we can add CSS. + const possibleElements = document.querySelectorAll('div[class*="sprite-selector-item_sprite-name"]'); + const spriteNameElem = Array.prototype.find.call( + possibleElements, + (elem) => elem.textContent === target.getName() + ); + if (!spriteNameElem) continue; + elem = spriteNameElem.parentElement; + } + elem.dataset.highlighted = "true"; + elemPendingToRemoveHighlights.push(elem); + } + const callbackFactory = (elemToRemoveHighlights) => () => { + for (const removingElem of elemToRemoveHighlights) { + if (!removingElem.isConnected) continue; + removingElem.dataset.highlighted = "false"; + } + }; + const callback = callbackFactory(elemPendingToRemoveHighlights); + this.highlights = { + callback, + timeoutId: setTimeout(callback, 2000), + }; + } + + getAssociatedBroadcastId(blockId) { + const editingTarget = this.vm.editingTarget; + const block = editingTarget.blocks.getBlock(blockId); + if (block.opcode === "event_whenbroadcastreceived") { + return block.fields.BROADCAST_OPTION.id; + } else { + const input = block.inputs.BROADCAST_INPUT; + // Allow shadow blocks + return editingTarget.blocks.getBlock(input.shadow).fields.BROADCAST_OPTION.id; + } + } +} diff --git a/addon/userscript.css b/addon/userscript.css new file mode 100644 index 0000000..f0014b8 --- /dev/null +++ b/addon/userscript.css @@ -0,0 +1,472 @@ +#s3devToolBar { + display: flex; + white-space: nowrap; + font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; +} + +.s3devLabel { + display: flex; + padding-right: 2em; +} + +.s3devLabel > span:first-child { + margin-left: 1.5em; + margin-right: 1em; + font-weight: bold; + font-size: 0.625rem; + user-select: none; + cursor: default; + white-space: nowrap; + padding-top: 2px; +} + +.s3devAction { + transition: opacity 200ms ease-in; + /*font-weight: bold;*/ + opacity: 0; +} + +.s3devLabel:hover .s3devAction { + opacity: 0.7; +} + +/* Wrapper around find button and drop down */ +.s3devWrap { + overflow: visible; + /*margin-left:3em;*/ + position: relative; +} + +#s3devFind { + height: 2rem; +} + +/* Find Input Box */ +input.s3devInp { + background: rgba(255, 255, 255, 0.5); + border-radius: calc(0.5rem / 2); + font-size: 0.75rem; + font-weight: bold; + padding: 0.4em; + z-index: 2; + position: relative; + + border: 1px solid hsla(0, 0%, 0%, 0.15); + /*height: 30px;*/ + /*bottom: 5px;*/ + + min-width: 100%; + box-sizing: border-box !important; +} + +.s3devInp:hover { + background-color: white; +} + +.s3devInp:focus { + border-color: hsla(215, 100%, 65%, 1); + /*-webkit-box-shadow: 0 0 0 0.25rem hsla(215, 100%, 65%, 0.35);*/ + /*box-shadow: 0 0 0 0.25rem hsla(215, 100%, 65%, 0.35);*/ + outline: none; +} + +/* Drop down from find button */ +#s3devDDOut { + top: -6px; +} + +/* Drop down from find button */ +div.s3devDDOut { + z-index: 100; + left: 0; + width: 16em; + position: relative; + /*padding: 2.2em 0 0;*/ + /*background-color: white;*/ + padding: 4px; +} + +/* Drop down from find button */ +ul.s3devDD { + display: none; + position: relative; + padding: 0.2em 0; + font-size: 0.75rem; + line-height: 1; + overflow-y: auto; + min-height: 128px; + max-height: 65vh; + user-select: none; + max-width: 100%; +} + +div.s3devDDOut.vis { + /*box-shadow: 0 2px 3px rgba(0,0,0,0.3), 0 5px 8px rgba(0,0,0,0.2);*/ + box-shadow: 0px 0px 8px 1px rgba(0, 0, 0, 0.3); + background-color: white; + border: none; + border-radius: 4px; +} + +div.s3devDDOut.vis ul.s3devDD { + display: block; + border: none; +} + +/* Drop down items */ +.s3devDD > li { + display: block; + padding: 0.5em 0.3em; + white-space: nowrap; + margin: 0; + font-weight: bold; + text-overflow: ellipsis; + overflow: hidden; +} + +.s3devDD > li > b { + background-color: #aaffaa; + color: black; +} + +/* Drop down items */ +.s3devDD > li:hover, +.s3devDD > li.sel { + color: white; + cursor: pointer; +} + +#s3devDD > li::before { + content: "\25CF "; /* ● */ +} + +.define { + color: rgb(255, 102, 128); +} +.define:hover, +.define.sel { + background-color: rgb(255, 102, 128); +} + +.flag { + color: #4cbf56; +} +.flag:hover, +.flag.sel { + background-color: #4cbf56; +} + +.receive { + color: rgb(255, 191, 0); +} +.receive:hover, +.receive.sel { + background-color: rgb(255, 191, 0); +} + +.event { + background-color: rgb(255, 213, 0); + color: rgb(255, 191, 0); +} +.event:hover, +.event.sel { + background-color: rgb(255, 191, 0); +} + +.var, +.VAR { + color: rgb(255, 120, 26); +} +.var:hover, +.var.sel, +.VAR:hover, +.VAR.sel { + background-color: rgb(255, 120, 26); +} + +.list, +.LIST { + color: rgb(255, 102, 26); +} +.list:hover, +.list.sel, +.LIST:hover, +.LIST.sel { + background-color: rgb(255, 102, 26); +} + +.costume { + color: rgb(26, 66, 255); +} +.costume:hover, +.costume.sel { + background-color: rgb(26, 66, 255); +} + +.operators { + background-color: rgb(64, 191, 74); + color: rgb(56, 148, 56); +} +.operators:hover, +.operators.sel { + background-color: rgb(56, 148, 56); +} + +.data { + background-color: rgb(255, 140, 26); + color: rgb(219, 110, 0); +} +.data:hover, +.data.sel { + background-color: rgb(219, 110, 0); +} + +.data-lists { + background-color: rgb(255, 102, 26); + color: rgb(255, 102, 26); +} +.data-lists:hover, +.data-lists.sel { + background-color: rgb(207, 81, 20); +} + +.sensing { + background-color: rgb(76, 191, 230); + color: rgb(46, 142, 184); +} +.sensing:hover, +.sensing.sel { + background-color: rgb(46, 142, 184); +} + +.looks { + background-color: rgb(153, 102, 255); + color: rgb(119, 77, 203); +} +.looks:hover, +.looks.sel { + background-color: rgb(119, 77, 203); +} + +.sounds { + background-color: rgb(214, 92, 214); + color: rgb(189, 66, 189); +} +.sounds:hover, +.sounds.sel { + background-color: rgb(189, 66, 189); +} + +.motion { + background-color: rgb(76, 151, 255); + color: rgb(51, 115, 204); +} +.motion:hover, +.motion.sel { + background-color: rgb(51, 115, 204); +} + +.events { + background-color: rgb(255, 213, 0); + color: rgb(204, 153, 0); +} +.events:hover, +.events.sel { + background-color: rgb(204, 153, 0); +} + +.control { + background-color: rgb(255, 171, 25); + color: rgb(207, 139, 23); +} +.control:hover, +.control.sel { + background-color: rgb(207, 139, 23); +} + +.null { + background-color: rgb(255, 102, 128); + color: rgb(255, 77, 106); +} +.null:hover, +.null.sel { + background-color: rgb(255, 77, 106); +} + +.extension { + background-color: rgb(15 189 140); +} +.extension:hover, +.extension.sel { + background-color: rgb(11 158 117); +} + +/*.s3devDD>li.hat::before { content: '◠ ';}*/ +/*.s3devDD>li.hat::before { content: '▲ ';}*/ +/*.s3devDD>li.block::before { content: '■ ';}*/ +/*.s3devDD>li.reporter::before { content: '● ';}*/ +/*.s3devDD>li.boolean::before { content: '◆ ';}*/ + +#s3devIDD > li { + height: 19px; + padding: 3px 8px; + margin: 2px 0.3em; + box-sizing: border-box; + position: relative; + color: white; + font-weight: bold; + width: min-content; +} + +.s3devDD > li.hat { + border-radius: 14px 14px 3px 3px; +} +.s3devDD > li.block { + border-radius: 3px; +} +.s3devDD > li.reporter { + border-radius: 10px; +} + +.s3devDD > li.boolean { + width: min-content; +} +.s3devDD > li.boolean::before { + content: ""; + position: absolute; + left: 0; + top: 0; + width: 0; + height: 0; + border-right: 9px solid transparent; + border-top: 9px solid white; + border-bottom: 10px solid white; +} +.s3devDD > li.boolean::after { + content: ""; + position: absolute; + right: 0; + top: 0; + width: 0; + height: 0; + border-left: 9px solid transparent; + border-top: 9px solid white; + border-bottom: 10px solid white; +} + +#s3devOverlay { + position: fixed; + top: 0; + left: 0; + right: 0; + bottom: 0; + background-color: rgba(80, 80, 80, 0.5); + z-index: 9999; + padding: 10em; + color: white; + font-weight: bold; +} + +.s3devMulti { + font-weight: normal; + position: absolute; + right: 0; + white-space: nowrap; + background-color: inherit; + z-index: 1; + padding: 0; +} + +.s3devNav { + padding: 0 6px; +} + +.s3devNav:hover { + color: #ffff80; +} + +.s3devAction { + margin-left: 2em; + font-size: 12px; + font-weight: bold; + line-height: 2; +} + +@media screen and (max-width: 1180px) { + .s3devAction { + display: none; + } +} + +.s3devHide { + display: none; +} + +.s3dev-mi:hover { + background-color: #d6e9f8; +} + +#s3devHelpPop { + position: fixed; + top: 0; + left: 0; + right: 0; + bottom: 0; + background-color: rgba(64, 64, 64, 0.3); + z-index: 1000000; +} + +#s3devHelpPop > div { + box-sizing: border-box; + position: relative; + width: 800px; + max-height: 800px; + max-width: 85%; + top: 20vh; + height: 60vh; + overflow-y: auto; + background-color: white; + box-shadow: 0 4px 16px 2px rgba(0, 0, 0, 0.4); + margin-left: auto; + margin-right: auto; + padding: 1em 2em 4em; +} + +#s3devFloatingBar { + display: flex; + white-space: nowrap; + font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; + + position: absolute; + min-width: 128px; + background-color: white; + border-radius: 4px; + box-shadow: rgba(0, 0, 0, 0.3) 0 0 3px, rgba(0, 0, 0, 0.2) 0 3px 10px; + + z-index: 1000001; +} + +#s3devInsertLabel { + padding: 0; + align-items: center; +} + +#s3devIInp { + border: 0; +} + +/* Drop down from find button */ +ul#s3devIDD { + max-height: 200px; + margin-bottom: 0; +} + +#s3devIDD > li > b { + background-color: rgba(0, 0, 0, 0.6); + color: white; +} + +[data-highlighted="true"] { + background-color: hsla(30, 100%, 55%, 1) !important; /* orange */ + color: white !important; +} diff --git a/addon/userscript.js b/addon/userscript.js new file mode 100644 index 0000000..7aa7d22 --- /dev/null +++ b/addon/userscript.js @@ -0,0 +1,55 @@ +import DevTools from "./DevTools.js"; + +export default async function ({ addon, global, console, msg, safeMsg: m }) { + // Scratch Addons: do not run if extension is already enabled + + // noinspection JSUnresolvedVariable + if (window.initGUI) { + return; + } + + // 0-indexed 6 = July + const releaseDate = new Date(2021, 1, 8); + const releaseDateLocalized = new Intl.DateTimeFormat(msg.locale).format(releaseDate); + + const helpHTML = ` +
+
+

${m("help-title")}

+

${m("version", { + version: "1.9.0", + date: releaseDateLocalized, + ndash: "–", + url: 'Griffpatch', + })}

+
+

${m("changes024")}

+

${m("ctrl-space")} – ${m("ctrl-space-desc")}

+

${m("fixes")} – ${m("fixes-desc")}

+
+

${m("code-tab-features")}

+

${m("interactive-find-bar")} - ${m("interactive-find-bar-desc")}

+

${m("improved-tidy-up")} – ${m("improved-tidy-up-desc")}

+

${m("copy-to-clipboard")} – ${m("copy-to-clipboard-desc")}

+

${m("paste-from-clipboard")} – ${m("paste-from-clipboard-desc")}

+

${m("show-broadcast")} – ${m("show-broadcast-desc")}

+

${m("swap-variable")} – ${m("swap-variable-desc")}

+

${m("middleclick")} – ${m("middleclick-desc")}

+

${m("ctrl-lr")} – ${m("ctrl-lr-desc")}

+

${m("ctrl-space")} – ${m("ctrl-space-desc")}

+
+

${m("costume-tab-features")}

+

${m("find-bar")} – ${m("find-bar-costume-desc")}

+

${m("ctrl-lr")} – ${m("ctrl-lr-desc")}

+

${m("send-top-bottom")} – ${m("send-top-bottom-desc")}

+
+

${m( + "youtube" + )} - https://www.youtube.com/user/griffpatch

+
+
+`; + + const devTools = new DevTools(addon, msg, m, helpHTML); + devTools.init(); +} diff --git a/images/bigIcon.png b/images/bigIcon.png new file mode 100644 index 0000000..687c3b9 Binary files /dev/null and b/images/bigIcon.png differ diff --git a/images/favicon.png b/images/favicon.png new file mode 100644 index 0000000..40c8af7 Binary files /dev/null and b/images/favicon.png differ diff --git a/inject/l10n.js b/inject/l10n.js new file mode 100644 index 0000000..c5a9e2c --- /dev/null +++ b/inject/l10n.js @@ -0,0 +1,34 @@ +import LocalizationProvider from "../../libraries/l10n.js"; + +export default class UserscriptLocalizationProvider extends LocalizationProvider { + constructor(urls) { + super(); + this._urls = urls; + this.generalLoaded = false; + } + + async loadByAddonId(addonId) { + if (addonId !== "_general" && !this.generalLoaded) { + await this.loadByAddonId("_general"); + } + let addonMessages = {}; + for (const dir of this._urls) { + let resp; + let messages = {}; + const url = `${dir}/${addonId}.json`; + try { + resp = await fetch(url); + messages = await resp.json(); + } catch (_) { + continue; + } + addonMessages = Object.assign(messages, addonMessages); + this.messages = Object.assign(messages, this.messages); + } + this._generateCache(addonMessages); + if (addonId === "_general") { + this._refreshDateTime(); + this.generalLoaded = true; + } + } +} diff --git a/inject/run-addon.js b/inject/run-addon.js new file mode 100644 index 0000000..c94621f --- /dev/null +++ b/inject/run-addon.js @@ -0,0 +1,68 @@ +import Localization from "./l10n.js"; + +const MAIN_JS = "userscript.js"; + +const path = document.querySelector("script[id='devtools-extension-module']").getAttribute("data-path"); +const getURL = (x) => `${path}${x}`; +const scriptUrl = getURL(`addon/${MAIN_JS}`); + +let scratchVm; +const oldPrototypes = { + functionBind: Function.prototype.bind, +}; +Function.prototype.bind = function (...args) { + if ( + args[0] && + Object.prototype.hasOwnProperty.call(args[0], "editingTarget") && + Object.prototype.hasOwnProperty.call(args[0], "runtime") + ) { + scratchVm = args[0]; + Function.prototype.bind = oldPrototypes.functionBind; + return oldPrototypes.functionBind.apply(this, args); + } else { + return oldPrototypes.functionBind.apply(this, args); + } +}; + +const addon = { + self: { + _isDevtoolsExtension: true, + }, + tab: { + traps: { + onceValues: { + get vm() { + return scratchVm; + }, + }, + }, + }, +}; + +const langCode = `; ${document.cookie}`.split("; scratchlanguage=").pop().split(";").shift() || navigator.language; +function getL10NURLs() { + // Note: not identical to Scratch Addons function + const urls = [getURL(`l10n/${langCode}`)]; + if (langCode.includes("-")) { + urls.push(getURL(`l10n/${langCode.split("-")[0]}`)); + } + const enJSON = getURL("l10n/en"); + if (!urls.includes(enJSON)) urls.push(enJSON); + return urls; +} +const l10nObject = new Localization(getL10NURLs()); + +const msg = (key, placeholders) => l10nObject.get(`editor-devtools/${key}`, placeholders); +msg.locale = langCode; + +l10nObject.loadByAddonId("editor-devtools").then(() => + import(scriptUrl).then((module) => + module.default({ + addon, + global: {}, + console, + msg, + safeMsg: (key, placeholders) => l10nObject.escaped(`editor-devtools/${key}`, placeholders), + }) + ) +); diff --git a/l10n/en/_general.json b/l10n/en/_general.json new file mode 100644 index 0000000..c1c4df4 --- /dev/null +++ b/l10n/en/_general.json @@ -0,0 +1,4 @@ +{ + "_locale": "en", + "_locale_name": "English" +} diff --git a/l10n/en/editor-devtools.json b/l10n/en/editor-devtools.json new file mode 100644 index 0000000..1e22fc0 --- /dev/null +++ b/l10n/en/editor-devtools.json @@ -0,0 +1,59 @@ +{ + "editor-devtools/help-title": "Scratch 3 Developer Tools", + "editor-devtools/version": "Version {version} - Released {date} {ndash} by {url} and Scratch Addons contributors & translators", + "editor-devtools/changes024": "Changes in 0.2.3 - 0.2.4", + "editor-devtools/ctrl-space": "Ctrl + Space or Middle Click", + "editor-devtools/ctrl-space-desc": "Experimental Feature - This pops up a floating input box where you can type the name of a block (or parts of it) and drag the block into the code to make use of it right there.", + "editor-devtools/fixes": "Fixes", + "editor-devtools/fixes-desc": "Fix for input box not appearing on project load. Fix for pressing Ctrl+Left or Right while trying to enter text.", + "editor-devtools/code-tab-features": "Code Tab Features", + "editor-devtools/interactive-find-bar": "Interactive Find Bar (Ctrl + F)", + "editor-devtools/interactive-find-bar-desc": "Quickly find and jump to any Custom Block, Variable, Event, or Hat block defined in a sprite by clicking on the new find bar located to the right of the Code, Costumes and Sound tabs. Begin typing to filter down the list. Use the up and down arrow keys to switch between the possible entries, and the left and right arrows to cycle between al found instances of that block.", + "editor-devtools/improved-tidy-up": "Improved Code Tidy Up", + "editor-devtools/improved-tidy-up-desc": "Right click on the scripts window to pop up the menu and the clean up blocks option will have been replaced by a Clean Up Blocks (+) option. Se this to tidy your scripts and it will preserve your scripts columns as well as attempt to align the comments and remove all those orphaned variables, etc. You'll like this a lot I guarantee!", + "editor-devtools/copy-to-clipboard": "Copy to Clipboard", + "editor-devtools/copy-to-clipboard-desc": "Right click a block and 3 new options are available to Copy All, Copy Block, and Cut Block. The Copy All will copy to the clipboard everything including and below the block you clicked on. Copy block will only copy the current block and its contents, but nothing below. And cut block will copy it and remove it from the workspace.", + "editor-devtools/paste-from-clipboard": "Paste from Clipboard", + "editor-devtools/paste-from-clipboard-desc": "Pastes from the clipboard, but importantly pastes it where your mouse cursor is so you can then place it (rather than placing it where you copied it from like the current scratch implementation).", + "editor-devtools/swap-variable": "Swap Variable in Sprite", + "editor-devtools/swap-variable-desc": "Right click a variable in your scripts for this new option. It allows you to switch all references to this variable in the current sprite all in one go to another variable. This is great for when you made a mistake and want to switch from one variable to another or need to change from a 'for all sprites' to a 'for this sprite only'. This option will not remove the old variable and will not affect any other sprites variables.", + "editor-devtools/middleclick": "Middle Click", + "editor-devtools/middleclick-desc": "Using the middle mouse button on a variable or custom block allows you to jump to its definition or open it in the interactive find bar.", + "editor-devtools/ctrl-lr": "Ctrl + Left, Ctrl + Right", + "editor-devtools/ctrl-lr-desc": "Navigate to previous / next visited position in the script window (after using the navigate to block or find bar). This allows you to middle click a custom block to go to its definition, then press ctrl + Left to go back to where you were before.", + "editor-devtools/costume-tab-features": "Costumes Tab Features", + "editor-devtools/find-bar": "Find Bar", + "editor-devtools/find-bar-costume-desc": "Click to list all costumes by name, and type to locate one. Use the arrow keys or mouse to click a name to just straight to that costume.", + "editor-devtools/ctrl-lr-costume-desc": "These keys navigate you to the previous / next costume in the sprite.", + "editor-devtools/send-top-bottom": "Send to Top, Send to Bottom", + "editor-devtools/send-top-bottom-desc": "Right click a costume and 2 new menu items are present. These can be used to send the clicked sprite to the top or bottom of the list of costumes for fast re-ordering.", + "editor-devtools/youtube": "YouTube tutorials", + "editor-devtools/orphaned": "{count, plural, one {Griffpatch: I found 1 orphaned reporter block. Shall I delete it for you?} other {Griffpatch: I found # orphaned reporter blocks. Shall I delete them for you?} }", + "editor-devtools/unused-var": "{count, plural, one {Griffpatch: I found 1 unused local variable. Shall I delete it for you? Here it is:\n} other {Griffpatch: I found # unused local variables. Shall I delete them for you? Here they are:\n} }", + "editor-devtools/searching-in": "Searching in {name}", + "editor-devtools/var-not-exist": "That variable does not exist...", + "editor-devtools/find": "Find", + "editor-devtools/find-placeholder": "Find (Ctrl+F)", + "editor-devtools/deep": "Deep", + "editor-devtools/help": "Help", + "editor-devtools/tutorials": "Tutorials", + "editor-devtools/enter-expr": "Griffpatch: Enter an expression (i.e. a+2*3)", + "editor-devtools/replace": "Griffpatch: Switch all {name} in this sprite for the variable named:", + "editor-devtools/top": "Send to top", + "editor-devtools/bottom": "Send to bottom", + "editor-devtools/clean-plus": "Clean Up Blocks (+)", + "editor-devtools/paste": "Paste", + "editor-devtools/copy-all": "Copy All", + "editor-devtools/copy-block": "Copy Block", + "editor-devtools/cut-block": "Cut Block", + "editor-devtools/swap": "Swap {var} in sprite", + "editor-devtools/lists": "lists", + "editor-devtools/variables": "variables", + "editor-devtools/insert": "Insert", + "editor-devtools/start-typing": "Start Typing...", + "editor-devtools/show-senders": "Show senders", + "editor-devtools/show-receivers": "Show receivers", + "editor-devtools/show-broadcast": "Show Broadcast Senders/Receivers", + "editor-devtools/show-broadcast-desc": "Right-click a broadcast block, then click \"Show senders\" or \"Show receivers\". Sprites with the block will get highlighted.", + "editor-devtools/extension-description-not-for-addon": "Scratch 3 Developer Tools to enhance your Scratch Editing Experience on https://scratch.mit.edu" +} diff --git a/l10n/es/editor-devtools.json b/l10n/es/editor-devtools.json new file mode 100644 index 0000000..5e79563 --- /dev/null +++ b/l10n/es/editor-devtools.json @@ -0,0 +1,59 @@ +{ + "editor-devtools/help-title": "Herramientas de Desarrollador de Scratch 3", + "editor-devtools/version": "Versión {version} - Publicada {date} {ndash} por {url}", + "editor-devtools/changes024": "Cambios en 0.2.3 - 0.2.4", + "editor-devtools/ctrl-space": "Ctrl + Espacio o click medio", + "editor-devtools/ctrl-space-desc": "Función Experimental - Esto pone una ventana flotante donde puedes escribir el nombre de un bloque (o partes de él) y arrastrar el bloque al código para usarlo allí.", + "editor-devtools/fixes": "Arreglos", + "editor-devtools/fixes-desc": "Arregla la barra de busqueda no apareciendo cuando carga el proyecto. Arregla presionar Ctrl+Izquierda o Derecha al intentar ingresar texto.", + "editor-devtools/code-tab-features": "Funciones de la Pestaña de Código", + "editor-devtools/interactive-find-bar": "Barra de Búsqueda Interactiva (Ctrl + F)", + "editor-devtools/interactive-find-bar-desc": "Rápidamente busque y salte a cualquier bloque propio, variable, evento o bloque sombrero definido en un objeto clickeando en la nueva barra de búsqueda ubicada a la derecha de las pestañas de Código, Disfraces y Sonidos. Empiece a escribir para filtrar la lista. Use las teclas arriba y abajo para cambiar entre las posibles entradas y las flechas izquierda y derecha para revisar cada resultado de ese bloque.", + "editor-devtools/improved-tidy-up": "Ordenado de Bloques Mejorado", + "editor-devtools/improved-tidy-up-desc": "Haga click derecho en la ventana de código para mostrar el menú y la opción de ordenar bloques será reemplazada por una opción de \"Ordenar Bloques (+)\". Use esto para ordenar sus scripts, preservando las columnas como también intentando alinear los comentarios y quitar toda variable huérfana, etc. ¡Le va a encantar, se lo garantizo!", + "editor-devtools/copy-to-clipboard": "Copiar al Portapapeles", + "editor-devtools/copy-to-clipboard-desc": "Haga click derecho a un bloque y 3 nuevas opciones estarán disponisbles: Copiar Todos, Copiar Bloque y Cortar Bloque. El botón Copiar Todos copiará todo incluido abajo del bloque que clickeaste. Copiar Bloque solo copiará el bloque actual y sus contenidos, pero nada de abajo. Cortar Bloque lo copiará y lo eliminará.", + "editor-devtools/paste-from-clipboard": "Pegar del Portapapeles", + "editor-devtools/paste-from-clipboard-desc": "Pega del portapapeles, pero lo pega donde está su cursor del ratón para que puedas posicionarlo (en vez de ponerlo donde lo copió, como la implementación actual de Scratch).", + "editor-devtools/swap-variable": "Intercambiar Variable en Objeto", + "editor-devtools/swap-variable-desc": "Haga click derecho a una variable en la parte de código para esta nueva opción. Te permite intercambiar todas las referencias a esta variable en el objeto actual a otra variable. Esto es bueno para cuando cometió un error y quiere cambiar todas las referencias a una variable a otra o tiene que cambiar \"para todos los objetos\" a \"solo para este objeto\". Esta opción no quitará la variable antigua y no afectará las variables de otros objetos.", + "editor-devtools/middleclick": "Click Medi", + "editor-devtools/middleclick-desc": "Usando el botón del medio del ratón en una variable o bloque propio, puedes saltar a su definición o abrirlo en la barra de búsqueda interativa.", + "editor-devtools/ctrl-lr": "Ctrl + Izquierda, Ctrl + Derecha", + "editor-devtools/ctrl-lr-desc": "Navegue a la posición siguiente o anterior de la ventana de código (luego de usar la función \"navegar a bloque\" o la barra de búsqueda). Esto le permite hacer click medio en un bloque propio para ir a su definición, luego presione Ctrl + Izquierda para volver donde estaba antes.", + "editor-devtools/costume-tab-features": "Funciones de la Pestaña de Disfraces", + "editor-devtools/find-bar": "Barra de Búsqueda", + "editor-devtools/find-bar-costume-desc": "Haga click para listar todos los disfraces por nombre, y escriba para encontrar uno solo. Use las flechas o el ratón para clickear un nombre e ir directamente a ese disfraz.", + "editor-devtools/ctrl-lr-costume-desc": "Estas flechas le permiten navegar al anterior o próximo disfraz del objeto.", + "editor-devtools/send-top-bottom": "Mandar al Frente, Mandar al Fndo", + "editor-devtools/send-top-bottom-desc": "Haga click derecho a un disfraz y 2 nuevas opciones estarán presentes. Estas pueden ser usadas para enviar el disfraz actual al frente o al final de la lista de disfraces para un reordenado rápido.", + "editor-devtools/youtube": "Tutoriales en YouTube", + "editor-devtools/orphaned": "{count, plural, one {Griffpatch: encontré 1 bloque huérfano. ¿Debería borrarlo?} other {Griffpatch: encontré # bloques huérfanos. ¿Debería borrarlos?} }", + "editor-devtools/unused-var": "{count, plural, one {Griffpatch: encontré 1 variable locales sin usar. ¿Debería borrarla? Esta es:} other {Griffpatch: encontré # variables locales sin usar. ¿Debería borrarlas? Estas son:\n} }", + "editor-devtools/searching-in": "Buscando en {name}", + "editor-devtools/var-not-exist": "Esa variable no existe..", + "editor-devtools/find": "Buscar", + "editor-devtools/find-placeholder": "Buscar (Ctrl+F)", + "editor-devtools/deep": "Profundo", + "editor-devtools/help": "Ayuda", + "editor-devtools/tutorials": "Tutoriales", + "editor-devtools/enter-expr": "Griffpatch: ingrese una expresión (por ejemplo, a+2*3)", + "editor-devtools/replace": "Griffpatch: cambiar todos los {name} en este objeto por la variable llamada:", + "editor-devtools/top": "Mandar al frente", + "editor-devtools/bottom": "Mandar al fond", + "editor-devtools/clean-plus": "Ordenar bloques (+)", + "editor-devtools/paste": "Pegar", + "editor-devtools/copy-all": "Copiar Todos", + "editor-devtools/copy-block": "Copiar Bloque", + "editor-devtools/cut-block": "Cortar Bloque", + "editor-devtools/swap": "Intercambiar variable {var} en objecto", + "editor-devtools/lists": "listas", + "editor-devtools/insert": "Insertar", + "editor-devtools/start-typing": "Empiece a escribir...", + "editor-devtools/show-senders": "Mostrar emisores", + "editor-devtools/show-receivers": "Mostrar receptores", + "editor-devtools/show-broadcast": "Opción de mostrar emisores/receptores", + "editor-devtools/show-broadcast-desc": "Haga click derecho en un bloque de enviar o recibir mensaje, y luego haga click en \"mostrar emisores\" o \"mostrar receptores\". Objetos con esos bloques serán resaltados.", + "editor-devtools/@name": "Herramientas de desarrollador", + "editor-devtools/@description": "Agrega una barra de búsqueda y nuevas opciones de menú para el editor: copie y pegue bloques, ordene de mejor manera, vaya directamente a la definición de un bloque propio y más." +} diff --git a/libraries/autoescaper.js b/libraries/autoescaper.js new file mode 100644 index 0000000..1240e0e --- /dev/null +++ b/libraries/autoescaper.js @@ -0,0 +1,17 @@ +/* + Auto-escape input to prevent XSS. + Usage: autoescaper`trusted code ${untrusted value}` +*/ + +const escapeHTML = (str) => str.replace(/([<>'"&])/g, (_, l) => `&#${l.charCodeAt(0)};`); +const autoescaper = (strings, ...dangerous) => { + let r = ""; + let i = 0; + for (; i < strings.length; i++) { + r += strings[i]; + if (i !== dangerous.length) r += escapeHTML(String(dangerous[i])); + } + return r; +}; +export default autoescaper; +export { escapeHTML }; diff --git a/libraries/intl-messageformat.umd.min.js b/libraries/intl-messageformat.umd.min.js new file mode 100644 index 0000000..1806fda --- /dev/null +++ b/libraries/intl-messageformat.umd.min.js @@ -0,0 +1,1789 @@ +!(function (e, t) { + "object" == typeof exports && "undefined" != typeof module + ? t(exports) + : "function" == typeof define && define.amd + ? define(["exports"], t) + : t(((e = "undefined" != typeof globalThis ? globalThis : e || self).IntlMessageFormat = {})); +})(this, function (e) { + "use strict"; + /*! ***************************************************************************** + Copyright (c) Microsoft Corporation. + + Permission to use, copy, modify, and/or distribute this software for any + purpose with or without fee is hereby granted. + + THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + PERFORMANCE OF THIS SOFTWARE. + ***************************************************************************** */ var t = function ( + e, + r + ) { + return (t = + Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && + function (e, t) { + e.__proto__ = t; + }) || + function (e, t) { + for (var r in t) Object.prototype.hasOwnProperty.call(t, r) && (e[r] = t[r]); + })(e, r); + }; + function r(e, r) { + function n() { + this.constructor = e; + } + t(e, r), (e.prototype = null === r ? Object.create(r) : ((n.prototype = r.prototype), new n())); + } + var n, + a, + i = function () { + return (i = + Object.assign || + function e(t) { + for (var r, n = 1, a = arguments.length; n < a; n++) + for (var i in (r = arguments[n])) Object.prototype.hasOwnProperty.call(r, i) && (t[i] = r[i]); + return t; + }).apply(this, arguments); + }; + function o() { + for (var e = 0, t = 0, r = arguments.length; t < r; t++) e += arguments[t].length; + var n = Array(e), + a = 0; + for (t = 0; t < r; t++) for (var i = arguments[t], o = 0, u = i.length; o < u; o++, a++) n[a] = i[o]; + return n; + } + function u(e) { + return e.type === n.literal; + } + function c(e) { + return e.type === n.argument; + } + function s(e) { + return e.type === n.number; + } + function l(e) { + return e.type === n.date; + } + function f(e) { + return e.type === n.time; + } + function p(e) { + return e.type === n.select; + } + function h(e) { + return e.type === n.plural; + } + function g(e) { + return e.type === n.pound; + } + function m(e) { + return e.type === n.tag; + } + function d(e) { + return !(!e || "object" != typeof e || 0 !== e.type); + } + function y(e) { + return !(!e || "object" != typeof e || 1 !== e.type); + } + !(function (e) { + (e[(e.literal = 0)] = "literal"), + (e[(e.argument = 1)] = "argument"), + (e[(e.number = 2)] = "number"), + (e[(e.date = 3)] = "date"), + (e[(e.time = 4)] = "time"), + (e[(e.select = 5)] = "select"), + (e[(e.plural = 6)] = "plural"), + (e[(e.pound = 7)] = "pound"), + (e[(e.tag = 8)] = "tag"); + })(n || (n = {})), + (function (e) { + (e[(e.number = 0)] = "number"), (e[(e.dateTime = 1)] = "dateTime"); + })(a || (a = {})); + var v = /(?:[Eec]{1,6}|G{1,5}|[Qq]{1,5}|(?:[yYur]+|U{1,5})|[ML]{1,5}|d{1,2}|D{1,3}|F{1}|[abB]{1,5}|[hkHK]{1,2}|w{1,2}|W{1}|m{1,2}|s{1,2}|[zZOvVxX]{1,4})(?=([^']*'[^']*')*[^']*$)/g, + A = /^\.(?:(0+)(\*)?|(#+)|(0+)(#+))$/g, + b = /^(@+)?(\+|#+)?$/g; + function w(e) { + var t = {}; + return ( + e.replace(b, function (e, r, n) { + return ( + "string" != typeof n + ? ((t.minimumSignificantDigits = r.length), (t.maximumSignificantDigits = r.length)) + : "+" === n + ? (t.minimumSignificantDigits = r.length) + : "#" === r[0] + ? (t.maximumSignificantDigits = r.length) + : ((t.minimumSignificantDigits = r.length), + (t.maximumSignificantDigits = r.length + ("string" == typeof n ? n.length : 0))), + "" + ); + }), + t + ); + } + function C(e) { + switch (e) { + case "sign-auto": + return { signDisplay: "auto" }; + case "sign-accounting": + return { currencySign: "accounting" }; + case "sign-always": + return { signDisplay: "always" }; + case "sign-accounting-always": + return { signDisplay: "always", currencySign: "accounting" }; + case "sign-except-zero": + return { signDisplay: "exceptZero" }; + case "sign-accounting-except-zero": + return { signDisplay: "exceptZero", currencySign: "accounting" }; + case "sign-never": + return { signDisplay: "never" }; + } + } + function x(e) { + return C(e) || {}; + } + function E(e) { + for (var t = {}, r = 0, n = e; r < n.length; r++) { + var a = n[r]; + switch (a.stem) { + case "percent": + t.style = "percent"; + continue; + case "currency": + (t.style = "currency"), (t.currency = a.options[0]); + continue; + case "group-off": + t.useGrouping = !1; + continue; + case "precision-integer": + case ".": + t.maximumFractionDigits = 0; + continue; + case "measure-unit": + (t.style = "unit"), (t.unit = a.options[0].replace(/^(.*?)-/, "")); + continue; + case "compact-short": + (t.notation = "compact"), (t.compactDisplay = "short"); + continue; + case "compact-long": + (t.notation = "compact"), (t.compactDisplay = "long"); + continue; + case "scientific": + t = i( + i(i({}, t), { notation: "scientific" }), + a.options.reduce(function (e, t) { + return i(i({}, e), x(t)); + }, {}) + ); + continue; + case "engineering": + t = i( + i(i({}, t), { notation: "engineering" }), + a.options.reduce(function (e, t) { + return i(i({}, e), x(t)); + }, {}) + ); + continue; + case "notation-simple": + t.notation = "standard"; + continue; + case "unit-width-narrow": + (t.currencyDisplay = "narrowSymbol"), (t.unitDisplay = "narrow"); + continue; + case "unit-width-short": + (t.currencyDisplay = "code"), (t.unitDisplay = "short"); + continue; + case "unit-width-full-name": + (t.currencyDisplay = "name"), (t.unitDisplay = "long"); + continue; + case "unit-width-iso-code": + t.currencyDisplay = "symbol"; + continue; + } + if (A.test(a.stem)) { + if (a.options.length > 1) throw new RangeError("Fraction-precision stems only accept a single optional option"); + a.stem.replace(A, function (e, r, n, a, i, o) { + return ( + "*" === n + ? (t.minimumFractionDigits = r.length) + : a && "#" === a[0] + ? (t.maximumFractionDigits = a.length) + : i && o + ? ((t.minimumFractionDigits = i.length), (t.maximumFractionDigits = i.length + o.length)) + : ((t.minimumFractionDigits = r.length), (t.maximumFractionDigits = r.length)), + "" + ); + }), + a.options.length && (t = i(i({}, t), w(a.options[0]))); + } else if (b.test(a.stem)) t = i(i({}, t), w(a.stem)); + else { + var o = C(a.stem); + o && (t = i(i({}, t), o)); + } + } + return t; + } + var D = (function (e) { + function t(r, n, a, i) { + var o = e.call(this) || this; + return ( + (o.message = r), + (o.expected = n), + (o.found = a), + (o.location = i), + (o.name = "SyntaxError"), + "function" == typeof Error.captureStackTrace && Error.captureStackTrace(o, t), + o + ); + } + return ( + r(t, e), + (t.buildMessage = function (e, t) { + function r(e) { + return e.charCodeAt(0).toString(16).toUpperCase(); + } + function n(e) { + return e + .replace(/\\/g, "\\\\") + .replace(/"/g, '\\"') + .replace(/\0/g, "\\0") + .replace(/\t/g, "\\t") + .replace(/\n/g, "\\n") + .replace(/\r/g, "\\r") + .replace(/[\x00-\x0F]/g, function (e) { + return "\\x0" + r(e); + }) + .replace(/[\x10-\x1F\x7F-\x9F]/g, function (e) { + return "\\x" + r(e); + }); + } + function a(e) { + return e + .replace(/\\/g, "\\\\") + .replace(/\]/g, "\\]") + .replace(/\^/g, "\\^") + .replace(/-/g, "\\-") + .replace(/\0/g, "\\0") + .replace(/\t/g, "\\t") + .replace(/\n/g, "\\n") + .replace(/\r/g, "\\r") + .replace(/[\x00-\x0F]/g, function (e) { + return "\\x0" + r(e); + }) + .replace(/[\x10-\x1F\x7F-\x9F]/g, function (e) { + return "\\x" + r(e); + }); + } + function i(e) { + switch (e.type) { + case "literal": + return '"' + n(e.text) + '"'; + case "class": + var t = e.parts.map(function (e) { + return Array.isArray(e) ? a(e[0]) + "-" + a(e[1]) : a(e); + }); + return "[" + (e.inverted ? "^" : "") + t + "]"; + case "any": + return "any character"; + case "end": + return "end of input"; + case "other": + return e.description; + } + } + return ( + "Expected " + + (function o(e) { + var t, + r, + n = e.map(i); + if ((n.sort(), n.length > 0)) { + for (t = 1, r = 1; t < n.length; t++) n[t - 1] !== n[t] && ((n[r] = n[t]), r++); + n.length = r; + } + switch (n.length) { + case 1: + return n[0]; + case 2: + return n[0] + " or " + n[1]; + default: + return n.slice(0, -1).join(", ") + ", or " + n[n.length - 1]; + } + })(e) + + " but " + + (function u(e) { + return e ? '"' + n(e) + '"' : "end of input"; + })(t) + + " found." + ); + }), + t + ); + })(Error), + F = function I(e, t) { + t = void 0 !== t ? t : {}; + var r, + a = {}, + o = { start: Te }, + u = Te, + c = Ee("<", !1), + s = function (e) { + return e.join(""); + }, + l = Ee("#", !1), + f = Fe("tagElement"), + p = Ee("/>", !1), + h = Ee(">", !1), + g = Ee(" ve && ((ve = me), (Ae = [])), Ae.push(e)); + } + function Te() { + return Oe(); + } + function Oe() { + var e, t; + for (e = [], t = _e(); t !== a; ) e.push(t), (t = _e()); + return e; + } + function _e() { + var t, r; + return ( + (t = me), + (de = me), + (it ? a : void 0) !== a && + (r = (function o() { + var e, t, r, o, u, c, s; + return ( + be++, + (e = Le()) === a && + ((e = me), + (t = Pe()) !== a && (r = Oe()) !== a && (o = Re()) !== a + ? ((de = e), + (c = r), + (u = t) !== (s = o) && xe('Mismatch tag "' + u + '" !== "' + s + '"', Ce()), + (e = t = i({ type: n.tag, value: u, children: c }, at()))) + : ((me = e), (e = a))), + be--, + e === a && ((t = a), 0 === be && Se(f)), + e + ); + })()) !== a + ? ((de = t), (t = r)) + : ((me = t), (t = a)), + t === a && + (t = (function u() { + var e, t; + return (e = me), (t = je()) !== a && ((de = e), (t = i({ type: n.literal, value: t }, at()))), t; + })()) === a && + (t = (function c() { + var t, r, o, u; + return ( + be++, + (t = me), + 123 === e.charCodeAt(me) ? ((r = "{"), me++) : ((r = a), 0 === be && Se(d)), + r !== a && $e() !== a && (o = Qe()) !== a && $e() !== a + ? (125 === e.charCodeAt(me) ? ((u = "}"), me++) : ((u = a), 0 === be && Se(y)), + u !== a ? ((de = t), (t = r = i({ type: n.argument, value: o }, at()))) : ((me = t), (t = a))) + : ((me = t), (t = a)), + be--, + t === a && ((r = a), 0 === be && Se(m)), + t + ); + })()) === a && + (t = (function s() { + var t; + return ( + (t = (function r() { + var t, r, n, o, u, c, s, l, f; + return ( + (t = me), + 123 === e.charCodeAt(me) ? ((r = "{"), me++) : ((r = a), 0 === be && Se(d)), + r !== a && $e() !== a && (n = Qe()) !== a && $e() !== a + ? (44 === e.charCodeAt(me) ? ((o = ","), me++) : ((o = a), 0 === be && Se(T)), + o !== a && $e() !== a + ? ("number" === e.substr(me, 6) ? ((u = "number"), (me += 6)) : ((u = a), 0 === be && Se(O)), + u !== a && $e() !== a + ? ((c = me), + 44 === e.charCodeAt(me) ? ((s = ","), me++) : ((s = a), 0 === be && Se(T)), + s !== a && + (l = $e()) !== a && + (f = (function p() { + var t, r, n; + return ( + (t = me), + "::" === e.substr(me, 2) ? ((r = "::"), (me += 2)) : ((r = a), 0 === be && Se(k)), + r !== a && + (n = (function o() { + var e, t, r, n; + if (((e = me), (t = []), (r = Ve()) !== a)) + for (; r !== a; ) t.push(r), (r = Ve()); + else t = a; + return ( + t !== a && + ((de = e), + (t = i({ type: 0, tokens: (n = t), parsedOptions: ot ? E(n) : {} }, at()))), + t + ); + })()) !== a + ? ((de = t), (t = r = n)) + : ((me = t), (t = a)), + t === a && + ((t = me), + (de = me), + rt.push("numberArgStyle"), + (r = (r = !0) ? void 0 : a) !== a && (n = je()) !== a + ? ((de = t), (t = r = S(n))) + : ((me = t), (t = a))), + t + ); + })()) !== a + ? (c = s = [s, l, f]) + : ((me = c), (c = a)), + c === a && (c = null), + c !== a && (s = $e()) !== a + ? (125 === e.charCodeAt(me) ? ((l = "}"), me++) : ((l = a), 0 === be && Se(y)), + l !== a ? ((de = t), (t = r = _(n, u, c))) : ((me = t), (t = a))) + : ((me = t), (t = a))) + : ((me = t), (t = a))) + : ((me = t), (t = a))) + : ((me = t), (t = a)), + t + ); + })()) === a && + (t = (function n() { + var t, r, n, o, u, c, s, l, f; + return ( + (t = me), + 123 === e.charCodeAt(me) ? ((r = "{"), me++) : ((r = a), 0 === be && Se(d)), + r !== a && $e() !== a && (n = Qe()) !== a && $e() !== a + ? (44 === e.charCodeAt(me) ? ((o = ","), me++) : ((o = a), 0 === be && Se(T)), + o !== a && $e() !== a + ? ("date" === e.substr(me, 4) ? ((u = "date"), (me += 4)) : ((u = a), 0 === be && Se(V)), + u === a && + ("time" === e.substr(me, 4) ? ((u = "time"), (me += 4)) : ((u = a), 0 === be && Se(Z))), + u !== a && $e() !== a + ? ((c = me), + 44 === e.charCodeAt(me) ? ((s = ","), me++) : ((s = a), 0 === be && Se(T)), + s !== a && + (l = $e()) !== a && + (f = (function p() { + var t, r, n; + return ( + (t = me), + "::" === e.substr(me, 2) ? ((r = "::"), (me += 2)) : ((r = a), 0 === be && Se(k)), + r !== a && + (n = (function o() { + var t, r, n, o, u, c, s; + if (((t = me), (r = me), (n = []), (o = Ze()) === a && (o = Be()), o !== a)) + for (; o !== a; ) n.push(o), (o = Ze()) === a && (o = Be()); + else n = a; + return ( + (r = n !== a ? e.substring(r, me) : n) !== a && + ((de = t), + (r = i( + { + type: 1, + pattern: (u = r), + parsedOptions: ot + ? ((c = u), + (s = {}), + c.replace(v, function (e) { + var t = e.length; + switch (e[0]) { + case "G": + s.era = 4 === t ? "long" : 5 === t ? "narrow" : "short"; + break; + case "y": + s.year = 2 === t ? "2-digit" : "numeric"; + break; + case "Y": + case "u": + case "U": + case "r": + throw new RangeError( + "`Y/u/U/r` (year) patterns are not supported, use `y` instead" + ); + case "q": + case "Q": + throw new RangeError( + "`q/Q` (quarter) patterns are not supported" + ); + case "M": + case "L": + s.month = ["numeric", "2-digit", "short", "long", "narrow"][ + t - 1 + ]; + break; + case "w": + case "W": + throw new RangeError( + "`w/W` (week) patterns are not supported" + ); + case "d": + s.day = ["numeric", "2-digit"][t - 1]; + break; + case "D": + case "F": + case "g": + throw new RangeError( + "`D/F/g` (day) patterns are not supported, use `d` instead" + ); + case "E": + s.weekday = 4 === t ? "short" : 5 === t ? "narrow" : "short"; + break; + case "e": + if (t < 4) + throw new RangeError( + "`e..eee` (weekday) patterns are not supported" + ); + s.weekday = ["short", "long", "narrow", "short"][t - 4]; + break; + case "c": + if (t < 4) + throw new RangeError( + "`c..ccc` (weekday) patterns are not supported" + ); + s.weekday = ["short", "long", "narrow", "short"][t - 4]; + break; + case "a": + s.hour12 = !0; + break; + case "b": + case "B": + throw new RangeError( + "`b/B` (period) patterns are not supported, use `a` instead" + ); + case "h": + (s.hourCycle = "h12"), + (s.hour = ["numeric", "2-digit"][t - 1]); + break; + case "H": + (s.hourCycle = "h23"), + (s.hour = ["numeric", "2-digit"][t - 1]); + break; + case "K": + (s.hourCycle = "h11"), + (s.hour = ["numeric", "2-digit"][t - 1]); + break; + case "k": + (s.hourCycle = "h24"), + (s.hour = ["numeric", "2-digit"][t - 1]); + break; + case "j": + case "J": + case "C": + throw new RangeError( + "`j/J/C` (hour) patterns are not supported, use `h/H/K/k` instead" + ); + case "m": + s.minute = ["numeric", "2-digit"][t - 1]; + break; + case "s": + s.second = ["numeric", "2-digit"][t - 1]; + break; + case "S": + case "A": + throw new RangeError( + "`S/A` (second) patterns are not supported, use `s` instead" + ); + case "z": + s.timeZoneName = t < 4 ? "short" : "long"; + break; + case "Z": + case "O": + case "v": + case "V": + case "X": + case "x": + throw new RangeError( + "`Z/O/v/V/X/x` (timeZone) patterns are not supported, use `z` instead" + ); + } + return ""; + }), + s) + : {}, + }, + at() + ))), + r + ); + })()) !== a + ? ((de = t), (t = r = n)) + : ((me = t), (t = a)), + t === a && + ((t = me), + (de = me), + rt.push("dateOrTimeArgStyle"), + (r = (r = !0) ? void 0 : a) !== a && (n = je()) !== a + ? ((de = t), (t = r = S(n))) + : ((me = t), (t = a))), + t + ); + })()) !== a + ? (c = s = [s, l, f]) + : ((me = c), (c = a)), + c === a && (c = null), + c !== a && (s = $e()) !== a + ? (125 === e.charCodeAt(me) ? ((l = "}"), me++) : ((l = a), 0 === be && Se(y)), + l !== a ? ((de = t), (t = r = _(n, u, c))) : ((me = t), (t = a))) + : ((me = t), (t = a))) + : ((me = t), (t = a))) + : ((me = t), (t = a))) + : ((me = t), (t = a)), + t + ); + })()), + t + ); + })()) === a && + (t = (function p() { + var t, r, o, u, c, s, l, f, p, h, g; + if (((t = me), 123 === e.charCodeAt(me) ? ((r = "{"), me++) : ((r = a), 0 === be && Se(d)), r !== a)) + if ($e() !== a) + if ((o = Qe()) !== a) + if ($e() !== a) + if ((44 === e.charCodeAt(me) ? ((u = ","), me++) : ((u = a), 0 === be && Se(T)), u !== a)) + if ($e() !== a) + if ( + ("plural" === e.substr(me, 6) ? ((c = "plural"), (me += 6)) : ((c = a), 0 === be && Se(B)), + c === a && + ("selectordinal" === e.substr(me, 13) + ? ((c = "selectordinal"), (me += 13)) + : ((c = a), 0 === be && Se(U))), + c !== a) + ) + if ($e() !== a) + if ((44 === e.charCodeAt(me) ? ((s = ","), me++) : ((s = a), 0 === be && Se(T)), s !== a)) + if ($e() !== a) + if ( + ((l = me), + "offset:" === e.substr(me, 7) + ? ((f = "offset:"), (me += 7)) + : ((f = a), 0 === be && Se(G)), + f !== a && (p = $e()) !== a && (h = qe()) !== a + ? (l = f = [f, p, h]) + : ((me = l), (l = a)), + l === a && (l = null), + l !== a) + ) + if ((f = $e()) !== a) { + if (((p = []), (h = Ge()) !== a)) for (; h !== a; ) p.push(h), (h = Ge()); + else p = a; + p !== a && (h = $e()) !== a + ? (125 === e.charCodeAt(me) ? ((g = "}"), me++) : ((g = a), 0 === be && Se(y)), + g !== a + ? ((de = t), + (t = r = (function (e, t, r, a) { + return i( + { + type: n.plural, + pluralType: "plural" === t ? "cardinal" : "ordinal", + value: e, + offset: r ? r[2] : 0, + options: a.reduce(function (e, t) { + var r = t.id, + n = t.value, + a = t.location; + return ( + r in e && + xe( + 'Duplicate option "' + + r + + '" in plural element: "' + + we() + + '"', + Ce() + ), + (e[r] = { value: n, location: a }), + e + ); + }, {}), + }, + at() + ); + })(o, c, l, p))) + : ((me = t), (t = a))) + : ((me = t), (t = a)); + } else (me = t), (t = a); + else (me = t), (t = a); + else (me = t), (t = a); + else (me = t), (t = a); + else (me = t), (t = a); + else (me = t), (t = a); + else (me = t), (t = a); + else (me = t), (t = a); + else (me = t), (t = a); + else (me = t), (t = a); + else (me = t), (t = a); + else (me = t), (t = a); + return t; + })()) === a && + (t = (function h() { + var t, r, o, u, c, s, l, f, p; + if (((t = me), 123 === e.charCodeAt(me) ? ((r = "{"), me++) : ((r = a), 0 === be && Se(d)), r !== a)) + if ($e() !== a) + if ((o = Qe()) !== a) + if ($e() !== a) + if ((44 === e.charCodeAt(me) ? ((u = ","), me++) : ((u = a), 0 === be && Se(T)), u !== a)) + if ($e() !== a) + if ( + ("select" === e.substr(me, 6) ? ((c = "select"), (me += 6)) : ((c = a), 0 === be && Se(H)), + c !== a) + ) + if ($e() !== a) + if ((44 === e.charCodeAt(me) ? ((s = ","), me++) : ((s = a), 0 === be && Se(T)), s !== a)) + if ($e() !== a) { + if (((l = []), (f = Ue()) !== a)) for (; f !== a; ) l.push(f), (f = Ue()); + else l = a; + l !== a && (f = $e()) !== a + ? (125 === e.charCodeAt(me) ? ((p = "}"), me++) : ((p = a), 0 === be && Se(y)), + p !== a + ? ((de = t), + (t = r = (function (e, t) { + return i( + { + type: n.select, + value: e, + options: t.reduce(function (e, t) { + var r = t.id, + n = t.value, + a = t.location; + return ( + r in e && + xe( + 'Duplicate option "' + + r + + '" in select element: "' + + we() + + '"', + Ce() + ), + (e[r] = { value: n, location: a }), + e + ); + }, {}), + }, + at() + ); + })(o, l))) + : ((me = t), (t = a))) + : ((me = t), (t = a)); + } else (me = t), (t = a); + else (me = t), (t = a); + else (me = t), (t = a); + else (me = t), (t = a); + else (me = t), (t = a); + else (me = t), (t = a); + else (me = t), (t = a); + else (me = t), (t = a); + else (me = t), (t = a); + else (me = t), (t = a); + return t; + })()) === a && + (t = (function g() { + var t, r; + return ( + (t = me), + 35 === e.charCodeAt(me) ? ((r = "#"), me++) : ((r = a), 0 === be && Se(l)), + r !== a && ((de = t), (r = i({ type: n.pound }, at()))), + r + ); + })()), + t + ); + } + function je() { + var t, r, n, i; + if (((t = me), (de = me), (r = (r = it) ? void 0 : a) !== a)) { + if ( + ((n = []), + (i = Xe()) === a && + (i = Je()) === a && + (i = Ke()) === a && + (60 === e.charCodeAt(me) ? ((i = "<"), me++) : ((i = a), 0 === be && Se(c))), + i !== a) + ) + for (; i !== a; ) + n.push(i), + (i = Xe()) === a && + (i = Je()) === a && + (i = Ke()) === a && + (60 === e.charCodeAt(me) ? ((i = "<"), me++) : ((i = a), 0 === be && Se(c))); + else n = a; + n !== a ? ((de = t), (t = r = s(n))) : ((me = t), (t = a)); + } else (me = t), (t = a); + if (t === a) { + if (((t = me), (r = []), (n = Xe()) === a && (n = Je()) === a && (n = Ke()) === a && (n = Ne()), n !== a)) + for (; n !== a; ) r.push(n), (n = Xe()) === a && (n = Je()) === a && (n = Ke()) === a && (n = Ne()); + else r = a; + r !== a && ((de = t), (r = s(r))), (t = r); + } + return t; + } + function Ne() { + var t, r, n; + return ( + (t = me), + (r = me), + be++, + (n = Pe()) === a && (n = Re()) === a && (n = Le()), + be--, + n === a ? (r = void 0) : ((me = r), (r = a)), + r !== a + ? (60 === e.charCodeAt(me) ? ((n = "<"), me++) : ((n = a), 0 === be && Se(c)), + n !== a ? ((de = t), (t = r = "<")) : ((me = t), (t = a))) + : ((me = t), (t = a)), + t + ); + } + function Le() { + var t, r, o, u, s, l; + return ( + (t = me), + (r = me), + 60 === e.charCodeAt(me) ? ((o = "<"), me++) : ((o = a), 0 === be && Se(c)), + o !== a && (u = We()) !== a && (s = $e()) !== a + ? ("/>" === e.substr(me, 2) ? ((l = "/>"), (me += 2)) : ((l = a), 0 === be && Se(p)), + l !== a ? (r = o = [o, u, s, l]) : ((me = r), (r = a))) + : ((me = r), (r = a)), + r !== a && ((de = t), (r = i({ type: n.literal, value: r.join("") }, at()))), + r + ); + } + function Pe() { + var t, r, n, i; + return ( + (t = me), + 60 === e.charCodeAt(me) ? ((r = "<"), me++) : ((r = a), 0 === be && Se(c)), + r !== a && (n = We()) !== a + ? (62 === e.charCodeAt(me) ? ((i = ">"), me++) : ((i = a), 0 === be && Se(h)), + i !== a ? ((de = t), (t = r = n)) : ((me = t), (t = a))) + : ((me = t), (t = a)), + t + ); + } + function Re() { + var t, r, n, i; + return ( + (t = me), + ""), me++) : ((i = a), 0 === be && Se(h)), + i !== a ? ((de = t), (t = r = n)) : ((me = t), (t = a))) + : ((me = t), (t = a)), + t + ); + } + function ze() { + var t, r, n, i, o; + if ( + (be++, + (t = me), + (r = []), + (n = me), + (i = me), + be++, + (o = He()) === a && (b.test(e.charAt(me)) ? ((o = e.charAt(me)), me++) : ((o = a), 0 === be && Se(w))), + be--, + o === a ? (i = void 0) : ((me = i), (i = a)), + i !== a + ? (e.length > me ? ((o = e.charAt(me)), me++) : ((o = a), 0 === be && Se(C)), + o !== a ? (n = i = [i, o]) : ((me = n), (n = a))) + : ((me = n), (n = a)), + n !== a) + ) + for (; n !== a; ) + r.push(n), + (n = me), + (i = me), + be++, + (o = He()) === a && (b.test(e.charAt(me)) ? ((o = e.charAt(me)), me++) : ((o = a), 0 === be && Se(w))), + be--, + o === a ? (i = void 0) : ((me = i), (i = a)), + i !== a + ? (e.length > me ? ((o = e.charAt(me)), me++) : ((o = a), 0 === be && Se(C)), + o !== a ? (n = i = [i, o]) : ((me = n), (n = a))) + : ((me = n), (n = a)); + else r = a; + return (t = r !== a ? e.substring(t, me) : r), be--, t === a && ((r = a), 0 === be && Se(A)), t; + } + function Me() { + var t, r, n; + return ( + be++, + (t = me), + 47 === e.charCodeAt(me) ? ((r = "/"), me++) : ((r = a), 0 === be && Se(F)), + r !== a && (n = ze()) !== a ? ((de = t), (t = r = n)) : ((me = t), (t = a)), + be--, + t === a && ((r = a), 0 === be && Se(x)), + t + ); + } + function Ve() { + var e, t, r, n; + if ((be++, (e = me), $e() !== a)) + if ((t = ze()) !== a) { + for (r = [], n = Me(); n !== a; ) r.push(n), (n = Me()); + r !== a + ? ((de = e), + (e = (function (e, t) { + return { stem: e, options: t }; + })(t, r))) + : ((me = e), (e = a)); + } else (me = e), (e = a); + else (me = e), (e = a); + return be--, e === a && 0 === be && Se(I), e; + } + function Ze() { + var t, r, n, i; + if (((t = me), 39 === e.charCodeAt(me) ? ((r = "'"), me++) : ((r = a), 0 === be && Se(j)), r !== a)) { + if ( + ((n = []), + (i = Xe()) === a && (N.test(e.charAt(me)) ? ((i = e.charAt(me)), me++) : ((i = a), 0 === be && Se(L))), + i !== a) + ) + for (; i !== a; ) + n.push(i), + (i = Xe()) === a && (N.test(e.charAt(me)) ? ((i = e.charAt(me)), me++) : ((i = a), 0 === be && Se(L))); + else n = a; + n !== a + ? (39 === e.charCodeAt(me) ? ((i = "'"), me++) : ((i = a), 0 === be && Se(j)), + i !== a ? (t = r = [r, n, i]) : ((me = t), (t = a))) + : ((me = t), (t = a)); + } else (me = t), (t = a); + if (t === a) + if ( + ((t = []), + (r = Xe()) === a && (P.test(e.charAt(me)) ? ((r = e.charAt(me)), me++) : ((r = a), 0 === be && Se(R))), + r !== a) + ) + for (; r !== a; ) + t.push(r), + (r = Xe()) === a && (P.test(e.charAt(me)) ? ((r = e.charAt(me)), me++) : ((r = a), 0 === be && Se(R))); + else t = a; + return t; + } + function Be() { + var t, r; + if (((t = []), z.test(e.charAt(me)) ? ((r = e.charAt(me)), me++) : ((r = a), 0 === be && Se(M)), r !== a)) + for (; r !== a; ) t.push(r), z.test(e.charAt(me)) ? ((r = e.charAt(me)), me++) : ((r = a), 0 === be && Se(M)); + else t = a; + return t; + } + function Ue() { + var t, r, n, o, u, c, s; + return ( + (t = me), + $e() !== a && (r = tt()) !== a && $e() !== a + ? (123 === e.charCodeAt(me) ? ((n = "{"), me++) : ((n = a), 0 === be && Se(d)), + n !== a + ? ((de = me), + rt.push("select"), + void 0 !== a && (o = Oe()) !== a + ? (125 === e.charCodeAt(me) ? ((u = "}"), me++) : ((u = a), 0 === be && Se(y)), + u !== a + ? ((de = t), (c = r), (s = o), rt.pop(), (t = i({ id: c, value: s }, at()))) + : ((me = t), (t = a))) + : ((me = t), (t = a))) + : ((me = t), (t = a))) + : ((me = t), (t = a)), + t + ); + } + function Ge() { + var t, r, n, o, u, c, s; + return ( + (t = me), + $e() !== a && + (r = (function l() { + var t, r, n, i; + return ( + (t = me), + (r = me), + 61 === e.charCodeAt(me) ? ((n = "="), me++) : ((n = a), 0 === be && Se(Y)), + n !== a && (i = qe()) !== a ? (r = n = [n, i]) : ((me = r), (r = a)), + (t = r !== a ? e.substring(t, me) : r) === a && (t = tt()), + t + ); + })()) !== a && + $e() !== a + ? (123 === e.charCodeAt(me) ? ((n = "{"), me++) : ((n = a), 0 === be && Se(d)), + n !== a + ? ((de = me), + rt.push("plural"), + void 0 !== a && (o = Oe()) !== a + ? (125 === e.charCodeAt(me) ? ((u = "}"), me++) : ((u = a), 0 === be && Se(y)), + u !== a + ? ((de = t), (c = r), (s = o), rt.pop(), (t = i({ id: c, value: s }, at()))) + : ((me = t), (t = a))) + : ((me = t), (t = a))) + : ((me = t), (t = a))) + : ((me = t), (t = a)), + t + ); + } + function He() { + var t; + return ( + be++, + q.test(e.charAt(me)) ? ((t = e.charAt(me)), me++) : ((t = a), 0 === be && Se(X)), + be--, + t === a && 0 === be && Se($), + t + ); + } + function Ye() { + var t; + return ( + be++, + K.test(e.charAt(me)) ? ((t = e.charAt(me)), me++) : ((t = a), 0 === be && Se(Q)), + be--, + t === a && 0 === be && Se(J), + t + ); + } + function $e() { + var t, r, n; + for (be++, t = me, r = [], n = He(); n !== a; ) r.push(n), (n = He()); + return (t = r !== a ? e.substring(t, me) : r), be--, t === a && ((r = a), 0 === be && Se(W)), t; + } + function qe() { + var t, r, n, i; + return ( + be++, + (t = me), + 45 === e.charCodeAt(me) ? ((r = "-"), me++) : ((r = a), 0 === be && Se(te)), + r === a && (r = null), + r !== a && (n = et()) !== a ? ((de = t), (t = r = (i = n) ? (r ? -i : i) : 0)) : ((me = t), (t = a)), + be--, + t === a && ((r = a), 0 === be && Se(ee)), + t + ); + } + function Xe() { + var t, r; + return ( + be++, + (t = me), + "''" === e.substr(me, 2) ? ((r = "''"), (me += 2)) : ((r = a), 0 === be && Se(ne)), + r !== a && ((de = t), (r = "'")), + be--, + (t = r) === a && ((r = a), 0 === be && Se(re)), + t + ); + } + function Je() { + var t, r, n, i, o, u; + if (((t = me), 39 === e.charCodeAt(me) ? ((r = "'"), me++) : ((r = a), 0 === be && Se(j)), r !== a)) + if ( + (n = (function c() { + var t, r, n, i, o; + return ( + (t = me), + (r = me), + e.length > me ? ((n = e.charAt(me)), me++) : ((n = a), 0 === be && Se(C)), + n !== a + ? ((de = me), + (i = (i = "<" === (o = n) || ">" === o || "{" === o || "}" === o || (nt() && "#" === o)) + ? void 0 + : a) !== a + ? (r = n = [n, i]) + : ((me = r), (r = a))) + : ((me = r), (r = a)), + r !== a ? e.substring(t, me) : r + ); + })()) !== a + ) { + for ( + i = me, + o = [], + "''" === e.substr(me, 2) ? ((u = "''"), (me += 2)) : ((u = a), 0 === be && Se(ne)), + u === a && (N.test(e.charAt(me)) ? ((u = e.charAt(me)), me++) : ((u = a), 0 === be && Se(L))); + u !== a; + + ) + o.push(u), + "''" === e.substr(me, 2) ? ((u = "''"), (me += 2)) : ((u = a), 0 === be && Se(ne)), + u === a && (N.test(e.charAt(me)) ? ((u = e.charAt(me)), me++) : ((u = a), 0 === be && Se(L))); + (i = o !== a ? e.substring(i, me) : o) !== a + ? (39 === e.charCodeAt(me) ? ((o = "'"), me++) : ((o = a), 0 === be && Se(j)), + o === a && (o = null), + o !== a ? ((de = t), (t = r = n + i.replace("''", "'"))) : ((me = t), (t = a))) + : ((me = t), (t = a)); + } else (me = t), (t = a); + else (me = t), (t = a); + return t; + } + function Ke() { + var t, r, n, i, o; + return ( + (t = me), + (r = me), + e.length > me ? ((n = e.charAt(me)), me++) : ((n = a), 0 === be && Se(C)), + n !== a + ? ((de = me), + (i = (i = !( + "<" === (o = n) || + "{" === o || + (nt() && "#" === o) || + ((function u() { + return rt.length > 1; + })() && + "}" === o) + )) + ? void 0 + : a) !== a + ? (r = n = [n, i]) + : ((me = r), (r = a))) + : ((me = r), (r = a)), + r === a && (10 === e.charCodeAt(me) ? ((r = "\n"), me++) : ((r = a), 0 === be && Se(ae))), + r !== a ? e.substring(t, me) : r + ); + } + function Qe() { + var t, r; + return ( + be++, + (t = me), + (r = et()) === a && (r = tt()), + (t = r !== a ? e.substring(t, me) : r), + be--, + t === a && ((r = a), 0 === be && Se(ie)), + t + ); + } + function We() { + var t, r; + return ( + be++, + (t = me), + (r = et()) === a && + (r = (function n() { + var t, r, n, i, o; + if ( + (be++, + (t = me), + (r = []), + 45 === e.charCodeAt(me) ? ((n = "-"), me++) : ((n = a), 0 === be && Se(te)), + n === a && + ((n = me), + (i = me), + be++, + (o = He()) === a && (o = Ye()), + be--, + o === a ? (i = void 0) : ((me = i), (i = a)), + i !== a + ? (e.length > me ? ((o = e.charAt(me)), me++) : ((o = a), 0 === be && Se(C)), + o !== a ? (n = i = [i, o]) : ((me = n), (n = a))) + : ((me = n), (n = a))), + n !== a) + ) + for (; n !== a; ) + r.push(n), + 45 === e.charCodeAt(me) ? ((n = "-"), me++) : ((n = a), 0 === be && Se(te)), + n === a && + ((n = me), + (i = me), + be++, + (o = He()) === a && (o = Ye()), + be--, + o === a ? (i = void 0) : ((me = i), (i = a)), + i !== a + ? (e.length > me ? ((o = e.charAt(me)), me++) : ((o = a), 0 === be && Se(C)), + o !== a ? (n = i = [i, o]) : ((me = n), (n = a))) + : ((me = n), (n = a))); + else r = a; + return (t = r !== a ? e.substring(t, me) : r), be--, t === a && ((r = a), 0 === be && Se(ge)), t; + })()), + (t = r !== a ? e.substring(t, me) : r), + be--, + t === a && ((r = a), 0 === be && Se(oe)), + t + ); + } + function et() { + var t, r, n, i, o; + if ( + (be++, + (t = me), + 48 === e.charCodeAt(me) ? ((r = "0"), me++) : ((r = a), 0 === be && Se(ce)), + r !== a && ((de = t), (r = 0)), + (t = r) === a) + ) { + if ( + ((t = me), + (r = me), + se.test(e.charAt(me)) ? ((n = e.charAt(me)), me++) : ((n = a), 0 === be && Se(le)), + n !== a) + ) { + for (i = [], fe.test(e.charAt(me)) ? ((o = e.charAt(me)), me++) : ((o = a), 0 === be && Se(pe)); o !== a; ) + i.push(o), fe.test(e.charAt(me)) ? ((o = e.charAt(me)), me++) : ((o = a), 0 === be && Se(pe)); + i !== a ? (r = n = [n, i]) : ((me = r), (r = a)); + } else (me = r), (r = a); + r !== a && ((de = t), (r = parseInt(r.join(""), 10))), (t = r); + } + return be--, t === a && ((r = a), 0 === be && Se(ue)), t; + } + function tt() { + var t, r, n, i, o; + if ( + (be++, + (t = me), + (r = []), + (n = me), + (i = me), + be++, + (o = He()) === a && (o = Ye()), + be--, + o === a ? (i = void 0) : ((me = i), (i = a)), + i !== a + ? (e.length > me ? ((o = e.charAt(me)), me++) : ((o = a), 0 === be && Se(C)), + o !== a ? (n = i = [i, o]) : ((me = n), (n = a))) + : ((me = n), (n = a)), + n !== a) + ) + for (; n !== a; ) + r.push(n), + (n = me), + (i = me), + be++, + (o = He()) === a && (o = Ye()), + be--, + o === a ? (i = void 0) : ((me = i), (i = a)), + i !== a + ? (e.length > me ? ((o = e.charAt(me)), me++) : ((o = a), 0 === be && Se(C)), + o !== a ? (n = i = [i, o]) : ((me = n), (n = a))) + : ((me = n), (n = a)); + else r = a; + return (t = r !== a ? e.substring(t, me) : r), be--, t === a && ((r = a), 0 === be && Se(he)), t; + } + var rt = ["root"]; + function nt() { + return "plural" === rt[rt.length - 1]; + } + function at() { + return t && t.captureLocation ? { location: Ce() } : {}; + } + var it = t && t.ignoreTag, + ot = t && t.shouldParseSkeleton; + if ((r = u()) !== a && me === e.length) return r; + throw ( + (r !== a && me < e.length && Se({ type: "end" }), + (function ut(e, t, r) { + return new D(D.buildMessage(e, t), e, t, r); + })(Ae, ve < e.length ? e.charAt(ve) : null, ke(ve, ve < e.length ? ve + 1 : ve))) + ); + }, + k = /(^|[^\\])#/g; + function S(e, t) { + t = i({ normalizeHashtagInPlural: !0, shouldParseSkeleton: !0 }, t || {}); + var r = F(e, t); + return ( + t.normalizeHashtagInPlural && + (function e(t) { + t.forEach(function (t) { + (h(t) || p(t)) && + Object.keys(t.options).forEach(function (r) { + for (var n, a = t.options[r], i = -1, c = void 0, s = 0; s < a.value.length; s++) { + var l = a.value[s]; + if (u(l) && k.test(l.value)) { + (i = s), (c = l); + break; + } + } + if (c) { + var f = c.value.replace(k, "$1{" + t.value + ", number}"), + p = F(f); + (n = a.value).splice.apply(n, o([i, 1], p)); + } + e(a.value); + }); + }); + })(r), + r + ); + } + function T(e, t, r, n) { + var a = (function i(e) { + return null == e || "number" == typeof e || "boolean" == typeof e; + })(n) + ? n + : r(n), + o = t.get(a); + return void 0 === o && ((o = e.call(this, n)), t.set(a, o)), o; + } + function O(e, t, r) { + var n = Array.prototype.slice.call(arguments, 3), + a = r(n), + i = t.get(a); + return void 0 === i && ((i = e.apply(this, n)), t.set(a, i)), i; + } + function _(e, t, r, n, a) { + return r.bind(t, e, n, a); + } + function j(e, t) { + return _(e, this, 1 === e.length ? T : O, t.cache.create(), t.serializer); + } + function N() { + return JSON.stringify(arguments); + } + function L() { + this.cache = Object.create(null); + } + (L.prototype.has = function (e) { + return e in this.cache; + }), + (L.prototype.get = function (e) { + return this.cache[e]; + }), + (L.prototype.set = function (e, t) { + this.cache[e] = t; + }); + var P = { + create: function e() { + return new L(); + }, + }, + R = function z(e, t) { + return (t && t.strategy ? t.strategy : j)(e, { + cache: t && t.cache ? t.cache : P, + serializer: t && t.serializer ? t.serializer : N, + }); + }, + M = { + variadic: function V(e, t) { + return _(e, this, O, t.cache.create(), t.serializer); + }, + monadic: function Z(e, t) { + return _(e, this, T, t.cache.create(), t.serializer); + }, + }; + R.strategies = M; + var B, + U = Object.freeze(Object.assign(Object.create(null), R, { default: R, strategies: M })); + ((B = e.ErrorCode || (e.ErrorCode = {})).MISSING_VALUE = "MISSING_VALUE"), + (B.INVALID_VALUE = "INVALID_VALUE"), + (B.MISSING_INTL_API = "MISSING_INTL_API"); + var G, + H = (function (e) { + function t(t, r, n) { + var a = e.call(this, t) || this; + return (a.code = r), (a.originalMessage = n), a; + } + return ( + r(t, e), + (t.prototype.toString = function () { + return "[formatjs Error: " + this.code + "] " + this.message; + }), + t + ); + })(Error), + Y = (function (e) { + function t(t, r, n, a) { + return ( + e.call( + this, + 'Invalid values for "' + t + '": "' + r + '". Options are "' + Object.keys(n).join('", "') + '"', + "INVALID_VALUE", + a + ) || this + ); + } + return r(t, e), t; + })(H), + $ = (function (e) { + function t(t, r, n) { + return e.call(this, 'Value for "' + t + '" must be of type ' + r, "INVALID_VALUE", n) || this; + } + return r(t, e), t; + })(H), + q = (function (e) { + function t(t, r) { + return ( + e.call( + this, + 'The intl string context variable "' + t + '" was not provided to the string "' + r + '"', + "MISSING_VALUE", + r + ) || this + ); + } + return r(t, e), t; + })(H); + function X(e) { + return "function" == typeof e; + } + function J(e, t, r, n, a, i, o) { + if (1 === e.length && u(e[0])) return [{ type: 0, value: e[0].value }]; + for (var v = [], A = 0, b = e; A < b.length; A++) { + var w = b[A]; + if (u(w)) v.push({ type: 0, value: w.value }); + else if (g(w)) "number" == typeof i && v.push({ type: 0, value: r.getNumberFormat(t).format(i) }); + else { + var C = w.value; + if (!a || !(C in a)) throw new q(C, o); + var x = a[C]; + if (c(w)) + (x && "string" != typeof x && "number" != typeof x) || + (x = "string" == typeof x || "number" == typeof x ? String(x) : ""), + v.push({ type: "string" == typeof x ? 0 : 1, value: x }); + else if (l(w)) { + var E = "string" == typeof w.style ? n.date[w.style] : y(w.style) ? w.style.parsedOptions : void 0; + v.push({ type: 0, value: r.getDateTimeFormat(t, E).format(x) }); + } else if (f(w)) + (E = "string" == typeof w.style ? n.time[w.style] : y(w.style) ? w.style.parsedOptions : void 0), + v.push({ type: 0, value: r.getDateTimeFormat(t, E).format(x) }); + else if (s(w)) + (E = "string" == typeof w.style ? n.number[w.style] : d(w.style) ? w.style.parsedOptions : void 0), + v.push({ type: 0, value: r.getNumberFormat(t, E).format(x) }); + else { + if (m(w)) { + var D = w.children, + F = w.value, + I = a[F]; + if (!X(I)) throw new $(F, "function", o); + var k = I( + J(D, t, r, n, a, i).map(function (e) { + return e.value; + }) + ); + Array.isArray(k) || (k = [k]), + v.push.apply( + v, + k.map(function (e) { + return { type: "string" == typeof e ? 0 : 1, value: e }; + }) + ); + } + if (p(w)) { + if (!(S = w.options[x] || w.options.other)) throw new Y(w.value, x, Object.keys(w.options), o); + v.push.apply(v, J(S.value, t, r, n, a)); + } else if (h(w)) { + var S; + if (!(S = w.options["=" + x])) { + if (!Intl.PluralRules) + throw new H( + 'Intl.PluralRules is not available in this environment.\nTry polyfilling it using "@formatjs/intl-pluralrules"\n', + "MISSING_INTL_API", + o + ); + var T = r.getPluralRules(t, { type: w.pluralType }).select(x - (w.offset || 0)); + S = w.options[T] || w.options.other; + } + if (!S) throw new Y(w.value, x, Object.keys(w.options), o); + v.push.apply(v, J(S.value, t, r, n, a, x - (w.offset || 0))); + } + } + } + } + return (function O(e) { + return e.length < 2 + ? e + : e.reduce(function (e, t) { + var r = e[e.length - 1]; + return r && 0 === r.type && 0 === t.type ? (r.value += t.value) : e.push(t), e; + }, []); + })(v); + } + function K(e) { + return { + create: function () { + return { + has: function (t) { + return t in e; + }, + get: function (t) { + return e[t]; + }, + set: function (t, r) { + e[t] = r; + }, + }; + }, + }; + } + ((G = e.PART_TYPE || (e.PART_TYPE = {}))[(G.literal = 0)] = "literal"), (G[(G.object = 1)] = "object"); + var Q = R || U, + W = (function () { + function e(t, r, n, a) { + var u = this; + if ( + (void 0 === r && (r = e.defaultLocale), + (this.formatterCache = { number: {}, dateTime: {}, pluralRules: {} }), + (this.format = function (e) { + var t = u.formatToParts(e); + if (1 === t.length) return t[0].value; + var r = t.reduce(function (e, t) { + return ( + e.length && 0 === t.type && "string" == typeof e[e.length - 1] + ? (e[e.length - 1] += t.value) + : e.push(t.value), + e + ); + }, []); + return r.length <= 1 ? r[0] || "" : r; + }), + (this.formatToParts = function (e) { + return J(u.ast, u.locales, u.formatters, u.formats, e, void 0, u.message); + }), + (this.resolvedOptions = function () { + return { locale: Intl.NumberFormat.supportedLocalesOf(u.locales)[0] }; + }), + (this.getAst = function () { + return u.ast; + }), + "string" == typeof t) + ) { + if (((this.message = t), !e.__parse)) + throw new TypeError("IntlMessageFormat.__parse must be set to process `message` of type `string`"); + this.ast = e.__parse(t, { normalizeHashtagInPlural: !1, ignoreTag: null == a ? void 0 : a.ignoreTag }); + } else this.ast = t; + if (!Array.isArray(this.ast)) throw new TypeError("A message must be provided as a String or AST."); + (this.formats = (function c(e, t) { + return t + ? Object.keys(e).reduce(function (r, n) { + return ( + (r[n] = (function a(e, t) { + return t + ? i( + i(i({}, e || {}), t || {}), + Object.keys(e).reduce(function (r, n) { + return (r[n] = i(i({}, e[n]), t[n] || {})), r; + }, {}) + ) + : e; + })(e[n], t[n])), + r + ); + }, i({}, e)) + : e; + })(e.formats, n)), + (this.locales = r), + (this.formatters = + (a && a.formatters) || + (function s(e) { + return ( + void 0 === e && (e = { number: {}, dateTime: {}, pluralRules: {} }), + { + getNumberFormat: Q( + function () { + for (var e, t = [], r = 0; r < arguments.length; r++) t[r] = arguments[r]; + return new ((e = Intl.NumberFormat).bind.apply(e, o([void 0], t)))(); + }, + { cache: K(e.number), strategy: Q.strategies.variadic } + ), + getDateTimeFormat: Q( + function () { + for (var e, t = [], r = 0; r < arguments.length; r++) t[r] = arguments[r]; + return new ((e = Intl.DateTimeFormat).bind.apply(e, o([void 0], t)))(); + }, + { cache: K(e.dateTime), strategy: Q.strategies.variadic } + ), + getPluralRules: Q( + function () { + for (var e, t = [], r = 0; r < arguments.length; r++) t[r] = arguments[r]; + return new ((e = Intl.PluralRules).bind.apply(e, o([void 0], t)))(); + }, + { cache: K(e.pluralRules), strategy: Q.strategies.variadic } + ), + } + ); + })(this.formatterCache)); + } + return ( + Object.defineProperty(e, "defaultLocale", { + get: function () { + return ( + e.memoizedDefaultLocale || (e.memoizedDefaultLocale = new Intl.NumberFormat().resolvedOptions().locale), + e.memoizedDefaultLocale + ); + }, + enumerable: !1, + configurable: !0, + }), + (e.memoizedDefaultLocale = null), + (e.__parse = S), + (e.formats = { + number: { currency: { style: "currency" }, percent: { style: "percent" } }, + date: { + short: { month: "numeric", day: "numeric", year: "2-digit" }, + medium: { month: "short", day: "numeric", year: "numeric" }, + long: { month: "long", day: "numeric", year: "numeric" }, + full: { weekday: "long", month: "long", day: "numeric", year: "numeric" }, + }, + time: { + short: { hour: "numeric", minute: "numeric" }, + medium: { hour: "numeric", minute: "numeric", second: "numeric" }, + long: { hour: "numeric", minute: "numeric", second: "numeric", timeZoneName: "short" }, + full: { hour: "numeric", minute: "numeric", second: "numeric", timeZoneName: "short" }, + }, + }), + e + ); + })(); + (e.FormatError = H), + (e.IntlMessageFormat = W), + (e.InvalidValueError = Y), + (e.InvalidValueTypeError = $), + (e.MissingValueError = q), + (e.default = W), + (e.formatToParts = J), + (e.isFormatXMLElementFn = X), + Object.defineProperty(e, "__esModule", { value: !0 }); +}); diff --git a/libraries/l10n.js b/libraries/l10n.js new file mode 100644 index 0000000..8a5878b --- /dev/null +++ b/libraries/l10n.js @@ -0,0 +1,79 @@ +import { escapeHTML } from "./autoescaper.js"; +import * as _IntlMessageFormat from "./intl-messageformat.umd.min.js"; +const MessageFormat = IntlMessageFormat.IntlMessageFormat; + +// This library is shared between background and userscript. +// Subclasses are responsible for implementing methods to load translations. + +export default class LocalizationProvider extends EventTarget { + constructor() { + super(); + this.messages = {}; + this._cache = {}; + this._cache_locale = ""; + this._date = new Intl.DateTimeFormat(); + this._datetime = new Intl.DateTimeFormat([], { + timeStyle: "short", + dateStyle: "short", + }); + } + + _refreshDateTime() { + this._date = new Intl.DateTimeFormat(this.locale); + this._datetime = new Intl.DateTimeFormat(this.locale, { + timeStyle: "short", + dateStyle: "short", + }); + } + + _generateCache(messages) { + messages = messages || this.messages; + this._cache_locale = messages._locale || this.locale; + for (const message of Object.keys(messages)) { + if (message.startsWith("_")) continue; + this._cache[message] = new MessageFormat(messages[message], this._cache_locale); + } + } + + _get(key, placeholders, messageHandler, fallback) { + // Use cache if raw message is requested, and cache is up-to-date + if ( + messageHandler === null && + this.locale === this._cache_locale && + Object.prototype.hasOwnProperty.call(this._cache, key) + ) { + return this._cache[key].format(placeholders); + } + messageHandler = messageHandler || ((m) => m); + if (Object.prototype.hasOwnProperty.call(this.messages, key)) { + const message = messageHandler(this.messages[key]); + return new MessageFormat(message, this.locale).format(placeholders); + } + console.warn("Key missing:", key); + return fallback || key; + } + + get(key, placeholders = {}, fallback = "") { + return this._get(key, placeholders, null, fallback); + } + + escaped(key, placeholders = {}, fallback = "") { + return this._get(key, placeholders, (message) => escapeHTML(message), fallback); + } + + get locale() { + return this.messages._locale || "en"; + } + + get localeName() { + return this.messages._locale_name || "English"; + } + + date(dateObj) { + return this._date.format(dateObj); + } + + datetime(dateObj) { + return this._datetime.format(dateObj); + } +} diff --git a/manifest.json b/manifest.json new file mode 100644 index 0000000..3fabc26 --- /dev/null +++ b/manifest.json @@ -0,0 +1,25 @@ +{ + "manifest_version": 2, + "name": "__MSG_extensionName__", + "description": "__MSG_extensionDescription__", + "default_locale": "en", + "author": "Griffpatch", + "version": "1.8.0", + "homepage_url": "https://www.griffpatch.co.uk", + "icons": { + "32": "images/favicon.png", + "128": "images/bigIcon.png" + }, + "browser_action": { + "default_icon": "images/favicon.png" + }, + "content_scripts": [ + { + "run_at": "document_start", + "matches": ["https://scratch.mit.edu/projects/*", "https://llk.github.io/scratch-gui/*"], + "js": ["run-inject.js"], + "css": ["addon/userscript.css"] + } + ], + "web_accessible_resources": ["addon/*", "images/*", "inject/*", "libraries/*", "l10n/*"] +} diff --git a/run-inject.js b/run-inject.js new file mode 100644 index 0000000..4bf06b2 --- /dev/null +++ b/run-inject.js @@ -0,0 +1,20 @@ +if (document.head) onHeadAvailable(); +else { + const observer = new MutationObserver(() => { + if (document.head) { + onHeadAvailable(); + observer.disconnect(); + } + }); + observer.observe(document.documentElement, { subtree: true, childList: true }); +} + +function onHeadAvailable() { + document.head.classList.add("griffpatchDevtoolsExtensionEnabled"); + const script = document.createElement("script"); + script.id = "devtools-extension-module"; + script.setAttribute("data-path", chrome.runtime.getURL("")); + script.type = "module"; + script.src = chrome.runtime.getURL("inject/run-addon.js"); + document.head.appendChild(script); +}