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

- MIT license + GNU AGPLv3 license Star SketchForge on GitHub Sponsor SketchForge on GitHub Local first - Version v0.9.0 + Version v1.0.0

@@ -212,19 +212,38 @@ docker compose -f deploy/docker/compose.yaml down ### Update SketchForge Later -If you used Git: +The home dashboard's **Settings** panel checks the official version and displays an update prompt when a newer version is available. It never installs an update automatically. Choosing **Not now** dismisses only that version, so a later release will be offered again. + +If you used Git, update the existing checkout in place. You do not need to remove or download the repository again: ```bash git pull docker compose -f deploy/docker/compose.yaml up --build -d ``` +If you use the prebuilt GHCR Compose file: + +```bash +docker compose -f deploy/docker/compose-ghcr.yaml pull sketchforge +docker compose -f deploy/docker/compose-ghcr.yaml up -d --no-deps sketchforge +``` + If you downloaded the ZIP, download the newest ZIP, extract it, and run: ```bash docker compose -f deploy/docker/compose.yaml up --build -d ``` +Application updates do not clear private projects stored in the browser. Docker shared projects remain in the existing `sketchforge-shared-projects` volume or the host directory configured with `SKETCHFORGE_SHARED_PROJECTS_VOLUME`. Never add `--volumes` or `-v` to an update command. + +For an administrator-managed one-click installation, configure all of the following server variables: + +- `SKETCHFORGE_UPDATE_TRIGGER_URL`: an internal HTTPS endpoint that pulls/recreates only the SketchForge application while retaining its existing project volume. +- `SKETCHFORGE_UPDATE_ADMIN_KEY`: the key the administrator must enter in the confirmation dialog. +- `SKETCHFORGE_UPDATE_TRIGGER_TOKEN` (optional): a bearer token SketchForge sends only to the internal update service. + +Without an administrator-managed trigger, the confirmation opens these safe update instructions instead of granting the web container access to the Docker socket. + ### Docker Troubleshooting - **`docker` is not recognized**: install Docker Desktop, open it, and try again. @@ -326,7 +345,11 @@ Please do not open public issues for security-sensitive reports. Read [.github/S ## License -MIT. See [LICENSE](LICENSE). +Copyright © 2026 SketchForge contributors. + +SketchForge is licensed under the **GNU Affero General Public License v3.0 only** (`AGPL-3.0-only`). If you modify SketchForge and let users interact with the modified version over a network, you must offer those users the corresponding source code under the same license. See [LICENSE](LICENSE). + +The application exposes a **Source** link in the dashboard. Operators distributing or hosting a modified build should set `NEXT_PUBLIC_SOURCE_CODE_URL` at build time to the public URL containing that build's complete corresponding source code. ## SketchForge MCP Skill diff --git a/apps/web/.env.example b/apps/web/.env.example index f5e6522..06b1c3d 100644 --- a/apps/web/.env.example +++ b/apps/web/.env.example @@ -1 +1,7 @@ # No environment variables are required for local development. + +# Optional administrator-managed update trigger. Keep these server-side; never +# prefix them with NEXT_PUBLIC_. The trigger must preserve /data/projects. +# SKETCHFORGE_UPDATE_TRIGGER_URL=https://updater.internal/sketchforge +# SKETCHFORGE_UPDATE_ADMIN_KEY=replace-with-a-long-random-key +# SKETCHFORGE_UPDATE_TRIGGER_TOKEN=optional-internal-service-token diff --git a/apps/web/public/assets/challenges/key-tag/01-finished-target.png b/apps/web/public/assets/challenges/key-tag/01-finished-target.png new file mode 100644 index 0000000..9d1fa4f Binary files /dev/null and b/apps/web/public/assets/challenges/key-tag/01-finished-target.png differ diff --git a/apps/web/public/assets/challenges/key-tag/02-middle-box.png b/apps/web/public/assets/challenges/key-tag/02-middle-box.png new file mode 100644 index 0000000..78bcf5f Binary files /dev/null and b/apps/web/public/assets/challenges/key-tag/02-middle-box.png differ diff --git a/apps/web/public/assets/challenges/key-tag/03-left-round-end.png b/apps/web/public/assets/challenges/key-tag/03-left-round-end.png new file mode 100644 index 0000000..183ffba Binary files /dev/null and b/apps/web/public/assets/challenges/key-tag/03-left-round-end.png differ diff --git a/apps/web/public/assets/challenges/key-tag/04-right-round-end.png b/apps/web/public/assets/challenges/key-tag/04-right-round-end.png new file mode 100644 index 0000000..020de97 Binary files /dev/null and b/apps/web/public/assets/challenges/key-tag/04-right-round-end.png differ diff --git a/apps/web/public/assets/challenges/key-tag/05-select-left-circle.png b/apps/web/public/assets/challenges/key-tag/05-select-left-circle.png new file mode 100644 index 0000000..717861c Binary files /dev/null and b/apps/web/public/assets/challenges/key-tag/05-select-left-circle.png differ diff --git a/apps/web/public/assets/challenges/key-tag/06-hole-cylinder.png b/apps/web/public/assets/challenges/key-tag/06-hole-cylinder.png new file mode 100644 index 0000000..0badbf7 Binary files /dev/null and b/apps/web/public/assets/challenges/key-tag/06-hole-cylinder.png differ diff --git a/apps/web/public/assets/challenges/key-tag/07-align-hole.png b/apps/web/public/assets/challenges/key-tag/07-align-hole.png new file mode 100644 index 0000000..1f64bdb Binary files /dev/null and b/apps/web/public/assets/challenges/key-tag/07-align-hole.png differ diff --git a/apps/web/public/assets/challenges/key-tag/08-unlock-left-circle.png b/apps/web/public/assets/challenges/key-tag/08-unlock-left-circle.png new file mode 100644 index 0000000..f96f40b Binary files /dev/null and b/apps/web/public/assets/challenges/key-tag/08-unlock-left-circle.png differ diff --git a/apps/web/public/assets/challenges/key-tag/09-grouped-key-tag.png b/apps/web/public/assets/challenges/key-tag/09-grouped-key-tag.png new file mode 100644 index 0000000..49a75d6 Binary files /dev/null and b/apps/web/public/assets/challenges/key-tag/09-grouped-key-tag.png differ diff --git a/apps/web/public/assets/challenges/key-tag/card-key-tag-dark.webp b/apps/web/public/assets/challenges/key-tag/card-key-tag-dark.webp new file mode 100644 index 0000000..74f2af6 Binary files /dev/null and b/apps/web/public/assets/challenges/key-tag/card-key-tag-dark.webp differ diff --git a/apps/web/public/assets/challenges/key-tag/card-key-tag-light.webp b/apps/web/public/assets/challenges/key-tag/card-key-tag-light.webp new file mode 100644 index 0000000..3db4a33 Binary files /dev/null and b/apps/web/public/assets/challenges/key-tag/card-key-tag-light.webp differ diff --git a/apps/web/public/assets/challenges/nameplate/01-finished-target.webp b/apps/web/public/assets/challenges/nameplate/01-finished-target.webp new file mode 100644 index 0000000..cac24ed Binary files /dev/null and b/apps/web/public/assets/challenges/nameplate/01-finished-target.webp differ diff --git a/apps/web/public/assets/challenges/nameplate/02-base-box.png b/apps/web/public/assets/challenges/nameplate/02-base-box.png new file mode 100644 index 0000000..707039f Binary files /dev/null and b/apps/web/public/assets/challenges/nameplate/02-base-box.png differ diff --git a/apps/web/public/assets/challenges/nameplate/02-base-box.webp b/apps/web/public/assets/challenges/nameplate/02-base-box.webp new file mode 100644 index 0000000..d448dcc Binary files /dev/null and b/apps/web/public/assets/challenges/nameplate/02-base-box.webp differ diff --git a/apps/web/public/assets/challenges/nameplate/03-rounded-base.webp b/apps/web/public/assets/challenges/nameplate/03-rounded-base.webp new file mode 100644 index 0000000..1725235 Binary files /dev/null and b/apps/web/public/assets/challenges/nameplate/03-rounded-base.webp differ diff --git a/apps/web/public/assets/challenges/nameplate/04-text-added.webp b/apps/web/public/assets/challenges/nameplate/04-text-added.webp new file mode 100644 index 0000000..32180ac Binary files /dev/null and b/apps/web/public/assets/challenges/nameplate/04-text-added.webp differ diff --git a/apps/web/public/assets/challenges/nameplate/05-text-customized.webp b/apps/web/public/assets/challenges/nameplate/05-text-customized.webp new file mode 100644 index 0000000..f675dfb Binary files /dev/null and b/apps/web/public/assets/challenges/nameplate/05-text-customized.webp differ diff --git a/apps/web/public/assets/challenges/nameplate/06-text-centered.webp b/apps/web/public/assets/challenges/nameplate/06-text-centered.webp new file mode 100644 index 0000000..3897eb3 Binary files /dev/null and b/apps/web/public/assets/challenges/nameplate/06-text-centered.webp differ diff --git a/apps/web/public/assets/challenges/nameplate/07-grouped-nameplate.webp b/apps/web/public/assets/challenges/nameplate/07-grouped-nameplate.webp new file mode 100644 index 0000000..cac24ed Binary files /dev/null and b/apps/web/public/assets/challenges/nameplate/07-grouped-nameplate.webp differ diff --git a/apps/web/public/assets/challenges/nameplate/card-nameplate-dark.webp b/apps/web/public/assets/challenges/nameplate/card-nameplate-dark.webp new file mode 100644 index 0000000..8391545 Binary files /dev/null and b/apps/web/public/assets/challenges/nameplate/card-nameplate-dark.webp differ diff --git a/apps/web/public/assets/challenges/nameplate/card-nameplate-light.webp b/apps/web/public/assets/challenges/nameplate/card-nameplate-light.webp new file mode 100644 index 0000000..cac24ed Binary files /dev/null and b/apps/web/public/assets/challenges/nameplate/card-nameplate-light.webp differ diff --git a/apps/web/src/app/api/app-update/route.ts b/apps/web/src/app/api/app-update/route.ts new file mode 100644 index 0000000..806e3a3 --- /dev/null +++ b/apps/web/src/app/api/app-update/route.ts @@ -0,0 +1,166 @@ +import { timingSafeEqual } from "node:crypto"; +import { NextResponse } from "next/server"; +import { appUpdateIsAvailable, OFFICIAL_UPDATE_GUIDE_URL, type AppUpdateStatus } from "@/lib/appUpdates"; +import { SKF_CREATED_WITH_VERSION } from "@/lib/skfProject"; + +export const runtime = "nodejs"; +export const dynamic = "force-dynamic"; +export const revalidate = false; + +const DEFAULT_MANIFEST_URL = "https://raw.githubusercontent.com/Formsmith746/SketchForge-3D/main/package.json"; +const UPDATE_CACHE_MS = 5 * 60 * 1000; +const UPDATE_TRIGGER_COOLDOWN_MS = 15 * 1000; + +let cachedLatest: { version: string; expiresAt: number } | null = null; +let nextTriggerAt = 0; + +function sameOriginRequest(request: Request) { + const origin = request.headers.get("origin"); + if (!origin) return true; + try { + const requestUrl = new URL(request.url); + const forwardedHost = request.headers.get("x-forwarded-host")?.split(",")[0]?.trim(); + const forwardedProtocol = request.headers.get("x-forwarded-proto")?.split(",")[0]?.trim(); + const host = forwardedHost || request.headers.get("host") || requestUrl.host; + const protocol = forwardedProtocol || requestUrl.protocol.replace(/:$/, ""); + return new URL(origin).origin === `${protocol}://${host}`; + } catch { + return false; + } +} + +function safeEqual(left: string, right: string) { + const leftBytes = Buffer.from(left); + const rightBytes = Buffer.from(right); + return leftBytes.length === rightBytes.length && timingSafeEqual(leftBytes, rightBytes); +} + +function updateTriggerUrl() { + const configured = process.env.SKETCHFORGE_UPDATE_TRIGGER_URL?.trim(); + if (!configured) return null; + try { + const url = new URL(configured); + return url.protocol === "http:" || url.protocol === "https:" ? url : null; + } catch { + return null; + } +} + +async function latestOfficialVersion(force = false) { + if (!force && cachedLatest && cachedLatest.expiresAt > Date.now()) return cachedLatest.version; + const controller = new AbortController(); + const timeout = setTimeout(() => controller.abort(), 7_500); + try { + const response = await fetch(process.env.SKETCHFORGE_UPDATE_MANIFEST_URL?.trim() || DEFAULT_MANIFEST_URL, { + cache: "no-store", + headers: { Accept: "application/json", "User-Agent": "SketchForge update checker" }, + signal: controller.signal, + }); + if (!response.ok) throw new Error(`Update server returned ${response.status}`); + const payload = await response.json() as { version?: unknown }; + const version = typeof payload.version === "string" ? payload.version.trim() : ""; + if (!/^v?\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/.test(version)) { + throw new Error("Update server returned an invalid version"); + } + cachedLatest = { version, expiresAt: Date.now() + UPDATE_CACHE_MS }; + return version; + } finally { + clearTimeout(timeout); + } +} + +function updateGuideUrl() { + return process.env.SKETCHFORGE_UPDATE_GUIDE_URL?.trim() || OFFICIAL_UPDATE_GUIDE_URL; +} + +async function statusResponse(force = false): Promise { + const trigger = updateTriggerUrl(); + const adminKeyConfigured = Boolean(process.env.SKETCHFORGE_UPDATE_ADMIN_KEY?.trim()); + try { + const latestVersion = await latestOfficialVersion(force); + return { + currentVersion: SKF_CREATED_WITH_VERSION, + latestVersion, + updateAvailable: appUpdateIsAvailable(SKF_CREATED_WITH_VERSION, latestVersion), + checkedAt: new Date().toISOString(), + updateUrl: updateGuideUrl(), + installationReady: Boolean(trigger && adminKeyConfigured), + requiresUpdateKey: Boolean(trigger && adminKeyConfigured), + }; + } catch (error) { + return { + currentVersion: SKF_CREATED_WITH_VERSION, + latestVersion: null, + updateAvailable: false, + checkedAt: new Date().toISOString(), + updateUrl: updateGuideUrl(), + installationReady: Boolean(trigger && adminKeyConfigured), + requiresUpdateKey: Boolean(trigger && adminKeyConfigured), + checkError: error instanceof Error ? error.message : "Could not check for updates", + }; + } +} + +export async function GET(request: Request) { + const force = new URL(request.url).searchParams.get("force") === "1"; + return NextResponse.json(await statusResponse(force), { headers: { "Cache-Control": "no-store" } }); +} + +export async function POST(request: Request) { + if (!sameOriginRequest(request)) return NextResponse.json({ error: "Updates only accept same-origin requests" }, { status: 403 }); + const trigger = updateTriggerUrl(); + const adminKey = process.env.SKETCHFORGE_UPDATE_ADMIN_KEY?.trim() || ""; + if (!trigger || !adminKey) { + return NextResponse.json( + { error: "One-click installation is not configured on this server", updateUrl: updateGuideUrl() }, + { status: 409 }, + ); + } + + const suppliedKey = request.headers.get("x-sketchforge-update-key")?.trim() || ""; + if (!suppliedKey || !safeEqual(suppliedKey, adminKey)) { + return NextResponse.json({ error: "The update key is incorrect" }, { status: 401 }); + } + if (Date.now() < nextTriggerAt) { + return NextResponse.json({ error: "An update was already requested. Wait a moment before trying again." }, { status: 429 }); + } + + const status = await statusResponse(true); + if (status.checkError) return NextResponse.json({ error: status.checkError }, { status: 502 }); + if (!status.updateAvailable || !status.latestVersion) { + return NextResponse.json({ error: "SketchForge is already up to date", status }, { status: 409 }); + } + + nextTriggerAt = Date.now() + UPDATE_TRIGGER_COOLDOWN_MS; + const controller = new AbortController(); + const timeout = setTimeout(() => controller.abort(), 10_000); + try { + const triggerToken = process.env.SKETCHFORGE_UPDATE_TRIGGER_TOKEN?.trim(); + const response = await fetch(trigger, { + method: "POST", + headers: { + Accept: "application/json", + "Content-Type": "application/json", + ...(triggerToken ? { Authorization: `Bearer ${triggerToken}` } : {}), + }, + body: JSON.stringify({ + application: "SketchForge", + currentVersion: status.currentVersion, + latestVersion: status.latestVersion, + preserveProjectStorage: true, + }), + cache: "no-store", + signal: controller.signal, + }); + if (!response.ok) throw new Error(`Update service returned ${response.status}`); + return NextResponse.json( + { accepted: true, currentVersion: status.currentVersion, latestVersion: status.latestVersion }, + { status: 202, headers: { "Cache-Control": "no-store" } }, + ); + } catch (error) { + nextTriggerAt = 0; + return NextResponse.json({ error: error instanceof Error ? error.message : "Could not start the update" }, { status: 502 }); + } finally { + clearTimeout(timeout); + } +} diff --git a/apps/web/src/app/globals.css b/apps/web/src/app/globals.css index 44d9c01..332a195 100644 --- a/apps/web/src/app/globals.css +++ b/apps/web/src/app/globals.css @@ -1,4 +1,4 @@ -@import "tailwindcss"; +@import "tailwindcss"; :root { --background: #fafafa; @@ -581,6 +581,11 @@ button { color: #536a80; } +.dashboard-sidebar-footer { + display: grid; + gap: 8px; +} + .dashboard-main { min-width: 0; padding: 22px; @@ -1178,6 +1183,8 @@ button { z-index: 12; display: grid; width: min(380px, calc(100vw - 32px)); + max-height: calc(100vh - 44px); + overflow-y: auto; gap: 14px; padding: 16px; color: #263f57; @@ -1253,6 +1260,160 @@ button { font-size: 14px; } +.dashboard-version-row a { + color: #0e69f1; + font-size: 13px; + font-weight: 850; + text-decoration: none; +} + +.dashboard-version-row a:hover { + text-decoration: underline; +} + +.dashboard-update-settings { + display: grid; + gap: 10px; + padding: 13px; + color: #52697d; + border: 1px solid #d6e1ea; + border-radius: 7px; + background: #f6f9fb; +} + +.dashboard-update-settings > div { + display: grid; + gap: 4px; +} + +.dashboard-update-settings > div strong { + color: #263f57; + font-size: 14px; +} + +.dashboard-update-settings > div span, +.dashboard-update-status { + font-size: 12px; + font-weight: 650; + line-height: 1.4; +} + +.dashboard-update-status.ready { + color: #187146; + font-weight: 800; +} + +.dashboard-update-status.error { + color: #b4232f; +} + +.dashboard-check-update, +.dashboard-update-available { + display: inline-flex; + min-height: 36px; + align-items: center; + justify-content: center; + gap: 7px; + padding: 0 12px; + border-radius: 6px; + font-size: 13px; + font-weight: 800; + cursor: pointer; +} + +.dashboard-check-update { + color: #31526b; + border: 1px solid #cbd9e3; + background: #ffffff; +} + +.dashboard-update-available { + color: #ffffff; + border: 1px solid #0e69f1; + background: #0e69f1; +} + +.dashboard-check-update:disabled, +.dashboard-update-available:disabled { + cursor: wait; + opacity: 0.62; +} + +.dashboard-check-update .spin { + animation: dashboard-update-spin 850ms linear infinite; +} + +@keyframes dashboard-update-spin { + to { transform: rotate(360deg); } +} + +.dashboard-update-dialog { + width: min(500px, 100%); +} + +.dashboard-update-copy { + display: grid; + gap: 12px; + padding: 18px; +} + +.dashboard-update-copy > p { + padding: 0; +} + +.dashboard-update-safety, +.dashboard-update-note, +.dashboard-update-message { + padding: 11px 12px; + color: #40586c; + border: 1px solid #cfe0ec; + border-radius: 6px; + background: #f2f8fc; + font-size: 13px; + font-weight: 650; + line-height: 1.45; +} + +.dashboard-update-safety code { + color: #1d4f72; + font-weight: 800; +} + +.dashboard-update-note { + border-color: #ead9ae; + background: #fff9e9; +} + +.dashboard-update-message { + border-color: #bdddc9; + background: #effaf3; +} + +.dashboard-update-key { + display: grid; + gap: 7px; + color: #40586c; + font-size: 13px; + font-weight: 800; +} + +.dashboard-update-key input { + width: 100%; + height: 40px; + min-width: 0; + padding: 0 11px; + color: #1d3448; + border: 1px solid #cbd9e3; + border-radius: 6px; + outline: 0; + background: #ffffff; +} + +.dashboard-update-key input:focus { + border-color: #0e69f1; + box-shadow: 0 0 0 3px rgba(14, 105, 241, 0.12); +} + @media (max-width: 860px) { .dashboard-topbar { grid-template-columns: 1fr auto; @@ -3578,13 +3739,6 @@ button { fill: #607589; } -.sketch-grid-settings { - padding: 4px 7px; - background: rgba(248, 251, 252, 0.92); - border: 1px solid #d6e2e9; - border-radius: 3px; -} - .sketch-point-actions { position: absolute; bottom: 12px; @@ -6448,6 +6602,62 @@ html[data-theme="dark"] .workplane-stage { background: var(--background); } +html[data-theme="dark"] .editor-loading-screen { + background: #101820; +} + +html[data-theme="dark"] .editor-skeleton-shimmer { + background: #304552; +} + +html[data-theme="dark"] .editor-skeleton-shimmer::after { + background: linear-gradient( + 105deg, + transparent 18%, + rgba(142, 177, 196, 0.08) 38%, + rgba(188, 215, 229, 0.28) 50%, + rgba(142, 177, 196, 0.08) 62%, + transparent 82% + ); +} + +html[data-theme="dark"] .editor-loading-toolbar { + background: #18242e; + border-color: #30424f; + box-shadow: 0 1px 3px rgba(0, 0, 0, 0.3); +} + +html[data-theme="dark"] .editor-loading-tool-groups { + background: #1a2630; + border-color: #30424f; +} + +html[data-theme="dark"] .editor-loading-tool-section { + background: linear-gradient(90deg, rgba(52, 72, 86, 0.34), rgba(31, 47, 59, 0.16) 44%, rgba(8, 15, 21, 0.14)); + border-color: #334652; +} + +html[data-theme="dark"] .editor-loading-viewport { + background-color: #101820; + background-image: + linear-gradient(rgba(102, 139, 158, 0.12) 1px, transparent 1px), + linear-gradient(90deg, rgba(102, 139, 158, 0.12) 1px, transparent 1px); +} + +html[data-theme="dark"] .editor-loading-viewport::after { + background: radial-gradient(ellipse, rgba(77, 126, 151, 0.12), transparent 68%); +} + +html[data-theme="dark"] .editor-loading-model span { + box-shadow: 0 10px 24px rgba(0, 0, 0, 0.24); +} + +html[data-theme="dark"] .editor-loading-viewport-controls { + background: rgba(24, 38, 48, 0.9); + border-color: #3a4d5b; + box-shadow: 0 4px 16px rgba(0, 0, 0, 0.34); +} + html[data-theme="dark"] .dashboard-topbar { color: #ffffff; background: #0e69f1; @@ -6481,6 +6691,66 @@ html[data-theme="dark"] .dashboard-version-row strong { color: #e1edf5; } +html[data-theme="dark"] .dashboard-version-row a { + color: #72aefc; +} + +html[data-theme="dark"] .dashboard-update-settings { + color: #9eb1c0; + border-color: #344856; + background: #111b23; +} + +html[data-theme="dark"] .dashboard-update-settings > div strong { + color: #e1edf5; +} + +html[data-theme="dark"] .dashboard-update-status.ready { + color: #71d5a5; +} + +html[data-theme="dark"] .dashboard-update-status.error { + color: #ff8e98; +} + +html[data-theme="dark"] .dashboard-check-update { + color: #d8e6f1; + border-color: #3a4e5d; + background: #1b2a35; +} + +html[data-theme="dark"] .dashboard-update-safety, +html[data-theme="dark"] .dashboard-update-note, +html[data-theme="dark"] .dashboard-update-message { + color: #c2d3df; + border-color: #3a5263; + background: #142733; +} + +html[data-theme="dark"] .dashboard-update-note { + border-color: #665a38; + background: #2c2819; +} + +html[data-theme="dark"] .dashboard-update-message { + border-color: #37624b; + background: #152b20; +} + +html[data-theme="dark"] .dashboard-update-safety code { + color: #8bc0ff; +} + +html[data-theme="dark"] .dashboard-update-key { + color: #c2d3df; +} + +html[data-theme="dark"] .dashboard-update-key input { + color: #e1edf5; + border-color: #3a4e5d; + background: #111b23; +} + html[data-theme="dark"] .dashboard-section-header span, html[data-theme="dark"] .project-card-meta, html[data-theme="dark"] .dashboard-import-notice, @@ -6940,11 +7210,6 @@ html[data-theme="dark"] .sketch-grid .axis { stroke: #6bcae3; } -html[data-theme="dark"] .sketch-grid-settings { - background: rgba(20, 32, 41, 0.94); - border-color: #3a4d5a; -} - html[data-theme="dark"] .sketch-command-button { color: #c3d3de; } @@ -7126,3 +7391,810 @@ html[data-theme="dark"] .cube-face:focus-visible { html[data-theme="dark"] .grid-settings { color: #a9bdca; } + +/* Challenge 1: Key Tag */ +.challenge-key-tag-page { + position: relative; + width: min(100%, 980px); + margin-inline: auto; + padding-inline-start: 54px; +} + +.challenge-key-tag-rail { + position: absolute; + inset: 0 auto 0 11px; + display: grid; + width: 28px; + grid-auto-rows: 1fr; + place-items: center; +} + +.challenge-card-stack { + display: grid; + min-width: 0; + gap: 22px; +} + +.challenge-key-tag-rail::before { + position: absolute; + inset: 0 auto 0 13px; + width: 2px; + background: #dbe5eb; + content: ""; +} + +.challenge-key-tag-rail span { + position: relative; + z-index: 1; + width: 34px; + height: 34px; + background: #fff; + border: 3px solid #0e69f1; + border-radius: 999px; + box-shadow: 0 0 0 6px #f4f7f9; +} + +.challenge-key-tag-rail span::after { + position: absolute; + inset: 7px; + background: #0e69f1; + border-radius: inherit; + content: ""; +} + +.challenge-key-tag-card { + display: grid; + min-width: 0; + min-height: 294px; + grid-template-columns: minmax(210px, 0.85fr) minmax(280px, 1.6fr); + overflow: hidden; + background: #fff; + border: 2px solid #0e69f1; + border-radius: 16px; + box-shadow: 0 7px 22px rgba(35, 74, 122, 0.07); +} + +.challenge-key-tag-preview { + min-width: 0; + align-self: center; + margin: 14px 10px 14px 14px; + overflow: hidden; + aspect-ratio: 16 / 9; + background: #f3f6f8; + border-radius: 12px; +} + +.challenge-key-tag-photo { + display: block; + width: 100%; + height: 100%; + object-fit: cover; +} + +.challenge-key-tag-photo-dark { + display: none; +} + +.challenge-key-tag-content { + display: flex; + min-width: 0; + flex-direction: column; + justify-content: center; + padding: clamp(20px, 3vw, 28px); +} + +.challenge-key-tag-title-row { + display: flex; + align-items: baseline; + gap: 12px; +} + +.challenge-key-tag-title-row > span { + color: #0e69f1; + font-size: 20px; + font-weight: 850; +} + +.challenge-key-tag-title-row h2 { + margin: 0; + color: #223b50; + font-size: clamp(23px, 3vw, 28px); + letter-spacing: -0.02em; +} + +.challenge-key-tag-content > p { + max-width: 520px; + margin: 10px 0 16px; + color: #6c8091; + font-size: 14px; + line-height: 1.55; +} + +.challenge-key-tag-skills { + display: flex; + flex-wrap: wrap; + gap: 8px; + margin-bottom: 18px; +} + +.challenge-key-tag-skills span { + display: inline-flex; + min-height: 34px; + align-items: center; + gap: 7px; + padding: 0 10px; + color: #40586b; + background: #f7f9fb; + border: 1px solid #dce5eb; + border-radius: 8px; + font-size: 11px; + font-weight: 750; + white-space: nowrap; +} + +.challenge-key-tag-skills svg { + flex: 0 0 auto; + color: #0e69f1; +} + +.challenge-key-tag-start { + width: min(190px, 100%); + min-height: 42px; + color: #fff; + background: #0e69f1; + border: 1px solid #0e69f1; + border-radius: 8px; + box-shadow: 0 3px 8px rgba(14, 105, 241, 0.18); + cursor: pointer; + font-size: 13px; + font-weight: 850; +} + +.challenge-key-tag-start:hover { + background: #075bd7; +} + +.challenge-key-tag-start:focus-visible { + outline: 3px solid #ffce47; + outline-offset: 3px; +} + +/* Full-height challenge tutorial */ +.key-tag-tutorial-panel { + position: absolute; + inset: 0 0 0 auto; + z-index: 12; + display: grid; + width: clamp(320px, 30vw, 390px); + min-width: 0; + grid-template-rows: auto minmax(0, 1fr) auto; + color: #263f57; + background: #f8fafb; + border-left: 1px solid #ccd9e3; + box-shadow: -10px 0 28px rgba(25, 48, 68, 0.14); +} + +.workplane-stage.key-tag-tutorial-active .shape-inspector { + right: clamp(320px, 30vw, 390px); +} + +.workplane-stage.key-tag-tutorial-active .grid-settings { + right: calc(clamp(320px, 30vw, 390px) + 12px); +} + +.key-tag-tutorial-panel.key-tag-tutorial-panel-collapsed { + inset: 0 0 0 auto; + width: 54px; + place-items: center; + grid-template-rows: auto 1fr auto; + padding: 10px 0 14px; +} + +.workplane-stage.key-tag-tutorial-collapsed .shape-inspector { + right: 54px; +} + +.workplane-stage.key-tag-tutorial-collapsed .grid-settings { + right: 66px; +} + +.key-tag-tutorial-expand, +.key-tag-tutorial-collapse { + display: grid; + width: 34px; + height: 34px; + place-items: center; + color: #4b6477; + background: #edf3f7; + border: 1px solid #d3dee6; + border-radius: 8px; + cursor: pointer; +} + +.key-tag-tutorial-expand:hover, +.key-tag-tutorial-collapse:hover { + color: #0e69f1; + background: #e3edff; + border-color: #8bbaf7; +} + +.key-tag-tutorial-expand:focus-visible, +.key-tag-tutorial-collapse:focus-visible, +.key-tag-tutorial-footer button:focus-visible { + outline: 3px solid #ffce47; + outline-offset: 2px; +} + +.key-tag-tutorial-collapsed-label { + color: #314c63; + font-size: 12px; + font-weight: 850; + letter-spacing: 0.04em; + text-transform: uppercase; + writing-mode: vertical-rl; + transform: rotate(180deg); +} + +.key-tag-tutorial-collapsed-count { + color: #6b8192; + font-size: 11px; + font-weight: 800; +} + +.key-tag-tutorial-header { + display: flex; + min-width: 0; + align-items: center; + justify-content: space-between; + gap: 12px; + padding: 15px 16px; + background: #fff; + border-bottom: 1px solid #d9e3ea; +} + +.key-tag-tutorial-header > div:first-child { + display: grid; + min-width: 0; + gap: 2px; +} + +.key-tag-tutorial-header > div:first-child span, +.key-tag-tutorial-eyebrow { + color: #0e69f1; + font-size: 10px; + font-weight: 900; + letter-spacing: 0.08em; + text-transform: uppercase; +} + +.key-tag-tutorial-header strong { + overflow: hidden; + color: #243e55; + font-size: 17px; + text-overflow: ellipsis; + white-space: nowrap; +} + +.key-tag-tutorial-header-actions { + display: flex; + flex: 0 0 auto; + align-items: center; + gap: 8px; +} + +.key-tag-tutorial-count { + color: #60788b; + font-size: 12px; + font-weight: 800; +} + +.key-tag-tutorial-body { + min-height: 0; + overflow: auto; + overscroll-behavior: contain; + padding: clamp(16px, 2vw, 22px); +} + +.key-tag-tutorial-copy h2 { + margin: 7px 0 8px; + color: #223b50; + font-size: clamp(21px, 2.4vw, 26px); + line-height: 1.15; + letter-spacing: -0.02em; +} + +.key-tag-tutorial-copy p { + margin: 0; + color: #607789; + font-size: 13px; + line-height: 1.55; +} + +.key-tag-snap-row, +.key-tag-tutorial-dimension-heading { + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; +} + +.key-tag-snap-row { + margin-top: 16px; + padding: 11px 12px; + color: #486176; + background: #fff; + border: 1px solid #d7e2e9; + border-radius: 9px; + font-size: 12px; +} + +.key-tag-snap-row strong, +.key-tag-tutorial-dimension-heading strong { + color: #203d56; +} + +.nameplate-tutorial-callout { + margin-top: 14px; + padding: 10px 12px; + color: #31536d; + background: #eaf3ff; + border: 1px solid #bdd7fa; + border-radius: 9px; + font-size: 12px; + font-weight: 750; + line-height: 1.45; +} + +.nameplate-fillet-button-target { + position: relative; + z-index: 91; + outline: 4px solid #ffbf2f !important; + outline-offset: 3px; + box-shadow: 0 0 0 9px rgba(255, 191, 47, 0.28), 0 0 24px rgba(255, 174, 0, 0.72) !important; + animation: nameplate-fillet-target-pulse 1.15s ease-in-out infinite alternate; +} + +.nameplate-fillet-coachmark { + position: fixed; + z-index: 100; + display: grid; + min-width: 112px; + place-items: center; + gap: 1px; + padding: 8px 12px 9px; + color: #342300; + background: #ffd45c; + border: 2px solid #9f6a00; + border-radius: 10px; + box-shadow: 0 8px 24px rgba(91, 57, 0, 0.3); + pointer-events: none; + transform: translate(-50%, 0); +} + +.nameplate-fillet-coachmark svg { + position: absolute; + bottom: calc(100% + 3px); + left: 50%; + color: #ffb000; + filter: drop-shadow(0 1px 0 #7e5300); + transform: translateX(-50%); +} + +.nameplate-fillet-coachmark strong { + font-size: 13px; + font-weight: 900; + letter-spacing: 0.01em; + white-space: nowrap; +} + +@keyframes nameplate-fillet-target-pulse { + from { + outline-offset: 2px; + } + + to { + outline-offset: 6px; + } +} + +.key-tag-tutorial-dimensions { + display: grid; + gap: 12px; + margin-top: 16px; +} + +.key-tag-tutorial-dimension-control { + display: grid; + gap: 8px; +} + +.key-tag-tutorial-dimension-heading { + color: #607789; + font-size: 11px; +} + +.key-tag-tutorial-slider { + position: relative; + height: 6px; + background: #d9e4eb; + border-radius: 999px; +} + +.key-tag-tutorial-slider > span { + position: absolute; + inset: 0 auto 0 0; + min-width: 5px; + background: #0e69f1; + border-radius: inherit; +} + +.key-tag-tutorial-slider > i { + position: absolute; + top: 50%; + width: 13px; + height: 13px; + background: #fff; + border: 3px solid #0e69f1; + border-radius: 50%; + transform: translate(-50%, -50%); +} + +.key-tag-tutorial-image-box { + display: grid; + width: 100%; + margin-top: 18px; + overflow: hidden; + place-items: center; + aspect-ratio: 16 / 10; + background: #eaf0f4; + border: 1px solid #d4dfe7; + border-radius: 12px; +} + +.key-tag-tutorial-capture { + display: block; + width: 100%; + height: 100%; + object-fit: contain; +} + +.key-tag-tutorial-footer { + display: grid; + grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); + gap: 10px; + padding: 13px 16px; + background: #fff; + border-top: 1px solid #d9e3ea; +} + +.key-tag-tutorial-footer button { + display: inline-flex; + min-width: 0; + min-height: 40px; + align-items: center; + justify-content: center; + gap: 5px; + border-radius: 8px; + cursor: pointer; + font-size: 12px; + font-weight: 850; +} + +.key-tag-tutorial-footer .secondary { + color: #415a6d; + background: #fff; + border: 1px solid #d5e0e7; +} + +.key-tag-tutorial-footer .secondary:disabled { + cursor: default; + opacity: 0.45; +} + +.key-tag-tutorial-footer .primary { + color: #fff; + background: #0e69f1; + border: 1px solid #0e69f1; +} + +/* Explicit grid areas keep Create beside the brand instead of on a third row. */ +@media (max-width: 860px) { + .dashboard-topbar { + grid-template-areas: + "brand create" + "search search"; + grid-template-columns: minmax(0, 1fr) auto; + } + + .dashboard-brand { + grid-area: brand; + } + + .dashboard-search { + grid-area: search; + } + + .dashboard-primary { + grid-area: create; + } + + .challenge-key-tag-page { + padding-inline-start: 42px; + } + + .challenge-key-tag-rail { + left: 4px; + } + + .key-tag-tutorial-panel { + width: clamp(300px, 42vw, 360px); + } + + .workplane-stage.key-tag-tutorial-active .shape-inspector { + right: clamp(300px, 42vw, 360px); + } + + .workplane-stage.key-tag-tutorial-active .grid-settings { + right: calc(clamp(300px, 42vw, 360px) + 12px); + } + + .workplane-stage.key-tag-tutorial-collapsed .shape-inspector { + right: 54px; + } + + .workplane-stage.key-tag-tutorial-collapsed .grid-settings { + right: 66px; + } +} + +@media (max-width: 720px) { + .challenge-key-tag-page { + padding-inline-start: 0; + } + + .challenge-key-tag-rail { + display: none; + } + + .challenge-key-tag-card { + min-height: 0; + grid-template-columns: minmax(0, 1fr); + } + + .challenge-key-tag-preview { + height: auto; + margin: 12px 12px 0; + } + + .challenge-key-tag-content { + padding: 18px; + } + + .challenge-key-tag-skills { + gap: 6px; + margin-bottom: 14px; + } + + .challenge-key-tag-skills span { + min-height: 31px; + padding-inline: 8px; + font-size: 10px; + } +} + +@media (max-width: 680px) { + .key-tag-tutorial-panel { + inset: auto 0 0; + width: 100%; + height: min(54vh, 480px); + border-top: 1px solid #ccd9e3; + border-left: 0; + box-shadow: 0 -10px 28px rgba(25, 48, 68, 0.18); + } + + .key-tag-tutorial-panel.key-tag-tutorial-panel-collapsed { + inset: auto 10px 10px auto; + width: 54px; + height: min(210px, calc(100vh - 90px)); + border: 1px solid #ccd9e3; + border-radius: 12px; + box-shadow: 0 7px 22px rgba(25, 48, 68, 0.2); + } + + .workplane-stage.key-tag-tutorial-active .shape-inspector, + .workplane-stage.key-tag-tutorial-collapsed .shape-inspector { + right: 0; + } + + .workplane-stage.key-tag-tutorial-active .grid-settings, + .workplane-stage.key-tag-tutorial-collapsed .grid-settings { + right: 12px; + } + + .key-tag-tutorial-header, + .key-tag-tutorial-footer { + padding: 10px 12px; + } + + .key-tag-tutorial-body { + display: grid; + grid-template-columns: minmax(0, 1fr) minmax(150px, 0.8fr); + gap: 14px; + align-items: start; + padding: 13px 14px; + } + + .key-tag-tutorial-image-box { + margin-top: 0; + } +} + +@media (max-width: 520px) { + .dashboard-topbar { + gap: 7px 9px; + padding: 7px 9px; + } + + .dashboard-brand img { + width: 38px; + height: 38px; + } + + .dashboard-brand span { + font-size: 18px; + } + + .dashboard-primary { + height: 38px; + padding-inline: 12px; + } + + .dashboard-search { + height: 38px; + } + + .challenge-key-tag-card { + border-radius: 12px; + } + + .challenge-key-tag-title-row > span { + font-size: 17px; + } + + .challenge-key-tag-content > p { + margin-block: 8px 13px; + font-size: 13px; + } + + .challenge-key-tag-start { + width: 100%; + } + + .key-tag-tutorial-panel { + height: min(62vh, 520px); + } + + .key-tag-tutorial-body { + display: block; + } + + .key-tag-tutorial-image-box { + margin-top: 13px; + } +} + +@media (max-width: 380px) { + .dashboard-brand span, + .dashboard-primary span { + display: none; + } + + .dashboard-primary { + width: 38px; + padding: 0; + } + + .challenge-key-tag-skills span { + flex: 1 1 calc(50% - 6px); + justify-content: center; + } +} + +html[data-theme="dark"] .challenge-key-tag-card, +html[data-theme="dark"] .key-tag-tutorial-panel { + color: #d8e6ef; + background: #17232d; + border-color: #3c79c8; +} + +html[data-theme="dark"] .challenge-key-tag-rail::before { + background: #344a59; +} + +html[data-theme="dark"] .challenge-key-tag-rail span { + background: #17232d; + box-shadow: 0 0 0 6px #101a22; +} + +html[data-theme="dark"] .challenge-key-tag-title-row h2, +html[data-theme="dark"] .key-tag-tutorial-header strong, +html[data-theme="dark"] .key-tag-tutorial-copy h2, +html[data-theme="dark"] .key-tag-snap-row strong, +html[data-theme="dark"] .key-tag-tutorial-dimension-heading strong, +html[data-theme="dark"] .key-tag-tutorial-collapsed-label { + color: #e2edf5; +} + +html[data-theme="dark"] .challenge-key-tag-content > p, +html[data-theme="dark"] .key-tag-tutorial-copy p, +html[data-theme="dark"] .key-tag-tutorial-dimension-heading, +html[data-theme="dark"] .key-tag-tutorial-count, +html[data-theme="dark"] .key-tag-tutorial-collapsed-count { + color: #9fb1bf; +} + +html[data-theme="dark"] .challenge-key-tag-preview, +html[data-theme="dark"] .key-tag-tutorial-image-box { + background: #20313c; + border-color: #354a58; +} + +html[data-theme="dark"] .challenge-key-tag-photo-light { + display: none; +} + +html[data-theme="dark"] .challenge-key-tag-photo-dark { + display: block; +} + +html[data-theme="dark"] .challenge-key-tag-skills span, +html[data-theme="dark"] .key-tag-snap-row { + color: #bed0dc; + background: #22333f; + border-color: #354a58; +} + +html[data-theme="dark"] .key-tag-tutorial-header, +html[data-theme="dark"] .key-tag-tutorial-footer { + background: #111d25; + border-color: #344854; +} + +html[data-theme="dark"] .key-tag-tutorial-expand, +html[data-theme="dark"] .key-tag-tutorial-collapse { + color: #b8cbd7; + background: #22333f; + border-color: #3b5160; +} + +html[data-theme="dark"] .key-tag-tutorial-slider { + background: #344854; +} + +html[data-theme="dark"] .key-tag-tutorial-slider > i { + background: #17232d; +} + +html[data-theme="dark"] .key-tag-tutorial-footer .secondary { + color: #c2d2dc; + background: #22333f; + border-color: #3b5160; +} + +html[data-theme="dark"] .nameplate-tutorial-callout { + color: #bed5e4; + background: #193044; + border-color: #315677; +} + +html[data-theme="dark"] .nameplate-fillet-coachmark { + color: #251700; + background: #ffc83d; + border-color: #f5a800; +} + +@media (prefers-reduced-motion: reduce) { + .nameplate-fillet-button-target { + animation: none; + } +} diff --git a/apps/web/src/app/page.tsx b/apps/web/src/app/page.tsx index 4482dc2..1c2bf69 100644 --- a/apps/web/src/app/page.tsx +++ b/apps/web/src/app/page.tsx @@ -1,9 +1,12 @@ "use client"; -import { Clock3, EllipsisVertical, FileUp, FolderKanban, Grid3X3, HomeIcon, List, Pencil, Plus, RefreshCw, Search, Settings, SlidersHorizontal, Trash2, X } from "lucide-react"; +import { Clock3, EllipsisVertical, FileUp, FolderKanban, Grid3X3, HomeIcon, List, Palette, Pencil, Plus, RefreshCw, Search, Settings, SlidersHorizontal, Trash2, X } from "lucide-react"; import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { SketchForgeEditor, importedShapeFromStl, importedShapeFromSvg } from "@/components/SketchForgeEditor"; +import ChallengesDashboard from "@/components/official/ChallengesDashboard"; import { applyAppTheme, readStoredAppTheme, resolveAppTheme, storeAppTheme, type AppThemePreference, type ResolvedAppTheme } from "@/lib/appTheme"; +import type { AppUpdateStatus } from "@/lib/appUpdates"; +import { isChallengeTutorialId, type ChallengeTutorialId } from "@/lib/challenges"; import { hydrateEditorHistoryState, type EditorHistoryEntry } from "@/lib/editorHistory"; import { createLocalId } from "@/lib/localIds"; import { @@ -21,7 +24,7 @@ import type { GridSize, ProjectAsset, WorkplaneShape, WorkplaneWorkspaceSettings type AppView = "dashboard" | "editor"; type ViewMode = "grid" | "list"; -type DashboardSection = "home" | "shared" | "challenges"; +type DashboardSection = "home" | "shared" | "challenges" | "customization"; type DownloadMode = "browser" | "folder"; type DashboardProject = { @@ -107,8 +110,11 @@ const PROJECT_SHAPES_STORE_NAME = "projectShapes"; const PROJECT_SHAPE_RESOURCES_STORE_NAME = "projectShapeResources"; const DOWNLOAD_MODE_STORAGE_KEY = "sketchForge.downloadMode"; const DOWNLOAD_FOLDER_STORAGE_KEY = "sketchForge.downloadFolder"; +const ACTIVE_CHALLENGE_TUTORIAL_STORAGE_KEY = "sketchForge.activeChallengeTutorial"; +const DISMISSED_UPDATE_VERSION_STORAGE_KEY = "sketchForge.dismissedUpdateVersion"; const PROJECT_ACCENTS: DashboardProject["accent"][] = ["cyan", "green", "gold", "red"]; const STATIC_EXPORT_BUILD = process.env.NEXT_PUBLIC_STATIC_EXPORT === "true"; +const SOURCE_CODE_URL = process.env.NEXT_PUBLIC_SOURCE_CODE_URL?.trim() || "https://github.com/Formsmith746/SketchForge-3D"; const EDITOR_SKELETON_MIN_DURATION_MS = 320; const knownProjectResourceKeys = new Map>(); @@ -507,6 +513,7 @@ export default function Home() { const [sharedProjects, setSharedProjects] = useState([]); const [sharedProjectsEnabled, setSharedProjectsEnabled] = useState(false); const [sharedProjectsLoading, setSharedProjectsLoading] = useState(false); + const [activeChallengeTutorial, setActiveChallengeTutorial] = useState(null); const [projectShapesById, setProjectShapesById] = useState>({}); const projectsJsonRef = useRef(""); const dashboardImportInputRef = useRef(null); @@ -562,6 +569,14 @@ export default function Home() { const requestedProjectId = params.get("project"); if (requestedProjectId && storedProjects.some((project) => project.id === requestedProjectId)) { setActiveProjectId(requestedProjectId); + try { + const storedChallenge = JSON.parse(window.localStorage.getItem(ACTIVE_CHALLENGE_TUTORIAL_STORAGE_KEY) ?? "null") as { projectId?: string; tutorial?: ChallengeTutorialId } | null; + if (storedChallenge?.projectId === requestedProjectId && isChallengeTutorialId(storedChallenge.tutorial)) { + setActiveChallengeTutorial(storedChallenge.tutorial); + } + } catch { + window.localStorage.removeItem(ACTIVE_CHALLENGE_TUTORIAL_STORAGE_KEY); + } } startEditorTransition(); setEditorStarted(true); @@ -704,7 +719,7 @@ export default function Home() { return sortMode === "name" ? [...filtered].sort((a, b) => a.name.localeCompare(b.name)) : [...filtered].sort((a, b) => b.updatedAt - a.updatedAt); }, [query, sharedProjects, sortMode]); - const openEditor = (projectId: string | null, options: { allowMissingFromStorage?: boolean } = {}) => { + const openEditor = (projectId: string | null, options: { allowMissingFromStorage?: boolean; challengeTutorial?: ChallengeTutorialId | null } = {}) => { if (projectId && typeof window !== "undefined" && !options.allowMissingFromStorage) { const storedProjects = readProjects(); const storedProject = storedProjects.find((project) => project.id === projectId); @@ -720,6 +735,25 @@ export default function Home() { setProjects((current) => current.map((project) => (project.id === projectId ? { ...project, updatedAt: Date.now() } : project))); } startEditorTransition(); + let nextChallengeTutorial = options.challengeTutorial ?? null; + if (typeof window !== "undefined" && projectId) { + if (nextChallengeTutorial) { + window.localStorage.setItem( + ACTIVE_CHALLENGE_TUTORIAL_STORAGE_KEY, + JSON.stringify({ projectId, tutorial: nextChallengeTutorial }), + ); + } else { + try { + const storedChallenge = JSON.parse(window.localStorage.getItem(ACTIVE_CHALLENGE_TUTORIAL_STORAGE_KEY) ?? "null") as { projectId?: string; tutorial?: ChallengeTutorialId } | null; + if (storedChallenge?.projectId === projectId && isChallengeTutorialId(storedChallenge.tutorial)) { + nextChallengeTutorial = storedChallenge.tutorial; + } + } catch { + window.localStorage.removeItem(ACTIVE_CHALLENGE_TUTORIAL_STORAGE_KEY); + } + } + } + setActiveChallengeTutorial(nextChallengeTutorial); setActiveProjectId(projectId); setEditorStarted(true); setView("editor"); @@ -884,7 +918,7 @@ export default function Home() { }); }, []); - const createAndOpenProject = (name?: string) => { + const createAndOpenProject = (name?: string, challengeTutorial: ChallengeTutorialId | null = null) => { const project = newProject(name ?? `Untitled design ${projects.length + 1}`, projects.length); setProjectShapesById((current) => ({ ...current, @@ -898,7 +932,7 @@ export default function Home() { setDashboardNotice("Could not prepare project shape storage"); }); setProjects((current) => [project, ...current]); - openEditor(project.id, { allowMissingFromStorage: true }); + openEditor(project.id, { allowMissingFromStorage: true, challengeTutorial }); }; const openSkfProjectFromFile = useCallback(async (file: File, sharedProject?: SharedProject) => { @@ -1072,6 +1106,7 @@ export default function Home() { setProjects((current) => current.map((project) => (project.id === activeProjectId ? { ...project, updatedAt: Date.now() } : project))); } setDashboardSection("home"); + setActiveChallengeTutorial(null); setEditorLoading(false); setView("dashboard"); if (typeof window !== "undefined") { @@ -1158,6 +1193,7 @@ export default function Home() { viewMode={viewMode} onCloseSettings={() => setSettingsOpen(false)} onCreate={() => createAndOpenProject()} + onStartChallenge={(challenge) => createAndOpenProject(challenge === "nameplate" ? "Personalized Nameplate" : "Key Tag", challenge)} onDeleteProject={deleteProject} onDownloadFolderChange={setDownloadFolder} onDownloadModeChange={setDownloadMode} @@ -1166,6 +1202,10 @@ export default function Home() { setDashboardSection("challenges"); setDashboardNotice(""); }} + onCustomization={() => { + setDashboardSection("customization"); + setDashboardNotice(""); + }} onDashboardHome={() => setDashboardSection("home")} onOpenSharedProject={(project) => void openSharedProject(project)} onOpenProject={openEditor} @@ -1206,6 +1246,11 @@ export default function Home() { projectModifiedAt={activeProject?.updatedAt} projectRevision={activeProjectShapeEntry?.revision ?? activeProject?.revision ?? 0} sharedProjectsEnabled={sharedProjectsEnabled} + challengeTutorial={activeChallengeTutorial} + onChallengeTutorialFinish={() => { + setActiveChallengeTutorial(null); + window.localStorage.removeItem(ACTIVE_CHALLENGE_TUTORIAL_STORAGE_KEY); + }} themePreference={themePreference} resolvedTheme={resolvedTheme} onThemePreferenceChange={setThemePreference} @@ -1302,11 +1347,13 @@ function Dashboard({ viewMode, onCloseSettings, onCreate, + onStartChallenge, onDeleteProject, onDownloadFolderChange, onDownloadModeChange, onImportFile, onChallenges, + onCustomization, onDashboardHome, onOpenSharedProject, onOpenProject, @@ -1334,11 +1381,13 @@ function Dashboard({ viewMode: ViewMode; onCloseSettings: () => void; onCreate: () => void; + onStartChallenge: (challenge: ChallengeTutorialId) => void; onDeleteProject: (projectId: string) => void; onDownloadFolderChange: (value: string) => void; onDownloadModeChange: (value: DownloadMode) => void; onImportFile: () => void; onChallenges: () => void; + onCustomization: () => void; onDashboardHome: () => void; onOpenSharedProject: (project: SharedProject) => void; onOpenProject: (projectId: string) => void; @@ -1355,6 +1404,13 @@ function Dashboard({ const [projectPendingDeleteId, setProjectPendingDeleteId] = useState(null); const [projectPendingRenameId, setProjectPendingRenameId] = useState(null); const [projectNameDraft, setProjectNameDraft] = useState(""); + const [updateStatus, setUpdateStatus] = useState(null); + const [updateChecking, setUpdateChecking] = useState(false); + const [updatePromptOpen, setUpdatePromptOpen] = useState(false); + const [updateKey, setUpdateKey] = useState(""); + const [updateStarting, setUpdateStarting] = useState(false); + const [updateMessage, setUpdateMessage] = useState(""); + const updateCheckedRef = useRef(false); const projectPendingDelete = projects.find((project) => project.id === projectPendingDeleteId) ?? null; const projectPendingRename = projects.find((project) => project.id === projectPendingRenameId) ?? null; @@ -1387,6 +1443,79 @@ function Dashboard({ closeProjectRename(); }; + const checkForUpdates = useCallback(async (force: boolean, alwaysPrompt: boolean) => { + if (staticExportBuild) return; + setUpdateChecking(true); + setUpdateMessage(""); + try { + const response = await fetch(`/api/app-update${force ? "?force=1" : ""}`, { cache: "no-store" }); + const payload = await response.json() as AppUpdateStatus & { error?: string }; + if (!response.ok) throw new Error(payload.error || "Could not check for updates"); + setUpdateStatus(payload); + if (payload.updateAvailable && payload.latestVersion) { + const dismissedVersion = window.localStorage.getItem(DISMISSED_UPDATE_VERSION_STORAGE_KEY); + if (alwaysPrompt || dismissedVersion !== payload.latestVersion) { + onCloseSettings(); + setUpdatePromptOpen(true); + } + } else if (alwaysPrompt && !payload.checkError) { + setUpdateMessage("SketchForge is up to date."); + } + } catch (error) { + setUpdateMessage(error instanceof Error ? error.message : "Could not check for updates"); + } finally { + setUpdateChecking(false); + } + }, [onCloseSettings, staticExportBuild]); + + useEffect(() => { + if (staticExportBuild || updateCheckedRef.current) return; + updateCheckedRef.current = true; + void checkForUpdates(false, false); + }, [checkForUpdates, staticExportBuild]); + + const dismissUpdate = () => { + if (updateStatus?.latestVersion) { + window.localStorage.setItem(DISMISSED_UPDATE_VERSION_STORAGE_KEY, updateStatus.latestVersion); + } + setUpdatePromptOpen(false); + setUpdateKey(""); + setUpdateMessage(""); + }; + + const requestUpdate = async () => { + if (!updateStatus?.updateAvailable) return; + if (!updateStatus.installationReady) { + window.open(updateStatus.updateUrl, "_blank", "noopener,noreferrer"); + dismissUpdate(); + return; + } + if (updateStatus.requiresUpdateKey && !updateKey.trim()) { + setUpdateMessage("Enter the server update key to continue."); + return; + } + + setUpdateStarting(true); + setUpdateMessage(""); + try { + const response = await fetch("/api/app-update", { + method: "POST", + headers: { "x-sketchforge-update-key": updateKey.trim() }, + }); + const payload = await response.json() as { accepted?: boolean; error?: string; updateUrl?: string }; + if (!response.ok || !payload.accepted) throw new Error(payload.error || "Could not start the update"); + if (updateStatus.latestVersion) { + window.localStorage.setItem(DISMISSED_UPDATE_VERSION_STORAGE_KEY, updateStatus.latestVersion); + } + setUpdateMessage("Update started. The server may briefly go offline; reopen this page after it restarts."); + setUpdateKey(""); + } catch (error) { + setUpdateMessage(error instanceof Error ? error.message : "Could not start the update"); + } finally { + setUpdateStarting(false); + } + }; + return (
@@ -1421,15 +1550,23 @@ function Dashboard({ Challenges + + +
+
- -
+
{dashboardSection === "challenges" ? ( + + ) : dashboardSection === "customization" ? (
Coming soon
@@ -1634,6 +1771,49 @@ function Dashboard({
) : null} + {updatePromptOpen && updateStatus?.updateAvailable && updateStatus.latestVersion ? ( +
+
+
+ SketchForge {updateStatus.latestVersion} is available + +
+
+

Do you want to update from version {updateStatus.currentVersion}?

+
+ Your projects are kept. Private projects stay in this browser, and Docker shared projects remain in the persistent /data/projects volume. +
+ {!updateStatus.installationReady ? ( +
One-click installation is not configured on this server. Continue to the safe update guide.
+ ) : null} + {updateStatus.requiresUpdateKey ? ( + + ) : null} + {updateMessage ?
{updateMessage}
: null} +
+
+ + +
+
+
+ ) : null} + {settingsOpen ? (
@@ -1665,6 +1845,46 @@ function Dashboard({ SketchForge version {SKF_CREATED_WITH_VERSION} +
+
+ Software updates + Updates are checked automatically but are never installed without your approval. +
+ {staticExportBuild ? ( + Managed by the website owner + ) : updateStatus?.checkError ? ( + {updateStatus.checkError} + ) : updateStatus?.updateAvailable && updateStatus.latestVersion ? ( + + ) : updateStatus ? ( + Up to date + ) : null} + {!staticExportBuild ? ( + + ) : null} + {updateMessage && settingsOpen ? {updateMessage} : null} +
+
+ License + AGPLv3 +
+
+ Corresponding source + View source +
) : null}
diff --git a/apps/web/src/components/SketchForgeEditor.tsx b/apps/web/src/components/SketchForgeEditor.tsx index 5cfe602..5360abe 100644 --- a/apps/web/src/components/SketchForgeEditor.tsx +++ b/apps/web/src/components/SketchForgeEditor.tsx @@ -16,6 +16,7 @@ import gentilisBoldFontJson from "three/examples/fonts/gentilis_bold.typeface.js import helvetikerBoldFontJson from "three/examples/fonts/helvetiker_bold.typeface.json"; import optimerBoldFontJson from "three/examples/fonts/optimer_bold.typeface.json"; import type { AppThemePreference, ResolvedAppTheme } from "@/lib/appTheme"; +import type { ChallengeTutorialId } from "@/lib/challenges"; import { manifoldModuleSource } from "@/generated/manifoldModuleSource"; import { manifoldWasmBase64 } from "@/generated/manifoldWasmBase64"; import { sphereTessellation } from "@/lib/sphereTessellation"; @@ -84,12 +85,14 @@ import { appendEditorHistorySnapshot, boundedEditorHistoryState, editorHistoryEn import { snapShapeFootprintToVisibleGrid, visibleGridStep } from "@/lib/gridSnap"; import { createLocalId } from "@/lib/localIds"; import { projectExportFileName } from "@/lib/exportNames"; +import { exportMeshesToObj } from "@/lib/objExport"; import { attachProjectAsset, dedupeProjectAssets, projectAssetFromBytes, sourceFormatForFileName } from "@/lib/projectAssets"; import { findSketchOutlineIntersection } from "@/lib/sketchProfileValidation"; import { buildSketchRevolveMesh, DEFAULT_SKETCH_REVOLVE_SETTINGS, normalizeSketchRevolveSettings, type SketchRevolveMesh } from "@/lib/sketchRevolve"; import { exportSkfProject, SKF_MEDIA_TYPE } from "@/lib/skfProject"; import { makeShapeFromAsset, sceneShape, toolbarShapeAssets, type ToolbarShapeAsset } from "@/lib/shapeCatalog"; import { importedShapeFromStl, importExtensionSupported } from "@/lib/stlImport"; +import { exportMeshesToStl } from "@/lib/stlExport"; import { importedShapeFromSvg, invalidSvgMeshReason } from "@/lib/svgImport"; import { toSvgProjection, type SvgProjectionLayer } from "@/lib/svgExport"; import { normalizeSnapGrid, normalizeWorkspaceSettings, workplaneSettingsFingerprint } from "@/lib/workplaneSettings"; @@ -113,6 +116,7 @@ import { type SketchForgeMcpViewFace, } from "@/lib/sketchforgeMcpProtocol"; import type { CadModifierComponentMesh, CadModifierDisplayEdge, CadModifierEdge, CadModifierKind, CadModifierMeshPart, CadModifierPrimitivePart, CadModifierQuality, CadModifierWorkerRequest, CadModifierWorkerResponse } from "@/lib/cadModifierTypes"; +import type { SketchCadBuildResponse } from "@/lib/sketchCadTypes"; import type { AlignAxis, AlignHandleStatus, AlignTarget, GridSize, ProjectAsset, ShapeAsset, SketchImage, SketchOperation, SketchPoint, SketchProfile, SketchRevolveSettings, SketchSegment, WorkplaneShape, WorkplaneWorkspaceSettings } from "@/types/sketchforge"; export { importedShapeFromStl, importedShapeFromSvg }; @@ -529,6 +533,76 @@ async function shapeFromSketchProfile(profile: SketchProfile, height: number, ex } satisfies WorkplaneShape); } +let sketchCadWorker: Worker | null = null; +let sketchCadRequestId = 0; +const sketchCadPending = new Map void; + reject: (error: Error) => void; + timer: number; +}>(); + +function ensureSketchCadWorker() { + if (sketchCadWorker) return sketchCadWorker; + const worker = new Worker(new URL("../workers/sketchCad.worker.ts", import.meta.url), { type: "module" }); + worker.onmessage = (event: MessageEvent) => { + const pending = sketchCadPending.get(event.data.requestId); + if (!pending) return; + window.clearTimeout(pending.timer); + sketchCadPending.delete(event.data.requestId); + pending.resolve(event.data); + }; + worker.onerror = () => { + sketchCadPending.forEach((pending) => { + window.clearTimeout(pending.timer); + pending.reject(new Error("The OpenCascade sketch worker failed to start")); + }); + sketchCadPending.clear(); + worker.terminate(); + sketchCadWorker = null; + }; + sketchCadWorker = worker; + return worker; +} + +async function cadShapeFromSketchProfile(profile: SketchProfile, height: number, existing?: WorkplaneShape | null) { + const safeHeight = Math.max(MIN_SHAPE_DIMENSION, height); + const worker = ensureSketchCadWorker(); + const requestId = ++sketchCadRequestId; + const response = await new Promise((resolve, reject) => { + const timer = window.setTimeout(() => { + sketchCadPending.delete(requestId); + reject(new Error("OpenCascade timed out while building the sketch")); + }, 30_000); + sketchCadPending.set(requestId, { resolve, reject, timer }); + worker.postMessage({ type: "build", requestId, profile: cloneSketchProfile(profile), height: safeHeight }); + }); + if (response.type === "error") throw new Error(response.message); + const source = canonicalizeShape({ + ...(existing ?? { + id: createLocalId("sketch-extrusion"), + name: "Sketch extrusion", + kind: "mesh" as const, + color: "#d41721", + x: 0, + z: 0, + size: 1, + width: 1, + depth: 1, + height: safeHeight, + rotation: 0, + }), + sketchProfile: cloneSketchProfile(profile), + sketchOperation: "extrude", + edgeTreatments: undefined, + edgeTreatmentHistory: undefined, + cadDisplayEdges: undefined, + cadDisplayEdgesVersion: undefined, + }); + const shape = shapeFromCadMesh(source, response.positions, response.normals, response.indices, response.brep); + if (!shape) throw new Error("OpenCascade returned an empty sketch solid"); + return { ...shape, sketchProfile: cloneSketchProfile(profile), sketchOperation: "extrude" as const }; +} + async function shapeFromRevolvedSketchProfile( profile: SketchProfile, settings: Partial, @@ -2263,7 +2337,10 @@ function cadModifierPrimitiveForShape(shape: WorkplaneShape): CadModifierPrimiti } function bakeShapeTransformIntoMesh(shape: WorkplaneShape): WorkplaneShape { - if (!shapeHasTransformToBake(shape)) { + // Rotation is a non-destructive transform for editable text. Baking it would + // change the shape to `kind: "mesh"`, hiding the Text and Font controls even + // though the user never grouped or otherwise converted the object. + if (shape.kind === "text" || !shapeHasTransformToBake(shape)) { return shape; } @@ -2459,53 +2536,6 @@ async function importedShapeFromImage(file: File): Promise { }; } -function normalFor(a: Vec3, b: Vec3, c: Vec3): Vec3 { - const ux = b[0] - a[0]; - const uy = b[1] - a[1]; - const uz = b[2] - a[2]; - const vx = c[0] - a[0]; - const vy = c[1] - a[1]; - const vz = c[2] - a[2]; - const nx = uy * vz - uz * vy; - const ny = uz * vx - ux * vz; - const nz = ux * vy - uy * vx; - const length = Math.hypot(nx, ny, nz) || 1; - return [nx / length, ny / length, nz / length]; -} - -function toStl(meshes: MeshData[]) { - const lines = ["solid sketchforge_design"]; - meshes.forEach((mesh) => { - mesh.faces.forEach(([ai, bi, ci]) => { - const a = mesh.vertices[ai]; - const b = mesh.vertices[bi]; - const c = mesh.vertices[ci]; - const n = normalFor(a, b, c); - lines.push(` facet normal ${n[0]} ${n[1]} ${n[2]}`); - lines.push(" outer loop"); - lines.push(` vertex ${a[0]} ${a[1]} ${a[2]}`); - lines.push(` vertex ${b[0]} ${b[1]} ${b[2]}`); - lines.push(` vertex ${c[0]} ${c[1]} ${c[2]}`); - lines.push(" endloop"); - lines.push(" endfacet"); - }); - }); - lines.push("endsolid sketchforge_design"); - return lines.join("\n"); -} - -function toObj(meshes: MeshData[]) { - const lines = ["# SketchForge OBJ export"]; - let offset = 1; - meshes.forEach((mesh) => { - lines.push(`o ${mesh.name}`); - mesh.vertices.forEach(([x, y, z]) => lines.push(`v ${x} ${y} ${z}`)); - mesh.faces.forEach(([a, b, c]) => lines.push(`f ${a + offset} ${b + offset} ${c + offset}`)); - offset += mesh.vertices.length; - }); - return lines.join("\n"); -} - async function toSvg(shapes: WorkplaneShape[], title: string) { const runtime = await getManifoldRuntime(); const layers: SvgProjectionLayer[] = []; @@ -3118,6 +3148,12 @@ function separateMeshParts(shape: WorkplaneShape) { .filter((part): part is WorkplaneShape => Boolean(part)); } +function cadModifierSourceParts(shape: WorkplaneShape) { + if (shape.kind !== "text" || shape.importedMesh || shape.cadBrep) return [shape]; + const glyphParts = separateMeshParts(shape); + return glyphParts.length > 1 ? glyphParts : [shape]; +} + function separablePartCount(shape: WorkplaneShape) { if (shape.locked || shape.hole) return 0; if (shape.groupedShapes?.length && !shape.importedMesh) return shape.groupedShapes.length; @@ -5279,6 +5315,8 @@ export function SketchForgeEditor({ projectModifiedAt = Date.now(), projectRevision = 0, sharedProjectsEnabled = false, + challengeTutorial = null, + onChallengeTutorialFinish, themePreference = "system", resolvedTheme = "light", onThemePreferenceChange, @@ -5323,6 +5361,8 @@ export function SketchForgeEditor({ projectModifiedAt?: number; projectRevision?: number; sharedProjectsEnabled?: boolean; + challengeTutorial?: ChallengeTutorialId | null; + onChallengeTutorialFinish?: () => void; themePreference?: AppThemePreference; resolvedTheme?: ResolvedAppTheme; onThemePreferenceChange?: (preference: AppThemePreference) => void; @@ -6566,8 +6606,9 @@ export function SketchForgeEditor({ if (sketchOperation === "revolve") { resolved = await shapeFromRevolvedSketchProfile(sketchProfile, sketchRevolveSettings, existing); } else { - const extrusion = await shapeFromSketchProfile(sketchProfile, height, existing); - resolved = extrusion ? placeSketchExtrusion(extrusion, activeSketchWorkplane, existing) : null; + setNotice("Building exact sketch geometry…"); + const extrusion = await cadShapeFromSketchProfile(sketchProfile, height, existing); + resolved = placeSketchExtrusion(extrusion, activeSketchWorkplane, existing); } } catch (error) { setNotice(error instanceof Error ? error.message : `The sketch profile cannot be ${sketchOperation === "revolve" ? "revolved" : "extruded"} to 3D`); @@ -6579,7 +6620,7 @@ export function SketchForgeEditor({ } const nextShapes = existing ? shapes.map((shape) => (shape.id === existing.id ? resolved : shape)) : [...shapes, resolved]; const action = sketchOperation === "revolve" ? "Revolve sketch" : "Sketch"; - commitShapes(nextShapes, resolved.id, existing ? `${action} updated` : sketchOperation === "revolve" ? "Revolved sketch created" : "Sketch created at 10 mm height"); + commitShapes(nextShapes, resolved.id, existing ? `${action} updated` : sketchOperation === "revolve" ? "Revolved sketch created" : "Exact sketch created at 10 mm height"); setSketchActive(false); setSketchRevolvePreview(null); setEditingSketchShapeId(null); @@ -7072,7 +7113,9 @@ export function SketchForgeEditor({ invalidateCadModifierSession(); const appliedEdgeTreatmentCount = edgeTreatmentFeatureCount(selectedShape); const hasAppliedEdgeTreatment = Boolean(selectedShape.importedMesh && selectedShape.edgeTreatments?.length); - const sourceParts = selectedShape.groupedShapes?.length && !hasAppliedEdgeTreatment ? restoreGroupedChildren(selectedShape) : [selectedShape]; + const sourceParts = (selectedShape.groupedShapes?.length && !hasAppliedEdgeTreatment + ? restoreGroupedChildren(selectedShape) + : [selectedShape]).flatMap(cadModifierSourceParts); const partInputs: Array<{ shape: WorkplaneShape; mesh?: MeshData; brep?: string; brepTransform?: number[]; primitive?: CadModifierPrimitivePart }> = sourceParts.map((shape) => { const frame = shape.cadBrepFrame; const preserveNeedsRetessellation = preservesEdgeTreatmentSize(shape) && Boolean(frame) && ( @@ -7145,7 +7188,9 @@ export function SketchForgeEditor({ } const appliedEdgeTreatmentCount = edgeTreatmentFeatureCount(shape); const hasAppliedEdgeTreatment = Boolean(shape.importedMesh && shape.edgeTreatments?.length); - const sourceParts = shape.groupedShapes?.length && !hasAppliedEdgeTreatment ? restoreGroupedChildren(shape) : [shape]; + const sourceParts = (shape.groupedShapes?.length && !hasAppliedEdgeTreatment + ? restoreGroupedChildren(shape) + : [shape]).flatMap(cadModifierSourceParts); const partInputs: Array<{ shape: WorkplaneShape; mesh?: MeshData; brep?: string; brepTransform?: number[]; primitive?: CadModifierPrimitivePart }> = sourceParts.map((partShape) => { const frame = partShape.cadBrepFrame; const preserveNeedsRetessellation = preservesEdgeTreatmentSize(partShape) && Boolean(frame) && ( @@ -7711,8 +7756,7 @@ export function SketchForgeEditor({ let shape: WorkplaneShape; if (kind === "sketch") { const profile = defaultMcpSketchProfile(width, depth); - const extruded = await shapeFromSketchProfile(profile, height); - if (!extruded) throw new Error("Could not create the sketch profile"); + const extruded = await cadShapeFromSketchProfile(profile, height); shape = canonicalizeShape({ ...extruded, name, @@ -7724,7 +7768,7 @@ export function SketchForgeEditor({ rotationX: mcpNumber(params.rotationX, 0), rotationZ: mcpNumber(params.rotationZ, 0), }); - } else if (kind === "box" || kind === "cylinder") { + } else if (kind === "box" || kind === "cylinder" || kind === "text") { shape = sceneShape({ name, kind, @@ -7740,9 +7784,13 @@ export function SketchForgeEditor({ rotationX: mcpNumber(params.rotationX, 0), rotationZ: mcpNumber(params.rotationZ, 0), sides: kind === "cylinder" ? Math.max(3, Math.floor(mcpNumber(params.sides, 96))) : undefined, + text: kind === "text" ? mcpString(params.text, "TEXT") : undefined, + font: kind === "text" ? mcpString(params.font, "Multilanguage") : undefined, + bevel: kind === "text" ? Math.max(0, mcpNumber(params.bevel, 0)) : undefined, + segments: kind === "text" ? Math.max(1, Math.floor(mcpNumber(params.segments, 2))) : undefined, }); } else { - throw new Error("MCP create_shape currently supports box, cube, cylinder, and sketch"); + throw new Error("MCP create_shape currently supports box, cube, cylinder, text, and sketch"); } const committedShape = canonicalizeShape(bakeShapeTransformIntoMesh(shape)); commitShapes([...currentShapes(), committedShape], committedShape.id, `${committedShape.name} added by MCP`); @@ -7822,6 +7870,9 @@ export function SketchForgeEditor({ if (typeof params.color === "string") patch.color = params.color; if (typeof params.name === "string") patch.name = params.name; if (typeof params.hole === "boolean") patch.hole = params.hole; + if (typeof params.text === "string") patch.text = params.text; + if (typeof params.font === "string") patch.font = params.font; + if (typeof params.bevel === "number" && Number.isFinite(params.bevel)) patch.bevel = Math.max(0, params.bevel); const nextShapes = currentShapes().map((shape) => { if (shape.id !== target.id) return shape; const patched = { ...shape, ...cleanShapePatch(patch) }; @@ -8272,12 +8323,12 @@ export function SketchForgeEditor({ } const meshes = exportable.map(meshForShape); if (format === "stl") { - void downloadTextFile(projectExportFileName(exportName, "stl"), toStl(meshes), "model/stl") + void downloadTextFile(projectExportFileName(exportName, "stl"), exportMeshesToStl(meshes), "model/stl") .then((result) => finishNotice("STL", result)) .catch((error: unknown) => failNotice("STL", error)); return; } - void downloadTextFile(projectExportFileName(exportName, "obj"), toObj(meshes), "text/plain") + void downloadTextFile(projectExportFileName(exportName, "obj"), exportMeshesToObj(meshes), "text/plain") .then((result) => finishNotice("OBJ", result)) .catch((error: unknown) => failNotice("OBJ", error)); }, [hasSelection, projectName, selectedShapes, shapes]); @@ -8897,6 +8948,8 @@ export function SketchForgeEditor({ modifierEdges={edgeModifier?.edges.filter((edge) => modifierAvailableEdgeIds.includes(edge.id)) ?? []} selectedModifierEdgeIds={edgeModifier?.selectedEdgeIds ?? []} onModifierEdgeToggle={toggleModifierEdge} + challengeTutorial={challengeTutorial} + onChallengeTutorialFinish={onChallengeTutorialFinish} themePreference={themePreference} resolvedTheme={resolvedTheme} onThemePreferenceChange={onThemePreferenceChange} @@ -9274,7 +9327,15 @@ function SecondaryToolbar({ const { icon: Icon, action, enabled, label } = tool; const active = "active" in tool && Boolean(tool.active); return ( - ); diff --git a/apps/web/src/components/SketchWorkspace.tsx b/apps/web/src/components/SketchWorkspace.tsx index d7577be..f5386f3 100644 --- a/apps/web/src/components/SketchWorkspace.tsx +++ b/apps/web/src/components/SketchWorkspace.tsx @@ -608,14 +608,7 @@ export function SketchWorkspace({ const end = pointById.get(segment.endId); return Boolean(start && end && (contains(start) || contains(end) || contains({ x: (start.x + end.x) / 2, z: (start.z + end.z) / 2 }))); }).map((segment) => segment.id); - const imageIds = (profile.images ?? []).filter((image) => { - const imageMinX = image.x - image.width / 2; - const imageMaxX = image.x + image.width / 2; - const imageMinZ = image.z - image.depth / 2; - const imageMaxZ = image.z + image.depth / 2; - return imageMaxX >= minX && imageMinX <= maxX && imageMaxZ >= minZ && imageMinZ <= maxZ; - }).map((image) => image.id); - onSelectMany(pointIds, segmentIds, imageIds); + onSelectMany(pointIds, segmentIds, []); setPointerAction(null); return; } @@ -745,7 +738,6 @@ export function SketchWorkspace({ if (event.button !== 0 || tool !== "select") return; const point = pointFromEvent(event); if (!point) return; - onSelectImage(image.id); beginEntityDrag(event, { kind: "move-image", pointerId: event.pointerId, @@ -989,7 +981,7 @@ export function SketchWorkspace({ ) : null} -
+
diff --git a/apps/web/src/components/WorkplaneViewport.tsx b/apps/web/src/components/WorkplaneViewport.tsx index 39f1ad3..8226e0b 100644 --- a/apps/web/src/components/WorkplaneViewport.tsx +++ b/apps/web/src/components/WorkplaneViewport.tsx @@ -21,8 +21,11 @@ import optimerBoldFontJson from "three/examples/fonts/optimer_bold.typeface.json import { AlignOverlay, MirrorOverlay, type AlignOverlayState, type MirrorOverlayState } from "@/components/workplane/ActionOverlays"; import { MoveDimensionOverlay } from "@/components/workplane/MoveDimensionOverlay"; import { ShapeInspector, SnapGridControl, type ShapeInspectorUpdateOptions } from "@/components/workplane/ShapeInspector"; +import { KeyTagTutorialPanel } from "@/components/workplane/KeyTagTutorialPanel"; +import { NameplateTutorialPanel } from "@/components/workplane/NameplateTutorialPanel"; import { WorkspaceSettingsModal } from "@/components/workplane/WorkspaceSettingsModal"; import type { AppThemePreference, ResolvedAppTheme } from "@/lib/appTheme"; +import type { ChallengeTutorialId } from "@/lib/challenges"; import { cadModifierPrimitiveForBakedShape, cadTransformFromMatrix, cadTransformToMatrix } from "@/lib/cadBakeMetadata"; import { createGearGeometry } from "@/lib/gearGeometry"; import { parseMeasurementInput } from "@/lib/measurementUnits"; @@ -201,6 +204,8 @@ type WorkplaneViewportProps = { modifierEdges?: CadModifierEdge[]; selectedModifierEdgeIds?: number[]; onModifierEdgeToggle?: (id: number, singleEdge: boolean) => void; + challengeTutorial?: ChallengeTutorialId | null; + onChallengeTutorialFinish?: () => void; themePreference?: AppThemePreference; resolvedTheme?: ResolvedAppTheme; onThemePreferenceChange?: (preference: AppThemePreference) => void; @@ -2223,6 +2228,8 @@ export function WorkplaneViewport({ modifierEdges = [], selectedModifierEdgeIds = [], onModifierEdgeToggle, + challengeTutorial = null, + onChallengeTutorialFinish, themePreference = "system", resolvedTheme = "light", onThemePreferenceChange, @@ -2254,6 +2261,12 @@ export function WorkplaneViewport({ const [rulerOverlay, setRulerOverlay] = useState(null); const [moveDimensionOverlay, setMoveDimensionOverlay] = useState(null); const [moveDimensionsEnabled, setMoveDimensionsEnabled] = useState(true); + const [challengeTutorialCollapsed, setChallengeTutorialCollapsed] = useState(false); + + useEffect(() => { + setChallengeTutorialCollapsed(false); + }, [challengeTutorial]); + const hostRef = useRef(null); const threeRef = useRef(null); const shapesRef = useRef(shapes); @@ -3220,6 +3233,7 @@ export function WorkplaneViewport({ } return shapesRef.current .filter((shape) => !shape.hidden) + .filter((shape) => !shape.imagePlate) .filter((shape) => { const bounds = shapeScreenBounds(state, shape); return bounds ? boundsIntersectRect(bounds, rect) : false; @@ -3778,7 +3792,12 @@ export function WorkplaneViewport({ state.raycaster.layers.set(RENDER_LAYER_SHAPES); const intersections = state.raycaster.intersectObjects(state.shapeLayer.children, true); - const hit = intersections.find((entry) => typeof entry.object.userData.shapeId === "string"); + const hit = intersections.find((entry) => { + const shapeId = entry.object.userData.shapeId; + if (typeof shapeId !== "string") return false; + const shape = shapesRef.current.find((candidate) => candidate.id === shapeId); + return shape ? !shape.imagePlate : false; + }); if (hit) { return hit.object.userData.shapeId as string; } @@ -3786,6 +3805,7 @@ export function WorkplaneViewport({ let nearestId: string | null = null; let nearestDistance = Number.POSITIVE_INFINITY; shapesRef.current.forEach((shape) => { + if (shape.imagePlate) return; const center = new THREE.Vector3(shape.x, (shape.elevation ?? 0) + shape.height / 2, shape.z).project(state.camera); const screenX = rect.left + ((center.x + 1) / 2) * rect.width; const screenY = rect.top + ((1 - center.y) / 2) * rect.height; @@ -4757,7 +4777,7 @@ export function WorkplaneViewport({ }, [onWorkplaneModeChange, resetView, rulerToolsOpen, setPlacementWorkplaneAtSelection, setRulerActive, togglePlacementWorkplane, toggleProjection, zoomCamera]); return ( -
+
event.stopPropagation()}>
@@ -4939,6 +4959,20 @@ export function WorkplaneViewport({ onClose={() => setSettingsOpen(false)} /> ) : null} + + {challengeTutorial === "key-tag" ? ( + + ) : challengeTutorial === "nameplate" ? ( + + ) : null}
); } diff --git a/apps/web/src/components/official/ChallengesDashboard.tsx b/apps/web/src/components/official/ChallengesDashboard.tsx new file mode 100644 index 0000000..ca3a561 --- /dev/null +++ b/apps/web/src/components/official/ChallengesDashboard.tsx @@ -0,0 +1,106 @@ +"use client"; + +import { AlignCenter, Box, CircleDotDashed, Group, LockKeyhole, MoveUp, Type } from "lucide-react"; +import type { ChallengeTutorialId } from "@/lib/challenges"; + +function KeyTagPreview() { + return ( + <> + Finished red Key Tag model on the SketchForge workplane + Finished red Key Tag model on the dark SketchForge workplane + + ); +} + +function NameplatePreview() { + return ( + <> + Finished blue ALEX nameplate on the SketchForge workplane + Finished blue ALEX nameplate on the dark SketchForge workplane + + ); +} + +export default function ChallengesDashboard({ onStartChallenge }: { onStartChallenge: (challenge: ChallengeTutorialId) => void }) { + return ( +
+ + +
+
+
+ +
+ +
+
+ 01 +

Key Tag

+
+ +

Build your first Key Tag from simple shapes.

+ +
+ + + + + +
+ + +
+
+ +
+
+ +
+ +
+
+ 02 +

Personalized Nameplate

+
+ +

Create a printable nameplate with rounded edges and raised custom text.

+ +
+ + + + + + +
+ + +
+
+
+
+ ); +} diff --git a/apps/web/src/components/workplane/KeyTagTutorialPanel.tsx b/apps/web/src/components/workplane/KeyTagTutorialPanel.tsx new file mode 100644 index 0000000..f808aa4 --- /dev/null +++ b/apps/web/src/components/workplane/KeyTagTutorialPanel.tsx @@ -0,0 +1,233 @@ +"use client"; + +import { ChevronLeft, ChevronRight } from "lucide-react"; +import { useState } from "react"; + +const KEY_TAG_STEP_STORAGE_KEY = "sketchforge:key-tag-tutorial-step"; + +type TutorialDimension = { + label: "Length" | "Width" | "Height"; + value: string; + slider: number; +}; + +type TutorialStep = { + eyebrow: string; + title: string; + body: string; + image: string; + alt: string; + dimensions?: TutorialDimension[]; + snapGrid?: string; +}; + +const STEPS: TutorialStep[] = [ + { + eyebrow: "Before you start", + title: "Build a Key Tag", + body: "Set Snap Grid to 0.5 mm, then build the Key Tag from simple shapes.", + image: "/assets/challenges/key-tag/01-finished-target.png", + alt: "Finished Key Tag shown in the SketchForge workplane", + snapGrid: "0.5 mm", + }, + { + eyebrow: "Step 1", + title: "Make the middle", + body: "Add a Box, then set its size in the shape panel.", + image: "/assets/challenges/key-tag/02-middle-box.png", + alt: "The middle box of the Key Tag in SketchForge", + dimensions: [ + { label: "Length", value: "25.50 mm", slider: 38 }, + { label: "Width", value: "11.50 mm", slider: 20 }, + { label: "Height", value: "1.00 mm", slider: 5 }, + ], + }, + { + eyebrow: "Step 2", + title: "Add the left round end", + body: "Add a solid Cylinder and place half of it over the left end of the box.", + image: "/assets/challenges/key-tag/03-left-round-end.png", + alt: "A solid cylinder added to the left end of the Key Tag", + dimensions: [ + { label: "Length", value: "11.50 mm", slider: 20 }, + { label: "Width", value: "11.50 mm", slider: 20 }, + { label: "Height", value: "1.00 mm", slider: 5 }, + ], + }, + { + eyebrow: "Step 3", + title: "Make the other end", + body: "Duplicate the solid cylinder and place the copy on the right end.", + image: "/assets/challenges/key-tag/04-right-round-end.png", + alt: "Two solid cylinders forming both rounded ends of the Key Tag", + }, + { + eyebrow: "Step 4", + title: "Lock the left circle", + body: "Select the left solid cylinder and press Lock. It will be the alignment reference.", + image: "/assets/challenges/key-tag/05-select-left-circle.png", + alt: "The left solid cylinder selected in the SketchForge workplane", + }, + { + eyebrow: "Step 5", + title: "Create the hole", + body: "Add another Cylinder, set its size, then change it from Solid to Hole.", + image: "/assets/challenges/key-tag/06-hole-cylinder.png", + alt: "The small hole cylinder added near the left end of the Key Tag", + dimensions: [ + { label: "Length", value: "3.00 mm", slider: 8 }, + { label: "Width", value: "3.00 mm", slider: 8 }, + { label: "Height", value: "2.00 mm", slider: 7 }, + ], + }, + { + eyebrow: "Step 6", + title: "Align the hole", + body: "Select the hole and the locked left circle. Press Align and choose the middle on both horizontal axes.", + image: "/assets/challenges/key-tag/07-align-hole.png", + alt: "The hole aligned to the center of the left solid cylinder", + }, + { + eyebrow: "Step 7", + title: "Unlock the circle", + body: "Select the left solid circle again and press Unlock.", + image: "/assets/challenges/key-tag/08-unlock-left-circle.png", + alt: "The left solid cylinder selected again after the hole has been aligned", + }, + { + eyebrow: "Step 8", + title: "Group the Key Tag", + body: "Select the box, both solid circles, and the hole. Press Group.", + image: "/assets/challenges/key-tag/09-grouped-key-tag.png", + alt: "The finished grouped Key Tag selected in SketchForge", + }, +]; + +function storedStepIndex() { + if (typeof window === "undefined") return 0; + const parsed = Number.parseInt(window.localStorage.getItem(KEY_TAG_STEP_STORAGE_KEY) ?? "0", 10); + return Number.isFinite(parsed) ? Math.max(0, Math.min(STEPS.length - 1, parsed)) : 0; +} + +export function KeyTagTutorialPanel({ + onFinish, + collapsed = false, + onCollapsedChange, +}: { + onFinish?: () => void; + collapsed?: boolean; + onCollapsedChange?: (collapsed: boolean) => void; +}) { + const [stepIndex, setStepIndex] = useState(storedStepIndex); + const step = STEPS[stepIndex]; + const first = stepIndex === 0; + const last = stepIndex === STEPS.length - 1; + + const goToStep = (index: number) => { + const next = Math.max(0, Math.min(STEPS.length - 1, index)); + setStepIndex(next); + window.localStorage.setItem(KEY_TAG_STEP_STORAGE_KEY, String(next)); + }; + + if (collapsed) { + return ( + + ); + } + + return ( + + ); +} diff --git a/apps/web/src/components/workplane/NameplateTutorialPanel.tsx b/apps/web/src/components/workplane/NameplateTutorialPanel.tsx new file mode 100644 index 0000000..196a6cf --- /dev/null +++ b/apps/web/src/components/workplane/NameplateTutorialPanel.tsx @@ -0,0 +1,270 @@ +"use client"; + +import { ArrowUp, ChevronLeft, ChevronRight } from "lucide-react"; +import { useLayoutEffect, useState } from "react"; + +const NAMEPLATE_STEP_STORAGE_KEY = "sketchforge:nameplate-tutorial-step"; + +type TutorialDimension = { + label: "Length" | "Width" | "Height" | "Elevation"; + value: string; + slider: number; +}; + +type TutorialStep = { + eyebrow: string; + title: string; + body: string; + image: string; + alt: string; + dimensions?: TutorialDimension[]; + snapGrid?: string; + callout?: string; +}; + +const STEPS: TutorialStep[] = [ + { + eyebrow: "Before you start", + title: "Build a Nameplate", + body: "Create a rounded base, personalize a Text object, then combine both parts into one printable design.", + image: "/assets/challenges/nameplate/01-finished-target.webp", + alt: "Finished blue ALEX nameplate on the SketchForge workplane", + snapGrid: "0.5 mm", + }, + { + eyebrow: "Step 1", + title: "Make the base", + body: "Add a Box and enter these dimensions in the shape panel.", + image: "/assets/challenges/nameplate/02-base-box.webp", + alt: "Plain rectangular blue nameplate base", + dimensions: [ + { label: "Length", value: "24.00 mm", slider: 24 }, + { label: "Width", value: "70.00 mm", slider: 70 }, + { label: "Height", value: "3.00 mm", slider: 12 }, + ], + }, + { + eyebrow: "Step 2", + title: "Round the outside", + body: "Select the base, press Fillet, select its outside edges, and apply the treatment.", + image: "/assets/challenges/nameplate/03-rounded-base.webp", + alt: "Blue nameplate base with softly rounded outer edges", + callout: "Use a 1.00 mm fillet amount.", + }, + { + eyebrow: "Step 3", + title: "Add a Text object", + body: "Open Shapes and add Text. The new object starts with the letter T.", + image: "/assets/challenges/nameplate/04-text-added.webp", + alt: "A red capital T Text object on the blue nameplate base", + }, + { + eyebrow: "Step 4", + title: "Personalize the text", + body: "Change the Text field to your name. This example uses ALEX. Pick any font you like.", + image: "/assets/challenges/nameplate/05-text-customized.webp", + alt: "Raised red ALEX text placed off-center on the blue base", + dimensions: [ + { label: "Height", value: "2.00 mm", slider: 9 }, + ], + }, + { + eyebrow: "Step 5", + title: "Place it on top", + body: "Lift the Text object until its bottom sits exactly on the top face of the 3 mm base.", + image: "/assets/challenges/nameplate/05-text-customized.webp", + alt: "Raised red ALEX text resting on the blue nameplate base", + dimensions: [ + { label: "Elevation", value: "3.00 mm", slider: 12 }, + ], + }, + { + eyebrow: "Step 6", + title: "Center the name", + body: "Lock the base, select the Text and base, then Align to the middle on both horizontal axes. Unlock the base afterward.", + image: "/assets/challenges/nameplate/06-text-centered.webp", + alt: "Red ALEX text centered on the blue nameplate base", + callout: "The locked base stays fixed as your alignment reference.", + }, + { + eyebrow: "Step 7", + title: "Group the Nameplate", + body: "Select the base and Text object, then press Group to make one finished printable model.", + image: "/assets/challenges/nameplate/07-grouped-nameplate.webp", + alt: "Finished grouped blue ALEX nameplate", + }, +]; + +function storedStepIndex() { + if (typeof window === "undefined") return 0; + const parsed = Number.parseInt(window.localStorage.getItem(NAMEPLATE_STEP_STORAGE_KEY) ?? "0", 10); + return Number.isFinite(parsed) ? Math.max(0, Math.min(STEPS.length - 1, parsed)) : 0; +} + +function FilletButtonCoachmark() { + const [position, setPosition] = useState<{ left: number; top: number } | null>(null); + + useLayoutEffect(() => { + const target = document.querySelector('button[data-sketchforge-tool="fillet"]'); + if (!target) return; + + const updatePosition = () => { + const rect = target.getBoundingClientRect(); + setPosition({ + left: rect.left + rect.width / 2, + top: rect.bottom + 42, + }); + }; + + target.classList.add("nameplate-fillet-button-target"); + updatePosition(); + window.addEventListener("resize", updatePosition); + window.addEventListener("scroll", updatePosition, true); + const observer = new ResizeObserver(updatePosition); + observer.observe(target); + + return () => { + target.classList.remove("nameplate-fillet-button-target"); + window.removeEventListener("resize", updatePosition); + window.removeEventListener("scroll", updatePosition, true); + observer.disconnect(); + }; + }, []); + + if (!position) return null; + + return ( +
+
+ ); +} + +export function NameplateTutorialPanel({ + onFinish, + collapsed = false, + onCollapsedChange, +}: { + onFinish?: () => void; + collapsed?: boolean; + onCollapsedChange?: (collapsed: boolean) => void; +}) { + const [stepIndex, setStepIndex] = useState(storedStepIndex); + const step = STEPS[stepIndex]; + const first = stepIndex === 0; + const last = stepIndex === STEPS.length - 1; + + const goToStep = (index: number) => { + const next = Math.max(0, Math.min(STEPS.length - 1, index)); + setStepIndex(next); + window.localStorage.setItem(NAMEPLATE_STEP_STORAGE_KEY, String(next)); + }; + + if (collapsed) { + return ( + + ); + } + + return ( + <> + {stepIndex === 2 ? : null} + + + ); +} diff --git a/apps/web/src/lib/appUpdates.ts b/apps/web/src/lib/appUpdates.ts new file mode 100644 index 0000000..30c6922 --- /dev/null +++ b/apps/web/src/lib/appUpdates.ts @@ -0,0 +1,65 @@ +export const OFFICIAL_UPDATE_GUIDE_URL = "https://github.com/Formsmith746/SketchForge-3D#update-sketchforge-later"; + +export type AppUpdateStatus = { + currentVersion: string; + latestVersion: string | null; + updateAvailable: boolean; + checkedAt: string; + updateUrl: string; + installationReady: boolean; + requiresUpdateKey: boolean; + checkError?: string; +}; + +type ParsedVersion = { + major: number; + minor: number; + patch: number; + prerelease: string[]; +}; + +function parseVersion(value: string): ParsedVersion | null { + const match = value.trim().match(/^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/); + if (!match) return null; + return { + major: Number(match[1]), + minor: Number(match[2]), + patch: Number(match[3]), + prerelease: match[4] ? match[4].split(".") : [], + }; +} + +function comparePrereleasePart(left: string, right: string) { + const leftNumber = /^\d+$/.test(left) ? Number(left) : null; + const rightNumber = /^\d+$/.test(right) ? Number(right) : null; + if (leftNumber !== null && rightNumber !== null) return Math.sign(leftNumber - rightNumber); + if (leftNumber !== null) return -1; + if (rightNumber !== null) return 1; + return left.localeCompare(right); +} + +export function compareAppVersions(leftValue: string, rightValue: string) { + const left = parseVersion(leftValue); + const right = parseVersion(rightValue); + if (!left || !right) return leftValue.trim().localeCompare(rightValue.trim()); + + for (const key of ["major", "minor", "patch"] as const) { + if (left[key] !== right[key]) return Math.sign(left[key] - right[key]); + } + if (!left.prerelease.length && !right.prerelease.length) return 0; + if (!left.prerelease.length) return 1; + if (!right.prerelease.length) return -1; + + const partCount = Math.max(left.prerelease.length, right.prerelease.length); + for (let index = 0; index < partCount; index += 1) { + if (left.prerelease[index] === undefined) return -1; + if (right.prerelease[index] === undefined) return 1; + const comparison = comparePrereleasePart(left.prerelease[index], right.prerelease[index]); + if (comparison !== 0) return comparison; + } + return 0; +} + +export function appUpdateIsAvailable(currentVersion: string, latestVersion: string) { + return compareAppVersions(latestVersion, currentVersion) > 0; +} diff --git a/apps/web/src/lib/challenges.ts b/apps/web/src/lib/challenges.ts new file mode 100644 index 0000000..019c8ec --- /dev/null +++ b/apps/web/src/lib/challenges.ts @@ -0,0 +1,7 @@ +export const CHALLENGE_TUTORIAL_IDS = ["key-tag", "nameplate"] as const; + +export type ChallengeTutorialId = (typeof CHALLENGE_TUTORIAL_IDS)[number]; + +export function isChallengeTutorialId(value: unknown): value is ChallengeTutorialId { + return typeof value === "string" && CHALLENGE_TUTORIAL_IDS.includes(value as ChallengeTutorialId); +} diff --git a/apps/web/src/lib/meshCoordinates.ts b/apps/web/src/lib/meshCoordinates.ts new file mode 100644 index 0000000..f03d018 --- /dev/null +++ b/apps/web/src/lib/meshCoordinates.ts @@ -0,0 +1,11 @@ +export type MeshPoint = readonly [number, number, number]; + +/** Maps the Z-up coordinate convention used by slicers/CAD files into SketchForge's Y-up scene. */ +export function zUpToSketchForge([x, y, z]: MeshPoint): [number, number, number] { + return [x, z, -y]; +} + +/** Maps SketchForge's Y-up scene into the Z-up coordinate convention expected by slicers. */ +export function sketchForgeToZUp([x, y, z]: MeshPoint): [number, number, number] { + return [x, -z, y]; +} diff --git a/apps/web/src/lib/objExport.ts b/apps/web/src/lib/objExport.ts new file mode 100644 index 0000000..f5b8337 --- /dev/null +++ b/apps/web/src/lib/objExport.ts @@ -0,0 +1,79 @@ +import type { MeshPoint } from "@/lib/meshCoordinates"; + +export type ObjExportMesh = { + name: string; + vertices: readonly MeshPoint[]; + faces: readonly (readonly [number, number, number])[]; +}; + +const OBJ_WELD_TOLERANCE = 0.00001; + +function bucketKey(x: number, y: number, z: number) { + return `${x}:${y}:${z}`; +} + +function weldMeshVertices(mesh: ObjExportMesh) { + const vertices: Array<[number, number, number]> = []; + const buckets = new Map(); + const remappedIndices: number[] = []; + + mesh.vertices.forEach((sourceVertex) => { + // OBJ tools conventionally treat Y as up. Keep SketchForge's Y-up + // coordinates here so slicers do not apply their OBJ axis conversion a + // second time. STL is exported separately using explicit Z-up coordinates. + const vertex: [number, number, number] = [...sourceVertex]; + const bucketX = Math.floor(vertex[0] / OBJ_WELD_TOLERANCE); + const bucketY = Math.floor(vertex[1] / OBJ_WELD_TOLERANCE); + const bucketZ = Math.floor(vertex[2] / OBJ_WELD_TOLERANCE); + let weldedIndex: number | undefined; + + for (let xOffset = -1; xOffset <= 1 && weldedIndex === undefined; xOffset += 1) { + for (let yOffset = -1; yOffset <= 1 && weldedIndex === undefined; yOffset += 1) { + for (let zOffset = -1; zOffset <= 1 && weldedIndex === undefined; zOffset += 1) { + const candidates = buckets.get(bucketKey(bucketX + xOffset, bucketY + yOffset, bucketZ + zOffset)) ?? []; + weldedIndex = candidates.find((candidateIndex) => { + const candidate = vertices[candidateIndex]; + return ( + Math.abs(candidate[0] - vertex[0]) <= OBJ_WELD_TOLERANCE && + Math.abs(candidate[1] - vertex[1]) <= OBJ_WELD_TOLERANCE && + Math.abs(candidate[2] - vertex[2]) <= OBJ_WELD_TOLERANCE + ); + }); + } + } + } + + if (weldedIndex === undefined) { + weldedIndex = vertices.length; + vertices.push(vertex); + const key = bucketKey(bucketX, bucketY, bucketZ); + buckets.set(key, [...(buckets.get(key) ?? []), weldedIndex]); + } + remappedIndices.push(weldedIndex); + }); + + const faces = mesh.faces + .map(([a, b, c]) => [remappedIndices[a], remappedIndices[b], remappedIndices[c]] as [number, number, number]) + .filter(([a, b, c]) => a !== b && b !== c && c !== a); + + return { vertices, faces }; +} + +function objNumber(value: number) { + return Math.abs(value) < 1e-12 ? "0" : String(value); +} + +export function exportMeshesToObj(meshes: readonly ObjExportMesh[]) { + const lines = ["# SketchForge OBJ export"]; + let offset = 1; + + meshes.forEach((mesh) => { + const welded = weldMeshVertices(mesh); + lines.push(`o ${mesh.name}`); + welded.vertices.forEach(([x, y, z]) => lines.push(`v ${objNumber(x)} ${objNumber(y)} ${objNumber(z)}`)); + welded.faces.forEach(([a, b, c]) => lines.push(`f ${a + offset} ${b + offset} ${c + offset}`)); + offset += welded.vertices.length; + }); + + return lines.join("\n"); +} diff --git a/apps/web/src/lib/sketchCadProfile.ts b/apps/web/src/lib/sketchCadProfile.ts new file mode 100644 index 0000000..c56c08b --- /dev/null +++ b/apps/web/src/lib/sketchCadProfile.ts @@ -0,0 +1,151 @@ +import type { SketchPoint, SketchProfile, SketchSegment } from "@/types/sketchforge"; + +export type OrderedCadSketchStep = { segment: SketchSegment; from: SketchPoint; to: SketchPoint }; +export type OrderedCadSketchPath = { id: string; points: SketchPoint[]; steps: OrderedCadSketchStep[]; closed: boolean }; +export type CadSketchRegion = { outer: OrderedCadSketchPath; holes: OrderedCadSketchPath[] }; + +export function orderedCadSketchPaths(profile: SketchProfile): OrderedCadSketchPath[] { + const pointById = new Map(profile.points.map((point) => [point.id, point])); + const adjacency = new Map>(); + profile.points.forEach((point) => adjacency.set(point.id, [])); + const valid = profile.segments.filter((segment) => { + if (segment.startId === segment.endId || !pointById.has(segment.startId) || !pointById.has(segment.endId)) return false; + adjacency.get(segment.startId)?.push({ pointId: segment.endId, segment }); + adjacency.get(segment.endId)?.push({ pointId: segment.startId, segment }); + return true; + }); + const unvisited = new Set(valid.map((segment) => segment.id)); + const paths: OrderedCadSketchPath[] = []; + + while (unvisited.size > 0) { + const seedId = unvisited.values().next().value as string; + const seed = valid.find((segment) => segment.id === seedId); + if (!seed) break; + const component = new Set(); + const queue = [seed.startId, seed.endId]; + while (queue.length > 0) { + const id = queue.pop(); + if (!id || component.has(id)) continue; + component.add(id); + adjacency.get(id)?.forEach((edge) => queue.push(edge.pointId)); + } + const startId = [...component].find((id) => (adjacency.get(id)?.filter((edge) => unvisited.has(edge.segment.id)).length ?? 0) === 1) ?? seed.startId; + const first = pointById.get(startId); + if (!first) { + unvisited.delete(seed.id); + continue; + } + const points = [first]; + const steps: OrderedCadSketchStep[] = []; + let currentId = startId; + for (let guard = 0; guard <= valid.length; guard += 1) { + const edge = adjacency.get(currentId)?.find((candidate) => unvisited.has(candidate.segment.id)); + if (!edge) break; + const from = pointById.get(currentId); + const to = pointById.get(edge.pointId); + if (!from || !to) break; + unvisited.delete(edge.segment.id); + steps.push({ segment: edge.segment, from, to }); + currentId = to.id; + if (currentId === startId) break; + points.push(to); + } + paths.push({ id: seed.id, points, steps, closed: currentId === startId && steps.length >= 3 }); + } + return paths; +} + +function sampledPath(path: OrderedCadSketchPath) { + const samples: Array<{ x: number; z: number }> = []; + path.steps.forEach(({ segment, from, to }, stepIndex) => { + if (stepIndex === 0) samples.push({ x: from.x, z: from.z }); + const forward = segment.startId === from.id; + const first = forward ? from.handleOut : from.handleIn; + const second = forward ? to.handleIn : to.handleOut; + if (segment.kind === "line" || !first || !second) { + samples.push({ x: to.x, z: to.z }); + return; + } + for (let index = 1; index <= 16; index += 1) { + const amount = index / 16; + const inverse = 1 - amount; + samples.push({ + x: inverse ** 3 * from.x + 3 * inverse ** 2 * amount * first.x + 3 * inverse * amount ** 2 * second.x + amount ** 3 * to.x, + z: inverse ** 3 * from.z + 3 * inverse ** 2 * amount * first.z + 3 * inverse * amount ** 2 * second.z + amount ** 3 * to.z, + }); + } + }); + return samples; +} + +function signedArea(points: Array<{ x: number; z: number }>) { + return points.reduce((area, point, index) => { + const next = points[(index + 1) % points.length]; + return area + point.x * next.z - next.x * point.z; + }, 0) / 2; +} + +function pointInPolygon(point: { x: number; z: number }, polygon: Array<{ x: number; z: number }>) { + let inside = false; + for (let index = 0, previous = polygon.length - 1; index < polygon.length; previous = index, index += 1) { + const current = polygon[index]; + const before = polygon[previous]; + if ((current.z > point.z) !== (before.z > point.z) + && point.x < ((before.x - current.x) * (point.z - current.z)) / (before.z - current.z) + current.x) inside = !inside; + } + return inside; +} + +export function cadSketchRegions(profile: SketchProfile): CadSketchRegion[] { + const allPaths = orderedCadSketchPaths(profile); + const openCount = allPaths.filter((path) => !path.closed).length; + const records = allPaths + .filter((path) => path.closed) + .map((path) => { + const polygon = sampledPath(path); + return { path, polygon, area: Math.abs(signedArea(polygon)) }; + }) + .filter((record) => record.polygon.length >= 3 && record.area > 1e-8) + .sort((a, b) => b.area - a.area); + + // Compute nesting depth: count how many larger closed paths contain each record. + // Even depth = solid (outer boundary), odd depth = hole. + const depths = records.map((record, index) => { + let depth = 0; + for (let i = 0; i < records.length; i++) { + if (i === index) continue; + if (records[i].area > record.area && pointInPolygon(record.polygon[0], records[i].polygon)) { + depth++; + } + } + return depth; + }); + + const regions: CadSketchRegion[] = []; + records.forEach((record, index) => { + const depth = depths[index]; + if (depth % 2 === 0) { + regions.push({ outer: record.path, holes: [] }); + } else { + // Odd depth: find the nearest even-depth ancestor (smallest containing solid) + let bestParent: (typeof records)[number] | null = null; + for (let i = 0; i < records.length; i++) { + if (i === index) continue; + if (depths[i] % 2 === 0 && depths[i] < depth && records[i].area > record.area && pointInPolygon(record.polygon[0], records[i].polygon)) { + if (!bestParent || records[i].area < bestParent.area) { + bestParent = records[i]; + } + } + } + if (bestParent) { + const region = regions.find((r) => r.outer === bestParent!.path); + if (region) region.holes.push(record.path); + } + } + }); + + if (regions.length === 0 && openCount > 0 && allPaths.length > 0) { + throw new Error("All profile paths are open. Close at least one loop before finishing the sketch."); + } + return regions; +} diff --git a/apps/web/src/lib/sketchCadTypes.ts b/apps/web/src/lib/sketchCadTypes.ts new file mode 100644 index 0000000..076c237 --- /dev/null +++ b/apps/web/src/lib/sketchCadTypes.ts @@ -0,0 +1,20 @@ +import type { SketchProfile } from "@/types/sketchforge"; + +export type SketchCadBuildRequest = { + type: "build"; + requestId: number; + profile: SketchProfile; + height: number; +}; + +export type SketchCadBuildResponse = + | { + type: "built"; + requestId: number; + positions: Float32Array; + normals: Float32Array; + indices: Uint32Array; + triangleCount: number; + brep: string; + } + | { type: "error"; requestId: number; message: string }; diff --git a/apps/web/src/lib/skfProject.ts b/apps/web/src/lib/skfProject.ts index 8f6495e..a35739e 100644 --- a/apps/web/src/lib/skfProject.ts +++ b/apps/web/src/lib/skfProject.ts @@ -11,7 +11,7 @@ import type { GridSize, ProjectAsset, ProjectAssetSourceFormat, SketchOperation, export const SKF_SCHEMA_ID = "com.sketchforge.project"; export const SKF_FORMAT_VERSION = 1; export const SKF_MINIMUM_READER_VERSION = 1; -export const SKF_CREATED_WITH_VERSION = "0.9.0"; +export const SKF_CREATED_WITH_VERSION = "1.0.0"; export const SKF_MEDIA_TYPE = "application/vnd.sketchforge.project+zip"; export const SKF_LIMITS = { diff --git a/apps/web/src/lib/stlExport.ts b/apps/web/src/lib/stlExport.ts new file mode 100644 index 0000000..454f1f9 --- /dev/null +++ b/apps/web/src/lib/stlExport.ts @@ -0,0 +1,41 @@ +import { sketchForgeToZUp, type MeshPoint } from "@/lib/meshCoordinates"; + +export type StlExportMesh = { + vertices: readonly MeshPoint[]; + faces: readonly (readonly [number, number, number])[]; +}; + +function normalFor(a: MeshPoint, b: MeshPoint, c: MeshPoint): [number, number, number] { + const ux = b[0] - a[0]; + const uy = b[1] - a[1]; + const uz = b[2] - a[2]; + const vx = c[0] - a[0]; + const vy = c[1] - a[1]; + const vz = c[2] - a[2]; + const nx = uy * vz - uz * vy; + const ny = uz * vx - ux * vz; + const nz = ux * vy - uy * vx; + const length = Math.hypot(nx, ny, nz) || 1; + return [nx / length, ny / length, nz / length]; +} + +export function exportMeshesToStl(meshes: readonly StlExportMesh[]) { + const lines = ["solid sketchforge_design"]; + meshes.forEach((mesh) => { + mesh.faces.forEach(([ai, bi, ci]) => { + const a = sketchForgeToZUp(mesh.vertices[ai]); + const b = sketchForgeToZUp(mesh.vertices[bi]); + const c = sketchForgeToZUp(mesh.vertices[ci]); + const n = normalFor(a, b, c); + lines.push(` facet normal ${n[0]} ${n[1]} ${n[2]}`); + lines.push(" outer loop"); + lines.push(` vertex ${a[0]} ${a[1]} ${a[2]}`); + lines.push(` vertex ${b[0]} ${b[1]} ${b[2]}`); + lines.push(` vertex ${c[0]} ${c[1]} ${c[2]}`); + lines.push(" endloop"); + lines.push(" endfacet"); + }); + }); + lines.push("endsolid sketchforge_design"); + return lines.join("\n"); +} diff --git a/apps/web/src/lib/stlImport.ts b/apps/web/src/lib/stlImport.ts index 9e546b6..254fb84 100644 --- a/apps/web/src/lib/stlImport.ts +++ b/apps/web/src/lib/stlImport.ts @@ -1,6 +1,7 @@ import * as THREE from "three"; import { STLLoader } from "three/examples/jsm/loaders/STLLoader.js"; import { createLocalId } from "@/lib/localIds"; +import { zUpToSketchForge } from "@/lib/meshCoordinates"; import type { WorkplaneShape } from "@/types/sketchforge"; const stlLoader = new STLLoader(); @@ -10,6 +11,34 @@ function fileExtension(fileName: string) { return fileName.split(".").pop()?.toLowerCase() ?? ""; } +function stlHeader(buffer: ArrayBuffer) { + return new TextDecoder("ascii").decode(new Uint8Array(buffer, 0, Math.min(80, buffer.byteLength))).toLowerCase(); +} + +function stlUsesSketchForgeYUp(buffer: ArrayBuffer, position: THREE.BufferAttribute | THREE.InterleavedBufferAttribute) { + // SketchForge's older ASCII STL exports were already Y-up. Preserve those, + // including tall models where geometry alone cannot reveal an up axis. + if (stlHeader(buffer).includes("sketchforge")) return true; + + let minY = Number.POSITIVE_INFINITY; + let maxY = Number.NEGATIVE_INFINITY; + let minZ = Number.POSITIVE_INFINITY; + let maxZ = Number.NEGATIVE_INFINITY; + for (let i = 0; i < position.count; i += 1) { + minY = Math.min(minY, position.getY(i)); + maxY = Math.max(maxY, position.getY(i)); + minZ = Math.min(minZ, position.getZ(i)); + maxZ = Math.max(maxZ, position.getZ(i)); + } + + const ySpan = maxY - minY; + const zSpan = maxZ - minZ; + // Some legacy/model-library STLs (including the Raspberry Pi fixture) are + // unmistakably flat on Y. Keep that established orientation; ambiguous STL + // files follow the slicer-standard Z-up convention. + return Number.isFinite(ySpan) && Number.isFinite(zSpan) && ySpan <= zSpan * 0.55; +} + export function importedShapeFromTriangleSoup( fileName: string, rawPositions: number[], @@ -97,11 +126,14 @@ export function importedShapeFromStl(fileName: string, buffer: ArrayBuffer): Wor const normal = geometry.getAttribute("normal"); const rawPositions: number[] = []; const rawNormals: number[] = []; + const usesSketchForgeYUp = stlUsesSketchForgeYUp(buffer, position); for (let i = 0; i < position.count; i += 1) { - rawPositions.push(position.getX(i), position.getY(i), position.getZ(i)); + const sourcePosition: [number, number, number] = [position.getX(i), position.getY(i), position.getZ(i)]; + rawPositions.push(...(usesSketchForgeYUp ? sourcePosition : zUpToSketchForge(sourcePosition))); if (normal) { - rawNormals.push(normal.getX(i), normal.getY(i), normal.getZ(i)); + const sourceNormal: [number, number, number] = [normal.getX(i), normal.getY(i), normal.getZ(i)]; + rawNormals.push(...(usesSketchForgeYUp ? sourceNormal : zUpToSketchForge(sourceNormal))); } } diff --git a/apps/web/src/workers/sketchCad.worker.ts b/apps/web/src/workers/sketchCad.worker.ts new file mode 100644 index 0000000..f0d3841 --- /dev/null +++ b/apps/web/src/workers/sketchCad.worker.ts @@ -0,0 +1,78 @@ +/// + +import { OcctKernel, type ShapeHandle } from "occt-wasm"; +import { cadSketchRegions, type OrderedCadSketchPath } from "@/lib/sketchCadProfile"; +import type { SketchCadBuildRequest, SketchCadBuildResponse } from "@/lib/sketchCadTypes"; + +let kernelPromise: Promise | null = null; + +function kernel() { + const moduleUrl = "/occt/occt-wasm.js"; + kernelPromise ??= import(/* webpackIgnore: true */ moduleUrl) + .then((imported: { default: (options?: { locateFile?: (path: string) => string }) => Promise }) => imported.default({ + locateFile: (path) => path.endsWith(".wasm") ? "/occt/occt-wasm.wasm" : path, + })) + .then((module) => { + const KernelConstructor = OcctKernel as unknown as new (rawModule: unknown) => OcctKernel; + return new KernelConstructor(module); + }); + return kernelPromise; +} + +function post(message: SketchCadBuildResponse, transfer: Transferable[] = []) { + self.postMessage(message, { transfer }); +} + +function pathWire(cad: OcctKernel, path: OrderedCadSketchPath) { + const edges = path.steps.map(({ segment, from, to }) => { + const forward = segment.startId === from.id; + const first = forward ? from.handleOut : from.handleIn; + const second = forward ? to.handleIn : to.handleOut; + if (segment.kind !== "line" && first && second) { + return cad.makeBezierEdge([ + { x: from.x, y: 0, z: from.z }, + { x: first.x, y: 0, z: first.z }, + { x: second.x, y: 0, z: second.z }, + { x: to.x, y: 0, z: to.z }, + ]); + } + return cad.makeLineEdge({ x: from.x, y: 0, z: from.z }, { x: to.x, y: 0, z: to.z }); + }); + return cad.makeWire(edges); +} + +self.onmessage = async (event: MessageEvent) => { + const request = event.data; + let cad: OcctKernel | null = null; + try { + cad = await kernel(); + cad.releaseAll(); + const regions = cadSketchRegions(request.profile); + if (regions.length === 0) throw new Error("No closed profile found. Draw at least one closed loop and ensure it has no degenerate (zero-area) geometry."); + const solids: ShapeHandle[] = regions.map((region) => { + let face = cad!.makeFace(pathWire(cad!, region.outer)); + if (region.holes.length > 0) face = cad!.addHolesInFace(face, region.holes.map((hole) => pathWire(cad!, hole))); + return cad!.extrude(face, 0, request.height, 0); + }); + const result = solids.length === 1 ? solids[0] : cad.makeCompound(solids); + if (!cad.isValid(result)) throw new Error("OpenCascade produced invalid sketch topology"); + const mesh = cad.tessellate(result, { linearDeflection: 0.05, angularDeflection: 0.16 }); + const positions = new Float32Array(mesh.positions); + const normals = new Float32Array(mesh.normals); + const indices = new Uint32Array(mesh.indices); + const brep = cad.toBREP(result); + post({ type: "built", requestId: request.requestId, positions, normals, indices, triangleCount: mesh.triangleCount, brep }, [positions.buffer, normals.buffer, indices.buffer]); + } catch (error) { + const message = error instanceof Error ? error.message : String(error ?? "The CAD kernel could not build this sketch"); + post({ type: "error", requestId: request.requestId, message }); + if (/memory|WebAssembly|abort/i.test(message)) kernelPromise = null; + } finally { + try { + cad?.releaseAll(); + } catch { + // The arena may already have reset after a kernel error. + } + } +}; + +export {}; diff --git a/deploy/docker/compose-ghcr.yaml b/deploy/docker/compose-ghcr.yaml index 2902a61..e916568 100644 --- a/deploy/docker/compose-ghcr.yaml +++ b/deploy/docker/compose-ghcr.yaml @@ -5,6 +5,9 @@ services: - "${SKETCHFORGE_PORT:-3000}:3000" environment: SKETCHFORGE_SHARED_PROJECTS_DIR: /data/projects + SKETCHFORGE_UPDATE_TRIGGER_URL: "${SKETCHFORGE_UPDATE_TRIGGER_URL:-}" + SKETCHFORGE_UPDATE_ADMIN_KEY: "${SKETCHFORGE_UPDATE_ADMIN_KEY:-}" + SKETCHFORGE_UPDATE_TRIGGER_TOKEN: "${SKETCHFORGE_UPDATE_TRIGGER_TOKEN:-}" volumes: - "${SKETCHFORGE_SHARED_PROJECTS_VOLUME:-sketchforge-shared-projects}:/data/projects" restart: unless-stopped diff --git a/deploy/docker/compose.yaml b/deploy/docker/compose.yaml index f2d9745..ab255e8 100644 --- a/deploy/docker/compose.yaml +++ b/deploy/docker/compose.yaml @@ -8,6 +8,9 @@ services: - "${SKETCHFORGE_PORT:-3000}:3000" environment: SKETCHFORGE_SHARED_PROJECTS_DIR: /data/projects + SKETCHFORGE_UPDATE_TRIGGER_URL: "${SKETCHFORGE_UPDATE_TRIGGER_URL:-}" + SKETCHFORGE_UPDATE_ADMIN_KEY: "${SKETCHFORGE_UPDATE_ADMIN_KEY:-}" + SKETCHFORGE_UPDATE_TRIGGER_TOKEN: "${SKETCHFORGE_UPDATE_TRIGGER_TOKEN:-}" volumes: - "${SKETCHFORGE_SHARED_PROJECTS_VOLUME:-sketchforge-shared-projects}:/data/projects" restart: unless-stopped diff --git a/package-lock.json b/package-lock.json index f3e974d..3d61e43 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,13 +1,13 @@ { "name": "sketchforge", - "version": "0.9.0", + "version": "1.0.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "sketchforge", - "version": "0.9.0", - "license": "MIT", + "version": "1.0.0", + "license": "AGPL-3.0-only", "dependencies": { "@tailwindcss/postcss": "^4.1.8", "@types/three": "^0.184.1", diff --git a/package.json b/package.json index fd74175..5929865 100644 --- a/package.json +++ b/package.json @@ -1,8 +1,8 @@ { "name": "sketchforge", - "version": "0.9.0", + "version": "1.0.0", "private": true, - "license": "MIT", + "license": "AGPL-3.0-only", "scripts": { "copy:occt": "node scripts/copy-occt-wasm.mjs", "predev": "npm run copy:occt", diff --git a/tests/e2e/sketchCadExtrusion.e2e.ts b/tests/e2e/sketchCadExtrusion.e2e.ts new file mode 100644 index 0000000..f62bb52 --- /dev/null +++ b/tests/e2e/sketchCadExtrusion.e2e.ts @@ -0,0 +1,206 @@ +import { beforeAll, describe, expect, it, vi } from "vitest"; +import { fileURLToPath } from "node:url"; +import { dirname, join } from "node:path"; +import type { SketchProfile } from "@/types/sketchforge"; + +// Load the real OCCT kernel directly (same approach as stepRoundTrip.e2e.ts). +vi.mock("@/lib/brepKernel", async () => { + const brep = await import("brepjs"); + const { OcctKernel } = await import("occt-wasm"); + const wasm = join(dirname(fileURLToPath(import.meta.resolve("occt-wasm"))), "occt-wasm.wasm"); + let ready: Promise | null = null; + return { + loadBrepWithOcct: () => + (ready ??= (async () => { + const kernel = await OcctKernel.init({ wasm }); + brep.registerKernel("occt-wasm", brep.OcctWasmAdapter.fromKernel(kernel)); + return brep; + })()), + }; +}); + +let cadSketchRegions: typeof import("@/lib/sketchCadProfile").cadSketchRegions; + +beforeAll(async () => { + ({ cadSketchRegions } = await import("@/lib/sketchCadProfile")); +}); + +function rectangle(id: string, x: number, z: number, width: number, depth: number): SketchProfile { + const points = [ + { id: `${id}-0`, x, z }, + { id: `${id}-1`, x: x + width, z }, + { id: `${id}-2`, x: x + width, z: z + depth }, + { id: `${id}-3`, x, z: z + depth }, + ]; + const segments = points.map((point, index) => ({ + id: `${id}-s${index}`, + kind: "line" as const, + startId: point.id, + endId: points[(index + 1) % points.length].id, + })); + return { points, segments }; +} + +function mergeProfiles(...profiles: SketchProfile[]): SketchProfile { + return { + points: profiles.flatMap((p) => p.points), + segments: profiles.flatMap((p) => p.segments), + }; +} + +describe("Sketch CAD profile → B-Rep extrusion (real OCCT kernel)", () => { + it("produces valid B-Rep from a single closed rectangle", async () => { + const { OcctKernel } = await import("occt-wasm"); + const profile = rectangle("rect", 0, 0, 20, 10); + const regions = cadSketchRegions(profile); + expect(regions).toHaveLength(1); + expect(regions[0].outer.closed).toBe(true); + expect(regions[0].holes).toHaveLength(0); + + const wasm = join(dirname(fileURLToPath(import.meta.resolve("occt-wasm"))), "occt-wasm.wasm"); + const kernel = await OcctKernel.init({ wasm }); + + const edges = regions[0].outer.steps.map(({ from, to }) => + kernel.makeLineEdge({ x: from.x, y: 0, z: from.z }, { x: to.x, y: 0, z: to.z }), + ); + const wire = kernel.makeWire(edges); + const face = kernel.makeFace(wire); + const solid = kernel.extrude(face, 0, 15, 0); + expect(kernel.isValid(solid)).toBe(true); + expect(kernel.isSolid(solid)).toBe(true); + + const mesh = kernel.tessellate(solid, { linearDeflection: 0.05, angularDeflection: 0.16 }); + expect(mesh.triangleCount).toBeGreaterThan(0); + expect(mesh.positions.length).toBeGreaterThanOrEqual(9); + expect(mesh.indices.length).toBeGreaterThanOrEqual(3); + + const brep = kernel.toBREP(solid); + expect(brep).toBeTruthy(); + expect(brep.length).toBeGreaterThan(0); + kernel.releaseAll(); + }); + + it("extrudes a rectangle with a hole into a valid hollow solid", async () => { + const { OcctKernel } = await import("occt-wasm"); + const profile = mergeProfiles( + rectangle("outer", 0, 0, 40, 40), + rectangle("hole", 10, 10, 20, 20), + ); + const regions = cadSketchRegions(profile); + expect(regions).toHaveLength(1); + expect(regions[0].holes).toHaveLength(1); + + const wasm = join(dirname(fileURLToPath(import.meta.resolve("occt-wasm"))), "occt-wasm.wasm"); + const kernel = await OcctKernel.init({ wasm }); + + const outerEdges = regions[0].outer.steps.map(({ from, to }) => + kernel.makeLineEdge({ x: from.x, y: 0, z: from.z }, { x: to.x, y: 0, z: to.z }), + ); + const outerWire = kernel.makeWire(outerEdges); + let face = kernel.makeFace(outerWire); + + const holeEdges = regions[0].holes[0].steps.map(({ from, to }) => + kernel.makeLineEdge({ x: from.x, y: 0, z: from.z }, { x: to.x, y: 0, z: to.z }), + ); + const holeWire = kernel.makeWire(holeEdges); + face = kernel.addHolesInFace(face, [holeWire]); + + const solid = kernel.extrude(face, 0, 10, 0); + expect(kernel.isValid(solid)).toBe(true); + expect(kernel.isSolid(solid)).toBe(true); + + const mesh = kernel.tessellate(solid, { linearDeflection: 0.05, angularDeflection: 0.16 }); + expect(mesh.triangleCount).toBeGreaterThan(0); + kernel.releaseAll(); + }); + + it("produces two separate solids from disjoint rectangles", async () => { + const { OcctKernel } = await import("occt-wasm"); + const profile = mergeProfiles( + rectangle("left", 0, 0, 10, 10), + rectangle("right", 20, 0, 10, 10), + ); + const regions = cadSketchRegions(profile); + expect(regions).toHaveLength(2); + + const wasm = join(dirname(fileURLToPath(import.meta.resolve("occt-wasm"))), "occt-wasm.wasm"); + const kernel = await OcctKernel.init({ wasm }); + + const solids = regions.map((region) => { + const edges = region.outer.steps.map(({ from, to }) => + kernel.makeLineEdge({ x: from.x, y: 0, z: from.z }, { x: to.x, y: 0, z: to.z }), + ); + const wire = kernel.makeWire(edges); + const face = kernel.makeFace(wire); + return kernel.extrude(face, 0, 5, 0); + }); + + const compound = kernel.makeCompound(solids); + expect(kernel.isValid(compound)).toBe(true); + + const mesh = kernel.tessellate(compound, { linearDeflection: 0.05, angularDeflection: 0.16 }); + expect(mesh.triangleCount).toBeGreaterThan(0); + kernel.releaseAll(); + }); + + it("extrudes a profile with an island inside a hole", async () => { + const { OcctKernel } = await import("occt-wasm"); + const profile = mergeProfiles( + rectangle("outer", 0, 0, 40, 40), + rectangle("hole", 5, 5, 30, 30), + rectangle("island", 12, 12, 16, 16), + ); + const regions = cadSketchRegions(profile); + expect(regions).toHaveLength(2); + + const outerRegion = regions.find((r) => r.outer.id.includes("outer")); + const islandRegion = regions.find((r) => r.outer.id.includes("island")); + expect(outerRegion).toBeDefined(); + expect(islandRegion).toBeDefined(); + expect(outerRegion!.holes).toHaveLength(1); + expect(islandRegion!.holes).toHaveLength(0); + + const wasm = join(dirname(fileURLToPath(import.meta.resolve("occt-wasm"))), "occt-wasm.wasm"); + const kernel = await OcctKernel.init({ wasm }); + + const buildSolid = (region: { outer: typeof regions[0]["outer"]; holes: typeof regions[0]["holes"] }) => { + const outerEdges = region.outer.steps.map(({ from, to }) => + kernel.makeLineEdge({ x: from.x, y: 0, z: from.z }, { x: to.x, y: 0, z: to.z }), + ); + let face = kernel.makeFace(kernel.makeWire(outerEdges)); + if (region.holes.length > 0) { + const holeWires = region.holes.map((hole) => { + const holeEdges = hole.steps.map(({ from, to }) => + kernel.makeLineEdge({ x: from.x, y: 0, z: from.z }, { x: to.x, y: 0, z: to.z }), + ); + return kernel.makeWire(holeEdges); + }); + face = kernel.addHolesInFace(face, holeWires); + } + return kernel.extrude(face, 0, 8, 0); + }; + + const solids = regions.map(buildSolid); + const compound = kernel.makeCompound(solids); + expect(kernel.isValid(compound)).toBe(true); + + const mesh = kernel.tessellate(compound, { linearDeflection: 0.05, angularDeflection: 0.16 }); + expect(mesh.triangleCount).toBeGreaterThan(0); + kernel.releaseAll(); + }); + + it("rejects a profile with only open paths", () => { + const openProfile: SketchProfile = { + points: [ + { id: "a-0", x: 0, z: 0 }, + { id: "a-1", x: 10, z: 0 }, + { id: "a-2", x: 10, z: 10 }, + ], + segments: [ + { id: "a-s0", kind: "line", startId: "a-0", endId: "a-1" }, + { id: "a-s1", kind: "line", startId: "a-1", endId: "a-2" }, + ], + }; + expect(() => cadSketchRegions(openProfile)).toThrow(/open/i); + }); +}); diff --git a/tests/unit/appUpdates.test.ts b/tests/unit/appUpdates.test.ts new file mode 100644 index 0000000..ebe426d --- /dev/null +++ b/tests/unit/appUpdates.test.ts @@ -0,0 +1,21 @@ +import { describe, expect, it } from "vitest"; +import { appUpdateIsAvailable, compareAppVersions } from "@/lib/appUpdates"; + +describe("application update versions", () => { + it("orders semantic releases numerically", () => { + expect(compareAppVersions("0.10.0", "0.9.9")).toBeGreaterThan(0); + expect(compareAppVersions("1.0.0", "0.99.99")).toBeGreaterThan(0); + expect(compareAppVersions("v1.0.0", "1.0.0")).toBe(0); + }); + + it("keeps prereleases below their stable release", () => { + expect(compareAppVersions("1.0.0-beta.2", "1.0.0-beta.1")).toBeGreaterThan(0); + expect(compareAppVersions("1.0.0", "1.0.0-rc.1")).toBeGreaterThan(0); + }); + + it("only offers a strictly newer version", () => { + expect(appUpdateIsAvailable("1.0.0", "1.0.1")).toBe(true); + expect(appUpdateIsAvailable("1.0.0", "1.0.0")).toBe(false); + expect(appUpdateIsAvailable("1.0.0", "0.9.9")).toBe(false); + }); +}); diff --git a/tests/unit/challenges.test.ts b/tests/unit/challenges.test.ts new file mode 100644 index 0000000..0f4fa45 --- /dev/null +++ b/tests/unit/challenges.test.ts @@ -0,0 +1,15 @@ +import { describe, expect, it } from "vitest"; +import { CHALLENGE_TUTORIAL_IDS, isChallengeTutorialId } from "@/lib/challenges"; + +describe("challenge tutorial ids", () => { + it("recognizes every supported challenge", () => { + expect(CHALLENGE_TUTORIAL_IDS).toEqual(["key-tag", "nameplate"]); + expect(CHALLENGE_TUTORIAL_IDS.every(isChallengeTutorialId)).toBe(true); + }); + + it("rejects stale or malformed stored values", () => { + expect(isChallengeTutorialId("phone-stand")).toBe(false); + expect(isChallengeTutorialId(null)).toBe(false); + expect(isChallengeTutorialId({ tutorial: "nameplate" })).toBe(false); + }); +}); diff --git a/tests/unit/meshCoordinates.test.ts b/tests/unit/meshCoordinates.test.ts new file mode 100644 index 0000000..a8fd74f --- /dev/null +++ b/tests/unit/meshCoordinates.test.ts @@ -0,0 +1,12 @@ +import { describe, expect, it } from "vitest"; +import { sketchForgeToZUp, zUpToSketchForge } from "@/lib/meshCoordinates"; + +describe("mesh coordinate conventions", () => { + it("maps slicer Z-up coordinates to SketchForge Y-up and back", () => { + const slicerPoint: [number, number, number] = [12, 34, 56]; + const sketchForgePoint = zUpToSketchForge(slicerPoint); + + expect(sketchForgePoint).toEqual([12, 56, -34]); + expect(sketchForgeToZUp(sketchForgePoint)).toEqual(slicerPoint); + }); +}); diff --git a/tests/unit/objExport.test.ts b/tests/unit/objExport.test.ts new file mode 100644 index 0000000..8b574d6 --- /dev/null +++ b/tests/unit/objExport.test.ts @@ -0,0 +1,43 @@ +import { describe, expect, it } from "vitest"; +import { exportMeshesToObj, type ObjExportMesh } from "@/lib/objExport"; + +function duplicatedTetrahedron(): ObjExportMesh { + const a: [number, number, number] = [0, 0, 0]; + const b: [number, number, number] = [10, 0, 0]; + const c: [number, number, number] = [0, 10, 0]; + const d: [number, number, number] = [0, 0, 10]; + return { + name: "closed_tetrahedron", + vertices: [a, c, b, a, b, d, b, c, d, c, a, d], + faces: [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11]], + }; +} + +describe("OBJ export", () => { + it("preserves OBJ's conventional Y-up coordinates", () => { + const obj = exportMeshesToObj([duplicatedTetrahedron()]); + const vertices = obj.split("\n").filter((line) => line.startsWith("v ")); + + expect(vertices).toContain("v 0 0 10"); + expect(vertices).toContain("v 0 10 0"); + }); + + it("welds coincident triangle vertices so a closed mesh has no boundary edges", () => { + const obj = exportMeshesToObj([duplicatedTetrahedron()]); + const vertices = obj.split("\n").filter((line) => line.startsWith("v ")); + const faces = obj.split("\n").filter((line) => line.startsWith("f ")); + const edgeUse = new Map(); + + faces.forEach((line) => { + const [a, b, c] = line.slice(2).trim().split(/\s+/).map(Number); + [[a, b], [b, c], [c, a]].forEach(([start, end]) => { + const key = start < end ? `${start}:${end}` : `${end}:${start}`; + edgeUse.set(key, (edgeUse.get(key) ?? 0) + 1); + }); + }); + + expect(vertices).toHaveLength(4); + expect(faces).toHaveLength(4); + expect([...edgeUse.values()].every((count) => count === 2)).toBe(true); + }); +}); diff --git a/tests/unit/sketchCadProfile.test.ts b/tests/unit/sketchCadProfile.test.ts new file mode 100644 index 0000000..4d882e8 --- /dev/null +++ b/tests/unit/sketchCadProfile.test.ts @@ -0,0 +1,118 @@ +import { describe, expect, it } from "vitest"; +import { cadSketchRegions, orderedCadSketchPaths } from "@/lib/sketchCadProfile"; +import type { SketchPoint, SketchProfile, SketchSegment } from "@/types/sketchforge"; + +function rectangle(id: string, x: number, z: number, width: number, depth: number) { + const points: SketchPoint[] = [ + { id: `${id}-0`, x, z }, + { id: `${id}-1`, x: x + width, z }, + { id: `${id}-2`, x: x + width, z: z + depth }, + { id: `${id}-3`, x, z: z + depth }, + ]; + const segments: SketchSegment[] = points.map((point, index) => ({ + id: `${id}-s${index}`, + kind: "line", + startId: point.id, + endId: points[(index + 1) % points.length].id, + })); + return { points, segments }; +} + +function profile(...rectangles: ReturnType[]): SketchProfile { + return { + points: rectangles.flatMap((rectangle) => rectangle.points), + segments: rectangles.flatMap((rectangle) => rectangle.segments), + }; +} + +describe("OCCT sketch profile preparation", () => { + it("orders a closed loop even when its segments arrive out of order", () => { + const square = rectangle("outer", 0, 0, 20, 10); + const paths = orderedCadSketchPaths({ ...profile(square), segments: [...square.segments].reverse() }); + expect(paths).toHaveLength(1); + expect(paths[0].closed).toBe(true); + expect(paths[0].steps).toHaveLength(4); + }); + + it("assigns an enclosed loop as a hole", () => { + const regions = cadSketchRegions(profile( + rectangle("outer", 0, 0, 20, 20), + rectangle("hole", 5, 5, 4, 4), + )); + expect(regions).toHaveLength(1); + expect(regions[0].outer.id).toContain("outer"); + expect(regions[0].holes).toHaveLength(1); + }); + + it("keeps disjoint loops as separate solids", () => { + const regions = cadSketchRegions(profile( + rectangle("left", 0, 0, 4, 4), + rectangle("right", 10, 0, 4, 4), + )); + expect(regions).toHaveLength(2); + expect(regions.every((region) => region.holes.length === 0)).toBe(true); + }); + + it("rejects open paths with a clear error", () => { + const square = rectangle("open", 0, 0, 10, 10); + square.segments.pop(); + expect(() => cadSketchRegions(profile(square))).toThrow(/open/i); + }); + + it("creates a solid island inside a hole (3-level nesting)", () => { + const regions = cadSketchRegions(profile( + rectangle("outer", 0, 0, 40, 40), + rectangle("hole", 5, 5, 30, 30), + rectangle("island", 12, 12, 16, 16), + )); + expect(regions).toHaveLength(2); + const outerRegion = regions.find((r) => r.outer.id.includes("outer")); + const islandRegion = regions.find((r) => r.outer.id.includes("island")); + expect(outerRegion).toBeDefined(); + expect(outerRegion!.holes).toHaveLength(1); + expect(outerRegion!.holes[0].id).toContain("hole"); + expect(islandRegion).toBeDefined(); + expect(islandRegion!.holes).toHaveLength(0); + }); + + it("handles 4-level nesting (outer > hole > island > island-hole)", () => { + const regions = cadSketchRegions(profile( + rectangle("outer", 0, 0, 60, 60), + rectangle("hole", 5, 5, 50, 50), + rectangle("island", 15, 15, 30, 30), + rectangle("ihole", 20, 20, 20, 20), + )); + const outerRegion = regions.find((r) => r.outer.id.includes("outer")); + const islandRegion = regions.find((r) => r.outer.id.includes("island")); + expect(outerRegion).toBeDefined(); + expect(outerRegion!.holes).toHaveLength(1); + expect(outerRegion!.holes[0].id).toContain("hole"); + expect(islandRegion).toBeDefined(); + expect(islandRegion!.holes).toHaveLength(1); + expect(islandRegion!.holes[0].id).toContain("ihole"); + }); + + it("throws when all paths are open", () => { + const open1 = rectangle("a", 0, 0, 10, 10); + open1.segments.pop(); + const open2 = rectangle("b", 20, 0, 10, 10); + open2.segments.pop(); + expect(() => cadSketchRegions(profile(open1, open2))).toThrow(/open/i); + }); + + it("returns empty for a single degenerate zero-area path", () => { + const degenerate: SketchProfile = { + points: [ + { id: "d-0", x: 0, z: 0 }, + { id: "d-1", x: 1, z: 0 }, + { id: "d-2", x: 0, z: 0 }, + ], + segments: [ + { id: "d-s0", kind: "line", startId: "d-0", endId: "d-1" }, + { id: "d-s1", kind: "line", startId: "d-1", endId: "d-2" }, + { id: "d-s2", kind: "line", startId: "d-2", endId: "d-0" }, + ], + }; + expect(cadSketchRegions(degenerate)).toEqual([]); + }); +}); diff --git a/tests/unit/stlExport.test.ts b/tests/unit/stlExport.test.ts new file mode 100644 index 0000000..c3244ca --- /dev/null +++ b/tests/unit/stlExport.test.ts @@ -0,0 +1,13 @@ +import { describe, expect, it } from "vitest"; +import { exportMeshesToStl } from "@/lib/stlExport"; + +describe("STL export orientation", () => { + it("writes editor Y-up coordinates as slicer Z-up coordinates", () => { + const stl = exportMeshesToStl([{ + vertices: [[0, 0, 0], [10, 0, 0], [0, 20, 5]], + faces: [[0, 1, 2]], + }]); + + expect(stl).toContain("vertex 0 -5 20"); + }); +}); diff --git a/tests/unit/stlImportOrientation.test.ts b/tests/unit/stlImportOrientation.test.ts new file mode 100644 index 0000000..1981560 --- /dev/null +++ b/tests/unit/stlImportOrientation.test.ts @@ -0,0 +1,48 @@ +import { describe, expect, it } from "vitest"; +import { importedShapeFromStl } from "@/lib/stlImport"; + +function boxStl(width: number, ySize: number, zSize: number, name = "box") { + const vertices = [ + [0, 0, 0], [width, 0, 0], [width, ySize, 0], [0, ySize, 0], + [0, 0, zSize], [width, 0, zSize], [width, ySize, zSize], [0, ySize, zSize], + ]; + const faces = [ + [0, 2, 1], [0, 3, 2], [4, 5, 6], [4, 6, 7], + [0, 1, 5], [0, 5, 4], [1, 2, 6], [1, 6, 5], + [2, 3, 7], [2, 7, 6], [3, 0, 4], [3, 4, 7], + ]; + const facets = faces.map(([a, b, c]) => `facet normal 0 0 0 + outer loop + vertex ${vertices[a].join(" ")} + vertex ${vertices[b].join(" ")} + vertex ${vertices[c].join(" ")} + endloop +endfacet`).join("\n"); + const source = `solid ${name}\n${facets}\nendsolid ${name}`; + return new TextEncoder().encode(source).buffer; +} + +describe("STL import orientation", () => { + it("maps a clearly Z-up slicer model to SketchForge Y-up", () => { + const shape = importedShapeFromStl("z-up-box.stl", boxStl(80, 60, 20)); + + expect(shape.importedMesh?.baseWidth).toBeCloseTo(80); + expect(shape.importedMesh?.baseHeight).toBeCloseTo(20); + expect(shape.importedMesh?.baseDepth).toBeCloseTo(60); + }); + + it("preserves an unmistakably flat Y-up legacy model", () => { + const shape = importedShapeFromStl("raspberry-pi-like.stl", boxStl(89, 20, 58)); + + expect(shape.importedMesh?.baseWidth).toBeCloseTo(89); + expect(shape.importedMesh?.baseHeight).toBeCloseTo(20); + expect(shape.importedMesh?.baseDepth).toBeCloseTo(58); + }); + + it("preserves previous SketchForge STL exports regardless of proportions", () => { + const shape = importedShapeFromStl("legacy-sketchforge.stl", boxStl(20, 80, 10, "sketchforge_design")); + + expect(shape.importedMesh?.baseHeight).toBeCloseTo(80); + expect(shape.importedMesh?.baseDepth).toBeCloseTo(10); + }); +});