Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
50872d8951 | ||
|
|
68458be71f | ||
|
|
65c776d1a2 | ||
|
|
105bdc8c75 | ||
|
|
619de5e1f8 | ||
|
|
106abd851a | ||
|
|
f50fc96416 | ||
|
|
1f23f54ee4 | ||
|
|
1c8aa9265c | ||
|
|
a706962e1e | ||
|
|
60313f5373 | ||
|
|
92418e7e4e | ||
|
|
5c413f4e8b | ||
|
|
2183dda2df | ||
|
|
2fa12e22d5 | ||
|
|
c3f1af6818 | ||
|
|
18aeeb200f | ||
|
|
b40fa704c6 | ||
|
|
55787fe3c5 | ||
|
|
43589410e3 | ||
|
|
9ac27f5fbd | ||
|
|
1faab39849 | ||
|
|
0ad0e362d6 | ||
|
|
7fbf3593fb | ||
|
|
8830b130ad | ||
|
|
aaecba5642 | ||
|
|
05c3dcd5b5 | ||
|
|
f678c0fa54 | ||
|
|
ef09b642d6 | ||
|
|
7852a77a7c | ||
|
|
582eb68139 | ||
|
|
d0ff245582 | ||
|
|
a109c7115e | ||
|
|
8a06d7cb93 | ||
|
|
60eb56da56 | ||
|
|
0877993b41 | ||
|
|
d404f5daab | ||
|
|
8e0ae3dd83 | ||
|
|
85d98a41c1 | ||
|
|
e1fe000608 | ||
|
|
e853268e52 | ||
|
|
4428cc7e8a | ||
|
|
1af139201d |
@@ -0,0 +1,3 @@
|
|||||||
|
# Drizzle
|
||||||
|
# Replace with your DB credentials!
|
||||||
|
DATABASE_URL="mysql://user:password@host:port/db-name"
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
|
test-results
|
||||||
node_modules
|
node_modules
|
||||||
|
|
||||||
# Output
|
# Output
|
||||||
|
|||||||
@@ -7,3 +7,4 @@ bun.lockb
|
|||||||
|
|
||||||
# Miscellaneous
|
# Miscellaneous
|
||||||
/static/
|
/static/
|
||||||
|
/drizzle/
|
||||||
|
|||||||
@@ -0,0 +1,16 @@
|
|||||||
|
{
|
||||||
|
"useTabs": true,
|
||||||
|
"singleQuote": true,
|
||||||
|
"trailingComma": "none",
|
||||||
|
"printWidth": 100,
|
||||||
|
"plugins": ["prettier-plugin-svelte", "prettier-plugin-tailwindcss"],
|
||||||
|
"overrides": [
|
||||||
|
{
|
||||||
|
"files": "*.svelte",
|
||||||
|
"options": {
|
||||||
|
"parser": "svelte"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"tailwindStylesheet": "./src/app.css"
|
||||||
|
}
|
||||||
@@ -1,8 +0,0 @@
|
|||||||
{
|
|
||||||
"recommendations": [
|
|
||||||
"svelte.svelte-vscode",
|
|
||||||
"esbenp.prettier-vscode",
|
|
||||||
"dbaeumer.vscode-eslint",
|
|
||||||
"bradlc.vscode-tailwindcss"
|
|
||||||
]
|
|
||||||
}
|
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
{
|
|
||||||
"files.associations": {
|
|
||||||
"*.css": "tailwindcss"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,232 @@
|
|||||||
|
GNU GENERAL PUBLIC LICENSE
|
||||||
|
Version 3, 29 June 2007
|
||||||
|
|
||||||
|
Copyright © 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||||
|
|
||||||
|
Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
|
||||||
|
|
||||||
|
Preamble
|
||||||
|
|
||||||
|
The GNU General Public License is a free, copyleft license for software and other kinds of works.
|
||||||
|
|
||||||
|
The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too.
|
||||||
|
|
||||||
|
When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things.
|
||||||
|
|
||||||
|
To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others.
|
||||||
|
|
||||||
|
For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights.
|
||||||
|
|
||||||
|
Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it.
|
||||||
|
|
||||||
|
For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions.
|
||||||
|
|
||||||
|
Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users.
|
||||||
|
|
||||||
|
Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free.
|
||||||
|
|
||||||
|
The precise terms and conditions for copying, distribution and modification follow.
|
||||||
|
|
||||||
|
TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
0. Definitions.
|
||||||
|
|
||||||
|
“This License” refers to version 3 of the GNU General Public License.
|
||||||
|
|
||||||
|
“Copyright” also means copyright-like laws that apply to other kinds of works, such as semiconductor masks.
|
||||||
|
|
||||||
|
“The Program” refers to any copyrightable work licensed under this License. Each licensee is addressed as “you”. “Licensees” and “recipients” may be individuals or organizations.
|
||||||
|
|
||||||
|
To “modify” a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a “modified version” of the earlier work or a work “based on” the earlier work.
|
||||||
|
|
||||||
|
A “covered work” means either the unmodified Program or a work based on the Program.
|
||||||
|
|
||||||
|
To “propagate” a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well.
|
||||||
|
|
||||||
|
To “convey” a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying.
|
||||||
|
|
||||||
|
An interactive user interface displays “Appropriate Legal Notices” to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion.
|
||||||
|
|
||||||
|
1. Source Code.
|
||||||
|
The “source code” for a work means the preferred form of the work for making modifications to it. “Object code” means any non-source form of a work.
|
||||||
|
|
||||||
|
A “Standard Interface” means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language.
|
||||||
|
|
||||||
|
The “System Libraries” of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A “Major Component”, in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it.
|
||||||
|
|
||||||
|
The “Corresponding Source” for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work.
|
||||||
|
|
||||||
|
The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source.
|
||||||
|
|
||||||
|
The Corresponding Source for a work in source code form is that same work.
|
||||||
|
|
||||||
|
2. Basic Permissions.
|
||||||
|
All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law.
|
||||||
|
|
||||||
|
You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you.
|
||||||
|
|
||||||
|
Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary.
|
||||||
|
|
||||||
|
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||||
|
No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures.
|
||||||
|
|
||||||
|
When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures.
|
||||||
|
|
||||||
|
4. Conveying Verbatim Copies.
|
||||||
|
You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program.
|
||||||
|
|
||||||
|
You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee.
|
||||||
|
|
||||||
|
5. Conveying Modified Source Versions.
|
||||||
|
You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions:
|
||||||
|
|
||||||
|
a) The work must carry prominent notices stating that you modified it, and giving a relevant date.
|
||||||
|
|
||||||
|
b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to “keep intact all notices”.
|
||||||
|
|
||||||
|
c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it.
|
||||||
|
|
||||||
|
d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so.
|
||||||
|
|
||||||
|
A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an “aggregate” if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate.
|
||||||
|
|
||||||
|
6. Conveying Non-Source Forms.
|
||||||
|
You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways:
|
||||||
|
|
||||||
|
a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange.
|
||||||
|
|
||||||
|
b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge.
|
||||||
|
|
||||||
|
c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b.
|
||||||
|
|
||||||
|
d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements.
|
||||||
|
|
||||||
|
e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d.
|
||||||
|
|
||||||
|
A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work.
|
||||||
|
|
||||||
|
A “User Product” is either (1) a “consumer product”, which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, “normally used” refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product.
|
||||||
|
|
||||||
|
“Installation Information” for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made.
|
||||||
|
|
||||||
|
If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM).
|
||||||
|
|
||||||
|
The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network.
|
||||||
|
|
||||||
|
Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying.
|
||||||
|
|
||||||
|
7. Additional Terms.
|
||||||
|
“Additional permissions” are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions.
|
||||||
|
|
||||||
|
When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms:
|
||||||
|
|
||||||
|
a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or
|
||||||
|
|
||||||
|
b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or
|
||||||
|
|
||||||
|
c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or
|
||||||
|
|
||||||
|
d) Limiting the use for publicity purposes of names of licensors or authors of the material; or
|
||||||
|
|
||||||
|
e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or
|
||||||
|
|
||||||
|
f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors.
|
||||||
|
|
||||||
|
All other non-permissive additional terms are considered “further restrictions” within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying.
|
||||||
|
|
||||||
|
If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms.
|
||||||
|
|
||||||
|
Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way.
|
||||||
|
|
||||||
|
8. Termination.
|
||||||
|
You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11).
|
||||||
|
|
||||||
|
However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation.
|
||||||
|
|
||||||
|
Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice.
|
||||||
|
|
||||||
|
Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10.
|
||||||
|
|
||||||
|
9. Acceptance Not Required for Having Copies.
|
||||||
|
You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so.
|
||||||
|
|
||||||
|
10. Automatic Licensing of Downstream Recipients.
|
||||||
|
Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License.
|
||||||
|
|
||||||
|
An “entity transaction” is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts.
|
||||||
|
|
||||||
|
You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it.
|
||||||
|
|
||||||
|
11. Patents.
|
||||||
|
A “contributor” is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's “contributor version”.
|
||||||
|
|
||||||
|
A contributor's “essential patent claims” are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, “control” includes the right to grant patent sublicenses in a manner consistent with the requirements of this License.
|
||||||
|
|
||||||
|
Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version.
|
||||||
|
|
||||||
|
In the following three paragraphs, a “patent license” is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To “grant” such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party.
|
||||||
|
|
||||||
|
If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. “Knowingly relying” means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid.
|
||||||
|
|
||||||
|
If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it.
|
||||||
|
|
||||||
|
A patent license is “discriminatory” if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007.
|
||||||
|
|
||||||
|
Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law.
|
||||||
|
|
||||||
|
12. No Surrender of Others' Freedom.
|
||||||
|
If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program.
|
||||||
|
|
||||||
|
13. Use with the GNU Affero General Public License.
|
||||||
|
Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such.
|
||||||
|
|
||||||
|
14. Revised Versions of this License.
|
||||||
|
The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
|
||||||
|
|
||||||
|
Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License “or any later version” applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation.
|
||||||
|
|
||||||
|
If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program.
|
||||||
|
|
||||||
|
Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version.
|
||||||
|
|
||||||
|
15. Disclaimer of Warranty.
|
||||||
|
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||||
|
|
||||||
|
16. Limitation of Liability.
|
||||||
|
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
|
||||||
|
|
||||||
|
17. Interpretation of Sections 15 and 16.
|
||||||
|
If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee.
|
||||||
|
|
||||||
|
END OF TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
How to Apply These Terms to Your New Programs
|
||||||
|
|
||||||
|
If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms.
|
||||||
|
|
||||||
|
To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the “copyright” line and a pointer to where the full notice is found.
|
||||||
|
|
||||||
|
olszewski.ink
|
||||||
|
Copyright (C) 2026 ChaosMaker
|
||||||
|
|
||||||
|
This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
|
||||||
|
|
||||||
|
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
|
||||||
|
|
||||||
|
You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
Also add information on how to contact you by electronic and paper mail.
|
||||||
|
|
||||||
|
If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode:
|
||||||
|
|
||||||
|
olszewski.ink Copyright (C) 2026 ChaosMaker
|
||||||
|
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||||
|
This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details.
|
||||||
|
|
||||||
|
The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an “about box”.
|
||||||
|
|
||||||
|
You should also get your employer (if you work as a programmer) or school, if any, to sign a “copyright disclaimer” for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see <https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read <https://www.gnu.org/philosophy/why-not-lgpl.html>.
|
||||||
@@ -1,54 +1,62 @@
|
|||||||
# sv
|
Preview can be found here -> https://gornodox.dev
|
||||||
|
|
||||||
Everything you need to build a Svelte project, powered by [`sv`](https://github.com/sveltejs/cli).
|
Hello everyone that decided to visit my repo.
|
||||||
|
Today i present to you a 'Work In Progress', state of the art (not really) portfolio website.
|
||||||
|
|
||||||
## Creating a project
|
The main idea was that the "bash terminal" would serve as the main interface that the user would interact with...
|
||||||
|
|
||||||
If you're seeing this, you've probably already done this step. Congrats!
|
But then I thought to myself,
|
||||||
|
>*Wouldn't it be cool if it would actually work like a terminal?`*
|
||||||
|
|
||||||
```sh
|
...and that's how we got here.
|
||||||
# create a new project
|
|
||||||
npx sv create my-app
|
|
||||||
```
|
|
||||||
|
|
||||||
To recreate this project with the same configuration:
|
>***Make note that not all features listed below may be implemented when you're seeing this.***
|
||||||
|
|
||||||
```sh
|
The whole environment is a simulation of a linux environment, from every data structure to the way everything behaves. Theres a file system representation that gets generated from a live folder structure by [this](https://github.com/ChaosMakerMLG/FileSystemParser) project.
|
||||||
# recreate this project
|
This gets parsed by my website into the object structure that the whole `Bash` algorithm can deal and interact with.
|
||||||
pnpm dlx sv@1.1.1 create --template minimal --types ts --add prettier eslint tailwindcss="plugins:none" --install pnpm gornodox.dev
|
|
||||||
```
|
|
||||||
|
|
||||||
## Adding features
|
There are users, permissions, ownership, links (hard and symbolic)
|
||||||
|
File system supports file contents - they get cached into a file with a name, and the node stored on heap just has the name to the correct file cache.
|
||||||
|
|
||||||
Add features to your project with `sv add`:
|
Every command is treated like a process that can be exited
|
||||||
|
aswell as files being executable
|
||||||
|
|
||||||
```sh
|
All of this is purely data-driven and modular, so if you where to take my code and just implement an IO system that would interact with my algorithm, then it would work out of the box, which is REALLYYY COOOL in my opinion.
|
||||||
npx sv add
|
|
||||||
```
|
|
||||||
|
|
||||||
For example, to add Tailwind CSS:
|
All the changes that the user makes will be stored on their browsers `localStorage` and read out on login
|
||||||
|
|
||||||
```sh
|
The website will still serve the purpose of being a portfolio but the actuall portfolio part will just be a process that is ran at initialization of the terminal, and it will display the info about me as a TUI ^w^
|
||||||
npx sv add tailwindcss
|
|
||||||
```
|
|
||||||
|
|
||||||
## Developing
|
It can of course be shutdown as mentioned above and thats how you get access to the shell ;)
|
||||||
|
|
||||||
Once you've created a project and installed dependencies with `npm install` (or `pnpm install` or `yarn`), start a development server:
|
## This project uses and implements:
|
||||||
|
|
||||||
```sh
|
- Tree traversal
|
||||||
npm run dev
|
- Binary search
|
||||||
|
- Quick sort
|
||||||
|
- And much mode weird stuff...
|
||||||
|
|
||||||
# or start the server and open the app in a new browser tab
|
## Commands:
|
||||||
npm run dev -- --open
|
- return
|
||||||
```
|
- ls
|
||||||
|
- echo
|
||||||
|
- touch
|
||||||
|
- mkdir
|
||||||
|
- pwd
|
||||||
|
- cd
|
||||||
|
- exit
|
||||||
|
- cp
|
||||||
|
- mv
|
||||||
|
- rm
|
||||||
|
- cat
|
||||||
|
- less
|
||||||
|
- chown
|
||||||
|
- chmod
|
||||||
|
- reboot
|
||||||
|
- help
|
||||||
|
- whoami
|
||||||
|
- sudo
|
||||||
|
- su
|
||||||
|
- clear
|
||||||
|
|
||||||
## Building
|
> More will probably added with time :)
|
||||||
|
|
||||||
To create a production version of your app:
|
|
||||||
|
|
||||||
```sh
|
|
||||||
npm run build
|
|
||||||
```
|
|
||||||
|
|
||||||
You can preview the production build with `npm run preview`.
|
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
import { defineConfig } from 'drizzle-kit';
|
||||||
|
|
||||||
|
if (!process.env.DATABASE_URL) throw new Error('DATABASE_URL is not set');
|
||||||
|
|
||||||
|
export default defineConfig({
|
||||||
|
schema: './src/lib/server/db/schema.ts',
|
||||||
|
dialect: 'mysql',
|
||||||
|
dbCredentials: { url: process.env.DATABASE_URL },
|
||||||
|
verbose: true,
|
||||||
|
strict: true
|
||||||
|
});
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
import { expect, test } from '@playwright/test';
|
||||||
|
|
||||||
|
test('home page has expected h1', async ({ page }) => {
|
||||||
|
await page.goto('/');
|
||||||
|
await expect(page.locator('h1')).toBeVisible();
|
||||||
|
});
|
||||||
@@ -1,22 +1,26 @@
|
|||||||
import prettier from 'eslint-config-prettier';
|
import prettier from 'eslint-config-prettier';
|
||||||
import path from 'node:path';
|
import { fileURLToPath } from 'node:url';
|
||||||
|
import { includeIgnoreFile } from '@eslint/compat';
|
||||||
import js from '@eslint/js';
|
import js from '@eslint/js';
|
||||||
import svelte from 'eslint-plugin-svelte';
|
import svelte from 'eslint-plugin-svelte';
|
||||||
import { defineConfig, includeIgnoreFile } from 'eslint/config';
|
import { defineConfig } from 'eslint/config';
|
||||||
import globals from 'globals';
|
import globals from 'globals';
|
||||||
import ts from 'typescript-eslint';
|
import ts from 'typescript-eslint';
|
||||||
|
import svelteConfig from './svelte.config.js';
|
||||||
|
|
||||||
const gitignorePath = path.resolve(import.meta.dirname, '.gitignore');
|
const gitignorePath = fileURLToPath(new URL('./.gitignore', import.meta.url));
|
||||||
|
|
||||||
export default defineConfig(
|
export default defineConfig(
|
||||||
includeIgnoreFile(gitignorePath),
|
includeIgnoreFile(gitignorePath),
|
||||||
js.configs.recommended,
|
js.configs.recommended,
|
||||||
ts.configs.recommended,
|
...ts.configs.recommended,
|
||||||
svelte.configs.recommended,
|
...svelte.configs.recommended,
|
||||||
prettier,
|
prettier,
|
||||||
svelte.configs.prettier,
|
...svelte.configs.prettier,
|
||||||
{
|
{
|
||||||
languageOptions: { globals: { ...globals.browser, ...globals.node } },
|
languageOptions: {
|
||||||
|
globals: { ...globals.browser, ...globals.node }
|
||||||
|
},
|
||||||
rules: {
|
rules: {
|
||||||
// typescript-eslint strongly recommend that you do not use the no-undef lint rule on TypeScript projects.
|
// typescript-eslint strongly recommend that you do not use the no-undef lint rule on TypeScript projects.
|
||||||
// see: https://typescript-eslint.io/troubleshooting/faqs/eslint/#i-get-errors-from-the-no-undef-rule-about-global-variables-not-being-defined-even-though-there-are-no-typescript-errors
|
// see: https://typescript-eslint.io/troubleshooting/faqs/eslint/#i-get-errors-from-the-no-undef-rule-about-global-variables-not-being-defined-even-though-there-are-no-typescript-errors
|
||||||
@@ -29,13 +33,9 @@ export default defineConfig(
|
|||||||
parserOptions: {
|
parserOptions: {
|
||||||
projectService: true,
|
projectService: true,
|
||||||
extraFileExtensions: ['.svelte'],
|
extraFileExtensions: ['.svelte'],
|
||||||
parser: ts.parser
|
parser: ts.parser,
|
||||||
|
svelteConfig
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
|
||||||
{
|
|
||||||
// Override or add rule settings here, such as:
|
|
||||||
// 'svelte/button-has-type': 'error'
|
|
||||||
rules: {}
|
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"name": "gornodox.dev",
|
"name": "svelte-portfolio",
|
||||||
"private": true,
|
"private": true,
|
||||||
"version": "0.0.1",
|
"version": "0.0.69",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "vite dev",
|
"dev": "vite dev",
|
||||||
@@ -10,38 +10,49 @@
|
|||||||
"prepare": "svelte-kit sync || echo ''",
|
"prepare": "svelte-kit sync || echo ''",
|
||||||
"check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json",
|
"check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json",
|
||||||
"check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch",
|
"check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch",
|
||||||
|
"format": "prettier --write .",
|
||||||
"lint": "prettier --check . && eslint .",
|
"lint": "prettier --check . && eslint .",
|
||||||
"format": "prettier --write ."
|
"test:e2e": "playwright test",
|
||||||
|
"test": "npm run test:e2e && npm run test:unit -- --run",
|
||||||
|
"test:unit": "vitest",
|
||||||
|
"db:push": "drizzle-kit push",
|
||||||
|
"db:generate": "drizzle-kit generate",
|
||||||
|
"db:migrate": "drizzle-kit migrate",
|
||||||
|
"db:studio": "drizzle-kit studio"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@eslint/js": "^10.0.1",
|
"@eslint/compat": "^1.4.0",
|
||||||
"@sveltejs/adapter-node": "^6.0.2",
|
"@eslint/js": "^9.36.0",
|
||||||
"@sveltejs/kit": "^3.1.1",
|
"@playwright/test": "^1.55.1",
|
||||||
"@sveltejs/vite-plugin-svelte": "^7.3.1",
|
"@sveltejs/adapter-auto": "^6.1.0",
|
||||||
"@tailwindcss/vite": "^4.3.3",
|
"@sveltejs/kit": "^2.43.2",
|
||||||
"@types/node": "^26.6.6",
|
"@sveltejs/vite-plugin-svelte": "^6.2.0",
|
||||||
"eslint": "^10.14.0",
|
"@tailwindcss/vite": "^4.1.16",
|
||||||
|
"@types/node": "^24",
|
||||||
|
"@vitest/browser": "^3.2.4",
|
||||||
|
"drizzle-kit": "^0.18.1",
|
||||||
|
"drizzle-orm": "^0.45.2",
|
||||||
|
"eslint": "^9.36.0",
|
||||||
"eslint-config-prettier": "^10.1.8",
|
"eslint-config-prettier": "^10.1.8",
|
||||||
"eslint-plugin-svelte": "^3.23.1",
|
"eslint-plugin-svelte": "^3.12.4",
|
||||||
"globals": "^17.13.0",
|
"globals": "^16.4.0",
|
||||||
"prettier": "^3.9.10",
|
"mysql2": "^3.16.3",
|
||||||
"prettier-plugin-svelte": "^4.1.1",
|
"playwright": "^1.55.1",
|
||||||
"prettier-plugin-tailwindcss": "^0.8.1",
|
"prettier": "^3.6.2",
|
||||||
"svelte": "^5.57.3",
|
"prettier-plugin-svelte": "^3.4.0",
|
||||||
"svelte-check": "^4.7.7",
|
"prettier-plugin-tailwindcss": "^0.6.14",
|
||||||
"tailwindcss": "^4.3.3",
|
"svelte": "^5.39.5",
|
||||||
"typescript": "^6.0.3",
|
"svelte-check": "^4.3.2",
|
||||||
"typescript-eslint": "^8.72.1",
|
"tailwindcss": "^4.1.16",
|
||||||
"vite": "^8.3.5"
|
"typescript": "^5.9.2",
|
||||||
},
|
"typescript-eslint": "^8.44.1",
|
||||||
"imports": {
|
"vite": "^7.1.7",
|
||||||
"#lib": "./src/lib/index.js",
|
"vitest": "^3.2.4",
|
||||||
"#lib/*": "./src/lib/*"
|
"vitest-browser-svelte": "^1.1.0"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@lucide/svelte": "^1.66.0",
|
"@lucide/svelte": "^0.548.0",
|
||||||
"@wterm/dom": "^0.5.9",
|
"gl-matrix": "^3.4.4",
|
||||||
"@wterm/svelte": "^0.5.9",
|
"zod": "^4.3.6"
|
||||||
"termos": "file:./src/lib/termos-0.1.1.tgz"
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,9 @@
|
|||||||
|
import { defineConfig } from '@playwright/test';
|
||||||
|
|
||||||
|
export default defineConfig({
|
||||||
|
webServer: {
|
||||||
|
command: 'npm run build && npm run preview',
|
||||||
|
port: 4173
|
||||||
|
},
|
||||||
|
testDir: 'e2e'
|
||||||
|
});
|
||||||
@@ -1,2 +0,0 @@
|
|||||||
allowBuilds:
|
|
||||||
esbuild: true
|
|
||||||
@@ -1,12 +0,0 @@
|
|||||||
/** @type {import("prettier").Config} */
|
|
||||||
const config = {
|
|
||||||
useTabs: true,
|
|
||||||
singleQuote: true,
|
|
||||||
trailingComma: 'none',
|
|
||||||
printWidth: 100,
|
|
||||||
plugins: ['prettier-plugin-svelte', 'prettier-plugin-tailwindcss'],
|
|
||||||
overrides: [{ files: '*.svelte', options: { parser: 'svelte' } }],
|
|
||||||
tailwindStylesheet: './src/routes/layout.css'
|
|
||||||
};
|
|
||||||
|
|
||||||
export default config;
|
|
||||||
@@ -1,47 +1,6 @@
|
|||||||
@import './style/global.css';
|
@import './style/global.css';
|
||||||
@import './style/themes.css';
|
|
||||||
@import 'tailwindcss';
|
@import 'tailwindcss';
|
||||||
|
|
||||||
.crt-vignette {
|
|
||||||
position: fixed;
|
|
||||||
inset: 0;
|
|
||||||
z-index: 898;
|
|
||||||
pointer-events: none;
|
|
||||||
background: radial-gradient(ellipse at center, transparent 55%, rgba(0, 0, 0, 0.3) 100%);
|
|
||||||
}
|
|
||||||
|
|
||||||
/* scanlines — your existing rule, unchanged */
|
|
||||||
.crt-scanlines {
|
|
||||||
display: block;
|
|
||||||
position: fixed;
|
|
||||||
inset: 0;
|
|
||||||
pointer-events: none;
|
|
||||||
z-index: 900;
|
|
||||||
background:
|
|
||||||
linear-gradient(rgba(18, 16, 16, 0) 50%, rgba(0, 0, 0, 0.25) 50%),
|
|
||||||
linear-gradient(90deg, rgba(255, 0, 0, 0.06), rgba(0, 255, 0, 0.02), rgba(0, 0, 255, 0.06));
|
|
||||||
background-size:
|
|
||||||
100% 2px,
|
|
||||||
3px 100%;
|
|
||||||
}
|
|
||||||
|
|
||||||
/* grain — SVG fractal noise, tiled, topmost */
|
|
||||||
.crt-grain {
|
|
||||||
position: fixed;
|
|
||||||
inset: 0;
|
|
||||||
z-index: 902;
|
|
||||||
pointer-events: none;
|
|
||||||
opacity: 0.035;
|
|
||||||
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='160' height='160'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.9' numOctaves='3' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)'/%3E%3C/svg%3E");
|
|
||||||
}
|
|
||||||
|
|
||||||
/* single toggle — hides all three when data-crt="false" */
|
|
||||||
:root[data-crt='false'] #crt-vignette,
|
|
||||||
:root[data-crt='false'] #crt-scanlines,
|
|
||||||
:root[data-crt='false'] #crt-grain {
|
|
||||||
display: none;
|
|
||||||
}
|
|
||||||
|
|
||||||
:root {
|
:root {
|
||||||
font-family: system-ui, Avenir, Helvetica, Arial, sans-serif;
|
font-family: system-ui, Avenir, Helvetica, Arial, sans-serif;
|
||||||
line-height: 1.5;
|
line-height: 1.5;
|
||||||
@@ -82,11 +41,10 @@ h1 {
|
|||||||
padding: 2em;
|
padding: 2em;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* button:hover {
|
button:hover {
|
||||||
border-color: #646cff;
|
border-color: #646cff;
|
||||||
}
|
}
|
||||||
button:focus,
|
button:focus,
|
||||||
button:focus-visible {
|
button:focus-visible {
|
||||||
outline: 4px auto -webkit-focus-ring-color;
|
outline: 4px auto -webkit-focus-ring-color;
|
||||||
}
|
}
|
||||||
*/
|
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ declare global {
|
|||||||
// interface PageState {}
|
// interface PageState {}
|
||||||
// interface Platform {}
|
// interface Platform {}
|
||||||
}
|
}
|
||||||
|
namespace TermOS {}
|
||||||
}
|
}
|
||||||
|
|
||||||
export {};
|
export {};
|
||||||
|
|||||||
@@ -1,26 +1,11 @@
|
|||||||
<!doctype html>
|
<!doctype html>
|
||||||
<html lang="en" data-theme="gruvbox">
|
<html lang="en">
|
||||||
<head>
|
<head>
|
||||||
<script>
|
|
||||||
// Immediately apply saved or system theme – no flash
|
|
||||||
(function () {
|
|
||||||
const saved = localStorage.getItem('theme');
|
|
||||||
const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
|
|
||||||
const theme =
|
|
||||||
saved === 'dark' || saved === 'light' ? saved : prefersDark ? 'dark' : 'light';
|
|
||||||
document.documentElement.setAttribute('data-theme', theme);
|
|
||||||
document.documentElement.style.setProperty('--initial-load', 'true');
|
|
||||||
})();
|
|
||||||
</script>
|
|
||||||
<meta charset="utf-8" />
|
<meta charset="utf-8" />
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||||
<meta name="text-scale" content="scale" />
|
|
||||||
%sveltekit.head%
|
%sveltekit.head%
|
||||||
</head>
|
</head>
|
||||||
<body data-sveltekit-preload-data="hover">
|
<body data-sveltekit-preload-data="hover">
|
||||||
<div style="display: contents">%sveltekit.body%</div>
|
<div style="display: contents">%sveltekit.body%</div>
|
||||||
<!-- <div id="crt-vignette" class="crt-vignette" aria-hidden="true"></div> -->
|
|
||||||
<div id="crt-scanlines" class="crt-scanlines" aria-hidden="true"></div>
|
|
||||||
<div id="crt-grain" class="crt-grain" aria-hidden="true"></div>
|
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -0,0 +1,7 @@
|
|||||||
|
import { describe, it, expect } from 'vitest';
|
||||||
|
|
||||||
|
describe('sum test', () => {
|
||||||
|
it('adds 1 + 2 to equal 3', () => {
|
||||||
|
expect(1 + 2).toBe(3);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
<?xml version="1.0" encoding="iso-8859-1"?>
|
||||||
|
<!-- Uploaded to: SVG Repo, www.svgrepo.com, Generator: SVG Repo Mixer Tools -->
|
||||||
|
<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"
|
||||||
|
viewBox="0 0 512 512" xml:space="preserve">
|
||||||
|
<path style="fill:#464655;" d="M473.655,88.276H38.345C17.167,88.276,0,105.443,0,126.621v73.471h512v-73.471
|
||||||
|
C512,105.443,494.833,88.276,473.655,88.276z"/>
|
||||||
|
<path style="fill:#FFE15A;" d="M0,385.379c0,21.177,17.167,38.345,38.345,38.345h435.31c21.177,0,38.345-17.167,38.345-38.345
|
||||||
|
v-73.471H0V385.379z"/>
|
||||||
|
<rect y="200.09" style="fill:#FF4B55;" width="512" height="111.81"/>
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 668 B |
@@ -0,0 +1,2 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?><!-- Uploaded to: SVG Repo, www.svgrepo.com, Generator: SVG Repo Mixer Tools -->
|
||||||
|
<svg width="800px" height="800px" viewBox="0 0 36 36" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--twemoji" preserveAspectRatio="xMidYMid meet"><path fill="#00247D" d="M0 9.059V13h5.628zM4.664 31H13v-5.837zM23 25.164V31h8.335zM0 23v3.941L5.63 23zM31.337 5H23v5.837zM36 26.942V23h-5.631zM36 13V9.059L30.371 13zM13 5H4.664L13 10.837z"></path><path fill="#CF1B2B" d="M25.14 23l9.712 6.801a3.977 3.977 0 0 0 .99-1.749L28.627 23H25.14zM13 23h-2.141l-9.711 6.8c.521.53 1.189.909 1.938 1.085L13 23.943V23zm10-10h2.141l9.711-6.8a3.988 3.988 0 0 0-1.937-1.085L23 12.057V13zm-12.141 0L1.148 6.2a3.994 3.994 0 0 0-.991 1.749L7.372 13h3.487z"></path><path fill="#EEE" d="M36 21H21v10h2v-5.836L31.335 31H32a3.99 3.99 0 0 0 2.852-1.199L25.14 23h3.487l7.215 5.052c.093-.337.158-.686.158-1.052v-.058L30.369 23H36v-2zM0 21v2h5.63L0 26.941V27c0 1.091.439 2.078 1.148 2.8l9.711-6.8H13v.943l-9.914 6.941c.294.07.598.116.914.116h.664L13 25.163V31h2V21H0zM36 9a3.983 3.983 0 0 0-1.148-2.8L25.141 13H23v-.943l9.915-6.942A4.001 4.001 0 0 0 32 5h-.663L23 10.837V5h-2v10h15v-2h-5.629L36 9.059V9zM13 5v5.837L4.664 5H4a3.985 3.985 0 0 0-2.852 1.2l9.711 6.8H7.372L.157 7.949A3.968 3.968 0 0 0 0 9v.059L5.628 13H0v2h15V5h-2z"></path><path fill="#CF1B2B" d="M21 15V5h-6v10H0v6h15v10h6V21h15v-6z"></path></svg>
|
||||||
|
After Width: | Height: | Size: 1.4 KiB |
|
Before Width: | Height: | Size: 1.5 KiB After Width: | Height: | Size: 1.5 KiB |
@@ -0,0 +1,10 @@
|
|||||||
|
<?xml version="1.0" encoding="iso-8859-1"?>
|
||||||
|
<!-- Uploaded to: SVG Repo, www.svgrepo.com, Generator: SVG Repo Mixer Tools -->
|
||||||
|
<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"
|
||||||
|
viewBox="0 0 512 512" xml:space="preserve">
|
||||||
|
<path style="fill:#41479B;" d="M38.345,88.273C17.167,88.273,0,105.44,0,126.618v258.759c0,21.177,17.167,38.345,38.345,38.345
|
||||||
|
h132.322V88.273H38.345z"/>
|
||||||
|
<rect x="170.67" y="88.277" style="fill:#F5F5F5;" width="170.67" height="335.45"/>
|
||||||
|
<path style="fill:#FF4B55;" d="M473.655,88.273H341.333v335.448h132.322c21.177,0,38.345-17.167,38.345-38.345V126.618
|
||||||
|
C512,105.44,494.833,88.273,473.655,88.273z"/>
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 695 B |
@@ -0,0 +1 @@
|
|||||||
|
32aac83d-ce2b-4def-977c-dcdcb6f514ef
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
<?xml version="1.0" encoding="iso-8859-1"?>
|
||||||
|
<!-- Uploaded to: SVG Repo, www.svgrepo.com, Generator: SVG Repo Mixer Tools -->
|
||||||
|
<svg height="800px" width="800px" version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"
|
||||||
|
viewBox="0 0 512 512" xml:space="preserve">
|
||||||
|
<path style="fill:#F5F5F5;" d="M473.655,88.275H38.345C17.167,88.275,0,105.442,0,126.62V385.38
|
||||||
|
c0,21.177,17.167,38.345,38.345,38.345h435.31c21.177,0,38.345-17.167,38.345-38.345V126.62
|
||||||
|
C512,105.442,494.833,88.275,473.655,88.275z"/>
|
||||||
|
<circle style="fill:#FF4B55;" cx="256" cy="255.999" r="97.1"/>
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 620 B |
|
After Width: | Height: | Size: 11 KiB |
|
After Width: | Height: | Size: 44 KiB |
@@ -0,0 +1,2 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?><!-- Uploaded to: SVG Repo, www.svgrepo.com, Generator: SVG Repo Mixer Tools -->
|
||||||
|
<svg width="800px" height="800px" viewBox="0 0 36 36" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--twemoji" preserveAspectRatio="xMidYMid meet"><path fill="#EEE" d="M32 5H4a4 4 0 0 0-4 4v9h36V9a4 4 0 0 0-4-4z"></path><path fill="#DC143C" d="M0 27a4 4 0 0 0 4 4h28a4 4 0 0 0 4-4v-9H0v9z"></path></svg>
|
||||||
|
After Width: | Height: | Size: 506 B |
@@ -1 +1,2 @@
|
|||||||
// place files you want to import through the `#lib` alias in this folder.
|
|
||||||
|
|
||||||
|
|||||||
@@ -1,43 +0,0 @@
|
|||||||
<script lang="ts">
|
|
||||||
import { onMount, type SvelteComponent } from 'svelte';
|
|
||||||
|
|
||||||
let {
|
|
||||||
node,
|
|
||||||
callbacks
|
|
||||||
}: {
|
|
||||||
node: HTMLElement | SvelteComponent | Document;
|
|
||||||
callbacks: { title: string; fn: (e: MouseEvent) => void }[];
|
|
||||||
} = $props();
|
|
||||||
|
|
||||||
let contextMenu: HTMLElement;
|
|
||||||
|
|
||||||
onMount(() => {
|
|
||||||
node.oncontextmenu = showContextMenu;
|
|
||||||
node.onclick = hideContextMenu;
|
|
||||||
contextMenu.onclick = hideContextMenu;
|
|
||||||
});
|
|
||||||
|
|
||||||
function showContextMenu(e: PointerEvent) {
|
|
||||||
e.preventDefault();
|
|
||||||
|
|
||||||
console.log('im called');
|
|
||||||
|
|
||||||
contextMenu.style.display = 'block';
|
|
||||||
contextMenu.style.top = e.pageY.toString() + 'px';
|
|
||||||
contextMenu.style.left = e.pageX.toString() + 'px';
|
|
||||||
}
|
|
||||||
|
|
||||||
function hideContextMenu() {
|
|
||||||
contextMenu.style.display = 'none';
|
|
||||||
}
|
|
||||||
</script>
|
|
||||||
|
|
||||||
<div bind:this={contextMenu} class=" bg-surface-3 absolute z-200 hidden rounded-md p-2">
|
|
||||||
<ul>
|
|
||||||
{#each callbacks as item}
|
|
||||||
<li class=" border-b-px border-text-primary">
|
|
||||||
<button aria-label={item.title} onclick={(e) => item.fn(e)}>{item.title}</button>
|
|
||||||
</li>
|
|
||||||
{/each}
|
|
||||||
</ul>
|
|
||||||
</div>
|
|
||||||
@@ -1,423 +0,0 @@
|
|||||||
<script lang="ts">
|
|
||||||
import { onMount } from 'svelte';
|
|
||||||
|
|
||||||
let {
|
|
||||||
children,
|
|
||||||
value = $bindable(''),
|
|
||||||
cursorPrompt = '$',
|
|
||||||
blinkDelay = 250,
|
|
||||||
autofocus = true,
|
|
||||||
oninput = () => {},
|
|
||||||
onsubmit = () => {}
|
|
||||||
}: {
|
|
||||||
children: any;
|
|
||||||
value?: string;
|
|
||||||
cursorPrompt?: string;
|
|
||||||
blinkDelay?: number;
|
|
||||||
autofocus?: boolean;
|
|
||||||
oninput?: (value: string) => void;
|
|
||||||
onsubmit?: (value: string) => void;
|
|
||||||
} = $props();
|
|
||||||
|
|
||||||
let container: HTMLElement;
|
|
||||||
let textField: HTMLElement;
|
|
||||||
let cursor: HTMLElement;
|
|
||||||
let cursorPos: number = $state(value.length);
|
|
||||||
let anchorPos: number | null = $state(null);
|
|
||||||
let isDragging: boolean = $state(false);
|
|
||||||
let focused: boolean = $state(false);
|
|
||||||
let blinkPaused: boolean = $state(false);
|
|
||||||
let blinkTimer: ReturnType<typeof setTimeout> | null = null;
|
|
||||||
|
|
||||||
const mods: Record<string, (e: KeyboardEvent) => void> = {
|
|
||||||
a: () => {
|
|
||||||
anchorPos = 0;
|
|
||||||
cursorPos = value.length;
|
|
||||||
pauseBlink();
|
|
||||||
},
|
|
||||||
c: () => copySelection(),
|
|
||||||
x: () => cutSelection(),
|
|
||||||
e: () => {
|
|
||||||
anchorPos = null;
|
|
||||||
cursorPos = value.length;
|
|
||||||
pauseBlink();
|
|
||||||
},
|
|
||||||
d: () => deleteCharAfter()
|
|
||||||
};
|
|
||||||
const base: Record<string, (e: KeyboardEvent) => void> = {
|
|
||||||
Home: (e) => moveTo(0, e.shiftKey),
|
|
||||||
End: (e) => moveTo(value.length, e.shiftKey),
|
|
||||||
ArrowLeft: (e) =>
|
|
||||||
e.ctrlKey ? moveTo(prevWordBoundary(cursorPos), e.shiftKey) : moveCursor(-1, e.shiftKey),
|
|
||||||
ArrowRight: (e) =>
|
|
||||||
e.ctrlKey ? moveTo(nextWordBoundary(cursorPos), e.shiftKey) : moveCursor(1, e.shiftKey),
|
|
||||||
Backspace: () => deleteCharBefore(),
|
|
||||||
Delete: () => deleteCharAfter(),
|
|
||||||
Enter: () => submit()
|
|
||||||
};
|
|
||||||
|
|
||||||
let selection = $derived.by(() => {
|
|
||||||
if (anchorPos === null || anchorPos === cursorPos) {
|
|
||||||
return { active: false, start: -1, end: -1 };
|
|
||||||
}
|
|
||||||
return {
|
|
||||||
active: true,
|
|
||||||
start: Math.min(anchorPos, cursorPos),
|
|
||||||
end: Math.max(anchorPos, cursorPos)
|
|
||||||
};
|
|
||||||
});
|
|
||||||
|
|
||||||
function isSelected(i: number): boolean {
|
|
||||||
return selection.active && i >= selection.start && i < selection.end;
|
|
||||||
}
|
|
||||||
|
|
||||||
function submit(): void {
|
|
||||||
onsubmit?.(value);
|
|
||||||
cursorPos = 0;
|
|
||||||
anchorPos = null;
|
|
||||||
}
|
|
||||||
|
|
||||||
function gust(): void {
|
|
||||||
if (!container) return;
|
|
||||||
//petals(container, { duration: 4000, swayAmp: 26, hideOriginals: false });
|
|
||||||
value = '';
|
|
||||||
cursorPos = 0;
|
|
||||||
anchorPos = null;
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---- cursor alignment ---------------------------------------------------
|
|
||||||
|
|
||||||
/** Move the caret to the exact pixel where the character at cursorPos lives. */
|
|
||||||
function syncCursor() {
|
|
||||||
if (!textField || !cursor) return;
|
|
||||||
|
|
||||||
/* const containerRect = container.getBoundingClientRect();
|
|
||||||
if (containerRect.width === 0) return;
|
|
||||||
|
|
||||||
const chars = container.querySelectorAll<HTMLElement>('.char');
|
|
||||||
// With the placeholder, chars is never empty — but guard anyway.
|
|
||||||
if (chars.length === 0) return; */
|
|
||||||
|
|
||||||
const containerRect = textField.getBoundingClientRect();
|
|
||||||
const chars = textField.querySelectorAll<HTMLElement>('.char');
|
|
||||||
|
|
||||||
if (chars.length === 0) {
|
|
||||||
cursor.style.transform = `translateX(0px)`;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
let refRect: DOMRect;
|
|
||||||
let x: number;
|
|
||||||
|
|
||||||
if (cursorPos >= chars.length) {
|
|
||||||
refRect = chars[chars.length - 1].getBoundingClientRect();
|
|
||||||
x = refRect.right - containerRect.left;
|
|
||||||
} else {
|
|
||||||
refRect = chars[cursorPos].getBoundingClientRect();
|
|
||||||
x = refRect.left - containerRect.left;
|
|
||||||
if (chars[cursorPos].classList.contains('selected')) {
|
|
||||||
cursor.style.backgroundColor = 'var(--color-bg-hard)';
|
|
||||||
} else {
|
|
||||||
cursor.style.backgroundColor = 'var(--color-fg1)';
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
cursor.style.transform = `translateX(${x}px)`;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Re-sync after every value / cursor movement (runs after DOM update).
|
|
||||||
$effect(() => {
|
|
||||||
void value;
|
|
||||||
void cursorPos;
|
|
||||||
syncCursor();
|
|
||||||
});
|
|
||||||
|
|
||||||
// Re-sync on webfont load and on resize (font metrics can change).
|
|
||||||
$effect(() => {
|
|
||||||
if (!container) return;
|
|
||||||
const ro = new ResizeObserver(() => syncCursor());
|
|
||||||
ro.observe(container);
|
|
||||||
document.fonts?.ready.then(() => syncCursor());
|
|
||||||
return () => ro.disconnect();
|
|
||||||
});
|
|
||||||
|
|
||||||
$effect(() => {
|
|
||||||
if (autofocus && container) {
|
|
||||||
container.focus();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
$effect(() => {
|
|
||||||
return () => {
|
|
||||||
if (blinkTimer) {
|
|
||||||
clearTimeout(blinkTimer);
|
|
||||||
blinkTimer = null;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
});
|
|
||||||
|
|
||||||
$effect(() => {
|
|
||||||
if (cursorPos > value.length) cursorPos = value.length;
|
|
||||||
});
|
|
||||||
|
|
||||||
// Global mousemove / mouseup during drag.
|
|
||||||
$effect(() => {
|
|
||||||
if (!isDragging) return;
|
|
||||||
|
|
||||||
const onMove = (e: MouseEvent) => {
|
|
||||||
const index = charIndexFromEvent(e);
|
|
||||||
if (index === null) return;
|
|
||||||
cursorPos = index;
|
|
||||||
pauseBlink();
|
|
||||||
};
|
|
||||||
|
|
||||||
window.addEventListener('mousemove', onMove);
|
|
||||||
window.addEventListener('mouseup', () => (isDragging = false));
|
|
||||||
return () => {
|
|
||||||
window.removeEventListener('mousemove', onMove);
|
|
||||||
window.removeEventListener('mouseup', () => (isDragging = false));
|
|
||||||
};
|
|
||||||
});
|
|
||||||
|
|
||||||
export function focusInput(): void {
|
|
||||||
container?.focus();
|
|
||||||
}
|
|
||||||
|
|
||||||
function pauseBlink() {
|
|
||||||
blinkPaused = true;
|
|
||||||
if (blinkTimer) clearTimeout(blinkTimer);
|
|
||||||
blinkTimer = setTimeout(() => {
|
|
||||||
blinkPaused = false;
|
|
||||||
blinkTimer = null;
|
|
||||||
}, blinkDelay);
|
|
||||||
}
|
|
||||||
|
|
||||||
function handleFocus() {
|
|
||||||
focused = true;
|
|
||||||
blinkPaused = false;
|
|
||||||
}
|
|
||||||
|
|
||||||
function handleBlur() {
|
|
||||||
focused = false;
|
|
||||||
if (blinkTimer) {
|
|
||||||
clearTimeout(blinkTimer);
|
|
||||||
blinkTimer = null;
|
|
||||||
}
|
|
||||||
blinkPaused = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
function charIndexFromEvent(e: MouseEvent): number | null {
|
|
||||||
const elem = (e.target as HTMLElement | null)?.closest?.(
|
|
||||||
'[data-char-index]'
|
|
||||||
) as HTMLElement | null;
|
|
||||||
if (!elem) return null;
|
|
||||||
const raw = elem.getAttribute('data-char-index');
|
|
||||||
return raw === null ? null : Number(raw);
|
|
||||||
}
|
|
||||||
|
|
||||||
function getSelectedText(): string {
|
|
||||||
if (!selection.active) return '';
|
|
||||||
return value.slice(selection.start, selection.end);
|
|
||||||
}
|
|
||||||
|
|
||||||
function deleteSelection(): void {
|
|
||||||
if (!selection.active) return;
|
|
||||||
value = value.slice(0, selection.start) + value.slice(selection.end);
|
|
||||||
cursorPos = selection.start;
|
|
||||||
anchorPos = null;
|
|
||||||
oninput(value);
|
|
||||||
}
|
|
||||||
|
|
||||||
function insertChar(char: string): void {
|
|
||||||
if (selection.active) {
|
|
||||||
value = value.slice(0, selection.start) + char + value.slice(selection.end);
|
|
||||||
cursorPos = selection.start + char.length;
|
|
||||||
anchorPos = null;
|
|
||||||
} else {
|
|
||||||
value = value.slice(0, cursorPos) + char + value.slice(cursorPos);
|
|
||||||
cursorPos += char.length;
|
|
||||||
}
|
|
||||||
oninput(value);
|
|
||||||
pauseBlink();
|
|
||||||
}
|
|
||||||
|
|
||||||
function deleteCharBefore() {
|
|
||||||
if (selection.active) {
|
|
||||||
deleteSelection();
|
|
||||||
pauseBlink();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (cursorPos > 0) {
|
|
||||||
value = value.slice(0, cursorPos - 1) + value.slice(cursorPos);
|
|
||||||
oninput(value);
|
|
||||||
cursorPos--;
|
|
||||||
pauseBlink();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function deleteCharAfter() {
|
|
||||||
if (selection.active) {
|
|
||||||
deleteSelection();
|
|
||||||
pauseBlink();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (cursorPos < value.length) {
|
|
||||||
value = value.slice(0, cursorPos) + value.slice(cursorPos + 1);
|
|
||||||
oninput(value);
|
|
||||||
pauseBlink();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function moveCursor(delta: number, extend: boolean) {
|
|
||||||
const newPos = cursorPos + delta;
|
|
||||||
if (newPos < 0 || newPos > value.length) return;
|
|
||||||
if (extend) {
|
|
||||||
if (anchorPos === null) anchorPos = cursorPos;
|
|
||||||
} else {
|
|
||||||
anchorPos = null;
|
|
||||||
}
|
|
||||||
cursorPos = newPos;
|
|
||||||
pauseBlink();
|
|
||||||
}
|
|
||||||
|
|
||||||
function moveTo(pos: number, extend: boolean) {
|
|
||||||
if (extend) {
|
|
||||||
if (anchorPos === null) anchorPos = cursorPos;
|
|
||||||
} else {
|
|
||||||
anchorPos = null;
|
|
||||||
}
|
|
||||||
cursorPos = pos;
|
|
||||||
pauseBlink();
|
|
||||||
}
|
|
||||||
|
|
||||||
function prevWordBoundary(pos: number): number {
|
|
||||||
let i = pos;
|
|
||||||
while (i > 0 && !/\s/.test(value[i - 1])) i--;
|
|
||||||
while (i > 0 && /\s/.test(value[i - 1])) i--;
|
|
||||||
return i;
|
|
||||||
}
|
|
||||||
|
|
||||||
function nextWordBoundary(pos: number): number {
|
|
||||||
let i = pos;
|
|
||||||
while (i < value.length && !/\s/.test(value[i])) i++;
|
|
||||||
while (i < value.length && /\s/.test(value[i])) i++;
|
|
||||||
return i;
|
|
||||||
}
|
|
||||||
|
|
||||||
function handleMouseDown(e: MouseEvent): void {
|
|
||||||
e.preventDefault();
|
|
||||||
container?.focus();
|
|
||||||
const idx = charIndexFromEvent(e);
|
|
||||||
const clickPos = idx ?? value.length;
|
|
||||||
|
|
||||||
if (e.shiftKey) {
|
|
||||||
if (anchorPos === null) anchorPos = cursorPos;
|
|
||||||
cursorPos = clickPos;
|
|
||||||
} else {
|
|
||||||
anchorPos = clickPos;
|
|
||||||
cursorPos = clickPos;
|
|
||||||
}
|
|
||||||
isDragging = true;
|
|
||||||
pauseBlink();
|
|
||||||
}
|
|
||||||
|
|
||||||
function handlePaste(e: ClipboardEvent): void {
|
|
||||||
e.preventDefault();
|
|
||||||
const text = e.clipboardData?.getData('text/plain') ?? '';
|
|
||||||
if (text) insertChar(text);
|
|
||||||
}
|
|
||||||
|
|
||||||
function copySelection(): void {
|
|
||||||
if (!selection.active) return;
|
|
||||||
void navigator.clipboard.writeText(getSelectedText());
|
|
||||||
}
|
|
||||||
|
|
||||||
function cutSelection(): void {
|
|
||||||
if (!selection.active) return;
|
|
||||||
void navigator.clipboard.writeText(getSelectedText());
|
|
||||||
deleteSelection();
|
|
||||||
pauseBlink();
|
|
||||||
}
|
|
||||||
|
|
||||||
function handleKeydown(e: KeyboardEvent) {
|
|
||||||
const isMod = e.ctrlKey || e.metaKey;
|
|
||||||
const key = e.key.length === 1 ? e.key.toLowerCase() : e.key;
|
|
||||||
|
|
||||||
function insertIfChar(e: KeyboardEvent): ((e: KeyboardEvent) => void) | undefined {
|
|
||||||
if (key.length !== 1 || e.altKey || e.metaKey) return undefined;
|
|
||||||
return (e) => insertChar(e.key);
|
|
||||||
}
|
|
||||||
|
|
||||||
const handler = isMod ? mods[key] : (base[key] ?? insertIfChar(e));
|
|
||||||
if (!handler) return;
|
|
||||||
|
|
||||||
e.preventDefault();
|
|
||||||
handler(e);
|
|
||||||
}
|
|
||||||
|
|
||||||
onMount(() => {
|
|
||||||
if (autofocus && container) {
|
|
||||||
container.focus();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
</script>
|
|
||||||
|
|
||||||
<div
|
|
||||||
id="terminal-input"
|
|
||||||
class="relative inline-block font-mono leading-relaxed whitespace-nowrap outline-none select-none"
|
|
||||||
bind:this={container}
|
|
||||||
tabindex="1"
|
|
||||||
role="textbox"
|
|
||||||
aria-label="terminal input"
|
|
||||||
onblur={handleBlur}
|
|
||||||
onfocus={handleFocus}
|
|
||||||
onkeydown={handleKeydown}
|
|
||||||
onpaste={handlePaste}
|
|
||||||
onmousedown={handleMouseDown}
|
|
||||||
>
|
|
||||||
{@render children()}<span
|
|
||||||
bind:this={textField}
|
|
||||||
class="text-fg0 relative inline cursor-text"
|
|
||||||
aria-hidden="true"
|
|
||||||
>
|
|
||||||
{#each value.split('') as char, i}
|
|
||||||
<span
|
|
||||||
class="char h-3 w-[1ch] py-0.5 leading-relaxed whitespace-pre-wrap"
|
|
||||||
class:selected={isSelected(i)}
|
|
||||||
class:text-bg={isSelected(i)}
|
|
||||||
data-char-index={i}>{char}</span
|
|
||||||
>
|
|
||||||
{/each}
|
|
||||||
<div
|
|
||||||
id="curs"
|
|
||||||
bind:this={cursor}
|
|
||||||
class="cursor bg-fg1 absolute bottom-0 left-0 h-px w-[1ch]"
|
|
||||||
class:animate-cursor-blink={!blinkPaused && !selection.active}
|
|
||||||
></div>
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<style>
|
|
||||||
.cursor {
|
|
||||||
transition: all 80ms ease;
|
|
||||||
}
|
|
||||||
.char {
|
|
||||||
transition: all 80ms ease;
|
|
||||||
}
|
|
||||||
|
|
||||||
.char.selected {
|
|
||||||
transition: none;
|
|
||||||
background-color: var(--fg1);
|
|
||||||
border-radius: 2px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.char.selected + .char.selected {
|
|
||||||
border-top-left-radius: 0;
|
|
||||||
border-bottom-left-radius: 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
.char.selected:has(+ .char.selected) {
|
|
||||||
border-top-right-radius: 0;
|
|
||||||
border-bottom-right-radius: 0;
|
|
||||||
}
|
|
||||||
</style>
|
|
||||||
@@ -1,32 +0,0 @@
|
|||||||
<script lang="ts">
|
|
||||||
import { mwin_movable } from '#lib/mwinlib/mwin_controller.svelte.ts';
|
|
||||||
import type { MWinParams } from '#lib/mwinlib/mwin_util.ts';
|
|
||||||
|
|
||||||
let {
|
|
||||||
children,
|
|
||||||
wrapper,
|
|
||||||
mwinoptions,
|
|
||||||
handle = $bindable(),
|
|
||||||
class: className = '',
|
|
||||||
...props
|
|
||||||
}: {
|
|
||||||
wrapper?: HTMLElement | string;
|
|
||||||
children?: any;
|
|
||||||
mwinoptions: Partial<MWinParams>;
|
|
||||||
handle?: HTMLElement | string;
|
|
||||||
class?: string;
|
|
||||||
[x: string]: any;
|
|
||||||
} = $props();
|
|
||||||
</script>
|
|
||||||
|
|
||||||
<div
|
|
||||||
{...props}
|
|
||||||
class=" transition-discrete will-change-auto {className}"
|
|
||||||
use:mwin_movable={{
|
|
||||||
wrapper,
|
|
||||||
handle,
|
|
||||||
...mwinoptions
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
{@render children()}
|
|
||||||
</div>
|
|
||||||
@@ -1,195 +0,0 @@
|
|||||||
<script lang="ts">
|
|
||||||
let {
|
|
||||||
username = $bindable(),
|
|
||||||
theme = $bindable(),
|
|
||||||
windowCount = $bindable(),
|
|
||||||
windowTitle = $bindable(),
|
|
||||||
version,
|
|
||||||
hash,
|
|
||||||
add
|
|
||||||
}: {
|
|
||||||
username: string;
|
|
||||||
theme: string;
|
|
||||||
windowCount: number;
|
|
||||||
windowTitle: string;
|
|
||||||
version: string;
|
|
||||||
hash: string;
|
|
||||||
add: () => void;
|
|
||||||
} = $props();
|
|
||||||
|
|
||||||
let now = $state(new Date());
|
|
||||||
let init = new Date().getTime();
|
|
||||||
|
|
||||||
function formatUptime(ms: number): string {
|
|
||||||
const totalSec = Math.floor(ms / 1000);
|
|
||||||
const d = Math.floor(totalSec / 86400);
|
|
||||||
const h = Math.floor((totalSec % 86400) / 3600);
|
|
||||||
const m = Math.floor((totalSec % 3600) / 60);
|
|
||||||
const s = totalSec % 60;
|
|
||||||
const pad = (n: number) => String(n).padStart(2, '0');
|
|
||||||
return d > 0 ? `${d}d ${h}:${pad(m)}:${pad(s)}` : `${h}:${pad(m)}:${pad(s)}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
$effect(() => {
|
|
||||||
const id = setInterval(() => (now = new Date()), 1000);
|
|
||||||
return () => clearInterval(id);
|
|
||||||
});
|
|
||||||
|
|
||||||
const weekday = $derived(now.toLocaleDateString('en-US', { weekday: 'short' }));
|
|
||||||
const time = $derived(
|
|
||||||
`${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}`
|
|
||||||
);
|
|
||||||
const uptime = $derived(`up ${formatUptime(now.getTime() - init)}`);
|
|
||||||
</script>
|
|
||||||
|
|
||||||
{#snippet sep(cls: string = '')}
|
|
||||||
<span
|
|
||||||
aria-hidden="true"
|
|
||||||
class="text-fg3 text-[9px] select-none {cls}"
|
|
||||||
style="font-family:ui-monospace,monospace">·</span
|
|
||||||
>
|
|
||||||
{/snippet}
|
|
||||||
|
|
||||||
{#snippet shortcut(keys: string, label: string)}
|
|
||||||
<span class="text-bg4 inline-flex items-center gap-0.75 whitespace-nowrap">
|
|
||||||
<kbd
|
|
||||||
class="border-bg1 text-fg2 inline-flex h-3.25 min-w-3.25 items-center justify-center rounded-[3px] border bg-black/25 px-1 text-[8.5px] leading-none font-medium"
|
|
||||||
>{keys}</kbd
|
|
||||||
>
|
|
||||||
<span class="text-fg4">{label}</span>
|
|
||||||
</span>
|
|
||||||
{/snippet}
|
|
||||||
|
|
||||||
<div
|
|
||||||
class="bg-bg-soft text-fg3 border-bg3 font-system grid w-full grid-cols-[auto_1fr_auto] gap-x-3 rounded-b-lg border-t text-[11px] shadow-[inset_0_1px_0_rgba(255,255,255,0.04),0_-2px_0_0_rgba(0,0,0,0.1),0_-6px_20px_-4px_rgba(0,0,0,0.5)]"
|
|
||||||
>
|
|
||||||
<div
|
|
||||||
class="col-span-full grid h-[22px] grid-cols-subgrid items-center px-[18px] shadow-[inset_0_-1px_0_var(--color-bg2)]"
|
|
||||||
>
|
|
||||||
<div class="flex items-center gap-1.5 justify-self-start">
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
class="group hover:bg-bg1 -ml-1 flex h-[18px] items-center rounded px-1"
|
|
||||||
aria-haspopup="menu"
|
|
||||||
aria-expanded="false"
|
|
||||||
>
|
|
||||||
<span class="text-fg3 group-hover:text-fg2 text-[10.5px] font-medium whitespace-nowrap"
|
|
||||||
>{username}</span
|
|
||||||
>
|
|
||||||
</button>
|
|
||||||
{@render sep()}
|
|
||||||
<span class="text-bg4 px-[3.5px] font-mono text-[9.5px] whitespace-nowrap">{uptime}</span>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
aria-label="New session"
|
|
||||||
onclick={() => add()}
|
|
||||||
class="text-fg3 hover:bg-bg1 hover:text-fg2 active:bg-bg2 focus-visible:ring-tyellow grid h-[18px] w-[18px] place-items-center justify-self-center rounded transition-colors focus:outline-none focus-visible:ring-1"
|
|
||||||
>
|
|
||||||
<svg
|
|
||||||
viewBox="0 0 16 16"
|
|
||||||
class="h-[10px] w-[10px]"
|
|
||||||
fill="none"
|
|
||||||
stroke="currentColor"
|
|
||||||
stroke-width="1.8"
|
|
||||||
stroke-linecap="round"
|
|
||||||
>
|
|
||||||
<path d="M8 3.5v9M3.5 8h9" />
|
|
||||||
</svg>
|
|
||||||
</button>
|
|
||||||
|
|
||||||
<time class="text-bg4 justify-self-end font-mono text-[9.5px] whitespace-nowrap">
|
|
||||||
<span class="text-fg3 pr-2 font-medium">{weekday}</span><span>{time}</span>
|
|
||||||
</time>
|
|
||||||
</div>
|
|
||||||
<div
|
|
||||||
class="col-span-full grid h-[22px] grid-cols-subgrid items-center rounded-b-lg px-[18px] font-mono text-[9.5px] whitespace-nowrap"
|
|
||||||
>
|
|
||||||
<div class="flex items-center gap-1.5 justify-self-start">
|
|
||||||
<span class="text-fg3">
|
|
||||||
<span class="text-bg4">[</span><span class="font-medium">{windowCount.toString()}</span
|
|
||||||
><span class="text-bg4">]</span>
|
|
||||||
</span>
|
|
||||||
{@render sep()}
|
|
||||||
<span class="text-fg3">{windowTitle}</span>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<span></span>
|
|
||||||
|
|
||||||
<span class="flex items-center gap-1.5 justify-self-end">
|
|
||||||
<span class="text-fg3">{version}</span>
|
|
||||||
{@render sep()}
|
|
||||||
<span class="text-bg4">{hash}</span>
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<!-- <div
|
|
||||||
class="bg-bg-soft text-fg3 border-bg3 grid w-full zoom-115 grid-cols-[auto_1fr_auto_auto_auto] gap-x-2 overflow-hidden rounded-b-lg border-t text-[11px]"
|
|
||||||
style="font-family:-apple-system,BlinkMacSystemFont,system-ui,sans-serif; box-shadow: inset 0 1px 0 rgba(255,255,255,0.04), 0 -2px 0 0 rgba(0,0,0,0.1), 0 -6px 20px -4px rgba(0,0,0,0.5), 0 -16px 40px -12px rgba(0,0,0,0.65);"
|
|
||||||
role="region"
|
|
||||||
aria-label="System status bar"
|
|
||||||
>
|
|
||||||
<div
|
|
||||||
class="col-span-full grid h-[22px] grid-cols-subgrid items-center px-4.5 shadow-[inset_0_-1px_0_var(--bg2)]"
|
|
||||||
>
|
|
||||||
<div class="flex items-center gap-2 justify-self-end">
|
|
||||||
<span aria-hidden="true" class="bg-tgreen h-1.25 w-1.25 shrink-0 rounded-full"></span>
|
|
||||||
<span class="text-fg3 text-[10.5px] font-medium whitespace-nowrap">{username}</span>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="flex min-w-0 items-center gap-2">
|
|
||||||
{@render sep()}
|
|
||||||
<span
|
|
||||||
class="text-fg3 hover:text-fg2 cursor-pointer text-[9.5px] whitespace-nowrap"
|
|
||||||
style="font-family:ui-monospace,monospace"
|
|
||||||
title="switch theme">{theme}</span
|
|
||||||
>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
aria-label="Settings"
|
|
||||||
class="text-bg4 flex h-5 w-5 shrink-0 items-center justify-center justify-self-end rounded border-0 bg-transparent p-0 text-[12px]"
|
|
||||||
>
|
|
||||||
<Cog color={'var(--fg1)'} size={8} />
|
|
||||||
</button>
|
|
||||||
|
|
||||||
{@render sep('justify-self-center')}
|
|
||||||
|
|
||||||
<time
|
|
||||||
datetime={now.toISOString()}
|
|
||||||
class="text-bg4 justify-self-start text-[9.5px] whitespace-nowrap"
|
|
||||||
style="font-family:ui-monospace,monospace"
|
|
||||||
>
|
|
||||||
<span class="text-fg4 font-medium">{weekday}</span>
|
|
||||||
{time}
|
|
||||||
</time>
|
|
||||||
</div>
|
|
||||||
<div
|
|
||||||
class="col-span-full grid h-[22px] grid-cols-subgrid items-center rounded-b-lg px-4.5 text-[9.5px] whitespace-nowrap"
|
|
||||||
style="font-family:ui-monospace,monospace"
|
|
||||||
>
|
|
||||||
<span class="text-fg3 justify-self-end whitespace-nowrap"
|
|
||||||
><span class="font-medium">{windowCount}</span> window{windowCount === 1 ? '' : 's'}</span
|
|
||||||
>
|
|
||||||
|
|
||||||
<div class="flex min-w-0 items-center gap-2">
|
|
||||||
{@render sep()}
|
|
||||||
{@render shortcut('⌘N', 'new terminal')}
|
|
||||||
{@render sep()}
|
|
||||||
{@render shortcut('⌘,', 'settings')}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<span class="inline-flex items-center gap-1.25 justify-self-end">
|
|
||||||
<span class="text-fg3">{version}</span>
|
|
||||||
{@render sep()}
|
|
||||||
<span class="text-bg4">{hash}</span>
|
|
||||||
</span>
|
|
||||||
|
|
||||||
{@render sep('justify-self-center')}
|
|
||||||
|
|
||||||
<span class="text-bg4 justify-self-start">{uptime}</span>
|
|
||||||
</div>
|
|
||||||
</div> -->
|
|
||||||
@@ -1,140 +0,0 @@
|
|||||||
<script lang="ts">
|
|
||||||
import { type MWinAPI, type MWinParams } from '#lib/mwinlib/mwin_util.ts';
|
|
||||||
import { resolvePointerToHome, type Shell } from 'termos';
|
|
||||||
import Input from './Input.svelte';
|
|
||||||
import Movable from './Movable.svelte';
|
|
||||||
|
|
||||||
let {
|
|
||||||
id,
|
|
||||||
wrapper,
|
|
||||||
username = $bindable(),
|
|
||||||
hostname = $bindable(),
|
|
||||||
working_dir = $bindable(),
|
|
||||||
mwin = $bindable(),
|
|
||||||
shell = $bindable(),
|
|
||||||
|
|
||||||
close
|
|
||||||
}: {
|
|
||||||
id: number;
|
|
||||||
wrapper: HTMLElement | string;
|
|
||||||
username: string;
|
|
||||||
hostname: string;
|
|
||||||
working_dir: string;
|
|
||||||
mwin: MWinAPI | undefined;
|
|
||||||
shell: Shell | undefined;
|
|
||||||
close?: (id: number) => void;
|
|
||||||
} = $props();
|
|
||||||
|
|
||||||
//let isProcessActive = $state(false);
|
|
||||||
const d = new TextDecoder('utf-8');
|
|
||||||
|
|
||||||
let inputValue = $state('');
|
|
||||||
let inputComponent: any;
|
|
||||||
let outputWrapper: HTMLElement;
|
|
||||||
let scrollDiv: HTMLElement;
|
|
||||||
let stdout: string = '';
|
|
||||||
let count: [string, string, string][] = $state([]);
|
|
||||||
let pwd: string = working_dir;
|
|
||||||
|
|
||||||
const mwinoptions: Partial<MWinParams> = {
|
|
||||||
handle: '#terminal-bar',
|
|
||||||
resizable: { threshold: 10, minWidth: 300, minHeight: 200 },
|
|
||||||
baseZIndex: 300,
|
|
||||||
onAPI: (api: MWinAPI) => {
|
|
||||||
mwin = api;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
async function onsubmit(value: string) {
|
|
||||||
const input = value.trim();
|
|
||||||
await shell!.execute(input);
|
|
||||||
pwd = resolvePointerToHome(shell!.State, shell!.Session.cwd);
|
|
||||||
}
|
|
||||||
|
|
||||||
$effect(() => {
|
|
||||||
shell!.on('stdout', (payload) => {
|
|
||||||
const decoded = d.decode(payload.data);
|
|
||||||
stdout = stdout + decoded;
|
|
||||||
});
|
|
||||||
|
|
||||||
shell!.on('result', (payload) => {
|
|
||||||
if (payload.result.type === 'error') {
|
|
||||||
stdout = stdout + payload.result.error.message + '\n';
|
|
||||||
}
|
|
||||||
working_dir = resolvePointerToHome(shell!.State, shell!.Session.cwd);
|
|
||||||
count.push([inputValue, pwd, stdout]);
|
|
||||||
stdout = '';
|
|
||||||
inputValue = '';
|
|
||||||
});
|
|
||||||
});
|
|
||||||
</script>
|
|
||||||
|
|
||||||
{#snippet Out(value: string, path: string, stdout: string)}
|
|
||||||
<span
|
|
||||||
><span class=" scroll-line text-tyellow">{username}</span><span>@</span><span class=" text-fg1"
|
|
||||||
>{hostname}</span
|
|
||||||
>
|
|
||||||
<span class="text-bg4">{path}</span><br /></span
|
|
||||||
>
|
|
||||||
<span class=" scroll-line mr-[1ch]">$</span><span>{value}</span>
|
|
||||||
<div class=" whitespace-pre-wrap">{stdout}</div>
|
|
||||||
{/snippet}
|
|
||||||
|
|
||||||
<Movable
|
|
||||||
{wrapper}
|
|
||||||
{mwinoptions}
|
|
||||||
class="shadow-subtle bg-bg-hard flex size-full h-128 w-210 flex-col rounded-lg"
|
|
||||||
>
|
|
||||||
<div
|
|
||||||
id="terminal-bar"
|
|
||||||
class=" bg-bg-soft grid grid-cols-[1fr_auto_1fr] rounded-t-md py-1 select-none"
|
|
||||||
>
|
|
||||||
<div class="dots-wrapper m-auto mx-3 flex size-max flex-row items-center justify-center gap-2">
|
|
||||||
<button
|
|
||||||
data-close-btn
|
|
||||||
class="bg-tl-red h-2.5 w-2.5 cursor-pointer rounded-full active:brightness-85"
|
|
||||||
type="button"
|
|
||||||
aria-label="Close terminal"
|
|
||||||
onclick={() => close?.(id)}
|
|
||||||
></button>
|
|
||||||
<button
|
|
||||||
class="bg-tl-yellow h-2.5 w-2.5 cursor-pointer rounded-full active:brightness-85"
|
|
||||||
type="button"
|
|
||||||
aria-label="Maximize terminal"
|
|
||||||
onclick={() => mwin?.maximize()}
|
|
||||||
></button>
|
|
||||||
<button
|
|
||||||
class="bg-tl-green h-2.5 w-2.5 cursor-pointer rounded-2xl active:brightness-85"
|
|
||||||
type="button"
|
|
||||||
aria-label="Minimize terminal"
|
|
||||||
></button>
|
|
||||||
</div>
|
|
||||||
<span class=" text-fg2 mx-auto text-sm font-medium">{username} — tsh</span>
|
|
||||||
<span></span>
|
|
||||||
</div>
|
|
||||||
<div
|
|
||||||
class="inner-content scroll-hidden text-fg4 font-ibm grow origin-top overflow-y-auto p-4 text-sm"
|
|
||||||
bind:this={scrollDiv}
|
|
||||||
id="cout"
|
|
||||||
onclick={() => inputComponent?.focusInput()}
|
|
||||||
onkeydown={() => inputComponent?.focusInput()}
|
|
||||||
role="textbox"
|
|
||||||
tabindex="-1"
|
|
||||||
>
|
|
||||||
<div bind:this={outputWrapper} class="">
|
|
||||||
{#each count as c}
|
|
||||||
{@render Out(c[0], c[1], c[2])}
|
|
||||||
<div class="mb-3"></div>
|
|
||||||
{/each}
|
|
||||||
</div>
|
|
||||||
<span
|
|
||||||
><span class=" text-tyellow">{shell!.Session.user.username}</span><span>@</span><span
|
|
||||||
class=" text-fg1">{hostname}</span
|
|
||||||
>
|
|
||||||
<span class="text-bg4">{working_dir}</span><br /></span
|
|
||||||
>
|
|
||||||
<Input bind:value={inputValue} blinkDelay={500} {onsubmit} bind:this={inputComponent}
|
|
||||||
><span class="font-ibm mr-[1ch]">$</span></Input
|
|
||||||
>
|
|
||||||
</div>
|
|
||||||
</Movable>
|
|
||||||
@@ -1,69 +0,0 @@
|
|||||||
<script lang="ts">
|
|
||||||
import { removeToast, toasts } from '#lib/stores/toasts.ts';
|
|
||||||
import { CircleCheckBig, CircleX, Info, TriangleAlert, X } from '@lucide/svelte';
|
|
||||||
import { onMount } from 'svelte';
|
|
||||||
import { fly } from 'svelte/transition';
|
|
||||||
|
|
||||||
onMount(() => {
|
|
||||||
toasts.set([]);
|
|
||||||
});
|
|
||||||
</script>
|
|
||||||
|
|
||||||
<div class="fixed top-4 right-4 z-50 flex h-full flex-col gap-2 overflow-visible">
|
|
||||||
{#each $toasts as toast (toast.id)}
|
|
||||||
<div
|
|
||||||
transition:fly={{ x: 20, y: 0, duration: 300 }}
|
|
||||||
id={`toast-${toast.id.toString()}`}
|
|
||||||
class="bg-surface-2 w-md overflow-hidden rounded-md"
|
|
||||||
onclick={() => toast.onClick?.(toast)}
|
|
||||||
role="button"
|
|
||||||
tabindex={toast.onClick ? 0 : undefined}
|
|
||||||
onkeydown={toast.onClick
|
|
||||||
? (e) => {
|
|
||||||
if (e.key === 'Enter' || e.key === ' ') {
|
|
||||||
e.preventDefault();
|
|
||||||
toast.onClick?.(toast);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
: undefined}
|
|
||||||
>
|
|
||||||
<div class="flex items-center justify-start">
|
|
||||||
<div class="mx-4 my-8">
|
|
||||||
{#if toast.type === 'info'}
|
|
||||||
<Info class=" text-info"></Info>
|
|
||||||
{:else if toast.type === 'error'}
|
|
||||||
<CircleX class="text-error"></CircleX>
|
|
||||||
{:else if toast.type === 'warn'}
|
|
||||||
<TriangleAlert class="text-warning"></TriangleAlert>
|
|
||||||
{:else}
|
|
||||||
<CircleCheckBig class="text-success"></CircleCheckBig>
|
|
||||||
{/if}
|
|
||||||
</div>
|
|
||||||
<div class="my-2 mr-auto mb-auto ml-2 flex flex-col items-start justify-start select-none">
|
|
||||||
<h5 class=" text- text-md text-text-primary font-bold">{toast.title}</h5>
|
|
||||||
<p class=" text-md text-text-secondary mb-2 overflow-x-hidden overflow-y-scroll">
|
|
||||||
{toast.message}
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
<div class=" m-2 self-start">
|
|
||||||
<button
|
|
||||||
class:hidden={toast.hideDismiss}
|
|
||||||
onclick={(e) => {
|
|
||||||
e.stopPropagation();
|
|
||||||
removeToast(toast.id);
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<X
|
|
||||||
stroke-width={3}
|
|
||||||
size={18}
|
|
||||||
class=" hover:text-text-secondary transition-all duration-200 active:scale-90"
|
|
||||||
></X>
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
{#if !toast.hideProgress && toast.tween}
|
|
||||||
<div style:padding-right={`${toast.tween.current}%`} class=" bg-primary h-[2px] w-0"></div>
|
|
||||||
{/if}
|
|
||||||
</div>
|
|
||||||
{/each}
|
|
||||||
</div>
|
|
||||||
@@ -1,27 +0,0 @@
|
|||||||
<script lang="ts">
|
|
||||||
let state = $state(false);
|
|
||||||
|
|
||||||
export function focus() {
|
|
||||||
console.log('called');
|
|
||||||
state = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
let { children, onclick }: { children?: any; onclick?: ({}?: unknown) => unknown } = $props();
|
|
||||||
</script>
|
|
||||||
|
|
||||||
<button
|
|
||||||
onclick={() => {
|
|
||||||
onclick?.();
|
|
||||||
console.log('im called');
|
|
||||||
}}
|
|
||||||
class="
|
|
||||||
|
|
||||||
cursor-pointer rounded-full
|
|
||||||
transition-all duration-200 active:translate-y-0.5
|
|
||||||
active:brightness-90 disabled:cursor-not-allowed disabled:opacity-50 disabled:hover:brightness-100
|
|
||||||
"
|
|
||||||
>
|
|
||||||
<div class="">
|
|
||||||
{@render children()}
|
|
||||||
</div>
|
|
||||||
</button>
|
|
||||||
@@ -1,580 +0,0 @@
|
|||||||
import {
|
|
||||||
getWrapperManager,
|
|
||||||
MWIN_MANAGER,
|
|
||||||
resolveElement,
|
|
||||||
type MWinAPI,
|
|
||||||
type MWinNormalizedParams,
|
|
||||||
type MWinParams,
|
|
||||||
type MWinState,
|
|
||||||
type ResizeDirection
|
|
||||||
} from './mwin_util';
|
|
||||||
|
|
||||||
export function mwin_movable(node: HTMLElement, options: Partial<MWinParams>) {
|
|
||||||
const controller = new MWinController(node, options);
|
|
||||||
const api: MWinAPI = {
|
|
||||||
state: controller.state,
|
|
||||||
minimize: () => controller.minimize(),
|
|
||||||
maximize: () => controller.maximize(),
|
|
||||||
close: () => controller.close(),
|
|
||||||
focus: () => controller.focus()
|
|
||||||
};
|
|
||||||
|
|
||||||
options.onAPI?.(api);
|
|
||||||
return {
|
|
||||||
destroy: () => controller.destroy()
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
class MWinController {
|
|
||||||
#rafID: number | null = null;
|
|
||||||
#pendingApply = false;
|
|
||||||
|
|
||||||
#node: HTMLElement;
|
|
||||||
#wrapper: HTMLElement;
|
|
||||||
#opts: MWinNormalizedParams;
|
|
||||||
#savedTransition: string;
|
|
||||||
#savedStyles: string;
|
|
||||||
#wrapperObserver: ResizeObserver | null = null;
|
|
||||||
|
|
||||||
#wrapperWidth: number = 0;
|
|
||||||
#wrapperHeight: number = 0;
|
|
||||||
#wrapperLeft: number = 0;
|
|
||||||
#wrapperTop: number = 0;
|
|
||||||
#wrapperBorderLeft: number = 0;
|
|
||||||
#wrapperBorderTop: number = 0;
|
|
||||||
|
|
||||||
#dragOffsetX: number = 0;
|
|
||||||
#dragOffsetY: number = 0;
|
|
||||||
#resizeDirection: ResizeDirection = null;
|
|
||||||
#resizeStartRect = { x: 0, y: 0, width: 0, height: 0 };
|
|
||||||
#resizeStartPos = { x: 0, y: 0 };
|
|
||||||
#restoreRect: { x: number; y: number; width: number; height: number } | null = null;
|
|
||||||
|
|
||||||
state = $state<MWinState>({
|
|
||||||
x: 0,
|
|
||||||
y: 0,
|
|
||||||
width: 0,
|
|
||||||
height: 0,
|
|
||||||
minimized: false,
|
|
||||||
maximized: false,
|
|
||||||
moving: false,
|
|
||||||
resizing: false,
|
|
||||||
zIndex: 0
|
|
||||||
});
|
|
||||||
|
|
||||||
constructor(node: HTMLElement, options: Partial<MWinParams>) {
|
|
||||||
this.#node = node;
|
|
||||||
|
|
||||||
const wrapper = resolveElement(options.wrapper, node);
|
|
||||||
if (!wrapper) throw new Error('[Movable] - Wrapper element not found!');
|
|
||||||
this.#wrapper = wrapper ?? document;
|
|
||||||
|
|
||||||
const wrapperStyle = getComputedStyle(this.#wrapper);
|
|
||||||
this.#wrapperBorderLeft = parseFloat(wrapperStyle.borderLeftWidth);
|
|
||||||
this.#wrapperBorderTop = parseFloat(wrapperStyle.borderTopWidth);
|
|
||||||
|
|
||||||
const resizableOpts = typeof options.resizable === 'object' ? options.resizable : {};
|
|
||||||
|
|
||||||
this.#opts = {
|
|
||||||
handle: resolveElement(options.handle, node),
|
|
||||||
initX: options.initX,
|
|
||||||
initY: options.initY,
|
|
||||||
initWidth: options.initWidth,
|
|
||||||
initHeight: options.initHeight,
|
|
||||||
baseZIndex: options.baseZIndex ?? 1,
|
|
||||||
resizeHandle: resolveElement(options.resizeHandle, node),
|
|
||||||
resizable: !!options.resizable,
|
|
||||||
threshold: resizableOpts.threshold ?? 8,
|
|
||||||
minWidth: resizableOpts.minWidth ?? 24, //MinWidth should be min-content
|
|
||||||
minHeight: resizableOpts.minHeight ?? 24, //MinHeight should be min-content
|
|
||||||
maxWidth: resizableOpts.maxWidth ?? Infinity,
|
|
||||||
maxHeight: resizableOpts.maxHeight ?? Infinity,
|
|
||||||
onClose: options.onClose,
|
|
||||||
onMinimize: options.onMinimize,
|
|
||||||
onMaximize: options.onMaximize,
|
|
||||||
onFocus: options.onFocus
|
|
||||||
};
|
|
||||||
this.#savedStyles = this.#node.style.cssText;
|
|
||||||
this.#savedTransition = this.#node.style.transition;
|
|
||||||
this.#node.style.transition = 'none';
|
|
||||||
this.#node.style.willChange = 'transform';
|
|
||||||
|
|
||||||
this.#wrapper.style.position = 'relative';
|
|
||||||
this.#node.style.position = 'absolute';
|
|
||||||
|
|
||||||
const wRect = this.#wrapper.getBoundingClientRect();
|
|
||||||
const nRect = this.#node.getBoundingClientRect();
|
|
||||||
|
|
||||||
this.state.x = this.#opts.initX ?? nRect.left - wRect.left;
|
|
||||||
this.state.y = this.#opts.initY ?? nRect.top - wRect.top;
|
|
||||||
this.state.width = this.#opts.initWidth ?? nRect.width;
|
|
||||||
this.state.height = this.#opts.initHeight ?? nRect.height;
|
|
||||||
|
|
||||||
this.#node.style.left = '0';
|
|
||||||
this.#node.style.top = '0';
|
|
||||||
this.#node.classList.add('[Movable]');
|
|
||||||
|
|
||||||
const mgr = getWrapperManager(this.#wrapper);
|
|
||||||
mgr.refCount++;
|
|
||||||
|
|
||||||
if (!node.hasAttribute('tabindex')) {
|
|
||||||
node.setAttribute('tabindex', '0');
|
|
||||||
}
|
|
||||||
|
|
||||||
node.setAttribute('role', 'region');
|
|
||||||
node.setAttribute('aria-label', 'Movable window');
|
|
||||||
|
|
||||||
this.#cacheWrapperRect();
|
|
||||||
|
|
||||||
node.addEventListener('pointerdown', this.#onPointerDown);
|
|
||||||
node.addEventListener('pointermove', this.#updateCursor);
|
|
||||||
node.addEventListener('pointerleave', this.#resetCursor);
|
|
||||||
|
|
||||||
this.#clampAndApply();
|
|
||||||
this.#bringToFront();
|
|
||||||
|
|
||||||
this.#wrapperObserver = new ResizeObserver(() => {
|
|
||||||
this.#wrapperWidth = this.#wrapper.clientWidth;
|
|
||||||
this.#wrapperHeight = this.#wrapper.clientHeight;
|
|
||||||
|
|
||||||
this.#onWrapperResize();
|
|
||||||
});
|
|
||||||
this.#wrapperObserver.observe(this.#wrapper);
|
|
||||||
}
|
|
||||||
|
|
||||||
#cacheWrapperRect() {
|
|
||||||
const wrapperRect = this.#wrapper.getBoundingClientRect();
|
|
||||||
|
|
||||||
this.#wrapperLeft = wrapperRect.left + this.#wrapperBorderLeft;
|
|
||||||
this.#wrapperTop = wrapperRect.top + this.#wrapperBorderTop;
|
|
||||||
this.#wrapperWidth = this.#wrapper.clientWidth;
|
|
||||||
this.#wrapperHeight = this.#wrapper.clientHeight;
|
|
||||||
}
|
|
||||||
|
|
||||||
#bringToFront() {
|
|
||||||
const mgr = getWrapperManager(this.#wrapper);
|
|
||||||
mgr.zCounter++;
|
|
||||||
|
|
||||||
this.#opts.onFocus?.();
|
|
||||||
this.state.zIndex = this.#opts.baseZIndex + mgr.zCounter;
|
|
||||||
this.#node.style.zIndex = String(this.state.zIndex);
|
|
||||||
}
|
|
||||||
|
|
||||||
#clampAndApply() {
|
|
||||||
this.#clampRect();
|
|
||||||
this.#apply();
|
|
||||||
}
|
|
||||||
|
|
||||||
#clampRect() {
|
|
||||||
const bw = this.#wrapperWidth;
|
|
||||||
const bh = this.#wrapperHeight;
|
|
||||||
|
|
||||||
let w = Math.min(this.state.width, bw, this.#opts.maxWidth);
|
|
||||||
w = Math.max(w, this.#opts.minWidth, 0);
|
|
||||||
let h = Math.min(this.state.height, bh, this.#opts.maxHeight);
|
|
||||||
h = Math.max(h, this.#opts.minHeight, 0);
|
|
||||||
|
|
||||||
this.state.width = w;
|
|
||||||
this.state.height = h;
|
|
||||||
|
|
||||||
const maxX = Math.max(0, bw - w);
|
|
||||||
const maxY = Math.max(0, bh - h);
|
|
||||||
this.state.x = Math.min(Math.max(this.state.x, 0), maxX);
|
|
||||||
this.state.y = Math.min(Math.max(this.state.y, 0), maxY);
|
|
||||||
}
|
|
||||||
|
|
||||||
#apply() {
|
|
||||||
this.#node.style.transform = `translate(${this.state.x}px, ${this.state.y}px)`;
|
|
||||||
this.#node.style.setProperty('--x', this.state.x.toString());
|
|
||||||
this.#node.style.setProperty('--y', this.state.y.toString());
|
|
||||||
this.#node.style.setProperty('--w', this.state.width.toString());
|
|
||||||
this.#node.style.setProperty('--h', this.state.height.toString());
|
|
||||||
this.#node.style.width = this.state.width + 'px';
|
|
||||||
this.#node.style.height = this.state.height + 'px';
|
|
||||||
}
|
|
||||||
|
|
||||||
#getCornerDirection(e: PointerEvent): ResizeDirection {
|
|
||||||
if (!this.#opts.resizable) return null;
|
|
||||||
const t = this.#opts.threshold;
|
|
||||||
|
|
||||||
let dirY: string = '';
|
|
||||||
if (e.clientY - this.state.y < t) dirY = 'n';
|
|
||||||
else if (this.state.y + this.state.height - e.clientY < t) dirY = 's';
|
|
||||||
|
|
||||||
let dirX: string = '';
|
|
||||||
if (e.clientX - this.state.x < t) dirX = 'w';
|
|
||||||
else if (this.state.x + this.state.width - e.clientX < t) dirX = 'e';
|
|
||||||
|
|
||||||
if (dirY && dirX) {
|
|
||||||
return (dirY + dirX) as ResizeDirection;
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
#onPointerCancel = () => this.#onPointerUp();
|
|
||||||
|
|
||||||
#onPointerDown = (e: PointerEvent): void => {
|
|
||||||
if (this.#isInteractive(e.target as HTMLElement)) return;
|
|
||||||
if (this.state.minimized) return;
|
|
||||||
|
|
||||||
if (this.state.maximized) {
|
|
||||||
const target = e.target as HTMLElement;
|
|
||||||
const canDrag = this.#opts.handle?.contains(target) || !this.#opts.handle;
|
|
||||||
if (canDrag) this.#unmaximizeAtCursor(e);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (this.#opts.resizeHandle?.contains(e.target as HTMLElement)) {
|
|
||||||
this.#startResize(e, 'se');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const dir = this.#getCornerDirection(e);
|
|
||||||
if (dir) {
|
|
||||||
this.#startResize(e, dir);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (this.#opts.handle?.contains(e.target as HTMLElement)) {
|
|
||||||
this.#startMove(e);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!this.#opts.handle) {
|
|
||||||
this.#startMove(e);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
#startMove(e: PointerEvent, skipOffset = false): void {
|
|
||||||
e.preventDefault();
|
|
||||||
this.#bringToFront();
|
|
||||||
this.state.moving = true;
|
|
||||||
this.#node.style.cursor = 'grabbing';
|
|
||||||
|
|
||||||
this.#cacheWrapperRect();
|
|
||||||
|
|
||||||
if (!skipOffset) {
|
|
||||||
const rect = this.#node.getBoundingClientRect();
|
|
||||||
this.#dragOffsetX = e.clientX - rect.left;
|
|
||||||
this.#dragOffsetY = e.clientY - rect.top;
|
|
||||||
}
|
|
||||||
|
|
||||||
this.#prepareInteraction();
|
|
||||||
}
|
|
||||||
|
|
||||||
#startResize(e: PointerEvent, direction: ResizeDirection): void {
|
|
||||||
e.preventDefault();
|
|
||||||
e.stopPropagation();
|
|
||||||
this.#bringToFront();
|
|
||||||
this.state.resizing = true;
|
|
||||||
|
|
||||||
this.#cacheWrapperRect();
|
|
||||||
|
|
||||||
this.#resizeDirection = direction;
|
|
||||||
this.#resizeStartRect = {
|
|
||||||
x: this.state.x,
|
|
||||||
y: this.state.y,
|
|
||||||
width: this.state.width,
|
|
||||||
height: this.state.height
|
|
||||||
};
|
|
||||||
|
|
||||||
this.#resizeStartPos = { x: e.clientX - this.#wrapperLeft, y: e.clientY - this.#wrapperTop };
|
|
||||||
|
|
||||||
this.#prepareInteraction();
|
|
||||||
}
|
|
||||||
|
|
||||||
#unmaximizeAtCursor(e: PointerEvent): void {
|
|
||||||
this.#cacheWrapperRect();
|
|
||||||
|
|
||||||
const cursorX = e.clientX - this.#wrapperLeft;
|
|
||||||
const cursorY = e.clientY - this.#wrapperTop;
|
|
||||||
|
|
||||||
const fracX = this.#wrapperWidth > 0 ? cursorX / this.#wrapperWidth : 0;
|
|
||||||
const fracY = this.#wrapperHeight > 0 ? cursorY / this.#wrapperHeight : 0;
|
|
||||||
|
|
||||||
if (this.#restoreRect) {
|
|
||||||
this.state.width = this.#restoreRect.width;
|
|
||||||
this.state.height = this.#restoreRect.height;
|
|
||||||
this.state.maximized = false;
|
|
||||||
this.#restoreRect = null;
|
|
||||||
} else {
|
|
||||||
// fallback: no saved rect, just keep current size
|
|
||||||
this.state.maximized = false;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Position so the same relative point stays under the cursor
|
|
||||||
let newX = cursorX - fracX * this.state.width;
|
|
||||||
let newY = cursorY - fracY * this.state.height;
|
|
||||||
|
|
||||||
// Clamp inside the boundary
|
|
||||||
const maxX = Math.max(0, this.#wrapperWidth - this.state.width);
|
|
||||||
const maxY = Math.max(0, this.#wrapperHeight - this.state.height);
|
|
||||||
newX = Math.min(Math.max(newX, 0), maxX);
|
|
||||||
newY = Math.min(Math.max(newY, 0), maxY);
|
|
||||||
|
|
||||||
this.state.x = newX;
|
|
||||||
this.state.y = newY;
|
|
||||||
this.#scheduleApply();
|
|
||||||
|
|
||||||
this.#dragOffsetX = cursorX - newX;
|
|
||||||
this.#dragOffsetY = cursorY - newY;
|
|
||||||
|
|
||||||
this.#bringToFront();
|
|
||||||
this.state.moving = true;
|
|
||||||
this.#node.style.cursor = 'grabbing';
|
|
||||||
this.#prepareInteraction();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
#prepareInteraction(): void {
|
|
||||||
document.body.style.userSelect = 'none';
|
|
||||||
this.#node.style.transition = 'none';
|
|
||||||
this.#node.style.willChange = 'transform, width, height';
|
|
||||||
this.#node.style.touchAction = 'none';
|
|
||||||
|
|
||||||
window.addEventListener('pointermove', this.#onPointerMove, { passive: true });
|
|
||||||
window.addEventListener('pointerup', this.#onPointerUp, { passive: true });
|
|
||||||
window.addEventListener('pointercancel', this.#onPointerCancel, { passive: true });
|
|
||||||
}
|
|
||||||
|
|
||||||
#onPointerMove = (e: PointerEvent): void => {
|
|
||||||
this.#cacheWrapperRect();
|
|
||||||
const events = e.getCoalescedEvents?.() ?? [e];
|
|
||||||
|
|
||||||
for (const event of events) {
|
|
||||||
if (this.state.moving) {
|
|
||||||
this.#updateMove(event);
|
|
||||||
} else if (this.state.resizing) {
|
|
||||||
this.#updateResize(event);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
this.#scheduleApply();
|
|
||||||
};
|
|
||||||
|
|
||||||
#scheduleApply(): void {
|
|
||||||
if (!this.#pendingApply) {
|
|
||||||
this.#pendingApply = true;
|
|
||||||
this.#rafID = requestAnimationFrame(() => {
|
|
||||||
if (!this.state.moving && !this.state.resizing) {
|
|
||||||
this.#node.style.willChange = 'auto';
|
|
||||||
}
|
|
||||||
|
|
||||||
this.#rafID = null;
|
|
||||||
this.#pendingApply = false;
|
|
||||||
this.#apply();
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#updateMove(e: PointerEvent): void {
|
|
||||||
let newX = e.clientX - this.#wrapperLeft - this.#dragOffsetX;
|
|
||||||
let newY = e.clientY - this.#wrapperTop - this.#dragOffsetY;
|
|
||||||
|
|
||||||
newX = Math.max(0, Math.min(newX, this.#wrapperWidth - this.state.width));
|
|
||||||
newY = Math.max(0, Math.min(newY, this.#wrapperHeight - this.state.height));
|
|
||||||
|
|
||||||
this.state.x = newX;
|
|
||||||
this.state.y = newY;
|
|
||||||
}
|
|
||||||
|
|
||||||
#updateResize(e: PointerEvent): void {
|
|
||||||
const dir = this.#resizeDirection!;
|
|
||||||
const start = this.#resizeStartRect;
|
|
||||||
const dx = e.clientX - this.#wrapperLeft - this.#resizeStartPos.x;
|
|
||||||
const dy = e.clientY - this.#wrapperTop - this.#resizeStartPos.y;
|
|
||||||
|
|
||||||
const anchorLeft = dir.includes('e') ? start.x : start.x + start.width;
|
|
||||||
const anchorTop = dir.includes('s') ? start.y : start.y + start.height;
|
|
||||||
|
|
||||||
let movingX = anchorLeft;
|
|
||||||
let movingY = anchorTop;
|
|
||||||
|
|
||||||
if (dir.includes('e')) movingX = start.x + start.width + dx;
|
|
||||||
else movingX = start.x + dx;
|
|
||||||
|
|
||||||
if (dir.includes('s')) movingY = start.y + start.height + dy;
|
|
||||||
else movingY = start.y + dy;
|
|
||||||
|
|
||||||
const minWidth = this.#opts.minWidth;
|
|
||||||
const minHeight = this.#opts.minHeight;
|
|
||||||
const maxWidth = Math.min(this.#opts.maxWidth, this.#wrapperWidth);
|
|
||||||
const maxHeight = Math.min(this.#opts.maxHeight, this.#wrapperHeight);
|
|
||||||
|
|
||||||
if (dir.includes('e')) {
|
|
||||||
movingX = Math.max(anchorLeft + minWidth, Math.min(movingX, anchorLeft + maxWidth));
|
|
||||||
movingX = Math.min(movingX, this.#wrapperWidth);
|
|
||||||
} else {
|
|
||||||
movingX = Math.min(anchorLeft - minWidth, Math.max(movingX, anchorLeft - maxWidth));
|
|
||||||
movingX = Math.max(movingX, 0);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (dir.includes('s')) {
|
|
||||||
movingY = Math.max(anchorTop + minHeight, Math.min(movingY, anchorTop + maxHeight));
|
|
||||||
movingY = Math.min(movingY, this.#wrapperHeight);
|
|
||||||
} else {
|
|
||||||
movingY = Math.min(anchorTop - minHeight, Math.max(movingY, anchorTop - maxHeight));
|
|
||||||
movingY = Math.max(movingY, 0);
|
|
||||||
}
|
|
||||||
|
|
||||||
const newX = Math.min(anchorLeft, movingX);
|
|
||||||
const newY = Math.min(anchorTop, movingY);
|
|
||||||
const newWidth = Math.abs(movingX - anchorLeft);
|
|
||||||
const newHeight = Math.abs(movingY - anchorTop);
|
|
||||||
|
|
||||||
this.state.x = newX;
|
|
||||||
this.state.y = newY;
|
|
||||||
this.state.width = newWidth;
|
|
||||||
this.state.height = newHeight;
|
|
||||||
}
|
|
||||||
|
|
||||||
#onPointerUp = (): void => {
|
|
||||||
if (this.#rafID !== null) {
|
|
||||||
cancelAnimationFrame(this.#rafID);
|
|
||||||
this.#rafID = null;
|
|
||||||
this.#pendingApply = false;
|
|
||||||
}
|
|
||||||
|
|
||||||
this.state.moving = false;
|
|
||||||
this.state.resizing = false;
|
|
||||||
this.#resizeDirection = null;
|
|
||||||
|
|
||||||
document.body.style.userSelect = '';
|
|
||||||
this.#node.style.transition = this.#savedTransition;
|
|
||||||
this.#node.style.willChange = 'auto';
|
|
||||||
this.#node.style.touchAction = '';
|
|
||||||
this.#node.style.cursor = 'auto';
|
|
||||||
|
|
||||||
window.removeEventListener('pointermove', this.#onPointerMove);
|
|
||||||
window.removeEventListener('pointerup', this.#onPointerUp);
|
|
||||||
window.removeEventListener('pointercancel', this.#onPointerCancel);
|
|
||||||
|
|
||||||
this.#apply();
|
|
||||||
};
|
|
||||||
|
|
||||||
#onWrapperResize(): void {
|
|
||||||
const style = getComputedStyle(this.#wrapper);
|
|
||||||
this.#wrapperBorderLeft = parseFloat(style.borderLeftWidth);
|
|
||||||
this.#wrapperBorderTop = parseFloat(style.borderTopWidth);
|
|
||||||
|
|
||||||
if (this.state.maximized) {
|
|
||||||
this.state.width = this.#wrapperWidth;
|
|
||||||
this.state.height = this.#wrapperHeight;
|
|
||||||
this.state.x = 0;
|
|
||||||
this.state.y = 0;
|
|
||||||
} else {
|
|
||||||
this.#clampRect();
|
|
||||||
}
|
|
||||||
|
|
||||||
this.#apply();
|
|
||||||
}
|
|
||||||
|
|
||||||
#updateCursor = (e: PointerEvent): void => {
|
|
||||||
if (this.state.moving || this.state.resizing) return;
|
|
||||||
const target = e.target as HTMLElement;
|
|
||||||
|
|
||||||
if (this.#isInteractive(target)) {
|
|
||||||
this.#resetCursor();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (this.#opts.resizeHandle?.contains(target)) {
|
|
||||||
this.#node.style.cursor = 'se-resize';
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const dir = this.#getCornerDirection(e);
|
|
||||||
if (dir) {
|
|
||||||
this.#node.style.cursor = dir === 'nw' || dir === 'se' ? 'nwse-resize' : 'nesw-resize';
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (this.#opts.handle) {
|
|
||||||
if (this.#opts.handle.contains(target)) {
|
|
||||||
this.#node.style.cursor = 'grab';
|
|
||||||
} else {
|
|
||||||
this.#node.style.cursor = '';
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
this.#node.style.cursor = '';
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
#resetCursor = (): void => {
|
|
||||||
this.#node.style.cursor = '';
|
|
||||||
};
|
|
||||||
|
|
||||||
#isInteractive(target: HTMLElement): boolean {
|
|
||||||
const tag = target.tagName;
|
|
||||||
if (['INPUT', 'BUTTON', 'TEXTAREA', 'SELECT', 'A'].includes(tag)) return true;
|
|
||||||
if (target.isContentEditable) return true;
|
|
||||||
return !!target.closest('[role="button"], [role="textbox"]');
|
|
||||||
}
|
|
||||||
|
|
||||||
minimize(): void {
|
|
||||||
this.state.minimized = !this.state.minimized;
|
|
||||||
this.#opts.onMinimize?.();
|
|
||||||
}
|
|
||||||
|
|
||||||
maximize(): void {
|
|
||||||
if (this.state.maximized) {
|
|
||||||
if (this.#restoreRect) {
|
|
||||||
Object.assign(this.state, this.#restoreRect);
|
|
||||||
this.#restoreRect = null;
|
|
||||||
}
|
|
||||||
this.state.maximized = false;
|
|
||||||
} else {
|
|
||||||
this.#restoreRect = {
|
|
||||||
x: this.state.x,
|
|
||||||
y: this.state.y,
|
|
||||||
width: this.state.width,
|
|
||||||
height: this.state.height
|
|
||||||
};
|
|
||||||
this.state.x = 0;
|
|
||||||
this.state.y = 0;
|
|
||||||
this.state.width = this.#wrapperWidth;
|
|
||||||
this.state.height = this.#wrapperHeight;
|
|
||||||
this.state.maximized = true;
|
|
||||||
}
|
|
||||||
this.#apply();
|
|
||||||
}
|
|
||||||
|
|
||||||
close(): void {
|
|
||||||
this.#opts.onClose?.();
|
|
||||||
}
|
|
||||||
|
|
||||||
focus(): void {
|
|
||||||
this.#bringToFront();
|
|
||||||
}
|
|
||||||
|
|
||||||
destroy(): void {
|
|
||||||
if (this.#rafID !== null) {
|
|
||||||
cancelAnimationFrame(this.#rafID);
|
|
||||||
}
|
|
||||||
|
|
||||||
this.#node.removeEventListener('pointerdown', this.#onPointerDown);
|
|
||||||
this.#node.removeEventListener('pointermove', this.#updateCursor);
|
|
||||||
this.#node.removeEventListener('pointerleave', this.#resetCursor);
|
|
||||||
//this.#node.removeEventListener('keydown', this.#onKeyDown);
|
|
||||||
|
|
||||||
window.removeEventListener('pointermove', this.#onPointerMove);
|
|
||||||
window.removeEventListener('pointerup', this.#onPointerUp);
|
|
||||||
window.removeEventListener('pointercancel', this.#onPointerCancel);
|
|
||||||
|
|
||||||
if (this.#wrapperObserver) {
|
|
||||||
this.#wrapperObserver.disconnect();
|
|
||||||
}
|
|
||||||
|
|
||||||
const mgr = getWrapperManager(this.#wrapper);
|
|
||||||
mgr.refCount--;
|
|
||||||
if (mgr.refCount === 0) {
|
|
||||||
delete (this.#wrapper as any)[MWIN_MANAGER];
|
|
||||||
}
|
|
||||||
|
|
||||||
document.body.style.userSelect = '';
|
|
||||||
this.#node.style.cssText = this.#savedStyles;
|
|
||||||
this.#node.style.transition = this.#savedTransition;
|
|
||||||
this.#node.style.willChange = 'auto';
|
|
||||||
this.#node.style.touchAction = '';
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,99 +0,0 @@
|
|||||||
export interface MWinParams {
|
|
||||||
wrapper: HTMLElement | (() => HTMLElement) | string; // changed
|
|
||||||
handle?: HTMLElement | (() => HTMLElement) | string;
|
|
||||||
initX?: number;
|
|
||||||
initY?: number;
|
|
||||||
initWidth?: number;
|
|
||||||
initHeight?: number;
|
|
||||||
baseZIndex?: number;
|
|
||||||
resizable?: boolean | MWinResizeParams;
|
|
||||||
resizeHandle?: HTMLElement | (() => HTMLElement) | string;
|
|
||||||
onClose?: () => void;
|
|
||||||
onMinimize?: () => void;
|
|
||||||
onMaximize?: () => void;
|
|
||||||
onFocus?: () => void;
|
|
||||||
onAPI?: (api: MWinAPI) => void;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface MWinNormalizedParams {
|
|
||||||
handle: HTMLElement | null;
|
|
||||||
initX?: number;
|
|
||||||
initY?: number;
|
|
||||||
initWidth?: number;
|
|
||||||
initHeight?: number;
|
|
||||||
baseZIndex: number;
|
|
||||||
resizeHandle: HTMLElement | null;
|
|
||||||
resizable: boolean;
|
|
||||||
threshold: number;
|
|
||||||
minWidth: number;
|
|
||||||
minHeight: number;
|
|
||||||
maxWidth: number;
|
|
||||||
maxHeight: number;
|
|
||||||
onClose?: () => void;
|
|
||||||
onMinimize?: () => void;
|
|
||||||
onMaximize?: () => void;
|
|
||||||
onFocus?: () => void;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface MWinResizeParams {
|
|
||||||
threshold?: number;
|
|
||||||
minWidth?: number;
|
|
||||||
minHeight?: number;
|
|
||||||
maxWidth?: number;
|
|
||||||
maxHeight?: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface MWinState {
|
|
||||||
x: number;
|
|
||||||
y: number;
|
|
||||||
width: number;
|
|
||||||
height: number;
|
|
||||||
minimized: boolean;
|
|
||||||
maximized: boolean;
|
|
||||||
moving: boolean;
|
|
||||||
resizing: boolean;
|
|
||||||
zIndex: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface MWinAPI {
|
|
||||||
state: MWinState;
|
|
||||||
minimize: () => void;
|
|
||||||
maximize: () => void;
|
|
||||||
close: () => void;
|
|
||||||
focus: () => void;
|
|
||||||
}
|
|
||||||
|
|
||||||
export class WrapperManager {
|
|
||||||
zCounter: number = 0;
|
|
||||||
refCount: number = 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
export type ResizeDirection = 'ne' | 'se' | 'sw' | 'nw' | null;
|
|
||||||
|
|
||||||
export const MWIN_MANAGER = Symbol('mwinlib');
|
|
||||||
|
|
||||||
export function getWrapperManager(wrapper: HTMLElement): WrapperManager {
|
|
||||||
let mgr = (wrapper as any)[MWIN_MANAGER] as WrapperManager | undefined;
|
|
||||||
if (!mgr) {
|
|
||||||
mgr = { zCounter: 0, refCount: 0 };
|
|
||||||
(wrapper as any)[MWIN_MANAGER] = mgr;
|
|
||||||
}
|
|
||||||
return mgr;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function resolveElement(
|
|
||||||
input: HTMLElement | (() => HTMLElement) | string | undefined,
|
|
||||||
relativeTo: HTMLElement
|
|
||||||
): HTMLElement | null {
|
|
||||||
if (!input) return null;
|
|
||||||
|
|
||||||
if (input instanceof HTMLElement) return input;
|
|
||||||
|
|
||||||
if (typeof input === 'function') return input();
|
|
||||||
|
|
||||||
if (typeof input === 'string') {
|
|
||||||
return relativeTo.closest(input) as HTMLElement | null;
|
|
||||||
}
|
|
||||||
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
import { customType } from 'drizzle-orm/mysql-core';
|
||||||
|
|
||||||
|
export const mediumblob = customType<{
|
||||||
|
data: Buffer;
|
||||||
|
driverData: Buffer;
|
||||||
|
}>({
|
||||||
|
dataType() {
|
||||||
|
return 'MEDIUMBLOB';
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
export const longblob = customType<{
|
||||||
|
data: Buffer;
|
||||||
|
driverData: Buffer;
|
||||||
|
}>({
|
||||||
|
dataType() {
|
||||||
|
return 'LONGBLOB';
|
||||||
|
}
|
||||||
|
});
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
import { drizzle } from 'drizzle-orm/mysql2';
|
||||||
|
import mysql from 'mysql2/promise';
|
||||||
|
import * as schema from './schema';
|
||||||
|
import { env } from '$env/dynamic/private';
|
||||||
|
|
||||||
|
if (!env.DATABASE_URL) throw new Error('DATABASE_URL is not set');
|
||||||
|
|
||||||
|
const client = mysql.createPool(env.DATABASE_URL);
|
||||||
|
|
||||||
|
export const db = drizzle(client, { schema, mode: 'default', logger: true });
|
||||||
@@ -0,0 +1,82 @@
|
|||||||
|
import {
|
||||||
|
boolean,
|
||||||
|
char,
|
||||||
|
int,
|
||||||
|
longtext,
|
||||||
|
mysqlTable,
|
||||||
|
serial,
|
||||||
|
text,
|
||||||
|
timestamp,
|
||||||
|
tinyint,
|
||||||
|
varchar
|
||||||
|
} from 'drizzle-orm/mysql-core';
|
||||||
|
import { longblob, mediumblob } from './custom-types';
|
||||||
|
|
||||||
|
export const task = mysqlTable('task', {
|
||||||
|
id: serial('id').primaryKey(),
|
||||||
|
title: text('title').notNull(),
|
||||||
|
priority: int('priority').notNull().default(1)
|
||||||
|
});
|
||||||
|
|
||||||
|
export const config = mysqlTable('config', {
|
||||||
|
key: varchar('key', { length: 64 }).primaryKey(),
|
||||||
|
value: longtext('value').notNull()
|
||||||
|
});
|
||||||
|
|
||||||
|
export const projects = mysqlTable('projects', {
|
||||||
|
id: tinyint('id').notNull().primaryKey().autoincrement(),
|
||||||
|
name: text('name').notNull(),
|
||||||
|
data: longtext('data', {}).notNull(),
|
||||||
|
enabled: tinyint('enabled').notNull()
|
||||||
|
});
|
||||||
|
|
||||||
|
export const locales = mysqlTable('locales', {
|
||||||
|
code: char('code').notNull().unique(),
|
||||||
|
name: char('name').notNull(),
|
||||||
|
dictionary: longtext().notNull(),
|
||||||
|
flag: longtext('').notNull(),
|
||||||
|
enabled: tinyint('enabled').notNull()
|
||||||
|
});
|
||||||
|
|
||||||
|
export const groups = mysqlTable('groups', {
|
||||||
|
gid: int('gid').primaryKey().autoincrement(),
|
||||||
|
name: varchar('name', { length: 32 }).notNull().unique()
|
||||||
|
});
|
||||||
|
|
||||||
|
export const users = mysqlTable('users', {
|
||||||
|
uid: int('uid').primaryKey().autoincrement(),
|
||||||
|
username: varchar('username', { length: 32 }).notNull().unique(),
|
||||||
|
password: varchar('password', { length: 128 }).notNull(),
|
||||||
|
home: int('home').notNull(),
|
||||||
|
gid: int('gid')
|
||||||
|
.notNull()
|
||||||
|
.references(() => groups.gid),
|
||||||
|
accessible: boolean('accessible').notNull(),
|
||||||
|
face: mediumblob('face')
|
||||||
|
});
|
||||||
|
|
||||||
|
export const filesystem = mysqlTable(
|
||||||
|
'filesystem',
|
||||||
|
{
|
||||||
|
id: int('id').primaryKey().default(1),
|
||||||
|
data: longtext('data').notNull(),
|
||||||
|
checksum: varchar('checksum', { length: 32 }).notNull(),
|
||||||
|
updatedAt: timestamp('updated_at').defaultNow().onUpdateNow()
|
||||||
|
} /* ,
|
||||||
|
{
|
||||||
|
// Ensures only one row can exist
|
||||||
|
singleRow: check('single_row_check', `id = 1`)
|
||||||
|
} */
|
||||||
|
);
|
||||||
|
|
||||||
|
export const fileContents = mysqlTable('file_contents', {
|
||||||
|
guid: varchar('guid', { length: 36 }).primaryKey(),
|
||||||
|
data: longblob('data').notNull(),
|
||||||
|
mimeType: varchar('mime_type', { length: 127 }).default('text/plain')
|
||||||
|
});
|
||||||
|
|
||||||
|
export const allowList = mysqlTable('allow_list', {
|
||||||
|
ip: int('ip').notNull()
|
||||||
|
});
|
||||||
|
|
||||||
|
export type Config = typeof config.$inferSelect;
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
export namespace Physis {
|
||||||
|
export class Engine {}
|
||||||
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
import Vector2 from '$lib/vector';
|
||||||
|
import Rigidbody2D from '../rigidbody/rigidbody2d';
|
||||||
|
|
||||||
|
export class AABB {
|
||||||
|
private size: Vector2 = new Vector2();
|
||||||
|
private halfSize: Vector2 = new Vector2();
|
||||||
|
private rigidbody: Rigidbody2D = new Rigidbody2D();
|
||||||
|
|
||||||
|
constructor(min?: Vector2, max?: Vector2) {
|
||||||
|
if (min !== undefined && max !== undefined) this.size = new Vector2(max).sub(min);
|
||||||
|
|
||||||
|
this.halfSize = new Vector2(this.size.mul(0.5));
|
||||||
|
}
|
||||||
|
|
||||||
|
public get getMin(): Vector2 {
|
||||||
|
return new Vector2(this.rigidbody.Position).sub(this.halfSize);
|
||||||
|
}
|
||||||
|
|
||||||
|
public get getMax(): Vector2 {
|
||||||
|
return new Vector2(this.rigidbody.Position).add(this.halfSize);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export default AABB;
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
import Vector2 from '$lib/vector';
|
||||||
|
import Rigidbody2D from '../rigidbody/rigidbody2d';
|
||||||
|
|
||||||
|
export class Box2D {
|
||||||
|
private size: Vector2 = new Vector2();
|
||||||
|
private halfSize: Vector2 = new Vector2();
|
||||||
|
private rigidbody: Rigidbody2D = new Rigidbody2D();
|
||||||
|
|
||||||
|
constructor();
|
||||||
|
constructor(min?: Vector2, max?: Vector2) {
|
||||||
|
if (min !== undefined && max !== undefined) this.size = new Vector2(max).sub(min);
|
||||||
|
|
||||||
|
this.halfSize = new Vector2(this.size.mul(0.5));
|
||||||
|
}
|
||||||
|
|
||||||
|
public get getMin(): Vector2 {
|
||||||
|
return new Vector2(this.rigidbody.Position).sub(this.halfSize);
|
||||||
|
}
|
||||||
|
|
||||||
|
public get getMax(): Vector2 {
|
||||||
|
return new Vector2(this.rigidbody.Position).add(this.halfSize);
|
||||||
|
}
|
||||||
|
|
||||||
|
public get getVectices(): Vector2[] {
|
||||||
|
const min: Vector2 = this.getMin;
|
||||||
|
const max: Vector2 = this.getMax;
|
||||||
|
|
||||||
|
const vertices: Vector2[] = [
|
||||||
|
new Vector2(min.x, min.y),
|
||||||
|
new Vector2(min.x, max.y),
|
||||||
|
new Vector2(max.x, min.y),
|
||||||
|
new Vector2(max.x, max.y)
|
||||||
|
];
|
||||||
|
|
||||||
|
if (this.rigidbody.Rotation != 0.0) {
|
||||||
|
for (const vert of vertices) {
|
||||||
|
//TODO Rotate Vert around this.rigidbody.getPosition by this.rigidbody.getRotation;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return vertices;
|
||||||
|
}
|
||||||
|
|
||||||
|
public get getRigidbody(): Rigidbody2D {
|
||||||
|
return this.rigidbody;
|
||||||
|
}
|
||||||
|
|
||||||
|
public get getHalfSize(): Vector2 {
|
||||||
|
return this.halfSize;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export default Box2D;
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
import type Vector2 from '$lib/vector';
|
||||||
|
import Rigidbody2D from '../rigidbody/rigidbody2d';
|
||||||
|
|
||||||
|
class Circle {
|
||||||
|
private radius: number = 1.0;
|
||||||
|
private rigidbody: Rigidbody2D = new Rigidbody2D();
|
||||||
|
|
||||||
|
public get Radius(): number {
|
||||||
|
return this.radius;
|
||||||
|
}
|
||||||
|
|
||||||
|
public get Center(): Vector2 {
|
||||||
|
return this.rigidbody.Position;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export default Circle;
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
import Vector2 from "$lib/vector";
|
||||||
|
|
||||||
|
class Collider2D {
|
||||||
|
protected offset: Vector2 = new Vector2();
|
||||||
|
|
||||||
|
//public abstract getInnertiaTensor(mass: number): number;
|
||||||
|
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
import type Vector2 from '$lib/vector';
|
||||||
|
|
||||||
|
class Ray2D {
|
||||||
|
private origin: Vector2;
|
||||||
|
private direction: Vector2;
|
||||||
|
|
||||||
|
constructor(origin: Vector2, direction: Vector2) {
|
||||||
|
this.origin = origin;
|
||||||
|
this.direction = direction;
|
||||||
|
this.direction.normalize();
|
||||||
|
}
|
||||||
|
|
||||||
|
public get Origin(): Vector2 {
|
||||||
|
return this.origin;
|
||||||
|
}
|
||||||
|
|
||||||
|
public get Direction(): Vector2 {
|
||||||
|
return this.direction;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export default Ray2D;
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
import Vector2 from '$lib/vector';
|
||||||
|
|
||||||
|
class RaycastResult {
|
||||||
|
private point: Vector2 = new Vector2();
|
||||||
|
private normal: Vector2 = new Vector2();
|
||||||
|
private t: number = -1;
|
||||||
|
private hit: boolean = false;
|
||||||
|
|
||||||
|
public init(point: Vector2, normal: Vector2, t: number, hit: boolean) {
|
||||||
|
this.point.set(point.x, point.y);
|
||||||
|
this.normal.set(normal.x, normal.y);
|
||||||
|
this.t = t;
|
||||||
|
this.hit = hit;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static reset(result: RaycastResult) {
|
||||||
|
if (result != null) {
|
||||||
|
result.point.set(Vector2.zero.x, Vector2.zero.y);
|
||||||
|
result.normal.set(Vector2.zero.x, Vector2.zero.y);
|
||||||
|
result.t = -1;
|
||||||
|
result.hit = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export default RaycastResult;
|
||||||
@@ -0,0 +1,233 @@
|
|||||||
|
import Line2D from '$lib/shimagic/renderer/line2d';
|
||||||
|
import Vector2 from '$lib/vector';
|
||||||
|
import VMath from '$lib/vmath';
|
||||||
|
import AABB from '../primitives/aabb';
|
||||||
|
import Box2D from '../primitives/box2d';
|
||||||
|
import Circle from '../primitives/circle';
|
||||||
|
import type Ray2D from '../primitives/ray2d';
|
||||||
|
import RaycastResult from '../primitives/raycast_result';
|
||||||
|
|
||||||
|
class IntersectionDetector2D {
|
||||||
|
public static pointOnLine(point: Vector2, line: Line2D): boolean {
|
||||||
|
let dy: number = line.getEnd().y - line.getStart().y;
|
||||||
|
let dx: number = line.getEnd().x - line.getStart().x;
|
||||||
|
let m: number = dy / dx;
|
||||||
|
|
||||||
|
let b = line.getEnd().y - m * line.getEnd().x;
|
||||||
|
|
||||||
|
//Check the line equation
|
||||||
|
return point.y == m * point.x + b;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static pointInCircle(point: Vector2, circle: Circle) {
|
||||||
|
const circleCenter: Vector2 = circle.Center;
|
||||||
|
const centerToPoint: Vector2 = new Vector2(point).sub(circleCenter);
|
||||||
|
|
||||||
|
return centerToPoint.sqrLength <= circle.Radius * circle.Radius;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static pointInAABB(point: Vector2, aabb: AABB): boolean {
|
||||||
|
let min: Vector2 = aabb.getMin;
|
||||||
|
let max: Vector2 = aabb.getMax;
|
||||||
|
|
||||||
|
return point.x <= max.x && point.x >= min.x && point.y >= min.y && point.y <= max.y;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static pointInBox2D(point: Vector2, box: Box2D): boolean {
|
||||||
|
const pointLocal = new Vector2(point);
|
||||||
|
VMath.rotate(pointLocal, box.getRigidbody.Rotation, box.getRigidbody.Position);
|
||||||
|
|
||||||
|
let min: Vector2 = box.getMin;
|
||||||
|
let max: Vector2 = box.getMax;
|
||||||
|
|
||||||
|
return (
|
||||||
|
pointLocal.x <= max.x &&
|
||||||
|
pointLocal.x >= min.x &&
|
||||||
|
pointLocal.y >= min.y &&
|
||||||
|
pointLocal.y <= max.y
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static lineAndCircle(line: Line2D, circle: Circle): boolean {
|
||||||
|
if (this.pointInCircle(line.getStart(), circle) || this.pointInCircle(line.getEnd(), circle))
|
||||||
|
return true;
|
||||||
|
|
||||||
|
const ab: Vector2 = new Vector2(line.getEnd()).sub(line.getStart());
|
||||||
|
|
||||||
|
const circleCenter: Vector2 = circle.Center;
|
||||||
|
const centerToLineStart: Vector2 = new Vector2(circleCenter).sub(line.getStart());
|
||||||
|
const t: number = centerToLineStart.dot(ab) / ab.dot(ab);
|
||||||
|
|
||||||
|
if (t < 0.0 || t > 1.0) return false;
|
||||||
|
|
||||||
|
const closestPoint: Vector2 = new Vector2(line.getStart()).add(ab.mul(t));
|
||||||
|
|
||||||
|
return this.pointInCircle(closestPoint, circle);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static lineAndAABB(line: Line2D, box: AABB): boolean {
|
||||||
|
if (this.pointInAABB(line.getStart(), box) || this.pointInAABB(line.getEnd(), box)) return true;
|
||||||
|
|
||||||
|
let uVec: Vector2 = new Vector2(line.getEnd()).sub(line.getStart());
|
||||||
|
uVec.normalize;
|
||||||
|
|
||||||
|
uVec.x = !uVec.equals(Vector2.zero) ? 1.0 / uVec.x : 0.0;
|
||||||
|
uVec.y = !uVec.equals(Vector2.zero) ? 1.0 / uVec.y : 0.0;
|
||||||
|
|
||||||
|
const min: Vector2 = box.getMin;
|
||||||
|
min.sub(line.getStart()).mul(uVec);
|
||||||
|
const max: Vector2 = box.getMax;
|
||||||
|
max.sub(line.getStart()).mul(uVec);
|
||||||
|
|
||||||
|
const tmin: number = Math.max(Math.min(min.x, max.x), Math.min(min.y, max.y));
|
||||||
|
const tmax: number = Math.min(Math.max(min.x, max.x), Math.max(min.y, max.y));
|
||||||
|
|
||||||
|
if (tmax < 0 || tmin > tmax) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
const t = tmin < 0 ? tmax : tmin;
|
||||||
|
return t > 0 && t * t < line.lengthSqr();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static lineAndBox2D(line: Line2D, box: Box2D): boolean {
|
||||||
|
const rotation: number = box.getRigidbody.Rotation;
|
||||||
|
const center: Vector2 = box.getRigidbody.Position;
|
||||||
|
const localStart: Vector2 = new Vector2(line.getStart());
|
||||||
|
const localEnd: Vector2 = new Vector2(line.getEnd());
|
||||||
|
|
||||||
|
VMath.rotate(localStart, rotation, center);
|
||||||
|
VMath.rotate(localEnd, rotation, center);
|
||||||
|
|
||||||
|
const localLine: Line2D = new Line2D(localStart, localEnd);
|
||||||
|
const aabb: AABB = new AABB(box.getMin, box.getMax);
|
||||||
|
|
||||||
|
return this.lineAndAABB(localLine, aabb);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static raycast(circle: Circle, ray: Ray2D, result: RaycastResult): boolean;
|
||||||
|
public static raycast(aabb: AABB, ray: Ray2D, result: RaycastResult): boolean;
|
||||||
|
public static raycast(box: Box2D, ray: Ray2D, result: RaycastResult): boolean;
|
||||||
|
public static raycast(
|
||||||
|
primitive: Circle | AABB | Box2D,
|
||||||
|
ray: Ray2D,
|
||||||
|
result: RaycastResult
|
||||||
|
): boolean {
|
||||||
|
if (primitive instanceof Circle) {
|
||||||
|
RaycastResult.reset(result);
|
||||||
|
|
||||||
|
const originToCircle: Vector2 = new Vector2(primitive.Center).sub(ray.Origin);
|
||||||
|
const radiusSqr: number = primitive.Radius * primitive.Radius;
|
||||||
|
const originToCircleSqr: number = originToCircle.sqrLength;
|
||||||
|
|
||||||
|
const a: number = originToCircle.dot(ray.Direction);
|
||||||
|
const bSqr: number = originToCircleSqr - a * a;
|
||||||
|
|
||||||
|
if (radiusSqr - bSqr < 0.0) return false;
|
||||||
|
|
||||||
|
const f: number = Math.sqrt(radiusSqr - bSqr);
|
||||||
|
let t: number = 0;
|
||||||
|
if (originToCircleSqr < radiusSqr) {
|
||||||
|
t = a + f;
|
||||||
|
} else {
|
||||||
|
t = a - f;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (result != null) {
|
||||||
|
const point: Vector2 = new Vector2(ray.Origin).add(new Vector2(ray.Direction)).mul(t);
|
||||||
|
const normal: Vector2 = new Vector2(point).sub(primitive.Center);
|
||||||
|
normal.normalize();
|
||||||
|
|
||||||
|
result.init(point, normal, t, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
} else if (primitive instanceof AABB) {
|
||||||
|
RaycastResult.reset(result);
|
||||||
|
let uVec: Vector2 = ray.Direction;
|
||||||
|
uVec.normalize;
|
||||||
|
|
||||||
|
uVec.x = !uVec.equals(Vector2.zero) ? 1.0 / uVec.x : 0.0;
|
||||||
|
uVec.y = !uVec.equals(Vector2.zero) ? 1.0 / uVec.y : 0.0;
|
||||||
|
|
||||||
|
const min: Vector2 = primitive.getMin;
|
||||||
|
min.sub(ray.Origin).mul(uVec);
|
||||||
|
const max: Vector2 = primitive.getMax;
|
||||||
|
max.sub(ray.Origin).mul(uVec);
|
||||||
|
|
||||||
|
const tmin: number = Math.max(Math.min(min.x, max.x), Math.min(min.y, max.y));
|
||||||
|
const tmax: number = Math.min(Math.max(min.x, max.x), Math.max(min.y, max.y));
|
||||||
|
|
||||||
|
if (tmax < 0 || tmin > tmax) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
const t = tmin < 0 ? tmax : tmin;
|
||||||
|
const hit: boolean = t > 0; //&& t * t < ray.Distance;
|
||||||
|
if (!hit) return false;
|
||||||
|
|
||||||
|
if (result != null) {
|
||||||
|
const point: Vector2 = new Vector2(ray.Origin).add(new Vector2(ray.Direction).mul(t));
|
||||||
|
const normal: Vector2 = new Vector2(ray.Origin).sub(point);
|
||||||
|
normal.normalize();
|
||||||
|
|
||||||
|
result.init(point, normal, t, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
} else {
|
||||||
|
//TODO: Box2D implementation
|
||||||
|
|
||||||
|
RaycastResult.reset(result);
|
||||||
|
|
||||||
|
const halfSize: Vector2 = primitive.getHalfSize;
|
||||||
|
|
||||||
|
const xAxis: Vector2 = new Vector2(1, 0);
|
||||||
|
const yAxis: Vector2 = new Vector2(0, 1);
|
||||||
|
VMath.rotate(xAxis, primitive.getRigidbody.Rotation, Vector2.zero);
|
||||||
|
VMath.rotate(yAxis, primitive.getRigidbody.Rotation, Vector2.zero);
|
||||||
|
|
||||||
|
const p: Vector2 = new Vector2(primitive.getRigidbody.Position).sub(ray.Origin);
|
||||||
|
const f: Vector2 = new Vector2(xAxis.dot(ray.Direction), yAxis.dot(ray.Direction));
|
||||||
|
const e: Vector2 = new Vector2(xAxis.dot(p), yAxis.dot(p));
|
||||||
|
|
||||||
|
const tArr: number[] = [0, 0, 0, 0];
|
||||||
|
if (VMath.compare(f.x, 0)) {
|
||||||
|
if (-e.x - halfSize.x > 0 || -e.x + halfSize.x < 0) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
f.x = 0.00001;
|
||||||
|
tArr[0 * 2 + 0] = e.x + halfSize.x / f.x;
|
||||||
|
tArr[0 * 2 + 1] = e.x - halfSize.x / f.x;
|
||||||
|
|
||||||
|
if (VMath.compare(f.y, 0)) {
|
||||||
|
if (-e.y - halfSize.y > 0 || -e.y + halfSize.y < 0) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
f.y = 0.00001;
|
||||||
|
tArr[1 * 2 + 0] = e.y + halfSize.y / f.y;
|
||||||
|
tArr[1 * 2 + 1] = e.x - halfSize.x / f.x;
|
||||||
|
|
||||||
|
const tmin: number = Math.max(Math.min(tArr[0], tArr[1]), Math.min(tArr[2], tArr[3]));
|
||||||
|
const tmax: number = Math.min(Math.max(tArr[0], tArr[1]), Math.max(tArr[2], tArr[3]));
|
||||||
|
|
||||||
|
const t = tmin < 0 ? tmax : tmin;
|
||||||
|
const hit: boolean = t > 0; //&& t * t < ray.Distance;
|
||||||
|
if (!hit) return false;
|
||||||
|
|
||||||
|
if (result != null) {
|
||||||
|
const point: Vector2 = new Vector2(ray.Origin).add(new Vector2(ray.Direction).mul(t));
|
||||||
|
const normal: Vector2 = new Vector2(ray.Origin).sub(point);
|
||||||
|
normal.normalize();
|
||||||
|
|
||||||
|
result.init(point, normal, t, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static circleAndLine()
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
import Vector2 from '$lib/vector';
|
||||||
|
|
||||||
|
class Rigidbody2D {
|
||||||
|
private position: Vector2 = new Vector2();
|
||||||
|
private rotation: number = 0.0;
|
||||||
|
|
||||||
|
public get Position(): Vector2 {
|
||||||
|
return this.position;
|
||||||
|
}
|
||||||
|
|
||||||
|
public set setPosition(position: Vector2) {
|
||||||
|
this.position = position;
|
||||||
|
}
|
||||||
|
|
||||||
|
public get Rotation(): number {
|
||||||
|
return this.rotation;
|
||||||
|
}
|
||||||
|
|
||||||
|
public set setRotation(rotation: number) {
|
||||||
|
this.rotation = rotation;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export default Rigidbody2D;
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
import Vector2 from '$lib/vector';
|
||||||
|
|
||||||
|
class Line2D {
|
||||||
|
private from: Vector2;
|
||||||
|
private to: Vector2;
|
||||||
|
|
||||||
|
constructor(from: Vector2, to: Vector2) {
|
||||||
|
this.from = from;
|
||||||
|
this.to = to;
|
||||||
|
}
|
||||||
|
|
||||||
|
public getStart(): Vector2 {
|
||||||
|
return this.from;
|
||||||
|
}
|
||||||
|
|
||||||
|
public getEnd(): Vector2 {
|
||||||
|
return this.to;
|
||||||
|
}
|
||||||
|
|
||||||
|
public lengthSqr(): number {
|
||||||
|
return new Vector2(this.to).sub(this.from).sqrLength;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export default Line2D;
|
||||||
@@ -0,0 +1,131 @@
|
|||||||
|
import type Vector2 from '$lib/vector';
|
||||||
|
|
||||||
|
class Renderer {
|
||||||
|
private gl: WebGL2RenderingContext;
|
||||||
|
private posBuffer!: WebGLBuffer;
|
||||||
|
private program!: WebGLProgram;
|
||||||
|
private drawMode: DrawMode = DrawMode.TEX;
|
||||||
|
|
||||||
|
constructor(canvas: HTMLCanvasElement) {
|
||||||
|
let context = canvas.getContext('webgl2');
|
||||||
|
if (!context) throw new Error(`Failed to get webgl2 context from ${canvas}`);
|
||||||
|
|
||||||
|
this.gl = context;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async init() {
|
||||||
|
try {
|
||||||
|
const vert: WebGLShader = await this.loadShader(
|
||||||
|
this.gl,
|
||||||
|
'src/lib/shimeji/renderer/shaders/vertex_shader.vert',
|
||||||
|
this.gl.VERTEX_SHADER
|
||||||
|
);
|
||||||
|
const frag: WebGLShader = await this.loadShader(
|
||||||
|
this.gl,
|
||||||
|
'src/lib/shimeji/renderer/shaders/fragment_shader.frag',
|
||||||
|
this.gl.FRAGMENT_SHADER
|
||||||
|
);
|
||||||
|
|
||||||
|
const program = this.gl.createProgram();
|
||||||
|
this.program = program;
|
||||||
|
|
||||||
|
this.gl.attachShader(program, vert);
|
||||||
|
this.gl.attachShader(program, frag);
|
||||||
|
this.gl.linkProgram(program);
|
||||||
|
|
||||||
|
if (!this.gl.getProgramParameter(program, this.gl.LINK_STATUS)) {
|
||||||
|
console.error(this.gl.getProgramInfoLog(program));
|
||||||
|
this.gl.deleteProgram(program);
|
||||||
|
|
||||||
|
throw new Error(`Failed to link program to webgl2 context ${program}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const pos = this.gl.createBuffer();
|
||||||
|
this.posBuffer = pos;
|
||||||
|
this.gl.bindBuffer(this.gl.ARRAY_BUFFER, pos);
|
||||||
|
this.gl.viewport(0, 0, this.gl.canvas.width, this.gl.canvas.height);
|
||||||
|
|
||||||
|
let resUniLoc = this.gl.getUniformLocation(program, 'u_resolution');
|
||||||
|
|
||||||
|
this.gl.clearColor(0, 0, 0, 0);
|
||||||
|
this.gl.clear(this.gl.COLOR_BUFFER_BIT);
|
||||||
|
|
||||||
|
this.gl.useProgram(program);
|
||||||
|
this.gl.enableVertexAttribArray(0);
|
||||||
|
|
||||||
|
this.gl.bindBuffer(this.gl.ARRAY_BUFFER, pos);
|
||||||
|
|
||||||
|
this.gl.vertexAttribPointer(0, 2, this.gl.FLOAT, false, 0, 0);
|
||||||
|
this.gl.uniform2f(resUniLoc, this.gl.canvas.width, this.gl.canvas.height);
|
||||||
|
} catch (error) {
|
||||||
|
console.log(error);
|
||||||
|
this.gl.VERTEX_SHADER;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async loadShader(
|
||||||
|
gl: WebGL2RenderingContext,
|
||||||
|
path: string,
|
||||||
|
type: typeof gl.VERTEX_SHADER | typeof gl.FRAGMENT_SHADER
|
||||||
|
) {
|
||||||
|
const response = await fetch(path);
|
||||||
|
if (!response.ok) throw new Error(`failed to fetch the shader file ${response}`);
|
||||||
|
const data = await response.text();
|
||||||
|
|
||||||
|
const shader = gl.createShader(type);
|
||||||
|
if (!shader) throw new Error(`Failed to create the shader ${shader}`);
|
||||||
|
|
||||||
|
gl.shaderSource(shader, data);
|
||||||
|
gl.compileShader(shader);
|
||||||
|
|
||||||
|
if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
|
||||||
|
console.error(gl.getShaderInfoLog(shader));
|
||||||
|
gl.deleteShader(shader);
|
||||||
|
|
||||||
|
throw new Error(`Failed to compile the shader ${shader}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
return shader;
|
||||||
|
}
|
||||||
|
|
||||||
|
public UpdateBounds(width: number, height: number): void {
|
||||||
|
this.gl.viewport(0, 0, width, height);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Set the draw mode to one of the enum values
|
||||||
|
* @param {DrawMode} mode
|
||||||
|
* @returns {void}
|
||||||
|
*/
|
||||||
|
public set SetDrawMode(mode: DrawMode) {}
|
||||||
|
|
||||||
|
public Draw(pos: Vector2, size: number): void {
|
||||||
|
//this.gl.clearColor(0, 0, 0, 0);
|
||||||
|
// this.gl.clear(this.gl.COLOR_BUFFER_BIT);
|
||||||
|
|
||||||
|
let x1 = pos.x - size;
|
||||||
|
let x2 = pos.x + size;
|
||||||
|
let y1 = pos.y + size;
|
||||||
|
let y2 = pos.y - size;
|
||||||
|
|
||||||
|
this.gl.bindBuffer(this.gl.ARRAY_BUFFER, this.posBuffer);
|
||||||
|
this.gl.bufferData(
|
||||||
|
this.gl.ARRAY_BUFFER,
|
||||||
|
new Float32Array([x1, y1, x2, y1, x2, y2, x1, y1, x1, y2, x2, y2]),
|
||||||
|
this.gl.DYNAMIC_DRAW
|
||||||
|
);
|
||||||
|
|
||||||
|
var primitiveType = this.gl.TRIANGLES;
|
||||||
|
var offset = 0;
|
||||||
|
var count = 6;
|
||||||
|
this.gl.drawArrays(primitiveType, offset, count);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
enum DrawMode {
|
||||||
|
TEX = 0,
|
||||||
|
WIRE = 1,
|
||||||
|
VERT = 2
|
||||||
|
}
|
||||||
|
|
||||||
|
export default Renderer;
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
#version 300 es
|
||||||
|
|
||||||
|
precision mediump float;
|
||||||
|
|
||||||
|
out vec4 color;
|
||||||
|
in vec4 v_color;
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
color = vec4(1.0, 1.0, 1.0, 1.0);
|
||||||
|
}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
#version 300 es
|
||||||
|
|
||||||
|
layout ( location = 0 ) in vec2 a_position;
|
||||||
|
uniform vec2 u_resolution;
|
||||||
|
out vec4 v_color;
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
vec2 zeroToOne = a_position / u_resolution;
|
||||||
|
vec2 zeroToTwo = zeroToOne * 2.0;
|
||||||
|
vec2 clipSpace = zeroToTwo - 1.0;
|
||||||
|
|
||||||
|
gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1);
|
||||||
|
//gl_Position = vec4(a_position, 0, 1);
|
||||||
|
gl_PointSize = 5.0;
|
||||||
|
v_color = vec4(a_position.xy, 0.0, 1.0);
|
||||||
|
}
|
||||||
@@ -0,0 +1,174 @@
|
|||||||
|
import type Vector2 from '$lib/vector';
|
||||||
|
|
||||||
|
export namespace WebG {
|
||||||
|
export class Engine {
|
||||||
|
private _GL: WebGL2RenderingContext;
|
||||||
|
private _Program!: WebGLProgram;
|
||||||
|
private _Shaders: Array<WebGLShader> = Array<WebGLShader>();
|
||||||
|
private _DrawMode: EngineDrawMode = EngineDrawMode.TEXTURE;
|
||||||
|
private _PosBuffer!: WebGLBuffer;
|
||||||
|
|
||||||
|
constructor(gl: WebGL2RenderingContext) {
|
||||||
|
this._GL = gl;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Factory method: Loads all shaders compiles and links them
|
||||||
|
* @async
|
||||||
|
* @public
|
||||||
|
* @param config - Engine configuration
|
||||||
|
* @returns Promise<Engine> that resolver when the engine is done initializing\
|
||||||
|
*/
|
||||||
|
public static async Initialize(config: EngineConfig) {
|
||||||
|
const GL = config.canvas.getContext('webgl2');
|
||||||
|
if (!GL) throw new Error('WebGL2 not supported!');
|
||||||
|
|
||||||
|
const shaderSources: ShaderSrc[] = [];
|
||||||
|
|
||||||
|
try {
|
||||||
|
const [vertSource, fragSource] = await Promise.all([
|
||||||
|
fetch(config.vertexShaderUrl).then((r) => r.text()),
|
||||||
|
fetch(config.fragmentShaderUrl).then((r) => r.text())
|
||||||
|
]);
|
||||||
|
|
||||||
|
shaderSources.push(
|
||||||
|
{ type: GL.VERTEX_SHADER, src: vertSource, url: config.vertexShaderUrl },
|
||||||
|
{ type: GL.FRAGMENT_SHADER, src: fragSource, url: config.fragmentShaderUrl }
|
||||||
|
);
|
||||||
|
} catch (error) {
|
||||||
|
throw new Error(`${error} Filed to fetch the shaders`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const ENGINE = new Engine(GL);
|
||||||
|
ENGINE._Program = GL.createProgram();
|
||||||
|
if (!ENGINE._Program) throw new Error(`Failed to create a new program ${ENGINE._Program}`);
|
||||||
|
|
||||||
|
for (const { type, src, url } of shaderSources) {
|
||||||
|
const shader = ENGINE.compileShader(type, src, url);
|
||||||
|
|
||||||
|
ENGINE._Shaders.push(shader);
|
||||||
|
|
||||||
|
GL.attachShader(ENGINE._Program, shader);
|
||||||
|
}
|
||||||
|
|
||||||
|
ENGINE._GL.linkProgram(ENGINE._Program);
|
||||||
|
if (!GL.getProgramParameter(ENGINE._Program, GL.LINK_STATUS))
|
||||||
|
throw new Error(
|
||||||
|
`Failed to link program ${ENGINE._Program} - Logs: ${GL.getProgramInfoLog(ENGINE._Program)}`
|
||||||
|
);
|
||||||
|
|
||||||
|
const pos = GL.createBuffer();
|
||||||
|
ENGINE._PosBuffer = pos;
|
||||||
|
ENGINE._GL.bindBuffer(ENGINE._GL.ARRAY_BUFFER, pos);
|
||||||
|
|
||||||
|
GL.enableVertexAttribArray(0);
|
||||||
|
GL.bindBuffer(GL.ARRAY_BUFFER, pos);
|
||||||
|
GL.vertexAttribPointer(0, 2, GL.FLOAT, false, 0, 0);
|
||||||
|
|
||||||
|
GL.clearColor(0, 0, 0, 0);
|
||||||
|
GL.clear(GL.COLOR_BUFFER_BIT);
|
||||||
|
|
||||||
|
GL.viewport(0, 0, GL.canvas.width, GL.canvas.height);
|
||||||
|
|
||||||
|
GL.useProgram(ENGINE._Program);
|
||||||
|
|
||||||
|
let resUniLoc = GL.getUniformLocation(ENGINE._Program, 'u_resolution');
|
||||||
|
GL.uniform2f(resUniLoc, GL.canvas.width, GL.canvas.height);
|
||||||
|
return ENGINE;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Compile a single shader from source
|
||||||
|
* @param type - WebGL Shader type (e.g., gl.VERTEX_SHADER)
|
||||||
|
* @param src - Source code in GLSL
|
||||||
|
* @param url - Source url - used for debbugging (optional)
|
||||||
|
* @returns - Compiled {WebGLShader}
|
||||||
|
* @private
|
||||||
|
*/
|
||||||
|
private compileShader(type: number, src: string, url?: string) {
|
||||||
|
const shader = this._GL.createShader(type);
|
||||||
|
if (!shader) throw new Error(`Failed to create a new shader of type ${type}`);
|
||||||
|
|
||||||
|
this._GL.shaderSource(shader, src);
|
||||||
|
this._GL.compileShader(shader);
|
||||||
|
|
||||||
|
if (!this._GL.getShaderParameter(shader, this._GL.COMPILE_STATUS)) {
|
||||||
|
this._GL.deleteShader(shader);
|
||||||
|
throw new Error(
|
||||||
|
`Failed to compile shader from source ${src} located at ${url || 'unknown'} - Logs: ${this._GL.getShaderInfoLog(shader)}`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return shader;
|
||||||
|
}
|
||||||
|
|
||||||
|
public get GL(): WebGL2RenderingContext {
|
||||||
|
return this._GL;
|
||||||
|
}
|
||||||
|
|
||||||
|
public get Program(): WebGLProgram {
|
||||||
|
return this._Program;
|
||||||
|
}
|
||||||
|
|
||||||
|
public setDrawMode(mode: EngineDrawMode) {
|
||||||
|
this._DrawMode = mode;
|
||||||
|
}
|
||||||
|
|
||||||
|
public draw(args: DrawCallArgs) {
|
||||||
|
const positions: Array<number> = [];
|
||||||
|
for (const v of args.vertices) {
|
||||||
|
positions.push(v.x, v.y);
|
||||||
|
}
|
||||||
|
|
||||||
|
this._GL.bindBuffer(this._GL.ARRAY_BUFFER, this._PosBuffer);
|
||||||
|
this._GL.bufferData(this._GL.ARRAY_BUFFER, new Float32Array(positions), this._GL.STATIC_DRAW);
|
||||||
|
|
||||||
|
this._GL.drawArrays(this._DrawMode, 0, args.vertices.length);
|
||||||
|
}
|
||||||
|
|
||||||
|
public destroy() {
|
||||||
|
for (const shader of this._Shaders) {
|
||||||
|
this._GL.detachShader(this._Program, shader);
|
||||||
|
this._GL.deleteShader(shader);
|
||||||
|
}
|
||||||
|
this._GL.deleteBuffer(this._PosBuffer);
|
||||||
|
this._GL.deleteProgram(this._Program);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Enum for setting the draw mode of the engine
|
||||||
|
* @enum {0} - Texture, the default form of rendering, either a texture or a color
|
||||||
|
*/
|
||||||
|
export enum EngineDrawMode {
|
||||||
|
TEXTURE = 5, //WebGL2RenderingContext.TRIANGLE_STRIP
|
||||||
|
WIREFRAME = 2, //WebGL2RenderingContext.LINES
|
||||||
|
VERTEX = 0 //WebGL2RenderingContext.POINTS
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface DrawCallArgs {
|
||||||
|
vertices: Array<Vector2>;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ShaderSrc {
|
||||||
|
type: number;
|
||||||
|
src: string;
|
||||||
|
url: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* {Engine} class factory method dependency that passes all the nesesary data for engine initialization
|
||||||
|
* @param canvas - A {HTMLCanvasElement}
|
||||||
|
* @param vertexShaderUrl - A string url to the primary vertex shader file
|
||||||
|
* @param fragmentShaderUrl - A string utl to the primary fragment shader file
|
||||||
|
* @param attributes - Shader attributes passed into and mapped to the program
|
||||||
|
* @param uniforms - Shader uniforms passed into and mapped to the program
|
||||||
|
*/
|
||||||
|
export interface EngineConfig {
|
||||||
|
canvas: HTMLCanvasElement;
|
||||||
|
vertexShaderUrl: string;
|
||||||
|
fragmentShaderUrl: string;
|
||||||
|
attributes?: Record<string, number>;
|
||||||
|
uniforms?: Record<string, number>;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,70 @@
|
|||||||
|
import { WebG } from './renderer/web_g_engine';
|
||||||
|
|
||||||
|
export namespace Shimagic {
|
||||||
|
export class Shimeji {
|
||||||
|
private WebGEngine: WebG.Engine;
|
||||||
|
//private PhysisEngine: Physis.Engine;
|
||||||
|
private size!: number;
|
||||||
|
|
||||||
|
private AnimID: number | null = null;
|
||||||
|
private pDeltaT: number = 0;
|
||||||
|
|
||||||
|
constructor(webgengine: WebG.Engine /* physis: Physis.Engine */) {
|
||||||
|
this.WebGEngine = webgengine;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Factory method: Initializes all sub-systems like WebG & Physis aswell as initializes the Shimeji and starts its animation
|
||||||
|
* @async
|
||||||
|
* @public
|
||||||
|
* @param {ShimejiConfig} config - Shimeji configuration
|
||||||
|
* @returns {Promise<Shimeji>} that resolves when the Shimeji is done initializing
|
||||||
|
*/
|
||||||
|
public static async Initialize(config: ShimejiConfig): Promise<Shimeji> {
|
||||||
|
const webg = await WebG.Engine.Initialize(config.webG);
|
||||||
|
//const physis = await Physis.Engine.Initialize(config.physis);
|
||||||
|
|
||||||
|
const shimeji = new Shimeji(webg);
|
||||||
|
shimeji.size = config.size;
|
||||||
|
|
||||||
|
const AFrame = (delta: number) => {
|
||||||
|
shimeji.pDeltaT = delta;
|
||||||
|
shimeji.AnimID = requestAnimationFrame(shimeji._anim);
|
||||||
|
};
|
||||||
|
|
||||||
|
shimeji.AnimID = requestAnimationFrame(AFrame);
|
||||||
|
|
||||||
|
return shimeji;
|
||||||
|
}
|
||||||
|
|
||||||
|
private _anim(delta: number) {
|
||||||
|
let dt = (delta - this.pDeltaT) / 1000;
|
||||||
|
dt = Math.min(dt, 0.05 /* * this.Physis.TIMESCALE */);
|
||||||
|
this.pDeltaT = delta;
|
||||||
|
|
||||||
|
this.UpdatePhysics(dt);
|
||||||
|
this.UpdateFrame(dt);
|
||||||
|
|
||||||
|
this.AnimID = requestAnimationFrame(this._anim);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A function called automatically every "frame" where the code for calculating the next physics frame of the Shimeji is placed
|
||||||
|
* @param delta - Automatically passed in deltaT value;
|
||||||
|
*/
|
||||||
|
private UpdatePhysics(delta: number): void {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A function called automatically every "frame" where the code for drawing the next frame of the Shimeji is placed
|
||||||
|
* @param delta - Automatically passed in deltaT value;
|
||||||
|
*/
|
||||||
|
private UpdateFrame(delta: number): void {}
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ShimejiConfig {
|
||||||
|
sprite: string; //temp soultion to
|
||||||
|
size: number;
|
||||||
|
webG: WebG.EngineConfig;
|
||||||
|
//physis: Physis.EngineConfig;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,242 @@
|
|||||||
|
import { Stack } from '../stack';
|
||||||
|
import { Terminal, type PrintData } from '../terminal/terminal';
|
||||||
|
import {
|
||||||
|
COMMANDS,
|
||||||
|
type CommandArgs,
|
||||||
|
type CommandResultData,
|
||||||
|
type ICommand
|
||||||
|
} from './commandRegistry';
|
||||||
|
import { GROUP, type Group } from './etc/groupData';
|
||||||
|
import { PASSWD, type User } from './etc/userData';
|
||||||
|
import { VirtualFS, type TreeNode } from './fs';
|
||||||
|
import type { KeybindInhibitor } from './keybindInhibitor';
|
||||||
|
import { ExitCode } from './metadata';
|
||||||
|
import { Process } from './process';
|
||||||
|
|
||||||
|
export enum Signal {
|
||||||
|
SIGINT,
|
||||||
|
SIGKILL
|
||||||
|
}
|
||||||
|
|
||||||
|
export type BashInitArgs = {
|
||||||
|
io?: Terminal;
|
||||||
|
fs: Map<number, TreeNode>;
|
||||||
|
user: { username: string; password: string };
|
||||||
|
};
|
||||||
|
|
||||||
|
export type Result = {
|
||||||
|
exitCode: ExitCode;
|
||||||
|
path: number; //the inode of the place that the command was executed in
|
||||||
|
resultData?: CommandResultData;
|
||||||
|
};
|
||||||
|
|
||||||
|
export class Bash {
|
||||||
|
private readonly vfs: VirtualFS;
|
||||||
|
private readonly _passwd: User[];
|
||||||
|
private readonly _group: Group[];
|
||||||
|
private readonly _terminal!: Terminal;
|
||||||
|
private readonly _commands: Record<string, ICommand>;
|
||||||
|
|
||||||
|
private _userInstances: Stack<User>;
|
||||||
|
|
||||||
|
private user: User;
|
||||||
|
private _process?: Process;
|
||||||
|
|
||||||
|
constructor(args: BashInitArgs) {
|
||||||
|
this._commands = COMMANDS;
|
||||||
|
this._passwd = PASSWD;
|
||||||
|
this._group = GROUP;
|
||||||
|
this._userInstances = new Stack<User>();
|
||||||
|
this._terminal = args.io!;
|
||||||
|
|
||||||
|
const loginResult = this.userLogin(args.user.username, args.user.password);
|
||||||
|
if (loginResult == ExitCode.ERROR)
|
||||||
|
this._terminal.throwExeption(
|
||||||
|
`Failed to initialize bash instance - access denied for user ${args.user.username}`,
|
||||||
|
ExitCode.ERROR
|
||||||
|
);
|
||||||
|
|
||||||
|
this.user = this._userInstances.peek()!;
|
||||||
|
this.vfs = new VirtualFS({ fs: args.fs, user: this.user });
|
||||||
|
}
|
||||||
|
|
||||||
|
private _initNewUserSession(user: User): User {
|
||||||
|
if (!this._passwd.includes(user))
|
||||||
|
this._terminal.throwExeption(
|
||||||
|
`user not found under the name ${user.username}`,
|
||||||
|
ExitCode.ERROR
|
||||||
|
);
|
||||||
|
|
||||||
|
this._userInstances.push(user);
|
||||||
|
return user;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async _initNewProcess(command: ICommand, args: CommandArgs) {
|
||||||
|
this._process = new Process(this, this.user.uid, 'TEMP PROCESS NAME', command, args);
|
||||||
|
|
||||||
|
//this._terminal.isProcessActive = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private _appendNewResult(inode: number, output: any, cmd: string) {
|
||||||
|
const data: PrintData = {
|
||||||
|
path: this.vfs.formatPath(this.vfs.getPathByInode(inode)),
|
||||||
|
output: output,
|
||||||
|
cmd: cmd
|
||||||
|
};
|
||||||
|
console.log(this.vfs.formatPath(this.vfs.getPathByInode(inode)), 'TEST TEST !@#');
|
||||||
|
this._terminal.PrintOutput(data);
|
||||||
|
}
|
||||||
|
|
||||||
|
updateHistory(input: string): void {
|
||||||
|
if ((this.user.history.length = 255)) {
|
||||||
|
this.user.history.unshift(...this.user.history.splice(-1));
|
||||||
|
this.user.history[0] = input;
|
||||||
|
} else {
|
||||||
|
this.user.history.push(input);
|
||||||
|
this.user.history.unshift(...this.user.history.splice(-1));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
clearTerminal(): void {
|
||||||
|
this._terminal.clearTerminal();
|
||||||
|
}
|
||||||
|
|
||||||
|
getCwd(): number {
|
||||||
|
return this.vfs.cwd;
|
||||||
|
}
|
||||||
|
|
||||||
|
getPwd(): number {
|
||||||
|
return this.vfs.pwd;
|
||||||
|
}
|
||||||
|
|
||||||
|
getUser(): User {
|
||||||
|
return this.user;
|
||||||
|
}
|
||||||
|
|
||||||
|
getFs(): VirtualFS {
|
||||||
|
return this.vfs;
|
||||||
|
}
|
||||||
|
|
||||||
|
getProcess(): Process | ExitCode.ERROR {
|
||||||
|
if (this._process) {
|
||||||
|
return this._process;
|
||||||
|
}
|
||||||
|
return ExitCode.ERROR;
|
||||||
|
}
|
||||||
|
|
||||||
|
getProcessKeybindInhibitor(): KeybindInhibitor | null {
|
||||||
|
if (this._process) {
|
||||||
|
return this._process.getKeybindInhibitor();
|
||||||
|
} else return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
getTerminalWidth(): number {
|
||||||
|
return this._terminal.getTerminalWidth();
|
||||||
|
}
|
||||||
|
|
||||||
|
getTerminalFontSize(): number {
|
||||||
|
return this._terminal.getFontSize();
|
||||||
|
}
|
||||||
|
|
||||||
|
hasSudoPerms(uid: number): boolean {
|
||||||
|
return this._group[0].members.includes(uid);
|
||||||
|
}
|
||||||
|
|
||||||
|
async executeCommand(commandName: string, args: CommandArgs): Promise<Result> {
|
||||||
|
let result: Result = { exitCode: ExitCode.ERROR, path: this.getCwd() };
|
||||||
|
const command: ICommand = this._commands[commandName];
|
||||||
|
|
||||||
|
if (!command) this.throwError(result);
|
||||||
|
|
||||||
|
if (command.root) {
|
||||||
|
if (this.hasSudoPerms(this.user.uid)) {
|
||||||
|
await this._initNewProcess(command, args);
|
||||||
|
if (!this._process) throw new Error('failed to init new process');
|
||||||
|
|
||||||
|
const out: Result = await this._process.getResult();
|
||||||
|
this._appendNewResult(this.getCwd(), out, this.user.history[0]);
|
||||||
|
}
|
||||||
|
this.throwError(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
await this._initNewProcess(command, args);
|
||||||
|
if (!this._process) throw new Error('failed to init new process');
|
||||||
|
|
||||||
|
const out: Result = await this._process.getResult();
|
||||||
|
console.log(out);
|
||||||
|
this._appendNewResult(out.path, out.resultData?.data, this.user.history[0]);
|
||||||
|
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
static testMethod() {
|
||||||
|
//
|
||||||
|
}
|
||||||
|
|
||||||
|
throwError(result: Result): void {
|
||||||
|
switch (result.exitCode) {
|
||||||
|
default: {
|
||||||
|
throw new Error(`Error, dont know where, just look for it;`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
userLogout() {
|
||||||
|
this._userInstances.pop();
|
||||||
|
if (this._userInstances.size() === 0) {
|
||||||
|
//TODO: Implement system logout
|
||||||
|
} else {
|
||||||
|
//this.changeUser(this._instances.peek()!);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
userLogin(username: string, passwd: string): ExitCode {
|
||||||
|
const user: User | undefined = this._passwd.find((user) => user.username === username);
|
||||||
|
|
||||||
|
if (user && user.passwd === passwd) {
|
||||||
|
this._initNewUserSession(user);
|
||||||
|
return ExitCode.SUCCESS;
|
||||||
|
}
|
||||||
|
return ExitCode.ERROR;
|
||||||
|
}
|
||||||
|
|
||||||
|
formatBytes(bytes: number, dPoint?: number, pow: 1024 | 1000 = 1024): string {
|
||||||
|
if (!+bytes) return '0';
|
||||||
|
|
||||||
|
const k: number = pow;
|
||||||
|
const dp: number = dPoint ? (dPoint < 0 ? 0 : dPoint) : 1;
|
||||||
|
const units: string[] = ['', 'K', 'M', 'G', 'T', 'P'];
|
||||||
|
|
||||||
|
const i: number = Math.floor(Math.log(bytes) / Math.log(k));
|
||||||
|
|
||||||
|
return `${(bytes / Math.pow(k, i)).toFixed(dp)}${units[i]}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
getGroupByName(name: string): Group {
|
||||||
|
const out: Group | undefined = this._group.find((group) => group.groupname === name);
|
||||||
|
|
||||||
|
if (out) return out;
|
||||||
|
else throw new Error(`Cannot find a user group named ${name}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
getUserByName(name: string): User {
|
||||||
|
const out: User | undefined = this._passwd.find((user) => user.username === name);
|
||||||
|
|
||||||
|
if (out) return out;
|
||||||
|
else throw new Error(`Cannot find a user named ${name}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
getGroupByGid(gid: number): Group {
|
||||||
|
const out: Group | undefined = this._group.find((group) => group.gid === gid);
|
||||||
|
|
||||||
|
if (out) return out;
|
||||||
|
else throw new Error(`Cannot find a user group with id of ${gid}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
getUserByUid(uid: number): User {
|
||||||
|
const out: User | undefined = this._passwd.find((user) => user.uid === uid);
|
||||||
|
|
||||||
|
if (out) return out;
|
||||||
|
else throw new Error(`Cannot find a user with id of ${uid}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,153 @@
|
|||||||
|
import { WebG } from '$lib/shimagic/renderer/web_g_engine';
|
||||||
|
import type { KeyBind } from '../terminal/keybindRegistry';
|
||||||
|
import type { Bash, Result } from './bash';
|
||||||
|
import { cd } from './commands/cd';
|
||||||
|
import { clear } from './commands/clear';
|
||||||
|
import { ls } from './commands/ls';
|
||||||
|
import { testProcess } from './commands/testAsync';
|
||||||
|
|
||||||
|
export type ICommand = {
|
||||||
|
method: (this: Bash, args: CommandArgs) => Result;
|
||||||
|
keybinds?: Map<KeyBind, () => any>;
|
||||||
|
flags: string[];
|
||||||
|
help: string;
|
||||||
|
root: boolean;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type CommandArgs = {
|
||||||
|
flags: string[];
|
||||||
|
args: string[];
|
||||||
|
};
|
||||||
|
|
||||||
|
export type CommandResultData = {
|
||||||
|
cmd: string; //the string that contains the shorthand for the command that was executed - used in a switch statement in parseResult
|
||||||
|
data: any; //the data that the commmand may have returned like TreeNodes[] from ls
|
||||||
|
args?: CommandArgs;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const COMMANDS = {
|
||||||
|
cd,
|
||||||
|
ls,
|
||||||
|
clear,
|
||||||
|
testProcess
|
||||||
|
} as const satisfies Record<string, ICommand>;
|
||||||
|
|
||||||
|
|
||||||
|
WebG.
|
||||||
|
/* //export const commands {
|
||||||
|
return: {
|
||||||
|
method: this.cmd_return,
|
||||||
|
flags: [],
|
||||||
|
help: "Help about this command",
|
||||||
|
},
|
||||||
|
ls: {
|
||||||
|
method: this.cmd_ls,
|
||||||
|
flags: [],
|
||||||
|
help: "./help/ls.md",
|
||||||
|
},
|
||||||
|
echo: {
|
||||||
|
method: this.cmd_echo,
|
||||||
|
flags: [],
|
||||||
|
help: "",
|
||||||
|
},
|
||||||
|
touch: {
|
||||||
|
method: this.cmd_touch,
|
||||||
|
flags: [],
|
||||||
|
help: "",
|
||||||
|
},
|
||||||
|
mkdir: {
|
||||||
|
method: this.cmd_mkdir,
|
||||||
|
flags: [],
|
||||||
|
help: "",
|
||||||
|
},
|
||||||
|
pwd: {
|
||||||
|
method: this.cmd_pwd,
|
||||||
|
flags: [],
|
||||||
|
help: "",
|
||||||
|
},
|
||||||
|
cd: {
|
||||||
|
method: this.cmd_cd,
|
||||||
|
flags: [],
|
||||||
|
help: "",
|
||||||
|
},
|
||||||
|
exit: {
|
||||||
|
method: this.cmd_exit,
|
||||||
|
flags: [],
|
||||||
|
help: "",
|
||||||
|
},
|
||||||
|
cp: {
|
||||||
|
method: this.cmd_cp,
|
||||||
|
flags: [],
|
||||||
|
help: "",
|
||||||
|
},
|
||||||
|
mv: {
|
||||||
|
method: this.cmd_mv,
|
||||||
|
flags: [],
|
||||||
|
help: "",
|
||||||
|
},
|
||||||
|
rmdir: {
|
||||||
|
method: this.cmd_rmdir,
|
||||||
|
flags: [],
|
||||||
|
help: "",
|
||||||
|
},
|
||||||
|
cat: {
|
||||||
|
method: this.cmd_cat,
|
||||||
|
flags: [],
|
||||||
|
help: "",
|
||||||
|
},
|
||||||
|
dir: {
|
||||||
|
method: this.cmd_dir,
|
||||||
|
flags: [],
|
||||||
|
help: "",
|
||||||
|
},
|
||||||
|
less: {
|
||||||
|
method: this.cmd_less,
|
||||||
|
flags: [],
|
||||||
|
help: "",
|
||||||
|
},
|
||||||
|
chown: {
|
||||||
|
method: this.cmd_chown,
|
||||||
|
flags: [],
|
||||||
|
help: "",
|
||||||
|
},
|
||||||
|
chmod: {
|
||||||
|
method: this.cmd_chmod,
|
||||||
|
flags: [],
|
||||||
|
help: "",
|
||||||
|
},
|
||||||
|
reboot: {
|
||||||
|
method: this.cmd_reboot,
|
||||||
|
flags: [],
|
||||||
|
help: "",
|
||||||
|
},
|
||||||
|
help: {
|
||||||
|
method: this.cmd_help,
|
||||||
|
flags: [],
|
||||||
|
help: "",
|
||||||
|
},
|
||||||
|
whoami: {
|
||||||
|
method: this.cmd_whoami,
|
||||||
|
flags: [],
|
||||||
|
help: "",
|
||||||
|
},
|
||||||
|
rm: {
|
||||||
|
method: this.cmd_rm,
|
||||||
|
flags: [],
|
||||||
|
help: "",
|
||||||
|
},
|
||||||
|
sudo: {
|
||||||
|
method: this.cmd_sudo,
|
||||||
|
flags: [],
|
||||||
|
help: "",
|
||||||
|
},
|
||||||
|
su: {
|
||||||
|
method: this.cmd_su,
|
||||||
|
flags: [],
|
||||||
|
help: "",
|
||||||
|
},
|
||||||
|
clear: {
|
||||||
|
method: this.cmd_clear,
|
||||||
|
flags: [],
|
||||||
|
help: "",
|
||||||
|
}
|
||||||
|
} */
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
import type { Bash, Result } from '../bash';
|
||||||
|
import type { CommandArgs, ICommand } from '../commandRegistry';
|
||||||
|
import { Type, type TreeNode } from '../fs';
|
||||||
|
import { ExitCode } from '../metadata';
|
||||||
|
|
||||||
|
export const cmd_cd = function (this: Bash, args: CommandArgs): Result {
|
||||||
|
let result: Result = { exitCode: ExitCode.ERROR, path: this.getCwd() };
|
||||||
|
const path = args.args[0];
|
||||||
|
let targetNode: TreeNode | null;
|
||||||
|
|
||||||
|
if (args.args.length > 1) return result; // Too many args
|
||||||
|
|
||||||
|
// if no args cd into home dir
|
||||||
|
|
||||||
|
if (args.args.length === 0) {
|
||||||
|
this.getFs().cwd = this.getFs().home;
|
||||||
|
result.exitCode = ExitCode.SUCCESS;
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
// if the arg is - cd make your current dir the prev dir and vice versa
|
||||||
|
|
||||||
|
if (args.args[0] === '-') {
|
||||||
|
[this.getFs().cwd, this.getFs().pwd] = [this.getFs().pwd, this.getFs().cwd];
|
||||||
|
|
||||||
|
result.exitCode = ExitCode.SUCCESS;
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.getFs().pwd = this.getFs().cwd;
|
||||||
|
targetNode = this.getFs().resolvePath(path); // Conversion from STRING path to TREENODE
|
||||||
|
console.log(targetNode, path, 'CD OUTPUT');
|
||||||
|
|
||||||
|
if (targetNode === null) return result;
|
||||||
|
if (targetNode.type !== Type.Directory) return result;
|
||||||
|
//if () return ExitCode.ERROR; // Check for read permissions on node and user
|
||||||
|
|
||||||
|
this.getFs().cwd = targetNode.inode; // CD was successfull, change current dir to the verified target dir
|
||||||
|
result.exitCode = ExitCode.SUCCESS;
|
||||||
|
return result;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const cd: ICommand = {
|
||||||
|
method: cmd_cd,
|
||||||
|
flags: [] as string[],
|
||||||
|
help: 'PATH TO HELP.md',
|
||||||
|
root: false
|
||||||
|
};
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
import { type Bash, type Result } from "../bash";
|
||||||
|
import type { CommandArgs, ICommand } from "../commandRegistry";
|
||||||
|
import { ExitCode } from "../metadata";
|
||||||
|
|
||||||
|
export const cmd_clear = function(this: Bash, args: CommandArgs): Result {
|
||||||
|
let result: Result = { exitCode: ExitCode.ERROR, path: this.getCwd() };
|
||||||
|
this.clearTerminal();
|
||||||
|
result.exitCode = ExitCode.SUCCESS;
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const clear: ICommand = {
|
||||||
|
method: cmd_clear,
|
||||||
|
flags: [] as string[],
|
||||||
|
help: 'PATH TO HELP.md',
|
||||||
|
root: false
|
||||||
|
};
|
||||||
@@ -0,0 +1,426 @@
|
|||||||
|
import type { Bash, Result } from '../bash';
|
||||||
|
import type { CommandArgs, CommandResultData, ICommand } from '../commandRegistry';
|
||||||
|
import { Type, VirtualFS, type NodePerms, type TreeNode } from '../fs';
|
||||||
|
import { ExitCode, type Permission } from '../metadata';
|
||||||
|
import { Sort, SortNodeBy } from '../sort';
|
||||||
|
|
||||||
|
type LsEntry = {
|
||||||
|
inode: number | null;
|
||||||
|
perms: string;
|
||||||
|
children: string;
|
||||||
|
owners: string;
|
||||||
|
size: string;
|
||||||
|
modt: string;
|
||||||
|
name: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
const LsEntryUtils = {
|
||||||
|
toString(entry: LsEntry): string {
|
||||||
|
return Object.entries(entry)
|
||||||
|
.filter(([_, value]) => value !== '')
|
||||||
|
.map(([_, value]) => value)
|
||||||
|
.join(' ').trimStart();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const months: readonly string[] = [
|
||||||
|
'Jan',
|
||||||
|
'Feb',
|
||||||
|
'Mar',
|
||||||
|
'Apr',
|
||||||
|
'May',
|
||||||
|
'Jun',
|
||||||
|
'Jul',
|
||||||
|
'Aug',
|
||||||
|
'Sep',
|
||||||
|
'Oct',
|
||||||
|
'Nov',
|
||||||
|
'Dec'
|
||||||
|
];
|
||||||
|
|
||||||
|
export const cmd_ls = function (this: Bash, args: CommandArgs): Result {
|
||||||
|
const Fs = this.getFs();
|
||||||
|
const resultData: CommandResultData = { cmd: 'ls', data: null, args: args };
|
||||||
|
const result: Result = { exitCode: ExitCode.ERROR, path: this.getCwd(), resultData: resultData };
|
||||||
|
const nodes: TreeNode[] = [];
|
||||||
|
|
||||||
|
//Check if any args contain the long flags with value and are valid flags inside the ls const
|
||||||
|
const valuedArgs = args.flags.filter((flag: string) =>
|
||||||
|
flag.includes('=') && ls.flags.includes(flag.split('=')[0]));
|
||||||
|
console.log(valuedArgs);
|
||||||
|
|
||||||
|
//Check if args contain any nonexistent flags, if so add it to an array and check its length. if 0 no bad flags
|
||||||
|
const invalidArgs = args.flags.filter((flag) => !ls.flags.includes(flag) && !valuedArgs.includes(flag));
|
||||||
|
console.log(invalidArgs);
|
||||||
|
|
||||||
|
if (invalidArgs.length > 0) {
|
||||||
|
this.throwError(result); //No such flag/s
|
||||||
|
}
|
||||||
|
|
||||||
|
if (args.args.length === 0) nodes.push(Fs.getNodeByINode(Fs.cwd));
|
||||||
|
|
||||||
|
for (let i = 0; i < args.args.length; i++) {
|
||||||
|
const node = Fs.resolvePath(args.args[i]);
|
||||||
|
if (node === null) this.throwError(result); //no such path (i think this will never occur as backed methods have error cases implemented - which is wrong)
|
||||||
|
|
||||||
|
nodes.push(node);
|
||||||
|
}
|
||||||
|
|
||||||
|
result.exitCode = ExitCode.SUCCESS;
|
||||||
|
resultData.data = result_ls.call(this, nodes, args);
|
||||||
|
return result;
|
||||||
|
};
|
||||||
|
|
||||||
|
function result_ls(this: Bash, data: any, args: CommandArgs): HTMLElement {
|
||||||
|
const Fs: VirtualFS = this.getFs();
|
||||||
|
|
||||||
|
const flagInfo = checkFlags(args.flags);
|
||||||
|
const nodes: TreeNode[] = data;
|
||||||
|
let nodeIndex: number = 0;
|
||||||
|
|
||||||
|
const f_a: boolean = flagInfo.has('a') || flagInfo.has('all');
|
||||||
|
const f_A: boolean = flagInfo.has('A') || flagInfo.has('almost-all');
|
||||||
|
//const f_G: boolean = flagInfo.has('G') || flagInfo.has('no-group');
|
||||||
|
const f_h: boolean = flagInfo.has('h') || flagInfo.has('human-readable');
|
||||||
|
const f_r: boolean = flagInfo.has('r') || flagInfo.has('reverse');
|
||||||
|
const f_R: boolean = flagInfo.has('R') || flagInfo.has('recursive');
|
||||||
|
//const f_Q: boolean = flagInfo.has('Q') || flagInfo.has('quote-name');
|
||||||
|
//const f_n: boolean = flagInfo.has('n') || flagInfo.has('numeric-uid-gid');
|
||||||
|
//const f_N: boolean = flagInfo.has('N') || flagInfo.has('literal');
|
||||||
|
//const f_L: boolean = flagInfo.has('L') || flagInfo.has('dereference');
|
||||||
|
const f_i: boolean = flagInfo.has('i') || flagInfo.has('inode');
|
||||||
|
//const f_help: boolean = flagInfo.has('help');
|
||||||
|
const f_si: boolean = flagInfo.has('si');
|
||||||
|
const f_X: boolean = flagInfo.has('X');
|
||||||
|
const f_S: boolean = flagInfo.has('S');
|
||||||
|
const f_t: boolean = flagInfo.has('t');
|
||||||
|
const f_l: boolean = flagInfo.has('l');
|
||||||
|
const f_U: boolean = flagInfo.has('U');
|
||||||
|
const f_f: boolean = flagInfo.has('f');
|
||||||
|
const f_g: boolean = flagInfo.has('g');
|
||||||
|
const f_o: boolean = flagInfo.has('o');
|
||||||
|
|
||||||
|
const valuedArgs = args.flags.filter((flag: string) =>
|
||||||
|
flag.includes('=') && ls.flags.includes(flag.split('=')[0]));
|
||||||
|
|
||||||
|
const w: HTMLElement = document.createElement('div');
|
||||||
|
|
||||||
|
if(f_R) {
|
||||||
|
const treeWalkResult: TreeNode[] = [];
|
||||||
|
const treeWalkCallback = (node: TreeNode) => { treeWalkResult.push(node); }
|
||||||
|
|
||||||
|
for(const node of nodes) {
|
||||||
|
treeWalkResult.push(node);
|
||||||
|
Fs.recursiveTraversalPre(node, treeWalkCallback);
|
||||||
|
}
|
||||||
|
nodes.length = 0;
|
||||||
|
nodes.push(...treeWalkResult.filter((node) => node.type != Type.File));
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const node of nodes) {
|
||||||
|
const elem: HTMLElement = document.createElement('div');
|
||||||
|
const childrenMap: TreeNode[] = node.children.map((child) => Fs.getNodeByINode(child));
|
||||||
|
|
||||||
|
const children: TreeNode[] = (f_a || f_A)
|
||||||
|
? childrenMap
|
||||||
|
: childrenMap.filter((child) => !child.name.startsWith('.'));
|
||||||
|
|
||||||
|
const timeArg = valuedArgs.find((flag) => flag.startsWith('time'));
|
||||||
|
const shouldNamesShift: boolean = children.some((child) => child.name.match(/\s/) !== null);
|
||||||
|
let timestamp: SortNodeBy.ATIME | SortNodeBy.CTIME | SortNodeBy.MTIME = SortNodeBy.MTIME;
|
||||||
|
|
||||||
|
if(f_a && !f_A) {
|
||||||
|
const current: TreeNode = node;
|
||||||
|
current.name = '.';
|
||||||
|
|
||||||
|
const parent: TreeNode = Fs.getNodeByINode(node.parent);
|
||||||
|
parent.name = '..';
|
||||||
|
|
||||||
|
children.unshift(current, parent);
|
||||||
|
}
|
||||||
|
|
||||||
|
if(timeArg) {
|
||||||
|
let value: string = timeArg.split('=')[1];
|
||||||
|
if (value && isValidNodeTimestamp(value)) timestamp = value;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!f_U && !f_f) {
|
||||||
|
const sortArg = valuedArgs.find((flag) => flag.startsWith('sort'));
|
||||||
|
let sortBy: SortNodeBy = SortNodeBy.NAME;
|
||||||
|
|
||||||
|
if(f_t) sortBy = timestamp;
|
||||||
|
if(f_S) sortBy = SortNodeBy.SIZE;
|
||||||
|
if(f_X) sortBy = SortNodeBy.EXTENSION;
|
||||||
|
|
||||||
|
if(sortArg) {
|
||||||
|
let value = sortArg.split('=')[1];
|
||||||
|
if(value && isValidNodeSortMethod(value)) sortBy = value;
|
||||||
|
}
|
||||||
|
|
||||||
|
Sort.nodeArraySort.call(this, children, f_r, sortBy);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (f_l || f_g || f_o) {
|
||||||
|
const rows: string[] = [];
|
||||||
|
const maxSizeWidth = Math.max(
|
||||||
|
...children.map((child) => child.size.toString().length));
|
||||||
|
|
||||||
|
for (const child of children) {
|
||||||
|
const entry: LsEntry = {
|
||||||
|
inode: null,
|
||||||
|
perms: formatPermission(child),
|
||||||
|
children: formatChildren(child),
|
||||||
|
owners: formatOwners.call(this, child, flagInfo),
|
||||||
|
size: formatSize.call(this, f_h, child, maxSizeWidth, f_si),
|
||||||
|
modt: formatModtime(child, timestamp),
|
||||||
|
name: formatName(child, flagInfo, shouldNamesShift)
|
||||||
|
};
|
||||||
|
|
||||||
|
if (f_i) entry.inode = child.inode;
|
||||||
|
|
||||||
|
rows.push(LsEntryUtils.toString(entry));
|
||||||
|
}
|
||||||
|
|
||||||
|
//TODO: Calculate the total size of contents in the node
|
||||||
|
rows.unshift('total ' + node.children.length.toString());
|
||||||
|
|
||||||
|
if (nodes.length > 1) {
|
||||||
|
const nodePath: HTMLElement = document.createElement('p');
|
||||||
|
nodePath.innerText = `${Fs.getPathByInode(node.inode)}:`;
|
||||||
|
w.appendChild(nodePath);
|
||||||
|
if(nodeIndex +1 < nodes.length) elem.style.marginBottom = `${this.getTerminalFontSize() * 2}px`;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (let i = 0; i < rows.length; i++) {
|
||||||
|
const p: HTMLElement = document.createElement('p');
|
||||||
|
p.innerText = rows[i];
|
||||||
|
elem.appendChild(p);
|
||||||
|
}
|
||||||
|
w.appendChild(elem);
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
const maxWidth: number = Math.ceil((this.getTerminalWidth() / this.getTerminalFontSize()) * 0.8);
|
||||||
|
|
||||||
|
let columns: string[][] = [];
|
||||||
|
let colWidths: number[];
|
||||||
|
let lowBound: number = 1;
|
||||||
|
let highBound: number = children.length;
|
||||||
|
|
||||||
|
while(lowBound + 1 < highBound) {
|
||||||
|
const c = lowBound + (highBound - lowBound) / 2;
|
||||||
|
|
||||||
|
columns = [];
|
||||||
|
colWidths = [];
|
||||||
|
let fileIndex = 0;
|
||||||
|
|
||||||
|
for(let i = 0; i < c; i++) {
|
||||||
|
if(fileIndex >= children.length) break;
|
||||||
|
columns[i] = [];
|
||||||
|
for(let j = 0; j < Math.ceil(children.length / c); j++) {
|
||||||
|
if(fileIndex >= children.length) break;
|
||||||
|
columns[i].push(children[fileIndex].name);
|
||||||
|
fileIndex++;
|
||||||
|
}
|
||||||
|
colWidths.push(Math.max(...columns[i].map((name) => name.length)));
|
||||||
|
}
|
||||||
|
|
||||||
|
const calcWidth: number = colWidths.reduce((prev, curr) => prev + curr) + ((c-1) * 2);
|
||||||
|
|
||||||
|
if(calcWidth < maxWidth) lowBound = c + 1;
|
||||||
|
else if(calcWidth > maxWidth) highBound = c -1
|
||||||
|
}
|
||||||
|
|
||||||
|
const wrapper: HTMLElement = document.createElement('div');
|
||||||
|
|
||||||
|
wrapper.style.display = 'flex';
|
||||||
|
wrapper.style.columnGap = `${this.getTerminalFontSize() * 2}px`;
|
||||||
|
wrapper.style.marginBottom = `${this.getTerminalFontSize() * 2}px`;
|
||||||
|
|
||||||
|
let fileIndex = 0;
|
||||||
|
|
||||||
|
for(let i = 0; i < lowBound; i++) {
|
||||||
|
if(fileIndex >= children.length) break;
|
||||||
|
const col: HTMLElement = document.createElement('div');
|
||||||
|
|
||||||
|
for(let j = 0; j < Math.ceil(children.length / lowBound); j++) {
|
||||||
|
if(fileIndex >= children.length) break;
|
||||||
|
|
||||||
|
const entry: HTMLElement = document.createElement('p');
|
||||||
|
|
||||||
|
entry.innerText = formatName(children[fileIndex], flagInfo, shouldNamesShift);
|
||||||
|
col.appendChild(entry);
|
||||||
|
fileIndex++;
|
||||||
|
}
|
||||||
|
wrapper.appendChild(col);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (nodes.length > 1) {
|
||||||
|
const nodePath: HTMLElement = document.createElement('p');
|
||||||
|
nodePath.innerText = `${Fs.getPathByInode(node.inode)}`;
|
||||||
|
w.appendChild(nodePath);
|
||||||
|
}
|
||||||
|
|
||||||
|
w.appendChild(wrapper);
|
||||||
|
}
|
||||||
|
nodeIndex++;
|
||||||
|
}
|
||||||
|
return w;
|
||||||
|
}
|
||||||
|
|
||||||
|
function isValidNodeSortMethod(value: string): value is SortNodeBy {
|
||||||
|
return Object.values(SortNodeBy).includes(value as SortNodeBy);
|
||||||
|
}
|
||||||
|
|
||||||
|
function isValidNodeTimestamp(value: string): value is SortNodeBy.ATIME | SortNodeBy.CTIME | SortNodeBy.MTIME {
|
||||||
|
return Object.values(SortNodeBy).includes(value as SortNodeBy.ATIME | SortNodeBy.CTIME | SortNodeBy.MTIME);
|
||||||
|
}
|
||||||
|
|
||||||
|
function parsePerms(perms: NodePerms): string {
|
||||||
|
const parts: string[] = [];
|
||||||
|
//for each key (key representing key name and p representing the key contents) of entries in perms as types keyof NodePerms and Permission
|
||||||
|
for (const [, permission] of Object.entries(perms) as [keyof NodePerms, Permission][]) {
|
||||||
|
const perms: string = `${permission.r ? 'r' : '-'}${permission.w ? 'w' : '-'}${permission.x ? 'x' : '-'}`;
|
||||||
|
parts.push(perms);
|
||||||
|
}
|
||||||
|
return parts.join('');
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatOwners(this: Bash, node: TreeNode, flag: any): string {
|
||||||
|
const owner: string = this.getUserByUid(node.owner).username;
|
||||||
|
const group: string = this.getGroupByGid(node.group).groupname;
|
||||||
|
|
||||||
|
if (flag.has('G') || flag.has('o')) {
|
||||||
|
if (flag.has('n')) return `${node.owner}`;
|
||||||
|
return `${owner}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (flag.has('g')) {
|
||||||
|
if (flag.has('n')) return `${node.group}`;
|
||||||
|
return `${group}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (flag.has('n')) return `${node.owner} ${node.group}`;
|
||||||
|
|
||||||
|
return `${owner} ${group}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatPermission(node: TreeNode): string {
|
||||||
|
switch(node.type) {
|
||||||
|
case Type.Directory:
|
||||||
|
return `d${parsePerms(node.permission)}`;
|
||||||
|
case Type.File:
|
||||||
|
return `-${parsePerms(node.permission)}`;
|
||||||
|
case Type.SymbolicLink:
|
||||||
|
return `l${parsePerms(node.permission)}`;
|
||||||
|
default:
|
||||||
|
throw new Error(`Node of unexpected type - ${node.type}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatChildren(node: TreeNode): string {
|
||||||
|
if (node.type !== Type.Directory) return ' 0';
|
||||||
|
if (!node.children) throw new Error('children array is null on this node');
|
||||||
|
|
||||||
|
const c = node.children.length.toString();
|
||||||
|
return c.length > 1 ? c : ` ${c}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatSize(
|
||||||
|
this: Bash,
|
||||||
|
humanReadable: boolean,
|
||||||
|
node: TreeNode,
|
||||||
|
max: number,
|
||||||
|
f_si: boolean
|
||||||
|
): string {
|
||||||
|
let size: string;
|
||||||
|
if (humanReadable) {
|
||||||
|
size = this.formatBytes(node.size, 1, f_si ? 1000 : 1024);
|
||||||
|
} else size = node.size.toString();
|
||||||
|
|
||||||
|
return size.padStart(max, ' ');
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatModtime(node: TreeNode, sortBy: SortNodeBy.ATIME | SortNodeBy.CTIME | SortNodeBy.MTIME): string {
|
||||||
|
const now = new Date();
|
||||||
|
//TODO: Change this to be dynamic based on the --time value passed
|
||||||
|
const hours: string = node.timestamps[sortBy].getHours().toString().padStart(2, '0');
|
||||||
|
const minutes: string = node.timestamps[sortBy].getMinutes().toString().padStart(2, '0');
|
||||||
|
const time: string =
|
||||||
|
now.getFullYear() === node.timestamps[sortBy].getFullYear()
|
||||||
|
? `${hours}:${minutes}`
|
||||||
|
: node.timestamps[sortBy].getFullYear().toString();
|
||||||
|
|
||||||
|
return [
|
||||||
|
months[node.timestamps[sortBy].getMonth()],
|
||||||
|
node.timestamps[sortBy].getDate().toString().padStart(2, ' '),
|
||||||
|
`${time}`
|
||||||
|
].join(' ');
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatName(node: TreeNode, flag: any, shouldShift: boolean) {
|
||||||
|
let name: string = node.name;
|
||||||
|
const char: string = flag.has('Q') ? '"' : "'";
|
||||||
|
|
||||||
|
if (/\s/.test(node.name)) {
|
||||||
|
name = `${char}${name}${char}`
|
||||||
|
} else {
|
||||||
|
//Shift non quoted names 1 char right to align if any names in group have a quote
|
||||||
|
name = `${shouldShift ? ' ' : ''}${node.name}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
return flag.has('p') && node.type === Type.Directory ? `${name}/` : name;
|
||||||
|
}
|
||||||
|
|
||||||
|
const checkFlags = (pFlags: string[]) => {
|
||||||
|
const flagSet = new Set(pFlags);
|
||||||
|
|
||||||
|
return { has: (flag: string) => flagSet.has(flag) };
|
||||||
|
};
|
||||||
|
|
||||||
|
export const ls: ICommand = {
|
||||||
|
method: cmd_ls,
|
||||||
|
flags: [
|
||||||
|
'l',
|
||||||
|
'a',
|
||||||
|
'A',
|
||||||
|
'c',
|
||||||
|
'U',
|
||||||
|
'g',
|
||||||
|
'G',
|
||||||
|
'h',
|
||||||
|
'f',
|
||||||
|
'x',
|
||||||
|
'X',
|
||||||
|
'u',
|
||||||
|
't',
|
||||||
|
'S',
|
||||||
|
'r',
|
||||||
|
'R',
|
||||||
|
'Q',
|
||||||
|
'p',
|
||||||
|
'o',
|
||||||
|
'n',
|
||||||
|
'N',
|
||||||
|
'L',
|
||||||
|
'm',
|
||||||
|
'i',
|
||||||
|
'sort',
|
||||||
|
'time',
|
||||||
|
'help',
|
||||||
|
'all',
|
||||||
|
'almost-all',
|
||||||
|
'no-group',
|
||||||
|
'human-readable',
|
||||||
|
'reverse',
|
||||||
|
'recursive',
|
||||||
|
'quote-name',
|
||||||
|
'indicator-style',
|
||||||
|
'literal',
|
||||||
|
'numeric-uid-gid',
|
||||||
|
'inode',
|
||||||
|
'si',
|
||||||
|
'dereference'
|
||||||
|
] as string[],
|
||||||
|
help: 'PATH TO HELP.MD',
|
||||||
|
root: false
|
||||||
|
};
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
import type { KeyBind } from "$lib/stores/terminal/keybindRegistry";
|
||||||
|
import { mount } from "svelte";
|
||||||
|
import { type Bash, type Result } from "../bash";
|
||||||
|
import type { CommandArgs, CommandResultData, ICommand } from "../commandRegistry";
|
||||||
|
import { ExitCode } from "../metadata";
|
||||||
|
import Login from "../../../../modules/Login.svelte";
|
||||||
|
import Loading from "../../../../modules/Loading.svelte";
|
||||||
|
|
||||||
|
export const cmd_process = function(this: Bash, args: CommandArgs): Result {
|
||||||
|
let result: Result = { exitCode: ExitCode.ERROR, path: this.getCwd() };
|
||||||
|
const resultData: CommandResultData = { cmd: 'ls', data: null, args: args };
|
||||||
|
|
||||||
|
result.resultData = resultData;
|
||||||
|
result.exitCode = ExitCode.SUCCESS;
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
const test_keybind: KeyBind = [
|
||||||
|
{
|
||||||
|
key: 'a',
|
||||||
|
modifiers: [
|
||||||
|
'Shift'
|
||||||
|
]
|
||||||
|
}
|
||||||
|
];
|
||||||
|
|
||||||
|
function test(): void {
|
||||||
|
console.log("Keybind works");
|
||||||
|
}
|
||||||
|
|
||||||
|
const keybinds: Map<KeyBind, () => any> = new Map([
|
||||||
|
[test_keybind,test]
|
||||||
|
]);
|
||||||
|
|
||||||
|
export const testProcess: ICommand = {
|
||||||
|
method: cmd_process,
|
||||||
|
keybinds: keybinds,
|
||||||
|
flags: [] as string[],
|
||||||
|
help: 'PATH TO HELP.md',
|
||||||
|
root: false
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
export type Group = {
|
||||||
|
groupname: string;
|
||||||
|
gid: number; // Primary group 'Users' 1000 - Others - 1000+ root - 0
|
||||||
|
members: number[]; //TODO: Make a formated type UID
|
||||||
|
};
|
||||||
|
|
||||||
|
export const GROUP: Group[] = [
|
||||||
|
{
|
||||||
|
groupname: 'sudo',
|
||||||
|
gid: 69,
|
||||||
|
members: [0, 1001]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
groupname: 'users',
|
||||||
|
gid: 984,
|
||||||
|
members: [1001, 1002]
|
||||||
|
}
|
||||||
|
] as const;
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
export type User = {
|
||||||
|
username: string;
|
||||||
|
passwd: string; //HASHED PASSWORD //TODO: Make a formated type
|
||||||
|
readonly uid: number; // Normal user 1000+ System user 1-999 root - 0 //TODO: Make a formated type
|
||||||
|
readonly gid: number; // Primary group | 'Users' 1000 - Others - 1000+ root - 0 //TODO: Make a formated type
|
||||||
|
home: string; //TODO: Make a formated type
|
||||||
|
accesible: boolean;
|
||||||
|
history: string[];
|
||||||
|
cwd?: number; //TODO: Make a formated type
|
||||||
|
pwd?: number; //TODO: Make a formated type
|
||||||
|
};
|
||||||
|
|
||||||
|
export const PASSWD: User[] = [
|
||||||
|
{
|
||||||
|
username: 'root',
|
||||||
|
passwd: '123',
|
||||||
|
uid: 0,
|
||||||
|
gid: 0,
|
||||||
|
home: '/',
|
||||||
|
accesible: false,
|
||||||
|
history: []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
username: 'admin',
|
||||||
|
passwd: '456',
|
||||||
|
uid: 1000,
|
||||||
|
gid: 1000,
|
||||||
|
home: '/home/admin',
|
||||||
|
accesible: true,
|
||||||
|
history: []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
username: 'user',
|
||||||
|
passwd: '789',
|
||||||
|
uid: 1001,
|
||||||
|
gid: 1000,
|
||||||
|
home: '/home/user',
|
||||||
|
accesible: true,
|
||||||
|
history: []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
username: 'gornodox',
|
||||||
|
passwd: '000',
|
||||||
|
uid: 1002,
|
||||||
|
gid: 1000,
|
||||||
|
home: '/home/gornodox',
|
||||||
|
accesible: true,
|
||||||
|
history: []
|
||||||
|
}
|
||||||
|
];
|
||||||
@@ -0,0 +1,217 @@
|
|||||||
|
import type { User } from './etc/userData';
|
||||||
|
import type { Permission, TimeStamps } from './metadata';
|
||||||
|
|
||||||
|
export enum Type {
|
||||||
|
Directory = 16384,
|
||||||
|
File = 32768,
|
||||||
|
SymbolicLink = 40960
|
||||||
|
}
|
||||||
|
|
||||||
|
export type NodePermission = {
|
||||||
|
user: Permission;
|
||||||
|
group: Permission;
|
||||||
|
other: Permission;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type FsInitArgs = {
|
||||||
|
fs: Map<number, TreeNode>;
|
||||||
|
user: User;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type TreeNode = {
|
||||||
|
inode: number;
|
||||||
|
parent: number;
|
||||||
|
name: string;
|
||||||
|
type: Type;
|
||||||
|
size: number; //Size in Bytes
|
||||||
|
children: number[];
|
||||||
|
content: string; // GUID of the cache file that contains the file contents.
|
||||||
|
link: number; // Links
|
||||||
|
permission: NodePerms;
|
||||||
|
owner: number;
|
||||||
|
group: number;
|
||||||
|
timestamps: TimeStamps;
|
||||||
|
interactible: boolean;
|
||||||
|
func: any;
|
||||||
|
};
|
||||||
|
|
||||||
|
export class VirtualFS {
|
||||||
|
private FsTable: Map<number, TreeNode>;
|
||||||
|
private rootINode: number;
|
||||||
|
private user: User;
|
||||||
|
|
||||||
|
home: number;
|
||||||
|
cwd: number;
|
||||||
|
pwd: number;
|
||||||
|
|
||||||
|
constructor(args: FsInitArgs) {
|
||||||
|
this.FsTable = args.fs;
|
||||||
|
this.user = args.user;
|
||||||
|
this.rootINode = 1;
|
||||||
|
|
||||||
|
this.home = this._pathStringToINode(args.user.home);
|
||||||
|
this.cwd = args.user.cwd ? args.user.cwd! : this.home;
|
||||||
|
this.pwd = args.user.pwd ? args.user.pwd! : this.cwd;
|
||||||
|
|
||||||
|
console.log(this.home);
|
||||||
|
console.log(this.cwd);
|
||||||
|
console.log(this.pwd);
|
||||||
|
}
|
||||||
|
|
||||||
|
private _iNodeToPathString(inode: number): string {
|
||||||
|
const currentNode = this.FsTable.get(inode);
|
||||||
|
|
||||||
|
if (!currentNode)
|
||||||
|
throw new Error('could not find the node in the fs table - inodetopathstring');
|
||||||
|
|
||||||
|
if (!currentNode.parent || currentNode.inode === this.rootINode) {
|
||||||
|
return '/';
|
||||||
|
}
|
||||||
|
|
||||||
|
const parentPath: string = this._iNodeToPathString(currentNode.parent);
|
||||||
|
return parentPath === '/' ? `/${currentNode.name}` : `${parentPath}/${currentNode.name}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
//TODO: Make all backend methods NOT throw errors. Just return null, and let more closely connected with bash functions call throwError() so user can see the error.
|
||||||
|
// this will save a lot of ass pain later.
|
||||||
|
|
||||||
|
private _pathStringToINode(path: string): number {
|
||||||
|
const normalizedPath = path.replace(/^\/+|\/+$/g, '');
|
||||||
|
const pathComponents = normalizedPath.split('/').filter((component) => component.length > 0);
|
||||||
|
|
||||||
|
console.log(path, 'pathstringtoinode');
|
||||||
|
|
||||||
|
if (pathComponents.length === 0) return this.rootINode;
|
||||||
|
|
||||||
|
let currentNode = this.FsTable.get(this.rootINode);
|
||||||
|
if (!currentNode) throw new Error('iNode does not exist,');
|
||||||
|
|
||||||
|
for (const component of pathComponents) {
|
||||||
|
const childINode = this._findChildNodeByName(currentNode, component);
|
||||||
|
if (childINode === null) throw new Error('this child iNode does not exist,');
|
||||||
|
|
||||||
|
const nextNode = this.FsTable.get(childINode);
|
||||||
|
if (!nextNode) throw new Error('iNode child does not exist,');
|
||||||
|
|
||||||
|
currentNode = nextNode;
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log(path, currentNode.inode);
|
||||||
|
return currentNode.inode;
|
||||||
|
}
|
||||||
|
|
||||||
|
private _findChildNodeByName(node: TreeNode, name: string): number {
|
||||||
|
console.log(name, node);
|
||||||
|
for (const childINode of node.children) {
|
||||||
|
const child = this.FsTable.get(childINode);
|
||||||
|
if (child && child.name === name) {
|
||||||
|
return childINode;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
throw new Error('could not find the specified child node');
|
||||||
|
}
|
||||||
|
|
||||||
|
private _isAbsolutePath = (path: string): boolean => {
|
||||||
|
return typeof path === 'string' && path.startsWith('/');
|
||||||
|
};
|
||||||
|
|
||||||
|
public getPathByInode(inode: number): string {
|
||||||
|
return this._iNodeToPathString(inode);
|
||||||
|
}
|
||||||
|
|
||||||
|
public formatPath(path: string): string {
|
||||||
|
console.log(path, 'formatPath');
|
||||||
|
const prefix = this._iNodeToPathString(this.home);
|
||||||
|
|
||||||
|
if (path.startsWith(prefix)) {
|
||||||
|
return path.replace(prefix, '~');
|
||||||
|
} else return path;
|
||||||
|
}
|
||||||
|
|
||||||
|
public resolvePath(path: string): TreeNode {
|
||||||
|
if (path === '/') return this.getNodeByINode(this.rootINode);
|
||||||
|
let parsedPath: string = path;
|
||||||
|
|
||||||
|
if (!this._isAbsolutePath(path)) {
|
||||||
|
const trail: string = this._iNodeToPathString(this.cwd);
|
||||||
|
parsedPath = `${trail}/${path}`;
|
||||||
|
console.log(parsedPath);
|
||||||
|
}
|
||||||
|
if (path.startsWith('~')) {
|
||||||
|
const trail: string = this._iNodeToPathString(this.home);
|
||||||
|
parsedPath = `${trail}/${path.replace('~', '')}`;
|
||||||
|
console.log(parsedPath);
|
||||||
|
}
|
||||||
|
|
||||||
|
const INode: number = this._pathStringToINode(parsedPath);
|
||||||
|
const Node: TreeNode = this.getNodeByINode(INode);
|
||||||
|
|
||||||
|
return Node;
|
||||||
|
}
|
||||||
|
|
||||||
|
public getNodeByINode(inode: number): TreeNode {
|
||||||
|
const node: TreeNode | undefined = this.FsTable.get(inode);
|
||||||
|
if (!node) throw new Error(`Could not get the node, no such inode exists - ${inode}`);
|
||||||
|
return node;
|
||||||
|
}
|
||||||
|
|
||||||
|
public recursiveTraversalPre(
|
||||||
|
node: TreeNode,
|
||||||
|
callback: (param: TreeNode) => void,
|
||||||
|
childIndex?: number[],
|
||||||
|
depthIndex?: number
|
||||||
|
): void {
|
||||||
|
if (!depthIndex) depthIndex = 0;
|
||||||
|
if (!childIndex) childIndex = [0];
|
||||||
|
|
||||||
|
if (node.type != Type.File && node.children[childIndex[depthIndex]]) {
|
||||||
|
node = this.getNodeByINode(node.children[childIndex[depthIndex]]);
|
||||||
|
depthIndex++;
|
||||||
|
if (!childIndex[depthIndex]) childIndex[depthIndex] = 0;
|
||||||
|
|
||||||
|
callback(node);
|
||||||
|
} else {
|
||||||
|
node = this.getNodeByINode(node.parent);
|
||||||
|
childIndex[depthIndex] = 0;
|
||||||
|
depthIndex--;
|
||||||
|
childIndex[depthIndex]++;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (depthIndex < 0) return;
|
||||||
|
|
||||||
|
this.recursiveTraversalPre(node, callback, childIndex, depthIndex);
|
||||||
|
}
|
||||||
|
|
||||||
|
private _createNode(name: string, type: Type, path: number, user: number): void {
|
||||||
|
let children: null | number[];
|
||||||
|
|
||||||
|
const node: TreeNode = {
|
||||||
|
inode: this.FsTable.size + 1,
|
||||||
|
name: name,
|
||||||
|
type: type,
|
||||||
|
size: 4096, //TODO: Calculate the size from the content
|
||||||
|
children: [],
|
||||||
|
content: '',
|
||||||
|
link: -1,
|
||||||
|
permission: {
|
||||||
|
user: {
|
||||||
|
r: true,
|
||||||
|
w: true,
|
||||||
|
x: false
|
||||||
|
},
|
||||||
|
group: {
|
||||||
|
r: true,
|
||||||
|
w: false,
|
||||||
|
x: false
|
||||||
|
},
|
||||||
|
other: {
|
||||||
|
r: true,
|
||||||
|
w: false,
|
||||||
|
x: false
|
||||||
|
}
|
||||||
|
},
|
||||||
|
owner: user,
|
||||||
|
group:
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
import type { KeyBind, Modifier } from "../terminal/keybindRegistry";
|
||||||
|
|
||||||
|
|
||||||
|
export class KeybindInhibitor{
|
||||||
|
private _keybinds: Map<KeyBind, () => any>;
|
||||||
|
|
||||||
|
constructor(keybinds: Map<KeyBind, () => any>) {
|
||||||
|
this._keybinds = keybinds;
|
||||||
|
}
|
||||||
|
|
||||||
|
private parseModifierStates(event: KeyboardEvent): Modifier[] | undefined {
|
||||||
|
const mods: Modifier[] = [];
|
||||||
|
|
||||||
|
if(event.altKey) mods.push('Alt');
|
||||||
|
if(event.ctrlKey) mods.push('Ctrl');
|
||||||
|
if(event.shiftKey) mods.push('Shift');
|
||||||
|
|
||||||
|
if(mods.length == 0) return undefined;
|
||||||
|
|
||||||
|
return mods;
|
||||||
|
}
|
||||||
|
|
||||||
|
processKeystroke(event: KeyboardEvent) {
|
||||||
|
const keybind: KeyBind = [
|
||||||
|
{
|
||||||
|
key: event.key,
|
||||||
|
modifiers: this.parseModifierStates(event)
|
||||||
|
}
|
||||||
|
];
|
||||||
|
|
||||||
|
const out = this._keybinds.get(keybind);
|
||||||
|
if(out) out();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
export type TimeStamps = {
|
||||||
|
modified: Date;
|
||||||
|
changed: Date;
|
||||||
|
accessed: Date;
|
||||||
|
};
|
||||||
|
|
||||||
|
// TODO: Finish this
|
||||||
|
export enum ExitCode {
|
||||||
|
SUCCESS = 0,
|
||||||
|
ERROR = 1
|
||||||
|
}
|
||||||
@@ -0,0 +1,78 @@
|
|||||||
|
export class Posix {
|
||||||
|
private static readonly CharTable = {
|
||||||
|
// Space and punctuation (32-47)
|
||||||
|
' ': 32,
|
||||||
|
'!': 33,
|
||||||
|
'"': 34,
|
||||||
|
'#': 35,
|
||||||
|
'$': 36,
|
||||||
|
'%': 37,
|
||||||
|
'&': 38,
|
||||||
|
"'": 39,
|
||||||
|
'(': 40,
|
||||||
|
')': 41,
|
||||||
|
'*': 42,
|
||||||
|
'+': 43,
|
||||||
|
',': 44,
|
||||||
|
'-': 45,
|
||||||
|
'.': 46,
|
||||||
|
'/': 47,
|
||||||
|
|
||||||
|
// Numbers 0-9 (48-57)
|
||||||
|
'0': 48, '1': 49, '2': 50, '3': 51, '4': 52,
|
||||||
|
'5': 53, '6': 54, '7': 55, '8': 56, '9': 57,
|
||||||
|
|
||||||
|
// More punctuation (58-64)
|
||||||
|
':': 58,
|
||||||
|
';': 59,
|
||||||
|
'<': 60,
|
||||||
|
'=': 61,
|
||||||
|
'>': 62,
|
||||||
|
'?': 63,
|
||||||
|
'@': 64,
|
||||||
|
|
||||||
|
// LETTERS - INTERLEAVED AaBbCc... (65-116)
|
||||||
|
'A': 65, 'a': 66,
|
||||||
|
'B': 67, 'b': 68,
|
||||||
|
'C': 69, 'c': 70,
|
||||||
|
'D': 71, 'd': 72,
|
||||||
|
'E': 73, 'e': 74,
|
||||||
|
'F': 75, 'f': 76,
|
||||||
|
'G': 77, 'g': 78,
|
||||||
|
'H': 79, 'h': 80,
|
||||||
|
'I': 81, 'i': 82,
|
||||||
|
'J': 83, 'j': 84,
|
||||||
|
'K': 85, 'k': 86,
|
||||||
|
'L': 87, 'l': 88,
|
||||||
|
'M': 89, 'm': 90,
|
||||||
|
'N': 91, 'n': 92,
|
||||||
|
'O': 93, 'o': 94,
|
||||||
|
'P': 95, 'p': 96,
|
||||||
|
'Q': 97, 'q': 98,
|
||||||
|
'R': 99, 'r': 100,
|
||||||
|
'S': 101, 's': 102,
|
||||||
|
'T': 103, 't': 104,
|
||||||
|
'U': 105, 'u': 106,
|
||||||
|
'V': 107, 'v': 108,
|
||||||
|
'W': 109, 'w': 110,
|
||||||
|
'X': 111, 'x': 112,
|
||||||
|
'Y': 113, 'y': 114,
|
||||||
|
'Z': 115, 'z': 116,
|
||||||
|
|
||||||
|
// Specials after letters (now 117-126)
|
||||||
|
'[': 117,
|
||||||
|
'\\': 118,
|
||||||
|
']': 119,
|
||||||
|
'^': 120,
|
||||||
|
'_': 121,
|
||||||
|
'`': 122,
|
||||||
|
'{': 123,
|
||||||
|
'|': 124,
|
||||||
|
'}': 125,
|
||||||
|
'~': 126
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
public static GetCharWeight(char: string): number {
|
||||||
|
return this.CharTable[char as keyof typeof this.CharTable];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,70 @@
|
|||||||
|
import type { Bash, Result } from './bash';
|
||||||
|
import type { CommandArgs, ICommand } from './commandRegistry';
|
||||||
|
import { KeybindInhibitor } from './keybindInhibitor';
|
||||||
|
import { ExitCode } from './metadata';
|
||||||
|
|
||||||
|
export class Process {
|
||||||
|
private _bash: Bash;
|
||||||
|
private _result: Result;
|
||||||
|
private _uid: number;
|
||||||
|
private _name: string;
|
||||||
|
private _initTimestamp: Date;
|
||||||
|
private _keybindInhibitor?: KeybindInhibitor;
|
||||||
|
private _abortController: AbortController;
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
_bashInstance: Bash,
|
||||||
|
uid: number,
|
||||||
|
name: string,
|
||||||
|
command: ICommand,
|
||||||
|
args: CommandArgs
|
||||||
|
) {
|
||||||
|
this._bash = _bashInstance;
|
||||||
|
this._result = { exitCode: ExitCode.ERROR, path: this._bash.getCwd() };
|
||||||
|
this._uid = uid;
|
||||||
|
this._name = name;
|
||||||
|
this._initTimestamp = new Date();
|
||||||
|
this._abortController = new AbortController();
|
||||||
|
|
||||||
|
if (command.keybinds) {
|
||||||
|
this._keybindInhibitor = new KeybindInhibitor(command.keybinds);
|
||||||
|
}
|
||||||
|
|
||||||
|
this._Run(command, _bashInstance, args);
|
||||||
|
}
|
||||||
|
|
||||||
|
public getKeybindInhibitor(): KeybindInhibitor | null {
|
||||||
|
if (this._keybindInhibitor) {
|
||||||
|
return this._keybindInhibitor;
|
||||||
|
} else {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public sigKill(callback: () => void): ExitCode {
|
||||||
|
this._abortController.abort();
|
||||||
|
callback();
|
||||||
|
|
||||||
|
return ExitCode.SUCCESS; //Only temp, need to add ExitCode.INT
|
||||||
|
}
|
||||||
|
|
||||||
|
public getUid(): number {
|
||||||
|
return this._uid;
|
||||||
|
}
|
||||||
|
|
||||||
|
public getInitTime(): Date {
|
||||||
|
return this._initTimestamp;
|
||||||
|
}
|
||||||
|
|
||||||
|
public getName(): string {
|
||||||
|
return this._name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async getResult(): Promise<Result> {
|
||||||
|
return this._result;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async _Run(command: ICommand, bashInstance: Bash, args: CommandArgs) {
|
||||||
|
this._result = command.method.call(bashInstance, args);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
import type { Bash } from "./bash";
|
||||||
|
import type { TreeNode } from "./fs";
|
||||||
|
|
||||||
|
export class Search {
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
@@ -0,0 +1,258 @@
|
|||||||
|
import { FileSystem } from '$lib/termos/filesystem/filesystem';
|
||||||
|
import type { TreeNode } from './fs';
|
||||||
|
|
||||||
|
export enum SortNodeBy {
|
||||||
|
NAME = 'name',
|
||||||
|
INODE = 'inode',
|
||||||
|
SIZE = 'size',
|
||||||
|
EXTENSION = 'extension',
|
||||||
|
TYPE = 'type',
|
||||||
|
MTIME = 'modified',
|
||||||
|
ATIME = 'accessed',
|
||||||
|
CTIME = 'changed'
|
||||||
|
}
|
||||||
|
|
||||||
|
export class Sort {
|
||||||
|
public static nodeArraySort(
|
||||||
|
nodes: TreeNode[] | number[],
|
||||||
|
reverse: boolean = false,
|
||||||
|
sortBy: SortNodeBy = SortNodeBy.NAME
|
||||||
|
): TreeNode[] {
|
||||||
|
const Fs = FileSystem.instance;
|
||||||
|
|
||||||
|
if (nodes.length === 0) {
|
||||||
|
console.warn('Tried to sort an empty node array!');
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
const parsedNodes: TreeNode[] = [];
|
||||||
|
|
||||||
|
if (typeof nodes[0] === 'number') {
|
||||||
|
for (const inode of nodes as number[]) {
|
||||||
|
const node = Fs.getNodeByInode(inode);
|
||||||
|
parsedNodes.push(node);
|
||||||
|
}
|
||||||
|
Sort.nodeQSort(parsedNodes, reverse, sortBy, 0, parsedNodes.length - 1);
|
||||||
|
console.log(parsedNodes);
|
||||||
|
return parsedNodes;
|
||||||
|
} else {
|
||||||
|
Sort.nodeQSort(nodes as TreeNode[], reverse, sortBy, 0, nodes.length - 1);
|
||||||
|
console.log(nodes);
|
||||||
|
return nodes as TreeNode[];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static nodeQSort(
|
||||||
|
array: TreeNode[],
|
||||||
|
reverse: boolean,
|
||||||
|
sortBy: SortNodeBy,
|
||||||
|
start: number,
|
||||||
|
end: number
|
||||||
|
) {
|
||||||
|
if (end <= start) return;
|
||||||
|
|
||||||
|
let pivot: number = this.nodePartition(array, reverse, sortBy, start, end);
|
||||||
|
this.nodeQSort(array, reverse, sortBy, start, pivot - 1);
|
||||||
|
this.nodeQSort(array, reverse, sortBy, pivot + 1, end);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static nodePartition(
|
||||||
|
part: TreeNode[],
|
||||||
|
reverse: boolean,
|
||||||
|
sortBy: SortNodeBy,
|
||||||
|
start: number,
|
||||||
|
end: number
|
||||||
|
): number {
|
||||||
|
let pivot: TreeNode = part[end];
|
||||||
|
let i: number = start - 1;
|
||||||
|
|
||||||
|
for (let j = start; j <= end; j++) {
|
||||||
|
if (this.nodeCompareElements(part[j], pivot, sortBy, reverse) < 0) {
|
||||||
|
i++;
|
||||||
|
let temp = part[i];
|
||||||
|
part[i] = part[j];
|
||||||
|
part[j] = temp;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
i++;
|
||||||
|
let temp = part[i];
|
||||||
|
part[i] = part[end];
|
||||||
|
part[end] = temp;
|
||||||
|
|
||||||
|
return i;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static nodeCompareElements(
|
||||||
|
a: TreeNode,
|
||||||
|
b: TreeNode,
|
||||||
|
sortBy: SortNodeBy,
|
||||||
|
reverse: boolean
|
||||||
|
): number {
|
||||||
|
switch (sortBy) {
|
||||||
|
case SortNodeBy.NAME: {
|
||||||
|
const nameA: string = a.name.startsWith('.') ? a.name.slice(1) : a.name;
|
||||||
|
const nameB: string = b.name.startsWith('.') ? b.name.slice(1) : b.name;
|
||||||
|
const minLength = Math.min(nameA.length, nameB.length);
|
||||||
|
|
||||||
|
for (let i = 0; i < minLength; i++) {
|
||||||
|
const charCodeA = Posix.GetCharWeight(nameA[i]);
|
||||||
|
const charCodeB = Posix.GetCharWeight(nameB[i]);
|
||||||
|
|
||||||
|
if (charCodeA !== charCodeB) {
|
||||||
|
return reverse ? charCodeB - charCodeA : charCodeA - charCodeB;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return reverse ? nameB.length - nameA.length : nameA.length - nameB.length;
|
||||||
|
}
|
||||||
|
case SortNodeBy.MTIME:
|
||||||
|
case SortNodeBy.ATIME:
|
||||||
|
case SortNodeBy.CTIME: {
|
||||||
|
console.log(sortBy, 'sortby');
|
||||||
|
// The sortBy serves as the lookup key in the timestamps object.
|
||||||
|
// It works because the times in SortBy enum have assigned values matching the names of the keys in the TreeNode object
|
||||||
|
const timeA: number = a.timestamps[sortBy].getTime();
|
||||||
|
const timeB: number = b.timestamps[sortBy].getTime();
|
||||||
|
|
||||||
|
return reverse ? timeA - timeB : timeB - timeA;
|
||||||
|
}
|
||||||
|
case SortNodeBy.SIZE: {
|
||||||
|
return reverse ? a.size - b.size : b.size - a.size;
|
||||||
|
}
|
||||||
|
case SortNodeBy.EXTENSION: {
|
||||||
|
const extA: string = a.name.split('.').pop() ?? '';
|
||||||
|
const extB: string = b.name.split('.').pop() ?? '';
|
||||||
|
const minLength = Math.min(extA.length, extB.length);
|
||||||
|
|
||||||
|
for (let i = 0; i < minLength; i++) {
|
||||||
|
const charCodeA = extA.charCodeAt(i);
|
||||||
|
const charCodeB = extB.charCodeAt(i);
|
||||||
|
|
||||||
|
if (charCodeA !== charCodeB) {
|
||||||
|
return reverse ? charCodeB - charCodeA : charCodeA - charCodeB;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return reverse ? extB.length - extA.length : extA.length - extB.length;
|
||||||
|
}
|
||||||
|
case SortNodeBy.INODE: {
|
||||||
|
return reverse ? b.inode - a.inode : a.inode - b.inode;
|
||||||
|
}
|
||||||
|
case SortNodeBy.TYPE: {
|
||||||
|
return reverse ? b.type - a.type : a.type - b.type;
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
throw new Error(`Sorting basis outside of the declared scope. - `);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class Posix {
|
||||||
|
private static readonly CharTable = {
|
||||||
|
// Space and punctuation (32-47)
|
||||||
|
' ': 32,
|
||||||
|
'!': 33,
|
||||||
|
'"': 34,
|
||||||
|
'#': 35,
|
||||||
|
$: 36,
|
||||||
|
'%': 37,
|
||||||
|
'&': 38,
|
||||||
|
"'": 39,
|
||||||
|
'(': 40,
|
||||||
|
')': 41,
|
||||||
|
'*': 42,
|
||||||
|
'+': 43,
|
||||||
|
',': 44,
|
||||||
|
'-': 45,
|
||||||
|
'.': 46,
|
||||||
|
'/': 47,
|
||||||
|
|
||||||
|
// Numbers 0-9 (48-57)
|
||||||
|
'0': 48,
|
||||||
|
'1': 49,
|
||||||
|
'2': 50,
|
||||||
|
'3': 51,
|
||||||
|
'4': 52,
|
||||||
|
'5': 53,
|
||||||
|
'6': 54,
|
||||||
|
'7': 55,
|
||||||
|
'8': 56,
|
||||||
|
'9': 57,
|
||||||
|
|
||||||
|
// More punctuation (58-64)
|
||||||
|
':': 58,
|
||||||
|
';': 59,
|
||||||
|
'<': 60,
|
||||||
|
'=': 61,
|
||||||
|
'>': 62,
|
||||||
|
'?': 63,
|
||||||
|
'@': 64,
|
||||||
|
|
||||||
|
// LETTERS - INTERLEAVED AaBbCc... (65-116)
|
||||||
|
A: 65,
|
||||||
|
a: 66,
|
||||||
|
B: 67,
|
||||||
|
b: 68,
|
||||||
|
C: 69,
|
||||||
|
c: 70,
|
||||||
|
D: 71,
|
||||||
|
d: 72,
|
||||||
|
E: 73,
|
||||||
|
e: 74,
|
||||||
|
F: 75,
|
||||||
|
f: 76,
|
||||||
|
G: 77,
|
||||||
|
g: 78,
|
||||||
|
H: 79,
|
||||||
|
h: 80,
|
||||||
|
I: 81,
|
||||||
|
i: 82,
|
||||||
|
J: 83,
|
||||||
|
j: 84,
|
||||||
|
K: 85,
|
||||||
|
k: 86,
|
||||||
|
L: 87,
|
||||||
|
l: 88,
|
||||||
|
M: 89,
|
||||||
|
m: 90,
|
||||||
|
N: 91,
|
||||||
|
n: 92,
|
||||||
|
O: 93,
|
||||||
|
o: 94,
|
||||||
|
P: 95,
|
||||||
|
p: 96,
|
||||||
|
Q: 97,
|
||||||
|
q: 98,
|
||||||
|
R: 99,
|
||||||
|
r: 100,
|
||||||
|
S: 101,
|
||||||
|
s: 102,
|
||||||
|
T: 103,
|
||||||
|
t: 104,
|
||||||
|
U: 105,
|
||||||
|
u: 106,
|
||||||
|
V: 107,
|
||||||
|
v: 108,
|
||||||
|
W: 109,
|
||||||
|
w: 110,
|
||||||
|
X: 111,
|
||||||
|
x: 112,
|
||||||
|
Y: 113,
|
||||||
|
y: 114,
|
||||||
|
Z: 115,
|
||||||
|
z: 116,
|
||||||
|
|
||||||
|
// Specials after letters (now 117-126)
|
||||||
|
'[': 117,
|
||||||
|
'\\': 118,
|
||||||
|
']': 119,
|
||||||
|
'^': 120,
|
||||||
|
_: 121,
|
||||||
|
'`': 122,
|
||||||
|
'{': 123,
|
||||||
|
'|': 124,
|
||||||
|
'}': 125,
|
||||||
|
'~': 126
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
public static GetCharWeight(char: string): number {
|
||||||
|
return this.CharTable[char as keyof typeof this.CharTable];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,72 @@
|
|||||||
|
type BrandedChar = string & { readonly __brand: unique symbol };
|
||||||
|
|
||||||
|
export class Char {
|
||||||
|
private readonly value: BrandedChar;
|
||||||
|
|
||||||
|
private constructor(char: string) {
|
||||||
|
if (char.length !== 1) {
|
||||||
|
throw new Error('Char must be exactly one character');
|
||||||
|
}
|
||||||
|
this.value = char as BrandedChar;
|
||||||
|
}
|
||||||
|
|
||||||
|
static from(char: string): Char {
|
||||||
|
return new Char(char);
|
||||||
|
}
|
||||||
|
|
||||||
|
valueOf(): string {
|
||||||
|
return this.value;
|
||||||
|
}
|
||||||
|
|
||||||
|
toString(): string {
|
||||||
|
return this.value;
|
||||||
|
}
|
||||||
|
|
||||||
|
charCode(): number {
|
||||||
|
return this.value.charCodeAt(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
isDigit(): boolean {
|
||||||
|
return /^\d$/.test(this.value);
|
||||||
|
}
|
||||||
|
|
||||||
|
isLetter(): boolean {
|
||||||
|
return /^[a-zA-Z]$/.test(this.value);
|
||||||
|
}
|
||||||
|
|
||||||
|
isAlphanumeric(): boolean {
|
||||||
|
return /^[a-zA-Z0-9]$/.test(this.value);
|
||||||
|
}
|
||||||
|
|
||||||
|
isWhitespace(): boolean {
|
||||||
|
return /^\s$/.test(this.value);
|
||||||
|
}
|
||||||
|
|
||||||
|
isUpperCase(): boolean {
|
||||||
|
return this.value === this.value.toUpperCase() && this.value !== this.value.toLowerCase();
|
||||||
|
}
|
||||||
|
|
||||||
|
isLowerCase(): boolean {
|
||||||
|
return this.value === this.value.toLowerCase() && this.value !== this.value.toUpperCase();
|
||||||
|
}
|
||||||
|
|
||||||
|
toUpperCase(): Char {
|
||||||
|
return Char.from(this.value.toUpperCase());
|
||||||
|
}
|
||||||
|
|
||||||
|
toLowerCase(): Char {
|
||||||
|
return Char.from(this.value.toLowerCase());
|
||||||
|
}
|
||||||
|
|
||||||
|
equals(other: Char): boolean {
|
||||||
|
return this.value === other.value;
|
||||||
|
}
|
||||||
|
|
||||||
|
equalsIgnoreCase(other: Char): boolean {
|
||||||
|
return this.value.toLowerCase() === other.value.toLowerCase();
|
||||||
|
}
|
||||||
|
|
||||||
|
static fromCharCode(charCode: number): Char {
|
||||||
|
return Char.from(String.fromCharCode(charCode));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
import plFlag from '$lib/assets/plFlag.svg';
|
||||||
|
import enFlag from '$lib/assets/enFlag.svg';
|
||||||
|
import deFlag from '$lib/assets/deFlag.svg';
|
||||||
|
import frFlag from '$lib/assets/frFlag.svg';
|
||||||
|
import jaFlag from '$lib/assets/jaFlag.svg';
|
||||||
|
|
||||||
|
import { writable } from 'svelte/store';
|
||||||
|
|
||||||
|
function getInitalLocale(): string {
|
||||||
|
if (typeof navigator === 'undefined') return 'en-US';
|
||||||
|
|
||||||
|
const sysPrefLocale = navigator.language
|
||||||
|
return sysPrefLocale
|
||||||
|
}
|
||||||
|
|
||||||
|
export const locale = writable(getInitalLocale());
|
||||||
@@ -1,191 +0,0 @@
|
|||||||
// $lib/stores/petals.ts
|
|
||||||
|
|
||||||
function mulberry32(seed: number): () => number {
|
|
||||||
let a = seed >>> 0;
|
|
||||||
return () => {
|
|
||||||
a = (a + 0x6d2b79f5) | 0;
|
|
||||||
let t = Math.imul(a ^ (a >>> 15), 1 | a);
|
|
||||||
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
|
|
||||||
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
function accelPosition(u: number, k: number): number {
|
|
||||||
if (k < 0.01) return u * u;
|
|
||||||
if (k > 50) return u;
|
|
||||||
const denom = k - 1 + Math.exp(-k);
|
|
||||||
return (k * u - 1 + Math.exp(-k * u)) / denom;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface PetalsOptions {
|
|
||||||
duration?: number;
|
|
||||||
fallAccel?: number;
|
|
||||||
fallDistance?: number;
|
|
||||||
leadIn?: number;
|
|
||||||
swayAmp?: number;
|
|
||||||
swayCycles?: number;
|
|
||||||
windX?: number;
|
|
||||||
spin?: number;
|
|
||||||
maxKeyframes?: number;
|
|
||||||
seed?: number;
|
|
||||||
hideOriginals?: boolean;
|
|
||||||
}
|
|
||||||
|
|
||||||
export type PetalsCleanup = () => void;
|
|
||||||
|
|
||||||
let callCounter = 0;
|
|
||||||
|
|
||||||
function viewportBottom(): number {
|
|
||||||
const vv = window.visualViewport;
|
|
||||||
if (vv) return vv.height + vv.offsetTop;
|
|
||||||
return Math.max(document.documentElement.clientHeight, window.innerHeight);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function petals(
|
|
||||||
node: HTMLElement,
|
|
||||||
{
|
|
||||||
duration = 15000,
|
|
||||||
fallAccel = 4,
|
|
||||||
fallDistance,
|
|
||||||
leadIn = 0.18,
|
|
||||||
swayAmp = 22,
|
|
||||||
swayCycles = 2.0,
|
|
||||||
windX = 60,
|
|
||||||
spin = 300,
|
|
||||||
maxKeyframes = 90,
|
|
||||||
seed,
|
|
||||||
hideOriginals = true
|
|
||||||
}: PetalsOptions = {}
|
|
||||||
): PetalsCleanup {
|
|
||||||
const chars = Array.from(node.querySelectorAll<HTMLElement>('.char')).filter(
|
|
||||||
(el) => el.textContent?.trim() !== ''
|
|
||||||
);
|
|
||||||
|
|
||||||
if (chars.length === 0) return () => {};
|
|
||||||
|
|
||||||
const effectiveSeed = seed ?? Date.now() ^ (callCounter++ * 0x9e3779b9);
|
|
||||||
|
|
||||||
const rect = node.getBoundingClientRect();
|
|
||||||
const vb = viewportBottom();
|
|
||||||
|
|
||||||
// ── Clone + fixed overlay ────────────────────────────────────────────
|
|
||||||
const clone = node.cloneNode(true) as HTMLElement;
|
|
||||||
clone.removeAttribute('id');
|
|
||||||
clone.querySelectorAll<HTMLElement>('[id]').forEach((n) => n.removeAttribute('id'));
|
|
||||||
|
|
||||||
clone.querySelectorAll<HTMLElement>('.prompt, .cursor').forEach((n) => {
|
|
||||||
n.style.visibility = 'hidden';
|
|
||||||
});
|
|
||||||
|
|
||||||
clone.style.cssText = `
|
|
||||||
position: fixed;
|
|
||||||
top: ${rect.top}px;
|
|
||||||
left: ${rect.left}px;
|
|
||||||
margin: 0;
|
|
||||||
overflow: visible;
|
|
||||||
pointer-events: none;
|
|
||||||
z-index: 9999;
|
|
||||||
contain: layout style;
|
|
||||||
`;
|
|
||||||
|
|
||||||
const origFont = getComputedStyle(node);
|
|
||||||
clone.style.fontSize = origFont.fontSize;
|
|
||||||
clone.style.fontFamily = origFont.fontFamily;
|
|
||||||
clone.style.fontWeight = origFont.fontWeight;
|
|
||||||
clone.style.fontStyle = origFont.fontStyle;
|
|
||||||
clone.style.fontVariant = origFont.fontVariant;
|
|
||||||
clone.style.fontStretch = origFont.fontStretch;
|
|
||||||
clone.style.lineHeight = origFont.lineHeight;
|
|
||||||
clone.style.letterSpacing = origFont.letterSpacing;
|
|
||||||
clone.style.wordSpacing = origFont.wordSpacing;
|
|
||||||
clone.style.color = 'var(--color-text-primary)';
|
|
||||||
clone.style.transition = 'var(--transition-standard)';
|
|
||||||
|
|
||||||
document.body.appendChild(clone);
|
|
||||||
|
|
||||||
if (hideOriginals) {
|
|
||||||
chars.forEach((el) => {
|
|
||||||
el.style.visibility = 'hidden';
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
const cloneChars = Array.from(clone.querySelectorAll<HTMLElement>('.char'));
|
|
||||||
const petalRects: DOMRect[] = [];
|
|
||||||
for (let i = 0; i < cloneChars.length; i++) {
|
|
||||||
petalRects.push(cloneChars[i].getBoundingClientRect());
|
|
||||||
}
|
|
||||||
|
|
||||||
const anims: Animation[] = [];
|
|
||||||
|
|
||||||
cloneChars.forEach((el, i) => {
|
|
||||||
const rand = mulberry32(effectiveSeed + i * 100003);
|
|
||||||
|
|
||||||
const charDuration = duration * (1.85 + rand() * 1.43);
|
|
||||||
const charAccel = fallAccel * (0.9 + rand() * 0.2);
|
|
||||||
const charSwayCycles = swayCycles * (0.7 + rand() * 0.7);
|
|
||||||
const charLeadIn = leadIn * (0.85 + rand() * 0.3);
|
|
||||||
|
|
||||||
const phase = rand() * Math.PI * 2;
|
|
||||||
const dir: 1 | -1 = rand() < 0.5 ? -1 : 1;
|
|
||||||
const amp = swayAmp * (0.5 + rand() * 0.9);
|
|
||||||
const spinTotal = spin * (0.7 + rand() * 0.6) * dir;
|
|
||||||
const charWindX = windX * (0.5 + rand() * 1.0);
|
|
||||||
|
|
||||||
let charFall: number;
|
|
||||||
if (fallDistance != null) {
|
|
||||||
charFall = fallDistance * (0.95 + rand() * 0.15);
|
|
||||||
} else {
|
|
||||||
const petalRect = petalRects[i];
|
|
||||||
const neededFall = vb - petalRect.top + petalRect.height + 40;
|
|
||||||
charFall = neededFall * (1 + rand() * 0.35);
|
|
||||||
}
|
|
||||||
|
|
||||||
const N = Math.min(maxKeyframes, Math.max(40, Math.round(charDuration / 200)));
|
|
||||||
const frames: Keyframe[] = [];
|
|
||||||
|
|
||||||
for (let k = 0; k <= N; k++) {
|
|
||||||
const t = k / N;
|
|
||||||
const y = charFall * accelPosition(t, charAccel);
|
|
||||||
|
|
||||||
const lead = Math.min(1, t / charLeadIn);
|
|
||||||
const leadSmooth = lead * lead * (3 - 2 * lead);
|
|
||||||
|
|
||||||
const sway = amp * leadSmooth * Math.sin(2 * Math.PI * charSwayCycles * t + phase);
|
|
||||||
const wind = charWindX * t;
|
|
||||||
const x = sway + wind;
|
|
||||||
|
|
||||||
const r = spinTotal * t;
|
|
||||||
|
|
||||||
frames.push({
|
|
||||||
transform: `translate(${x.toFixed(2)}px, ${y.toFixed(2)}px) rotate(${r.toFixed(2)}deg)`,
|
|
||||||
offset: t
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
anims.push(
|
|
||||||
el.animate(frames, {
|
|
||||||
duration: charDuration,
|
|
||||||
delay: 0,
|
|
||||||
easing: 'linear',
|
|
||||||
fill: 'forwards'
|
|
||||||
})
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
let cleaned = false;
|
|
||||||
const doCleanup = (): void => {
|
|
||||||
if (cleaned) return;
|
|
||||||
cleaned = true;
|
|
||||||
for (const a of anims) a.cancel();
|
|
||||||
clone.remove();
|
|
||||||
if (hideOriginals) {
|
|
||||||
chars.forEach((el) => {
|
|
||||||
el.style.visibility = '';
|
|
||||||
});
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
void Promise.allSettled(anims.map((a) => a.finished)).then(doCleanup);
|
|
||||||
|
|
||||||
return doCleanup;
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,281 @@
|
|||||||
|
//import Renderer from '$lib/shimeji/renderer/renderer';
|
||||||
|
import { WebG } from '$lib/shimagic/renderer/web_g_engine';
|
||||||
|
import Vector2 from '../vector';
|
||||||
|
|
||||||
|
export class Shimejii {
|
||||||
|
private canvas: HTMLCanvasElement;
|
||||||
|
private renderer: Renderer;
|
||||||
|
private size: number;
|
||||||
|
|
||||||
|
private pos: Vector2 = Vector2.zero;
|
||||||
|
private vel: Vector2 = Vector2.zero;
|
||||||
|
|
||||||
|
private mousePos: Vector2 = Vector2.zero;
|
||||||
|
|
||||||
|
private pivot: Vector2 = Vector2.zero;
|
||||||
|
|
||||||
|
private isBeingDragged: boolean = false;
|
||||||
|
|
||||||
|
private rafId: number | null = null;
|
||||||
|
private prevDeltaTime: number = 0;
|
||||||
|
|
||||||
|
private readonly TIMESCALE: number = 1;
|
||||||
|
private readonly RESTITUTION: number = 0.4;
|
||||||
|
private readonly CURSOR_STRENGTH: number = 500;
|
||||||
|
private readonly DAMPING: number = 1;
|
||||||
|
private readonly MASS: number = 1;
|
||||||
|
private readonly FRICTION: number = 0.9;
|
||||||
|
private readonly GRAVITY: number = 50;
|
||||||
|
|
||||||
|
private bounds: { minX: number; minY: number; maxX: number; maxY: number };
|
||||||
|
|
||||||
|
constructor(size: number = 40, canvas: HTMLCanvasElement, renderer: Renderer) {
|
||||||
|
this.size = size;
|
||||||
|
this.canvas = canvas;
|
||||||
|
this.renderer = renderer;
|
||||||
|
|
||||||
|
this.bounds = {
|
||||||
|
minX: 0,
|
||||||
|
minY: 0,
|
||||||
|
maxX: window.innerWidth,
|
||||||
|
maxY: window.innerHeight
|
||||||
|
};
|
||||||
|
|
||||||
|
this.pos.set(window.innerWidth / 2, window.innerHeight / 2);
|
||||||
|
this.vel.set(Math.floor(Math.random() * 5000) - 2500, Math.floor(Math.random() * 5000) - 2500);
|
||||||
|
|
||||||
|
this.updateBounds();
|
||||||
|
window.addEventListener('resize', () => this.updateBounds());
|
||||||
|
}
|
||||||
|
|
||||||
|
private updateBounds(): void {
|
||||||
|
this.bounds = {
|
||||||
|
minX: 0,
|
||||||
|
minY: 0,
|
||||||
|
maxX: window.innerWidth,
|
||||||
|
maxY: window.innerHeight
|
||||||
|
};
|
||||||
|
|
||||||
|
this.canvas.width = window.innerWidth;
|
||||||
|
this.canvas.height = window.innerHeight;
|
||||||
|
this.renderer.UpdateBounds(window.innerWidth, window.innerHeight);
|
||||||
|
}
|
||||||
|
|
||||||
|
start(): void {
|
||||||
|
if (this.rafId !== null) return;
|
||||||
|
|
||||||
|
const firstFrame = (delta: number) => {
|
||||||
|
this.prevDeltaTime = delta;
|
||||||
|
this.rafId = requestAnimationFrame(animate);
|
||||||
|
};
|
||||||
|
|
||||||
|
const animate = (delta: number) => {
|
||||||
|
let dt = (delta - this.prevDeltaTime) / 1000;
|
||||||
|
dt = Math.min(dt, 0.05 * this.TIMESCALE);
|
||||||
|
this.prevDeltaTime = delta;
|
||||||
|
|
||||||
|
this.updatePhysics(dt);
|
||||||
|
this.applyBoundaries();
|
||||||
|
this.render();
|
||||||
|
this.rafId = requestAnimationFrame(animate);
|
||||||
|
};
|
||||||
|
|
||||||
|
this.rafId = requestAnimationFrame(firstFrame);
|
||||||
|
}
|
||||||
|
|
||||||
|
stop(): void {
|
||||||
|
if (this.rafId !== null) {
|
||||||
|
cancelAnimationFrame(this.rafId);
|
||||||
|
this.rafId = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* private setupDragEvents(): void {
|
||||||
|
this.element.addEventListener('mousedown', (e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
this.isBeingDragged = true;
|
||||||
|
this.element.style.cursor = 'grabbing';
|
||||||
|
|
||||||
|
const parent = this.element.parentElement;
|
||||||
|
if (parent) parent.style.cursor = 'grabbing';
|
||||||
|
|
||||||
|
this.pivot.x = e.offsetX - this.rect.width / 2;
|
||||||
|
this.pivot.y = e.offsetY - this.rect.height / 2;
|
||||||
|
});
|
||||||
|
|
||||||
|
document.addEventListener('mousemove', (e) => {
|
||||||
|
this.mousePos.x = e.pageX;
|
||||||
|
this.mousePos.y = e.pageY;
|
||||||
|
});
|
||||||
|
|
||||||
|
document.addEventListener('mouseup', (e) => {
|
||||||
|
if (this.isBeingDragged) {
|
||||||
|
this.isBeingDragged = false;
|
||||||
|
this.element.style.cursor = 'grab';
|
||||||
|
|
||||||
|
const parent = this.element.parentElement;
|
||||||
|
if (parent) parent.style.cursor = 'auto';
|
||||||
|
|
||||||
|
this.pivot = Vector2.zero;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.canvas.getContext('2d')!.clearRect(0, 0, this.canvas.width, this.canvas.height);
|
||||||
|
});
|
||||||
|
|
||||||
|
this.element.addEventListener('dragstart', (e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
});
|
||||||
|
} */
|
||||||
|
|
||||||
|
private updatePhysics(dt: number): void {
|
||||||
|
console.log(this.vel.x, this.vel.y);
|
||||||
|
if (this.isBeingDragged) {
|
||||||
|
const direction: Vector2 = this.mousePos.sub(this.pivot).sub(this.pos);
|
||||||
|
|
||||||
|
const force: Vector2 = direction.mul(this.CURSOR_STRENGTH);
|
||||||
|
|
||||||
|
const acceleration: Vector2 = force.div(this.MASS).deadZone(0.001);
|
||||||
|
|
||||||
|
acceleration.mulEq(dt);
|
||||||
|
|
||||||
|
this.vel.addEq(acceleration);
|
||||||
|
this.vel.mulEq(0.8);
|
||||||
|
}
|
||||||
|
|
||||||
|
this.vel.y += this.GRAVITY;
|
||||||
|
this.vel.mulEq(this.DAMPING);
|
||||||
|
|
||||||
|
if (this.pos.y + this.size >= this.bounds.maxY) {
|
||||||
|
this.vel.x *= this.FRICTION;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.vel.deadZoneEq(0.00001);
|
||||||
|
//if (Math.abs(this.vel.x) <= 0.00001) this.vel.x = 0;
|
||||||
|
//if (Math.abs(this.vel.y) <= 0.00001) this.vel.y = 0;
|
||||||
|
|
||||||
|
const outVel = this.vel.mul(dt);
|
||||||
|
this.pos.addEq(outVel);
|
||||||
|
}
|
||||||
|
|
||||||
|
private applyBoundaries(): void {
|
||||||
|
const leftBound = this.size;
|
||||||
|
const rightBound = this.bounds.maxX - this.size;
|
||||||
|
|
||||||
|
if (this.pos.x < leftBound) {
|
||||||
|
this.pos.x = leftBound;
|
||||||
|
this.vel.x = -this.RESTITUTION * this.vel.x;
|
||||||
|
} else if (this.pos.x > rightBound) {
|
||||||
|
this.pos.x = rightBound;
|
||||||
|
this.vel.x = -this.RESTITUTION * this.vel.x;
|
||||||
|
}
|
||||||
|
|
||||||
|
const topBound = this.size;
|
||||||
|
const bottomBound = this.bounds.maxY - this.size;
|
||||||
|
|
||||||
|
if (this.pos.y < topBound) {
|
||||||
|
this.pos.y = topBound;
|
||||||
|
this.vel.y = -this.RESTITUTION * this.vel.y;
|
||||||
|
} else if (this.pos.y > bottomBound) {
|
||||||
|
this.pos.y = bottomBound;
|
||||||
|
this.vel.y = -this.RESTITUTION * this.vel.y;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private drawRay(pos1: { x: number; y: number }, pos2: { x: number; y: number }) {
|
||||||
|
const ctx = this.canvas.getContext('2d')!;
|
||||||
|
ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
|
||||||
|
ctx.strokeStyle = 'white';
|
||||||
|
ctx.lineWidth = 0.1;
|
||||||
|
ctx.beginPath();
|
||||||
|
ctx.moveTo(pos1.x, pos1.y);
|
||||||
|
ctx.lineTo(pos2.x, pos2.y);
|
||||||
|
ctx.stroke();
|
||||||
|
}
|
||||||
|
|
||||||
|
private render(): void {
|
||||||
|
this.renderer.Draw(this.pos, this.size);
|
||||||
|
|
||||||
|
/* if(this.isBeingDragged) {
|
||||||
|
this.drawRay(
|
||||||
|
{x: this.mouseX, y: this.mouseY},
|
||||||
|
{x: this.x + this.pivotX, y: this.y + this.pivotY}
|
||||||
|
)
|
||||||
|
} */
|
||||||
|
}
|
||||||
|
|
||||||
|
addImpulse(x: number, y: number): void {
|
||||||
|
this.vel.x += x;
|
||||||
|
this.vel.y += y;
|
||||||
|
}
|
||||||
|
|
||||||
|
moveTo(pos: number) {}
|
||||||
|
}
|
||||||
|
|
||||||
|
export namespace Shimagic {
|
||||||
|
export class Shimeji {
|
||||||
|
private WebGEngine: WebG.Engine;
|
||||||
|
//private PhysisEngine: Physis.Engine;
|
||||||
|
private size!: number;
|
||||||
|
|
||||||
|
private AnimID: number | null = null;
|
||||||
|
private pDeltaT: number = 0;
|
||||||
|
|
||||||
|
constructor(webgengine: WebG.Engine /* physis: Physis.Engine */) {
|
||||||
|
this.WebGEngine = webgengine;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Factory method: Initializes all sub-systems like WebG & Physis aswell as initializes the Shimeji and starts its animation
|
||||||
|
* @async
|
||||||
|
* @public
|
||||||
|
* @param {ShimejiConfig} config - Shimeji configuration
|
||||||
|
* @returns {Promise<Shimeji>} that resolves when the Shimeji is done initializing
|
||||||
|
*/
|
||||||
|
public static async Initialize(config: ShimejiConfig): Promise<Shimeji> {
|
||||||
|
const webg = await WebG.Engine.Initialize(config.webG);
|
||||||
|
//const physis = await Physis.Engine.Initialize(config.physis);
|
||||||
|
|
||||||
|
const shimeji = new Shimeji(webg);
|
||||||
|
shimeji.size = config.size;
|
||||||
|
|
||||||
|
const AFrame = (delta: number) => {
|
||||||
|
shimeji.pDeltaT = delta;
|
||||||
|
shimeji.AnimID = requestAnimationFrame(shimeji._anim);
|
||||||
|
};
|
||||||
|
|
||||||
|
shimeji.AnimID = requestAnimationFrame(AFrame);
|
||||||
|
|
||||||
|
return shimeji;
|
||||||
|
}
|
||||||
|
|
||||||
|
private _anim(delta: number) {
|
||||||
|
let dt = (delta - this.pDeltaT) / 1000;
|
||||||
|
dt = Math.min(dt, 0.05 /* * this.Physis.TIMESCALE */);
|
||||||
|
this.pDeltaT = delta;
|
||||||
|
|
||||||
|
this.UpdatePhysics(dt);
|
||||||
|
this.UpdateFrame(dt);
|
||||||
|
|
||||||
|
this.AnimID = requestAnimationFrame(this._anim);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A function called automatically every "frame" where the code for calculating the next physics frame of the Shimeji is placed
|
||||||
|
* @param delta - Automatically passed in deltaT value;
|
||||||
|
*/
|
||||||
|
private UpdatePhysics(delta: number): void {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A function called automatically every "frame" where the code for drawing the next frame of the Shimeji is placed
|
||||||
|
* @param delta - Automatically passed in deltaT value;
|
||||||
|
*/
|
||||||
|
private UpdateFrame(delta: number): void {}
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ShimejiConfig {
|
||||||
|
sprite: string; //temp soultion to
|
||||||
|
size: number;
|
||||||
|
webG: WebG.EngineConfig;
|
||||||
|
//physis: Physis.EngineConfig;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,336 @@
|
|||||||
|
import Vector2 from "../vector";
|
||||||
|
|
||||||
|
export class Shimeji {
|
||||||
|
private element: HTMLElement;
|
||||||
|
private canvas: HTMLCanvasElement;
|
||||||
|
private rect: DOMRect;
|
||||||
|
|
||||||
|
private pos: Vector2 = Vector2.zero;
|
||||||
|
private vel: Vector2 = Vector2.zero;
|
||||||
|
|
||||||
|
private angle: number = 0; // radians
|
||||||
|
private angularVelocity: number = 0; // rad/s
|
||||||
|
private inertia: number; // kg·m²
|
||||||
|
private localGrip: Vector2 = Vector2.zero; // offset from center (body‑fixed)
|
||||||
|
|
||||||
|
private mousePos: Vector2 = Vector2.zero;
|
||||||
|
|
||||||
|
private pivot: Vector2 = Vector2.zero;
|
||||||
|
|
||||||
|
private isBeingDragged: boolean = false;
|
||||||
|
|
||||||
|
private rafId: number | null = null;
|
||||||
|
private prevDeltaTime: number = 0;
|
||||||
|
|
||||||
|
|
||||||
|
private readonly RESTITUTION: number = 0.6;
|
||||||
|
private readonly STIFFNESS: number = 500;
|
||||||
|
private readonly DAMPING: number = 1;
|
||||||
|
private readonly MASS: number = 10.0;
|
||||||
|
private readonly FRICTION: number = 0.9;
|
||||||
|
private readonly GRAVITY: number = 10;
|
||||||
|
|
||||||
|
private bounds: { minX: number; minY: number; maxX: number; maxY: number };
|
||||||
|
|
||||||
|
constructor(element: HTMLElement, canvas: HTMLCanvasElement) {
|
||||||
|
this.element = element;
|
||||||
|
this.canvas= canvas;
|
||||||
|
this.rect = element.getBoundingClientRect();
|
||||||
|
|
||||||
|
this.bounds = {
|
||||||
|
minX: 0,
|
||||||
|
minY: 0,
|
||||||
|
maxX: window.innerWidth,
|
||||||
|
maxY: window.innerHeight
|
||||||
|
};
|
||||||
|
|
||||||
|
this.inertia = (1 / 12) *
|
||||||
|
this.MASS * (this.rect.width * this.rect.width + this.rect.height * this.rect.height);
|
||||||
|
|
||||||
|
this.pos.set(window.innerWidth / 2, window.innerHeight/ 2);
|
||||||
|
|
||||||
|
this.updateBounds();
|
||||||
|
window.addEventListener('resize', () => this.updateBounds());
|
||||||
|
|
||||||
|
console.log(this.element.getBoundingClientRect());
|
||||||
|
|
||||||
|
this.setupDragEvents();
|
||||||
|
}
|
||||||
|
|
||||||
|
private updateBounds(): void {
|
||||||
|
this.bounds = {
|
||||||
|
minX: 0,
|
||||||
|
minY: 0,
|
||||||
|
maxX: window.innerWidth,
|
||||||
|
maxY: window.innerHeight
|
||||||
|
};
|
||||||
|
|
||||||
|
this.canvas.width = window.innerWidth;
|
||||||
|
this.canvas.height = window.innerHeight;
|
||||||
|
}
|
||||||
|
|
||||||
|
start(): void {
|
||||||
|
if (this.rafId !== null) return;
|
||||||
|
|
||||||
|
const firstFrame = (delta: number) => {
|
||||||
|
this.prevDeltaTime = delta;
|
||||||
|
this.rafId = requestAnimationFrame(animate);
|
||||||
|
}
|
||||||
|
|
||||||
|
const animate = (delta: number) => {
|
||||||
|
const dt: number = Math.min(delta - this.prevDeltaTime, 0.05);
|
||||||
|
this.prevDeltaTime = delta;
|
||||||
|
|
||||||
|
this.updatePhysics(dt);
|
||||||
|
this.applyBoundaries();
|
||||||
|
this.render();
|
||||||
|
this.rafId = requestAnimationFrame(animate);
|
||||||
|
};
|
||||||
|
|
||||||
|
this.rafId = requestAnimationFrame(firstFrame);
|
||||||
|
}
|
||||||
|
|
||||||
|
stop(): void {
|
||||||
|
if (this.rafId !== null) {
|
||||||
|
cancelAnimationFrame(this.rafId);
|
||||||
|
this.rafId = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private getCornerWorld(lx: number, ly: number): Vector2 {
|
||||||
|
// lx, ly are in local coordinates (relative to center, with rotation)
|
||||||
|
const cos = Math.cos(this.angle);
|
||||||
|
const sin = Math.sin(this.angle);
|
||||||
|
return new Vector2(
|
||||||
|
this.pos.x + (lx * cos - ly * sin),
|
||||||
|
this.pos.y + (lx * sin + ly * cos)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
private setupDragEvents(): void {
|
||||||
|
this.element.addEventListener('mousedown', (e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
this.isBeingDragged = true;
|
||||||
|
this.element.style.cursor = 'grabbing';
|
||||||
|
|
||||||
|
const parent = this.element.parentElement;
|
||||||
|
if(parent) parent.style.cursor = 'grabbing';
|
||||||
|
|
||||||
|
const clickWorld = new Vector2(e.pageX, e.pageY);
|
||||||
|
const center = this.pos;
|
||||||
|
const offset = clickWorld.sub(center)
|
||||||
|
const cos = Math.cos(-this.angle);
|
||||||
|
const sin = Math.sin(-this.angle);
|
||||||
|
|
||||||
|
this.localGrip = new Vector2(
|
||||||
|
offset.x * cos - offset.y * sin,
|
||||||
|
offset.x * sin + offset.y * cos
|
||||||
|
);
|
||||||
|
|
||||||
|
this.pivot.x = e.offsetX - this.rect.width / 2;
|
||||||
|
this.pivot.y = e.offsetY - this.rect.height / 2;
|
||||||
|
|
||||||
|
});
|
||||||
|
|
||||||
|
document.addEventListener('mousemove', (e) => {
|
||||||
|
this.mousePos.x = e.pageX;
|
||||||
|
this.mousePos.y = e.pageY;
|
||||||
|
});
|
||||||
|
|
||||||
|
document.addEventListener('mouseup', (e) => {
|
||||||
|
if(this.isBeingDragged) {
|
||||||
|
this.isBeingDragged = false;
|
||||||
|
this.element.style.cursor = 'grab';
|
||||||
|
|
||||||
|
const parent = this.element.parentElement;
|
||||||
|
if(parent) parent.style.cursor = 'auto';
|
||||||
|
|
||||||
|
this.pivot = Vector2.zero;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.canvas.getContext('2d')!.clearRect(0, 0, this.canvas.width, this.canvas.height);
|
||||||
|
});
|
||||||
|
|
||||||
|
this.element.addEventListener('dragstart', (e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private updatePhysics(dt: number): void {
|
||||||
|
|
||||||
|
const cos = Math.cos(this.angle);
|
||||||
|
const sin = Math.sin(this.angle);
|
||||||
|
const gripWorld = new Vector2(
|
||||||
|
this.pos.x + (this.localGrip.x * cos - this.localGrip.y * sin),
|
||||||
|
this.pos.y + (this.localGrip.x * sin + this.localGrip.y * cos)
|
||||||
|
);
|
||||||
|
|
||||||
|
if (this.isBeingDragged) {
|
||||||
|
const direction: Vector2 = this.mousePos.sub(gripWorld);
|
||||||
|
|
||||||
|
const force: Vector2 = direction.mul(this.STIFFNESS);
|
||||||
|
|
||||||
|
const acceleration: Vector2 = force.div(this.MASS).deadZone(0.001);
|
||||||
|
|
||||||
|
acceleration.mulEq(dt);
|
||||||
|
|
||||||
|
this.vel.addEq(acceleration);
|
||||||
|
this.vel.mulEq(0.8);
|
||||||
|
|
||||||
|
const r = gripWorld.sub(this.pos);
|
||||||
|
const torque = r.cross(force);
|
||||||
|
this.angularVelocity += (torque / this.inertia) * dt;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.vel.y += this.GRAVITY;
|
||||||
|
this.vel.mulEq(this.DAMPING);
|
||||||
|
|
||||||
|
if (this.pos.y + this.rect.width >= this.bounds.maxY) {
|
||||||
|
this.vel.x *= this.FRICTION;
|
||||||
|
}
|
||||||
|
|
||||||
|
const outVel = this.vel.mul(dt);
|
||||||
|
this.pos.addEq(outVel);
|
||||||
|
|
||||||
|
this.angle += this.angularVelocity * dt;
|
||||||
|
this.angle %= 2 * Math.PI;
|
||||||
|
}
|
||||||
|
|
||||||
|
private applyBoundaries(): void {
|
||||||
|
const w = this.rect.width / 2;
|
||||||
|
const h = this.rect.height / 2;
|
||||||
|
|
||||||
|
// List of corners in local coordinates (four combinations)
|
||||||
|
const corners = [
|
||||||
|
{ lx: w, ly: h }, // top‑right
|
||||||
|
{ lx: w, ly: -h }, // bottom‑right
|
||||||
|
{ lx: -w, ly: h }, // top‑left
|
||||||
|
{ lx: -w, ly: -h } // bottom‑left
|
||||||
|
];
|
||||||
|
|
||||||
|
// Check each wall
|
||||||
|
// Left wall (x = leftBound)
|
||||||
|
const leftBound = w;
|
||||||
|
for (const corner of corners) {
|
||||||
|
const world = this.getCornerWorld(corner.lx, corner.ly);
|
||||||
|
if (world.x < leftBound) {
|
||||||
|
// Penetration depth (distance from wall to corner)
|
||||||
|
const penetration = leftBound - world.x;
|
||||||
|
// Normal points to the right (+x)
|
||||||
|
const normal = new Vector2(1, 0);
|
||||||
|
// Contact point is the wall at corner's y (or clamp to avoid escaping)
|
||||||
|
const contactY = Math.min(Math.max(world.y, this.bounds.minY + h), this.bounds.maxY - h);
|
||||||
|
const contactPoint = new Vector2(leftBound, contactY);
|
||||||
|
this.resolveCollision(normal, contactPoint);
|
||||||
|
// Reposition to avoid continuous penetration
|
||||||
|
this.pos.x = leftBound - w;
|
||||||
|
return; // after one correction, stop checking further walls to avoid multiple impulses
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Right wall (x = rightBound)
|
||||||
|
const rightBound = this.bounds.maxX - w;
|
||||||
|
for (const corner of corners) {
|
||||||
|
const world = this.getCornerWorld(corner.lx, corner.ly);
|
||||||
|
if (world.x > rightBound) {
|
||||||
|
const penetration = world.x - rightBound;
|
||||||
|
const normal = new Vector2(-1, 0);
|
||||||
|
const contactY = Math.min(Math.max(world.y, this.bounds.minY + h), this.bounds.maxY - h);
|
||||||
|
const contactPoint = new Vector2(rightBound, contactY);
|
||||||
|
this.resolveCollision(normal, contactPoint);
|
||||||
|
this.pos.x = rightBound + w;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Top wall (y = topBound)
|
||||||
|
const topBound = h;
|
||||||
|
for (const corner of corners) {
|
||||||
|
const world = this.getCornerWorld(corner.lx, corner.ly);
|
||||||
|
if (world.y < topBound) {
|
||||||
|
const penetration = topBound - world.y;
|
||||||
|
const normal = new Vector2(0, 1);
|
||||||
|
const contactX = Math.min(Math.max(world.x, leftBound), rightBound);
|
||||||
|
const contactPoint = new Vector2(contactX, topBound);
|
||||||
|
this.resolveCollision(normal, contactPoint);
|
||||||
|
this.pos.y = topBound - h;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Bottom wall (y = bottomBound)
|
||||||
|
const bottomBound = this.bounds.maxY - h;
|
||||||
|
for (const corner of corners) {
|
||||||
|
const world = this.getCornerWorld(corner.lx, corner.ly);
|
||||||
|
if (world.y > bottomBound) {
|
||||||
|
const penetration = world.y - bottomBound;
|
||||||
|
const normal = new Vector2(0, -1);
|
||||||
|
const contactX = Math.min(Math.max(world.x, leftBound), rightBound);
|
||||||
|
const contactPoint = new Vector2(contactX, bottomBound);
|
||||||
|
this.resolveCollision(normal, contactPoint);
|
||||||
|
this.pos.y = bottomBound + h;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private resolveCollision(normal: Vector2, contactPoint: Vector2): void {
|
||||||
|
// Vector from center to contact point
|
||||||
|
const r = contactPoint.sub(this.pos);
|
||||||
|
|
||||||
|
// Velocity of the contact point
|
||||||
|
const v_rel = this.vel.clone();
|
||||||
|
// Add tangential component from angular velocity: ω × r
|
||||||
|
v_rel.x -= this.angularVelocity * r.y;
|
||||||
|
v_rel.y += this.angularVelocity * r.x;
|
||||||
|
|
||||||
|
// Relative velocity along normal
|
||||||
|
const vn = v_rel.dot(normal);
|
||||||
|
if (vn > 0) return; // Already separating
|
||||||
|
|
||||||
|
// Impulse numerator
|
||||||
|
const numerator = -(1 + this.RESTITUTION) * vn;
|
||||||
|
|
||||||
|
// Denominator: 1/m + (r × n)^2 / I
|
||||||
|
const r_cross_n = r.cross(normal);
|
||||||
|
const denominator = 1 / this.MASS + (r_cross_n * r_cross_n) / this.inertia;
|
||||||
|
|
||||||
|
const j = numerator / denominator;
|
||||||
|
const impulse = normal.mul(j);
|
||||||
|
|
||||||
|
// Apply impulse
|
||||||
|
this.vel.addEq(impulse.div(this.MASS));
|
||||||
|
this.angularVelocity += r.cross(impulse) / this.inertia;
|
||||||
|
}
|
||||||
|
|
||||||
|
private drawRay(pos1: {x: number, y: number}, pos2: {x: number, y: number}) {
|
||||||
|
const ctx = this.canvas.getContext("2d")!;
|
||||||
|
ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
|
||||||
|
ctx.strokeStyle = "white";
|
||||||
|
ctx.lineWidth = 0.1
|
||||||
|
ctx.beginPath();
|
||||||
|
ctx.moveTo(pos1.x, pos1.y);
|
||||||
|
ctx.lineTo(pos2.x, pos2.y);
|
||||||
|
ctx.stroke();
|
||||||
|
}
|
||||||
|
|
||||||
|
private render(): void {
|
||||||
|
this.element.style.transform = `translate(${this.pos.x}px, ${this.pos.y}px) rotate(${this.angle * 180 / Math.PI}deg)`;
|
||||||
|
|
||||||
|
/* if(this.isBeingDragged) {
|
||||||
|
this.drawRay(
|
||||||
|
{x: this.mousePos.x, y: this.mousePos.y},
|
||||||
|
{x: this.pos.x + this.pivot.x, y: this.pos.y + this.pivot.y}
|
||||||
|
)
|
||||||
|
} */
|
||||||
|
}
|
||||||
|
|
||||||
|
addImpulse(x: number, y: number): void {
|
||||||
|
this.vel.x += x;
|
||||||
|
this.vel.y += y;
|
||||||
|
}
|
||||||
|
|
||||||
|
moveTo(pos: number) {
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
export class Stack<T> {
|
||||||
|
private items: T[] = [];
|
||||||
|
|
||||||
|
push(element: T): void {
|
||||||
|
this.items.push(element);
|
||||||
|
}
|
||||||
|
|
||||||
|
pop(): T | undefined {
|
||||||
|
return this.items.pop();
|
||||||
|
}
|
||||||
|
|
||||||
|
peek(): T | undefined {
|
||||||
|
return this.items[this.items.length - 1];
|
||||||
|
}
|
||||||
|
|
||||||
|
isEmpty(): boolean {
|
||||||
|
return this.items.length === 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
size(): number {
|
||||||
|
return this.items.length;
|
||||||
|
}
|
||||||
|
|
||||||
|
clear(): void {
|
||||||
|
this.items = [];
|
||||||
|
}
|
||||||
|
|
||||||
|
toArray(): T[] {
|
||||||
|
return [...this.items];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,142 @@
|
|||||||
|
import type { TreeNode } from '../bash/fs';
|
||||||
|
//import { type ILocale } from './localeRegistry';
|
||||||
|
import { Terminal, type PageCallbacks, type TermInitArgs } from './terminal';
|
||||||
|
|
||||||
|
let initializing = $state(true);
|
||||||
|
|
||||||
|
export function isInitializing(): boolean {
|
||||||
|
return initializing;
|
||||||
|
}
|
||||||
|
|
||||||
|
function jsonToNodeTable(data: JSON): Map<number, TreeNode> {
|
||||||
|
const FsTable: Map<number, TreeNode> = new Map<number, TreeNode>();
|
||||||
|
const entryList = Object.entries(data);
|
||||||
|
|
||||||
|
for (let i = 0; i < entryList.length; i++) {
|
||||||
|
const object: any = entryList[i][1];
|
||||||
|
const node: TreeNode = {
|
||||||
|
inode: object.Inode,
|
||||||
|
name: object.Name,
|
||||||
|
type: object.Type,
|
||||||
|
size: object.Size,
|
||||||
|
interactible: object.Interactible,
|
||||||
|
func: object.Func,
|
||||||
|
children: object.Children,
|
||||||
|
content: object.Content,
|
||||||
|
link: object.Target,
|
||||||
|
permission: {
|
||||||
|
user: {
|
||||||
|
r: object.Permission[0]?.Read,
|
||||||
|
w: object.Permission[0]?.Write,
|
||||||
|
x: object.Permission[0]?.Exec
|
||||||
|
},
|
||||||
|
group: {
|
||||||
|
r: object.Permission[1]?.Read,
|
||||||
|
w: object.Permission[1]?.Write,
|
||||||
|
x: object.Permission[1]?.Exec
|
||||||
|
},
|
||||||
|
other: {
|
||||||
|
r: object.Permission[2]?.Read,
|
||||||
|
w: object.Permission[2]?.Write,
|
||||||
|
x: object.Permission[2]?.Exec
|
||||||
|
}
|
||||||
|
},
|
||||||
|
owner: object.Owner,
|
||||||
|
group: object.Group,
|
||||||
|
timestamps: {
|
||||||
|
modified: new Date(object.TimeStamps.MTime),
|
||||||
|
changed: new Date(object.TimeStamps.CTime),
|
||||||
|
accessed: new Date(object.TimeStamps.ATime)
|
||||||
|
},
|
||||||
|
parent: object.Parent
|
||||||
|
};
|
||||||
|
|
||||||
|
FsTable.set(object.Inode, node);
|
||||||
|
}
|
||||||
|
return FsTable;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function fetchFsJson(sig: string): Promise<JSON> {
|
||||||
|
const signature: string | null = localStorage.getItem('signature');
|
||||||
|
|
||||||
|
if (signature !== sig || signature === null || localStorage.getItem('fs') === null) {
|
||||||
|
const fs: JSON = await fetchFileSystem('/src/lib/assets/fs/fs.json');
|
||||||
|
localStorage.setItem('signature', sig);
|
||||||
|
localStorage.setItem('fs', JSON.stringify(fs));
|
||||||
|
|
||||||
|
console.info('FS fetched from file, new sinature:', sig);
|
||||||
|
|
||||||
|
return fs;
|
||||||
|
} else {
|
||||||
|
const fs: string | null = localStorage.getItem('fs');
|
||||||
|
if (fs === null) throw new Error('FS in LocalStorage is null!');
|
||||||
|
|
||||||
|
console.info('FS fetched from localStorage with signature:', sig);
|
||||||
|
|
||||||
|
return JSON.parse(fs);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function fetchFsSignature(path: string): Promise<any> {
|
||||||
|
try {
|
||||||
|
const response = await fetch(path);
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error(`HTTP error! status: ${response.status}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const data = await response.text();
|
||||||
|
return data.slice(0, 36); //32 characters of uuid + 4 dashes
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Failed to fetch the file system signature', error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function fetchFileSystem(path: string): Promise<any> {
|
||||||
|
const response = await fetch(path);
|
||||||
|
if (!response.ok) throw new Error('Failed to fetch the file system json');
|
||||||
|
|
||||||
|
const data = await response.json();
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function fetchLocale(id: string): Promise<any> {
|
||||||
|
const response = await fetch(`/src/lib/assets/locales/terminal/${id}.json`);
|
||||||
|
if (!response.ok) throw new Error('Failed to fetch the chosen locale');
|
||||||
|
|
||||||
|
const data = await response.json();
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function initTerminal(
|
||||||
|
user: { username: string; password: string },
|
||||||
|
callbackInit: PageCallbacks,
|
||||||
|
localeId: string
|
||||||
|
): Promise<Shell> {
|
||||||
|
try {
|
||||||
|
const sig = await fetchFsSignature('/src/lib/assets/fs/signature');
|
||||||
|
const fsJson: JSON = await fetchFsJson(sig);
|
||||||
|
const fs: Map<number, TreeNode> = jsonToNodeTable(fsJson);
|
||||||
|
/* const locale: ILocale = {
|
||||||
|
id: localeId,
|
||||||
|
keys: fetchLocale(localeId)
|
||||||
|
}; */
|
||||||
|
|
||||||
|
const args: TermInitArgs = {
|
||||||
|
//locale,
|
||||||
|
bash: {
|
||||||
|
fs,
|
||||||
|
user
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const terminal = new Terminal(args);
|
||||||
|
terminal.registerCallbacks(callbackInit);
|
||||||
|
|
||||||
|
return terminal;
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Failed to initialize terminal:', error);
|
||||||
|
throw error;
|
||||||
|
} finally {
|
||||||
|
initializing = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
export type Modifier = 'Ctrl' | 'Alt' | 'Shift';
|
||||||
|
|
||||||
|
type KeyStroke = {
|
||||||
|
key: string;
|
||||||
|
modifiers?: Modifier[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export type KeyBind = [KeyStroke] | [KeyStroke, KeyStroke];
|
||||||
|
|
||||||
|
const sigint: KeyBind = [{
|
||||||
|
key: 'c',
|
||||||
|
modifiers: ['Ctrl']
|
||||||
|
}];
|
||||||
|
|
||||||
|
export const TERMINAL_KEYBINDS = {
|
||||||
|
sigint
|
||||||
|
} as const satisfies Record<string, KeyBind>;
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
/* export interface ILocale {
|
||||||
|
id: string;
|
||||||
|
keys?: {};
|
||||||
|
SetKeys: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
const en_US: ILocale = {
|
||||||
|
id: 'en_US',
|
||||||
|
keys: {},
|
||||||
|
|
||||||
|
SetKeys(): () {
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export const LOCALES = {
|
||||||
|
en_US
|
||||||
|
} as const satisfies Record<string, ILocale>; */
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
import { mount, unmount } from 'svelte';
|
||||||
|
import Output from '../../../../modules/terminal/Output.svelte';
|
||||||
|
import { isInitializing } from '../init.svelte';
|
||||||
|
import type { PrintData } from '../terminal';
|
||||||
|
|
||||||
|
interface OutputProps {
|
||||||
|
path: string;
|
||||||
|
output: any;
|
||||||
|
cmd: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
const outputInstances = new Set<Output>();
|
||||||
|
|
||||||
|
function appendOutput(container: HTMLElement, props: OutputProps): Output | undefined {
|
||||||
|
if (!container) return;
|
||||||
|
const instance = mount(Output, {
|
||||||
|
target: container,
|
||||||
|
props
|
||||||
|
});
|
||||||
|
|
||||||
|
outputInstances.add(instance);
|
||||||
|
return instance;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function print(e: HTMLElement, data: PrintData): void {
|
||||||
|
if (data.cmd == 'clear') return;
|
||||||
|
|
||||||
|
if (isInitializing()) {
|
||||||
|
console.error('Terminal is initializing! Skipping Print');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
appendOutput(e, {
|
||||||
|
path: data.path,
|
||||||
|
output: data.output,
|
||||||
|
cmd: data.cmd
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function clear(): void {
|
||||||
|
for (const instance of outputInstances) {
|
||||||
|
unmount(instance, {});
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,196 @@
|
|||||||
|
import { Bash, type BashInitArgs, type Result } from '../bash/bash';
|
||||||
|
import type { CommandArgs } from '../bash/commandRegistry';
|
||||||
|
import type { User } from '../bash/etc/userData';
|
||||||
|
import { VirtualFS } from '../bash/fs';
|
||||||
|
import { KeybindInhibitor } from '../bash/keybindInhibitor';
|
||||||
|
import { ExitCode } from '../bash/metadata';
|
||||||
|
import type { Process } from '../bash/process';
|
||||||
|
import { TERMINAL_KEYBINDS, type KeyBind } from './keybindRegistry';
|
||||||
|
//import type { ILocale } from './localeRegistry';
|
||||||
|
|
||||||
|
export type TerminalMode = {};
|
||||||
|
|
||||||
|
export type TermInitArgs = {
|
||||||
|
bash: BashInitArgs;
|
||||||
|
//locale: ILocale
|
||||||
|
};
|
||||||
|
|
||||||
|
export type ParsedInput = {
|
||||||
|
command: string;
|
||||||
|
args: CommandArgs;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type PrintData = {
|
||||||
|
path: string;
|
||||||
|
output: any; // TODO: Make this be any predefined format of outputs like ls, ls w/ flags and so on;
|
||||||
|
cmd: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type PageCallbacks = {
|
||||||
|
print: (data: PrintData) => void;
|
||||||
|
clear: () => void;
|
||||||
|
getWidth: () => number;
|
||||||
|
getFontSize: () => number;
|
||||||
|
};
|
||||||
|
|
||||||
|
TermOS.Shell;
|
||||||
|
|
||||||
|
export class Terminal {
|
||||||
|
private _bash: Bash;
|
||||||
|
private _callbacks: Partial<PageCallbacks> = {};
|
||||||
|
private _keybindInhibitor: KeybindInhibitor;
|
||||||
|
|
||||||
|
//public isProcessActive: boolean = false;
|
||||||
|
//public locale: ILocale;
|
||||||
|
|
||||||
|
constructor(args: TermInitArgs) {
|
||||||
|
args.bash.io = this;
|
||||||
|
this._bash = new Bash(args.bash);
|
||||||
|
|
||||||
|
const keybinds: Map<KeyBind, () => any> = new Map([
|
||||||
|
[TERMINAL_KEYBINDS.sigint, this._processKill]
|
||||||
|
]);
|
||||||
|
|
||||||
|
this._keybindInhibitor = new KeybindInhibitor(keybinds);
|
||||||
|
|
||||||
|
//this.locale = args.locale;
|
||||||
|
}
|
||||||
|
|
||||||
|
private _processKill(): ExitCode {
|
||||||
|
const get: Process | ExitCode = this._bash.getProcess();
|
||||||
|
if (get == ExitCode.ERROR) return ExitCode.ERROR;
|
||||||
|
|
||||||
|
const process: Process = get;
|
||||||
|
const result = process.sigKill(() => {
|
||||||
|
console.log('process kill successful');
|
||||||
|
});
|
||||||
|
|
||||||
|
//this.isProcessActive = false;
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
private _parseInput(input: string): ParsedInput {
|
||||||
|
let args: string[] = [];
|
||||||
|
const result: ParsedInput = { command: '', args: { flags: [], args: [] } };
|
||||||
|
let current: string = '';
|
||||||
|
let inQuotes: boolean = false;
|
||||||
|
let quoteChar: string = '';
|
||||||
|
|
||||||
|
for (let i = 0; i < input.length; i++) {
|
||||||
|
const char = input[i];
|
||||||
|
|
||||||
|
if ((char === '"' || char === "'") && !inQuotes) {
|
||||||
|
inQuotes = true;
|
||||||
|
quoteChar = char;
|
||||||
|
continue;
|
||||||
|
} else if (char === quoteChar && inQuotes) {
|
||||||
|
inQuotes = false;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (char === ' ' && !inQuotes) {
|
||||||
|
if (current === '') continue;
|
||||||
|
|
||||||
|
result.command === '' ? (result.command = current) : args.push(current);
|
||||||
|
current = '';
|
||||||
|
} else {
|
||||||
|
current += char;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (current !== '') result.command === '' ? (result.command = current) : args.push(current);
|
||||||
|
|
||||||
|
for (let i = 0; i < args.length; i++) {
|
||||||
|
let curr = args[i];
|
||||||
|
console.log(curr);
|
||||||
|
|
||||||
|
if (curr.startsWith('--')) {
|
||||||
|
curr = curr.replaceAll('--', '');
|
||||||
|
if (curr.length === 0) continue;
|
||||||
|
|
||||||
|
result.args.flags.push(curr);
|
||||||
|
} else if (curr.startsWith('-')) {
|
||||||
|
curr = curr.replaceAll('-', '');
|
||||||
|
if (curr.length === 0) continue;
|
||||||
|
|
||||||
|
for (let n = 0; n < curr.length; n++) {
|
||||||
|
result.args.flags.push(curr[n]);
|
||||||
|
}
|
||||||
|
} else result.args.args.push(curr);
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
throwExeption(message: string, exitCode: ExitCode) {
|
||||||
|
console.error(message, exitCode);
|
||||||
|
}
|
||||||
|
|
||||||
|
executeCommand(input: string): Promise<Result> {
|
||||||
|
this._bash.updateHistory(input);
|
||||||
|
const parsed: ParsedInput = this._parseInput(input);
|
||||||
|
//console.log(parsed, 'executeCommand output');
|
||||||
|
|
||||||
|
return this._bash.executeCommand(parsed.command, parsed.args);
|
||||||
|
}
|
||||||
|
|
||||||
|
registerCallbacks(callbacks: PageCallbacks): void {
|
||||||
|
this._callbacks = callbacks;
|
||||||
|
}
|
||||||
|
|
||||||
|
clearTerminal() {
|
||||||
|
this._callbacks.clear?.();
|
||||||
|
}
|
||||||
|
|
||||||
|
getPrimaryKeybindInhibitor(): KeybindInhibitor {
|
||||||
|
const processKeybinds: KeybindInhibitor | null = this._bash.getProcessKeybindInhibitor();
|
||||||
|
if (processKeybinds) {
|
||||||
|
return processKeybinds;
|
||||||
|
} else {
|
||||||
|
return this._keybindInhibitor;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
getProcessKeyInhibitor(): KeybindInhibitor | ExitCode.ERROR {
|
||||||
|
const out = this._bash.getProcessKeybindInhibitor();
|
||||||
|
if (out) return out;
|
||||||
|
else return ExitCode.ERROR;
|
||||||
|
}
|
||||||
|
|
||||||
|
getKeybindInhibitor(): KeybindInhibitor {
|
||||||
|
return this._keybindInhibitor;
|
||||||
|
}
|
||||||
|
|
||||||
|
getUser(): User {
|
||||||
|
return this._bash.getUser();
|
||||||
|
}
|
||||||
|
|
||||||
|
getTerminalWidth(): number {
|
||||||
|
const width = this._callbacks.getWidth?.();
|
||||||
|
if (!width) {
|
||||||
|
throw new Error('somehow width is undefined still after all the checks');
|
||||||
|
}
|
||||||
|
|
||||||
|
return width;
|
||||||
|
}
|
||||||
|
|
||||||
|
getFontSize(): number {
|
||||||
|
const size = this._callbacks.getFontSize?.();
|
||||||
|
if (!size) {
|
||||||
|
throw new Error('somehow font size is undefined still after all the checks');
|
||||||
|
}
|
||||||
|
|
||||||
|
return size;
|
||||||
|
}
|
||||||
|
|
||||||
|
getCwd(): string {
|
||||||
|
const fs: VirtualFS = this._bash.getFs();
|
||||||
|
console.log(fs.getPathByInode(this._bash.getCwd()));
|
||||||
|
return fs.formatPath(fs.getPathByInode(this._bash.getCwd()));
|
||||||
|
}
|
||||||
|
|
||||||
|
PrintOutput(data: PrintData) {
|
||||||
|
this._callbacks.print?.(data);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,30 +1,17 @@
|
|||||||
import { writable } from 'svelte/store';
|
import { writable } from 'svelte/store';
|
||||||
|
|
||||||
function getInitialTheme(): string {
|
function getInitalTheme(): string {
|
||||||
// On client, read from the data-theme attribute set by the blocking script
|
if (typeof window === 'undefined') return 'dark';
|
||||||
if (typeof document !== 'undefined') {
|
|
||||||
const theme = document.documentElement.getAttribute('data-theme');
|
const savedTheme: string | null = localStorage.getItem('theme');
|
||||||
if (theme === 'dark' || theme === 'light') return theme;
|
if (savedTheme === 'dark' || savedTheme === 'light') return savedTheme;
|
||||||
}
|
|
||||||
// Fallback (SSR or if script failed)
|
const sysPrefTheme = window.matchMedia('(prefers-color-scheme: dark)').matches;
|
||||||
if (typeof window !== 'undefined') {
|
return sysPrefTheme ? 'dark' : 'light';
|
||||||
return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
|
|
||||||
}
|
|
||||||
return 'dark';
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export const theme = writable(getInitialTheme());
|
export const theme = writable(getInitalTheme());
|
||||||
|
|
||||||
theme.subscribe((value) => {
|
theme.subscribe((value) => {
|
||||||
if (typeof document !== 'undefined') {
|
if (typeof window !== 'undefined') localStorage.setItem('theme', value);
|
||||||
document.documentElement.setAttribute('data-theme', value);
|
|
||||||
localStorage.setItem('theme', value);
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
|
|
||||||
// Optional: listen to system preference changes
|
|
||||||
if (typeof window !== 'undefined') {
|
|
||||||
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) => {
|
|
||||||
theme.set(e.matches ? 'dark' : 'light');
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,95 +0,0 @@
|
|||||||
import { Tween } from 'svelte/motion';
|
|
||||||
import { writable } from 'svelte/store';
|
|
||||||
|
|
||||||
export interface ToastMessage {
|
|
||||||
id: number;
|
|
||||||
type: 'success' | 'error' | 'info' | 'warn';
|
|
||||||
title: string;
|
|
||||||
message: string;
|
|
||||||
duration: number;
|
|
||||||
tween?: Tween<number>;
|
|
||||||
initial: number;
|
|
||||||
target: number;
|
|
||||||
hideProgress: boolean;
|
|
||||||
hideDismiss: boolean;
|
|
||||||
onClose?: (tm: ToastMessage) => void;
|
|
||||||
onClick?: (tm: ToastMessage) => void;
|
|
||||||
}
|
|
||||||
|
|
||||||
let toastId = 0;
|
|
||||||
export const toasts = writable<ToastMessage[]>([]);
|
|
||||||
|
|
||||||
export function addToast({
|
|
||||||
type,
|
|
||||||
title,
|
|
||||||
message,
|
|
||||||
duration,
|
|
||||||
initial,
|
|
||||||
target,
|
|
||||||
hideProgress,
|
|
||||||
hideDismiss,
|
|
||||||
onClose,
|
|
||||||
onClick
|
|
||||||
}: {
|
|
||||||
type: ToastMessage['type'];
|
|
||||||
title?: string;
|
|
||||||
message?: string;
|
|
||||||
duration?: number;
|
|
||||||
initial?: number;
|
|
||||||
target?: number;
|
|
||||||
hideProgress?: boolean;
|
|
||||||
hideDismiss?: boolean;
|
|
||||||
onClose?: (tm: ToastMessage) => void;
|
|
||||||
onClick?: (tm: ToastMessage) => void;
|
|
||||||
}) {
|
|
||||||
const id = ++toastId;
|
|
||||||
title = title ?? '';
|
|
||||||
message = message ?? '';
|
|
||||||
duration = duration ?? 3000;
|
|
||||||
initial = initial ?? 100;
|
|
||||||
target = target ?? 0;
|
|
||||||
hideProgress = hideProgress ?? false;
|
|
||||||
hideDismiss = hideDismiss ?? false;
|
|
||||||
|
|
||||||
let isPermament: boolean = duration === 0 || duration === Infinity;
|
|
||||||
|
|
||||||
if (hideDismiss) isPermament = false;
|
|
||||||
if (isPermament) hideProgress = true;
|
|
||||||
|
|
||||||
let tween: Tween<number> | undefined;
|
|
||||||
|
|
||||||
if (!isPermament) {
|
|
||||||
tween = new Tween(initial, { duration: duration });
|
|
||||||
tween.set(target).then(() => {
|
|
||||||
removeToast(id);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
toasts.update((t) => [
|
|
||||||
...t,
|
|
||||||
{
|
|
||||||
id,
|
|
||||||
type,
|
|
||||||
title,
|
|
||||||
message,
|
|
||||||
duration,
|
|
||||||
tween,
|
|
||||||
initial,
|
|
||||||
target,
|
|
||||||
hideProgress,
|
|
||||||
hideDismiss,
|
|
||||||
onClose,
|
|
||||||
onClick
|
|
||||||
}
|
|
||||||
]);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function removeToast(id: number) {
|
|
||||||
let closedToast: ToastMessage | undefined;
|
|
||||||
toasts.update((ts) => {
|
|
||||||
closedToast = ts.find((t) => t.id === id);
|
|
||||||
return ts.filter((t) => t.id !== id);
|
|
||||||
});
|
|
||||||
|
|
||||||
if (closedToast?.onClose) closedToast.onClose(closedToast);
|
|
||||||
}
|
|
||||||
@@ -1,4 +0,0 @@
|
|||||||
export function capitalize(word: string): string {
|
|
||||||
if (!word) '';
|
|
||||||
return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase();
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
import { Command } from '../shell/command';
|
||||||
|
|
||||||
|
export class cd extends Command {}
|
||||||
@@ -0,0 +1,353 @@
|
|||||||
|
import type { User } from '../shell/shell';
|
||||||
|
|
||||||
|
export class FileSystem {
|
||||||
|
static #instance: FileSystem;
|
||||||
|
private _fs: Map<number, TreeNode>;
|
||||||
|
private _root: number;
|
||||||
|
|
||||||
|
private constructor(fs: Map<number, TreeNode>) {
|
||||||
|
this._fs = fs;
|
||||||
|
this._root = this._fs.values().next().value!.inode;
|
||||||
|
|
||||||
|
if (!this._root) throw new Error('First entry in the filesystem map empty!');
|
||||||
|
}
|
||||||
|
|
||||||
|
public static async Init(fsJson: JSON) {
|
||||||
|
//const fsChecksum = MD5.hash(JSON.stringify(fsJson));
|
||||||
|
|
||||||
|
/*
|
||||||
|
const cache: string | null = localStorage.getItem('fs-json');
|
||||||
|
if (cache) {
|
||||||
|
const fsCacheChecksum = MD5.hash(cache);
|
||||||
|
|
||||||
|
console.log(fsChecksum);
|
||||||
|
console.log(fsCacheChecksum);
|
||||||
|
|
||||||
|
if (fsChecksum !== fsCacheChecksum) {
|
||||||
|
//calculate version control difference to preserve user made changes (do a merge)
|
||||||
|
}
|
||||||
|
fsJson = JSON.parse(cache);
|
||||||
|
}
|
||||||
|
|
||||||
|
localStorage.setItem('fs-json', JSON.stringify(fsJson));
|
||||||
|
*/
|
||||||
|
|
||||||
|
const fs: Map<number, TreeNode> = this._jsonToNodeTable(fsJson);
|
||||||
|
|
||||||
|
// This produces a different checksum!
|
||||||
|
// Find a way to produce the same hash from Map and a fetched json file or cached stringified json
|
||||||
|
|
||||||
|
FileSystem.#instance = new FileSystem(fs);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* private async _fetchFsSignature(path: string): Promise<any> {
|
||||||
|
try {
|
||||||
|
const response = await fetch(path);
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error(`HTTP error! status: ${response.status}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const data = await response.text();
|
||||||
|
return data.slice(0, 36); //32 characters of uuid + 4 dashes
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Failed to fetch the file system signature', error);
|
||||||
|
}
|
||||||
|
} */
|
||||||
|
|
||||||
|
/* private static async fetchFsJson(): Promise<JSON> {
|
||||||
|
const checksum: string | null = localStorage.getItem('fs-checksum');
|
||||||
|
|
||||||
|
if (checksum !== sig || signature === null || localStorage.getItem('fs') === null) {
|
||||||
|
const fs: JSON = await this._fetchFileSystem('/src/lib/assets/fs/fs.json');
|
||||||
|
localStorage.setItem('signature', sig);
|
||||||
|
localStorage.setItem('fs', JSON.stringify(fs));
|
||||||
|
|
||||||
|
console.info('FS fetched from file, new sinature:', sig);
|
||||||
|
|
||||||
|
return fs;
|
||||||
|
} else {
|
||||||
|
const fs: string | null = localStorage.getItem('fs');
|
||||||
|
if (fs === null) throw new Error('FS in LocalStorage is null!');
|
||||||
|
|
||||||
|
console.info('FS fetched from localStorage with signature:', sig);
|
||||||
|
|
||||||
|
return JSON.parse(fs);
|
||||||
|
}
|
||||||
|
} */
|
||||||
|
|
||||||
|
private static _jsonToNodeTable(data: JSON): Map<number, TreeNode> {
|
||||||
|
const FsTable: Map<number, TreeNode> = new Map<number, TreeNode>();
|
||||||
|
const entryList = Object.entries(data);
|
||||||
|
|
||||||
|
for (let i = 0; i < entryList.length; i++) {
|
||||||
|
const object: any = entryList[i][1];
|
||||||
|
const node: TreeNode = {
|
||||||
|
inode: object.Inode,
|
||||||
|
name: object.Name,
|
||||||
|
type: object.Type,
|
||||||
|
size: object.Size,
|
||||||
|
interactible: object.Interactible,
|
||||||
|
func: object.Func,
|
||||||
|
children: object.Children,
|
||||||
|
content: object.Content,
|
||||||
|
link: object.Target,
|
||||||
|
permission: {
|
||||||
|
user: {
|
||||||
|
r: object.Permission[0]?.Read,
|
||||||
|
w: object.Permission[0]?.Write,
|
||||||
|
x: object.Permission[0]?.Exec
|
||||||
|
},
|
||||||
|
group: {
|
||||||
|
r: object.Permission[1]?.Read,
|
||||||
|
w: object.Permission[1]?.Write,
|
||||||
|
x: object.Permission[1]?.Exec
|
||||||
|
},
|
||||||
|
other: {
|
||||||
|
r: object.Permission[2]?.Read,
|
||||||
|
w: object.Permission[2]?.Write,
|
||||||
|
x: object.Permission[2]?.Exec
|
||||||
|
}
|
||||||
|
},
|
||||||
|
owner: object.Owner,
|
||||||
|
group: object.Group,
|
||||||
|
timestamps: {
|
||||||
|
modified: new Date(object.TimeStamps.MTime),
|
||||||
|
changed: new Date(object.TimeStamps.CTime),
|
||||||
|
accessed: new Date(object.TimeStamps.ATime)
|
||||||
|
},
|
||||||
|
parent: object.Parent
|
||||||
|
};
|
||||||
|
|
||||||
|
FsTable.set(object.Inode, node);
|
||||||
|
}
|
||||||
|
return FsTable;
|
||||||
|
}
|
||||||
|
|
||||||
|
private _createNode(name: string, type: Type, path: number, user: User): void {
|
||||||
|
const currTime: Date = new Date();
|
||||||
|
|
||||||
|
const node: TreeNode = {
|
||||||
|
parent: path,
|
||||||
|
inode: this._fs.size + 1,
|
||||||
|
name: name,
|
||||||
|
type: type,
|
||||||
|
size: 4096,
|
||||||
|
children: [],
|
||||||
|
content: '',
|
||||||
|
link: -1,
|
||||||
|
permission: {
|
||||||
|
user: {
|
||||||
|
r: true,
|
||||||
|
w: true,
|
||||||
|
x: false
|
||||||
|
},
|
||||||
|
group: {
|
||||||
|
r: true,
|
||||||
|
w: false,
|
||||||
|
x: false
|
||||||
|
},
|
||||||
|
other: {
|
||||||
|
r: true,
|
||||||
|
w: false,
|
||||||
|
x: false
|
||||||
|
}
|
||||||
|
},
|
||||||
|
owner: user.uid,
|
||||||
|
group: user.gid,
|
||||||
|
timestamps: {
|
||||||
|
modified: currTime,
|
||||||
|
changed: currTime,
|
||||||
|
accessed: currTime
|
||||||
|
},
|
||||||
|
interactible: false,
|
||||||
|
func: null
|
||||||
|
};
|
||||||
|
|
||||||
|
this._fs.set(this._fs.size + 1, node);
|
||||||
|
}
|
||||||
|
|
||||||
|
private _deleteNode(inode: number): void {
|
||||||
|
this._fs.delete(inode);
|
||||||
|
}
|
||||||
|
|
||||||
|
private _iNodeToPathString(inode: number): string {
|
||||||
|
const currentNode = this._fs.get(inode);
|
||||||
|
|
||||||
|
if (!currentNode)
|
||||||
|
throw new Error(`Failed to parse the path from inode, inode doesnt exist - ${inode}`);
|
||||||
|
if (!currentNode.parent || currentNode.inode === this._root) return '/';
|
||||||
|
|
||||||
|
const parentPath: string | null = this._iNodeToPathString(currentNode.parent);
|
||||||
|
if (!parentPath)
|
||||||
|
throw new Error(
|
||||||
|
`Failed to parse the path from inode, inode doesnt exist - ${currentNode.parent}`
|
||||||
|
);
|
||||||
|
|
||||||
|
return parentPath === '/' ? `/${currentNode.name}` : `${parentPath}/${currentNode.name}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
private _pathStringToNode(path: string): TreeNode {
|
||||||
|
// Truncates all slatshes at the start and end of the string
|
||||||
|
const normalizedPath: string = path.replace(/^\/+|\/+$/g, '');
|
||||||
|
|
||||||
|
// Splits the path to node names and filters them out from empty strings
|
||||||
|
const pathComponents: string[] = normalizedPath.split('/').filter((node) => node.length > 0);
|
||||||
|
|
||||||
|
let currentNode: TreeNode | undefined = this._fs.get(this._root);
|
||||||
|
if (!currentNode)
|
||||||
|
throw new Error(`WARNING! - Root node not found under FileSystem._root - ${this._root}`);
|
||||||
|
if (pathComponents.length === 0) return currentNode;
|
||||||
|
|
||||||
|
for (const component of pathComponents) {
|
||||||
|
const childINode: number = this._getChildNodeByName(currentNode!, component)?.inode;
|
||||||
|
|
||||||
|
if (!childINode)
|
||||||
|
throw new Error(`Failed to parse the child node from path, is the path correct?`);
|
||||||
|
|
||||||
|
const nextNode = this._fs.get(childINode);
|
||||||
|
if (!nextNode)
|
||||||
|
throw new Error(`Failed to parse the child node from path, is the path correct?`);
|
||||||
|
|
||||||
|
currentNode = nextNode;
|
||||||
|
}
|
||||||
|
|
||||||
|
return currentNode;
|
||||||
|
}
|
||||||
|
|
||||||
|
private _getChildNodeByName(node: TreeNode, name: string): TreeNode {
|
||||||
|
for (const inode of node.children) {
|
||||||
|
const child = this._fs.get(inode);
|
||||||
|
if (child && child.name === name) return child;
|
||||||
|
}
|
||||||
|
throw new Error(
|
||||||
|
`Node under the name ${name} not found in the child list of ${node.name} - ${node.inode}`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
private _isAbsolutePath = (path: string): boolean => {
|
||||||
|
return typeof path === 'string' && path.startsWith('/');
|
||||||
|
};
|
||||||
|
|
||||||
|
public getPathByINode(inode: number): string {
|
||||||
|
return this._iNodeToPathString(inode);
|
||||||
|
}
|
||||||
|
|
||||||
|
public formatPath(path: string, user: User): string {
|
||||||
|
if (path.startsWith(user.home)) return path.replace(user.home, '~');
|
||||||
|
return path;
|
||||||
|
}
|
||||||
|
|
||||||
|
public getNodeByInode(inode: number): TreeNode {
|
||||||
|
const node: TreeNode | undefined = this._fs.get(inode);
|
||||||
|
if (!node) throw new Error(`No node exists under inode - ${inode}`);
|
||||||
|
return node;
|
||||||
|
}
|
||||||
|
|
||||||
|
public resolvePath(path: string, user: User): TreeNode {
|
||||||
|
if (path === '/') return this._fs.get(this._root)!;
|
||||||
|
|
||||||
|
let parsedPath: string = path;
|
||||||
|
|
||||||
|
if (!this._isAbsolutePath(path)) {
|
||||||
|
const trail = this._iNodeToPathString(user.cwd!);
|
||||||
|
if (!trail)
|
||||||
|
throw new Error('Somehow the current user has his cwd set to a nonexistant directory', {
|
||||||
|
cause: 'iNodeToPathString returned null from user.cwd'
|
||||||
|
});
|
||||||
|
parsedPath = `${trail}/${path}`;
|
||||||
|
}
|
||||||
|
if (path.startsWith('~')) {
|
||||||
|
const trail = user.home;
|
||||||
|
if (!trail)
|
||||||
|
throw new Error('User has his home directory set to a nonexistant one or is undefined', {
|
||||||
|
cause: 'iNodeToPathString returned null from user.home'
|
||||||
|
});
|
||||||
|
parsedPath = `${trail}/${path.replace('~', '')}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
return this._pathStringToNode(parsedPath);
|
||||||
|
}
|
||||||
|
|
||||||
|
public recursiveTraversalPre(
|
||||||
|
node: TreeNode,
|
||||||
|
callback: (param: TreeNode) => void,
|
||||||
|
childIndex?: number[],
|
||||||
|
depthIndex?: number
|
||||||
|
): void {
|
||||||
|
if (!depthIndex) depthIndex = 0;
|
||||||
|
if (!childIndex) childIndex = [0];
|
||||||
|
|
||||||
|
if (node.type != Type.File && node.children[childIndex[depthIndex]]) {
|
||||||
|
let unNode = this._fs.get(node.children[childIndex[depthIndex]]);
|
||||||
|
if (!unNode)
|
||||||
|
throw new Error(`Node does not exist under inode ${node.children[childIndex[depthIndex]]}`);
|
||||||
|
node = unNode;
|
||||||
|
|
||||||
|
depthIndex++;
|
||||||
|
if (!childIndex[depthIndex]) childIndex[depthIndex] = 0;
|
||||||
|
|
||||||
|
callback(node);
|
||||||
|
} else {
|
||||||
|
let unNode = this._fs.get(node.parent);
|
||||||
|
if (!unNode) throw new Error(`Node does not exist under inode ${node.parent}`);
|
||||||
|
node = unNode;
|
||||||
|
|
||||||
|
childIndex[depthIndex] = 0;
|
||||||
|
depthIndex--;
|
||||||
|
childIndex[depthIndex]++;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (depthIndex < 0) return;
|
||||||
|
|
||||||
|
this.recursiveTraversalPre(node, callback, childIndex, depthIndex);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static get instance(): FileSystem {
|
||||||
|
if (!FileSystem.#instance) {
|
||||||
|
throw new Error(`FileSystem was not initialized properly!`);
|
||||||
|
}
|
||||||
|
|
||||||
|
return FileSystem.#instance;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export type TreeNode = {
|
||||||
|
inode: number;
|
||||||
|
parent: number;
|
||||||
|
name: string;
|
||||||
|
type: Type;
|
||||||
|
size: number; //Size in Bytes
|
||||||
|
children: number[];
|
||||||
|
content: string; // GUID of the cache file that contains the file contents.
|
||||||
|
link: number; // Links
|
||||||
|
permission: NodePermission;
|
||||||
|
owner: number;
|
||||||
|
group: number;
|
||||||
|
timestamps: TimeStamps;
|
||||||
|
interactible: boolean;
|
||||||
|
func: any;
|
||||||
|
};
|
||||||
|
|
||||||
|
export enum Type {
|
||||||
|
Directory = 16384,
|
||||||
|
File = 32768,
|
||||||
|
SymbolicLink = 40960
|
||||||
|
}
|
||||||
|
|
||||||
|
export type NodePermission = {
|
||||||
|
user: Permission;
|
||||||
|
group: Permission;
|
||||||
|
other: Permission;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type Permission = {
|
||||||
|
r: boolean;
|
||||||
|
w: boolean;
|
||||||
|
x: boolean;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type TimeStamps = {
|
||||||
|
modified: Date;
|
||||||
|
changed: Date;
|
||||||
|
accessed: Date;
|
||||||
|
};
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
export abstract class Command {
|
||||||
|
public abstract readonly _flags: CommandFlag[];
|
||||||
|
public abstract readonly _root: boolean;
|
||||||
|
//public abstract readonly _keybinds?: Map<KeyBind, () => any>;
|
||||||
|
public abstract readonly _help: string; //TODO: Dont know where to pull the help text from yet
|
||||||
|
public abstract result: CommandResult;
|
||||||
|
|
||||||
|
public abstract Main(flags: CommandFlag[], args: string[]): void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type CommandFlag = {
|
||||||
|
flag: string;
|
||||||
|
values?: string[];
|
||||||
|
};
|
||||||
|
|
||||||
|
export type CommandResult = {
|
||||||
|
bin: string;
|
||||||
|
flags?: CommandFlag[];
|
||||||
|
args?: string[];
|
||||||
|
path: number;
|
||||||
|
exitcode: ExitCode;
|
||||||
|
data?: any;
|
||||||
|
};
|
||||||
@@ -0,0 +1,67 @@
|
|||||||
|
import type { Command, CommandResult } from "./command";
|
||||||
|
|
||||||
|
export class Process {
|
||||||
|
private _shell: Shell;
|
||||||
|
private _uid: number;
|
||||||
|
private _name: string;
|
||||||
|
private _timestamp: Date;
|
||||||
|
//private _keybindInhibitor?: KeybindInhibitor;
|
||||||
|
private _abortController: AbortController;
|
||||||
|
private _result: CommandResult;
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
bash: Shell,
|
||||||
|
uid: number,
|
||||||
|
name: string,
|
||||||
|
command: Command,
|
||||||
|
args: CommandArgs
|
||||||
|
) {
|
||||||
|
this._shell = shell;
|
||||||
|
|
||||||
|
this._uid = uid;
|
||||||
|
this._name = name;
|
||||||
|
this._timestamp = new Date();
|
||||||
|
this._abortController = new AbortController();
|
||||||
|
|
||||||
|
this._result: CommandResult = { exitCode: ExitCode.ERROR, path: this._bash.getCwd() }
|
||||||
|
|
||||||
|
if(command._keybinds) {
|
||||||
|
this._keybindInhibitor = new KeybindInhibitor(command.keybinds)
|
||||||
|
}
|
||||||
|
|
||||||
|
this._Exec(command, bash, args);
|
||||||
|
}
|
||||||
|
|
||||||
|
public getKeybindInhibitor(): KeybindInhibitor | null {
|
||||||
|
if(this._keybindInhibitor) return this._keybindInhibitor;
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
public sigKill(callback: () => void): ExitCode {
|
||||||
|
this._abortController.abort();
|
||||||
|
callback();
|
||||||
|
|
||||||
|
return ExitCode.INT;
|
||||||
|
}
|
||||||
|
|
||||||
|
public get Uid(): number {
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
public get Timestamp(): Date {
|
||||||
|
return this._timestamp;
|
||||||
|
}
|
||||||
|
|
||||||
|
public get Name(): string {
|
||||||
|
return this._name
|
||||||
|
}
|
||||||
|
|
||||||
|
public async get Result(): Promise<CommandResult> {
|
||||||
|
return this._result;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async _Exec(command: Command, shell: Shell, flags: CommandFlag[], args: string[]) {
|
||||||
|
this._result = Command.
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
import type { Stack } from '$lib/stores/stack';
|
||||||
|
import type { Command } from './command';
|
||||||
|
import type { Process } from './process';
|
||||||
|
|
||||||
|
export class Shell {
|
||||||
|
private _passwd: User[];
|
||||||
|
private _group: Group[];
|
||||||
|
|
||||||
|
private _commands: Command[];
|
||||||
|
|
||||||
|
private _userSessions: Stack<User>;
|
||||||
|
|
||||||
|
private user: User;
|
||||||
|
private _process?: Process;
|
||||||
|
|
||||||
|
constructor() {}
|
||||||
|
|
||||||
|
public static Initialize(
|
||||||
|
username: string,
|
||||||
|
password: string,
|
||||||
|
commands: Map<string, Command>,
|
||||||
|
passwd: Map<number, User>,
|
||||||
|
group: Map<number, Group>
|
||||||
|
) {}
|
||||||
|
}
|
||||||
|
|
||||||
|
export enum ExitCode {
|
||||||
|
OK = 0,
|
||||||
|
ERR = 1,
|
||||||
|
INT = 2
|
||||||
|
}
|
||||||
|
|
||||||
|
export type User = {
|
||||||
|
username: string;
|
||||||
|
password: string;
|
||||||
|
readonly uid: number;
|
||||||
|
readonly gid: number;
|
||||||
|
home: string;
|
||||||
|
accessible: boolean;
|
||||||
|
history: string;
|
||||||
|
cwd?: number;
|
||||||
|
pwd?: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type Group = {
|
||||||
|
groupname: string;
|
||||||
|
gid: number;
|
||||||
|
members: number[];
|
||||||
|
};
|
||||||