Initial commit

This commit is contained in:
2025-07-04 22:10:37 +00:00
commit b4b3790113
31 changed files with 6791 additions and 0 deletions

BIN
.DS_Store vendored Normal file

Binary file not shown.

64
.gitignore vendored Normal file
View File

@ -0,0 +1,64 @@
# ---> Swift
# Xcode
#
# gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore
## User settings
xcuserdata/
## Obj-C/Swift specific
*.hmap
## App packaging
*.ipa
*.dSYM.zip
*.dSYM
## Playgrounds
timeline.xctimeline
playground.xcworkspace
# Swift Package Manager
#
# Add this line if you want to avoid checking in source code from Swift Package Manager dependencies.
# Packages/
# Package.pins
# Package.resolved
# *.xcodeproj
#
# Xcode automatically generates this directory with a .xcworkspacedata file and xcuserdata
# hence it is not needed unless you have added a package configuration file to your project
# .swiftpm
.build/
# CocoaPods
#
# We recommend against adding the Pods directory to your .gitignore. However
# you should judge for yourself, the pros and cons are mentioned at:
# https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control
#
# Pods/
#
# Add this line if you want to avoid checking in source code from the Xcode workspace
# *.xcworkspace
# Carthage
#
# Add this line if you want to avoid checking in source code from Carthage dependencies.
# Carthage/Checkouts
Carthage/Build/
# fastlane
#
# It is recommended to not store the screenshots in the git repo.
# Instead, use fastlane to re-generate the screenshots whenever they are needed.
# For more information about the recommended setup visit:
# https://docs.fastlane.tools/best-practices/source-control/#source-control
fastlane/report.xml
fastlane/Preview.html
fastlane/screenshots/**/*.png
fastlane/test_output

235
LICENSE Normal file
View File

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

3
README.md Normal file
View File

@ -0,0 +1,3 @@
# SwiftForge
A native SwiftUI application for interacting with any Gitea or Forgejo instance.

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

50
SwiftForge.icon/icon.json Normal file
View File

@ -0,0 +1,50 @@
{
"fill" : {
"linear-gradient" : [
"display-p3:0.00000,1.00000,0.68361,1.00000",
"extended-srgb:0.00000,0.53333,1.00000,1.00000"
]
},
"groups" : [
{
"layers" : [
{
"fill-specializations" : [
{
"appearance" : "dark",
"value" : {
"linear-gradient" : [
"display-p3:0.00000,1.00000,0.68361,1.00000",
"extended-srgb:0.00000,0.53333,1.00000,1.00000"
]
}
}
],
"image-name" : "swiftforge.png",
"name" : "swiftforge",
"position" : {
"scale" : 2,
"translation-in-points" : [
0,
0
]
}
}
],
"shadow" : {
"kind" : "neutral",
"opacity" : 0.5
},
"translucency" : {
"enabled" : true,
"value" : 0.5
}
}
],
"supported-platforms" : {
"circles" : [
"watchOS"
],
"squares" : "shared"
}
}

View File

