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

+ Shapic + Shapic +

+ +SNS 플랫폼에 최적화된 이미지 리사이즈 & 최적화 데스크톱 앱 + +## 왜 만들었나 + +고화소 사진을 Instagram 등 SNS에 그대로 올리면 플랫폼의 자동 압축과 리사이즈로 화질이 뭉개집니다. 업로드 전에 플랫폼 규격에 맞게 직접 리사이즈하면 화질 저하를 최소화할 수 있지만, 이를 위해 매번 Photoshop 같은 무거운 도구를 실행하는 건 비효율적입니다. Shapic은 드래그 앤 드롭만으로 SNS 최적화 리사이즈를 완료할 수 있도록 설계된 경량 데스크톱 앱입니다. + +![Shapic 스크린샷](https://github.com/user-attachments/assets/d5e47772-d508-4124-a7f9-35af62e4e046) + +## 주요 기능 + +- **SNS 프리셋** — Instagram, Facebook, X(Twitter), YouTube, TikTok, LinkedIn 등 33개 내장 프리셋 +- **커스텀 프리셋** — 원하는 크기/포맷/품질로 직접 프리셋 생성 +- **다양한 리사이즈 모드** — 프리셋 맞춤(Cover/Contain), 비율 유지, 긴쪽/짧은쪽/너비/높이 기준 +- **EXIF 프레임** — 카메라·렌즈·촬영 정보를 미니멀 화이트 프레임으로 자동 삽입 +- **일괄 처리** — 여러 이미지를 한 번에 변환, 실시간 진행률 표시 +- **실시간 미리보기** — 설정 변경 시 결과물 즉시 확인, 압축률 표시 +- **포맷 변환** — JPEG(mozjpeg) / WebP 출력, 품질 조절 가능 +- **다양한 입력 포맷** — JPG, PNG, WebP, HEIF, HEIC, TIFF 지원 + +## 다운로드 + +| 플랫폼 | 다운로드 | +| --------------------- | -------------------------------------------------------------- | +| macOS (Apple Silicon) | [다운로드](https://github.com/devlasbe/shapic/releases/latest/download/Shapic-arm64.dmg) | +| macOS (Intel) | [다운로드](https://github.com/devlasbe/shapic/releases/latest/download/Shapic-x64.dmg) | +| Windows | [다운로드](https://github.com/devlasbe/shapic/releases/latest/download/Shapic-Setup.exe) | + +## macOS 설치 안내 + +현재 Shapic은 Apple 공증을 받지 않은 상태이므로, 처음 실행 시 보안 경고가 표시됩니다. + +1. 다운로드한 `.dmg` 파일을 열고 Shapic을 Applications 폴더로 드래그 +2. Shapic을 실행하면 **"확인할 수 없는 개발자"** 경고가 표시됨 +3. **시스템 설정 → 개인정보 보호 및 보안** 으로 이동 +4. 하단의 **"그래도 열기"** 버튼 클릭 +5. 이후부터는 정상적으로 실행됩니다 + +## 사용법 + +### 1. 이미지 불러오기 + +앱 중앙 영역에 이미지를 드래그 앤 드롭하거나, 클릭하여 파일을 선택합니다. + +### 2. 설정 + +우측 패널에서 리사이즈 옵션을 설정합니다. + +1. **프리셋 선택** — SNS 플랫폼별 프리셋 또는 커스텀 프리셋 +2. **리사이즈 모드** — 프리셋 맞춤(Cover/Contain), 비율 유지 등 +3. **출력 포맷** — JPEG 또는 WebP, 품질 슬라이더로 조절 +4. **EXIF 프레임** — 촬영 정보가 있는 이미지에 자동 프레임 적용 +5. **출력 폴더** — 변환된 이미지가 저장될 위치 선택 + +### 3. 변환 + +- **단일 변환** — 선택한 이미지 1장만 변환 +- **일괄 변환** — 불러온 모든 이미지를 한 번에 변환 + +## 기술 스택 + +| 분류 | 기술 | +| ------------- | ------------------------------- | +| 프레임워크 | Electron 41 | +| 프론트엔드 | React 19, TypeScript | +| 스타일링 | Tailwind CSS 4 | +| 상태 관리 | Zustand | +| 이미지 처리 | Sharp | +| EXIF 파싱 | exif-reader | +| 빌드 | Electron Vite, Electron Builder | +| 패키지 매니저 | pnpm | + +## 로컬 실행 + +### 요구 사항 + +- Node.js 22+ +- pnpm + +### 설치 및 실행 + +```bash +# 저장소 클론 +git clone https://github.com/devlasbe/shapic.git +cd shapic + +# 의존성 설치 +pnpm install + +# 개발 모드 실행 +pnpm dev +``` + +### 빌드 & 패키징 + +```bash +# 프로덕션 빌드 +pnpm build + +# 앱 패키징 (dmg / exe) +pnpm package +``` + +## 프로젝트 구조 + +``` +src/ +├── main/ # Electron 메인 프로세스 +│ ├── ipc/ # IPC 핸들러 (이미지, 프리셋, 다이얼로그) +│ └── services/ # 이미지 처리, EXIF 파싱, 프레임 렌더링 +├── preload/ # Preload 스크립트 (API 브릿지) +├── renderer/ # React 프론트엔드 +│ └── src/ +│ ├── components/ # UI 컴포넌트 (레이아웃, 설정, 프리뷰 등) +│ ├── hooks/ # 커스텀 훅 +│ ├── presets/ # 기본 프리셋 정의 +│ ├── stores/ # Zustand 상태 관리 +│ ├── types/ # 타입 정의 +│ └── utils/ # 유틸리티 +└── shared/ # 메인/렌더러 공유 모듈 (타입, 상수, 프리셋) +``` + +## 라이선스 + +이 프로젝트는 [GPL-3.0 라이선스](./LICENSE)로 배포됩니다. diff --git a/electron-builder.yml b/electron-builder.yml index ff479cb..b55f62d 100644 --- a/electron-builder.yml +++ b/electron-builder.yml @@ -1,5 +1,6 @@ -appId: com.imageforge.app -productName: ImageForge +appId: com.shapic.app +productName: Shapic +copyright: Copyright © 2026 lasbe directories: buildResources: resources output: dist @@ -13,14 +14,9 @@ asarUnpack: mac: target: - dmg - - zip category: public.app-category.graphics-design - artifactName: "${productName}-${version}-${arch}.${ext}" + artifactName: "${productName}-${arch}.${ext}" win: target: - nsis - - portable -linux: - target: - - AppImage - - deb + artifactName: "${productName}-Setup.${ext}" diff --git a/package.json b/package.json index 8982450..d5f9334 100644 --- a/package.json +++ b/package.json @@ -1,5 +1,6 @@ { - "name": "imageforge", + "name": "shapic", + "productName": "Shapic", "version": "1.0.0", "description": "Image resize & optimize desktop app for SNS platforms", "type": "module", @@ -16,8 +17,12 @@ "electron", "sharp" ], - "author": "", - "license": "ISC", + "author": { + "name": "lasbe", + "email": "devlasbe@gmail.com", + "url": "https://lasbe.kr" + }, + "license": "GPL-3.0", "dependencies": { "clsx": "^2.1.1", "electron-store": "^11.0.2", diff --git a/resources/icon.icns b/resources/icon.icns new file mode 100644 index 0000000..6eba98d Binary files /dev/null and b/resources/icon.icns differ diff --git a/resources/icon.png b/resources/icon.png new file mode 100644 index 0000000..ccff251 Binary files /dev/null and b/resources/icon.png differ diff --git a/src/main/index.ts b/src/main/index.ts index 5e6bb29..588b2ee 100644 --- a/src/main/index.ts +++ b/src/main/index.ts @@ -1,8 +1,10 @@ -import { app, BrowserWindow, shell, protocol, net } from 'electron' -import { join } from 'path' -import { registerAllIpcHandlers } from './ipc/index.js' +import { app, BrowserWindow, shell, protocol, net, Menu, nativeImage } from "electron"; +import { join } from "path"; +import { registerAllIpcHandlers } from "./ipc/index.js"; -let mainWindow: BrowserWindow | null = null +app.name = "Shapic"; + +let mainWindow: BrowserWindow | null = null; const createWindow = () => { mainWindow = new BrowserWindow({ @@ -10,53 +12,122 @@ const createWindow = () => { height: 800, minWidth: 900, minHeight: 600, - title: 'ImageForge', - titleBarStyle: 'hiddenInset', + title: "Shapic", + icon: join(__dirname, "../../resources/icon.png"), + titleBarStyle: "hiddenInset", trafficLightPosition: { x: 12, y: 14 }, webPreferences: { - preload: join(__dirname, '../preload/index.js'), + preload: join(__dirname, "../preload/index.mjs"), nodeIntegration: false, contextIsolation: true, sandbox: false, - webSecurity: true - } - }) + webSecurity: true, + }, + }); - mainWindow.on('ready-to-show', () => { - mainWindow?.show() - }) + mainWindow.on("ready-to-show", () => { + mainWindow?.show(); + }); mainWindow.webContents.setWindowOpenHandler((details) => { - shell.openExternal(details.url) - return { action: 'deny' } - }) + shell.openExternal(details.url); + return { action: "deny" }; + }); - if (!app.isPackaged && process.env['ELECTRON_RENDERER_URL']) { - mainWindow.loadURL(process.env['ELECTRON_RENDERER_URL']) + if (!app.isPackaged && process.env["ELECTRON_RENDERER_URL"]) { + mainWindow.loadURL(process.env["ELECTRON_RENDERER_URL"]); } else { - mainWindow.loadFile(join(__dirname, '../renderer/index.html')) + mainWindow.loadFile(join(__dirname, "../renderer/index.html")); } -} +}; app.whenReady().then(() => { // file:// 프로토콜로 로컬 이미지 접근 허용 - protocol.handle('local-file', (request) => { - const filePath = decodeURIComponent(request.url.replace('local-file://', '')) - return net.fetch(`file://${filePath}`) - }) + protocol.handle("local-file", (request) => { + const filePath = decodeURIComponent(request.url.replace("local-file://", "")); + return net.fetch(`file://${filePath}`); + }); + + // 앱 아이콘 경로 + const iconPath = join(__dirname, "../../resources/icon.png"); + + // macOS dock 아이콘 설정 (dev 모드에서도 적용) + if (process.platform === "darwin") { + app.dock?.setIcon(nativeImage.createFromPath(iconPath)); + } + + // macOS About 패널 설정 + app.setAboutPanelOptions({ + applicationName: "Shapic", + applicationVersion: app.getVersion(), + copyright: "Copyright © 2026 lasbe", + credits: "devlasbe@gmail.com\nhttps://lasbe.kr", + website: "https://lasbe.kr", + }); + + // macOS 앱 메뉴 구성 + if (process.platform === "darwin") { + const template: Electron.MenuItemConstructorOptions[] = [ + { + label: app.name, + submenu: [ + { role: "about" }, + { type: "separator" }, + { role: "services" }, + { type: "separator" }, + { role: "hide" }, + { role: "hideOthers" }, + { role: "unhide" }, + { type: "separator" }, + { role: "quit" }, + ], + }, + { + label: "Edit", + submenu: [ + { role: "undo" }, + { role: "redo" }, + { type: "separator" }, + { role: "cut" }, + { role: "copy" }, + { role: "paste" }, + { role: "selectAll" }, + ], + }, + { + label: "View", + submenu: [ + { role: "reload" }, + { role: "forceReload" }, + { role: "toggleDevTools" }, + { type: "separator" }, + { role: "resetZoom" }, + { role: "zoomIn" }, + { role: "zoomOut" }, + { type: "separator" }, + { role: "togglefullscreen" }, + ], + }, + { + label: "Window", + submenu: [{ role: "minimize" }, { role: "zoom" }, { type: "separator" }, { role: "front" }], + }, + ]; + Menu.setApplicationMenu(Menu.buildFromTemplate(template)); + } - registerAllIpcHandlers() - createWindow() + registerAllIpcHandlers(); + createWindow(); - app.on('activate', () => { + app.on("activate", () => { if (BrowserWindow.getAllWindows().length === 0) { - createWindow() + createWindow(); } - }) -}) + }); +}); -app.on('window-all-closed', () => { - if (process.platform !== 'darwin') { - app.quit() +app.on("window-all-closed", () => { + if (process.platform !== "darwin") { + app.quit(); } -}) +}); diff --git a/src/main/ipc/dialog.ts b/src/main/ipc/dialog.ts index 0b1d2af..00cc562 100644 --- a/src/main/ipc/dialog.ts +++ b/src/main/ipc/dialog.ts @@ -1,6 +1,5 @@ import { ipcMain, dialog, BrowserWindow } from 'electron' - -const SUPPORTED_EXTENSIONS = ['jpg', 'jpeg', 'png', 'webp', 'heif', 'heic', 'tiff', 'tif'] +import { SUPPORTED_EXTENSIONS } from '../../shared/constants.js' export const registerDialogHandlers = () => { ipcMain.handle('dialog:openFile', async (event) => { diff --git a/src/main/ipc/image.ts b/src/main/ipc/image.ts index 338eb4d..ce63388 100644 --- a/src/main/ipc/image.ts +++ b/src/main/ipc/image.ts @@ -1,56 +1,14 @@ import { ipcMain, BrowserWindow } from 'electron' import { loadImageMetadata, processBatch, generatePreview } from '../services/image-processor.js' import { getCustomPresets } from '../services/preset-store.js' - -type PresetLookupType = { - id: string - width: number - height: number | null - format: 'jpeg' | 'webp' - quality: number -} - -// 내장 프리셋을 main process에서도 참조 (renderer의 defaults.ts와 동일) -const BUILT_IN_PRESET_MAP: Record = { - 'ig-feed-square': { id: 'ig-feed-square', width: 1080, height: 1080, format: 'jpeg', quality: 85 }, - 'ig-feed-portrait': { id: 'ig-feed-portrait', width: 1080, height: 1350, format: 'jpeg', quality: 85 }, - 'ig-feed-landscape': { id: 'ig-feed-landscape', width: 1080, height: 566, format: 'jpeg', quality: 85 }, - 'ig-story': { id: 'ig-story', width: 1080, height: 1920, format: 'jpeg', quality: 85 }, - 'ig-profile': { id: 'ig-profile', width: 320, height: 320, format: 'jpeg', quality: 90 }, - 'ig-carousel': { id: 'ig-carousel', width: 1080, height: 1350, format: 'jpeg', quality: 85 }, - 'fb-post-link': { id: 'fb-post-link', width: 1200, height: 630, format: 'jpeg', quality: 80 }, - 'fb-post-photo': { id: 'fb-post-photo', width: 1200, height: 1200, format: 'jpeg', quality: 80 }, - 'fb-post-portrait': { id: 'fb-post-portrait', width: 1080, height: 1350, format: 'jpeg', quality: 80 }, - 'fb-cover': { id: 'fb-cover', width: 851, height: 315, format: 'jpeg', quality: 85 }, - 'fb-event': { id: 'fb-event', width: 1920, height: 1005, format: 'jpeg', quality: 85 }, - 'fb-profile': { id: 'fb-profile', width: 400, height: 400, format: 'jpeg', quality: 90 }, - 'tw-post': { id: 'tw-post', width: 1600, height: 900, format: 'jpeg', quality: 85 }, - 'tw-post-alt': { id: 'tw-post-alt', width: 1200, height: 675, format: 'jpeg', quality: 85 }, - 'tw-header': { id: 'tw-header', width: 1500, height: 500, format: 'jpeg', quality: 85 }, - 'tw-profile': { id: 'tw-profile', width: 800, height: 800, format: 'jpeg', quality: 90 }, - 'yt-thumbnail': { id: 'yt-thumbnail', width: 1280, height: 720, format: 'jpeg', quality: 90 }, - 'yt-thumbnail-hd': { id: 'yt-thumbnail-hd', width: 1920, height: 1080, format: 'jpeg', quality: 90 }, - 'yt-banner': { id: 'yt-banner', width: 2560, height: 1440, format: 'jpeg', quality: 85 }, - 'yt-shorts': { id: 'yt-shorts', width: 1080, height: 1920, format: 'jpeg', quality: 85 }, - 'yt-profile': { id: 'yt-profile', width: 800, height: 800, format: 'jpeg', quality: 90 }, - 'tt-cover': { id: 'tt-cover', width: 1080, height: 1920, format: 'jpeg', quality: 85 }, - 'tt-profile': { id: 'tt-profile', width: 200, height: 200, format: 'jpeg', quality: 90 }, - 'li-post-landscape': { id: 'li-post-landscape', width: 1200, height: 627, format: 'jpeg', quality: 80 }, - 'li-post-square': { id: 'li-post-square', width: 1080, height: 1080, format: 'jpeg', quality: 80 }, - 'li-profile-banner': { id: 'li-profile-banner', width: 1584, height: 396, format: 'jpeg', quality: 85 }, - 'li-company-banner': { id: 'li-company-banner', width: 1128, height: 191, format: 'jpeg', quality: 85 }, - 'li-profile': { id: 'li-profile', width: 400, height: 400, format: 'jpeg', quality: 90 }, - 'web-standard': { id: 'web-standard', width: 1920, height: null, format: 'webp', quality: 80 }, - 'web-retina': { id: 'web-retina', width: 3840, height: null, format: 'webp', quality: 75 }, - 'print-a4': { id: 'print-a4', width: 3508, height: 2480, format: 'jpeg', quality: 95 }, - 'print-card': { id: 'print-card', width: 1050, height: 600, format: 'jpeg', quality: 95 } -} +import { BUILT_IN_PRESET_MAP } from '../../shared/presets.js' +import type { PresetLookupType, ResizeModeType, OutputFormatType, FrameStyleType } from '../../shared/types.js' const findPreset = (presetId: string | null): PresetLookupType | null => { if (!presetId) return null if (BUILT_IN_PRESET_MAP[presetId]) return BUILT_IN_PRESET_MAP[presetId] const custom = getCustomPresets().find((p) => p.id === presetId) - if (custom) return { id: custom.id, width: custom.width, height: custom.height, format: custom.format as 'jpeg' | 'webp', quality: custom.quality } + if (custom) return { id: custom.id, width: custom.width, height: custom.height, format: custom.format as OutputFormatType, quality: custom.quality } return null } @@ -64,9 +22,9 @@ export const registerImageHandlers = () => { images: { id: string; path: string; name: string }[] outputDir: string presetId: string | null - resizeMode: { kind: string; [key: string]: unknown } - output: { format: 'jpeg' | 'webp'; quality: number } - frame: string + resizeMode: ResizeModeType + output: { format: OutputFormatType; quality: number } + frame: FrameStyleType concurrency?: number }) => { const window = BrowserWindow.fromWebContents(event.sender) @@ -79,9 +37,9 @@ export const registerImageHandlers = () => { images: options.images, outputDir: options.outputDir, preset, - resizeMode: options.resizeMode as any, + resizeMode: options.resizeMode, output: options.output, - frameStyle: options.frame as any, + frameStyle: options.frame, concurrency: options.concurrency }, window.webContents @@ -91,19 +49,19 @@ export const registerImageHandlers = () => { ipcMain.handle('image:preview', async (_event, request: { imagePath: string presetId: string | null - resizeMode: { kind: string; [key: string]: unknown } - outputFormat: 'jpeg' | 'webp' + resizeMode: ResizeModeType + outputFormat: OutputFormatType quality: number - frameStyle: string + frameStyle: FrameStyleType }) => { const preset = findPreset(request.presetId) return generatePreview( request.imagePath, preset, - request.resizeMode as any, + request.resizeMode, request.outputFormat, request.quality, - request.frameStyle as any + request.frameStyle ) }) } diff --git a/src/main/services/exif-reader.ts b/src/main/services/exif-reader.ts index 813cbd6..e4abd21 100644 --- a/src/main/services/exif-reader.ts +++ b/src/main/services/exif-reader.ts @@ -1,16 +1,8 @@ import sharp from 'sharp' import exifReader from 'exif-reader' +import type { ExifDataType } from '../../shared/types.js' -export type ExifDataType = { - cameraBrand: string | null - cameraModel: string | null - lens: string | null - aperture: string | null - shutterSpeed: string | null - iso: number | null - focalLength: string | null - dateTime: string | null -} +export type { ExifDataType } const formatShutterSpeed = (exposureTime: number | undefined): string | null => { if (!exposureTime) return null @@ -26,7 +18,7 @@ export const readExif = async (imagePath: string): Promise if (!exifBuffer) return null - const parsed = exifReader(exifBuffer) as Record> + const parsed = exifReader(exifBuffer) as unknown as Record> const image = parsed?.Image ?? parsed?.image ?? {} const photo = parsed?.Photo ?? parsed?.exif ?? {} @@ -67,7 +59,8 @@ export const readExif = async (imagePath: string): Promise focalLength: focalLengthValue ? `${focalLengthValue}mm` : null, dateTime: dateTimeStr } - } catch { + } catch (err) { + console.warn(`EXIF 파싱 실패 (${imagePath}):`, err) return null } } diff --git a/src/main/services/frame-renderer.ts b/src/main/services/frame-renderer.ts index d7b7d70..9af770c 100644 --- a/src/main/services/frame-renderer.ts +++ b/src/main/services/frame-renderer.ts @@ -1,7 +1,5 @@ import sharp from 'sharp' -import type { ExifDataType } from './exif-reader.js' - -type FrameStyleType = 'simple-bar' | 'card' | 'minimal-white' +import type { ExifDataType } from '../../shared/types.js' type FrameContextType = { imageWidth: number @@ -25,46 +23,15 @@ const buildInfoParts = (exif: ExifDataType) => { return { cameraInfo, lensInfo, settingsParts } } -const generateSimpleBarSvg = (ctx: FrameContextType): { svg: string; frameHeight: number } => { - const frameHeight = 72 - const { imageWidth, exif } = ctx - const fontSize = Math.max(11, Math.min(15, imageWidth / 70)) - const { cameraInfo, lensInfo, settingsParts } = buildInfoParts(exif) - - const leftText = [cameraInfo, lensInfo].filter(Boolean).join(' · ') - const rightText = settingsParts - - const svg = ` - - ${escapeXml(leftText)} - ${escapeXml(rightText)} -` - - return { svg, frameHeight } -} - -const generateCardSvg = (ctx: FrameContextType): { svg: string; frameHeight: number } => { - const frameHeight = 110 - const { imageWidth, exif } = ctx - const fontSize = Math.max(11, Math.min(14, imageWidth / 80)) - const { cameraInfo, lensInfo, settingsParts } = buildInfoParts(exif) - - const svg = ` - - - ${escapeXml(cameraInfo)} - ${escapeXml(lensInfo)} - - ${escapeXml(settingsParts)} -` - - return { svg, frameHeight } +export const calcFrameDimensions = (imageWidth: number): { frameHeight: number; fontSize: number } => { + const frameHeight = Math.max(32, Math.min(200, Math.round(imageWidth * 0.05))) + const fontSize = Math.max(8, Math.min(48, Math.round(frameHeight * 0.23))) + return { frameHeight, fontSize } } const generateMinimalWhiteSvg = (ctx: FrameContextType): { svg: string; frameHeight: number } => { - const frameHeight = 56 const { imageWidth, exif } = ctx - const fontSize = Math.max(10, Math.min(13, imageWidth / 85)) + const { frameHeight, fontSize } = calcFrameDimensions(imageWidth) const { cameraInfo, settingsParts } = buildInfoParts(exif) const centerText = [cameraInfo, settingsParts].filter(Boolean).join(' ') @@ -77,75 +44,56 @@ const generateMinimalWhiteSvg = (ctx: FrameContextType): { svg: string; frameHei return { svg, frameHeight } } -const generateFrameSvg = ( - style: FrameStyleType, - ctx: FrameContextType -): { svg: string; frameHeight: number } => { - switch (style) { - case 'simple-bar': - return generateSimpleBarSvg(ctx) - case 'card': - return generateCardSvg(ctx) - case 'minimal-white': - return generateMinimalWhiteSvg(ctx) +export const calcFrameLayout = (targetWidth: number, targetHeight: number) => { + const borderWidth = Math.max(8, Math.round(targetWidth * 0.015)) + const innerWidth = targetWidth - 2 * borderWidth + const { frameHeight } = calcFrameDimensions(innerWidth) + return { + innerWidth, + innerHeight: targetHeight - 2 * borderWidth - frameHeight, + borderWidth, + frameHeight } } export const applyFrame = async ( resizedImageBuffer: Buffer, exif: ExifDataType, - style: FrameStyleType + overrideBorderWidth?: number ): Promise => { const meta = await sharp(resizedImageBuffer).metadata() - const imageWidth = meta.width! - const imageHeight = meta.height! + if (!meta.width || !meta.height) { + throw new Error('프레임 적용을 위한 이미지 크기를 읽을 수 없습니다') + } + const imageWidth = meta.width + const imageHeight = meta.height - const { svg, frameHeight } = generateFrameSvg(style, { imageWidth, exif }) + const { svg, frameHeight } = generateMinimalWhiteSvg({ imageWidth, exif }) const framePng = await sharp(Buffer.from(svg)).resize(imageWidth, frameHeight).png().toBuffer() - const bgColor = - style === 'minimal-white' - ? { r: 255, g: 255, b: 255, alpha: 1 } - : { r: 26, g: 26, b: 26, alpha: 1 } - - const borderWidth = style === 'minimal-white' ? Math.max(8, Math.round(imageWidth * 0.015)) : 0 + const bgColor = { r: 255, g: 255, b: 255, alpha: 1 } + const borderWidth = overrideBorderWidth ?? Math.max(8, Math.round(imageWidth * 0.015)) - let pipeline = sharp(resizedImageBuffer) - - if (borderWidth > 0) { - pipeline = pipeline.extend({ + const extended = await sharp(resizedImageBuffer) + .extend({ top: borderWidth, bottom: frameHeight + borderWidth, left: borderWidth, right: borderWidth, background: bgColor }) - } else { - pipeline = pipeline.extend({ - top: 0, - bottom: frameHeight, - left: 0, - right: 0, - background: bgColor - }) - } - - const compositeTop = borderWidth > 0 ? imageHeight + borderWidth : imageHeight - const compositeLeft = borderWidth - - const result = await pipeline .composite([ { input: framePng, - top: compositeTop, - left: compositeLeft, + top: imageHeight + borderWidth, + left: borderWidth, blend: 'over' } ]) .toBuffer() - return result + return extended } export const hasExifForFrame = (exif: ExifDataType | null): boolean => { diff --git a/src/main/services/image-processor.ts b/src/main/services/image-processor.ts index 3c86df0..8c491aa 100644 --- a/src/main/services/image-processor.ts +++ b/src/main/services/image-processor.ts @@ -3,41 +3,24 @@ import path from 'node:path' import fs from 'node:fs/promises' import os from 'node:os' import type { BrowserWindow } from 'electron' +import type { ResizeModeType, OutputFormatType, FrameStyleType, PresetLookupType } from '../../shared/types.js' import { readExif } from './exif-reader.js' -import { applyFrame, hasExifForFrame } from './frame-renderer.js' - -type ResizeModeType = - | { kind: 'preset-fit'; fit: 'cover' | 'contain' | 'fill' | 'inside' | 'outside' } - | { kind: 'aspect-ratio' } - | { kind: 'long-side'; pixels: number } - | { kind: 'short-side'; pixels: number } - | { kind: 'width'; pixels: number } - | { kind: 'height'; pixels: number } - -type OutputFormatType = 'jpeg' | 'webp' -type FrameStyleType = 'none' | 'simple-bar' | 'card' | 'minimal-white' - -type PresetType = { - id: string - width: number - height: number | null - format: OutputFormatType - quality: number -} +import { applyFrame, hasExifForFrame, calcFrameLayout, calcFrameDimensions } from './frame-renderer.js' type ProcessImageOptionsType = { inputPath: string outputDir: string - preset: PresetType | null + preset: PresetLookupType | null resizeMode: ResizeModeType output: { format: OutputFormatType; quality: number } frameStyle: FrameStyleType + outputPath?: string } type BatchProcessOptionsType = { images: { id: string; path: string; name: string }[] outputDir: string - preset: PresetType | null + preset: PresetLookupType | null resizeMode: ResizeModeType output: { format: OutputFormatType; quality: number } frameStyle: FrameStyleType @@ -70,32 +53,47 @@ type ProcessingProgressType = { const resolveResizeOptions = ( mode: ResizeModeType, - preset: PresetType | null, + preset: PresetLookupType | null, originalWidth: number, originalHeight: number ): { width: number | null; height: number | null; options: sharp.ResizeOptions } => { switch (mode.kind) { case 'preset-fit': { if (!preset) throw new Error('Preset is required for preset-fit mode') + if (preset.width === null && preset.height === null) { + return { + width: null, + height: null, + options: {} + } + } return { width: preset.width, height: preset.height, options: { fit: mode.fit, position: 'centre', - withoutEnlargement: false + withoutEnlargement: false, + ...(mode.fit === 'contain' && { + background: { r: 255, g: 255, b: 255, alpha: 1 } + }) } } } case 'aspect-ratio': { - const targetWidth = preset?.width ?? 1920 + // Use the preset's larger dimension as long-side target; scale proportionally. + if (!preset || (preset.width === null && preset.height === null)) { + return { width: null, height: null, options: {} } + } + const maxSide = Math.max(preset.width ?? 0, preset.height ?? 0) + if (maxSide <= 0) { + return { width: null, height: null, options: {} } + } + const isLandscape = originalWidth >= originalHeight return { - width: targetWidth, - height: null, - options: { - fit: 'inside', - withoutEnlargement: true - } + width: isLandscape ? maxSide : null, + height: isLandscape ? null : maxSide, + options: { fit: 'inside', withoutEnlargement: false } } } case 'long-side': { @@ -137,39 +135,191 @@ const resolveResizeOptions = ( } } +const constrainFrameByHeight = ( + targetHeight: number, + originalWidth: number, + originalHeight: number +): { innerHeight: number; frameBorderWidth: number } => { + // First pass: estimate image width from target height + const estImageWidth = Math.round(targetHeight * (originalWidth / originalHeight)) + const estBorderWidth = Math.max(8, Math.round(estImageWidth * 0.015)) + const { frameHeight: estFrameHeight } = calcFrameDimensions(Math.max(1, estImageWidth - 2 * estBorderWidth)) + const estInnerHeight = targetHeight - 2 * estBorderWidth - estFrameHeight + + if (estInnerHeight < 1) { + return { innerHeight: targetHeight, frameBorderWidth: 0 } + } + + // Correction pass: recalculate from the corrected image width + const correctedWidth = Math.round(estInnerHeight * (originalWidth / originalHeight)) + const borderWidth = Math.max(8, Math.round(correctedWidth * 0.015)) + const { frameHeight } = calcFrameDimensions(correctedWidth) + const innerHeight = targetHeight - 2 * borderWidth - frameHeight + + if (innerHeight < 1) { + return { innerHeight: targetHeight, frameBorderWidth: 0 } + } + + return { innerHeight, frameBorderWidth: borderWidth } +} + +const adjustForFrame = ( + width: number | null, + height: number | null, + resizeOpts: sharp.ResizeOptions, + originalWidth: number, + originalHeight: number, + willApplyFrame: boolean +): { + width: number | null + height: number | null + resizeOpts: sharp.ResizeOptions + frameBorderWidth: number | undefined +} => { + if (!willApplyFrame || (width == null && height == null)) { + return { width, height, resizeOpts, frameBorderWidth: undefined } + } + + // Both dimensions specified (preset-fit mode) + if (width != null && height != null) { + const layout = calcFrameLayout(width, height) + if (layout.innerWidth < 1 || layout.innerHeight < 1) { + return { width, height, resizeOpts, frameBorderWidth: undefined } + } + return { + width: layout.innerWidth, + height: layout.innerHeight, + resizeOpts, + frameBorderWidth: layout.borderWidth + } + } + + // Width specified, height auto: subtract horizontal frame space only + if (width != null) { + const borderWidth = Math.max(8, Math.round(width * 0.015)) + const innerWidth = width - 2 * borderWidth + if (innerWidth < 1) return { width, height, resizeOpts, frameBorderWidth: undefined } + return { width: innerWidth, height: null, resizeOpts, frameBorderWidth: borderWidth } + } + + // Height specified, width auto: two-pass estimation for frame overhead + const { innerHeight, frameBorderWidth } = constrainFrameByHeight(height!, originalWidth, originalHeight) + if (frameBorderWidth === 0) return { width, height, resizeOpts, frameBorderWidth: undefined } + return { width: null, height: innerHeight, resizeOpts, frameBorderWidth } +} + +const buildOutputPathMap = async ( + images: { id: string; path: string; name: string }[], + outputDir: string, + outputFormat: OutputFormatType +): Promise> => { + const outputExt = outputFormat === 'jpeg' ? '.jpg' : '.webp' + + let existingFiles: Set + try { + const entries = await fs.readdir(outputDir) + existingFiles = new Set(entries.map((e) => e.toLowerCase())) + } catch { + existingFiles = new Set() + } + + const nameCounters = new Map() + const pathMap = new Map() + + for (const image of images) { + const baseName = path.basename(image.path, path.extname(image.path)) + const canonical = `${baseName}_shapic` + const canonicalLower = canonical.toLowerCase() + const extLower = outputExt.toLowerCase() + + let counter = nameCounters.get(canonicalLower) ?? 0 + + let outputFileName: string + if (counter === 0) { + const candidate = `${canonical}${outputExt}` + if (!existingFiles.has(candidate.toLowerCase())) { + outputFileName = candidate + nameCounters.set(canonicalLower, 1) + } else { + let n = 1 + while (existingFiles.has(`${canonicalLower} (${n})${extLower}`)) { + n++ + } + outputFileName = `${canonical} (${n})${outputExt}` + nameCounters.set(canonicalLower, n + 1) + } + } else { + while (existingFiles.has(`${canonicalLower} (${counter})${extLower}`)) { + counter++ + } + outputFileName = `${canonical} (${counter})${outputExt}` + nameCounters.set(canonicalLower, counter + 1) + } + + existingFiles.add(outputFileName.toLowerCase()) + pathMap.set(image.path, path.join(outputDir, outputFileName)) + } + + return pathMap +} + const processImage = async (options: ProcessImageOptionsType): Promise => { const { inputPath, outputDir, preset, resizeMode, output, frameStyle } = options const metadata = await sharp(inputPath).metadata() - const originalWidth = metadata.width! - const originalHeight = metadata.height! + if (!metadata.width || !metadata.height) { + throw new Error(`이미지 메타데이터를 읽을 수 없습니다: ${path.basename(inputPath)}`) + } + const originalWidth = metadata.width + const originalHeight = metadata.height const originalStat = await fs.stat(inputPath) - const { width, height, options: resizeOpts } = resolveResizeOptions( + let { width, height, options: resizeOpts } = resolveResizeOptions( resizeMode, preset, originalWidth, originalHeight ) - let pipeline = sharp(inputPath, { sequentialRead: true }) - pipeline = pipeline.rotate() - pipeline = pipeline.resize(width, height, resizeOpts) - - const outputExt = output.format === 'jpeg' ? '.jpg' : '.webp' - const baseName = path.basename(inputPath, path.extname(inputPath)) - const outputPath = path.join(outputDir, `${baseName}_imageforge${outputExt}`) - const needsFrame = frameStyle !== 'none' let exifData = null - if (needsFrame) { exifData = await readExif(inputPath) } + const willApplyFrame = needsFrame && exifData != null && hasExifForFrame(exifData) + + // For aspect-ratio mode: if constraining by width would make the final height + // exceed maxSide (due to frame vertical overhead), switch to height constraint + if (willApplyFrame && resizeMode.kind === 'aspect-ratio' && width != null && height == null) { + const bw = Math.max(8, Math.round(width * 0.015)) + const iw = width - 2 * bw + const estImageHeight = Math.round(iw * (originalHeight / originalWidth)) + const { frameHeight } = calcFrameDimensions(iw) + if (estImageHeight + 2 * bw + frameHeight > width) { + height = width + width = null + } + } + + let frameBorderWidth: number | undefined + ;({ width, height, resizeOpts, frameBorderWidth } = adjustForFrame( + width, height, resizeOpts, originalWidth, originalHeight, willApplyFrame + )) - if (needsFrame && exifData && hasExifForFrame(exifData)) { + let pipeline = sharp(inputPath, { sequentialRead: true }) + pipeline = pipeline.rotate() + pipeline = pipeline.resize(width, height, resizeOpts) + + const outputPath = + options.outputPath ?? + path.join( + outputDir, + `${path.basename(inputPath, path.extname(inputPath))}_shapic${output.format === 'jpeg' ? '.jpg' : '.webp'}` + ) + + if (willApplyFrame) { const resizedBuffer = await pipeline.toBuffer() - const framedBuffer = await applyFrame(resizedBuffer, exifData, frameStyle as 'simple-bar' | 'card' | 'minimal-white') + const framedBuffer = await applyFrame(resizedBuffer, exifData!, frameBorderWidth) let outputPipeline = sharp(framedBuffer) if (output.format === 'jpeg') { @@ -218,6 +368,12 @@ export const processBatch = async ( const errors: { inputPath: string; error: string }[] = [] let completedCount = 0 + const outputPathMap = await buildOutputPathMap( + options.images, + options.outputDir, + options.output.format + ) + const semaphore = new Array(concurrency).fill(Promise.resolve()) let semaphoreIndex = 0 @@ -238,7 +394,8 @@ export const processBatch = async ( preset: options.preset, resizeMode: options.resizeMode, output: options.output, - frameStyle: options.frameStyle + frameStyle: options.frameStyle, + outputPath: outputPathMap.get(image.path) }) results.push(result) @@ -287,37 +444,57 @@ export const processBatch = async ( export const generatePreview = async ( imagePath: string, - preset: PresetType | null, + preset: PresetLookupType | null, resizeMode: ResizeModeType, outputFormat: OutputFormatType, quality: number, frameStyle: FrameStyleType ): Promise<{ dataUrl: string; width: number; height: number; estimatedSize: number }> => { const metadata = await sharp(imagePath).metadata() - const originalWidth = metadata.width! - const originalHeight = metadata.height! + if (!metadata.width || !metadata.height) { + throw new Error(`이미지 메타데이터를 읽을 수 없습니다: ${path.basename(imagePath)}`) + } + const originalWidth = metadata.width + const originalHeight = metadata.height - const { width, height, options: resizeOpts } = resolveResizeOptions( + let { width, height, options: resizeOpts } = resolveResizeOptions( resizeMode, preset, originalWidth, originalHeight ) - let pipeline = sharp(imagePath, { sequentialRead: true }) - pipeline = pipeline.rotate() - pipeline = pipeline.resize(width, height, resizeOpts) - const needsFrame = frameStyle !== 'none' let exifData = null if (needsFrame) { exifData = await readExif(imagePath) } + const willApplyFrame = needsFrame && exifData != null && hasExifForFrame(exifData) + + if (willApplyFrame && resizeMode.kind === 'aspect-ratio' && width != null && height == null) { + const bw = Math.max(8, Math.round(width * 0.015)) + const iw = width - 2 * bw + const estImageHeight = Math.round(iw * (originalHeight / originalWidth)) + const { frameHeight } = calcFrameDimensions(iw) + if (estImageHeight + 2 * bw + frameHeight > width) { + height = width + width = null + } + } + + let frameBorderWidth: number | undefined + ;({ width, height, resizeOpts, frameBorderWidth } = adjustForFrame( + width, height, resizeOpts, originalWidth, originalHeight, willApplyFrame + )) + + let pipeline = sharp(imagePath, { sequentialRead: true }) + pipeline = pipeline.rotate() + pipeline = pipeline.resize(width, height, resizeOpts) let resultBuffer: Buffer - if (needsFrame && exifData && hasExifForFrame(exifData)) { + if (willApplyFrame) { const resizedBuffer = await pipeline.toBuffer() - resultBuffer = await applyFrame(resizedBuffer, exifData, frameStyle as 'simple-bar' | 'card' | 'minimal-white') + resultBuffer = await applyFrame(resizedBuffer, exifData!, frameBorderWidth) } else { resultBuffer = await pipeline.toBuffer() } @@ -345,14 +522,17 @@ export const generatePreview = async ( export const loadImageMetadata = async (filePath: string) => { const metadata = await sharp(filePath).metadata() + if (!metadata.width || !metadata.height) { + throw new Error(`이미지 메타데이터를 읽을 수 없습니다: ${path.basename(filePath)}`) + } const stat = await fs.stat(filePath) const exifData = await readExif(filePath) return { path: filePath, name: path.basename(filePath), - width: metadata.width!, - height: metadata.height!, + width: metadata.width, + height: metadata.height, format: metadata.format ?? 'unknown', size: stat.size, exifData diff --git a/src/preload/index.d.ts b/src/preload/index.d.ts index 439069f..101bf91 100644 --- a/src/preload/index.d.ts +++ b/src/preload/index.d.ts @@ -9,7 +9,7 @@ import type { PreviewResultType } from '../renderer/src/types/index.js' -export type ImageForgeApiType = { +export type ShapicApiType = { image: { load: (filePaths: string[]) => Promise process: (options: BatchProcessOptionsType) => Promise @@ -30,6 +30,6 @@ export type ImageForgeApiType = { declare global { interface Window { - api: ImageForgeApiType + api: ShapicApiType } } diff --git a/src/renderer/index.html b/src/renderer/index.html index a57b790..d9122f7 100644 --- a/src/renderer/index.html +++ b/src/renderer/index.html @@ -10,7 +10,7 @@ - ImageForge + Shapic
diff --git a/src/renderer/src/components/drop-zone.tsx b/src/renderer/src/components/drop-zone.tsx index aecd2b8..5fea942 100644 --- a/src/renderer/src/components/drop-zone.tsx +++ b/src/renderer/src/components/drop-zone.tsx @@ -1,6 +1,7 @@ import { useState, useCallback } from 'react' import { useAppStore } from '../stores/app-store' import { cn } from '../utils/cn' +import { SUPPORTED_EXTENSIONS } from '../../../shared/constants.js' import type { ImageFileType } from '../types' const DropZone = () => { @@ -44,9 +45,8 @@ const DropZone = () => { setIsDragOver(false) const files = Array.from(e.dataTransfer.files) - const imageFiles = files.filter((f) => - /\.(jpe?g|png|webp|heif|heic|tiff?)$/i.test(f.name) - ) + const extPattern = new RegExp(`\\.(${SUPPORTED_EXTENSIONS.join('|')})$`, 'i') + const imageFiles = files.filter((f) => extPattern.test(f.name)) const paths = imageFiles.map((f) => (f as File & { path: string }).path) await processFiles(paths) }, diff --git a/src/renderer/src/components/layout/app-layout.tsx b/src/renderer/src/components/layout/app-layout.tsx index 38683cd..2d05fcf 100644 --- a/src/renderer/src/components/layout/app-layout.tsx +++ b/src/renderer/src/components/layout/app-layout.tsx @@ -1,3 +1,4 @@ +import TitleBar from './title-bar' import LeftPanel from './left-panel' import CenterPanel from './center-panel' import RightPanel from './right-panel' @@ -6,6 +7,7 @@ import ProgressBar from '../progress-bar' const AppLayout = () => { return (
+
diff --git a/src/renderer/src/components/layout/left-panel.tsx b/src/renderer/src/components/layout/left-panel.tsx index b68560b..a59a022 100644 --- a/src/renderer/src/components/layout/left-panel.tsx +++ b/src/renderer/src/components/layout/left-panel.tsx @@ -1,24 +1,18 @@ -import ImageList from '../image-list' +import ImageList from "../image-list"; +import appIcon from "../../../../../resources/icon.png"; const LeftPanel = () => { return ( -
-
-
-
- - - - - - -
- ImageForge +
+
+
+ Shapic + Shapic
- ) -} + ); +}; -export default LeftPanel +export default LeftPanel; diff --git a/src/renderer/src/components/layout/right-panel.tsx b/src/renderer/src/components/layout/right-panel.tsx index 11bc25b..1ea4c32 100644 --- a/src/renderer/src/components/layout/right-panel.tsx +++ b/src/renderer/src/components/layout/right-panel.tsx @@ -1,16 +1,11 @@ -import Settings from '../settings' +import Settings from "../settings"; const RightPanel = () => { return ( -
-
- - 설정 - -
+
- ) -} + ); +}; -export default RightPanel +export default RightPanel; diff --git a/src/renderer/src/components/layout/title-bar.tsx b/src/renderer/src/components/layout/title-bar.tsx new file mode 100644 index 0000000..97a07d6 --- /dev/null +++ b/src/renderer/src/components/layout/title-bar.tsx @@ -0,0 +1,10 @@ +const TitleBar = () => { + return ( +
+ ) +} + +export default TitleBar diff --git a/src/renderer/src/components/preset-modal.tsx b/src/renderer/src/components/preset-modal.tsx index 0562751..551ee5e 100644 --- a/src/renderer/src/components/preset-modal.tsx +++ b/src/renderer/src/components/preset-modal.tsx @@ -8,6 +8,11 @@ type PresetModalPropsType = { onClose: () => void } +const MAX_DIMENSION = 10000 + +const isValidDimension = (v: number) => Number.isFinite(v) && v >= 1 && v <= MAX_DIMENSION +const isValidQuality = (v: number) => Number.isFinite(v) && v >= 1 && v <= 100 + const PresetModal = ({ onClose }: PresetModalPropsType) => { const addCustomPreset = useAppStore((s) => s.addCustomPreset) @@ -16,10 +21,13 @@ const PresetModal = ({ onClose }: PresetModalPropsType) => { const [width, setWidth] = useState(1080) const [height, setHeight] = useState(1080) const [format, setFormat] = useState('jpeg') - const [quality, setQuality] = useState(85) + const [quality, setQuality] = useState(100) + + const isValid = + name.trim().length > 0 && isValidDimension(width) && isValidDimension(height) && isValidQuality(quality) const handleSave = async () => { - if (!name.trim()) return + if (!isValid) return const saved = await window.api.preset.save({ name: name.trim(), @@ -64,8 +72,7 @@ const PresetModal = ({ onClose }: PresetModalPropsType) => { - - +
@@ -77,8 +84,12 @@ const PresetModal = ({ onClose }: PresetModalPropsType) => { value={width} onChange={(e) => setWidth(Number(e.target.value))} min={1} + max={MAX_DIMENSION} className="w-full mt-1.5 px-2.5 py-1.5 text-sm bg-card border border-border rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary" /> + {!isValidDimension(width) && ( +

1~{MAX_DIMENSION} 사이 값을 입력해 주세요

+ )}
@@ -87,8 +98,12 @@ const PresetModal = ({ onClose }: PresetModalPropsType) => { value={height} onChange={(e) => setHeight(Number(e.target.value))} min={1} + max={MAX_DIMENSION} className="w-full mt-1.5 px-2.5 py-1.5 text-sm bg-card border border-border rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary" /> + {!isValidDimension(height) && ( +

1~{MAX_DIMENSION} 사이 값을 입력해 주세요

+ )}
@@ -114,6 +129,9 @@ const PresetModal = ({ onClose }: PresetModalPropsType) => { max={100} className="w-full mt-1.5 px-2.5 py-1.5 text-sm bg-card border border-border rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary" /> + {!isValidQuality(quality) && ( +

1~100 사이 값을 입력해 주세요

+ )}
@@ -121,7 +139,7 @@ const PresetModal = ({ onClose }: PresetModalPropsType) => { -
diff --git a/src/renderer/src/components/preset-selector.tsx b/src/renderer/src/components/preset-selector.tsx index 30a33a5..1549651 100644 --- a/src/renderer/src/components/preset-selector.tsx +++ b/src/renderer/src/components/preset-selector.tsx @@ -14,7 +14,7 @@ const PresetSelector = () => { const grouped = useMemo(() => getGroupedPresets(customPresets), [customPresets]) return ( -
+
+
+ ) : ( + {selectedImage.name} setImageError('이미지를 불러올 수 없습니다')} + /> + )}
{/* 정보 바 */} diff --git a/src/renderer/src/components/settings.tsx b/src/renderer/src/components/settings.tsx index 68bdc2e..c96c051 100644 --- a/src/renderer/src/components/settings.tsx +++ b/src/renderer/src/components/settings.tsx @@ -1,12 +1,13 @@ import { useCallback } from 'react' import { useAppStore } from '../stores/app-store' -import { selectSelectedImage, selectHasImages } from '../stores/selectors' +import { selectSelectedImage, selectHasImages, selectIsAllDone } from '../stores/selectors' import { useProcessing } from '../hooks/use-processing' import PresetSelector from './preset-selector' import PillButton from './ui/pill-button' import Slider from './ui/slider' import Button from './ui/button' -import type { OutputFormatType, FrameStyleType, ResizeFitType } from '../types' +import Switch from './ui/switch' +import type { OutputFormatType, ResizeFitType } from '../types' const Settings = () => { const options = useAppStore((s) => s.options) @@ -14,8 +15,9 @@ const Settings = () => { const setResizeMode = useAppStore((s) => s.setResizeMode) const progress = useAppStore((s) => s.progress) const hasImages = useAppStore(selectHasImages) + const isAllDone = useAppStore(selectIsAllDone) const selectedImage = useAppStore(selectSelectedImage) - const { startProcessing } = useProcessing() + const { startSingleProcessing, startBatchProcessing, processingModeRef } = useProcessing() const handleSelectFolder = useCallback(async () => { const folder = await window.api.dialog.openFolder() @@ -24,132 +26,160 @@ const Settings = () => { const hasExif = selectedImage?.exifData != null - const canStart = hasImages && options.presetId && options.outputFolder && !progress.isProcessing + const commonDisabled = !options.presetId || !options.outputFolder || progress.isProcessing + const canSingle = !!selectedImage && !commonDisabled + const canBatch = hasImages && !isAllDone && !commonDisabled return (
-
- {/* 프리셋 선택 */} - +
+ {/* 카드 1: 크기 설정 */} +
+ {/* 프리셋 선택 */} + - {/* 리사이즈 모드 */} -
- -
- setResizeMode({ kind: 'preset-fit', fit: 'cover' })} - > - 프리셋 맞춤 - - setResizeMode({ kind: 'aspect-ratio' })} - > - 비율 유지 - -
- {options.resizeMode.kind === 'preset-fit' && ( -
+
+ + {/* 리사이즈 모드 */} +
+ +
setResizeMode({ kind: 'preset-fit', fit: 'cover' })} > - Cover + 프리셋 맞춤 setResizeMode({ kind: 'preset-fit', fit: 'contain' })} + active={options.resizeMode.kind === 'aspect-ratio'} + onClick={() => setResizeMode({ kind: 'aspect-ratio' })} > - Contain + 비율 유지
- )} + {options.resizeMode.kind === 'preset-fit' && ( +
+ setResizeMode({ kind: 'preset-fit', fit: 'cover' })} + > + Cover + + setResizeMode({ kind: 'preset-fit', fit: 'contain' })} + > + Contain + +
+ )} +
- {/* 포맷 선택 */} -
- -
- setOption('outputFormat', 'jpeg')} - > - JPEG - - setOption('outputFormat', 'webp')} - > - WebP - + {/* 카드 2: 출력 품질 */} +
+ {/* 포맷 선택 */} +
+ +
+ setOption('outputFormat', 'jpeg')} + > + JPEG + + setOption('outputFormat', 'webp')} + > + WebP + +
-
- {/* 품질 슬라이더 */} - setOption('quality', v)} - /> +
- {/* EXIF 프레임 */} -
- - {!hasExif && selectedImage && ( -

이 이미지에 EXIF 데이터가 없습니다

- )} - + {/* 품질 슬라이더 */} + setOption('quality', v)} + />
- {/* 출력 폴더 */} -
- - - {options.outputFolder && ( -

{options.outputFolder}

- )} + {/* 카드 3: 부가 설정 */} +
+ {/* EXIF 프레임 */} +
+
+ + setOption('frameStyle', on ? 'minimal-white' : 'none')} + disabled={!options.presetId || (selectedImage != null && !hasExif)} + /> +
+ {!hasExif && selectedImage && ( +

이 이미지에 EXIF 데이터가 없습니다

+ )} +
+ +
+ + {/* 출력 폴더 */} +
+ + + {options.outputFolder && ( +

{options.outputFolder}

+ )} +
- {/* 변환 시작 버튼 */} -
+ {/* 변환 버튼 */} +
+
diff --git a/src/renderer/src/components/ui/pill-button.tsx b/src/renderer/src/components/ui/pill-button.tsx index 7265c71..58122de 100644 --- a/src/renderer/src/components/ui/pill-button.tsx +++ b/src/renderer/src/components/ui/pill-button.tsx @@ -1,25 +1,25 @@ -import { cn } from '../../utils/cn' +import { cn } from "../../utils/cn"; type PillButtonPropsType = { - active: boolean - onClick: () => void - children: React.ReactNode -} + active: boolean; + onClick: () => void; + children: React.ReactNode; +}; const PillButton = ({ active, onClick, children }: PillButtonPropsType) => { return ( - ) -} + ); +}; -export default PillButton +export default PillButton; diff --git a/src/renderer/src/components/ui/switch.tsx b/src/renderer/src/components/ui/switch.tsx new file mode 100644 index 0000000..744d67c --- /dev/null +++ b/src/renderer/src/components/ui/switch.tsx @@ -0,0 +1,38 @@ +import { cn } from '../../utils/cn' + +type SwitchPropsType = { + checked: boolean + onChange: (checked: boolean) => void + disabled?: boolean + label?: string +} + +const Switch = ({ checked, onChange, disabled, label }: SwitchPropsType) => { + return ( + + ) +} + +export default Switch diff --git a/src/renderer/src/env.d.ts b/src/renderer/src/env.d.ts new file mode 100644 index 0000000..8be9851 --- /dev/null +++ b/src/renderer/src/env.d.ts @@ -0,0 +1,37 @@ +/// + +import type { + LoadedImageType, + BatchProcessOptionsType, + ProcessingProgressType, + BatchResultType, + PresetType, + CustomPresetInputType, + PreviewRequestType, + PreviewResultType +} from './types' + +type ShapicApiType = { + image: { + load: (filePaths: string[]) => Promise + process: (options: BatchProcessOptionsType) => Promise + preview: (request: PreviewRequestType) => Promise + onProgress: (callback: (progress: ProcessingProgressType) => void) => () => void + onComplete: (callback: (result: BatchResultType) => void) => () => void + } + preset: { + list: () => Promise + save: (preset: CustomPresetInputType) => Promise + delete: (id: string) => Promise + } + dialog: { + openFile: () => Promise + openFolder: () => Promise + } +} + +declare global { + interface Window { + api: ShapicApiType + } +} diff --git a/src/renderer/src/hooks/use-processing.ts b/src/renderer/src/hooks/use-processing.ts index db56e6b..fe721e9 100644 --- a/src/renderer/src/hooks/use-processing.ts +++ b/src/renderer/src/hooks/use-processing.ts @@ -1,15 +1,24 @@ -import { useEffect, useCallback } from 'react' +import { useEffect, useCallback, useRef } from 'react' import { useAppStore } from '../stores/app-store.js' import type { ProcessingProgressType, BatchResultType } from '../types/index.js' +export type ProcessingModeType = 'single' | 'batch' | null + export const useProcessing = () => { const images = useAppStore((s) => s.images) + const selectedImageId = useAppStore((s) => s.selectedImageId) const options = useAppStore((s) => s.options) const setProgress = useAppStore((s) => s.setProgress) - const resetProgress = useAppStore((s) => s.resetProgress) const updateImageStatus = useAppStore((s) => s.updateImageStatus) const updateImageResult = useAppStore((s) => s.updateImageResult) const updateImageError = useAppStore((s) => s.updateImageError) + const processingModeRef = useRef(null) + const imagesRef = useRef(images) + + // images가 변경될 때 ref만 업데이트 (리스너 재등록 없음) + useEffect(() => { + imagesRef.current = images + }, [images]) useEffect(() => { const unsubProgress = window.api.image.onProgress((raw) => { @@ -36,7 +45,7 @@ export const useProcessing = () => { const result = raw as BatchResultType result.results.forEach((r) => { - const img = images.find((i) => i.path === r.inputPath) + const img = imagesRef.current.find((i) => i.path === r.inputPath) if (img) { updateImageResult(img.id, { outputSize: r.processedSize, @@ -46,44 +55,67 @@ export const useProcessing = () => { }) result.errors.forEach((e) => { - const img = images.find((i) => i.path === e.inputPath) + const img = imagesRef.current.find((i) => i.path === e.inputPath) if (img) { updateImageError(img.id, e.error) } }) setProgress({ isProcessing: false, overallPercent: 100 }) + processingModeRef.current = null }) return () => { unsubProgress() unsubComplete() } - }, [images, setProgress, resetProgress, updateImageStatus, updateImageResult, updateImageError]) + }, [setProgress, updateImageStatus, updateImageResult, updateImageError]) - const startProcessing = useCallback(async () => { - const imagesToProcess = images.filter((img) => img.status !== 'done') - if (imagesToProcess.length === 0 || !options.outputFolder) return - - setProgress({ - isProcessing: true, - currentIndex: 0, - totalCount: imagesToProcess.length, - overallPercent: 0, - currentFileName: imagesToProcess[0].name - }) + const processImages = useCallback( + async (imagesToProcess: typeof images) => { + if (imagesToProcess.length === 0 || !options.outputFolder) return - imagesToProcess.forEach((img) => updateImageStatus(img.id, 'processing')) + setProgress({ + isProcessing: true, + currentIndex: 0, + totalCount: imagesToProcess.length, + overallPercent: 0, + currentFileName: imagesToProcess[0].name + }) - await window.api.image.process({ - images: imagesToProcess.map((img) => ({ id: img.id, path: img.path, name: img.name })), - outputDir: options.outputFolder, - presetId: options.presetId, - resizeMode: options.resizeMode, - output: { format: options.outputFormat, quality: options.quality }, - frame: options.frameStyle - }) - }, [images, options, setProgress, updateImageStatus]) + imagesToProcess.forEach((img) => updateImageStatus(img.id, 'processing')) + + await window.api.image.process({ + images: imagesToProcess.map((img) => ({ id: img.id, path: img.path, name: img.name })), + outputDir: options.outputFolder, + presetId: options.presetId, + resizeMode: options.resizeMode, + output: { format: options.outputFormat, quality: options.quality }, + frame: options.frameStyle + }) + }, + [options, setProgress, updateImageStatus] + ) + + const startSingleProcessing = useCallback(async () => { + const image = images.find((img) => img.id === selectedImageId) + if (!image) return + + if (image.status === 'done') { + updateImageStatus(image.id, 'idle') + } + + processingModeRef.current = 'single' + await processImages([image]) + }, [images, selectedImageId, processImages, updateImageStatus]) + + const startBatchProcessing = useCallback(async () => { + const imagesToProcess = images.filter((img) => img.status !== 'done') + if (imagesToProcess.length === 0) return + + processingModeRef.current = 'batch' + await processImages(imagesToProcess) + }, [images, processImages]) - return { startProcessing } + return { startSingleProcessing, startBatchProcessing, processingModeRef } } diff --git a/src/renderer/src/presets/defaults.ts b/src/renderer/src/presets/defaults.ts index 397ad5b..f89bab3 100644 --- a/src/renderer/src/presets/defaults.ts +++ b/src/renderer/src/presets/defaults.ts @@ -1,391 +1 @@ -import type { PresetType, PresetCategoryType } from '../types/index.js' - -export const PRESET_CATEGORIES: Record = { - instagram: 'Instagram', - facebook: 'Facebook', - twitter: 'Twitter / X', - youtube: 'YouTube', - tiktok: 'TikTok', - linkedin: 'LinkedIn', - web: 'Web', - print: 'Print' -} - -export const BUILT_IN_PRESETS: PresetType[] = [ - // --- Instagram (6) --- - { - id: 'ig-feed-square', - name: 'Feed Square', - category: 'instagram', - width: 1080, - height: 1080, - format: 'jpeg', - quality: 85, - description: '1080x1080 · 1:1', - isCustom: false - }, - { - id: 'ig-feed-portrait', - name: 'Feed Portrait', - category: 'instagram', - width: 1080, - height: 1350, - format: 'jpeg', - quality: 85, - description: '1080x1350 · 4:5', - isCustom: false - }, - { - id: 'ig-feed-landscape', - name: 'Feed Landscape', - category: 'instagram', - width: 1080, - height: 566, - format: 'jpeg', - quality: 85, - description: '1080x566 · 1.91:1', - isCustom: false - }, - { - id: 'ig-story', - name: 'Story / Reel', - category: 'instagram', - width: 1080, - height: 1920, - format: 'jpeg', - quality: 85, - description: '1080x1920 · 9:16', - isCustom: false - }, - { - id: 'ig-profile', - name: 'Profile', - category: 'instagram', - width: 320, - height: 320, - format: 'jpeg', - quality: 90, - description: '320x320 · 1:1', - isCustom: false - }, - { - id: 'ig-carousel', - name: 'Carousel', - category: 'instagram', - width: 1080, - height: 1350, - format: 'jpeg', - quality: 85, - description: '1080x1350 · 4:5', - isCustom: false - }, - - // --- Facebook (6) --- - { - id: 'fb-post-link', - name: 'Post (Link)', - category: 'facebook', - width: 1200, - height: 630, - format: 'jpeg', - quality: 80, - description: '1200x630 · 1.91:1', - isCustom: false - }, - { - id: 'fb-post-photo', - name: 'Post (Photo)', - category: 'facebook', - width: 1200, - height: 1200, - format: 'jpeg', - quality: 80, - description: '1200x1200 · 1:1', - isCustom: false - }, - { - id: 'fb-post-portrait', - name: 'Post (Portrait)', - category: 'facebook', - width: 1080, - height: 1350, - format: 'jpeg', - quality: 80, - description: '1080x1350 · 4:5', - isCustom: false - }, - { - id: 'fb-cover', - name: 'Cover Photo', - category: 'facebook', - width: 851, - height: 315, - format: 'jpeg', - quality: 85, - description: '851x315 · 2.7:1', - isCustom: false - }, - { - id: 'fb-event', - name: 'Event Cover', - category: 'facebook', - width: 1920, - height: 1005, - format: 'jpeg', - quality: 85, - description: '1920x1005 · 1.91:1', - isCustom: false - }, - { - id: 'fb-profile', - name: 'Profile', - category: 'facebook', - width: 400, - height: 400, - format: 'jpeg', - quality: 90, - description: '400x400 · 1:1', - isCustom: false - }, - - // --- Twitter / X (4) --- - { - id: 'tw-post', - name: 'Post', - category: 'twitter', - width: 1600, - height: 900, - format: 'jpeg', - quality: 85, - description: '1600x900 · 16:9', - isCustom: false - }, - { - id: 'tw-post-alt', - name: 'Post (Alt)', - category: 'twitter', - width: 1200, - height: 675, - format: 'jpeg', - quality: 85, - description: '1200x675 · 16:9', - isCustom: false - }, - { - id: 'tw-header', - name: 'Header', - category: 'twitter', - width: 1500, - height: 500, - format: 'jpeg', - quality: 85, - description: '1500x500 · 3:1', - isCustom: false - }, - { - id: 'tw-profile', - name: 'Profile', - category: 'twitter', - width: 800, - height: 800, - format: 'jpeg', - quality: 90, - description: '800x800 · 1:1', - isCustom: false - }, - - // --- YouTube (5) --- - { - id: 'yt-thumbnail', - name: 'Thumbnail', - category: 'youtube', - width: 1280, - height: 720, - format: 'jpeg', - quality: 90, - description: '1280x720 · 16:9', - isCustom: false - }, - { - id: 'yt-thumbnail-hd', - name: 'Thumbnail (HD)', - category: 'youtube', - width: 1920, - height: 1080, - format: 'jpeg', - quality: 90, - description: '1920x1080 · 16:9', - isCustom: false - }, - { - id: 'yt-banner', - name: 'Channel Banner', - category: 'youtube', - width: 2560, - height: 1440, - format: 'jpeg', - quality: 85, - description: '2560x1440 · 16:9', - isCustom: false - }, - { - id: 'yt-shorts', - name: 'Shorts Cover', - category: 'youtube', - width: 1080, - height: 1920, - format: 'jpeg', - quality: 85, - description: '1080x1920 · 9:16', - isCustom: false - }, - { - id: 'yt-profile', - name: 'Profile', - category: 'youtube', - width: 800, - height: 800, - format: 'jpeg', - quality: 90, - description: '800x800 · 1:1', - isCustom: false - }, - - // --- TikTok (2) --- - { - id: 'tt-cover', - name: 'Cover / Thumbnail', - category: 'tiktok', - width: 1080, - height: 1920, - format: 'jpeg', - quality: 85, - description: '1080x1920 · 9:16', - isCustom: false - }, - { - id: 'tt-profile', - name: 'Profile', - category: 'tiktok', - width: 200, - height: 200, - format: 'jpeg', - quality: 90, - description: '200x200 · 1:1', - isCustom: false - }, - - // --- LinkedIn (5) --- - { - id: 'li-post-landscape', - name: 'Post (Landscape)', - category: 'linkedin', - width: 1200, - height: 627, - format: 'jpeg', - quality: 80, - description: '1200x627 · 1.91:1', - isCustom: false - }, - { - id: 'li-post-square', - name: 'Post (Square)', - category: 'linkedin', - width: 1080, - height: 1080, - format: 'jpeg', - quality: 80, - description: '1080x1080 · 1:1', - isCustom: false - }, - { - id: 'li-profile-banner', - name: 'Profile Banner', - category: 'linkedin', - width: 1584, - height: 396, - format: 'jpeg', - quality: 85, - description: '1584x396 · 4:1', - isCustom: false - }, - { - id: 'li-company-banner', - name: 'Company Banner', - category: 'linkedin', - width: 1128, - height: 191, - format: 'jpeg', - quality: 85, - description: '1128x191 · ~6:1', - isCustom: false - }, - { - id: 'li-profile', - name: 'Profile', - category: 'linkedin', - width: 400, - height: 400, - format: 'jpeg', - quality: 90, - description: '400x400 · 1:1', - isCustom: false - }, - - // --- Web (2) --- - { - id: 'web-standard', - name: 'Web Standard', - category: 'web', - width: 1920, - height: null, - format: 'webp', - quality: 80, - description: 'max 1920px · 원본 비율', - isCustom: false - }, - { - id: 'web-retina', - name: 'Web Retina 2x', - category: 'web', - width: 3840, - height: null, - format: 'webp', - quality: 75, - description: 'max 3840px · 원본 비율', - isCustom: false - }, - - // --- Print (2) --- - { - id: 'print-a4', - name: 'A4 (300dpi)', - category: 'print', - width: 3508, - height: 2480, - format: 'jpeg', - quality: 95, - description: '3508x2480 · 210x297mm', - isCustom: false - }, - { - id: 'print-card', - name: '명함 (300dpi)', - category: 'print', - width: 1050, - height: 600, - format: 'jpeg', - quality: 95, - description: '1050x600 · 90x50mm', - isCustom: false - } -] - -export const getGroupedPresets = (customPresets: PresetType[] = []) => { - const allPresets = [...BUILT_IN_PRESETS, ...customPresets] - return (Object.keys(PRESET_CATEGORIES) as PresetCategoryType[]).map((category) => ({ - category, - label: PRESET_CATEGORIES[category], - presets: allPresets.filter((p) => p.category === category) - })) -} +export { BUILT_IN_PRESETS, PRESET_CATEGORIES, getGroupedPresets } from '../../../shared/presets.js' diff --git a/src/renderer/src/stores/app-store.ts b/src/renderer/src/stores/app-store.ts index b9442a8..d033334 100644 --- a/src/renderer/src/stores/app-store.ts +++ b/src/renderer/src/stores/app-store.ts @@ -40,7 +40,7 @@ const initialOptions: ProcessingOptionsType = { presetId: null, resizeMode: { kind: 'preset-fit', fit: 'cover' }, outputFormat: 'jpeg', - quality: 85, + quality: 100, frameStyle: 'none', outputFolder: '' } diff --git a/src/renderer/src/types/index.ts b/src/renderer/src/types/index.ts index 126e121..e00d3aa 100644 --- a/src/renderer/src/types/index.ts +++ b/src/renderer/src/types/index.ts @@ -1,44 +1,28 @@ -// --- 상태 & 옵션 유니언 타입 --- +// --- 공유 타입 re-export --- + +export type { + OutputFormatType, + FrameStyleType, + ResizeFitType, + PresetCategoryType, + ResizeModeType, + ExifDataType, + PresetType, + PresetLookupType +} from '../../../shared/types.js' + +import type { + ExifDataType, + ResizeModeType, + OutputFormatType, + FrameStyleType, + PresetType +} from '../../../shared/types.js' + +// --- 상태 타입 (renderer 전용) --- export type ImageStatusType = 'idle' | 'processing' | 'done' | 'error' -export type OutputFormatType = 'jpeg' | 'webp' - -export type FrameStyleType = 'none' | 'simple-bar' | 'card' | 'minimal-white' - -export type PresetCategoryType = - | 'instagram' - | 'facebook' - | 'twitter' - | 'youtube' - | 'tiktok' - | 'linkedin' - | 'web' - | 'print' - -export type ResizeFitType = 'cover' | 'contain' | 'fill' | 'inside' | 'outside' - -export type ResizeModeType = - | { kind: 'preset-fit'; fit: ResizeFitType } - | { kind: 'aspect-ratio' } - | { kind: 'long-side'; pixels: number } - | { kind: 'short-side'; pixels: number } - | { kind: 'width'; pixels: number } - | { kind: 'height'; pixels: number } - -// --- EXIF 데이터 --- - -export type ExifDataType = { - cameraBrand: string | null - cameraModel: string | null - lens: string | null - aperture: string | null - shutterSpeed: string | null - iso: number | null - focalLength: string | null - dateTime: string | null -} - // --- 이미지 파일 --- export type ImageFileType = { @@ -69,18 +53,6 @@ export type LoadedImageType = { // --- 프리셋 --- -export type PresetType = { - id: string - name: string - category: PresetCategoryType - width: number - height: number | null - format: OutputFormatType - quality: number - description: string - isCustom: boolean -} - export type CustomPresetInputType = Omit // --- 처리 옵션 --- diff --git a/src/shared/constants.ts b/src/shared/constants.ts new file mode 100644 index 0000000..9312d99 --- /dev/null +++ b/src/shared/constants.ts @@ -0,0 +1 @@ +export const SUPPORTED_EXTENSIONS = ['jpg', 'jpeg', 'png', 'webp', 'heif', 'heic', 'tiff', 'tif'] diff --git a/src/shared/presets.ts b/src/shared/presets.ts new file mode 100644 index 0000000..3c4996f --- /dev/null +++ b/src/shared/presets.ts @@ -0,0 +1,352 @@ +import type { PresetType, PresetCategoryType, PresetLookupType } from './types.js' + +export const PRESET_CATEGORIES: Record = { + instagram: 'Instagram', + facebook: 'Facebook', + twitter: 'Twitter / X', + youtube: 'YouTube', + tiktok: 'TikTok', + linkedin: 'LinkedIn', + general: '일반' +} + +export const BUILT_IN_PRESETS: PresetType[] = [ + // --- Instagram (5) --- + { + id: 'ig-feed-square', + name: 'Feed Square', + category: 'instagram', + width: 1080, + height: 1080, + format: 'jpeg', + quality: 85, + description: '1080x1080 · 1:1', + isCustom: false + }, + { + id: 'ig-feed-portrait', + name: 'Feed Portrait', + category: 'instagram', + width: 1080, + height: 1350, + format: 'jpeg', + quality: 85, + description: '1080x1350 · 4:5', + isCustom: false + }, + { + id: 'ig-feed-landscape', + name: 'Feed Landscape', + category: 'instagram', + width: 1080, + height: 566, + format: 'jpeg', + quality: 85, + description: '1080x566 · 1.91:1', + isCustom: false + }, + { + id: 'ig-story', + name: 'Story / Reel', + category: 'instagram', + width: 1080, + height: 1920, + format: 'jpeg', + quality: 85, + description: '1080x1920 · 9:16', + isCustom: false + }, + { + id: 'ig-carousel', + name: 'Carousel', + category: 'instagram', + width: 1080, + height: 1350, + format: 'jpeg', + quality: 85, + description: '1080x1350 · 4:5', + isCustom: false + }, + + // --- Facebook (6) --- + { + id: 'fb-post-link', + name: 'Post (Link)', + category: 'facebook', + width: 1200, + height: 630, + format: 'jpeg', + quality: 80, + description: '1200x630 · 1.91:1', + isCustom: false + }, + { + id: 'fb-post-photo', + name: 'Post (Photo)', + category: 'facebook', + width: 1200, + height: 1200, + format: 'jpeg', + quality: 80, + description: '1200x1200 · 1:1', + isCustom: false + }, + { + id: 'fb-post-portrait', + name: 'Post (Portrait)', + category: 'facebook', + width: 1080, + height: 1350, + format: 'jpeg', + quality: 80, + description: '1080x1350 · 4:5', + isCustom: false + }, + { + id: 'fb-cover', + name: 'Cover Photo', + category: 'facebook', + width: 851, + height: 315, + format: 'jpeg', + quality: 85, + description: '851x315 · 2.7:1', + isCustom: false + }, + { + id: 'fb-event', + name: 'Event Cover', + category: 'facebook', + width: 1920, + height: 1005, + format: 'jpeg', + quality: 85, + description: '1920x1005 · 1.91:1', + isCustom: false + }, + { + id: 'fb-profile', + name: 'Profile', + category: 'facebook', + width: 400, + height: 400, + format: 'jpeg', + quality: 90, + description: '400x400 · 1:1', + isCustom: false + }, + + // --- Twitter / X (4) --- + { + id: 'tw-post', + name: 'Post', + category: 'twitter', + width: 1600, + height: 900, + format: 'jpeg', + quality: 85, + description: '1600x900 · 16:9', + isCustom: false + }, + { + id: 'tw-post-alt', + name: 'Post (Alt)', + category: 'twitter', + width: 1200, + height: 675, + format: 'jpeg', + quality: 85, + description: '1200x675 · 16:9', + isCustom: false + }, + { + id: 'tw-header', + name: 'Header', + category: 'twitter', + width: 1500, + height: 500, + format: 'jpeg', + quality: 85, + description: '1500x500 · 3:1', + isCustom: false + }, + { + id: 'tw-profile', + name: 'Profile', + category: 'twitter', + width: 800, + height: 800, + format: 'jpeg', + quality: 90, + description: '800x800 · 1:1', + isCustom: false + }, + + // --- YouTube (5) --- + { + id: 'yt-thumbnail', + name: 'Thumbnail', + category: 'youtube', + width: 1280, + height: 720, + format: 'jpeg', + quality: 90, + description: '1280x720 · 16:9', + isCustom: false + }, + { + id: 'yt-thumbnail-hd', + name: 'Thumbnail (HD)', + category: 'youtube', + width: 1920, + height: 1080, + format: 'jpeg', + quality: 90, + description: '1920x1080 · 16:9', + isCustom: false + }, + { + id: 'yt-banner', + name: 'Channel Banner', + category: 'youtube', + width: 2560, + height: 1440, + format: 'jpeg', + quality: 85, + description: '2560x1440 · 16:9', + isCustom: false + }, + { + id: 'yt-shorts', + name: 'Shorts Cover', + category: 'youtube', + width: 1080, + height: 1920, + format: 'jpeg', + quality: 85, + description: '1080x1920 · 9:16', + isCustom: false + }, + { + id: 'yt-profile', + name: 'Profile', + category: 'youtube', + width: 800, + height: 800, + format: 'jpeg', + quality: 90, + description: '800x800 · 1:1', + isCustom: false + }, + + // --- TikTok (2) --- + { + id: 'tt-cover', + name: 'Cover / Thumbnail', + category: 'tiktok', + width: 1080, + height: 1920, + format: 'jpeg', + quality: 85, + description: '1080x1920 · 9:16', + isCustom: false + }, + { + id: 'tt-profile', + name: 'Profile', + category: 'tiktok', + width: 200, + height: 200, + format: 'jpeg', + quality: 90, + description: '200x200 · 1:1', + isCustom: false + }, + + // --- LinkedIn (5) --- + { + id: 'li-post-landscape', + name: 'Post (Landscape)', + category: 'linkedin', + width: 1200, + height: 627, + format: 'jpeg', + quality: 80, + description: '1200x627 · 1.91:1', + isCustom: false + }, + { + id: 'li-post-square', + name: 'Post (Square)', + category: 'linkedin', + width: 1080, + height: 1080, + format: 'jpeg', + quality: 80, + description: '1080x1080 · 1:1', + isCustom: false + }, + { + id: 'li-profile-banner', + name: 'Profile Banner', + category: 'linkedin', + width: 1584, + height: 396, + format: 'jpeg', + quality: 85, + description: '1584x396 · 4:1', + isCustom: false + }, + { + id: 'li-company-banner', + name: 'Company Banner', + category: 'linkedin', + width: 1128, + height: 191, + format: 'jpeg', + quality: 85, + description: '1128x191 · ~6:1', + isCustom: false + }, + { + id: 'li-profile', + name: 'Profile', + category: 'linkedin', + width: 400, + height: 400, + format: 'jpeg', + quality: 90, + description: '400x400 · 1:1', + isCustom: false + }, + + // --- 일반 (1) --- + { + id: 'general-original', + name: '원본 비율', + category: 'general', + width: null, + height: null, + format: 'jpeg', + quality: 90, + description: '원본 크기 · 비율 유지', + isCustom: false + } +] + +// main process에서 프리셋 조회용 맵 (자동 생성) +export const BUILT_IN_PRESET_MAP: Record = Object.fromEntries( + BUILT_IN_PRESETS.map((p) => [ + p.id, + { id: p.id, width: p.width, height: p.height, format: p.format, quality: p.quality } + ]) +) + +export const getGroupedPresets = (customPresets: PresetType[] = []) => { + const allPresets = [...BUILT_IN_PRESETS, ...customPresets] + return (Object.keys(PRESET_CATEGORIES) as PresetCategoryType[]).map((category) => ({ + category, + label: PRESET_CATEGORIES[category], + presets: allPresets.filter((p) => p.category === category) + })) +} diff --git a/src/shared/types.ts b/src/shared/types.ts new file mode 100644 index 0000000..5e0194f --- /dev/null +++ b/src/shared/types.ts @@ -0,0 +1,55 @@ +// --- main/renderer 공유 타입 --- + +export type OutputFormatType = 'jpeg' | 'webp' + +export type FrameStyleType = 'none' | 'minimal-white' + +export type ResizeFitType = 'cover' | 'contain' | 'fill' | 'inside' | 'outside' + +export type PresetCategoryType = + | 'instagram' + | 'facebook' + | 'twitter' + | 'youtube' + | 'tiktok' + | 'linkedin' + | 'general' + +export type ResizeModeType = + | { kind: 'preset-fit'; fit: ResizeFitType } + | { kind: 'aspect-ratio' } + | { kind: 'long-side'; pixels: number } + | { kind: 'short-side'; pixels: number } + | { kind: 'width'; pixels: number } + | { kind: 'height'; pixels: number } + +export type ExifDataType = { + cameraBrand: string | null + cameraModel: string | null + lens: string | null + aperture: string | null + shutterSpeed: string | null + iso: number | null + focalLength: string | null + dateTime: string | null +} + +export type PresetType = { + id: string + name: string + category: PresetCategoryType + width: number | null + height: number | null + format: OutputFormatType + quality: number + description: string + isCustom: boolean +} + +export type PresetLookupType = { + id: string + width: number | null + height: number | null + format: OutputFormatType + quality: number +} diff --git a/tsconfig.node.json b/tsconfig.node.json index 0ad9799..95b3e08 100644 --- a/tsconfig.node.json +++ b/tsconfig.node.json @@ -6,7 +6,7 @@ "target": "ESNext", "lib": ["ESNext"], "outDir": "./out", - "rootDir": "./src", + "rootDir": ".", "strict": true, "esModuleInterop": true, "skipLibCheck": true, @@ -18,6 +18,7 @@ "include": [ "src/main/**/*", "src/preload/**/*", + "src/shared/**/*", "electron.vite.config.ts" ] } diff --git a/tsconfig.web.json b/tsconfig.web.json index dba144b..29c161f 100644 --- a/tsconfig.web.json +++ b/tsconfig.web.json @@ -6,7 +6,7 @@ "target": "ESNext", "lib": ["ESNext", "DOM", "DOM.Iterable"], "outDir": "./out", - "rootDir": "./src/renderer/src", + "rootDir": "./src", "strict": true, "esModuleInterop": true, "skipLibCheck": true, @@ -16,5 +16,5 @@ "jsx": "react-jsx", "types": ["node"] }, - "include": ["src/renderer/src/**/*"] + "include": ["src/renderer/src/**/*", "src/shared/**/*"] }