@ -0,0 +1,572 @@
// !$*UTF8*$!
{
archiveVersion = 1;
classes = {
};
objectVersion = 77;
objects = {
/* Begin PBXBuildFile section */
D26E8EE02E18A3B700AF6152 /* SwiftForge.icon in Resources */ = {isa = PBXBuildFile; fileRef = D26E8EDF2E18A3B700AF6152 /* SwiftForge.icon */; };
/* End PBXBuildFile section */
/* Begin PBXContainerItemProxy section */
D2F15E032E188949006453A8 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = D2F15DED2E188948006453A8 /* Project object */;
proxyType = 1;
remoteGlobalIDString = D2F15DF42E188948006453A8;
remoteInfo = SwiftForge;
};
D2F15E0D2E188949006453A8 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = D2F15DED2E188948006453A8 /* Project object */;
proxyType = 1;
remoteGlobalIDString = D2F15DF42E188948006453A8;
remoteInfo = SwiftForge;
};
/* End PBXContainerItemProxy section */
/* Begin PBXFileReference section */
D26E8EDF2E18A3B700AF6152 /* SwiftForge.icon */ = {isa = PBXFileReference; lastKnownFileType = folder.iconcomposer.icon; path = SwiftForge.icon; sourceTree = "<group>"; };
D2F15DF52E188948006453A8 /* SwiftForge.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = SwiftForge.app; sourceTree = BUILT_PRODUCTS_DIR; };
D2F15E022E188949006453A8 /* SwiftForgeTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = SwiftForgeTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
D2F15E0C2E188949006453A8 /* SwiftForgeUITests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = SwiftForgeUITests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
/* End PBXFileReference section */
/* Begin PBXFileSystemSynchronizedRootGroup section */
D2F15DF72E188948006453A8 /* SwiftForge */ = {
isa = PBXFileSystemSynchronizedRootGroup;
path = SwiftForge;
sourceTree = "<group>";
};
D2F15E052E188949006453A8 /* SwiftForgeTests */ = {
isa = PBXFileSystemSynchronizedRootGroup;
path = SwiftForgeTests;
sourceTree = "<group>";
};
D2F15E0F2E188949006453A8 /* SwiftForgeUITests */ = {
isa = PBXFileSystemSynchronizedRootGroup;
path = SwiftForgeUITests;
sourceTree = "<group>";
};
/* End PBXFileSystemSynchronizedRootGroup section */
/* Begin PBXFrameworksBuildPhase section */
D2F15DF22E188948006453A8 /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
D2F15DFF2E188949006453A8 /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
D2F15E092E188949006453A8 /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */
D2F15DEC2E188948006453A8 = {
isa = PBXGroup;
children = (
D26E8EDF2E18A3B700AF6152 /* SwiftForge.icon */,
D2F15DF72E188948006453A8 /* SwiftForge */,
D2F15E052E188949006453A8 /* SwiftForgeTests */,
D2F15E0F2E188949006453A8 /* SwiftForgeUITests */,
D2F15DF62E188948006453A8 /* Products */,
);
sourceTree = "<group>";
};
D2F15DF62E188948006453A8 /* Products */ = {
isa = PBXGroup;
children = (
D2F15DF52E188948006453A8 /* SwiftForge.app */,
D2F15E022E188949006453A8 /* SwiftForgeTests.xctest */,
D2F15E0C2E188949006453A8 /* SwiftForgeUITests.xctest */,
);
name = Products;
sourceTree = "<group>";
};
/* End PBXGroup section */
/* Begin PBXNativeTarget section */
D2F15DF42E188948006453A8 /* SwiftForge */ = {
isa = PBXNativeTarget;
buildConfigurationList = D2F15E162E188949006453A8 /* Build configuration list for PBXNativeTarget "SwiftForge" */;
buildPhases = (
D2F15DF12E188948006453A8 /* Sources */,
D2F15DF22E188948006453A8 /* Frameworks */,
D2F15DF32E188948006453A8 /* Resources */,
);
buildRules = (
);
dependencies = (
);
fileSystemSynchronizedGroups = (
D2F15DF72E188948006453A8 /* SwiftForge */,
);
name = SwiftForge;
packageProductDependencies = (
);
productName = SwiftForge;
productReference = D2F15DF52E188948006453A8 /* SwiftForge.app */;
productType = "com.apple.product-type.application";
};
D2F15E012E188949006453A8 /* SwiftForgeTests */ = {
isa = PBXNativeTarget;
buildConfigurationList = D2F15E192E188949006453A8 /* Build configuration list for PBXNativeTarget "SwiftForgeTests" */;
buildPhases = (
D2F15DFE2E188949006453A8 /* Sources */,
D2F15DFF2E188949006453A8 /* Frameworks */,
D2F15E002E188949006453A8 /* Resources */,
);
buildRules = (
);
dependencies = (
D2F15E042E188949006453A8 /* PBXTargetDependency */,
);
fileSystemSynchronizedGroups = (
D2F15E052E188949006453A8 /* SwiftForgeTests */,
);
name = SwiftForgeTests;
packageProductDependencies = (
);
productName = SwiftForgeTests;
productReference = D2F15E022E188949006453A8 /* SwiftForgeTests.xctest */;
productType = "com.apple.product-type.bundle.unit-test";
};
D2F15E0B2E188949006453A8 /* SwiftForgeUITests */ = {
isa = PBXNativeTarget;
buildConfigurationList = D2F15E1C2E188949006453A8 /* Build configuration list for PBXNativeTarget "SwiftForgeUITests" */;
buildPhases = (
D2F15E082E188949006453A8 /* Sources */,
D2F15E092E188949006453A8 /* Frameworks */,
D2F15E0A2E188949006453A8 /* Resources */,
);
buildRules = (
);
dependencies = (
D2F15E0E2E188949006453A8 /* PBXTargetDependency */,
);
fileSystemSynchronizedGroups = (
D2F15E0F2E188949006453A8 /* SwiftForgeUITests */,
);
name = SwiftForgeUITests;
packageProductDependencies = (
);
productName = SwiftForgeUITests;
productReference = D2F15E0C2E188949006453A8 /* SwiftForgeUITests.xctest */;
productType = "com.apple.product-type.bundle.ui-testing";
};
/* End PBXNativeTarget section */
/* Begin PBXProject section */
D2F15DED2E188948006453A8 /* Project object */ = {
isa = PBXProject;
attributes = {
BuildIndependentTargetsInParallel = 1;
LastSwiftUpdateCheck = 1640;
LastUpgradeCheck = 2600;
TargetAttributes = {
D2F15DF42E188948006453A8 = {
CreatedOnToolsVersion = 16.4;
};
D2F15E012E188949006453A8 = {
CreatedOnToolsVersion = 16.4;
TestTargetID = D2F15DF42E188948006453A8;
};
D2F15E0B2E188949006453A8 = {
CreatedOnToolsVersion = 16.4;
TestTargetID = D2F15DF42E188948006453A8;
};
};
};
buildConfigurationList = D2F15DF02E188948006453A8 /* Build configuration list for PBXProject "SwiftForge" */;
developmentRegion = en;
hasScannedForEncodings = 0;
knownRegions = (
en,
Base,
);
mainGroup = D2F15DEC2E188948006453A8;
minimizedProjectReferenceProxies = 1;
preferredProjectObjectVersion = 77;
productRefGroup = D2F15DF62E188948006453A8 /* Products */;
projectDirPath = "";
projectRoot = "";
targets = (
D2F15DF42E188948006453A8 /* SwiftForge */,
D2F15E012E188949006453A8 /* SwiftForgeTests */,
D2F15E0B2E188949006453A8 /* SwiftForgeUITests */,
);
};
/* End PBXProject section */
/* Begin PBXResourcesBuildPhase section */
D2F15DF32E188948006453A8 /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
D26E8EE02E18A3B700AF6152 /* SwiftForge.icon in Resources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
D2F15E002E188949006453A8 /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
D2F15E0A2E188949006453A8 /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXResourcesBuildPhase section */
/* Begin PBXSourcesBuildPhase section */
D2F15DF12E188948006453A8 /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
D2F15DFE2E188949006453A8 /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
D2F15E082E188949006453A8 /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXSourcesBuildPhase section */
/* Begin PBXTargetDependency section */
D2F15E042E188949006453A8 /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
target = D2F15DF42E188948006453A8 /* SwiftForge */;
targetProxy = D2F15E032E188949006453A8 /* PBXContainerItemProxy */;
};
D2F15E0E2E188949006453A8 /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
target = D2F15DF42E188948006453A8 /* SwiftForge */;
targetProxy = D2F15E0D2E188949006453A8 /* PBXContainerItemProxy */;
};
/* End PBXTargetDependency section */
/* Begin XCBuildConfiguration section */
D2F15E142E188949006453A8 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES;
CLANG_ANALYZER_NONNULL = YES;
CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++20";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_ENABLE_OBJC_WEAK = YES;
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_COMMA = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
CLANG_WARN_STRICT_PROTOTYPES = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
COPY_PHASE_STRIP = NO;
DEBUG_INFORMATION_FORMAT = dwarf;
DEVELOPMENT_TEAM = 4BC9Y2LL4B;
ENABLE_STRICT_OBJC_MSGSEND = YES;
ENABLE_TESTABILITY = YES;
ENABLE_USER_SCRIPT_SANDBOXING = YES;
GCC_C_LANGUAGE_STANDARD = gnu17;
GCC_DYNAMIC_NO_PIC = NO;
GCC_NO_COMMON_BLOCKS = YES;
GCC_OPTIMIZATION_LEVEL = 0;
GCC_PREPROCESSOR_DEFINITIONS = (
"DEBUG=1",
"$(inherited)",
);
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
GCC_WARN_UNDECLARED_SELECTOR = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 18.5;
LOCALIZATION_PREFERS_STRING_CATALOGS = YES;
MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE;
MTL_FAST_MATH = YES;
ONLY_ACTIVE_ARCH = YES;
SDKROOT = iphoneos;
STRING_CATALOG_GENERATE_SYMBOLS = YES;
SWIFT_ACTIVE_COMPILATION_CONDITIONS = "DEBUG $(inherited)";
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
};
name = Debug;
};
D2F15E152E188949006453A8 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES;
CLANG_ANALYZER_NONNULL = YES;
CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++20";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_ENABLE_OBJC_WEAK = YES;
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_COMMA = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
CLANG_WARN_STRICT_PROTOTYPES = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
COPY_PHASE_STRIP = NO;
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
DEVELOPMENT_TEAM = 4BC9Y2LL4B;
ENABLE_NS_ASSERTIONS = NO;
ENABLE_STRICT_OBJC_MSGSEND = YES;
ENABLE_USER_SCRIPT_SANDBOXING = YES;
GCC_C_LANGUAGE_STANDARD = gnu17;
GCC_NO_COMMON_BLOCKS = YES;
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
GCC_WARN_UNDECLARED_SELECTOR = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 18.5;
LOCALIZATION_PREFERS_STRING_CATALOGS = YES;
MTL_ENABLE_DEBUG_INFO = NO;
MTL_FAST_MATH = YES;
SDKROOT = iphoneos;
STRING_CATALOG_GENERATE_SYMBOLS = YES;
SWIFT_COMPILATION_MODE = wholemodule;
VALIDATE_PRODUCT = YES;
};
name = Release;
};
D2F15E172E188949006453A8 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = SwiftForge;
ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 1;
DEVELOPMENT_TEAM = 4BC9Y2LL4B;
ENABLE_PREVIEWS = YES;
GENERATE_INFOPLIST_FILE = YES;
INFOPLIST_KEY_UIApplicationSceneManifest_Generation = YES;
INFOPLIST_KEY_UIApplicationSupportsIndirectInputEvents = YES;
INFOPLIST_KEY_UILaunchScreen_Generation = YES;
INFOPLIST_KEY_UISupportedInterfaceOrientations_iPad = "UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight";
INFOPLIST_KEY_UISupportedInterfaceOrientations_iPhone = "UIInterfaceOrientationPortrait UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight";
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
);
MARKETING_VERSION = 1.0;
PRODUCT_BUNDLE_IDENTIFIER = com.atridad.SwiftForge;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_EMIT_LOC_STRINGS = YES;
SWIFT_VERSION = 5.0;
TARGETED_DEVICE_FAMILY = "1,2";
};
name = Debug;
};
D2F15E182E188949006453A8 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = SwiftForge;
ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 1;
DEVELOPMENT_TEAM = 4BC9Y2LL4B;
ENABLE_PREVIEWS = YES;
GENERATE_INFOPLIST_FILE = YES;
INFOPLIST_KEY_UIApplicationSceneManifest_Generation = YES;
INFOPLIST_KEY_UIApplicationSupportsIndirectInputEvents = YES;
INFOPLIST_KEY_UILaunchScreen_Generation = YES;
INFOPLIST_KEY_UISupportedInterfaceOrientations_iPad = "UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight";
INFOPLIST_KEY_UISupportedInterfaceOrientations_iPhone = "UIInterfaceOrientationPortrait UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight";
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
);
MARKETING_VERSION = 1.0;
PRODUCT_BUNDLE_IDENTIFIER = com.atridad.SwiftForge;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_EMIT_LOC_STRINGS = YES;
SWIFT_VERSION = 5.0;
TARGETED_DEVICE_FAMILY = "1,2";
};
name = Release;
};
D2F15E1A2E188949006453A8 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
BUNDLE_LOADER = "$(TEST_HOST)";
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 1;
DEVELOPMENT_TEAM = 4BC9Y2LL4B;
GENERATE_INFOPLIST_FILE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 18.5;
MARKETING_VERSION = 1.0;
PRODUCT_BUNDLE_IDENTIFIER = com.atridad.SwiftForgeTests;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_EMIT_LOC_STRINGS = NO;
SWIFT_VERSION = 5.0;
TARGETED_DEVICE_FAMILY = "1,2";
TEST_HOST = "$(BUILT_PRODUCTS_DIR)/SwiftForge.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/SwiftForge";
};
name = Debug;
};
D2F15E1B2E188949006453A8 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
BUNDLE_LOADER = "$(TEST_HOST)";
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 1;
DEVELOPMENT_TEAM = 4BC9Y2LL4B;
GENERATE_INFOPLIST_FILE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 18.5;
MARKETING_VERSION = 1.0;
PRODUCT_BUNDLE_IDENTIFIER = com.atridad.SwiftForgeTests;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_EMIT_LOC_STRINGS = NO;
SWIFT_VERSION = 5.0;
TARGETED_DEVICE_FAMILY = "1,2";
TEST_HOST = "$(BUILT_PRODUCTS_DIR)/SwiftForge.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/SwiftForge";
};
name = Release;
};
D2F15E1D2E188949006453A8 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 1;
DEVELOPMENT_TEAM = 4BC9Y2LL4B;
GENERATE_INFOPLIST_FILE = YES;
MARKETING_VERSION = 1.0;
PRODUCT_BUNDLE_IDENTIFIER = com.atridad.SwiftForgeUITests;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_EMIT_LOC_STRINGS = NO;
SWIFT_VERSION = 5.0;
TARGETED_DEVICE_FAMILY = "1,2";
TEST_TARGET_NAME = SwiftForge;
};
name = Debug;
};
D2F15E1E2E188949006453A8 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 1;
DEVELOPMENT_TEAM = 4BC9Y2LL4B;
GENERATE_INFOPLIST_FILE = YES;
MARKETING_VERSION = 1.0;
PRODUCT_BUNDLE_IDENTIFIER = com.atridad.SwiftForgeUITests;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_EMIT_LOC_STRINGS = NO;
SWIFT_VERSION = 5.0;
TARGETED_DEVICE_FAMILY = "1,2";
TEST_TARGET_NAME = SwiftForge;
};
name = Release;
};
/* End XCBuildConfiguration section */
/* Begin XCConfigurationList section */
D2F15DF02E188948006453A8 /* Build configuration list for PBXProject "SwiftForge" */ = {
isa = XCConfigurationList;
buildConfigurations = (
D2F15E142E188949006453A8 /* Debug */,
D2F15E152E188949006453A8 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
D2F15E162E188949006453A8 /* Build configuration list for PBXNativeTarget "SwiftForge" */ = {
isa = XCConfigurationList;
buildConfigurations = (
D2F15E172E188949006453A8 /* Debug */,
D2F15E182E188949006453A8 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
D2F15E192E188949006453A8 /* Build configuration list for PBXNativeTarget "SwiftForgeTests" */ = {
isa = XCConfigurationList;
buildConfigurations = (
D2F15E1A2E188949006453A8 /* Debug */,
D2F15E1B2E188949006453A8 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
D2F15E1C2E188949006453A8 /* Build configuration list for PBXNativeTarget "SwiftForgeUITests" */ = {
isa = XCConfigurationList;
buildConfigurations = (
D2F15E1D2E188949006453A8 /* Debug */,
D2F15E1E2E188949006453A8 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
/* End XCConfigurationList section */
};
rootObject = D2F15DED2E188948006453A8 /* Project object */;
}

View File

@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<Workspace
version = "1.0">
<FileRef
location = "self:">
</FileRef>
</Workspace>

View File

@ -0,0 +1,11 @@
{
"colors" : [
{
"idiom" : "universal"
}
],
"info" : {
"author" : "xcode",
"version" : 1
}
}

View File

@ -0,0 +1,35 @@
{
"images" : [
{
"idiom" : "universal",
"platform" : "ios",
"size" : "1024x1024"
},
{
"appearances" : [
{
"appearance" : "luminosity",
"value" : "dark"
}
],
"idiom" : "universal",
"platform" : "ios",
"size" : "1024x1024"
},
{
"appearances" : [
{
"appearance" : "luminosity",
"value" : "tinted"
}
],
"idiom" : "universal",
"platform" : "ios",
"size" : "1024x1024"
}
],
"info" : {
"author" : "xcode",
"version" : 1
}
}

View File

@ -0,0 +1,23 @@
{
"images" : [
{
"filename" : "swiftforge.png",
"idiom" : "universal",
"scale" : "1x"
},
{
"filename" : "swiftforge 1.png",
"idiom" : "universal",
"scale" : "2x"
},
{
"filename" : "swiftforge 2.png",
"idiom" : "universal",
"scale" : "3x"
}
],
"info" : {
"author" : "xcode",
"version" : 1
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

View File

@ -0,0 +1,6 @@
{
"info" : {
"author" : "xcode",
"version" : 1
}
}

View File

@ -0,0 +1,354 @@
//
// ContentView.swift
// SwiftForge
//
// Created by Atridad Lahiji on 2025-07-04.
//
import Foundation
import SwiftUI
struct ContentView: View {
@EnvironmentObject var authManager: AuthenticationManager
@EnvironmentObject var settingsManager: SettingsManager
@State private var isCheckingAuth = true
@Environment(\.scenePhase) private var scenePhase
var body: some View {
Group {
if isCheckingAuth {
AppLoadingView()
} else if authManager.isAuthenticated {
MainTabView()
} else {
LoginView()
}
}
.preferredColorScheme(settingsManager.theme.colorScheme)
.accentColor(settingsManager.accentColor.color)
.animation(.easeInOut(duration: 0.3), value: authManager.isAuthenticated)
.onAppear {
checkAuthenticationStatus()
}
}
private func checkAuthenticationStatus() {
// Check authentication status first
authManager.checkAuthenticationStatus()
// Give it a moment to complete the check
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
isCheckingAuth = false
}
}
}
struct AppLoadingView: View {
@State private var isAnimating = false
var body: some View {
VStack(spacing: 20) {
Image("AppLogo")
.font(.system(size: 60))
.foregroundColor(.accentColor)
.scaleEffect(isAnimating ? 1.1 : 1.0)
.animation(
.easeInOut(duration: 1.0).repeatForever(autoreverses: true), value: isAnimating)
Text("SwiftForge")
.font(.largeTitle)
.fontWeight(.bold)
ProgressView()
.progressViewStyle(CircularProgressViewStyle(tint: .accentColor))
.scaleEffect(1.2)
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background(Color(.systemBackground))
.onAppear {
isAnimating = true
}
}
}
struct MainTabView: View {
@EnvironmentObject var authManager: AuthenticationManager
@State private var selectedTab = 0
var body: some View {
TabView(selection: $selectedTab) {
NavigationStack {
RepositoriesView()
}
.tabItem {
Image(systemName: "folder")
Text("Repositories")
}
.tag(0)
NavigationStack {
ProfileView()
}
.tabItem {
Image(systemName: "person.circle")
Text("Profile")
}
.tag(1)
}
.onAppear {
}
}
}
struct LoginView: View {
@EnvironmentObject var authManager: AuthenticationManager
@State private var serverURL = ""
@State private var token = ""
@State private var showingTokenHelp = false
var body: some View {
NavigationStack {
VStack(spacing: 24) {
// Header
VStack(spacing: 16) {
Image(systemName: "hammer.fill")
.font(.system(size: 60))
.foregroundColor(.accentColor)
Text("SwiftForge")
.font(.largeTitle)
.fontWeight(.bold)
Text("Connect to your Gitea instance")
.font(.subheadline)
.foregroundColor(.secondary)
.multilineTextAlignment(.center)
}
.padding(.top, 40)
// Form
VStack(spacing: 20) {
VStack(alignment: .leading, spacing: 8) {
Text("Server URL")
.font(.headline)
TextField("https://gitea.example.com", text: $serverURL)
.textFieldStyle(RoundedBorderTextFieldStyle())
.autocapitalization(.none)
.disableAutocorrection(true)
.keyboardType(.URL)
}
VStack(alignment: .leading, spacing: 8) {
HStack {
Text("Access Token")
.font(.headline)
Spacer()
Button("Help") {
showingTokenHelp = true
}
.font(.caption)
}
SecureField("Enter your access token", text: $token)
.textFieldStyle(RoundedBorderTextFieldStyle())
.autocapitalization(.none)
.disableAutocorrection(true)
}
}
.padding(.horizontal)
// Error message
if let errorMessage = authManager.errorMessage {
Text(errorMessage)
.foregroundColor(.red)
.font(.caption)
.multilineTextAlignment(.center)
.padding(.horizontal)
}
// Login button
Button(action: login) {
HStack {
if authManager.isLoading {
ProgressView()
.progressViewStyle(CircularProgressViewStyle(tint: .white))
.scaleEffect(0.8)
} else {
Image(systemName: "person.badge.key")
}
Text("Sign In")
}
.frame(maxWidth: .infinity)
.padding()
.background(canLogin ? Color.accentColor : Color.gray)
.foregroundColor(.white)
.cornerRadius(10)
}
.disabled(!canLogin || authManager.isLoading)
.padding(.horizontal)
Spacer()
// Footer
VStack(spacing: 8) {
Text("Secure authentication using")
.font(.caption)
.foregroundColor(.secondary)
HStack(spacing: 4) {
Image(systemName: "lock.shield")
.font(.caption)
Text("Keychain")
.font(.caption)
}
.foregroundColor(.secondary)
}
.padding(.bottom, 20)
}
.navigationTitle("")
.navigationBarHidden(true)
}
.sheet(isPresented: $showingTokenHelp) {
TokenHelpView()
}
.onAppear {
serverURL = authManager.serverURL
}
}
private var canLogin: Bool {
!serverURL.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
&& !token.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
}
private func login() {
Task {
await authManager.login(
serverURL: serverURL.trimmingCharacters(in: .whitespacesAndNewlines),
token: token.trimmingCharacters(in: .whitespacesAndNewlines)
)
}
}
}
struct TokenHelpView: View {
@Environment(\.dismiss) private var dismiss
var body: some View {
NavigationStack {
ScrollView {
VStack(alignment: .leading, spacing: 20) {
VStack(alignment: .leading, spacing: 12) {
Text("How to get your Access Token")
.font(.title2)
.fontWeight(.semibold)
Text("Follow these steps to create an access token in your Gitea instance:")
.foregroundColor(.secondary)
}
VStack(alignment: .leading, spacing: 16) {
StepView(
number: 1,
title: "Sign in to Gitea",
description:
"Open your Gitea instance in a web browser and sign in to your account."
)
StepView(
number: 2,
title: "Go to Settings",
description:
"Click on your profile picture in the top right corner and select 'Settings'."
)
StepView(
number: 3,
title: "Navigate to Applications",
description: "In the settings sidebar, click on 'Applications'."
)
StepView(
number: 4,
title: "Create Access Token",
description:
"Under 'Manage Access Tokens', enter a token name (e.g., 'SwiftForge') and click 'Generate Token'."
)
StepView(
number: 5,
title: "Copy the Token",
description:
"Copy the generated token immediately - you won't be able to see it again!"
)
}
VStack(alignment: .leading, spacing: 8) {
HStack {
Image(systemName: "exclamationmark.triangle.fill")
.foregroundColor(.orange)
Text("Important")
.fontWeight(.semibold)
}
Text(
"Keep your access token secure and don't share it with others. SwiftForge stores your token securely in the iOS Keychain."
)
.font(.caption)
.foregroundColor(.secondary)
}
.padding()
.background(Color.orange.opacity(0.1))
.cornerRadius(8)
}
.padding()
}
.navigationTitle("Access Token Help")
.navigationBarTitleDisplayMode(.inline)
.navigationBarBackButtonHidden(true)
.toolbar {
ToolbarItem(placement: .navigationBarTrailing) {
Button("Done") {
dismiss()
}
}
}
}
}
}
struct StepView: View {
let number: Int
let title: String
let description: String
var body: some View {
HStack(alignment: .top, spacing: 12) {
Text("\(number)")
.font(.caption)
.fontWeight(.bold)
.foregroundColor(.white)
.frame(width: 24, height: 24)
.background(Color.accentColor)
.clipShape(Circle())
VStack(alignment: .leading, spacing: 4) {
Text(title)
.fontWeight(.medium)
Text(description)
.font(.caption)
.foregroundColor(.secondary)
}
}
}
}
#Preview {
ContentView()
.environmentObject(AuthenticationManager())
.environmentObject(SettingsManager())
}

View File

@ -0,0 +1,327 @@
//
// AuthenticationManager.swift
// SwiftForge
//
// Created by Atridad Lahiji on 2025-07-04.
//
import Combine
import Foundation
import Security
@MainActor
class AuthenticationManager: ObservableObject {
@Published var isAuthenticated = false
@Published var currentUser: User?
@Published var serverURL: String = ""
@Published var isLoading = false
@Published var errorMessage: String?
@Published private var isUpdatingProfile = false
private let keychainService = "com.swiftforge.gitea"
private let tokenKey = "gitea_token"
private let serverURLKey = "gitea_server_url"
private let userDefaultsKey = "gitea_settings"
private var apiService: GiteaAPIService?
private var cancellables = Set<AnyCancellable>()
init() {
loadStoredCredentials()
}
// MARK: - Public Methods
func login(serverURL: String, token: String) async {
isLoading = true
errorMessage = nil
do {
// Validate inputs
let trimmedURL = serverURL.trimmingCharacters(in: .whitespacesAndNewlines)
let trimmedToken = token.trimmingCharacters(in: .whitespacesAndNewlines)
guard !trimmedToken.isEmpty else {
throw AuthenticationError.invalidCredentials
}
// Validate server URL format
guard let url = URL(string: trimmedURL),
url.scheme != nil
else {
throw AuthenticationError.invalidServerURL
}
// Create API service with provided credentials
let tempAPIService = GiteaAPIService(baseURL: trimmedURL, token: trimmedToken)
// Test the connection by fetching user info
let user = try await tempAPIService.getCurrentUser()
// If successful, store credentials and update state
try storeCredentials(serverURL: trimmedURL, token: trimmedToken)
self.serverURL = trimmedURL
self.currentUser = user
self.apiService = tempAPIService
self.isAuthenticated = true
} catch {
// Provide more specific error messages
if let apiError = error as? APIError {
switch apiError {
case .unauthorized:
self.errorMessage =
"Invalid access token. Please check your token and try again."
case .notFound:
self.errorMessage = "Server not found. Please check your server URL."
case .networkError:
self.errorMessage = "Network error. Please check your internet connection."
default:
self.errorMessage = error.localizedDescription
}
} else {
self.errorMessage = error.localizedDescription
}
}
isLoading = false
}
func logout() {
// Clear stored credentials
clearCredentials()
// Reset state
isAuthenticated = false
currentUser = nil
serverURL = ""
apiService = nil
errorMessage = nil
}
func checkAuthenticationStatus() {
guard let storedToken = getStoredToken(),
let storedServerURL = getStoredServerURL(),
!storedToken.isEmpty,
!storedServerURL.isEmpty
else {
isAuthenticated = false
return
}
serverURL = storedServerURL
apiService = GiteaAPIService(baseURL: storedServerURL, token: storedToken)
// Verify token is still valid
Task {
do {
let user = try await apiService?.getCurrentUser()
await MainActor.run {
self.currentUser = user
self.isAuthenticated = true
}
} catch {
await MainActor.run {
self.logout()
}
}
}
}
func refreshUser() async {
print("DEBUG: refreshUser called")
guard let apiService = apiService else {
print("DEBUG: refreshUser failed - no API service")
return
}
do {
print("DEBUG: refreshUser calling getCurrentUser")
let user = try await apiService.getCurrentUser()
print("DEBUG: refreshUser got user: \(user.login)")
currentUser = user
} catch {
print("DEBUG: refreshUser failed with error: \(error)")
// Handle cancellation and other errors gracefully
if error is CancellationError {
print("DEBUG: refreshUser cancelled - not showing error")
// Don't show error message for cancellation
return
}
errorMessage = error.localizedDescription
}
}
func updateUserProfile(
fullName: String?, email: String?, description: String?, website: String?, location: String?
) async throws {
print("DEBUG: *** updateUserProfile called ***")
print("DEBUG: Full call stack:")
for (index, symbol) in Thread.callStackSymbols.enumerated() {
print("DEBUG: \(index): \(symbol)")
}
print("DEBUG: isUpdatingProfile: \(isUpdatingProfile)")
guard let apiService = apiService else {
print("DEBUG: updateUserProfile failed - no API service")
throw AuthenticationError.invalidCredentials
}
// Prevent concurrent profile updates
guard !isUpdatingProfile else {
print("DEBUG: updateUserProfile blocked - operation already in progress")
throw AuthenticationError.operationInProgress
}
isUpdatingProfile = true
defer {
print("DEBUG: *** updateUserProfile finished ***")
isUpdatingProfile = false
}
let settings = UserSettingsOptions(
fullName: fullName,
email: email,
description: description,
website: website,
location: location,
hideEmail: nil,
hideActivity: nil,
language: nil,
theme: nil,
diffViewStyle: nil
)
do {
let updatedUser = try await apiService.updateUserSettings(settings: settings)
currentUser = updatedUser
} catch {
errorMessage = error.localizedDescription
throw error
}
}
func updateCurrentUser(_ user: User) {
currentUser = user
}
func getAPIService() -> GiteaAPIService? {
return apiService
}
// MARK: - Private Methods
private func loadStoredCredentials() {
if let storedServerURL = getStoredServerURL() {
serverURL = storedServerURL
}
}
private func storeCredentials(serverURL: String, token: String) throws {
// Store token in Keychain
try storeTokenInKeychain(token)
// Store server URL in UserDefaults
UserDefaults.standard.set(serverURL, forKey: serverURLKey)
}
private func clearCredentials() {
// Remove token from Keychain
deleteTokenFromKeychain()
// Remove server URL from UserDefaults
UserDefaults.standard.removeObject(forKey: serverURLKey)
}
private func getStoredToken() -> String? {
return getTokenFromKeychain()
}
private func getStoredServerURL() -> String? {
return UserDefaults.standard.string(forKey: serverURLKey)
}
// MARK: - Keychain Operations
private func storeTokenInKeychain(_ token: String) throws {
let tokenData = token.data(using: .utf8)!
let query: [String: Any] = [
kSecClass as String: kSecClassGenericPassword,
kSecAttrService as String: keychainService,
kSecAttrAccount as String: tokenKey,
kSecValueData as String: tokenData,
]
// Delete existing item if it exists
SecItemDelete(query as CFDictionary)
// Add new item
let status = SecItemAdd(query as CFDictionary, nil)
if status != errSecSuccess {
throw AuthenticationError.keychainError
}
}
private func getTokenFromKeychain() -> String? {
let query: [String: Any] = [
kSecClass as String: kSecClassGenericPassword,
kSecAttrService as String: keychainService,
kSecAttrAccount as String: tokenKey,
kSecReturnData as String: true,
kSecMatchLimit as String: kSecMatchLimitOne,
]
var dataTypeRef: AnyObject?
let status = SecItemCopyMatching(query as CFDictionary, &dataTypeRef)
if status == errSecSuccess,
let data = dataTypeRef as? Data,
let token = String(data: data, encoding: .utf8)
{
return token
}
return nil
}
private func deleteTokenFromKeychain() {
let query: [String: Any] = [
kSecClass as String: kSecClassGenericPassword,
kSecAttrService as String: keychainService,
kSecAttrAccount as String: tokenKey,
]
SecItemDelete(query as CFDictionary)
}
}
// MARK: - Authentication Errors
enum AuthenticationError: LocalizedError {
case invalidServerURL
case invalidCredentials
case networkError
case keychainError
case operationInProgress
case unknownError
var errorDescription: String? {
switch self {
case .invalidServerURL:
return "Invalid server URL. Please check the URL format."
case .invalidCredentials:
return "Invalid credentials. Please check your token."
case .networkError:
return "Network error. Please check your connection."
case .keychainError:
return "Failed to store credentials securely."
case .operationInProgress:
return "A profile update is already in progress. Please wait."
case .unknownError:
return "An unknown error occurred."
}
}
}

View File

@ -0,0 +1,695 @@
//
// GiteaAPIService.swift
// SwiftForge
//
// Created by Atridad Lahiji on 2025-07-04.
//
import Combine
import Foundation
class GiteaAPIService: ObservableObject {
let baseURL: String
private let token: String
private let session: URLSession
private let decoder: JSONDecoder
init(baseURL: String, token: String) {
self.baseURL = baseURL.trimmingCharacters(in: .whitespacesAndNewlines)
self.token = token.trimmingCharacters(in: .whitespacesAndNewlines)
self.session = URLSession.shared
self.decoder = JSONDecoder()
// Configure date formatter for Gitea's ISO 8601 dates
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
decoder.dateDecodingStrategy = .formatted(dateFormatter)
}
// MARK: - Private Methods
private func createRequest(endpoint: String, method: HTTPMethod = .GET, body: Data? = nil)
-> URLRequest?
{
guard let url = URL(string: "\(baseURL)/api/v1\(endpoint)") else {
return nil
}
var request = URLRequest(url: url)
request.httpMethod = method.rawValue
// Ensure token is not empty
guard !token.isEmpty else {
return nil
}
// Set Authorization header - Gitea accepts "token <token>" format
request.setValue("token \(token)", forHTTPHeaderField: "Authorization")
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue("application/json", forHTTPHeaderField: "Accept")
if let body = body {
request.httpBody = body
}
return request
}
private func performRequest<T: Codable>(_ request: URLRequest, responseType: T.Type)
async throws -> T
{
let (data, response) = try await session.data(for: request)
guard let httpResponse = response as? HTTPURLResponse else {
throw APIError.invalidResponse
}
guard 200...299 ~= httpResponse.statusCode else {
let errorMessage = String(data: data, encoding: .utf8) ?? "Unknown error"
switch httpResponse.statusCode {
case 401:
throw APIError.unauthorized
case 404:
throw APIError.notFound
default:
throw APIError.httpError(httpResponse.statusCode, errorMessage)
}
}
do {
return try decoder.decode(T.self, from: data)
} catch {
print("Decoding error: \(error)")
if let jsonString = String(data: data, encoding: .utf8) {
print("Response data: \(jsonString)")
}
throw APIError.decodingError(error)
}
}
private func performRequest(_ request: URLRequest) async throws {
let (data, response) = try await session.data(for: request)
guard let httpResponse = response as? HTTPURLResponse else {
throw APIError.invalidResponse
}
guard 200...299 ~= httpResponse.statusCode else {
let errorMessage = String(data: data, encoding: .utf8) ?? "Unknown error"
switch httpResponse.statusCode {
case 401:
throw APIError.unauthorized
case 404:
throw APIError.notFound
default:
throw APIError.httpError(httpResponse.statusCode, errorMessage)
}
}
}
// MARK: - User API
func getCurrentUser() async throws -> User {
guard let request = createRequest(endpoint: "/user") else {
throw APIError.invalidURL
}
return try await performRequest(request, responseType: User.self)
}
func getUser(username: String) async throws -> User {
guard let request = createRequest(endpoint: "/users/\(username)") else {
throw APIError.invalidURL
}
return try await performRequest(request, responseType: User.self)
}
func getUserRepositories(username: String? = nil, page: Int = 1, limit: Int = 30) async throws
-> [Repository]
{
let endpoint = username != nil ? "/users/\(username!)/repos" : "/user/repos"
let queryParams = "?page=\(page)&limit=\(limit)"
guard let request = createRequest(endpoint: endpoint + queryParams) else {
throw APIError.invalidURL
}
return try await performRequest(request, responseType: [Repository].self)
}
func getUserOrganizations(username: String? = nil) async throws -> [Organization] {
let endpoint = username != nil ? "/users/\(username!)/orgs" : "/user/orgs"
guard let request = createRequest(endpoint: endpoint) else {
throw APIError.invalidURL
}
return try await performRequest(request, responseType: [Organization].self)
}
func getStarredRepositories(page: Int = 1, limit: Int = 30) async throws -> [Repository] {
let queryParams = "?page=\(page)&limit=\(limit)"
guard let request = createRequest(endpoint: "/user/starred" + queryParams) else {
throw APIError.invalidURL
}
return try await performRequest(request, responseType: [Repository].self)
}
// MARK: - Repository API
func getRepository(owner: String, repo: String) async throws -> Repository {
guard let request = createRequest(endpoint: "/repos/\(owner)/\(repo)") else {
throw APIError.invalidURL
}
return try await performRequest(request, responseType: Repository.self)
}
func getRepositoryIssues(
owner: String, repo: String, state: IssueState? = nil, page: Int = 1, limit: Int = 30
) async throws -> [Issue] {
var queryParams = "?page=\(page)&limit=\(limit)"
if let state = state {
queryParams += "&state=\(state.rawValue)"
}
guard let request = createRequest(endpoint: "/repos/\(owner)/\(repo)/issues" + queryParams)
else {
throw APIError.invalidURL
}
return try await performRequest(request, responseType: [Issue].self)
}
func getRepositoryPullRequests(
owner: String, repo: String, state: IssueState? = nil, page: Int = 1, limit: Int = 30
) async throws -> [PullRequest] {
var queryParams = "?page=\(page)&limit=\(limit)"
if let state = state {
queryParams += "&state=\(state.rawValue)"
}
guard let request = createRequest(endpoint: "/repos/\(owner)/\(repo)/pulls" + queryParams)
else {
throw APIError.invalidURL
}
return try await performRequest(request, responseType: [PullRequest].self)
}
func getRepositoryBranches(owner: String, repo: String) async throws -> [Branch] {
guard let request = createRequest(endpoint: "/repos/\(owner)/\(repo)/branches") else {
throw APIError.invalidURL
}
return try await performRequest(request, responseType: [Branch].self)
}
func getRepositoryCommits(
owner: String, repo: String, sha: String? = nil, page: Int = 1, limit: Int = 30
) async throws -> [Commit] {
var queryParams = "?page=\(page)&limit=\(limit)"
if let sha = sha {
queryParams += "&sha=\(sha)"
}
guard let request = createRequest(endpoint: "/repos/\(owner)/\(repo)/commits" + queryParams)
else {
throw APIError.invalidURL
}
return try await performRequest(request, responseType: [Commit].self)
}
func getRepositoryReleases(owner: String, repo: String, page: Int = 1, limit: Int = 30)
async throws -> [Release]
{
let queryParams = "?page=\(page)&limit=\(limit)"
guard
let request = createRequest(endpoint: "/repos/\(owner)/\(repo)/releases" + queryParams)
else {
throw APIError.invalidURL
}
return try await performRequest(request, responseType: [Release].self)
}
func createRepository(
name: String,
description: String? = nil,
isPrivate: Bool = false,
autoInit: Bool = true,
gitignoreTemplate: String? = nil,
licenseTemplate: String? = nil
) async throws -> Repository {
let requestBody = CreateRepositoryRequest(
name: name,
description: description,
private: isPrivate,
autoInit: autoInit,
gitignoreTemplate: gitignoreTemplate,
licenseTemplate: licenseTemplate
)
let jsonData = try JSONEncoder().encode(requestBody)
guard let request = createRequest(endpoint: "/user/repos", method: .POST, body: jsonData)
else {
throw APIError.invalidURL
}
return try await performRequest(request, responseType: Repository.self)
}
func updateRepository(owner: String, repo: String, updateData: [String: Any]) async throws -> Repository {
// Encode the dictionary to JSON data
let jsonData = try JSONSerialization.data(withJSONObject: updateData)
guard let request = createRequest(endpoint: "/repos/\(owner)/\(repo)", method: .PATCH, body: jsonData) else {
throw APIError.invalidURL
}
return try await performRequest(request, responseType: Repository.self)
}
func deleteRepository(owner: String, repo: String) async throws {
guard let request = createRequest(endpoint: "/repos/\(owner)/\(repo)", method: .DELETE)
else {
throw APIError.invalidURL
}
try await performRequest(request)
}
func starRepository(owner: String, repo: String) async throws {
guard let request = createRequest(endpoint: "/user/starred/\(owner)/\(repo)", method: .PUT)
else {
throw APIError.invalidURL
}
try await performRequest(request)
}
func unstarRepository(owner: String, repo: String) async throws {
guard
let request = createRequest(endpoint: "/user/starred/\(owner)/\(repo)", method: .DELETE)
else {
throw APIError.invalidURL
}
try await performRequest(request)
}
func watchRepository(owner: String, repo: String) async throws {
guard
let request = createRequest(
endpoint: "/repos/\(owner)/\(repo)/subscription", method: .PUT)
else {
throw APIError.invalidURL
}
try await performRequest(request)
}
func unwatchRepository(owner: String, repo: String) async throws {
guard
let request = createRequest(
endpoint: "/repos/\(owner)/\(repo)/subscription", method: .DELETE)
else {
throw APIError.invalidURL
}
try await performRequest(request)
}
// MARK: - Issue API
func getIssue(owner: String, repo: String, index: Int) async throws -> Issue {
guard let request = createRequest(endpoint: "/repos/\(owner)/\(repo)/issues/\(index)")
else {
throw APIError.invalidURL
}
return try await performRequest(request, responseType: Issue.self)
}
func getIssueComments(owner: String, repo: String, index: Int) async throws -> [Comment] {
guard
let request = createRequest(
endpoint: "/repos/\(owner)/\(repo)/issues/\(index)/comments")
else {
throw APIError.invalidURL
}
return try await performRequest(request, responseType: [Comment].self)
}
func createIssueComment(owner: String, repo: String, index: Int, body: String) async throws
-> Comment
{
let commentData = ["body": body]
let jsonData = try JSONSerialization.data(withJSONObject: commentData)
guard
let request = createRequest(
endpoint: "/repos/\(owner)/\(repo)/issues/\(index)/comments", method: .POST,
body: jsonData)
else {
throw APIError.invalidURL
}
return try await performRequest(request, responseType: Comment.self)
}
// MARK: - Pull Request API
func getPullRequest(owner: String, repo: String, index: Int) async throws -> PullRequest {
guard let request = createRequest(endpoint: "/repos/\(owner)/\(repo)/pulls/\(index)") else {
throw APIError.invalidURL
}
return try await performRequest(request, responseType: PullRequest.self)
}
func getPullRequestFiles(owner: String, repo: String, index: Int) async throws -> [CommitFile] {
guard let request = createRequest(endpoint: "/repos/\(owner)/\(repo)/pulls/\(index)/files")
else {
throw APIError.invalidURL
}
return try await performRequest(request, responseType: [CommitFile].self)
}
func getPullRequestCommits(owner: String, repo: String, index: Int) async throws -> [Commit] {
guard
let request = createRequest(endpoint: "/repos/\(owner)/\(repo)/pulls/\(index)/commits")
else {
throw APIError.invalidURL
}
return try await performRequest(request, responseType: [Commit].self)
}
// MARK: - Notifications API
func getNotifications(all: Bool = false, page: Int = 1, limit: Int = 30) async throws
-> [Notification]
{
let queryParams = "?page=\(page)&limit=\(limit)&all=\(all)"
guard let request = createRequest(endpoint: "/notifications" + queryParams) else {
throw APIError.invalidURL
}
return try await performRequest(request, responseType: [Notification].self)
}
func markNotificationAsRead(id: Int) async throws {
guard let request = createRequest(endpoint: "/notifications/threads/\(id)", method: .PATCH)
else {
throw APIError.invalidURL
}
try await performRequest(request)
}
func markAllNotificationsAsRead() async throws {
guard let request = createRequest(endpoint: "/notifications", method: .PUT) else {
throw APIError.invalidURL
}
try await performRequest(request)
}
// MARK: - Search API
func searchRepositories(query: String, page: Int = 1, limit: Int = 30) async throws
-> SearchResults<Repository>
{
let encodedQuery =
query.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? ""
let queryParams = "?q=\(encodedQuery)&page=\(page)&limit=\(limit)"
guard let request = createRequest(endpoint: "/repos/search" + queryParams) else {
throw APIError.invalidURL
}
return try await performRequest(request, responseType: SearchResults<Repository>.self)
}
func searchIssues(query: String, page: Int = 1, limit: Int = 30) async throws -> SearchResults<
Issue
> {
let encodedQuery =
query.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? ""
let queryParams = "?q=\(encodedQuery)&page=\(page)&limit=\(limit)"
guard let request = createRequest(endpoint: "/repos/issues/search" + queryParams) else {
throw APIError.invalidURL
}
return try await performRequest(request, responseType: SearchResults<Issue>.self)
}
func searchUsers(query: String, page: Int = 1, limit: Int = 30) async throws -> SearchResults<
User
> {
let encodedQuery =
query.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? ""
let queryParams = "?q=\(encodedQuery)&page=\(page)&limit=\(limit)"
guard let request = createRequest(endpoint: "/users/search" + queryParams) else {
throw APIError.invalidURL
}
return try await performRequest(request, responseType: SearchResults<User>.self)
}
// MARK: - Organization API
func getOrganization(org: String) async throws -> Organization {
guard let request = createRequest(endpoint: "/orgs/\(org)") else {
throw APIError.invalidURL
}
return try await performRequest(request, responseType: Organization.self)
}
func getOrganizationRepositories(org: String, page: Int = 1, limit: Int = 30) async throws
-> [Repository]
{
let queryParams = "?page=\(page)&limit=\(limit)"
guard let request = createRequest(endpoint: "/orgs/\(org)/repos" + queryParams) else {
throw APIError.invalidURL
}
return try await performRequest(request, responseType: [Repository].self)
}
func getOrganizationMembers(org: String, page: Int = 1, limit: Int = 30) async throws -> [User]
{
let queryParams = "?page=\(page)&limit=\(limit)"
guard let request = createRequest(endpoint: "/orgs/\(org)/members" + queryParams) else {
throw APIError.invalidURL
}
return try await performRequest(request, responseType: [User].self)
}
// MARK: - Server Info API
func getServerVersion() async throws -> ServerVersion {
guard let request = createRequest(endpoint: "/version") else {
throw APIError.invalidURL
}
return try await performRequest(request, responseType: ServerVersion.self)
}
// MARK: - User Settings API
func updateUserSettings(settings: UserSettingsOptions) async throws -> User {
print("DEBUG: updateUserSettings called with settings: \(settings)")
let encoder = JSONEncoder()
encoder.keyEncodingStrategy = .convertToSnakeCase
guard let settingsData = try? encoder.encode(settings) else {
print("DEBUG: Failed to encode settings")
throw APIError.invalidRequest
}
if let jsonString = String(data: settingsData, encoding: .utf8) {
print("DEBUG: Request JSON: \(jsonString)")
}
// Try different endpoints and methods as fallbacks
// Order by most likely to succeed first
let endpoints = [
("/user", HTTPMethod.PATCH),
("/user", HTTPMethod.PUT),
("/user/settings", HTTPMethod.PATCH),
("/user/settings", HTTPMethod.PUT),
]
var lastError: Error?
for (endpoint, method) in endpoints {
print("DEBUG: Trying \(method.rawValue) request to: \(baseURL)/api/v1\(endpoint)")
guard
let request = createRequest(endpoint: endpoint, method: method, body: settingsData)
else {
print("DEBUG: Failed to create request for \(endpoint)")
continue
}
print("DEBUG: Request headers: \(request.allHTTPHeaderFields ?? [:])")
do {
let result = try await performRequest(request, responseType: User.self)
print("DEBUG: updateUserSettings succeeded with \(method.rawValue) \(endpoint)")
return result
} catch let error as APIError {
print("DEBUG: \(method.rawValue) to \(endpoint) failed: \(error)")
lastError = error
// If it's a 405 Method Not Allowed, try the next endpoint/method
if case .httpError(405, _) = error {
continue
}
// If it's a 404 Not Found, try the next endpoint
if case .httpError(404, _) = error {
continue
}
// For authentication errors, don't retry
if case .httpError(401, _) = error {
throw error
}
if case .httpError(403, _) = error {
throw error
}
// For other client errors (4xx), still try other endpoints
if case .httpError(let code, _) = error, code >= 400 && code < 500 {
continue
}
// For server errors (5xx), don't retry
if case .httpError(let code, _) = error, code >= 500 {
throw error
}
// For other errors, still continue but this might be the final error
continue
} catch {
print("DEBUG: \(method.rawValue) to \(endpoint) failed: \(error)")
lastError = error
continue
}
}
print(
"DEBUG: All update methods failed, final error: \(lastError?.localizedDescription ?? "Unknown error")"
)
throw lastError ?? APIError.invalidResponse
}
}
// MARK: - HTTP Method
enum HTTPMethod: String {
case GET = "GET"
case POST = "POST"
case PUT = "PUT"
case DELETE = "DELETE"
case PATCH = "PATCH"
}
// MARK: - API Errors
// MARK: - Request Models
struct CreateRepositoryRequest: Codable {
let name: String
let description: String?
let `private`: Bool
let autoInit: Bool
let gitignoreTemplate: String?
let licenseTemplate: String?
enum CodingKeys: String, CodingKey {
case name, description
case `private` = "private"
case autoInit = "auto_init"
case gitignoreTemplate = "gitignore_template"
case licenseTemplate = "license_template"
}
}
struct UserSettingsOptions: Codable {
let fullName: String?
let email: String?
let description: String?
let website: String?
let location: String?
let hideEmail: Bool?
let hideActivity: Bool?
let language: String?
let theme: String?
let diffViewStyle: String?
enum CodingKeys: String, CodingKey {
case fullName = "full_name"
case email = "email"
case description = "description"
case website = "website"
case location = "location"
case hideEmail = "hide_email"
case hideActivity = "hide_activity"
case language = "language"
case theme = "theme"
case diffViewStyle = "diff_view_style"
}
}
// MARK: - API Errors
enum APIError: LocalizedError {
case invalidURL
case invalidResponse
case invalidRequest
case unauthorized
case notFound
case httpError(Int, String)
case decodingError(Error)
case networkError(Error)
var errorDescription: String? {
switch self {
case .invalidURL:
return "Invalid URL"
case .invalidResponse:
return "Invalid response"
case .invalidRequest:
return "Invalid request"
case .unauthorized:
return "Unauthorized - Invalid access token"
case .notFound:
return "Server not found"
case .httpError(let code, let message):
return "HTTP Error \(code): \(message)"
case .decodingError(let error):
return "Decoding error: \(error.localizedDescription)"
case .networkError(let error):
return "Network error: \(error.localizedDescription)"
}
}
}

View File

@ -0,0 +1,385 @@
//
// SettingsManager.swift
// SwiftForge
//
// Created by Atridad Lahiji on 2025-07-04.
//
import Foundation
import SwiftUI
@MainActor
class SettingsManager: ObservableObject {
// MARK: - Published Properties
@Published var theme: AppTheme = .system {
didSet {
UserDefaults.standard.set(theme.rawValue, forKey: "app_theme")
}
}
@Published var accentColor: AppAccentColor = .blue {
didSet {
UserDefaults.standard.set(accentColor.rawValue, forKey: "accent_color")
}
}
@Published var repositoryListStyle: RepositoryListStyle = .detailed {
didSet {
UserDefaults.standard.set(repositoryListStyle.rawValue, forKey: "repository_list_style")
}
}
@Published var defaultRepositorySort: RepositorySort = .updated {
didSet {
UserDefaults.standard.set(defaultRepositorySort.rawValue, forKey: "default_repository_sort")
}
}
@Published var showPrivateRepositories: Bool = true {
didSet {
UserDefaults.standard.set(showPrivateRepositories, forKey: "show_private_repositories")
}
}
@Published var showForkedRepositories: Bool = true {
didSet {
UserDefaults.standard.set(showForkedRepositories, forKey: "show_forked_repositories")
}
}
@Published var enableNotifications: Bool = true {
didSet {
UserDefaults.standard.set(enableNotifications, forKey: "enable_notifications")
}
}
@Published var notificationTypes: Set<NotificationType> = [.issue, .pullRequest] {
didSet {
let typeStrings = notificationTypes.map { $0.rawValue }
UserDefaults.standard.set(typeStrings, forKey: "notification_types")
}
}
@Published var enablePushNotifications: Bool = false {
didSet {
UserDefaults.standard.set(enablePushNotifications, forKey: "enable_push_notifications")
}
}
@Published var notificationSoundEnabled: Bool = true {
didSet {
UserDefaults.standard.set(notificationSoundEnabled, forKey: "notification_sound_enabled")
}
}
@Published var cacheImages: Bool = true {
didSet {
UserDefaults.standard.set(cacheImages, forKey: "cache_images")
}
}
@Published var autoRefreshInterval: RefreshInterval = .minutes5 {
didSet {
UserDefaults.standard.set(autoRefreshInterval.rawValue, forKey: "auto_refresh_interval")
}
}
@Published var enableAutoRefresh: Bool = true {
didSet {
UserDefaults.standard.set(enableAutoRefresh, forKey: "enable_auto_refresh")
}
}
@Published var defaultIssueFilter: IssueState = .open {
didSet {
UserDefaults.standard.set(defaultIssueFilter.rawValue, forKey: "default_issue_filter")
}
}
@Published var defaultPRFilter: IssueState = .open {
didSet {
UserDefaults.standard.set(defaultPRFilter.rawValue, forKey: "default_pr_filter")
}
}
@Published var enableBiometricAuth: Bool = false {
didSet {
UserDefaults.standard.set(enableBiometricAuth, forKey: "enable_biometric_auth")
}
}
@Published var requireAuthOnLaunch: Bool = false {
didSet {
UserDefaults.standard.set(requireAuthOnLaunch, forKey: "require_auth_on_launch")
}
}
@Published var enableAnalytics: Bool = false {
didSet {
UserDefaults.standard.set(enableAnalytics, forKey: "enable_analytics")
}
}
@Published var enableCrashReporting: Bool = true {
didSet {
UserDefaults.standard.set(enableCrashReporting, forKey: "enable_crash_reporting")
}
}
// MARK: - Initialization
init() {
loadSettings()
}
// MARK: - Public Methods
func loadSettings() {
// Theme
if let themeString = UserDefaults.standard.string(forKey: "app_theme"),
let savedTheme = AppTheme(rawValue: themeString) {
theme = savedTheme
}
// Accent Color
if let colorString = UserDefaults.standard.string(forKey: "accent_color"),
let savedColor = AppAccentColor(rawValue: colorString) {
accentColor = savedColor
}
// Repository List Style
if let styleString = UserDefaults.standard.string(forKey: "repository_list_style"),
let savedStyle = RepositoryListStyle(rawValue: styleString) {
repositoryListStyle = savedStyle
}
// Repository Sort
if let sortString = UserDefaults.standard.string(forKey: "default_repository_sort"),
let savedSort = RepositorySort(rawValue: sortString) {
defaultRepositorySort = savedSort
}
// Boolean settings
showPrivateRepositories = UserDefaults.standard.bool(forKey: "show_private_repositories")
showForkedRepositories = UserDefaults.standard.bool(forKey: "show_forked_repositories")
enableNotifications = UserDefaults.standard.bool(forKey: "enable_notifications")
enablePushNotifications = UserDefaults.standard.bool(forKey: "enable_push_notifications")
notificationSoundEnabled = UserDefaults.standard.bool(forKey: "notification_sound_enabled")
cacheImages = UserDefaults.standard.bool(forKey: "cache_images")
enableAutoRefresh = UserDefaults.standard.bool(forKey: "enable_auto_refresh")
enableBiometricAuth = UserDefaults.standard.bool(forKey: "enable_biometric_auth")
requireAuthOnLaunch = UserDefaults.standard.bool(forKey: "require_auth_on_launch")
enableAnalytics = UserDefaults.standard.bool(forKey: "enable_analytics")
enableCrashReporting = UserDefaults.standard.bool(forKey: "enable_crash_reporting")
// Notification Types
if let typeStrings = UserDefaults.standard.array(forKey: "notification_types") as? [String] {
notificationTypes = Set(typeStrings.compactMap { NotificationType(rawValue: $0) })
}
// Refresh Interval
if let intervalString = UserDefaults.standard.string(forKey: "auto_refresh_interval"),
let savedInterval = RefreshInterval(rawValue: intervalString) {
autoRefreshInterval = savedInterval
}
// Default Filters
if let issueFilterString = UserDefaults.standard.string(forKey: "default_issue_filter"),
let savedFilter = IssueState(rawValue: issueFilterString) {
defaultIssueFilter = savedFilter
}
if let prFilterString = UserDefaults.standard.string(forKey: "default_pr_filter"),
let savedFilter = IssueState(rawValue: prFilterString) {
defaultPRFilter = savedFilter
}
// Set default values for new installations
if !UserDefaults.standard.bool(forKey: "settings_initialized") {
setDefaultValues()
UserDefaults.standard.set(true, forKey: "settings_initialized")
}
}
func resetToDefaults() {
theme = .system
accentColor = .blue
repositoryListStyle = .detailed
defaultRepositorySort = .updated
showPrivateRepositories = true
showForkedRepositories = true
enableNotifications = true
notificationTypes = [.issue, .pullRequest]
enablePushNotifications = false
notificationSoundEnabled = true
cacheImages = true
autoRefreshInterval = .minutes5
enableAutoRefresh = true
defaultIssueFilter = .open
defaultPRFilter = .open
enableBiometricAuth = false
requireAuthOnLaunch = false
enableAnalytics = false
enableCrashReporting = true
}
func clearAllSettings() {
let keys = [
"app_theme", "accent_color", "repository_list_style", "default_repository_sort",
"show_private_repositories", "show_forked_repositories", "enable_notifications",
"notification_types", "enable_push_notifications", "notification_sound_enabled",
"cache_images", "auto_refresh_interval", "enable_auto_refresh",
"default_issue_filter", "default_pr_filter", "enable_biometric_auth",
"require_auth_on_launch", "enable_analytics", "enable_crash_reporting",
"settings_initialized"
]
keys.forEach { UserDefaults.standard.removeObject(forKey: $0) }
loadSettings()
}
// MARK: - Private Methods
private func setDefaultValues() {
showPrivateRepositories = true
showForkedRepositories = true
enableNotifications = true
notificationSoundEnabled = true
cacheImages = true
enableAutoRefresh = true
enableCrashReporting = true
}
}
// MARK: - Enums
enum AppTheme: String, CaseIterable, Identifiable {
case light = "light"
case dark = "dark"
case system = "system"
var id: String { rawValue }
var displayName: String {
switch self {
case .light: return "Light"
case .dark: return "Dark"
case .system: return "System"
}
}
var colorScheme: ColorScheme? {
switch self {
case .light: return .light
case .dark: return .dark
case .system: return nil
}
}
}
enum AppAccentColor: String, CaseIterable, Identifiable {
case blue = "blue"
case green = "green"
case orange = "orange"
case pink = "pink"
case purple = "purple"
case red = "red"
case teal = "teal"
case yellow = "yellow"
var id: String { rawValue }
var displayName: String {
switch self {
case .blue: return "Blue"
case .green: return "Green"
case .orange: return "Orange"
case .pink: return "Pink"
case .purple: return "Purple"
case .red: return "Red"
case .teal: return "Teal"
case .yellow: return "Yellow"
}
}
var color: Color {
switch self {
case .blue: return .blue
case .green: return .green
case .orange: return .orange
case .pink: return .pink
case .purple: return .purple
case .red: return .red
case .teal: return .teal
case .yellow: return .yellow
}
}
}
enum RepositoryListStyle: String, CaseIterable, Identifiable {
case compact = "compact"
case detailed = "detailed"
var id: String { rawValue }
var displayName: String {
switch self {
case .compact: return "Compact"
case .detailed: return "Detailed"
}
}
}
enum RepositorySort: String, CaseIterable, Identifiable {
case name = "name"
case updated = "updated"
case created = "created"
case stars = "stars"
case forks = "forks"
var id: String { rawValue }
var displayName: String {
switch self {
case .name: return "Name"
case .updated: return "Last Updated"
case .created: return "Created"
case .stars: return "Stars"
case .forks: return "Forks"
}
}
}
enum RefreshInterval: String, CaseIterable, Identifiable {
case minutes1 = "1min"
case minutes5 = "5min"
case minutes15 = "15min"
case minutes30 = "30min"
case hour1 = "1hour"
case never = "never"
var id: String { rawValue }
var displayName: String {
switch self {
case .minutes1: return "1 minute"
case .minutes5: return "5 minutes"
case .minutes15: return "15 minutes"
case .minutes30: return "30 minutes"
case .hour1: return "1 hour"
case .never: return "Never"
}
}
var timeInterval: TimeInterval? {
switch self {
case .minutes1: return 60
case .minutes5: return 300
case .minutes15: return 900
case .minutes30: return 1800
case .hour1: return 3600
case .never: return nil
}
}
}

View File

@ -0,0 +1,643 @@
//
// GiteaModels.swift
// SwiftForge
//
// Created by Atridad Lahiji on 2025-07-04.
//
import Foundation
// MARK: - User
struct User: Codable, Identifiable, Equatable {
let id: Int
let login: String
let fullName: String?
let email: String?
let avatarUrl: String
let htmlUrl: String
let description: String?
let website: String?
let location: String?
let active: Bool
let isAdmin: Bool
let followersCount: Int
let followingCount: Int
let starredReposCount: Int
let created: Date
let lastLogin: Date?
enum CodingKeys: String, CodingKey {
case id, login, email, active, website, location, created, description
case fullName = "full_name"
case avatarUrl = "avatar_url"
case htmlUrl = "html_url"
case isAdmin = "is_admin"
case followersCount = "followers_count"
case followingCount = "following_count"
case starredReposCount = "starred_repos_count"
case lastLogin = "last_login"
}
}
// MARK: - Organization
struct Organization: Codable, Identifiable, Hashable, Equatable {
let id: Int
let username: String
let name: String?
let fullName: String?
let email: String?
let avatarUrl: String
let description: String?
let website: String?
let location: String?
let visibility: String
enum CodingKeys: String, CodingKey {
case id, username, name, email, description, website, location, visibility
case fullName = "full_name"
case avatarUrl = "avatar_url"
}
}
// MARK: - Repository
struct Repository: Codable, Identifiable, Equatable {
let id: Int
let name: String
let fullName: String
let description: String?
let htmlUrl: String
let cloneUrl: String
let sshUrl: String
let owner: User
let `private`: Bool
let fork: Bool
let template: Bool
let empty: Bool
let archived: Bool
let mirror: Bool
let size: Int
let language: String?
let languagesUrl: String
let forksCount: Int
let stargazersCount: Int
let watchersCount: Int
let openIssuesCount: Int
let openPrCounter: Int
let releaseCounter: Int
let defaultBranch: String
let createdAt: Date
let updatedAt: Date
let permissions: Permission?
let hasIssues: Bool
let hasWiki: Bool
let hasPullRequests: Bool
let hasProjects: Bool
let hasReleases: Bool
let hasPackages: Bool
let hasActions: Bool
let topics: [String]
let avatarUrl: String?
let internalTracker: InternalTracker?
let externalTracker: ExternalTracker?
let externalWiki: ExternalWiki?
enum CodingKeys: String, CodingKey {
case id, name, description, owner, fork, template, empty, archived, mirror, size
case language, permissions, topics
case fullName = "full_name"
case htmlUrl = "html_url"
case cloneUrl = "clone_url"
case sshUrl = "ssh_url"
case `private` = "private"
case languagesUrl = "languages_url"
case forksCount = "forks_count"
case stargazersCount = "stars_count"
case watchersCount = "watchers_count"
case openIssuesCount = "open_issues_count"
case openPrCounter = "open_pr_counter"
case releaseCounter = "release_counter"
case defaultBranch = "default_branch"
case createdAt = "created_at"
case updatedAt = "updated_at"
case hasIssues = "has_issues"
case hasWiki = "has_wiki"
case hasPullRequests = "has_pull_requests"
case hasProjects = "has_projects"
case hasReleases = "has_releases"
case hasPackages = "has_packages"
case hasActions = "has_actions"
case avatarUrl = "avatar_url"
case internalTracker = "internal_tracker"
case externalTracker = "external_tracker"
case externalWiki = "external_wiki"
}
}
// MARK: - Permission
struct Permission: Codable, Equatable {
let admin: Bool
let push: Bool
let pull: Bool
}
// MARK: - Internal Tracker
struct InternalTracker: Codable, Equatable {
let enableTimeTracker: Bool
let allowOnlyContributorsToTrackTime: Bool
let enableIssueDependencies: Bool
enum CodingKeys: String, CodingKey {
case enableTimeTracker = "enable_time_tracker"
case allowOnlyContributorsToTrackTime = "allow_only_contributors_to_track_time"
case enableIssueDependencies = "enable_issue_dependencies"
}
}
// MARK: - External Tracker
struct ExternalTracker: Codable, Equatable {
let externalTrackerUrl: String
let externalTrackerFormat: String
let externalTrackerStyle: String
let externalTrackerRegexpPattern: String
enum CodingKeys: String, CodingKey {
case externalTrackerUrl = "external_tracker_url"
case externalTrackerFormat = "external_tracker_format"
case externalTrackerStyle = "external_tracker_style"
case externalTrackerRegexpPattern = "external_tracker_regexp_pattern"
}
}
// MARK: - External Wiki
struct ExternalWiki: Codable, Equatable {
let externalWikiUrl: String
enum CodingKeys: String, CodingKey {
case externalWikiUrl = "external_wiki_url"
}
}
// MARK: - Issue
struct Issue: Codable, Identifiable {
let id: Int
let number: Int
let title: String
let body: String?
let user: User
let labels: [Label]
let milestone: Milestone?
let assignee: User?
let assignees: [User]
let state: IssueState
let isLocked: Bool
let comments: Int
let createdAt: Date
let updatedAt: Date
let closedAt: Date?
let dueDate: Date?
let pullRequest: PullRequestMeta?
let repository: Repository?
let htmlUrl: String
let url: String
enum CodingKeys: String, CodingKey {
case id, number, title, body, user, labels, milestone, assignee, assignees
case state, comments, repository, url
case isLocked = "is_locked"
case createdAt = "created_at"
case updatedAt = "updated_at"
case closedAt = "closed_at"
case dueDate = "due_date"
case pullRequest = "pull_request"
case htmlUrl = "html_url"
}
}
// MARK: - Issue State
enum IssueState: String, Codable, CaseIterable {
case open = "open"
case closed = "closed"
}
// MARK: - Pull Request Meta
struct PullRequestMeta: Codable {
let draft: Bool
let htmlUrl: String
let merged: Bool
let mergedAt: Date?
enum CodingKeys: String, CodingKey {
case draft, merged
case htmlUrl = "html_url"
case mergedAt = "merged_at"
}
}
// MARK: - Pull Request
struct PullRequest: Codable, Identifiable {
let id: Int
let number: Int
let title: String
let body: String?
let user: User
let labels: [Label]
let milestone: Milestone?
let assignee: User?
let assignees: [User]
let requestedReviewers: [User]
let requestedReviewersTeams: [Team]
let state: IssueState
let isLocked: Bool
let comments: Int
let reviewComments: Int
let draft: Bool
let merged: Bool
let mergeable: Bool?
let mergedAt: Date?
let mergedBy: User?
let base: PRBranchInfo
let head: PRBranchInfo
let mergeBase: String
let dueDate: Date?
let createdAt: Date
let updatedAt: Date
let closedAt: Date?
let htmlUrl: String
let url: String
let diffUrl: String
let patchUrl: String
enum CodingKeys: String, CodingKey {
case id, number, title, body, user, labels, milestone, assignee, assignees
case state, comments, draft, merged, mergeable, base, head, url
case isLocked = "is_locked"
case requestedReviewers = "requested_reviewers"
case requestedReviewersTeams = "requested_reviewers_teams"
case reviewComments = "review_comments"
case mergedAt = "merged_at"
case mergedBy = "merged_by"
case mergeBase = "merge_base"
case dueDate = "due_date"
case createdAt = "created_at"
case updatedAt = "updated_at"
case closedAt = "closed_at"
case htmlUrl = "html_url"
case diffUrl = "diff_url"
case patchUrl = "patch_url"
}
}
// MARK: - PR Branch Info
struct PRBranchInfo: Codable {
let label: String
let ref: String
let sha: String
let repoId: Int
let repo: Repository?
enum CodingKeys: String, CodingKey {
case label, ref, sha, repo
case repoId = "repo_id"
}
}
// MARK: - Team
struct Team: Codable, Identifiable {
let id: Int
let name: String
let description: String?
let organization: Organization?
let permission: TeamPermission
let includesAllRepositories: Bool
let canCreateOrgRepo: Bool
enum CodingKeys: String, CodingKey {
case id, name, description, organization, permission
case includesAllRepositories = "includes_all_repositories"
case canCreateOrgRepo = "can_create_org_repo"
}
}
// MARK: - Team Permission
enum TeamPermission: String, Codable {
case none = "none"
case read = "read"
case write = "write"
case admin = "admin"
case owner = "owner"
}
// MARK: - Label
struct Label: Codable, Identifiable {
let id: Int
let name: String
let color: String
let description: String?
let exclusive: Bool
let isArchived: Bool
let url: String
enum CodingKeys: String, CodingKey {
case id, name, color, description, exclusive, url
case isArchived = "is_archived"
}
}
// MARK: - Milestone
struct Milestone: Codable, Identifiable {
let id: Int
let title: String
let description: String?
let state: MilestoneState
let openIssues: Int
let closedIssues: Int
let createdAt: Date
let updatedAt: Date?
let closedAt: Date?
let dueOn: Date?
enum CodingKeys: String, CodingKey {
case id, title, description, state
case openIssues = "open_issues"
case closedIssues = "closed_issues"
case createdAt = "created_at"
case updatedAt = "updated_at"
case closedAt = "closed_at"
case dueOn = "due_on"
}
}
// MARK: - Milestone State
enum MilestoneState: String, Codable {
case open = "open"
case closed = "closed"
}
// MARK: - Comment
struct Comment: Codable, Identifiable {
let id: Int
let body: String
let user: User
let createdAt: Date
let updatedAt: Date
let htmlUrl: String
let issueUrl: String
let pullRequestUrl: String?
enum CodingKeys: String, CodingKey {
case id, body, user
case createdAt = "created_at"
case updatedAt = "updated_at"
case htmlUrl = "html_url"
case issueUrl = "issue_url"
case pullRequestUrl = "pull_request_url"
}
}
// MARK: - Commit
struct Commit: Codable, Identifiable {
let sha: String
let url: String
let htmlUrl: String
let author: User?
let committer: User?
let commit: CommitInfo
let parents: [CommitMeta]
let files: [CommitFile]?
let stats: CommitStats?
let created: Date
var id: String { sha }
enum CodingKeys: String, CodingKey {
case sha, url, author, committer, commit, parents, files, stats, created
case htmlUrl = "html_url"
}
}
// MARK: - Commit Info
struct CommitInfo: Codable {
let url: String
let author: CommitUser?
let committer: CommitUser?
let message: String
let tree: GitObject
let verification: CommitVerification?
}
// MARK: - Commit User
struct CommitUser: Codable {
let name: String
let email: String
let date: Date
}
// MARK: - Git Object
struct GitObject: Codable {
let sha: String
let url: String
}
// MARK: - Commit Meta
struct CommitMeta: Codable {
let sha: String
let url: String
let created: Date
}
// MARK: - Commit File
struct CommitFile: Codable {
let filename: String
let additions: Int
let deletions: Int
let changes: Int
let status: String
let rawUrl: String
let blobUrl: String
let patchUrl: String
enum CodingKeys: String, CodingKey {
case filename, additions, deletions, changes, status
case rawUrl = "raw_url"
case blobUrl = "blob_url"
case patchUrl = "patch_url"
}
}
// MARK: - Commit Stats
struct CommitStats: Codable {
let total: Int
let additions: Int
let deletions: Int
}
// MARK: - Commit Verification
struct CommitVerification: Codable {
let verified: Bool
let reason: String
let signature: String
let payload: String
let signer: User?
}
// MARK: - Branch
struct Branch: Codable, Identifiable {
let name: String
let commit: CommitMeta
let protected: Bool
let requiredApprovals: Int
let enableStatusCheck: Bool
let statusCheckContexts: [String]
let userCanPush: Bool
let userCanMerge: Bool
let effectiveBranchProtectionName: String
var id: String { name }
enum CodingKeys: String, CodingKey {
case name, commit, protected
case requiredApprovals = "required_approvals"
case enableStatusCheck = "enable_status_check"
case statusCheckContexts = "status_check_contexts"
case userCanPush = "user_can_push"
case userCanMerge = "user_can_merge"
case effectiveBranchProtectionName = "effective_branch_protection_name"
}
}
// MARK: - Release
struct Release: Codable, Identifiable {
let id: Int
let name: String
let body: String?
let tagName: String
let targetCommitish: String
let draft: Bool
let prerelease: Bool
let createdAt: Date
let publishedAt: Date?
let author: User
let url: String
let htmlUrl: String
let assetsUrl: String
let assets: [ReleaseAsset]
let tarballUrl: String
let zipballUrl: String
enum CodingKeys: String, CodingKey {
case id, name, body, draft, prerelease, author, url, assets
case tagName = "tag_name"
case targetCommitish = "target_commitish"
case createdAt = "created_at"
case publishedAt = "published_at"
case htmlUrl = "html_url"
case assetsUrl = "assets_url"
case tarballUrl = "tarball_url"
case zipballUrl = "zipball_url"
}
}
// MARK: - Release Asset
struct ReleaseAsset: Codable, Identifiable {
let id: Int
let name: String
let size: Int
let downloadCount: Int
let createdAt: Date
let uuid: String
let browserDownloadUrl: String
enum CodingKeys: String, CodingKey {
case id, name, size, uuid
case downloadCount = "download_count"
case createdAt = "created_at"
case browserDownloadUrl = "browser_download_url"
}
}
// MARK: - Notification
struct Notification: Codable, Identifiable {
let id: Int
let unread: Bool
let pinned: Bool
let subject: NotificationSubject
let repository: Repository
let url: String
let updatedAt: Date
enum CodingKeys: String, CodingKey {
case id, unread, pinned, subject, repository, url
case updatedAt = "updated_at"
}
}
// MARK: - Notification Subject
struct NotificationSubject: Codable {
let title: String
let url: String
let type: NotificationType
let state: IssueState?
let htmlUrl: String
let latestCommentUrl: String?
let latestCommentHtmlUrl: String?
enum CodingKeys: String, CodingKey {
case title, url, type, state
case htmlUrl = "html_url"
case latestCommentUrl = "latest_comment_url"
case latestCommentHtmlUrl = "latest_comment_html_url"
}
}
// MARK: - Notification Type
enum NotificationType: String, Codable {
case issue = "Issue"
case pullRequest = "PullRequest"
case commit = "Commit"
case repository = "Repository"
}
// MARK: - API Response Wrappers
struct APIResponse<T: Codable>: Codable {
let data: T
let ok: Bool
}
struct PaginatedResponse<T: Codable>: Codable {
let data: [T]
let totalCount: Int
let hasMore: Bool
enum CodingKeys: String, CodingKey {
case data
case totalCount = "total_count"
case hasMore = "has_more"
}
}
// MARK: - Server Version
struct ServerVersion: Codable {
let version: String
}
// MARK: - Search Results
struct SearchResults<T: Codable>: Codable {
let data: [T]
let ok: Bool
}
// MARK: - Authentication Token
struct AccessToken: Codable, Identifiable {
let id: Int
let name: String
let sha1: String
let tokenLastEight: String
let scopes: [String]
enum CodingKeys: String, CodingKey {
case id, name, sha1, scopes
case tokenLastEight = "token_last_eight"
}
}

View File

@ -0,0 +1,23 @@
//
// SwiftForgeApp.swift
// SwiftForge
//
// Created by Atridad Lahiji on 2025-07-04.
//
import SwiftUI
@main
struct SwiftForgeApp: App {
@StateObject private var authenticationManager = AuthenticationManager()
@StateObject private var settingsManager = SettingsManager()
var body: some Scene {
WindowGroup {
ContentView()
.environmentObject(authenticationManager)
.environmentObject(settingsManager)
}
}
}

View File

@ -0,0 +1,455 @@
//
// PreviewMocks.swift
// SwiftForge
//
// Created by Atridad Lahiji on 2025-07-04.
//
import Foundation
import SwiftUI
#if DEBUG
// MARK: - Mock Authentication Manager
class PreviewAuthenticationManager: ObservableObject {
@Published var isAuthenticated = true
@Published var isLoading = false
@Published var errorMessage: String?
@Published var currentUser: User?
@Published var serverURL = "https://github.com"
init() {
self.currentUser = PreviewData.sampleUser
}
func login(serverURL: String, token: String) async {}
func logout() {}
func checkAuthenticationStatus() {}
}
// MARK: - Mock Settings Manager
class PreviewSettingsManager: ObservableObject {
@Published var repositoryListStyle: String = "detailed"
@Published var showPrivateRepositories = true
@Published var showForkedRepositories = true
@Published var defaultRepositorySort: String = "updated"
@Published var theme: String = "system"
@Published var accentColor: String = "blue"
init() {}
}
// MARK: - Preview Extensions
extension PreviewData {
static let mockRepositories = [
Repository(
id: 1,
name: "SwiftForge",
fullName: "johndoe/SwiftForge",
description: "A powerful iOS Git client built with SwiftUI",
htmlUrl: "https://github.com/johndoe/SwiftForge",
cloneUrl: "https://github.com/johndoe/SwiftForge.git",
sshUrl: "git@github.com:johndoe/SwiftForge.git",
owner: sampleUser,
private: false,
fork: false,
template: false,
empty: false,
archived: false,
mirror: false,
size: 2048,
language: "Swift",
languagesUrl: "https://api.github.com/repos/johndoe/SwiftForge/languages",
forksCount: 25,
stargazersCount: 150,
watchersCount: 75,
openIssuesCount: 12,
openPrCounter: 5,
releaseCounter: 8,
defaultBranch: "main",
createdAt: Calendar.current.date(byAdding: .month, value: -6, to: Date()) ?? Date(),
updatedAt: Calendar.current.date(byAdding: .day, value: -2, to: Date()) ?? Date(),
permissions: nil,
hasIssues: true,
hasWiki: true,
hasPullRequests: true,
hasProjects: true,
hasReleases: true,
hasPackages: false,
hasActions: true,
topics: ["ios", "swift", "git", "mobile", "swiftui"],
avatarUrl: nil,
internalTracker: nil,
externalTracker: nil,
externalWiki: nil
),
Repository(
id: 2,
name: "swift-algorithms",
fullName: "johndoe/swift-algorithms",
description: "Commonly used sequence and collection algorithms for Swift",
htmlUrl: "https://github.com/johndoe/swift-algorithms",
cloneUrl: "https://github.com/johndoe/swift-algorithms.git",
sshUrl: "git@github.com:johndoe/swift-algorithms.git",
owner: sampleUser,
private: false,
fork: true,
template: false,
empty: false,
archived: false,
mirror: false,
size: 1024,
language: "Swift",
languagesUrl: "https://api.github.com/repos/johndoe/swift-algorithms/languages",
forksCount: 8,
stargazersCount: 45,
watchersCount: 20,
openIssuesCount: 3,
openPrCounter: 1,
releaseCounter: 12,
defaultBranch: "main",
createdAt: Calendar.current.date(byAdding: .month, value: -12, to: Date())
?? Date(),
updatedAt: Calendar.current.date(byAdding: .hour, value: -6, to: Date()) ?? Date(),
permissions: nil,
hasIssues: true,
hasWiki: false,
hasPullRequests: true,
hasProjects: false,
hasReleases: true,
hasPackages: true,
hasActions: true,
topics: ["swift", "algorithms", "data-structures"],
avatarUrl: nil,
internalTracker: nil,
externalTracker: nil,
externalWiki: nil
),
Repository(
id: 3,
name: "private-config",
fullName: "johndoe/private-config",
description: "Personal configuration files and scripts",
htmlUrl: "https://github.com/johndoe/private-config",
cloneUrl: "https://github.com/johndoe/private-config.git",
sshUrl: "git@github.com:johndoe/private-config.git",
owner: sampleUser,
private: true,
fork: false,
template: false,
empty: false,
archived: false,
mirror: false,
size: 512,
language: "Shell",
languagesUrl: "https://api.github.com/repos/johndoe/private-config/languages",
forksCount: 0,
stargazersCount: 0,
watchersCount: 1,
openIssuesCount: 0,
openPrCounter: 0,
releaseCounter: 0,
defaultBranch: "main",
createdAt: Calendar.current.date(byAdding: .month, value: -3, to: Date()) ?? Date(),
updatedAt: Calendar.current.date(byAdding: .day, value: -1, to: Date()) ?? Date(),
permissions: nil,
hasIssues: false,
hasWiki: false,
hasPullRequests: false,
hasProjects: false,
hasReleases: false,
hasPackages: false,
hasActions: false,
topics: ["dotfiles", "config", "personal"],
avatarUrl: nil,
internalTracker: nil,
externalTracker: nil,
externalWiki: nil
),
]
}
// MARK: - Mock View Components
struct MockRepositoriesView: View {
@State private var repositories = PreviewData.mockRepositories
@State private var searchText = ""
@State private var showingFilter = false
@State private var showingCreateRepository = false
var body: some View {
VStack(spacing: 0) {
CustomHeader(
title: "Repositories",
trailingContent: {
AnyView(
HStack(spacing: 12) {
Button(action: { showingCreateRepository = true }) {
Image(systemName: "plus")
.font(.system(size: 18, weight: .medium))
.foregroundColor(.primary)
}
Menu {
Button("Filter") {
showingFilter = true
}
Button("Sort") {}
} label: {
Image(systemName: "ellipsis.circle")
.font(.system(size: 18, weight: .medium))
.foregroundColor(.primary)
}
}
)
}
)
List(repositories) { repository in
VStack(alignment: .leading, spacing: 8) {
HStack {
VStack(alignment: .leading, spacing: 4) {
Text(repository.name)
.font(.headline)
.foregroundColor(.primary)
if let description = repository.description {
Text(description)
.font(.caption)
.foregroundColor(.secondary)
.lineLimit(2)
}
}
Spacer()
VStack(alignment: .trailing) {
if repository.private {
Image(systemName: "lock")
.font(.caption)
.foregroundColor(.secondary)
}
if repository.fork {
Image(systemName: "tuningfork")
.font(.caption)
.foregroundColor(.secondary)
}
}
}
HStack(spacing: 16) {
if let language = repository.language {
HStack(spacing: 4) {
Circle()
.fill(colorForLanguage(language))
.frame(width: 8, height: 8)
Text(language)
.font(.caption)
.foregroundColor(.secondary)
}
}
HStack(spacing: 4) {
Image(systemName: "star")
.font(.caption)
Text("\(repository.stargazersCount)")
.font(.caption)
}
.foregroundColor(.secondary)
HStack(spacing: 4) {
Image(systemName: "tuningfork")
.font(.caption)
Text("\(repository.forksCount)")
.font(.caption)
}
.foregroundColor(.secondary)
Spacer()
Text(repository.updatedAt.timeAgoSince())
.font(.caption)
.foregroundColor(.secondary)
}
}
.padding(.vertical, 4)
.listRowInsets(EdgeInsets(top: 8, leading: 16, bottom: 8, trailing: 16))
}
.listStyle(PlainListStyle())
}
.navigationBarHidden(true)
.searchable(text: $searchText, prompt: "Search repositories")
}
}
struct MockIssuesView: View {
var body: some View {
VStack(spacing: 0) {
CustomHeader(
title: "Issues",
trailingContent: {
AnyView(
Menu {
Button("Open") {}
Button("Closed") {}
} label: {
Image(systemName: "line.3.horizontal.decrease.circle")
.font(.system(size: 18, weight: .medium))
.foregroundColor(.primary)
}
)
}
)
EmptyStateView(
systemImage: "exclamationmark.triangle",
title: "No Repository Selected",
description: "Select a repository to view its issues",
actionTitle: "Browse Repositories",
action: {}
)
}
.navigationBarHidden(true)
}
}
struct MockNotificationsView: View {
var body: some View {
VStack(spacing: 0) {
CustomHeader(
title: "Notifications",
trailingContent: {
AnyView(
HStack(spacing: 12) {
Button("All") {}
.font(.caption)
Button(action: {}) {
Image(systemName: "checkmark.circle")
}
}
)
}
)
EmptyStateView(
systemImage: "bell.slash",
title: "No Notifications",
description: "You're all caught up! No new notifications.",
actionTitle: nil,
action: nil
)
}
.navigationBarHidden(true)
}
}
struct MockProfileView: View {
var body: some View {
VStack(spacing: 0) {
CustomHeader(
title: "Profile",
trailingContent: {
AnyView(
Menu {
Button("Edit Profile") {}
Button("Settings") {}
Divider()
Button("Sign Out", role: .destructive) {}
} label: {
Image(systemName: "ellipsis.circle")
.font(.system(size: 18, weight: .medium))
.foregroundColor(.primary)
}
)
}
)
ScrollView {
VStack(spacing: 20) {
// Profile Header
VStack(spacing: 12) {
AsyncImage(url: URL(string: PreviewData.sampleUser.avatarUrl)) {
phase in
switch phase {
case .success(let image):
image
.resizable()
.aspectRatio(contentMode: .fill)
case .failure(_):
Image(systemName: "person.circle.fill")
.font(.system(size: 60))
.foregroundColor(.secondary)
case .empty:
ProgressView()
@unknown default:
EmptyView()
}
}
.frame(width: 80, height: 80)
.clipShape(Circle())
VStack(spacing: 4) {
Text(
PreviewData.sampleUser.fullName ?? PreviewData.sampleUser.login
)
.font(.title2)
.fontWeight(.bold)
Text("@\(PreviewData.sampleUser.login)")
.font(.subheadline)
.foregroundColor(.secondary)
if let description = PreviewData.sampleUser.description {
Text(description)
.font(.subheadline)
.foregroundColor(.secondary)
.multilineTextAlignment(.center)
}
}
}
.padding()
// Stats
HStack(spacing: 20) {
VStack {
Text("\(PreviewData.sampleUser.followersCount)")
.font(.headline)
.fontWeight(.bold)
Text("Followers")
.font(.caption)
.foregroundColor(.secondary)
}
VStack {
Text("\(PreviewData.sampleUser.followingCount)")
.font(.headline)
.fontWeight(.bold)
Text("Following")
.font(.caption)
.foregroundColor(.secondary)
}
VStack {
Text("\(PreviewData.sampleUser.starredReposCount)")
.font(.headline)
.fontWeight(.bold)
Text("Stars")
.font(.caption)
.foregroundColor(.secondary)
}
}
.padding()
Spacer()
}
}
}
.navigationBarHidden(true)
}
}
#endif

View File

@ -0,0 +1,432 @@
//
// SharedViews.swift
// SwiftForge
//
// Created by Atridad Lahiji on 2025-07-04.
//
import Foundation
import SwiftUI
// MARK: - Common Views
struct CustomHeader: View {
let title: String
let showBackButton: Bool
let backAction: (() -> Void)?
let trailingContent: (() -> AnyView)?
init(
title: String,
showBackButton: Bool = false,
backAction: (() -> Void)? = nil,
@ViewBuilder trailingContent: @escaping () -> AnyView = { AnyView(EmptyView()) }
) {
self.title = title
self.showBackButton = showBackButton
self.backAction = backAction
self.trailingContent = trailingContent
}
var body: some View {
VStack(spacing: 0) {
HStack {
if showBackButton {
Button(action: backAction ?? {}) {
Image(systemName: "chevron.left")
.font(.system(size: 18, weight: .semibold))
.foregroundColor(.primary)
}
}
Text(title)
.font(.largeTitle)
.fontWeight(.bold)
.foregroundColor(.primary)
Spacer()
trailingContent?()
}
.padding(.horizontal, 16)
.padding(.top, 8)
.padding(.bottom, 12)
.background(Color.clear)
// Subtle separator
Rectangle()
.fill(Color.primary.opacity(0.1))
.frame(height: 0.5)
}
.background(Color.clear)
}
}
struct ErrorView: View {
let message: String
let retryAction: () -> Void
var body: some View {
VStack(spacing: 16) {
Image(systemName: "exclamationmark.triangle")
.font(.system(size: 50))
.foregroundColor(.orange)
Text("Something went wrong")
.font(.headline)
Text(message)
.font(.subheadline)
.foregroundColor(.secondary)
.multilineTextAlignment(.center)
Button("Try Again", action: retryAction)
.buttonStyle(.borderedProminent)
}
.padding()
}
}
struct LoadingView: View {
let message: String
var body: some View {
VStack(spacing: 16) {
ProgressView()
.progressViewStyle(CircularProgressViewStyle())
.scaleEffect(1.2)
Text(message)
.font(.subheadline)
.foregroundColor(.secondary)
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
}
struct EmptyStateView: View {
let systemImage: String
let title: String
let description: String
let actionTitle: String?
let action: (() -> Void)?
init(
systemImage: String, title: String, description: String, actionTitle: String? = nil,
action: (() -> Void)? = nil
) {
self.systemImage = systemImage
self.title = title
self.description = description
self.actionTitle = actionTitle
self.action = action
}
var body: some View {
VStack(spacing: 20) {
Image(systemName: systemImage)
.font(.system(size: 60))
.foregroundColor(.secondary)
Text(title)
.font(.title2)
.fontWeight(.semibold)
Text(description)
.font(.subheadline)
.foregroundColor(.secondary)
.multilineTextAlignment(.center)
if let actionTitle = actionTitle, let action = action {
Button(actionTitle, action: action)
.buttonStyle(.borderedProminent)
}
}
.padding()
}
}
// MARK: - Extensions
extension Date {
func timeAgoSince() -> String {
let formatter = RelativeDateTimeFormatter()
formatter.unitsStyle = .abbreviated
return formatter.localizedString(for: self, relativeTo: Date())
}
func formattedDate() -> String {
let formatter = DateFormatter()
formatter.dateStyle = .medium
formatter.timeStyle = .none
return formatter.string(from: self)
}
func formattedDateTime() -> String {
let formatter = DateFormatter()
formatter.dateStyle = .medium
formatter.timeStyle = .short
return formatter.string(from: self)
}
}
extension Color {
init?(hex: String) {
let hex = hex.trimmingCharacters(in: CharacterSet.alphanumerics.inverted)
var int: UInt64 = 0
Scanner(string: hex).scanHexInt64(&int)
let a: UInt64
let r: UInt64
let g: UInt64
let b: UInt64
switch hex.count {
case 3: // RGB (12-bit)
(a, r, g, b) = (255, (int >> 8) * 17, (int >> 4 & 0xF) * 17, (int & 0xF) * 17)
case 6: // RGB (24-bit)
(a, r, g, b) = (255, int >> 16, int >> 8 & 0xFF, int & 0xFF)
case 8: // ARGB (32-bit)
(a, r, g, b) = (int >> 24, int >> 16 & 0xFF, int >> 8 & 0xFF, int & 0xFF)
default:
return nil
}
self.init(
.sRGB,
red: Double(r) / 255,
green: Double(g) / 255,
blue: Double(b) / 255,
opacity: Double(a) / 255
)
}
}
extension String {
func truncated(to length: Int) -> String {
if self.count > length {
return String(self.prefix(length)) + "..."
} else {
return self
}
}
}
// MARK: - Language Colors
func colorForLanguage(_ language: String) -> Color {
switch language.lowercased() {
case "swift": return .orange
case "objective-c": return .blue
case "javascript": return .yellow
case "typescript": return .blue
case "python": return .green
case "java": return .red
case "kotlin": return .purple
case "rust": return .orange
case "go": return .cyan
case "c++", "cpp": return .blue
case "c": return .gray
case "c#": return .purple
case "ruby": return .red
case "php": return .purple
case "html": return .orange
case "css": return .blue
case "vue": return .green
case "react": return .cyan
case "dart": return .blue
case "flutter": return .blue
case "shell": return .green
case "bash": return .green
case "dockerfile": return .cyan
case "yaml", "yml": return .purple
case "json": return .yellow
case "xml": return .orange
case "sql": return .blue
case "r": return .blue
case "scala": return .red
case "haskell": return .purple
case "clojure": return .green
case "elixir": return .purple
case "erlang": return .red
case "lua": return .blue
case "perl": return .blue
case "powershell": return .blue
case "vim script": return .green
default: return .gray
}
}
// MARK: - View Modifiers
struct CardStyle: ViewModifier {
func body(content: Content) -> some View {
content
.cornerRadius(8)
.shadow(color: Color.black.opacity(0.1), radius: 1, x: 0, y: 1)
}
}
struct ListRowStyle: ViewModifier {
func body(content: Content) -> some View {
content
.listRowInsets(EdgeInsets(top: 8, leading: 16, bottom: 8, trailing: 16))
.listRowSeparator(.hidden)
}
}
extension View {
func cardStyle() -> some View {
modifier(CardStyle())
}
func listRowStyle() -> some View {
modifier(ListRowStyle())
}
func customHeader(
_ title: String, showBackButton: Bool = false, backAction: (() -> Void)? = nil,
@ViewBuilder trailingContent: @escaping () -> AnyView = { AnyView(EmptyView()) }
) -> some View {
VStack(spacing: 0) {
CustomHeader(
title: title,
showBackButton: showBackButton,
backAction: backAction,
trailingContent: trailingContent
)
self
}
}
}
struct GlassEffectModifier<S: Shape>: ViewModifier {
let shape: S
let namespace: Namespace.ID?
init(shape: S, namespace: Namespace.ID? = nil) {
self.shape = shape
self.namespace = namespace
}
func body(content: Content) -> some View {
if #available(iOS 26.0, macOS 26.0, *) {
GlassEffectContainer {
if let ns = namespace {
content
.glassEffect(in: shape)
.glassEffectID("glass", in: ns)
} else {
content
.glassEffect(in: shape)
}
}
} else {
content
.background(
shape
.fill(.regularMaterial)
.overlay(
shape
.stroke(Color.primary.opacity(0.1), lineWidth: 0.5)
)
)
.clipShape(shape)
}
}
}
// MARK: - Common Constants
struct AppConstants {
static let minimumRefreshInterval: TimeInterval = 30
static let defaultPageSize = 30
static let maxDescriptionLength = 100
static let maxTitleLength = 50
struct Animation {
static let defaultDuration: Double = 0.3
static let fastDuration: Double = 0.15
static let slowDuration: Double = 0.5
}
struct Spacing {
static let small: CGFloat = 8
static let medium: CGFloat = 16
static let large: CGFloat = 24
static let extraLarge: CGFloat = 32
}
struct CornerRadius {
static let small: CGFloat = 4
static let medium: CGFloat = 8
static let large: CGFloat = 12
static let extraLarge: CGFloat = 16
}
}
// MARK: - Preview Helpers
#if DEBUG
struct PreviewData {
static let sampleUser = User(
id: 1,
login: "johndoe",
fullName: "John Doe",
email: "john@example.com",
avatarUrl: "https://xsgames.co/randomusers/avatar.php?g=pixel",
htmlUrl: "https://github.com/johndoe",
description: "Software Developer",
website: "https://johndoe.com",
location: "San Francisco, CA",
active: true,
isAdmin: false,
followersCount: 1337,
followingCount: 420,
starredReposCount: 69,
created: Date(),
lastLogin: Date()
)
static let sampleRepository = Repository(
id: 1,
name: "sample-repo",
fullName: "johndoe/sample-repo",
description: "A sample repository for testing",
htmlUrl: "https://github.com/johndoe/sample-repo",
cloneUrl: "https://github.com/johndoe/sample-repo.git",
sshUrl: "git@github.com:johndoe/sample-repo.git",
owner: sampleUser,
private: false,
fork: false,
template: false,
empty: false,
archived: false,
mirror: false,
size: 1024,
language: "Swift",
languagesUrl: "https://api.github.com/repos/johndoe/sample-repo/languages",
forksCount: 10,
stargazersCount: 50,
watchersCount: 25,
openIssuesCount: 5,
openPrCounter: 2,
releaseCounter: 3,
defaultBranch: "main",
createdAt: Date(),
updatedAt: Date(),
permissions: nil,
hasIssues: true,
hasWiki: true,
hasPullRequests: true,
hasProjects: true,
hasReleases: true,
hasPackages: false,
hasActions: true,
topics: ["ios", "swift", "mobile"],
avatarUrl: nil,
internalTracker: nil,
externalTracker: nil,
externalWiki: nil
)
}
#endif

View File

@ -0,0 +1,117 @@
//
// CreateRepositoryView.swift
// SwiftForge
//
// Created by Atridad Lahiji on 2025-01-27.
//
import SwiftUI
struct CreateRepositoryView: View {
@Environment(\.dismiss) private var dismiss
@EnvironmentObject private var authManager: AuthenticationManager
@State private var repositoryName = ""
@State private var description = ""
@State private var isPrivate = false
@State private var initializeWithReadme = true
@State private var isCreating = false
@State private var showError = false
@State private var errorMessage = ""
var body: some View {
NavigationView {
Form {
Section(header: Text("Repository Details")) {
TextField("Repository name", text: $repositoryName)
.textFieldStyle(.roundedBorder)
TextField("Description (optional)", text: $description, axis: .vertical)
.textFieldStyle(.roundedBorder)
.lineLimit(3...6)
}
Section(header: Text("Settings")) {
Toggle("Private repository", isOn: $isPrivate)
Toggle("Initialize with README", isOn: $initializeWithReadme)
}
Section {
VStack(spacing: 8) {
Text("Repository will be created under your account")
.font(.caption)
.foregroundColor(.secondary)
if !repositoryName.isEmpty {
Text("github.com/username/\(repositoryName)")
.font(.caption)
.foregroundColor(.blue)
}
}
}
}
.navigationTitle("New Repository")
.toolbar {
ToolbarItem(placement: .cancellationAction) {
Button("Cancel") {
dismiss()
}
}
ToolbarItem(placement: .confirmationAction) {
Button("Create") {
createRepository()
}
.disabled(repositoryName.isEmpty || isCreating)
}
}
.alert("Error", isPresented: $showError) {
Button("OK") {}
} message: {
Text(errorMessage)
}
}
}
private func createRepository() {
guard !repositoryName.isEmpty else { return }
guard let apiService = authManager.getAPIService() else {
errorMessage = "Not authenticated"
showError = true
return
}
isCreating = true
Task {
do {
let _ = try await apiService.createRepository(
name: repositoryName,
description: description.isEmpty ? nil : description,
isPrivate: isPrivate,
autoInit: initializeWithReadme
)
// Success - dismiss the sheet
await MainActor.run {
dismiss()
}
} catch {
await MainActor.run {
isCreating = false
errorMessage = error.localizedDescription
showError = true
}
}
}
}
}
#if DEBUG
struct CreateRepositoryView_Previews: PreviewProvider {
static var previews: some View {
CreateRepositoryView()
}
}
#endif

View File

@ -0,0 +1,237 @@
//
// EditProfileView.swift
// SwiftForge
//
// Created by Atridad Lahiji on 2025-01-14.
//
import SwiftUI
struct EditProfileView: View {
@Environment(\.dismiss) private var dismiss
@EnvironmentObject var authManager: AuthenticationManager
@State private var fullName: String = ""
@State private var email: String = ""
@State private var description: String = ""
@State private var website: String = ""
@State private var location: String = ""
@State private var isLoading = false
@State private var errorMessage: String?
@State private var showingError = false
// Store original values to track changes
@State private var originalFullName: String = ""
@State private var originalEmail: String = ""
@State private var originalDescription: String = ""
@State private var originalWebsite: String = ""
@State private var originalLocation: String = ""
var body: some View {
NavigationView {
Form {
Section(header: Text("Basic Information")) {
HStack {
Text("Full Name")
Spacer()
TextField("Enter your full name", text: $fullName)
.textFieldStyle(RoundedBorderTextFieldStyle())
.frame(maxWidth: 200)
}
HStack {
Text("Email")
Spacer()
TextField("Enter your email", text: $email)
.textFieldStyle(RoundedBorderTextFieldStyle())
.keyboardType(.emailAddress)
.textInputAutocapitalization(.never)
.frame(maxWidth: 200)
}
}
Section(header: Text("About")) {
VStack(alignment: .leading, spacing: 8) {
Text("Description")
.font(.subheadline)
.foregroundColor(.secondary)
TextEditor(text: $description)
.frame(minHeight: 80)
.overlay(
RoundedRectangle(cornerRadius: 8)
.stroke(Color.gray.opacity(0.3), lineWidth: 1)
)
}
HStack {
Text("Website")
Spacer()
TextField("https://example.com", text: $website)
.textFieldStyle(RoundedBorderTextFieldStyle())
.keyboardType(.URL)
.textInputAutocapitalization(.never)
.frame(maxWidth: 200)
}
HStack {
Text("Location")
Spacer()
TextField("Enter your location", text: $location)
.textFieldStyle(RoundedBorderTextFieldStyle())
.frame(maxWidth: 200)
}
}
if let errorMessage = errorMessage {
Section {
Text(errorMessage)
.foregroundColor(.red)
.font(.caption)
}
}
}
.navigationTitle("Edit Profile")
.navigationBarTitleDisplayMode(.inline)
.toolbar {
ToolbarItem(placement: .navigationBarLeading) {
Button("Cancel") {
dismiss()
}
.disabled(isLoading)
}
ToolbarItem(placement: .navigationBarTrailing) {
Button("Save") {
Task {
await saveProfile()
}
}
.disabled(isLoading || !isFormValid || !hasChanges)
}
}
.onAppear {
loadCurrentUserData()
}
.navigationBarTitleDisplayMode(.inline)
.toolbarBackground(.visible, for: .navigationBar)
.overlay {
if isLoading {
ZStack {
Color.black.opacity(0.1)
.ignoresSafeArea()
ProgressView("Saving...")
.padding()
.background(Color(.systemBackground))
.cornerRadius(10)
.shadow(radius: 10)
}
}
}
}
}
private var hasChanges: Bool {
let trimmedFullName = fullName.trimmingCharacters(in: .whitespacesAndNewlines)
let trimmedEmail = email.trimmingCharacters(in: .whitespacesAndNewlines)
let trimmedDescription = description.trimmingCharacters(in: .whitespacesAndNewlines)
let trimmedWebsite = website.trimmingCharacters(in: .whitespacesAndNewlines)
let trimmedLocation = location.trimmingCharacters(in: .whitespacesAndNewlines)
return trimmedFullName != originalFullName || trimmedEmail != originalEmail
|| trimmedDescription != originalDescription || trimmedWebsite != originalWebsite
|| trimmedLocation != originalLocation
}
private var isFormValid: Bool {
let trimmedEmail = email.trimmingCharacters(in: .whitespacesAndNewlines)
// If email is provided, it must be valid
if !trimmedEmail.isEmpty && !isValidEmail(trimmedEmail) {
return false
}
// At least one field should have content (excluding empty strings)
return !fullName.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
|| !trimmedEmail.isEmpty
|| !description.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
|| !website.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
|| !location.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
}
private func isValidEmail(_ email: String) -> Bool {
let emailRegex = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}"
let emailPredicate = NSPredicate(format: "SELF MATCHES %@", emailRegex)
return emailPredicate.evaluate(with: email)
}
private func loadCurrentUserData() {
guard let user = authManager.currentUser else { return }
fullName = user.fullName ?? ""
email = user.email ?? ""
description = user.description ?? ""
website = user.website ?? ""
location = user.location ?? ""
// Store original values
originalFullName = fullName
originalEmail = email
originalDescription = description
originalWebsite = website
originalLocation = location
}
private func saveProfile() async {
print("DEBUG: saveProfile called")
guard isFormValid else {
print("DEBUG: saveProfile - form is not valid")
return
}
isLoading = true
errorMessage = nil
defer {
isLoading = false
print("DEBUG: saveProfile - isLoading set to false")
}
do {
print("DEBUG: saveProfile - preparing data")
let trimmedFullName = fullName.trimmingCharacters(in: .whitespacesAndNewlines)
let trimmedEmail = email.trimmingCharacters(in: .whitespacesAndNewlines)
let trimmedDescription = description.trimmingCharacters(in: .whitespacesAndNewlines)
let trimmedWebsite = website.trimmingCharacters(in: .whitespacesAndNewlines)
let trimmedLocation = location.trimmingCharacters(in: .whitespacesAndNewlines)
print("DEBUG: saveProfile - calling updateUserProfile")
try await authManager.updateUserProfile(
fullName: trimmedFullName.isEmpty ? nil : trimmedFullName,
email: trimmedEmail.isEmpty ? nil : trimmedEmail,
description: trimmedDescription.isEmpty ? nil : trimmedDescription,
website: trimmedWebsite.isEmpty ? nil : trimmedWebsite,
location: trimmedLocation.isEmpty ? nil : trimmedLocation
)
print("DEBUG: saveProfile - update successful, dismissing sheet")
// Success - dismiss the sheet
dismiss()
} catch {
print("DEBUG: saveProfile - error occurred: \(error)")
// Set error message but still dismiss for certain errors
errorMessage = error.localizedDescription
// Always dismiss the sheet after a few seconds to prevent getting stuck
DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
print("DEBUG: saveProfile - dismissing sheet after error with delay")
dismiss()
}
}
}
}
#Preview {
EditProfileView()
.environmentObject(AuthenticationManager())
}

View File

@ -0,0 +1,620 @@
//
// ProfileView.swift
// SwiftForge
//
// Created by Atridad Lahiji on 2025-07-04.
//
import SwiftUI
struct ProfileView: View {
@EnvironmentObject var authManager: AuthenticationManager
@EnvironmentObject var settingsManager: SettingsManager
@State private var isLoading = false
@State private var errorMessage: String?
@State private var showingSettings = false
@State private var showingLogoutConfirmation = false
@State private var userRepositories: [Repository] = []
@State private var userOrganizations: [Organization] = []
@State private var showingEditProfile = false
var body: some View {
VStack(spacing: 0) {
CustomHeader(
title: "Profile",
trailingContent: {
AnyView(
HStack(spacing: 12) {
Button(action: { showingEditProfile = true }) {
Image(systemName: "square.and.pencil")
.font(.system(size: 18, weight: .medium))
.foregroundColor(.primary)
.frame(width: 44, height: 44)
.modifier(GlassEffectModifier(shape: Circle()))
}
.buttonStyle(.borderless)
Button(action: { showingSettings = true }) {
Image(systemName: "gearshape")
.font(.system(size: 18, weight: .medium))
.foregroundColor(.primary)
.frame(width: 44, height: 44)
.modifier(GlassEffectModifier(shape: Circle()))
}
.buttonStyle(.borderless)
}
)
}
)
ScrollView {
VStack(spacing: 0) {
if isLoading {
LoadingView(message: "Loading profile...")
} else if let errorMessage = errorMessage {
ErrorView(message: errorMessage) {
Task { await refreshProfile() }
}
} else {
profileContent
}
}
}
}
.navigationBarHidden(true)
.refreshable {
await refreshProfile()
}
.sheet(isPresented: $showingSettings) {
SettingsView()
}
.sheet(
isPresented: $showingEditProfile,
onDismiss: {
Task {
await refreshProfile()
}
}
) {
EditProfileView()
.environmentObject(authManager)
.environmentObject(settingsManager)
}
.confirmationDialog("Sign Out", isPresented: $showingLogoutConfirmation) {
Button("Sign Out", role: .destructive) {
authManager.logout()
}
Button("Cancel", role: .cancel) {}
} message: {
Text("Are you sure you want to sign out?")
}
.onAppear {
if userRepositories.isEmpty && userOrganizations.isEmpty {
Task { await loadUserData() }
}
// Navigation appearance is handled by SwiftUI
}
}
private var profileContent: some View {
VStack(spacing: 24) {
profileHeader
Divider()
statisticsSection
Divider()
repositoriesSection
if !userOrganizations.isEmpty {
Divider()
organizationsSection
}
Divider()
accountSection
}
.padding()
}
private var profileHeader: some View {
VStack(spacing: 16) {
AsyncImage(url: URL(string: authManager.currentUser?.avatarUrl ?? "")) { phase in
switch phase {
case .success(let image):
image
.resizable()
.aspectRatio(contentMode: .fill)
.frame(width: 80, height: 80)
.clipped()
case .failure(_):
Image(systemName: "person.circle.fill")
.font(.system(size: 80))
.foregroundColor(.gray)
.frame(width: 80, height: 80)
case .empty:
Image(systemName: "person.circle.fill")
.font(.system(size: 80))
.foregroundColor(.gray)
.frame(width: 80, height: 80)
@unknown default:
Image(systemName: "person.circle.fill")
.font(.system(size: 80))
.foregroundColor(.gray)
.frame(width: 80, height: 80)
}
}
.frame(width: 80, height: 80)
.clipShape(Circle())
.overlay(
Circle()
.stroke(Color.gray.opacity(0.3), lineWidth: 1)
)
VStack(spacing: 4) {
if let fullName = authManager.currentUser?.fullName, !fullName.isEmpty {
Text(fullName)
.font(.title2)
.fontWeight(.semibold)
} else {
Text(authManager.currentUser?.login ?? "Unknown")
.font(.title2)
.fontWeight(.semibold)
}
Text("@\(authManager.currentUser?.login ?? "unknown")")
.font(.subheadline)
.foregroundColor(.secondary)
if let description = authManager.currentUser?.description, !description.isEmpty {
Text(description)
.font(.body)
.foregroundColor(.secondary)
.multilineTextAlignment(.center)
.padding(.top, 4)
}
if let location = authManager.currentUser?.location, !location.isEmpty {
HStack {
Image(systemName: "location")
.font(.caption)
Text(location)
.font(.caption)
}
.foregroundColor(.secondary)
.padding(.top, 2)
}
if let website = authManager.currentUser?.website, !website.isEmpty {
Link(destination: URL(string: website) ?? URL(string: "https://example.com")!) {
HStack {
Image(systemName: "link")
.font(.caption)
Text(website)
.font(.caption)
}
.foregroundColor(.accentColor)
.padding(.top, 2)
}
}
}
}
}
private var statisticsSection: some View {
VStack(alignment: .leading, spacing: 12) {
Text("Statistics")
.font(.headline)
.frame(maxWidth: .infinity, alignment: .leading)
HStack(spacing: 0) {
StatisticView(
title: "Repositories",
value: userRepositories.count
)
Divider()
.frame(height: 40)
StatisticView(
title: "Followers",
value: authManager.currentUser?.followersCount ?? 0
)
Divider()
.frame(height: 40)
StatisticView(
title: "Following",
value: authManager.currentUser?.followingCount ?? 0
)
Divider()
.frame(height: 40)
StatisticView(
title: "Stars",
value: authManager.currentUser?.starredReposCount ?? 0
)
}
.padding(.vertical, 8)
}
}
private var repositoriesSection: some View {
VStack(alignment: .leading, spacing: 12) {
HStack {
Text("Recent Repositories")
.font(.headline)
Spacer()
}
if userRepositories.isEmpty {
Text("No repositories found")
.font(.subheadline)
.foregroundColor(.secondary)
.frame(maxWidth: .infinity, alignment: .center)
.padding()
} else {
VStack(spacing: 12) {
ForEach(Array(userRepositories.prefix(3))) { repository in
RepositoryCard(repository: repository)
}
}
}
}
}
private var organizationsSection: some View {
VStack(alignment: .leading, spacing: 12) {
Text("Organizations")
.font(.headline)
.frame(maxWidth: .infinity, alignment: .leading)
ScrollView(.horizontal, showsIndicators: false) {
HStack(spacing: 12) {
ForEach(userOrganizations) { organization in
OrganizationCard(organization: organization)
}
}
.padding(.horizontal)
}
}
}
private var accountSection: some View {
VStack(alignment: .leading, spacing: 12) {
Text("Account")
.font(.headline)
.frame(maxWidth: .infinity, alignment: .leading)
VStack(spacing: 8) {
HStack {
Image(systemName: "server.rack")
.foregroundColor(.secondary)
Text("Server")
.font(.subheadline)
Spacer()
Text(
authManager.serverURL.replacingOccurrences(of: "https://", with: "")
.replacingOccurrences(of: "http://", with: "")
)
.font(.caption)
.foregroundColor(.secondary)
}
HStack {
Image(systemName: "person.badge.key")
.foregroundColor(.secondary)
Text("Account Type")
.font(.subheadline)
Spacer()
Text(authManager.currentUser?.isAdmin == true ? "Admin" : "User")
.font(.caption)
.foregroundColor(.secondary)
}
if let created = authManager.currentUser?.created {
HStack {
Image(systemName: "calendar")
.foregroundColor(.secondary)
Text("Member Since")
.font(.subheadline)
Spacer()
Text(created, style: .date)
.font(.caption)
.foregroundColor(.secondary)
}
}
}
.padding(.vertical, 8)
Button(action: { showingLogoutConfirmation = true }) {
HStack {
Image(systemName: "rectangle.portrait.and.arrow.right")
Text("Sign Out")
}
.frame(maxWidth: .infinity)
.padding()
.background(Color.red)
.foregroundColor(.white)
.cornerRadius(10)
}
.padding(.top, 8)
}
}
private func refreshProfile() async {
errorMessage = nil
await authManager.refreshUser()
// await loadUserData()
}
func triggerRefresh() {
Task {
await refreshProfile()
}
}
private func loadUserData() async {
guard let apiService = authManager.getAPIService() else { return }
isLoading = true
errorMessage = nil
defer {
isLoading = false
}
do {
async let repositories = apiService.getUserRepositories(limit: 10)
async let organizations = apiService.getUserOrganizations()
userRepositories = try await repositories
userOrganizations = try await organizations
} catch {
// Handle cancellation and other errors gracefully
if error is CancellationError {
// Don't show error message for cancellation
return
}
errorMessage = error.localizedDescription
}
}
}
struct StatisticView: View {
let title: String
let value: Int
var body: some View {
VStack(spacing: 4) {
Text("\(value)")
.font(.title2)
.fontWeight(.semibold)
Text(title)
.font(.caption)
.foregroundColor(.secondary)
}
.frame(maxWidth: .infinity)
}
}
struct RepositoryCard: View {
let repository: Repository
var body: some View {
VStack(alignment: .leading, spacing: 8) {
HStack {
Text(repository.name)
.font(.subheadline)
.fontWeight(.medium)
.lineLimit(1)
if repository.private {
Image(systemName: "lock.fill")
.font(.caption)
.foregroundColor(.orange)
}
Spacer()
HStack(spacing: 4) {
Image(systemName: "star")
.font(.caption)
Text("\(repository.stargazersCount)")
.font(.caption)
}
.foregroundColor(.secondary)
}
if let description = repository.description, !description.isEmpty {
Text(description)
.font(.caption)
.foregroundColor(.secondary)
.lineLimit(2)
}
HStack {
if let language = repository.language {
HStack(spacing: 4) {
Circle()
.fill(colorForLanguage(language))
.frame(width: 8, height: 8)
Text(language)
.font(.caption)
.foregroundColor(.secondary)
}
}
Spacer()
Text("Updated \(repository.updatedAt.timeAgoSince())")
.font(.caption)
.foregroundColor(.secondary)
}
}
.padding()
.cornerRadius(8)
}
}
struct OrganizationCard: View {
let organization: Organization
var body: some View {
VStack(spacing: 8) {
AsyncImage(url: URL(string: organization.avatarUrl)) { phase in
switch phase {
case .success(let image):
image
.resizable()
.aspectRatio(contentMode: .fill)
.frame(width: 50, height: 50)
.clipped()
case .failure(_):
Image(systemName: "building.2")
.font(.title2)
.foregroundColor(.gray)
.frame(width: 50, height: 50)
case .empty:
Image(systemName: "building.2")
.font(.title2)
.foregroundColor(.gray)
.frame(width: 50, height: 50)
@unknown default:
Image(systemName: "building.2")
.font(.title2)
.foregroundColor(.gray)
.frame(width: 50, height: 50)
}
}
.frame(width: 50, height: 50)
.clipShape(Circle())
Text(organization.username)
.font(.caption)
.fontWeight(.medium)
.lineLimit(1)
}
.frame(width: 80)
}
}
struct SettingsView: View {
@EnvironmentObject var settingsManager: SettingsManager
@EnvironmentObject var authManager: AuthenticationManager
@Environment(\.dismiss) private var dismiss
@State private var showingSignOutConfirmation = false
var body: some View {
NavigationView {
Form {
Section("Appearance") {
Picker("Theme", selection: $settingsManager.theme) {
ForEach(AppTheme.allCases) { theme in
Text(theme.displayName).tag(theme)
}
}
Picker("Accent Color", selection: $settingsManager.accentColor) {
ForEach(AppAccentColor.allCases) { color in
HStack {
Circle()
.fill(color.color)
.frame(width: 20, height: 20)
Text(color.displayName)
}
.tag(color)
}
}
}
Section("Repository Settings") {
Picker("List Style", selection: $settingsManager.repositoryListStyle) {
ForEach(RepositoryListStyle.allCases) { style in
Text(style.displayName).tag(style)
}
}
Picker("Default Sort", selection: $settingsManager.defaultRepositorySort) {
ForEach(RepositorySort.allCases) { sort in
Text(sort.displayName).tag(sort)
}
}
Toggle(
"Show Private Repositories", isOn: $settingsManager.showPrivateRepositories)
Toggle(
"Show Forked Repositories", isOn: $settingsManager.showForkedRepositories)
}
Section("Notifications") {
Toggle("Enable Notifications", isOn: $settingsManager.enableNotifications)
Toggle("Sound", isOn: $settingsManager.notificationSoundEnabled)
}
Section("Data") {
Toggle("Cache Images", isOn: $settingsManager.cacheImages)
Toggle("Auto Refresh", isOn: $settingsManager.enableAutoRefresh)
if settingsManager.enableAutoRefresh {
Picker("Refresh Interval", selection: $settingsManager.autoRefreshInterval)
{
ForEach(RefreshInterval.allCases) { interval in
Text(interval.displayName).tag(interval)
}
}
}
}
Section("Account") {
Button("Sign Out", role: .destructive) {
showingSignOutConfirmation = true
}
}
Section("About") {
HStack {
Text("Version")
Spacer()
Text("1.0.0")
.foregroundColor(.secondary)
}
}
}
.navigationTitle("Settings")
.navigationBarTitleDisplayMode(.inline)
.toolbar {
ToolbarItem(placement: .navigationBarTrailing) {
Button("Done") {
dismiss()
}
}
}
.confirmationDialog("Sign Out", isPresented: $showingSignOutConfirmation) {
Button("Sign Out", role: .destructive) {
dismiss()
authManager.logout()
}
Button("Cancel", role: .cancel) {}
} message: {
Text(
"Are you sure you want to sign out? You'll need to sign in again to access your repositories."
)
}
}
}
}
#Preview {
MockProfileView()
.environmentObject(PreviewAuthenticationManager())
.environmentObject(PreviewSettingsManager())
}

View File

@ -0,0 +1,374 @@
import Foundation
import SwiftUI
struct RepositoriesView: View {
@EnvironmentObject private var authManager: AuthenticationManager
@State private var showingCreateRepository = false
@State private var repositories: [Repository] = []
@State private var filteredRepositories: [Repository] = []
@State private var isLoading = false
@State private var errorMessage: String?
@State private var searchText = ""
@State private var selectedSortOption = SortOption.updated
@State private var showingFilters = false
@State private var showPrivateOnly = false
@State private var showPublicOnly = false
@Namespace private var glassNamespace
enum SortOption: String, CaseIterable {
case name = "Name"
case updated = "Updated"
case created = "Created"
case stars = "Stars"
case forks = "Forks"
}
var body: some View {
NavigationStack {
VStack(spacing: 0) {
CustomHeader(
title: "Repositories",
trailingContent: {
AnyView(
HStack(spacing: 12) {
Button(action: { showingCreateRepository = true }) {
Image(systemName: "plus")
.font(.system(size: 18, weight: .medium))
.foregroundColor(.primary)
.frame(width: 44, height: 44)
.modifier(GlassEffectModifier(shape: Circle()))
}
.buttonStyle(.borderless)
Button(action: {
Task {
await fetchRepositories()
}
}) {
Image(systemName: "arrow.clockwise")
.font(.system(size: 18, weight: .medium))
.foregroundColor(.primary)
.frame(width: 44, height: 44)
.modifier(GlassEffectModifier(shape: Circle()))
}
.buttonStyle(.borderless)
Button(action: { showingFilters = true }) {
Image(systemName: "line.3.horizontal.decrease.circle")
.font(.system(size: 18, weight: .medium))
.foregroundColor(.primary)
.frame(width: 44, height: 44)
.modifier(GlassEffectModifier(shape: Circle()))
}
.buttonStyle(.borderless)
}
)
})
if isLoading {
LoadingView(message: "Loading repositories...")
} else if let errorMessage = errorMessage {
ErrorView(message: errorMessage) {
Task {
await fetchRepositories()
}
}
} else if repositories.isEmpty {
EmptyStateView(
systemImage: "folder",
title: "No Repositories",
description:
"You don't have any repositories yet. Create your first repository to get started.",
actionTitle: "Create Repository"
) {
showingCreateRepository = true
}
} else {
List(filteredRepositories) { repository in
NavigationLink(
destination: RepositoryDetailView(
repository: repository,
onRepositoryUpdated: {
Task {
await fetchRepositories()
}
})
) {
CompactRepositoryRow(repository: repository)
}
.listRowInsets(EdgeInsets(top: 6, leading: 16, bottom: 6, trailing: 16))
.swipeActions(edge: .trailing, allowsFullSwipe: false) {
Button {
// Open in browser
if let url = URL(string: repository.htmlUrl) {
UIApplication.shared.open(url)
}
} label: {
Image(systemName: "safari")
Text("Open")
}
.tint(.blue)
ShareLink(item: URL(string: repository.htmlUrl)!) {
Image(systemName: "square.and.arrow.up")
Text("Share")
}
.tint(.green)
}
.swipeActions(edge: .leading, allowsFullSwipe: false) {
Button {
// Copy clone URL
UIPasteboard.general.string = repository.cloneUrl
} label: {
Image(systemName: "doc.on.doc")
Text("Copy")
}
.tint(.orange)
}
}
.listStyle(.plain)
.searchable(text: $searchText, prompt: "Search repositories...")
.onChange(of: searchText) { _ in
applyFiltersAndSort()
}
}
}
.sheet(
isPresented: $showingCreateRepository,
onDismiss: {
// Refresh repositories when create sheet is dismissed
Task {
await fetchRepositories()
}
}
) {
CreateRepositoryView()
.environmentObject(authManager)
}
.sheet(isPresented: $showingFilters) {
FiltersView(
showPrivateOnly: $showPrivateOnly,
showPublicOnly: $showPublicOnly,
selectedSortOption: $selectedSortOption,
onApply: {
applyFiltersAndSort()
},
onRefresh: {
Task {
await fetchRepositories()
}
}
)
}
.task {
await fetchRepositories()
}
}
}
private func applyFiltersAndSort() {
var filtered = repositories
// Apply search filter
if !searchText.isEmpty {
filtered = filtered.filter { repository in
repository.name.localizedCaseInsensitiveContains(searchText)
|| repository.description?.localizedCaseInsensitiveContains(
searchText) == true
|| repository.owner.login.localizedCaseInsensitiveContains(
searchText)
|| repository.language?.localizedCaseInsensitiveContains(
searchText) == true
}
}
// Apply visibility filters
if showPrivateOnly {
filtered = filtered.filter { $0.private }
} else if showPublicOnly {
filtered = filtered.filter { !$0.private }
}
// Apply sorting
switch selectedSortOption {
case .name:
filtered = filtered.sorted {
$0.name.localizedCaseInsensitiveCompare($1.name)
== .orderedAscending
}
case .updated:
filtered = filtered.sorted { $0.updatedAt > $1.updatedAt }
case .created:
filtered = filtered.sorted { $0.createdAt > $1.createdAt }
case .stars:
filtered = filtered.sorted { $0.stargazersCount > $1.stargazersCount }
case .forks:
filtered = filtered.sorted { $0.forksCount > $1.forksCount }
}
filteredRepositories = filtered
}
private func fetchRepositories() async {
guard let apiService = authManager.getAPIService() else {
errorMessage = "Not authenticated"
return
}
isLoading = true
errorMessage = nil
do {
repositories = try await apiService.getUserRepositories()
applyFiltersAndSort()
} catch {
errorMessage = error.localizedDescription
}
isLoading = false
}
}
struct FiltersView: View {
@Binding var showPrivateOnly: Bool
@Binding var showPublicOnly: Bool
@Binding var selectedSortOption: RepositoriesView.SortOption
let onApply: () -> Void
let onRefresh: () -> Void
@Environment(\.dismiss) private var dismiss
var body: some View {
NavigationView {
Form {
Section("Visibility") {
Toggle("Private repositories only", isOn: $showPrivateOnly)
.onChange(of: showPrivateOnly) { newValue in
if newValue {
showPublicOnly = false
}
}
Toggle("Public repositories only", isOn: $showPublicOnly)
.onChange(of: showPublicOnly) { newValue in
if newValue {
showPrivateOnly = false
}
}
}
Section("Sort By") {
Picker("Sort Option", selection: $selectedSortOption) {
ForEach(RepositoriesView.SortOption.allCases, id: \.self) { option in
Text(option.rawValue).tag(option)
}
}
.pickerStyle(.wheel)
}
Section {
Button("Clear All Filters") {
showPrivateOnly = false
showPublicOnly = false
selectedSortOption = .updated
onApply()
}
Button("Refresh") {
onRefresh()
dismiss()
}
}
}
.navigationTitle("Filters & Sort")
.navigationBarTitleDisplayMode(.inline)
.toolbar {
ToolbarItem(placement: .navigationBarLeading) {
Button("Cancel") {
dismiss()
}
}
ToolbarItem(placement: .navigationBarTrailing) {
Button("Apply") {
onApply()
dismiss()
}
}
}
}
}
}
struct CompactRepositoryRow: View {
let repository: Repository
var body: some View {
HStack(spacing: 12) {
VStack(alignment: .leading, spacing: 2) {
HStack(spacing: 6) {
Text(repository.name)
.font(.system(size: 16, weight: .medium))
.foregroundColor(.primary)
.lineLimit(1)
if repository.private {
Image(systemName: "lock.fill")
.font(.system(size: 12))
.foregroundColor(.secondary)
}
Spacer()
}
if let description = repository.description, !description.isEmpty {
Text(description)
.font(.system(size: 13))
.foregroundColor(.secondary)
.lineLimit(1)
}
HStack(spacing: 12) {
if let language = repository.language {
HStack(spacing: 4) {
Circle()
.fill(colorForLanguage(language))
.frame(width: 8, height: 8)
Text(language)
.font(.system(size: 12))
.foregroundColor(.secondary)
}
}
if repository.stargazersCount > 0 {
HStack(spacing: 2) {
Image(systemName: "star.fill")
.font(.system(size: 10))
Text("\(repository.stargazersCount)")
.font(.system(size: 12))
}
.foregroundColor(.secondary)
}
if repository.forksCount > 0 {
HStack(spacing: 2) {
Image(systemName: "tuningfork")
.font(.system(size: 10))
Text("\(repository.forksCount)")
.font(.system(size: 12))
}
.foregroundColor(.secondary)
}
Spacer()
Text(repository.updatedAt.timeAgoSince())
.font(.system(size: 11))
.foregroundColor(.secondary)
}
}
}
.padding(.vertical, 4)
.contentShape(Rectangle())
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,17 @@
//
// SwiftForgeTests.swift
// SwiftForgeTests
//
// Created by Atridad Lahiji on 2025-07-04.
//
import Testing
@testable import SwiftForge
struct SwiftForgeTests {
@Test func example() async throws {
// Write your test here and use APIs like `#expect(...)` to check expected conditions.
}
}

View File

@ -0,0 +1,41 @@
//
// SwiftForgeUITests.swift
// SwiftForgeUITests
//
// Created by Atridad Lahiji on 2025-07-04.
//
import XCTest
final class SwiftForgeUITests: XCTestCase {
override func setUpWithError() throws {
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// In UI tests its important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
override func tearDownWithError() throws {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
@MainActor
func testExample() throws {
// UI tests must launch the application that they test.
let app = XCUIApplication()
app.launch()
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
@MainActor
func testLaunchPerformance() throws {
// This measures how long it takes to launch your application.
measure(metrics: [XCTApplicationLaunchMetric()]) {
XCUIApplication().launch()
}
}
}

View File

@ -0,0 +1,33 @@
//
// SwiftForgeUITestsLaunchTests.swift
// SwiftForgeUITests
//
// Created by Atridad Lahiji on 2025-07-04.
//
import XCTest
final class SwiftForgeUITestsLaunchTests: XCTestCase {
override class var runsForEachTargetApplicationUIConfiguration: Bool {
true
}
override func setUpWithError() throws {
continueAfterFailure = false
}
@MainActor
func testLaunch() throws {
let app = XCUIApplication()
app.launch()
// Insert steps here to perform after app launch but before taking a screenshot,
// such as logging into a test account or navigating somewhere in the app
let attachment = XCTAttachment(screenshot: app.screenshot())
attachment.name = "Launch Screen"
attachment.lifetime = .keepAlways
add(attachment)
}
}