Repository: 0neGal/viper Branch: main Commit: 8cf3d60c8f8c Files: 83 Total size: 376.1 KB Directory structure: gitextract_gg5zgg59/ ├── .github/ │ ├── FUNDING.yml │ ├── ISSUE_TEMPLATE/ │ │ ├── bug_report.md │ │ ├── empty-template.md │ │ └── feature_request.md │ └── workflows/ │ ├── dev_builds.yml │ ├── localizations.yml │ └── release_builds.yml ├── .gitignore ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── FAQ.md ├── LICENSE ├── PUBLISH.md ├── README.md ├── docs/ │ ├── index.html │ ├── main.css │ ├── main.js │ └── redirect.js ├── package.json ├── scripts/ │ ├── downloads.js │ ├── langs.js │ └── publish.sh └── src/ ├── app/ │ ├── css/ │ │ ├── dragui.css │ │ ├── grid.css │ │ ├── launcher.css │ │ ├── popups.css │ │ ├── selection.css │ │ ├── theming.css │ │ ├── toasts.css │ │ ├── tooltip.css │ │ └── webview.css │ ├── fonts/ │ │ └── import.css │ ├── index.html │ ├── js/ │ │ ├── browser.js │ │ ├── dom_events.js │ │ ├── events.js │ │ ├── gamepad.js │ │ ├── gamepath.js │ │ ├── is_running.js │ │ ├── kill.js │ │ ├── launch.js │ │ ├── launcher.js │ │ ├── localize.js │ │ ├── mods.js │ │ ├── navigate.js │ │ ├── popups.js │ │ ├── process.js │ │ ├── request.js │ │ ├── set_buttons.js │ │ ├── settings.js │ │ ├── toasts.js │ │ ├── tooltip.js │ │ ├── update.js │ │ └── version.js │ ├── main.css │ └── main.js ├── cli.js ├── index.js ├── lang/ │ ├── de.json │ ├── en.json │ ├── es.json │ ├── fr.json │ ├── maintainers.json │ └── zh.json ├── lang.js ├── modules/ │ ├── console.js │ ├── findgame.js │ ├── gamepath.js │ ├── in_path.js │ ├── ipc.js │ ├── is_running.js │ ├── json.js │ ├── kill.js │ ├── launch.js │ ├── mods.js │ ├── packages.js │ ├── protocol.js │ ├── releases.js │ ├── requests.js │ ├── settings.js │ ├── update.js │ └── version.js └── win.js ================================================ FILE CONTENTS ================================================ ================================================ FILE: .github/FUNDING.yml ================================================ liberapay: 0neGal custom: ["github.com/R2Northstar"] ================================================ FILE: .github/ISSUE_TEMPLATE/bug_report.md ================================================ --- name: Bug report about: Create a bug report to help us fix problems title: 'bug: Short description of your bug' labels: bug assignees: '' --- **Describe the bug** A clear and concise description of what the bug is. **To Reproduce** Steps to reproduce the behavior: 1. Go to '...' 2. Click on '....' 3. Scroll down to '....' 4. See error **Expected behavior** A clear and concise description of what you expected to happen. **Screenshots** If applicable, add screenshots to help explain your problem. **Version:** If possible add on `--version` or simply the version of Viper **Additional Info** Any extra info should go here! ================================================ FILE: .github/ISSUE_TEMPLATE/empty-template.md ================================================ --- name: Empty Template about: An empty issue template with nothing in it. title: '' labels: '' assignees: '' --- ================================================ FILE: .github/ISSUE_TEMPLATE/feature_request.md ================================================ --- name: Feature request about: Suggest an idea or feature to be added to Viper title: 'feat: Your Feature' labels: enhancement assignees: '' --- **What feature would you like added?** A clear and concise description of the feature **Why should this feature be added?** What benefit does this feature offer? **Additional Info** Feel free to put anything here or delete it if not relevant. ================================================ FILE: .github/workflows/dev_builds.yml ================================================ name: Development builds CI on: push: pull_request: types: [opened, reopened] jobs: build-windows: name: "Create Windows development builds" runs-on: "windows-latest" steps: - name: Checkout repository uses: actions/checkout@v3 - name: Setup Node environment uses: actions/setup-node@v3 with: node-version: 20 - name: Install dependencies run: npm install - name: Create builds run: npm run build:windows - name: Archive production artifacts uses: actions/upload-artifact@v4 with: name: viper-windows-builds path: | dist/*.exe build-linux: name: "Create Linux development builds" runs-on: "ubuntu-latest" steps: - name: Checkout repository uses: actions/checkout@v3 - name: Setup Node environment uses: actions/setup-node@v3 with: node-version: 20 - name: Install dependencies run: npm install - name: Create builds run: npm run build:linux - name: Archive production artifacts uses: actions/upload-artifact@v4 with: name: viper-linux-builds path: | dist/*.AppImage dist/*.tar.gz dist/*.deb dist/*.rpm ================================================ FILE: .github/workflows/localizations.yml ================================================ name: Localizations on: push: pull_request: types: [opened, reopened] jobs: check-localizations: name: "Check localizations" runs-on: "ubuntu-latest" steps: - name: Checkout repository uses: actions/checkout@v3 - name: Setup Node environment uses: actions/setup-node@v3 with: node-version: 20 - name: Install dependencies run: npm install - name: Check localizations run: npm run langs:check ================================================ FILE: .github/workflows/release_builds.yml ================================================ name: Release CI on: release: types: [ prereleased ] jobs: build-windows: name: "Create Windows release builds" runs-on: "windows-latest" steps: - name: Checkout repository uses: actions/checkout@v3 - name: Setup Node environment uses: actions/setup-node@v3 with: node-version: 20 - name: Install dependencies run: npm install - name: Create builds run: npm run build:windows - name: Upload production artifacts to release uses: xresloader/upload-to-github-release@v1 env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} with: file: "dist/*.exe*;dist/latest.yml" release_id: ${{ github.event.release.id }} draft: false prerelease: true build-linux: name: "Create Linux release builds" runs-on: "ubuntu-latest" steps: - name: Checkout repository uses: actions/checkout@v3 - name: Setup Node environment uses: actions/setup-node@v3 with: node-version: 20 - name: Install dependencies run: npm install - name: Create builds run: npm run build:linux - name: Upload production artifacts to release uses: xresloader/upload-to-github-release@v1 env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} with: file: "dist/*.AppImage;dist/*.tar.gz;dist/*.deb;dist/*.rpm;dist/latest-linux.yml" release_id: ${{ github.event.release.id }} draft: false prerelease: true ================================================ FILE: .gitignore ================================================ .vscode/ dist/ node_modules/ ================================================ FILE: CODE_OF_CONDUCT.md ================================================


FAQ | Contributing | Releases

## Contributor Code of Conduct ### Our Pledge We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation. We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community. ### Our Standards Examples of behavior that contributes to a positive environment for our community include: - Demonstrating empathy and kindness toward other people - Being respectful of differing opinions, viewpoints, and experiences - Giving and gracefully accepting constructive feedback - Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience - Focusing on what is best not just for us as individuals, but for the overall community Examples of unacceptable behavior include: - The use of sexualized language or imagery, and sexual attention or advances of any kind - Trolling, insulting or derogatory comments, and personal or political attacks Public or private harassment Publishing others' private - information, such as a physical or email address, without their explicit permission - Other conduct which could reasonably be considered inappropriate in a professional setting ### Enforcement Responsibilities Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful. Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate. ### Scope This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. ### Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at mail@0negal.com or @0neGal on Twitter. All complaints will be reviewed and investigated promptly and fairly. All community leaders are obligated to respect the privacy and security of the reporter of any incident. ### Enforcement Guidelines Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct: #### 1. Correction **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community. **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested. #### 2. Warning **Community Impact**: A violation through a single incident or series of actions. **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban. #### 3. Temporary Ban **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior. **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban. #### 4. Permanent Ban **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals. **Consequence**: A permanent ban from any sort of public interaction within the community. ### Attribution This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0, available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity). [homepage]: https://www.contributor-covenant.org For answers to common questions about this code of conduct, see the FAQ at https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations. ================================================ FILE: CONTRIBUTING.md ================================================


FAQ | Contributing | Releases

## Contributing Generally speaking, as Viper is a FOSS (GPLv3) project any bug reports, pull requests, or other types of help, forks are appreciated, but preferably unless it's off-topic to the goals of Viper, it would be far more appreciated if you were to make a pull request, or similar, and get it upstream. **HOWEVER:** Before opening issues and pull requests and similar, please do read our code of conduct, as to avoid issues. ### General contributions If you're contributing, please follow code of conduct as mentioned above, along with that please do not change code style. Viper uses double quotes, 1 tab per indent, and semicolons at the end of function calls. `//` for 1-2 lines of comments, max of 72 comment text width always, preferably if textwidth outside of comments also exceeds 72 characters if possible find a way to make it fit within 72 characters. Lower case comments are also generally preferred when using `//` `/* */` is useful in some cases, refer to the code example below. `() => {}` is also preferred over `function () {}` when possible. Single use functions are also generally discouraged, if a function is used once there's no need to make it a function. As shown below below: ```js function foo(bar) { /* This is a very long comment, however, it does not exceed 72 characters, and instead wraps down so it fits nicely on a small screen without having to mess with soft-wrapping or similar. */ console.log(bar); // and this is a comment using "//", // which is two lines long } // examples of () => {} setInterval(() => { foo("I RUN EVERY 1000MS"); }, 1000) ``` With the above information you should be able to comfortably make contributions without too much hassle... ### Localizing/Translating Viper has a very simple i18n system, please read below for instructions. #### Language file The language file will be a file inside the `src/lang/` folder, name it according to the [ISO 3166-1 Alpha-2 standard](https://en.m.wikipedia.org/wiki/ISO_3166-1_alpha-2) in lowercase, meaning English = `en.json`, Spanish = `es.json`, French = `fr.json`, and so on. Everything inside the file is pretty straight forward, the only special one is the `lang.title` string, please set this to ` - `, meaning for French it's, `French - Français`. This will be shown inside the language selection screen. If you don't feel like editing a JSON file and copying keys back and forwards from other complete language files, then you're in luck, because `scripts/langs.js` help with this exact problem. Simply make sure a valid localization file already exists, meaning it could have just `{}` inside it. Then after that you can use the language script to manage it: ```sh $ npm install $ npm run langs:localize ``` You'll be prompted to select a language to edit, then if there are missing keys you'll be prompted for whether you just want to add those keys or if you want to edit all keys. After that you'll get a list of all the keys available, you'll simply select any of them, then you'll be prompted for the value for the key, then hit Enter when you're done, and you'll be put right back to the list of keys as before. You'll then edit as needed, when you're done select `Save changes`, you're changes will then be written to the localization file and it'll automatically be formatted for you. To sum it up: 1. Make sure a parseable JSON localization file exists in `src/lang/` 2. Run `npm run langs:localize` (after `npm install`) 3. Select your desired language 4. Select the key you want to add/change 5. Edit it as you wish 6. Save whenever your done 7. Commit your changes! If you do happen to manually edit your localization files remember to run the following commands before committing and pushing changes: ```sh $ npm install $ npm langs:check # verifies the files are parseable and not missing keys $ npm langs:format # formats and sorts the file for you ``` #### Maintainers file If you're okay with being contacted in the future when new strings have to be localized please put your contact links inside this file, under your language. Preferably put the link to your GitHub profile as that is the easiest contact method for obvious reasons. ================================================ FILE: FAQ.md ================================================


FAQ | Contributing | Releases

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



FAQ | Contributing | Releases

## What is Viper? Viper is a launcher and updater for [Northstar](https://github.com/R2Northstar/Northstar), and not much more than that. ## Install Downloads are available on the [releases page](https://github.com/0neGal/viper/releases/latest). Please note that some versions will update themselves automatically when a new release is available (just like Origin or Steam) and some will NOT, so choose it accordingly. Only the AppImage, Flatpak and Windows Setup/Installer can auto-update. **Windows:** [`Viper Setup [x.y.z].exe`](https://0negal.github.io/viper/index.html?win-setup) (auto-updates, and is recommended), [`Viper [x.y.z].exe`](https://0negal.github.io/viper/index.html?win-portable) (single executable, no fuss) **Linux:** [`.AppImage`](https://0negal.github.io/viper/index.html?appimage) or [Flatpak](https://flathub.org/apps/details/com.github._0negal.Viper) (auto-updates), [AUR (unofficial)](https://aur.archlinux.org/packages/viper-bin), [`.deb`](https://0negal.github.io/viper/index.html?deb), [`.rpm`](https://0negal.github.io/viper/index.html?rpm), [`.tar.gz`](https://0negal.github.io/viper/index.html?linux) GitHub release (latest by date) GitHub release downloads (latest by date) Flathub installs (Total) ## What can it do specifically?

Currently Viper is capable of: * Updating/Installing Northstar * Launching Vanilla and or Northstar * Manage Mods * Auto-Update itself * Be pretty! There are of course many other things that it can do, but summed up very simply, that is what Viper is capable of doing. With every update Viper gets more features and alike, often many optional features are also available in the settings menu.

## Configuration All settings take place in the settings page, found in the top right corner of the app, where you can change all kinds of settings. You can also manually go in and edit your config file (`viper.json`), if you feel so inclined. Your configuration file will be found in `%APPDATA%\viper.json` on Windows, and inside either `~/.config` or through your environment variables (`$XDG_CONFIG_HOME`) on Linux, the latter has priority. ## Support To get support please [open a GitHub issue](https://github.com/0neGal/viper/issues/new/choose), and clearly describe the problem with as many details as possible. ### Frequently Asked Questions (FAQ) Many of the questions and problems you may have might be able to be answered by reading the [FAQ page](FAQ.md). So before opening an issue or asking for support please read through it first! ## Sidenote Given that we already have so many Northstar updaters and launchers I urge people to instead of creating new launchers unless there's a very specific reason, just make a pull request on one of the existing ones, otherwise we'll continue to have new ones.

Relevant xkcd:

Some of the existing launchers are listed below: * Viper - A launcher, updater and mod manager with an easy to use GUI * [FlightCore](https://github.com/R2NorthstarTools/FlightCore) - A more minimal GUI manager and updater, with similar features to Viper * [ViperSH](https://github.com/0neGal/viper-sh) - A Bourne Shell, CLI only, Northstar updater and mod manager * [VTOL](https://github.com/BigSpice/VTOL) - an updater and manager for mods, very feature rich * [r2modman](https://github.com/ebkr/r2modmanPlus) - General purpose mod manager, which has support for Northstar * [Papa](https://github.com/AnActualEmerald/papa) - a CLI only installer, updater, and mod manager * [FIITE](https://github.com/EladNLG/FastestInstallerInTheEast) - a minimalistic CLI installer and updater. ## Development If you wanna edit Viper's code, run it, and so on, you can simply do something along the lines of the below: ```sh $ git clone https://github.com/0neGal/viper $ cd viper $ npm i $ npm run start ``` This'll launch it with the Electron build installed by `npm`. Additionally, if you're creating your own fork you easily publish builds and or make builds with either `npm run publish` or `npm run build` respectively, the prior requiring a `$GH_TOKEN` to be set, as it creates the release itself so it needs a token with access to your repo. So you'd do something along the lines of: ```sh $ GH_TOKEN="" npm run publish ``` Keep in mind building all Linux builds may take a while on some systems, as packaging the `tar.gz` release can take a while on many CPUs, at least from my testing. All other builds should be done quickly. When using the `publish` command it also automatically uploads the needed files to deploy auto-updates, keep in mind you'd need to have the `repository` setting changed to your new fork's location, otherwise it'll fetch from the original. ## Credits **Logo:** Imply#9781
**Viper Background:** [Uber Panzerhund](https://www.reddit.com/r/titanfall/comments/fwuh2x/take_to_the_skies)
**Titanfall+Northstar Logo:** [Aftonstjarma](https://www.steamgriddb.com/logo/47851) ================================================ FILE: docs/index.html ================================================ Viper
================================================ FILE: docs/main.css ================================================ /* base properties */ body, button { margin: 0; color: white; user-select: none; background: black; font-family: "Roboto", sans-serif; } /* positioning, sizing and everything for background elements */ .background, .background .color, .background .image { top: 0; left: 0; right: 0; bottom: 0; z-index: -1; position: fixed; background-size: cover; background-position: center; } /* tinted background color */ .background .color { background-color: rgb(0, 0, 0, 0.7); } /* background image elements */ .background .image { opacity: 0.0; transform: scale(1.0); background-position-x: 50%; transition: 0.8s opacity ease-in-out, 5.0s transform ease-out, 5.0s background-position-x ease-out; background-image: url("images/backgrounds/1.jpg"); } /* appear but dont animate */ .background .image.active-noanim { opacity: 1.0; } /* show and animate the image */ .background .image.active { opacity: 1.0; transform: scale(1.05); background-position-x: 25%; } /* main container for everything */ .main { width: 80vw; height: 100vh; display: flex; margin: 0 auto; max-width: 800px; position: relative; align-items: center; } /* actual containers with content */ .box { width: 100%; height: 80%; display: flex; max-height: 400px; border-radius: 15px; align-items: center; justify-content: center; } /* preview image */ .box .preview { width: 100%; cursor: default; border-radius: 15px; transition: 0.3s ease-in-out; transition-property: box-shadow, transform; box-shadow: 0px 8px 5px rgba(0, 0, 0, 0.1); } .box .preview:hover { transform: scale(1.05); box-shadow: 0px 5px 25px rgba(0, 0, 0, 0.4); } /* hide preview image devices with less than 900px in width */ @media (max-width: 900px) { .box:nth-child(2) { display: none; } } /* main div with text and content */ .info { text-align: center; } /* Viper logo+text */ .info .image { display: flex; align-items: center; justify-content: center; font-size: min(3vw, 30px); } /* Viper logo sizing */ .info .image img { width: 30%; max-width: 400px; } /* more download options link */ .info a { opacity: 0.8; color: #C7777F; text-decoration: none; transition: filter 0.2s ease-in; } .info a:hover { filter: brightness(80%); } /* big download button */ button { border: none; color: white; display: flex; margin: 15px auto; font-size: 24px; font-weight: bold; padding: 20px 40px; align-items: center; border-radius: 10px; justify-content: center; transition: 0.2s ease-in-out; background: linear-gradient(45deg, #81A1C1, #7380ED); filter: drop-shadow(0px 8px 5px rgba(0, 0, 0, 0.1)); } button:hover { transform: scale(1.05); filter: drop-shadow(0px 5px 15px rgba(0, 0, 0, 0.3)) brightness(110%); } button:active { opacity: 0.7;transform: scale(0.98); filter: drop-shadow(0px 5px 10px rgba(0, 0, 0, 0.4)); } /* platform icon in button */ button img { width: 28px; margin-right: 15px; } ================================================ FILE: docs/main.js ================================================ // change platform icon in "Download!" button if on Linux if (navigator.userAgent.match("Linux")) { document.querySelector("button img").src = "images/linux.png"; } // functionality of "Download!" button document.querySelector("button").addEventListener("click", () => { // if on Linux, navigate to .AppImage file if (navigator.userAgent.match("Linux")) { return location.replace("?appimage"); } // if not on Linux, navigate to .exe setup file location.replace("?win-setup"); }) // how many wallpapers are in images/backgrounds/ let backgrounds = 7; // initializes the elements for the backgrounds function init_backgrounds() { // run through `backgrounds` for (let i = 2; i < backgrounds + 1; i++) { // create background element let background = document.createElement("div"); // add relevant classes background.classList.add("image"); // set `background-image` CSS property background.style.backgroundImage = `url("images/backgrounds/${i}.jpg")`; // add image to DOM document.querySelector(".background .images").appendChild( background ) } }; init_backgrounds() // changes the current image to a random image, if the image picked is // the same as the one currently being shown, then we re-run this // function, aka duplicates do not happen! function change_background() { // get the ID for the new image let new_image = Math.floor(Math.random() * (backgrounds - 2) + 1); // get list of image elements let images = document.querySelector(".background .images").children; // if the new images is the current images, cancel and re-run if (images[new_image] == document.querySelector(".background .images .active")) { return change_background(); } // run through the images for (let i = 0; i < images.length; i++) { // if we're at the new active image, make it active if (i == new_image) { images[i].classList.add("active"); continue; } // remove any possible `.active` class from this image images[i].classList.remove("active"); } } // makes the initial (Viper) background/image animate on page load document.addEventListener("DOMContentLoaded", () => { let image = document.querySelector(".image.active-noanim"); image.classList.add("active"); image.classList.remove("active-noanim"); }) // change wallpaper every 5 seconds setInterval(change_background, 5000); ================================================ FILE: docs/redirect.js ================================================ let repo = "viper"; let author = "0neGal"; let api = "https://api.github.com/repos"; async function init() { let release = await (await fetch(`${api}/${author}/${repo}/releases/latest`)).json(); let assets = release.assets; let get = (asset) => { for (let i in assets) { if (assets[i].name.match(asset)) { return assets[i].browser_download_url; } } } let url; let search = location.search.replace(/^\?/, ""); switch(search) { case "win-setup": url = get(/Viper-Setup-.*\.exe$/); break; case "win-portable": url = get(/Viper-.*\.exe$/); break; case "appimage": url = get(/Viper-.*\.AppImage$/); break; case "linux": url = get(/viper-.*.tar\.gz$/); break; case "rpm": url = get(/viper-.*\.x86_64\.rpm$/); break; case "deb": url = get(/viper_.*_amd64\.deb$/); break; case "release-page": url = release.html_url; break; default: return; } location.replace(url); }; init() ================================================ FILE: package.json ================================================ { "name": "viper", "productName": "Viper", "version": "1.13.0", "description": "Launcher+Updater for TF|2 Northstar", "main": "src/index.js", "build": { "appId": "com.0negal.viper", "directories": { "buildResources": "src/assets/icons" }, "nsis": { "installerIcon": "icon.ico", "uninstallerIcon": "icon.ico", "installerHeaderIcon": "icon.ico" }, "linux": { "icon": "512x512.png", "category": "Game", "target": [ "AppImage", "tar.gz", "deb", "rpm" ] } }, "scripts": { "langs:check": "node scripts/langs.js --check", "langs:format": "node scripts/langs.js --format", "langs:localize": "node scripts/langs.js --localize", "start": "npx electron src/index.js", "debug": "npm run devtools", "devtools": "npx electron src/index.js --devtools", "build": "npx electron-builder --win nsis --win portable --linux --publish never", "build:windows": "npx electron-builder --win nsis --win portable --publish never", "build:linux": "npx electron-builder --linux --publish never", "publish": "npx electron-builder --win nsis --win portable --linux --publish always", "publish:windows": "npx electron-builder --win nsis --win portable --publish always", "publish:linux": "npx electron-builder --linux --publish always" }, "repository": { "type": "git", "url": "git+https://github.com/0neGal/viper" }, "author": "0neGal ", "license": "GPL-3.0-or-later", "bugs": { "url": "https://github.com/0neGal/viper/issues" }, "homepage": "https://github.com/0neGal/viper#readme", "dependencies": { "electron-updater": "^6.3.0", "enquirer": "^2.4.1", "flattenizer": "^1.1.3", "follow-redirects": "^1.15.6", "fs-extra": "^10.0.0", "fuse.js": "^6.5.3", "jsonrepair": "^2.2.1", "marked": "^4.0.10", "minimist": "^1.2.8", "recursive-copy": "^2.0.13", "simple-vdf": "^1.1.1", "unzip-stream": "^0.3.2" }, "devDependencies": { "electron": "^33.2.1", "electron-builder": "^24.13.3" } } ================================================ FILE: scripts/downloads.js ================================================ const https = require("https"); const args = require("minimist")(process.argv.slice(2), { boolean: [ "help", "total", "releases", "sort-releases", "total-platforms", "include-prereleases" ], default: { "help": false, "total": true, "releases": true, "sort-releases": false, "total-platforms": true, "include-prereleases": false } }) // help message if (args["help"]) { console.log(`options: --help shows this help message --no-total dont show total downloads --no-releases dont show individual releases --sort-releases sorts releases by download count --no-total-platforms hides individual total platform downloads --include-prereleases includes prereleases when listing out individual releases `.trim()) // the trim removes the last blank newline process.exit(0); } // when parsing releases, these will be filled let releases = {}; let total = { all: 0, linux: 0, windows: 0 } // calculates what percentage `value` is of `total` let percent = (total, value) => { return (value / total * 100).toFixed(2) + "%"; } // parses a release object from the GitHub API, and then it changes // `releases` and `total` accordingly let parse_release = (release) => { if (release.prerelease && ! args["include-prereleases"]) { return; } let name = release.name; let assets = release.assets; // run through downloadable files from release for (let i = 0; i < assets.length; i++) { // dont count blockmaps if (assets[i].name.match("blockmap")) { continue; } switch(assets[i].name) { // dont count these files case "latest.yml": case "latest-linux.yml": continue; default: let platform; let downloads = assets[i].download_count; // assume platform is Windows if filename ends with // `.exe`, and Linux if not if (assets[i].name.endsWith(".exe")) { platform = "windows"; } else { platform = "linux"; } // create new object for this release in `releases` if // it doesn't already have one if (! releases[name]) { releases[name] = { all: 0, linux: 0, windows: 0 } } // add total download counts total.all += downloads; releases[name].all += downloads; // add platform specific download counts total[platform] += downloads; releases[name][platform] += downloads; } } } // pads out `str` until it's `length` long let pad = (str, length) => { str = String(str); while (str.length < length) { str += " "; } return str; } // takes in `obj` and prints out a table based on it, each key in the // objects inside `obj` will be used as a column, and it'll attempt to // pad them so it the output looks properly "columnized" let print_table = (obj) => { // keep track of the longest value of a key let max_lengths = {}; // run through all the keys for (let i in obj) { for (let ii in obj[i]) { // get length of current key let length = String(obj[i][ii]).length; // if the currently longest value for this type of key is // smaller than `length`, then we make `length` the newest // longest value for this type of key, the same happens if // there's not been a registered longest key for this type // of key yet if (max_lengths[ii] < length || ! max_lengths[ii]) { max_lengths[ii] = length; } } } // run through object again for (let i in obj) { // we'll add to this, then print it later let line_str = ""; // run through keys for (let ii in obj[i]) { // add value to `line_str` padding it to the longest found // value for this type of key and adding 5 for some margin line_str += pad(obj[i][ii], max_lengths[ii] + 5); } // print the line of this table out console.log(line_str); } } let parse_json = (json) => { // parse `json` json = JSON.parse(json); // run through releases and parse them for (let i = 0; i < json.length; i++) { parse_release(json[i]); } // should we should print the individual release stats? if (args["releases"]) { // should we sort the releases? if (args["sort-releases"]) { // the finalized and sorted `releases` will go here let sorted = {}; // sort `releases` using the `.all` property releases = Object.keys(releases).sort((a, b) => { return releases[b].all - releases[a].all; }).forEach((key) => { sorted[key] = releases[key]; }) // set `releases` to now be the sorted version releases = sorted; } // initialize `table` with a header let table = [{ version: "VERSION", total: "TOTAL", windows: "WINDOWS", linux: "LINUX" }] // runs through `releases` adding the various lines of the table // to `table`, essentially converting it to something we can use // `print_table()` on and nothing else for (let i in releases) { table.push({ version: i, total: releases[i].all, windows: releases[i].windows + " (" + percent( releases[i].all, releases[i].windows ) + ")", linux: releases[i].linux + " (" + percent( releases[i].all, releases[i].linux ) + ")" }) } // print the finalized table print_table(table); } // if we dont want to print the total downloads, then we just exit if (! args["total"]) { process.exit(0); } // if we've already printed the list of releases, we add an extra // space between this and the total if (args["releases"]) { console.log(); } // print out the total console.log("Total downloads: " + total.all); // if we shouldn't print the platform distribution, then these empty // strings will be used instead let linux_percent = ""; let windows_percent = ""; // get the percent of platform distribution if (args["total-platforms"]) { let linux_percent = "(" + percent(total.all, total.linux) + ")"; let windows_percent = "(" + percent(total.all, total.windows) + ")"; } // print Windows platform distribution console.log( " Windows: " + total.windows, windows_percent ) // print Linux platform distribution console.log( " Linux: " + total.linux, linux_percent ) } let link = "/repos/0neGal/viper/releases"; // request info about releases via GitHub's API https.get({ host: "api.github.com", port: 443, path: link, method: "GET", headers: { "User-Agent": "viper" } }, (res) => { res.setEncoding("utf8"); let res_data = ""; res.on("data", data => { res_data += data; }) // we got the data, now lets parse it! res.on("end", () => { parse_json(res_data); }) }) ================================================ FILE: scripts/langs.js ================================================ const fs = require("fs"); const dialog = require("enquirer"); const flat = require("flattenizer"); const args = require("minimist")(process.argv.slice(2), { boolean: [ "help", "check", "format", "localize" ], default: { "help": false, "check": false, "format": false, "localize": false } }) console = require("../src/modules/console"); // help message if (args["help"]) { console.log(`options: --help shows this help message --check checks for incorrectly formatted lang files and missing localizations --format formats all lang files correctly if the files can be read and parsed --localize allows you add missing incorrectly localizations, and edit old ones `.trim()) // the trim removes the last blank newline process.exit(0); } // move into `scripts` folder, makes sure all file system requests work // identically to `require()` process.chdir(__dirname); // get list of files in `src/lang/`, except for `maintainers.json` these // should all be language files let langs = fs.readdirSync("../src/lang"); // get the English language file and flatten it let lang = flat.flatten(require("../src/lang/en.json")); // formats all files automatically, nothing too fancy, it ignores // `en.json` however, as its manually edited. let format = (logging = true) => { // run through langs langs.forEach((locale_file) => { // ignore these files if (locale_file == "en.json" || locale_file == "maintainers.json") { return; } // path to lang file let file_path = "../src/lang/" + locale_file; try { // attempt read, parse and flatten `file_path` let json = flat.flatten( JSON.parse(fs.readFileSync(file_path)) ) // sort `json` json = Object.fromEntries( Object.entries(json).sort() ) // delete keys that are only found in `locale_file` but not // in the English localization file, if something doesn't // exist in the English localization file, then it shouldn't // exist at all! for (let i in json) { if (! lang[i]) { delete json[i]; } } json = flat.unflatten(json); // attempt to stringify earlier JSON, with default // formatting, directly into `file_path` fs.writeFileSync( file_path, JSON.stringify(json, null, "\t") ) }catch(err) { // something went wrong! console.error("Couldn't format: " + locale_file); } }) console.ok("Formatted all localization files."); } // starts up a prompt interface to edit localization strings, letting // you both add missing ones, and change old ones let localize = async () => { // check if there's any missing keys let problems = check(false); // this'll have the `choices` for language picking prompt let lang_list = []; // run through langs langs.forEach((locale_file) => { // ignore these files if (locale_file == "en.json" || locale_file == "maintainers.json") { return; } // default value let lang_name = locale_file; // are we missing any keys? if so, add a "(missing)" label at // the end of the language name let missing = (problems[lang_name] && problems[lang_name].length); if (missing) { lang_name += ` (missing: ${missing})`; } // add to list of langs lang_list.push(lang_name); }) // prompt for which lang to edit let picked_lang = await new dialog.AutoComplete({ choices: lang_list, message: "Pick a language to edit:", }).run() // remove extra labels after the lang file name itself picked_lang = picked_lang.replace(/ \(.*/, ""); // this'll contain the languages flattened contents let lang_keys; try { // attempt to read, parse and flatten the language file lang_keys = flat.flatten(require("../src/lang/" + picked_lang)); }catch (err) { // something went wrong! console.error("Couldn't read and parse language file"); process.exit(1); } // should we just show the keys that are missing, or everything? let just_missing = false; // get just the flattened keys of the language let keys = Object.keys(lang_keys); // are there any missing keys? if (problems[picked_lang].length) { // prompt for whether we should only show missing keys just_missing = await new dialog.Confirm({ message: "Add just missing keys without editing all keys?", }).run() // if we should just show missing keys, remove all other keys, // if we're allowed to show other keys, then we'll at least add // the missing keys if (just_missing) { keys = problems[picked_lang]; } else { keys = [ ...problems[picked_lang], ...keys, ] } } // add "Save changes" option keys = [ "Save changes", ...keys ] // add "(missing)" label to missing keys for (let i = 0; i < keys.length; i++) { if (! just_missing && problems[picked_lang].includes(keys[i])) { keys[i] = keys[i] + " \x1b[91m(missing)\x1b[0m"; } } // this'll hold the flattened edits we make let edited_keys = {}; // starts the process of editing a key let edit_key = async () => { // prompt for which key to edit let key_to_edit = await new dialog.AutoComplete({ limit: 15, choices: [...keys], message: "Pick a key to edit:" }).run() // if "Save changes" was picked then return all the edits we've // made and stop prompting for new edits if (key_to_edit == "Save changes") { return edited_keys; } // strip labels from chosen key name key_to_edit = key_to_edit.split(" ")[0]; // prompt for what to set the key to let edited_key = await new dialog.Input({ type: "input", message: `Editing: ${key_to_edit}\n` + " Original string: " + lang[key_to_edit] + "\n" }).run() // add the edited key in `edited_keys` edited_keys[key_to_edit] = edited_key; // add "(edited)" to the label of this key for (let i = 0; i < keys.length; i++) { if (keys[i].split(" ")[0] == key_to_edit) { keys[i] = key_to_edit + " \x1b[94m(edited)\x1b[0m"; } } // clear screen and ask for the next edit to be made console.clear(); return edit_key(); } // start the process of key editing, whenever the below function // returns with the list of edits, it also only first returns when // all the changes have been made and "Save changes" has been // selected in the menu let changes = await edit_key(); console.clear(); try { // merge edits and original lang file, then unflatten them let final_json = flat.unflatten({ ...lang_keys, ...changes }) // attempt to write `final_json` to the language file fs.writeFileSync( "../src/lang/" + picked_lang, JSON.stringify(final_json, null, "\t") ) console.ok("Saved changes: " + picked_lang); // check for changes check(true); // format everything format(true); }catch(err) { // something went wrong! console.error("Failed to save changes: " + picked_lang); } } // checks whether or not language files are missing any keys, and // whether they're even parseable. // // an object will be returned containing information about each file and // which, if any, keys are missing from them let check = (logging = true) => { // this'll contain the missing keys for all the files, if any let problems = {}; // this'll be changed to `true` if any errors at any point arise let has_problems = false; // get list of maintainers for each language let maintainers = require("../src/lang/maintainers.json"); // run through langs langs.forEach((locale_file) => { // ignore this file, it's not a language file if (locale_file == "maintainers.json") {return} // this'll contain missing keys let missing = []; // this'll contain the flattened language file contents let locale = false; // this is the list of maintainers for this language let lang_maintainers = maintainers.list[ locale_file.replace(/\..*$/, "") ] // attempt read, parse and flatten language file try { locale = flat.flatten(require("../src/lang/" + locale_file)); }catch(err) { // we couldn't parse it! if (logging) { has_problems = true; console.error(`!! ${locale_file} is not formatted right !!`); } return; } // run through keys, and note ones that are missing from // `en.json` in this lang for (let i in lang) { if (! locale[i]) { missing.push(i); } } // add missing keys to `problems` problems[locale_file] = missing; // was there any missing keys? if (missing.length > 0) { // this is a problem has_problems = true; // do nothing if we're not supposed to log anything if (! logging) { return; } // log language file with missing keys console.error(`${locale_file} is missing:`); // log missing keys for (let i in missing) { console.error(` ${missing[i]}`); } // spacing console.log(); // log the maintainers for this language console.log("Maintainers: "); for (let i in lang_maintainers) { console.log(` ${lang_maintainers[i]}`); } console.log("\n"); } }) // if no problems occurred, and we can log things, then print that // everything went just fine! if (! has_problems && logging) { console.ok("All localizations are complete and parseable."); } return problems; } // run `check()` if `--check()` is set if (args["check"]) { let has_problems = false; // check localizations, and set `has_problems` depending on whether // any localization files have problems Object.values(check()).forEach((item) => { if (item.length) { has_problems = true; } }); // exit with the correct exit code if (has_problems) { process.exit(1); } else { process.exit(); } } // run `format()` if `--format` is set if (args["format"]) { format(); } // run `localize()` if `--localize` is set if (args["localize"]) { localize(); } ================================================ FILE: scripts/publish.sh ================================================ #!/bin/sh VERSION="v$(jq '.version' package.json -r)" LOCK1="v$(jq '.version' package-lock.json -r)" LOCK2="v$(jq '.packages[""].version' package-lock.json -r)" REPO="$(jq '.repository.url' package.json -r | sed 's/.*.com\///g')" REMOTEVERSION="$(curl --silent "https://api.github.com/repos/0neGal/viper/releases/latest" | grep '"tag_name":' | sed -E 's/.*"([^"]+)".*/\1/')" [ "$REMOTEVERSION" = "$VERSION" ] && { echo "A release already exists with the current version number!" exit 1 } [ "$VERSION" != "$LOCK1" ] && { echo "Two seperate version numbers in package.json and package-lock.json" echo " $VERSION, $LOCK1" exit 1 } [ "$LOCK1" != "$LOCK2" ] && { echo "Version mismatches in package-lock.json" echo " $LOCK1, $LOCK2" exit 1 } node scripts/langs.js --check || { echo "Please fix localization errors before publishing..." exit 1 } TOKEN="$GH_TOKEN" [ "$TOKEN" = "" ] && { echo "GH_TOKEN is not set, please type it below:" read -p "> " TOKEN } GH_TOKEN="$TOKEN" npm run publish ================================================ FILE: src/app/css/dragui.css ================================================ @import "theming.css"; /* This stylesheet is meant for the DragUI, i.e the UI that pops up when dragging a modfile over the window. */ #dragUI { top: 0; left: 0; right: 0; bottom: 0; color: white; opacity: 0.0; position: fixed; z-index: 1000000; pointer-events: none; background: var(--bg); backdrop-filter: blur(15px); transition: 0.1s ease-in-out; } #dragUI.shown { opacity: 1.0; pointer-events: all; } #dragUI #dragitems { --size: 25vw; top: 50%; left: 50%; opacity: 0.6; position: absolute; text-align: center; width: var(--size); height: var(--size); margin-top: calc(var(--size) / 2 * -1); margin-left: calc(var(--size) / 2 * -1); } #dragUI #dragitems #icon { width: 100%; height: 100%; filter: invert(1); transform: scale(0.45); background-size: cover; background-image: url("../icons/download.png"); transition: 0.1s ease-in-out; } #dragUI.shown #dragitems #icon { transform: scale(0.5); } #dragUI #dragitems #text { top: -5vw; position: relative; } ================================================ FILE: src/app/css/grid.css ================================================ @import "theming.css"; .grid, .grid .el, .popup .misc, .popup .loading { --spacing: calc(var(--padding) / 2); --height: calc(var(--padding) * 3.5); --mischeight: calc(var(--padding) * 1.5); animation-duration: 0.15s; animation-iteration-count: 1; animation-name: fadein; animation-fill-mode: forwards; animation-timing-function: ease-in-out; opacity: 0.0; transition: 0.15s ease-in-out; } .grid .el.no-animation, .popup .misc.no-animation, .popup .loading.no-animation { opacity: 1.0; animation-name: none; } .grid .el, input.search, .popup #close, .popup .misc button, .option .actions select, .option .actions input { color: white; display: flex; align-items: center; height: var(--height); margin: var(--spacing); padding: var(--spacing); background: var(--selbg); border-radius: var(--spacing); width: calc(50% - var(--spacing) * 4); } .popup .misc, input.search, .option .actions input { --height: var(--mischeight); } .popup .misc { display: flex; } .popup .misc.vertical { display: block; } .popup .misc.fixed { width: 100%; position: fixed; } input.search, .option .actions input, .option .actions select { border: none; outline: none; transition: filter 0.15s ease-in-out; width: calc(100% - var(--spacing) * 2); } input.search:focus, .option .actions input:focus, .option .actions button:active { filter: brightness(1.5); } .popup .misc button { --height: calc(var(--padding) * 1.5); padding: 0px; margin-left: 0px; padding: 0px !important; width: var(--height) !important; } .popup .misc button.long { width: max-content !important; padding-right: var(--spacing) !important; } .popup .misc button select { color: white; border: none; opacity: 0.6; outline: none; background: transparent; } .popup .misc button select option { color: white; background: var(--selbg); } .popup .misc button img { margin: 0px; opacity: 0.6; width: var(--height); transform: scale(0.5); height: var(--height) !important; } .popup .misc button:last-child { margin-left: 0px !important; } .popup#preview #close, .popup .misc.vertical button { margin: var(--spacing) var(--spacing) 0 auto !important; } .popup .loading { width: 100%; color: white; display: flex; position: absolute; text-align: center; align-items: center; justify-content: center; height: calc(100% - var(--mischeight) - var(--height)); } .popup .message { color: white; text-align: center; margin: var(--padding); width: calc(100% - var(--padding)); } .grid .el .image, .grid .el .image img { width: var(--height); height: var(--height); transition: opacity 0.2s; margin-right: var(--spacing); border-radius: var(--spacing); } .grid input { margin: 0; width: 100%; } #modsdiv .el:has(.switch:not(.on)) .image img { opacity: 0.5; } .grid .el .image img.blur { z-index: -1; position: relative; filter: blur(10px); top: calc(var(--height) * -1 + 5px); } .grid .el .text { height: inherit; overflow: hidden; overflow-x: scroll; padding: var(--padding) 0px; } .grid .el.has-icon .text { width: calc(100% - var(--height)); } .grid .el .title, .grid .el .description { height: 1.2em; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; } .grid .el .title { font-size: 1.2em; font-weight: 700; } .popup .message #loadmore { background: rgb(var(--blue2)); } .grid .el .description {font-size: 0.8em} .grid .el button { margin-top: var(--spacing); } .grid .el button.info { background: rgb(var(--blue2)); } .grid .el .switch { top: 3px; position: relative; background: var(--bg); } .grid .el .switch:not(.grid .el .switch.on)::after { background: var(--selbg); } ================================================ FILE: src/app/css/launcher.css ================================================ @import "theming.css"; /* This stylesheet is meant for various elements around the launcher, notably the navbar, launch buttons, and sidebar. */ .gamesContainer { width: 10%; height: 100%; min-width: 95px; max-width: 120px; float: left; display: flex; flex-wrap: wrap; align-content: center; } .mainContainer { height: 100%; flex-grow: 1; display: flex; position: relative; } /* nav bar buttons */ .gamesContainer button { background-size: 90%; background-position: center; background-repeat: no-repeat; border: none; transition: 0.3s ease-in-out; background-color: transparent; margin: 20px; position: relative; border-radius: 0px; box-sizing: border-box; flex-basis: calc(100% - 10px); } .gamesContainer button.inactive { opacity: 0.5; transform: scale(0.9); } .gamesContainer button.inactive:hover { transform: scale(0.95); filter: brightness(120%); } .gamesContainer button::before { content: ""; display: block; padding-top: 100%; } .gamesContainer button .content { width: 100%; height: 100%; top: 0; left: 0; position: absolute; } #vpBtn {background-image: url("../icons/viper.png")} #nsBtn {background-image: url("../icons/northstar.png")} #tfBtn { background-image: url("../icons/titanfall2.png"); background-size: 69%; /* nice */ } .contentContainer { width: 85%; color: white; flex-grow: 1; opacity: 1.0; margin-left: 5%; position: absolute; transition: 0.15s ease-in-out; } .contentContainer.hidden { opacity: 0.0; pointer-events: none; } .contentMenu { padding: 0; flex-grow: 1; display: flex; font-size: 20px; list-style: none; margin-bottom: 0; align-items: center; justify-content: center; margin-top: var(--padding); } .contentMenu li { opacity: 0.6; margin: 0 26px; cursor: pointer; font-weight: 700; text-align: center; height: fit-content; transition: opacity 0.3s ease-in-out; } .contentMenu li:last-child {margin-right: 0px} .contentMenu li:first-child {margin-left: 0px} .contentMenu li:hover, .contentMenu li.active-selection {opacity: 0.7} .contentMenu li[active] { opacity: 1.0; pointer-events: none; } .contentMenu li::after { top: 10px; width: 30px; height: 5px; opacity: 0.0; content: " "; display: block; text-align: center; position: relative; border-radius: 50px; left: calc(50% - 15px); background: rgb(var(--red)); transition: 0.2s ease-in-out; } .contentMenu li[active]::after { top: 5px; opacity: 1.0; } .section { opacity: 1.0; position: fixed; right: calc(var(--padding) * 2); left: calc(100px + var(--padding)); transition: opacity 0.15s ease-in-out; } .section.hidden { opacity: 0.0; pointer-events: none; } .section .release-block { margin-top: 0px; background: var(--bg); padding: var(--padding); backdrop-filter: blur(15px); margin-bottom: var(--padding); border-radius: calc(var(--padding) / 3); } .section .release-block { backdrop-filter: none; margin: var(--padding); background: var(--selbg); } .section .release-block p:nth-child(1) { opacity: 0.8; margin-top: 0px; margin-bottom: 0px; } .section .release-block h1:nth-child(2) { margin-top: 0px; } .section .release-block :last-child { margin-bottom: 0px; } .contentBody img {max-width: 100%} .contentBody .img {text-align: center} .contentBody .section > :first-child:not(.release-block) { margin-top: 35px; } .contentContainer .playBtnContainer { text-align: center; } .contentContainer .playBtn { width: 27%; height: 11%; border: none; color: white; padding: 20px; font-size: 24px; overflow: hidden; font-weight: bold; margin-top: 100px; margin-bottom: 10px; border-radius: 10px; background: var(--redbg); transition: 0.2s ease-in-out; filter: drop-shadow(0px 8px 5px rgba(0, 0, 0, 0.1)); --progress: 100%; } .contentContainer .playBtn:hover { transform: scale(1.05); filter: drop-shadow(0px 5px 15px rgba(0, 0, 0, 0.3)) brightness(110%); } .contentContainer .playBtn:active { opacity: 0.7;transform: scale(0.98); filter: drop-shadow(0px 5px 10px rgba(0, 0, 0, 0.4)); } .contentContainer .playBtn:before { top: 0; left: 0; bottom: 0; content: " "; opacity: 0.5; position: absolute; right: var(--progress); filter: brightness(1.5); background: var(--bluebg); transition: 0.2s ease-in-out; } .contentContainer #nsMain .playBtn { background: var(--bluebg); } #nsContent .contentMenu { margin-bottom: 0; } .contentBody .img img { transform: scale(0.85); } .contentBody .img { width: 100%; text-align: center; } #nsMods { height: 80vh; } #nsRelease, #vpReleaseNotes { height: 80vh; margin-top: 35px; overflow-y: scroll; background: var(--bg); flex-direction: column; backdrop-filter: blur(15px); border-radius: calc(var(--padding) / 3); } .inline * { display: inline-block; } #vpMain { margin-top: 140px; text-align: center; } #vpMain img { width: 20%; } #vpVersion { font-size: 16px; } .simplebar-scrollbar:before { background: rgb(var(--red)) !important; } button:has(img):not(img:only-child) { top: 2px; position: relative; align-items: center; display: inline-flex; justify-content: center; } button:has(img):not(img:only-child) img { width: 1em; height: 1em; height: fit-content; margin-right: calc(var(--padding) / 3) } button:has(img):has(span) img { opacity: 0.0; transition: opacity 0.2s ease-in-out; } button:has(img):has(span):hover img, button:has(img):has(span).active-selection img { opacity: 1.0; } button:has(img):has(span) span { right: 0.8em; position: relative; transition: right 0.2s ease-in-out; } button:has(img):has(span):hover span, button:has(img):has(span).active-selection span { right: 0.1em; } button:disabled { opacity: 0.5; pointer-events: none; } button.visual { opacity: 1.0; padding-right: 0px; pointer-events: none; background: transparent !important; } code { font-size: 16px; padding: 2px 5px; border-radius: 3px; background-color: #00000070; } #nsMods .line { width: 100%; display: flex; font-weight: 700; align-items: center; margin: calc(var(--padding) / 2); margin-top: calc(var(--padding) / 2); } #modsdiv { overflow-y: scroll; background: var(--bg); backdrop-filter: blur(15px); padding: calc(var(--padding) / 2); height: calc(80vh - var(--padding)); border-radius: calc(var(--padding) / 3); } #modsdiv .mod { display: flex; border-radius: 5px; transition: 0.1s ease-in-out; margin: calc(var(--padding) / 3); padding: calc(var(--padding) / 3); } #modsdiv .mod.selected { background: var(--selbg); } #modsdiv .mod .disabled, .modbtns { margin-left: auto; } .modbtns button { margin-left: var(--spacing); --spacing: calc(var(--padding) / 3); margin-top: calc(var(--spacing) / 2); margin-bottom: calc(var(--spacing) / 2); } #serverstatus { --spacing: calc(var(--padding) / 5); transition-duration: 0.2s; transition-timing-function: ease-in-out; transition-property: background, opacity; opacity: 0.0; display: block; margin: 0 auto; font-weight: 700; width: fit-content; color: transparent; border-radius: 50px; flex-basis: max-content; background: transparent; margin-top: calc(var(--spacing) * 2); padding: var(--spacing) calc(var(--spacing) * 3); } #serverstatus.up, #serverstatus.down { color: white; opacity: 1.0; } #serverstatus.up {background: rgb(var(--blue));} #serverstatus.down {background: rgb(var(--red));} ================================================ FILE: src/app/css/popups.css ================================================ @import "theming.css"; /* This stylesheet is meant for the various popups we use, whether it be the previewer, the browser, the settings menu, or anything alike. */ .popup { --spacing: var(--padding); --top-spacing: calc(var(--spacing) + calc(var(--spacing) * 1.6)); z-index: 2; opacity: 0.0; position: fixed; overflow-y: scroll; pointer-events: none; left: var(--spacing); right: var(--spacing); bottom: var(--spacing); top: var(--top-spacing); background: var(--bg); transform: scale(0.98); border-radius: calc(var(--padding) / 3); transition-duration: 0.15s; transition-property: opacity, transform; transition-timing-function: ease-in-out; } .popup.blur { backdrop-filter: blur(15px); } .popup.shown { opacity: 1.0; pointer-events: all; transform: scale(1.0); } .popup.small { left: 20vw; right: 20vw; bottom: calc(var(--padding) * 2); top: calc(var(--padding) * 2 + var(--top-spacing)); } #overlay { top: 0; left: 0; right: 0; bottom: 0; z-index: 1; opacity: 0.0; position: fixed; background: var(--bg); pointer-events: none; transition: opacity 0.15s ease-in-out; } #overlay.shown { opacity: 1.0; pointer-events: all; backdrop-filter: blur(10px); } /* browser/preview popup { */ @keyframes fadein { 0% {opacity: 0.0} 100% {opacity: 1.0} } .popup webview { width: 78%; margin: 0 auto; filter: opacity(1.0); transition: filter 0.15s ease-in-out; margin-top: calc(var(--spacing) / 2); height: calc(100% - calc(var(--spacing) / 2)); } .popup webview.loading { filter: opacity(0.0); pointer-events: none; } /* } */ /* settings popup { */ .popup .options details { opacity: 1.0; transition: 0.15s opacity ease-in-out; } .popup .options details:not([open]) { opacity: 0.5; } .popup .options details:hover:not([open]) { opacity: 0.8; } .popup .options details summary { cursor: pointer; list-style-type: none; } .popup .options { color: white; margin: calc(var(--padding) / 2); } .popup .options .option, .popup .options .buttons { width: 100%; display: flex; margin-bottom: var(--padding); justify-content: space-between; } .popup .overlay { z-index: 1; color: white; opacity: 0.0; position: fixed; pointer-events: none; transform: scale(0.9); background: var(--selbg); backdrop-filter: blur(15px); transition: 0.15s ease-in-out; padding: calc(var(--spacing) / 2); border-radius: calc(var(--spacing) / 2); } .popup .overlay.shown { opacity: 1.0; pointer-events: all; transform: scale(1.0); } #options.popup .misc button { margin-left: 0px; width: auto !important; padding-right: calc(var(--padding) / 2) !important; } .check { display:flex; cursor: pointer; } .check::before { width: 1em; height: 1em; content: " "; background-size: 75%; filter: brightness(1.3); background-position: center; background-repeat: no-repeat; transition: 0.15s ease-in-out; background-color: var(--selbg); margin-right: calc(var(--spacing) / 3); border-radius: calc(var(--spacing) / 4); } .check.checked::before { background-color: rgb(var(--red)); background-image: url(../icons/check.png); } .option .text, .buttons .text { font-weight: 600; } .option .text .desc, .buttons .text .desc { opacity: 0.8; font-weight: 500; font-size: 0.9em; max-width: 400px; margin-top: calc(var(--padding) / 3); } .option .actions input, .option .actions select { width: 100%; margin: 0px; --spacing: calc(var(--padding) / 3); } .option[type=array] .actions input { word-spacing: 15px; margin-right: 15vw; } .buttons .actions { text-align: right; } .buttons .actions button { margin-bottom: calc(var(--padding) / 5); } .option .actions button, .buttons .actions button { background: var(--selbg); } .title { display: flex; margin-top: calc(var(--padding) * 2); margin-bottom: calc(var(--padding) / 2); } .title:first-child { margin-top: 0px; } .title img { width: 30px; height: 30px; margin: auto 0; } .title h2 { margin: 0px; margin-left: calc(var(--padding) / 3); } /* } */ ================================================ FILE: src/app/css/selection.css ================================================ #selection { z-index: 99999999999999; transition: 0.15s ease-in-out; transition-property: opacity, border-radius, background, transform, width, height, top, left; position: fixed; pointer-events: none; transform: scale(1.0); background: rgba(255, 255, 255, 0.3); border-radius: calc(var(--padding) / 2); } :has(.active-selection.scroll-selection) #selection { background: rgba(255, 255, 255, 0.2); } #selection.keyboard-selecting, #selection.controller-selecting { transform: scale(1.1); } ================================================ FILE: src/app/css/theming.css ================================================ /* the only reason some of these properties have an !important property is for it to overwrite Thunderstore's CSS in the preview */ :root { --red: 199, 119, 127 !important; --red2: 181 97 105; --blue: 129, 161, 193; --blue2: 139, 143, 185; --orange: 213, 151, 131; --orange2: 197 129 107; --padding: 25px; --bg: rgba(0, 0, 0, 0.5); --selbg: rgba(80, 80, 80, 0.5); --redbg: linear-gradient(45deg, rgb(var(--red)), #FA4343); --bluebg: linear-gradient(45deg, rgb(var(--blue)), #7380ED); } body, button, input { font-family: "Roboto", sans-serif !important; } body, button, img, a { user-select: none; -webkit-user-drag: none; } a { text-decoration: none !important; color: rgb(var(--red)) !important; transition: filter 0.2s ease-in !important; } a.disabled:not([onclick="kill('game')"]) { opacity: 0.5; pointer-events: none; } a:hover, a.active-selection { filter: brightness(80%) !important; } input:disabled { opacity: 0.5; } ::-webkit-scrollbar { width: 18px !important; } ::-webkit-scrollbar-track { border-radius: 10px !important; background: transparent !important; } ::-webkit-scrollbar-thumb { border: 5px solid transparent; border-radius: 10px !important; box-shadow: rgb(var(--red)) 0px 0px 10px 10px inset; } ::selection { color: black !important; background: rgb(var(--red)) !important; } .bg-blue {background: rgb(var(--blue)) !important} .bg-blue2 {background: rgb(var(--blue2)) !important} .bg-orange {background: rgb(var(--orange)) !important} .bg-orange2 {background: rgb(var(--orange2)) !important} .bg-red {background: rgb(var(--red)) !important} .bg-red2 {background: rgb(var(--red2)) !important} ================================================ FILE: src/app/css/toasts.css ================================================ @import "theming.css"; #toasts { position: fixed; z-index: 100000; right: calc(var(--padding) * 1.5); bottom: calc(var(--padding) * 1.5); } @keyframes bodyfadeaway { 0% {opacity: 0.0; transform: scale(0.95)} 100% {opacity: 1.0; transform: scale(1.0)} } #toasts .toast { width: 300px; opacity: 0.0; cursor: pointer; overflow: hidden; max-height: 100vh; transform: scale(0.95); background: var(--selbg); transition: 0.2s ease-in-out; backdrop-filter: blur(15px); padding: calc(var(--padding) / 2); margin-top: calc(var(--padding) / 2); border-radius: calc(var(--padding) / 2.5); box-shadow: 0px 5px 15px rgba(0, 0, 0, 0.2); animation-duration: 0.2s; animation-iteration-count: 1; animation-name: bodyfadeaway; animation-fill-mode: forwards; animation-timing-function: ease-in-out; } #toasts .toast .title:only-child { margin-bottom: 0px; } #toasts .toast.hidden { margin-top: 0px; max-height: 0px; padding-top: 0px; padding-bottom: 0px; filter: opacity(0.0); transform: scale(0.95); } #toasts .toast:not(.hidden):hover {filter: opacity(0.9)} #toasts .toast:not(.hidden):active {filter: opacity(0.8)} .toast .description { opacity: 0.8; font-size: 0.8em; font-weight: 600; word-break: break-word; } ================================================ FILE: src/app/css/tooltip.css ================================================ @import "theming.css"; #tooltip { color: white; opacity: 0.0; position: fixed; font-weight: 600; font-size: 0.8em; width: max-content; z-index: 99999999999; pointer-events: none; background: var(--bg); backdrop-filter: blur(15px); transition: opacity 0.15s ease-in-out; border-radius: calc(var(--padding) / 1); padding: calc(var(--padding) / 2.8) calc(var(--padding) / 1.8); } #tooltip.visible { opacity: 1.0; } ================================================ FILE: src/app/css/webview.css ================================================ body { overflow-x: hidden; background: transparent !important; background-color: transparent !important; background-image: transparent !important; } .background { display: none; } .footer, #ncmp_tool, .bottom-ads, .ncmp__banner, #get-app-alert, .navbar, .bottom-padding, .card-header, .breadcrumb, .list-group, .mb-4, .my-2, .mt-2, #thunderstore-mod-manager-ad-alert { display: none !important; } .mt-2.mb-2 {display: block !important} .card {transform: translateY(-1.0rem)} ================================================ FILE: src/app/fonts/import.css ================================================ @font-face { font-weight: 100; font-style: italic; font-family: "Roboto"; src: url("Roboto-ThinItalic.ttf"); } @font-face { font-weight: 300; font-style: italic; font-family: "Roboto"; src: url("Roboto-Italic.ttf"); } @font-face { font-weight: 400; font-style: italic; font-family: "Roboto"; src: url("Roboto-Italic.ttf"); } @font-face { font-weight: 500; font-style: italic; font-family: "Roboto"; src: url("Roboto-MediumItalic.ttf"); } @font-face { font-weight: 700; font-style: italic; font-family: "Roboto"; src: url("Roboto-BoldItalic.ttf"); } @font-face { font-weight: 900; font-style: italic; font-family: "Roboto"; src: url("Roboto-BlackItalic.ttf"); } @font-face { font-weight: 100; font-style: normal; font-family: "Roboto"; src: url("Roboto-Thin.ttf"); } @font-face { font-weight: 300; font-style: normal; font-family: "Roboto"; src: url("Roboto-Light.ttf"); } @font-face { font-weight: 400; font-style: normal; font-family: "Roboto"; src: url("Roboto-Regular.ttf"); } @font-face { font-weight: 500; font-style: normal; font-family: "Roboto"; src: url("Roboto-Medium.ttf"); } @font-face { font-weight: 700; font-style: normal; font-family: "Roboto"; src: url("Roboto-Bold.ttf"); } @font-face { font-weight: 900; font-style: normal; font-family: "Roboto"; src: url("Roboto-Black.ttf"); } ================================================ FILE: src/app/index.html ================================================
Test
%%gui.mods.drag_n_drop%%
  • %%viper.menu.main%%
  • %%viper.menu.release%%
  • %%viper.menu.info%%
  • %%ns.menu.main%%
  • %%ns.menu.mods%%
  • %%ns.menu.release%%
  • filler
================================================ FILE: src/app/js/browser.js ================================================ const Fuse = require("fuse.js"); const { ipcRenderer, shell } = require("electron"); const lang = require("../../lang"); const popups = require("./popups"); const toasts = require("./toasts"); const request = require("./request"); var browser_fuse; var packages = []; var packagecount = 0; var browser_el = document.getElementById("browser") var browser = { maxentries: 50, mod_versions: {}, filters: { getpkgs: () => { let pkgs = []; let other = []; for (let i in packages) { if (! browser.filters.isfiltered(packages[i].categories)) { pkgs.push(packages[i]); } else { other.push(packages[i]); } } return pkgs; }, get: () => { let filtered = []; let unfiltered = []; let checks = browser_el.querySelectorAll("#filters .check"); for (let i = 0; i < checks.length; i++) { if (! checks[i].classList.contains("checked")) { filtered.push(checks[i].getAttribute("value")); } else { unfiltered.push(checks[i].getAttribute("value")); } } return { filtered, unfiltered }; }, isfiltered: (categories) => { let filtered = browser.filters.get().filtered; let unfiltered = browser.filters.get().unfiltered; let state = false; let filters = [ "Mods", "Skins", "Client-side", "Server-side", ]; let newcategories = []; for (let i = 0; i < categories.length; i++) { if (filters.includes(categories[i])) { newcategories.push(categories[i]); } }; categories = newcategories; if (categories.length == 0) {return true} for (let i = 0; i < categories.length; i++) { if (filtered.includes(categories[i])) { state = true; continue } else if (unfiltered.includes(categories[i])) { state = false; continue } state = true; } return state; }, toggle: (state) => { if (state == false) { filters.classList.remove("shown"); return } filters.classList.toggle("shown"); let filterRect = filter.getBoundingClientRect(); let spacing = parseInt(getComputedStyle(filters).getPropertyValue("--spacing")); filters.style.top = filterRect.bottom - (spacing + (spacing * 1.3)); filters.style.right = filterRect.right - filterRect.left + filterRect.width - (spacing / 2); }, }, toggle: (state) => { browser_el.scrollTo(0, 0); popups.set("#browser", state); if (state) { if (browserEntries.querySelectorAll(".el").length == 0) { browser.loadfront(); } } else if (state === false) { browser.filters.toggle(false); } }, install: async (package_obj, clear_queue = false) => { let can_connect = await request.check_with_toasts( "Thunderstore", "https://thunderstore.io" ) if (! can_connect) { return; } return mods.install_from_url( package_obj.download || package_obj.versions[0].download_url, package_obj.dependencies || package_obj.versions[0].dependencies, clear_queue, package_obj.author || package_obj.owner, package_obj.name || package_obj.pkg.name, package_obj.version || package_obj.versions[0].version_number ) }, add_pkg_properties: () => { for (let i = 0; i < packages.length; i++) { let properties = packages[i]; let normalized = mods.normalize(packages[i].name); let has_update = false; let local_name = false; let local_version = false; let remote_version = packages[i].versions[0].version_number; remote_version = version.format(remote_version); if (mods.list()) { for (let ii = 0; ii < mods.list().all.length; ii++) { let mod = mods.list().all[ii]; if (mods.normalize(mod.name) !== normalized && ( ! mod.package || mod.package.author + "-" + mod.package.package_name !== packages[i].full_name )) { continue; } local_name = mod.name; local_version = version.format(mod.version); if (version.is_newer(remote_version, local_version)) { has_update = true; } } } let install = () => { return browser.install({...properties}); } packages[i].unix_created = new Date(packages[i].date_created).getTime(); packages[i].unix_updated = new Date(packages[i].date_updated).getTime(); packages[i].install = install; packages[i].has_update = has_update; packages[i].local_version = local_version; packages[i].downloads = 0; for (let version of packages[i].versions) { packages[i].downloads += version.downloads || 0; } if (local_version) { browser.mod_versions[normalized] = { install: install, has_update: has_update, local_name: local_name, local_version: local_version, package: packages[i] } } } }, // sorts `pkgs` based on `property` in package object sort: (pkgs, property) => { // get property from sort selector, if not specified if (! property) { property = sort.querySelector("select").value; // if we somehow still don't have a property, just return if (! property) { return pkgs; } } // if `property` doesn't even exist, just return if (typeof pkgs[0][property] == "undefined") { return pkgs; } // sort in descending order return pkgs.sort((a, b) => { return b[property] - a[property]; }) }, loadfront: async () => { browser.loading(); packagecount = 0; if (packages.length < 1) { let host = "northstar.thunderstore.io"; let path = "/api/v1/package/"; packages = []; // attempt to get the list of packages from Thunderstore, if // this has been done recently, it'll simply return a cached // version of the request try { packages = JSON.parse( await request(host, path, "thunderstore-packages") ) }catch(err) { console.error(err) } browser.add_pkg_properties(); browser_fuse = new Fuse(packages, { keys: ["full_name"] }) } let pkgs = browser.sort(browser.filters.getpkgs()); for (let i in pkgs) { if (packagecount >= browser.maxentries) { browser.endoflist(); break } browser.mod_el_from_obj(pkgs[i]); packagecount++; } }, loading: (string) => { if (browser.filters.get().unfiltered.length == 0) { string = lang("gui.browser.no_results"); } if (string) { browserEntries.innerHTML = `
${string}
`; } if (! browserEntries.querySelector(".loading")) { browserEntries.innerHTML = `
${lang('gui.browser.loading')}
`; } }, endoflist: (is_end) => { let pkgs = []; let filtered = browser.filters.getpkgs(); for (let i = 0; i < filtered.length; i++) { if (filtered[packagecount + i]) { pkgs.push(filtered[packagecount + i]); } else { break } } if (browserEntries.querySelector(".message")) { browserEntries.querySelector(".message").remove(); } if (pkgs.length == 0 || is_end) { browser.msg(`${lang('gui.browser.endoflist')}`); return } browser.msg(``); loadmore.addEventListener("click", () => { browser.loadpkgs(pkgs); browser.endoflist(! pkgs.length); }) }, search: (string) => { browser.loading(); let res = browser_fuse.search(string); if (res.length < 1) { browser.loading(lang("gui.browser.no_results")); return } packagecount = 0; let count = 0; for (let i = 0; i < res.length; i++) { if (count >= browser.maxentries) {break} if (browser.filters.isfiltered(res[i].item.categories)) {continue} browser.mod_el_from_obj(res[i].item); count++; } if (count < 1) { browser.loading(lang("gui.browser.no_results")); } }, setbutton: (mod, string, icon) => { mod = mods.normalize(mod); if (browserEntries.querySelector(`#mod-${mod}`)) { let elems = browserEntries.querySelectorAll(`.el#mod-${mod}`); for (let i = 0; i < elems.length; i++) { if (icon) { string = `` + `${string}`; } elems[i].querySelector(".text button").innerHTML = string; } } else { let make = (str) => { if (browserEntries.querySelector(`#mod-${str}`)) { return browser.setbutton(str, string, icon); } else { return false; } } setTimeout(() => { for (let i = 0; i < mods.list().all.length; i++) { let modname = mods.normalize(mods.list().all[i].name); let modfolder = mods.normalize(mods.list().all[i].folder_name); if (mod.includes(modname)) { if (! make(modname)) { if (mods.list().all[i].manifest_name) { make(mods.normalize(mods.list().all[i].manifest_name)); } } } else if (mod.includes(modfolder)) {make(modfolder);break} } }, 1501) } }, loadpkgs: (pkgs, clear) => { if (clear) {packagecount = 0} if (browserEntries.querySelector(".message")) { browserEntries.querySelector(".message").remove(); } let count = 0; for (let i in pkgs) { if (count >= browser.maxentries) { if (pkgs[i] === undefined) { browser.endoflist(true); } browser.endoflist(); break } try { browser.mod_el_from_obj(pkgs[i]); }catch(e) {} count++; packagecount++; } }, msg: (html) => { let msg = document.createElement("div"); msg.classList.add("message"); msg.innerHTML = html; browserEntries.appendChild(msg); } } sort.querySelector("select").addEventListener("change", () => { browser.loadfront(); }) setInterval(browser.add_pkg_properties, 1500); if (navigator.onLine) { browser.loadfront(); } var view = document.querySelector(".popup#preview webview"); browser.preview = { show: () => { popups.show(preview, false); }, hide: () => { popups.hide(preview, false); }, set: (url, autoshow) => { if (autoshow != false) {browser.preview.show()} view.src = url; document.querySelector("#preview #external").setAttribute( "onclick", `require("electron").shell.openExternal("${url}")` ) } } browser.mod_el_from_obj = (obj) => { let pkg = {...obj, ...obj.versions[0]}; browser.mod_el({ pkg: pkg, title: pkg.name, image: pkg.icon, author: pkg.owner, url: pkg.package_url, download: pkg.download_url, version: pkg.version_number, categories: pkg.categories, description: pkg.description, dependencies: pkg.dependencies, }) } browser.mod_el = (properties) => { if (browser.filters.isfiltered(properties.categories)) {return} properties = { title: "No name", version: "1.0.0", image: "icons/no-image.png", author: "Unnamed Pilot", description: "No description", ...properties } if (properties.version[0] != "v") { properties.version = "v" + properties.version; } if (browserEntries.querySelector(".loading")) { browserEntries.innerHTML = ""; } let installicon = "downloads"; let installstr = lang("gui.browser.install"); let normalized_title = mods.normalize(properties.title) let installcallback = () => { browser.install(properties); } let nondefault_install = { "vanillaplus": "https://github.com/NachosChipeados/NP.VanillaPlus/blob/main/README.md" } if (normalized_title in nondefault_install) { installicon = "open"; installstr = lang("gui.browser.guide"); installcallback = () => { shell.openExternal(nondefault_install[normalized_title]) } } else if (properties.pkg.local_version) { installicon = "redo"; installstr = lang("gui.browser.reinstall"); if (properties.pkg.has_update) { installicon = "downloads"; installstr = lang("gui.browser.update"); } } let entry = document.createElement("div"); entry.classList.add("el"); entry.id = `mod-${normalized_title}`; entry.innerHTML = `
${properties.title}
${properties.description}
` entry.querySelector("button.install").addEventListener("click", installcallback) browserEntries.appendChild(entry); } browser.packages = async () => { await browser.loadfront(); return packages; } let recent_toasts = {}; function add_recent_toast(name, timeout = 3000) { if (recent_toasts[name]) {return} recent_toasts[name] = true; setTimeout(() => { delete recent_toasts[name]; }, timeout) } ipcRenderer.on("removed-mod", (_, mod) => { set_buttons(true); browser.setbutton(mod.name, lang("gui.browser.install"), "downloads"); if (mod.manifest_name) { browser.setbutton(mod.manifest_name, lang("gui.browser.install"), "downloads"); } }) ipcRenderer.on("failed-mod", (_, modname) => { if (recent_toasts["failed" + modname]) {return} add_recent_toast("failed" + modname); set_buttons(true); toasts.show({ timeout: 10000, scheme: "error", title: lang("gui.toast.title.failed"), description: lang("gui.toast.desc.failed") }) }) ipcRenderer.on("legacy-duped-mod", (_, modname) => { if (recent_toasts["duped" + modname]) {return} add_recent_toast("duped" + modname); set_buttons(true); toasts.show({ timeout: 10000, scheme: "warning", title: lang("gui.toast.title.duped"), description: modname + " " + lang("gui.toast.desc.duped") }) }) ipcRenderer.on("no-internet", () => { toasts.show({ timeout: 10000, scheme: "error", title: lang("gui.toast.title.no_internet"), description: lang("gui.toast.desc.no_internet") }) }) ipcRenderer.on("installed-mod", (_, mod) => { if (recent_toasts["installed" + mod.name]) {return} add_recent_toast("installed" + mod.name); let name = mod.fancy_name || mod.name; set_buttons(true); browser.setbutton(name, lang("gui.browser.reinstall"), "redo"); if (mod.malformed) { toasts.show({ timeout: 8000, scheme: "warning", title: lang("gui.toast.title.malformed"), description: name + " " + lang("gui.toast.desc.malformed") }) } toasts.show({ scheme: "success", title: lang("gui.toast.title.installed"), description: name + " " + lang("gui.toast.desc.installed") }) if (mods.install_queue.length != 0) { mods.install_from_url( "https://thunderstore.io/package/download/" + mods.install_queue[0].pkg, false, false, mods.install_queue[0].author, mods.install_queue[0].package_name, mods.install_queue[0].version ) mods.install_queue.shift(); } }) let searchtimeout; let searchstr = ""; let search = document.querySelector("#browser .search"); search.addEventListener("keyup", () => { browser.filters.toggle(false); clearTimeout(searchtimeout); if (searchstr != search.value) { if (search.value.replaceAll(" ", "") == "") { searchstr = ""; browser.loadfront(); return } searchtimeout = setTimeout(() => { browser.search(search.value); searchstr = search.value; }, 500) } }) let mouse_events = ["scroll", "mousedown", "touchdown"]; mouse_events.forEach((event) => { document.body.addEventListener(event, () => { let mouse_at = document.elementsFromPoint(mouseX, mouseY); if (! mouse_at.includes(document.querySelector("#preview"))) { browser.preview.hide(); } if (! mouse_at.includes(document.querySelector("#filter")) && ! mouse_at.includes(document.querySelector(".overlay"))) { browser.filters.toggle(false); } }) }); view.addEventListener("dom-ready", () => { let css = [ fs.readFileSync(__dirname + "/../css/theming.css", "utf8"), fs.readFileSync(__dirname + "/../css/webview.css", "utf8") ] view.insertCSS(css.join(" ")); }) view.addEventListener("did-stop-loading", () => { view.style.display = "flex"; setTimeout(() => { view.classList.remove("loading"); }, 200) }) view.addEventListener("did-start-loading", () => { view.style.display = "none"; view.classList.add("loading"); }) let mouseY = 0; let mouseX = 0; browser_el.addEventListener("mousemove", (event) => { mouseY = event.clientY; mouseX = event.clientX; }) let checks = document.querySelectorAll(".check"); for (let i = 0; i < checks.length; i++) { checks[i].setAttribute("onclick", "this.classList.toggle('checked');browser.loadfront();search.value = ''" ) } module.exports = browser; ================================================ FILE: src/app/js/dom_events.js ================================================ const popups = require("./popups"); const settings = require("./settings"); let drag_timer; document.addEventListener("dragover", (e) => { e.preventDefault(); e.stopPropagation(); dragUI.classList.add("shown"); clearTimeout(drag_timer); drag_timer = setTimeout(() => { dragUI.classList.remove("shown"); }, 5000) }) document.addEventListener("mouseover", () => { clearTimeout(drag_timer); dragUI.classList.remove("shown"); }) document.addEventListener("drop", (e) => { e.preventDefault(); e.stopPropagation(); dragUI.classList.remove("shown"); mods.install_from_path(e.dataTransfer.files[0].path); }) document.body.addEventListener("click", (e) => { if (e.target.tagName.toLowerCase() === "a" && e.target.protocol != "file:") { e.preventDefault(); shell.openExternal(e.target.href); } }) ================================================ FILE: src/app/js/events.js ================================================ const EventEmitter = require("events"); class Emitter extends EventEmitter {}; const events = new Emitter(); module.exports = events; ================================================ FILE: src/app/js/gamepad.js ================================================ const popups = require("./popups"); const settings = require("./settings"); const launcher = require("./launcher"); const navigate = require("./navigate"); window.addEventListener("gamepadconnected", (e) => { console.log("Gamepad connected:", e.gamepad.id); }, false) window.addEventListener("gamepaddisconnected", (e) => { console.log("Gamepad disconnected:", e.gamepad.id); }, false) // this contains the names/directions of axes and IDs that have // previously been pressed, if it is found that these were recently // pressed in the next iteration of the `setInterval()` below than the // iteration is skipped // // the value of each item is equivalent to the amount of iterations to // wait, so `up: 3` will cause it to wait 3 iterations, before `up` can // be pressed again let delay_press = {}; let held_buttons = {}; setInterval(() => { let gamepads = navigator.getGamepads(); // this has a list of all the directions that the `.axes[]` are // pointing in, letting us navigate in that direction let directions = {} // keeps track of which buttons `delay_press` that have already been // lowered, that way we can lower the ones that haven't been lowered // through a button press let lowered_delay = []; // is the select/accept button being held let selecting = false; for (let i in gamepads) { if (! gamepads[i]) {continue} // every other `.axes[]` element is a different coordinate, each // analog stick has 2 elements in `.axes[]`, the first one is // the x coordinate, second is the y coordinate // // so we use this to keep track of which coordinate we're // currently on, and thereby the direction of the float inside // `.axes[i]` let coord = "x"; let deadzone = 0.5; for (let ii = 0; ii < gamepads[i].axes.length; ii++) { let value = gamepads[i].axes[ii]; // check if we're beyond the deadzone in both the negative // and positive direction, and then using `coord` add a // direction to `directions` if (value < -deadzone) { if (coord == "y") { directions.up = true; } else { directions.left = true; } } else if (value > deadzone) { if (coord == "y") { directions.down = true; } else { directions.right = true; } } // flip `coord` if (coord == "x") { coord = "y"; } else { coord = "x"; } } // only support "standard" button layouts/mappings // // TODO: for anybody reading this in the future, the support // for other mappings is something that's on the table, // however, due to not having all the hardware in the world, // this will have to be up to someone else if (gamepads[i].mapping != "standard") { continue; } for (let ii = 0; ii < gamepads[i].buttons.length; ii++) { if (! gamepads[i].buttons[ii].pressed) { held_buttons[ii] = false; continue; } // a list of known combinations of buttons for the most // common brands out there, more should possibly be added let brands = { "Xbox": { accept: 0, cancel: 1 }, "Nintendo": { accept: 1, cancel: 0 }, "PlayStation": { accept: 0, cancel: 1 } } // this is the most common setup, to my understanding, with // the exception of third party Nintendo controller, may // need to be adjusted in the future let buttons = { accept: 0, cancel: 1 } // set `cancel` and `accept` accordingly to the ID of the // gamepad, if its a known brand for (let brand in brands) { // unknown brand if (! gamepads[i].id.includes(brand)) { continue; } // set buttons according to brand buttons = brands[brand]; break; } // if the button that's being pressed is the "accept" // button, then we set `selecting` to `true`, this is done // before we check for the button delay so that holding the // button keeps the selection in place, until the button is // no longer pressed if (ii == buttons.accept) { selecting = true; } // if this button is still delayed, we lower the delay and // then go to the next button if (delay_press[ii]) { delay_press[ii]--; lowered_delay.push(ii); continue; } // add delay to this button, so it doesn't get clicked // immediately again after this delay_press[ii] = 3; if (held_buttons[ii]) { continue; } held_buttons[ii] = true; // interpret `ii` as a specific button/action, using the // standard IDs: https://w3c.github.io/gamepad/#remapping switch(ii) { // settings popup (center cluster buttons) case 8: settings.popup.toggle(); break; case 9: settings.popup.toggle(); break; // change active section (top bumpers) case 4: launcher.relative_section("left"); break; case 5: launcher.relative_section("right"); break; // navigate selection (dpad) case 12: navigate.move("up"); break; case 13: navigate.move("down"); break; case 14: navigate.move("left"); break; case 15: navigate.move("right"); break; // click selected element case buttons.accept: navigate.select(); break; // close last opened popup case buttons.cancel: popups.hide_last(); break; } } } for (let i in directions) { if (directions[i] === true) { // if this direction is still delayed, we lower the delay, // and then go to the next direction if (delay_press[i]) { delay_press[i]--; lowered_delay.push(i); continue; } // move in the direction navigate.move(i); // add delay to this direction, to prevent it from being // triggered immediately again delay_press[i] = 5; } } // run through buttons that have or have had a delay for (let i in delay_press) { // if a button has a delay, and it hasn't already been lowered, // then we lower it if (delay_press[i] && ! lowered_delay.includes(i)) { delay_press[i]--; } } let selection_el = document.getElementById("selection"); // add `.selecting` to `#selection` depending on whether // `selecting`, is set or not if (selecting) { selection_el.classList.add("controller-selecting"); } else { selection_el.classList.remove("controller-selecting"); } }, 50) let can_keyboard_navigate = (e) => { // quite empty right now, might add more in the future, these are // just element selectors where movement with the keyboard is off let ignore_on_focus = [ "input", "select" ] // check for whether the active element is one that matches // something in `ignore_on_focus` for (let i = 0; i < ignore_on_focus.length; i++) { if (! document.activeElement.matches(ignore_on_focus)) { // active element does not match to `ignore_on_focus[i]` continue; } // if the key that's being pressed is "Escape" then we unfocus // to the currently focused active element, this lets you go // into an input, and then exit it as well if (e.key == "Escape") { document.activeElement.blur(); } return false; } // check if there's already an active selection if (document.querySelector(".active-selection")) { // this is a list of keys where this keyboard event will be // cancelled on, this prevents key events from being sent to // element, but still lets you type let cancel_keys = [ "Space", "Enter", "ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight" ] // cancel this keyboard event if `e.key` is inside `cancel_keys` if (cancel_keys.includes(e.code)) { e.preventDefault(); } } return true; } window.addEventListener("keydown", (e) => { // do nothing if we cant navigate if (! can_keyboard_navigate(e)) { return; } let select = () => { // do nothing if this is a repeat key press if (e.repeat) {return} // select `.active-selection` navigate.select(); // add `.keyboard-selecting` to `#selection` document.getElementById("selection") .classList.add("keyboard-selecting"); } // perform the relevant action for the key that was pressed switch(e.code) { // select case "Space": return select(); case "Enter": return select(); // close popup case "Escape": return popups.hide_last(); // move selection case "KeyK": case "ArrowUp": return navigate.move("up") case "KeyJ": case "ArrowDown": return navigate.move("down") case "KeyH": case "ArrowLeft": return navigate.move("left") case "KeyL": case "ArrowRight": return navigate.move("right") } }) window.addEventListener("keyup", (e) => { if (! can_keyboard_navigate(e)) { return; } let selection_el = document.getElementById("selection"); // perform the relevant action for the key that was pressed switch(e.code) { // the second and third cases here are for SteamDeck bumper // button support whilst inside the desktop layout case "KeyQ": case "ControlLeft": case "ControlRight": launcher.relative_section("left"); break; case "KeyE": case "AltLeft": case "AltRight": launcher.relative_section("right"); break; case "Space": return selection_el .classList.remove("keyboard-selecting"); case "Enter": return selection_el .classList.remove("keyboard-selecting"); } }) ================================================ FILE: src/app/js/gamepath.js ================================================ const ipcRenderer = require("electron").ipcRenderer; const lang = require("../../lang"); const process = require("./process"); const launcher = require("./launcher"); const settings = require("./settings"); // frontend part of settings a new game path ipcRenderer.on("newpath", (_, newpath) => { set_buttons(true); settings.set({gamepath: newpath}); ipcRenderer.send("gui-getmods"); ipcRenderer.send("save-settings", settings.data()); }) // a previously valid gamepath no longer exists, and is therefore lost ipcRenderer.on("gamepath-lost", () => { launcher.change_page(0); set_buttons(false, true); alert(lang("gui.gamepath.lost")); }) // error out when no game path is set ipcRenderer.on("no-path-selected", () => { alert(lang("gui.gamepath.must")); process.exit(); }) // error out when game path is wrong ipcRenderer.on("wrong-path", () => { alert(lang("gui.gamepath.wrong")); gamepath.set(false); }) // reports to the main process about game path status. module.exports = { open: () => { let gamepath = settings.data().gamepath; if (gamepath) { require("electron").shell.openPath(gamepath); } else { alert(lang("gui.settings.miscbuttons.open_gamepath_alert")); } }, set: (value) => { ipcRenderer.send("setpath", value); } } ================================================ FILE: src/app/js/is_running.js ================================================ const lang = require("../../lang"); // is the game running? let is_running = false; // updates play buttons depending on whether the game is running ipcRenderer.on("is-running", (event, running) => { let set_playbtns = (text) => { let playbtns = document.querySelectorAll(".playBtn"); for (let i = 0; i < playbtns.length; i++) { playbtns[i].innerHTML = text; } } if (running && is_running != running) { set_buttons(false); set_playbtns(lang("general.running")); is_running = running; // show force quit button in Titanfall tab tfquit.style.display = "inline-block"; update.setAttribute("onclick", "kill('game')"); update.innerHTML = "(" + lang("ns.menu.force_quit") + ")"; return; } if (is_running != running) { set_buttons(true); set_playbtns(lang("gui.launch")); is_running = running; // hide force quit button in Titanfall tab tfquit.style.display = "none"; update.setAttribute("onclick", "update.ns()"); update.innerHTML = "(" + lang("gui.update.check") + ")"; } }) // return whether the game is running module.exports = () => { return is_running; } ================================================ FILE: src/app/js/kill.js ================================================ const ipcRenderer = require("electron").ipcRenderer; // attempts to kill something using the main process' `modules/kill.js` // functions, it simply attempts to run `kill[function_name]()`, if it // doesn't exist, nothing happens module.exports = (function_name) => { ipcRenderer.send("kill", function_name); } ================================================ FILE: src/app/js/launch.js ================================================ const update = require("./update"); // tells the main process to launch `game_version` module.exports = (game_version) => { if (game_version == "vanilla") { ipcRenderer.send("launch", game_version); return; } if (update.ns.should_install) { update.ns(); } else { ipcRenderer.send("launch", game_version); } } ================================================ FILE: src/app/js/launcher.js ================================================ const popups = require("./popups"); const markdown = require("marked").parse; let launcher = {}; var servercount; var playercount; var masterserver; // changes the main page, this is the tabs in the sidebar launcher.change_page = (page) => { let btns = document.querySelectorAll(".gamesContainer button"); let pages = document.querySelectorAll(".mainContainer .contentContainer"); for (let i = 0; i < pages.length; i++) { pages[i].classList.add("hidden"); } for (let i = 0; i < btns.length; i++) { btns[i].classList.add("inactive"); } pages[page].classList.remove("hidden"); btns[page].classList.remove("inactive"); bgHolder.setAttribute("bg", page); }; launcher.change_page(1) launcher.format_release = (notes) => { if (! notes) {return ""} let content = ""; if (notes.length === 1) { content = notes[0]; } else { for (let release of notes) { if (release.prerelease) {continue} let new_content = // release date new Date(release.published_at).toLocaleString() + "\n" + // release name `# ${release.name}` + "\n\n" + // actual release text/body release.body + "\n\n\n"; content += "
\n" + markdown(new_content, {breaks: true}) + "\n" + "
"; } content = content.replaceAll(/\@(\S+)/g, `@$1`); } return markdown(content, { breaks: true }); } // sets content of `div` to a single release block with centered text // inside it, the text being `lang(lang_key)` launcher.error = (div, lang_key) => { div.innerHTML = "
" + "

" + lang(lang_key) + "

" + "
"; } // updates the Viper release notes ipcRenderer.on("vp-notes", (event, response) => { if (! response) { return launcher.error( vpReleaseNotes, "request.no_vp_release_notes" ) } vpReleaseNotes.innerHTML = launcher.format_release(response); }); // updates the Northstar release notes ipcRenderer.on("ns-notes", (event, response) => { if (! response) { return launcher.error( nsRelease, "request.no_ns_release_notes" ) } nsRelease.innerHTML = launcher.format_release(response); }); launcher.load_vp_notes = async () => { ipcRenderer.send("get-vp-notes"); }; launcher.load_vp_notes(); launcher.load_ns_notes = async () => { ipcRenderer.send("get-ns-notes"); }; launcher.load_ns_notes(); // TODO: We gotta make this more automatic instead of switch statements // it's both not pretty, but adding more sections requires way too much // effort, compared to how it should be. launcher.show_vp = (section) => { if (!["main", "release", "info", "credits"].includes(section)) throw new Error("unknown vp section"); vpMainBtn.removeAttribute("active"); vpReleaseBtn.removeAttribute("active"); vpInfoBtn.removeAttribute("active"); vpMain.classList.add("hidden"); vpReleaseNotes.classList.add("hidden"); vpInfo.classList.add("hidden"); switch(section) { case "main": vpMainBtn.setAttribute("active", ""); vpMain.classList.remove("hidden"); break; case "release": vpReleaseBtn.setAttribute("active", ""); vpReleaseNotes.classList.remove("hidden"); break; case "info": vpInfoBtn.setAttribute("active", ""); vpInfo.classList.remove("hidden"); break; } } launcher.show_ns = (section) => { if (! ["main", "release", "mods"].includes(section)) { throw new Error("unknown ns section"); } nsMainBtn.removeAttribute("active"); nsModsBtn.removeAttribute("active"); nsReleaseBtn.removeAttribute("active"); nsMain.classList.add("hidden"); nsMods.classList.add("hidden"); nsRelease.classList.add("hidden"); switch(section) { case "main": nsMainBtn.setAttribute("active", ""); nsMain.classList.remove("hidden"); break; case "mods": nsModsBtn.setAttribute("active", ""); nsMods.style.display = "block"; nsMods.classList.remove("hidden"); break; case "release": nsReleaseBtn.setAttribute("active", ""); nsRelease.classList.remove("hidden"); break; } } // changes the active section on the currently active // `.contentContainer` in the direction specified // // `direction` can be: left or right launcher.relative_section = (direction) => { // prevent switching section if a popup is open if (popups.open_list().length) { return; } // the `.contentMenu` in the currently active tab let active_menu = document.querySelector( ".contentContainer:not(.hidden) .contentMenu" ) // get the currently active section let active_section = active_menu.querySelector("[active]"); // no need to do anything, if there's somehow no active section if (! active_section) {return} // these will be filled out let prev_section, next_section; // get list of all the sections let sections = active_menu.querySelectorAll("li"); for (let i = 0; i < sections.length; i++) { if (sections[i] != active_section) { continue; } // make `next_section` be the next element in `sections` next_section = sections[i + 1]; // if we're at the first iteration, use the last element in // `sections` as the previous section, otherwise make it the // element before this iteration if (i == 0) { prev_section = sections[sections.length - 1]; } else { prev_section = sections[i - 1]; } } let new_section; // if we're going left, and a previous section was found, click it if (direction == "left" && prev_section) { new_section = prev_section; } else if (direction == "right") { // click the next section, if one was found, otherwise just // assume that the first section is the next section, as the // active section is likely just the last section, so we wrap // around instead if (next_section) { new_section = next_section; } else if (sections[0]) { new_section = sections[0]; } } if (new_section) { new_section.click(); // if there's an active selection, we select the new section, as // that selection may be in a section that's now hidden if (document.querySelector(".active-selection")) { navigate.selection(new_section); } } } launcher.check_servers = async () => { serverstatus.classList.add("checking"); try { let host = "northstar.tf"; let path = "/client/servers"; // ask the masterserver for the list of servers, if this has // been done recently, it'll simply return the cached version let servers = JSON.parse( await request(host, path, "ns-servers", false) ) masterserver = true; playercount = 0; servercount = servers.length; for (let i = 0; i < servers.length; i++) { playercount += servers[i].playerCount } }catch (err) { playercount = 0; servercount = 0; masterserver = false; } serverstatus.classList.remove("checking"); if (servercount == 0 || ! servercount || ! playercount) {masterserver = false} let playerstr = lang("gui.server.players"); if (playercount == 1) { playerstr = lang("gui.server.player"); } if (masterserver) { serverstatus.classList.add("up"); serverstatus.classList.remove("down"); serverstatus.innerHTML = `${servercount} ${lang("gui.server.servers")} - ${playercount} ${playerstr}`; } else { serverstatus.classList.add("down"); serverstatus.classList.remove("up"); serverstatus.innerHTML = lang("gui.server.offline"); } }; launcher.check_servers() // refreshes every 5 minutes setInterval(() => { launcher.check_servers(); }, 300000) module.exports = launcher; ================================================ FILE: src/app/js/localize.js ================================================ // localizes `string`, removing instances of `%%string%%` with // `lang("string")` and so forth function localize_string(string) { let parts = string.split("%%"); // basic checks to make sure `string` has lang strings if (parts.length == 0 || string.trim() == "" || ! string.match("%%")) { return string; } for (let i = 0; i < parts.length; i++) { // simply checks to make sure it is actually a lang string. if (parts[i][0] != " " && parts[i][parts[i].length - 1] != " ") { // get string let lang_str = lang(parts[i]); // make sure we got a string back, and if not, do nothing if (typeof lang_str !== "string") { continue; } // replace this part with the lang string parts[i] = lang_str; } } // return finalized formatted string return parts.join(""); } // runs `localize_string()` on `el`'s attributes, text nodes and children function localize_el(el) { // we don't want to mess with script tags if (el.tagName == "SCRIPT") {return} let attributes = el.getAttributeNames(); // run through child nodes for (let i = 0; i < el.childNodes.length; i++) { // if the node isn't a text node, we do nothing if (el.childNodes[i].nodeType != Node.TEXT_NODE) { continue; } // the node is a text node, so we set its `.textContent` by // running `format_string()` on it el.childNodes[i].textContent = localize_string(el.childNodes[i].textContent) } // run through attributes and run `format_string()` on their values for (let i = 0; i < attributes.length; i++) { let attr = el.getAttribute(attributes[i]); el.setAttribute(attributes[i], localize_string(attr)) } // run `replace_in_el()` on `el`'s children for (let i = 0; i < el.children.length; i++) { localize_el(el.children[i]); } } // localizes lang strings on (almost) all the elements inside `` module.exports = () => { localize_el(document.body); } ================================================ FILE: src/app/js/mods.js ================================================ const util = require('util'); const ipcRenderer = require("electron").ipcRenderer; const lang = require("../../lang"); const version = require("./version"); const toasts = require("./toasts"); const set_buttons = require("./set_buttons"); let mods = {}; let mods_list = { all: [], enabled: [], disabled: [] } // returns the list of mods mods.list = () => { return mods_list; } mods.load = (mods_obj) => { modcount.innerHTML = `${lang("gui.mods.count")} ${mods_obj.all.length}`; let normalized_names = []; let set_mod = (mod) => { let name = mod.name; if (mod.package) { name = mod.package.package_name; } let normalized_name = "mod-list-" + mods.normalize(name); normalized_names.push(normalized_name); let el = document.getElementById(normalized_name); if (el) { if (mod.disabled) { el.querySelector(".switch").classList.remove("on"); } else { el.querySelector(".switch").classList.add("on"); } return; } let div = document.createElement("div"); div.classList.add("el"); div.id = normalized_name; let mod_details = { name: mod.name, version: mod.version, description: mod.description } if (mod.package) { mod_details = { image: mod.package.icon, name: mod.package.manifest.name, version: mod.package.manifest.version_number, description: mod.package.manifest.description } } div.innerHTML += `
${mod_details.name}
${mod_details.description}
`; if (mod_details.name.match(/^Northstar\..*/)) { div.querySelector("img").src = "icons/northstar.png" } div.querySelector(".remove").onclick = () => { if (! mod.package) { return mods.remove(mod.name); } for (let i = 0; i < mod.packaged_mods.length; i++) { mods.remove(mod.packaged_mods[i]); } } if (mod.disabled) { div.querySelector(".switch").classList.remove("on"); } div.querySelector(".switch").addEventListener("click", () => { if (! mod.package) { return mods.toggle(mod.name); } for (let i = 0; i < mod.packaged_mods.length; i++) { mods.toggle(mod.packaged_mods[i]); } }) div.querySelector(".image").style.display = "none"; modsdiv.append(div); } for (let i = 0; i < mods_obj.all.length; i++) { set_mod(mods_obj.all[i]); } let mod_els = document.querySelectorAll("#modsdiv .el"); let mod_update_els = []; for (let i = 0; i < mod_els.length; i++) { let update_btn = mod_els[i].querySelector(".update"); if (update_btn && update_btn.style.display != "none") { mod_update_els.push(mod_els[i].id); } else { break; } } for (let i = 0; i < mod_els.length; i++) { let mod = mod_els[i].id.replace(/^mod-list-/, ""); if (! normalized_names.includes(mod_els[i].id)) { mod_els[i].remove(); return; } let image_container = mod_els[i].querySelector(".image"); let image_el = image_container.querySelector("img") let image_blur_el = image_container.querySelector("img.blur") if (browser.mod_versions[mod]) { image_el.src = browser.mod_versions[mod].package.versions[0].icon; } if (image_el.getAttribute("src") && ! image_container.parentElement.classList.contains("has-icon")) { let image_src = image_el.getAttribute("src"); image_blur_el.src = image_src; image_container.style.display = null; image_container.parentElement.classList.add("has-icon"); } if (browser.mod_versions[mod] && browser.mod_versions[mod].has_update) { mod_els[i].querySelector(".update").style.display = null; mod_els[i].querySelector(".update").setAttribute( "onclick", `browser.mod_versions["${mod}"].install()` ) if (mod_update_els.includes(mod_els[i].id)) { continue; } let mod_el = mod_els[i].cloneNode(true); // copy click event of the remove button to the new button mod_el.querySelector(".remove").onclick = mod_els[i].querySelector(".remove").onclick; mod_el.classList.add("no-animation"); mod_el.querySelector(".switch").addEventListener("click", () => { if (browser.mod_versions[mod].local_name) { mods.toggle(browser.mod_versions[mod].local_name); } }) mod_els[i].remove(); modsdiv.querySelector(".line:has(.search)").after(mod_el); } else { mod_els[i].querySelector(".update").style.display = "none"; } } } // attempts to filter `#modsdiv` with `query` mods.search = (query) => { // if no `query` is given, use the search input's value if (! query) { query = mods.search.el.value; } // normalizes `string` let normalize = (string) => { return string .trim().toLowerCase() .replaceAll(" ", "").replaceAll(".", ""); } // normalize `query` query = normalize(query); // get all mod elements let mod_els = document.querySelectorAll("#modsdiv .el"); // run through all the mod elements for (let mod_el of mod_els) { // get the normalized name of the mod let name = normalize(mod_el.querySelector(".title").innerText); // if the name has `query` in it, show it if (name.match(query)) { mod_el.style.display = null; } else { // hide if it doesn't match mod_el.style.display = "none"; } } } mods.search.el = document.getElementById("mods-search"); mods.search.el.addEventListener("keyup", () => {mods.search()}) mods.remove = (mod) => { if (mod.toLowerCase().match(/^northstar\./)) { if (! confirm(lang("gui.mods.required_confirm"))) { return; } } else if (mod == "allmods") { if (! confirm(lang("gui.mods.remove_all_confirm"))) { return; } } ipcRenderer.send("remove-mod", mod); } mods.toggle = (mod) => { // is this a core mod? if (mod.toLowerCase().match(/^northstar\./)) { // keep track of whether this mod is disabled let is_disabled = false; // run through disabled mods for (let mod_obj of mods_list.disabled) { // if `mod` is `mod_obj`, update `is_disabled` if (mod_obj.name.toLowerCase() == mod.toLowerCase()) { is_disabled = true; break; } } // show prompt if the mod is enabled if (! is_disabled && ! confirm(lang("gui.mods.required_confirm"))) { return; } } else if (mod == "allmods") { if (! confirm(lang("gui.mods.toggle_all_confirm"))) { return; } } ipcRenderer.send("toggle-mod", mod); } mods.install_queue = []; // tells the main process to install a mod through the file selector mods.install_prompt = () => { set_buttons(false); ipcRenderer.send("install-mod"); } // tells the main process to directly install a mod from this path mods.install_from_path = (path) => { set_buttons(false); ipcRenderer.send("install-from-path", path); } // tells the main process to install a mod from a URL mods.install_from_url = (url, dependencies, clearqueue, author, package_name, version) => { if (clearqueue) {mods.install_queue = []}; let prettydepends = []; if (dependencies) { let newdepends = []; for (let i = 0; i < dependencies.length; i++) { let depend = dependencies[i].toLowerCase(); if (! depend.match(/northstar-northstar-.*/)) { depend = dependencies[i].replaceAll("-", "/"); let pkg = depend.split("/"); if (! mods.is_installed(pkg[1])) { newdepends.push({ pkg: depend, author: pkg[0], version: pkg[2], package_name: pkg[1] }); prettydepends.push(`${pkg[1]} v${pkg[2]} - ${lang("gui.browser.made_by")} ${pkg[0]}`); } } } dependencies = newdepends; } if (dependencies && dependencies.length != 0) { let confirminstall = confirm(lang("gui.mods.confirm_dependencies") + prettydepends.join("\n")); if (! confirminstall) { return; } } set_buttons(false); ipcRenderer.send("install-from-url", url, author, package_name, version); if (dependencies) { mods.install_queue = dependencies; } } mods.is_installed = (modname) => { for (let i = 0; i < mods.list().all.length; i++) { let mod = mods.list().all[i]; if (mod.manifest_name) { if (mod.manifest_name.match(modname)) { return true; } } else if (mod.name.match(modname)) { return true; } } return false; } mods.normalize = (items) => { let main = (string) => { return string.replaceAll(" ", "") .replaceAll(".", "").replaceAll("-", "") .replaceAll("_", "").toLowerCase(); } if (typeof items == "string") { return main(items); } else { let newArray = []; for (let i = 0; i < items.length; i++) { newArray.push(main(items[i])); } return newArray; } } // updates the installed mods ipcRenderer.on("mods", (event, mods_obj) => { mods_list = mods_obj; if (! mods_obj) {return} mods.load(mods_obj); }) ipcRenderer.on("protocol-install-mod", async (event, data) => { const domain = data[0]; const author = data[1]; const package_name = data[2]; const version = data[3]; const packages = await browser.packages(); const package = packages.find((package) => { return package.owner == author && package.name == package_name; }) if (!package) { alert(util.format(lang("gui.mods.cant_find_specific"), author, package_name)); return; } const package_obj = package.versions.find((package_version) => { return package_version.version_number == version; }) if (!package_obj) { alert(util.format(lang("gui.mods.cant_find_version"), version, author, package_name)) return; } toasts.show({ timeout: 3000, scheme: "info", title: lang("gui.mods.installing"), description: package_obj.full_name }) mods.install_from_url( package_obj.download_url, package_obj.dependencies, false, author, package_name, version ); }) module.exports = mods; ================================================ FILE: src/app/js/navigate.js ================================================ const events = require("./events"); const popups = require("./popups"); const settings = require("./settings"); let navigate = { using: false } // sets `#selection` to the correct position, size and border radius, // according to what is currently the `.active-selection`, if none is // found, it'll instead be hidden navigate.selection = (new_selection) => { // if we're not allowed to unselect an element, then make sure that // element is still unselected, and then clear // `navigate.dont_unselect` if (navigate.dont_unselect && navigate.dont_unselect != new_selection) { navigate.dont_unselect.classList.add("active-selection"); navigate.dont_unselect = false; return; } if (new_selection) { let selected = document.querySelectorAll(".active-selection"); // make sure just `new_selection` has `.active-selection` for (let i = 0; i < selected.length; i++) { if (selected[i] != new_selection) { selected[i].classList.remove("active-selection"); } } new_selection.classList.add("active-selection"); } // shorthands let selection_el = document.getElementById("selection"); let active_el = document.querySelector(".active-selection"); // make sure there's an `active_el`, and hide the `selection_el` if // that isn't the case if (! active_el) { selection_el.style.opacity = "0.0"; return; } // this adds space between the `selection_el` and `` let padding = 8; // attempt to get the border radius of `active_el` let radius = getComputedStyle(active_el).borderRadius; // if there's no radius set, we default to the default of // `selection_el` through using `null` if (! radius || radius == "0px") { radius = null; } // set visibility and radius selection_el.style.opacity = "1.0"; selection_el.style.borderRadius = radius; // get bounds for position and size calculations of `selection_el` let active_bounds = active_el.getBoundingClientRect(); // set top and left side coordinate subtracting the padding selection_el.style.top = active_bounds.top - padding + "px"; selection_el.style.left = active_bounds.left - padding + "px"; // set width of `selection_el` with the padding selection_el.style.width = active_bounds.width + (padding * 2) + "px"; // set height of `selection_el` with the padding selection_el.style.height = active_bounds.height + (padding * 2) + "px"; } // data from the last iterations of the interval below let last_sel = { el: false, bounds: false } // auto update `#selection` if `.active-selection` changes bounds, but // not element by itself setInterval(() => { // get active selection let selected = document.querySelector(".active-selection"); // if there's no active selection, reset `last_sel` if (! selected) { last_sel.el = false; last_sel.bounds = false; return; } // get stringified bounds let bounds = JSON.stringify(selected.getBoundingClientRect()); // if `last_sel.el` is not `selected` the selected element was // changed, so we just set `last_el` and nothing more if (last_sel.el != selected) { last_sel.el = selected; last_sel.bounds = bounds; return; } // if stringified bounds changed we update `#selection` if (bounds != last_sel.bounds) { navigate.selection(); last_sel.el = selected; last_sel.bounds = bounds; } }, 50) // these events cause the `#selection` element to reposition itself window.addEventListener("resize", () => {navigate.selection()}, true); window.addEventListener("scroll", () => {navigate.selection()}, true); // listen for click events, and hide the `#selection` element, when // emitting a mouse event we will want to hide, as it then isn't needed window.addEventListener("click", (e) => { // make sure its a trusted click event, and therefore actually a // mouse, and not anything else if (! e.isTrusted) { return; } // we're no longer using navigation functions navigate.using = false; // get the `.active-selection` let active_el = document.querySelector(".active-selection"); // if there's an `active_el` then we unselect it, and update the // `#selection` element, hiding it if (active_el) { active_el.classList.remove("active-selection"); navigate.selection(); } }) // returns a list of valid elements that should be possible to navigate // to/select with the `#selection` element // // setting `div` makes it limit itself to elements inside that, without // it, it'll use `document.body` or the active popup, if one is found navigate.get_els = (div) => { let els = []; // is `div` not set, and is there a popup shown if (! div && document.body.querySelector(".popup.shown")) { // the spread operator is to convert from a `NodeList` to an // `Array`, and then we need to reverse this to get the ones // that are layered on top first. let popups_list = [...popups.list()].reverse(); // run through the list of popups for (let i = 0; i < popups_list.length; i++) { // if this popup is shown, we make it the current `div` if (popups_list[i].classList.contains("shown")) { div = popups_list[i]; break; } } // get buttons inside `#winbtns` els = [...document.body.querySelectorAll("#winbtns [onclick]")]; } if (! div) { // default div = document.body; } // this gets the list of all the elements we should be able to // select inside `div`, on top of anything that's already in `els` els = [...els, ...div.querySelectorAll([ "a", "input", "button", "select", "textarea", "[onclick]", ".scroll-selection" ])] // this'll contain a filtered list of `els` let new_els = []; // filter out elements we don't care about filter: for (let i = 0; i < els.length; i++) { // elements that match on `els.closest()` with any of these will // be stripped away, as we dont want them let ignore_closest = [ "#overlay", ".no-navigate", "button.visual", ".scroll-selection", ".popup:not(.shown)" ] // ignore, even if `.closest()` matches, if its just matching on // itself instead of a different element let ignore_closest_self = [ ".scroll-selection" ] // check if `els[i].closest()` matches on any of the elements // inside of `ignore_closest` for (let ii = 0; ii < ignore_closest.length; ii++) { let closest = els[i].closest(ignore_closest[ii]); // check if `.closest()` matches, but not on itself if (closest) { // ignore if `closest` is just `els[i]` and the selector // is inside `ignore_closest_self` if (closest == els[i] && ignore_closest_self.includes(ignore_closest[ii])) { continue; } // it matches continue filter; } } // make sure `els[i]` is visible on screen let visible = els[i].checkVisibility({ checkOpacity: true, visibilityProperty: true, checkVisibilityCSS: true, contentVisibilityAuto: true }) // filter out if not visible if (! visible) {continue} // add to filtered list new_els.push(els[i]) } // return the filtered list of elements return new_els; } // attempts to select the currently default selection, if inside a popup // we'll look for a `.default-selection`, if it doesn't exist we'll // simply use the first selectable element in it // // if not inside a popup we'll just use the currently selected tab in // the `.gamesContainer` sidebar navigate.default_selection = () => { // if we're not currently using any navigation functions, this // function shouldn't do anything, as it'll cause a selection to be // made, when it shouldn't be if (! navigate.using) { return; } // the spread operator is to convert from a `NodeList` to an // `Array`, and then we need to reverse this to get the ones // that are layered on top first. let popups_list = [...popups.list()].reverse(); let active_popup; // run through the list of popups for (let i = 0; i < popups_list.length; i++) { // if this popup is shown, set set `active_popup` to it if (popups_list[i].classList.contains("shown")) { active_popup = popups_list[i]; break; } } // is there no active popup? if (! active_popup) { // select the currently selected page in `.gamesContainer` document.querySelector( ".gamesContainer :not(.inactive)" ).classList.add("active-selection"); // update the `#selection` element navigate.selection(); return; } // get the default element inside the active popup let popup_default = active_popup.querySelector("default-selection"); // did we not find a default selection element? if (! popup_default) { // select the first selectable element in the popup navigate.get_els(active_popup)[0].classList.add( "active-selection" ) // update the `#selection` element navigate.selection(); return; } // select the default selection popup_default.classList.add("active-selection"); // update the `#selection` element navigate.selection(); } // this navigates `#selection` in the direction of `direction` // this can be: up, down, left and right navigate.move = async (direction) => { // make sure we note down that we're using navigation functions navigate.using = true; // get the `.active-selection` if there is one let active = document.querySelector(".active-selection"); // if there is no active selection, then attempt to select the // default selection if (! active) { navigate.default_selection() active = document.querySelector(".active-selection"); // if there is somehow still no active selection we stop here if (! active) { return; } } // is the active selection one that should be scrollable? if (active.classList.contains("scroll-selection")) { // scroll the respective `direction` if `active` has any more // scroll left in that direction // short hand to easily scroll in `direction` by `amount` with // smooth scrolling enabled let scroll = (direction, amount) => { // update the `#selection` element navigate.selection(); // scroll inside `` if the active selection is one if (active.tagName == "WEBVIEW") { active.executeJavaScript(` document.scrollingElement.scrollBy({ behavior: "smooth", ${direction}: ${amount} }) `) return; } active.scrollBy({ behavior: "smooth", [direction]: amount }) } // get values needed for determining if we should scroll the // active selection, and by how much let scroll_el = { top: active.scrollTop, left: active.scrollLeft, width: active.scrollWidth, height: active.scrollHeight, bounds: { width: active.clientWidth, height: active.clientWidth } } // get `scroll_el` from inside a `` if the active // selection is one if (active.tagName == "WEBVIEW") { scroll_el = await active.executeJavaScript(`(() => { return { top: document.scrollingElement.scrollTop, left: document.scrollingElement.scrollLeft, width: document.scrollingElement.scrollWidth, height: document.scrollingElement.scrollHeight, bounds: { width: document.scrollingElement.clientWidth, height: document.scrollingElement.clientHeight } } })()`) } // decrease to increase scroll length, and in reverse let scroll_scale = 2; if (direction == "up" && scroll_el.top > 0) { return scroll("top", -scroll_el.bounds.height / scroll_scale); } if (direction == "down" && scroll_el.top <= scroll_el.height && scroll_el.height != scroll_el.bounds.height) { return scroll("top", scroll_el.bounds.height / scroll_scale); } if (direction == "left" && scroll_el.left > 0) { return scroll("left", -width / scroll_scale); } if (direction == "right" && scroll_el.left <= scroll_el.width && scroll_el.width != scroll_el.bounds.width) { return scroll("left", scroll_el.bounds.width / scroll_scale); } } // attempt to get the element in the `direction` requested let move_to_el = navigate.get_relative_el(active, direction); // if no element is found, do nothing if (! move_to_el) {return} // switch `.active-selection` from `active` to `move_to_el` active.classList.remove("active-selection"); move_to_el.classList.add("active-selection"); // update the `#selection` element navigate.selection(); // make sure the selecting classes are removed, and thereby the // scale/pressed effect with it document.getElementById("selection").classList.remove( "keyboard-selecting", "controller-selecting" ) // stop here if `move_to_el` is a child to `document.body` if (move_to_el.parentElement == document.body) { return; } // this element will be scrolled in view later let scroll_el = move_to_el; // these elements cant be scrolled let no_scroll_parents = [ ".el .text", ".gamesContainer", ] // run through unscrollable parent elements for (let i = 0; i < no_scroll_parents.length; i++) { // check if `move_to_el.closest()` matches on anything in // `no_scroll_parents` let no_scroll_parent = move_to_el.closest( no_scroll_parents[i] ) if (! no_scroll_parent) { // it does not match continue; } // it matches, so we make the new `scroll_el` the parent scroll_el = no_scroll_parent; } // refuse to scroll to begin with, if any of these are a parent let ignore_parents = [ ".contentMenu", ".gamesContainer", ] // check if `ignore_parents` match on `move_to_el`, and if so, stop for (let i = 0; i < ignore_parents.length; i++) { if (move_to_el.closest(ignore_parents[i])) { return; } } if (scroll_el.closest(".grid .el")) { scroll_el = scroll_el.closest(".grid .el"); } // scroll `scroll_el` smoothly into view, centered scroll_el.scrollIntoView({ block: "center", inline: "center", behavior: "smooth", }) } // selects the currently selected element, by clicking or focusing it navigate.select = () => { // make sure we note down that we're using navigation functions navigate.using = true; // get the current selection let active = document.querySelector(".active-selection"); // make sure there is a selection if (! active) {return} // slight delay to prevent some timing issues setTimeout(() => { // if `active` is a switch, use `settings.popup.switch()` on it, // to be able to toggle it if (active.closest(".switch")) { active.closest(".switch").click(); settings.popup.switch(active.closest(".switch")); return; } // correctly open a `` is focused active.focus(); active.click(); // send fake Enter key to open selection menu ipcRenderer.send("send-enter-key"); // make sure element is unselected active.addEventListener("change", () => { active.blur(); }, { once: true }) return; } // click and focus `active` active.focus(); active.click(); }, 150) } // selects the closest and hopefully most correct element to select next // to `relative_el` in the direction of `direction` // // the direction can be: up, down, left and right navigate.get_relative_el = (relative_el, direction) => { // get selectable elements let els = navigate.get_els(); // get bounds of `relative_el` let bounds = relative_el.getBoundingClientRect(); // get the centered coordinates of `relative_el` let relative = { x: bounds.left + (bounds.width / 2), y: bounds.top + (bounds.height / 2) } // update the coordinates on the element itself relative_el.coords = relative; // attempt to return the element in the correct direction // if `x` or `y` is a number that's greater or less than 0 then // we'll go in the direction of the coordinate that is as such // // meaning `get_el(1, 0)` will go to the right let get_el = (x = 0, y = 0) => { // `coord` is the coordinate that we're trying to get an element // on, and `rev_coord` is just the opposite coord let coord, rev_coord; // set `coord` and `rev_coord` according to `x` and `y` if (x > 0 || x < 0) { coord = "x"; rev_coord = "y"; } else if (y > 0 || y < 0) { coord = "y"; rev_coord = "x"; } else { // something unexpected was given return false; } // this is the distance between each point which we check for // selectable elements, increasing this improves performance, // but lowers accuracy, and likewise in reverse let jump_distance = 5; // this is the coordinates to check in the direct coord check let check = { x: relative.x, y: relative.y } // this will contain the element that directly next to // `relative_el` from checking every point from `relative_el` // into `direction` let direct_el; // this is the amount of pixels inbetween `relative_el` and // `direct_el`, this means it doesn't have the distance from the // center of `direct_el` or anything included, just the raw // distance between them, this number could vary in accuracy // depending on how big or small `jump_distance` is let direct_distance = 0; // attempt to find an element from a straight line from // `relative_el`, by checking whether there's an element at each // point in the `direction` specified while (! direct_el) { // add `jump_distance` to the coordinates we're checking check.x += x * jump_distance; check.y += y * jump_distance; // get the elements at the coordinates we're checking let els_at = document.elementsFromPoint(check.x, check.y); // run through all the elements we found for (let i = 0; i < els_at.length; i++) { // make sure `els_at[i]` isn't `relative_el` and that // its a selectable element if (els_at[i] == relative_el || ! els.includes(els_at[i])) { // not selectable or is `relative_el` continue; } // set `direct_el` direct_el = els_at[i]; // get the bounds of `direct_el` let direct_bounds = direct_el.getBoundingClientRect(); // get the centered coordinates for `direct_el` let direct_coords = { x: direct_bounds.left + (direct_bounds.width / 2), y: direct_bounds.top + (direct_bounds.height / 2) } // update the coordinates on the element itself direct_el.coords = direct_coords; // get the difference between `relative_el` and // `direct_el`'s coordinates, effectively their distance let diff_x = direct_coords.x - relative.x; let diff_y = direct_coords.y - relative.y; // make sure this element is marked as the element that // was found directly direct_el.is_direct_el = true; // update the distance on the element itself direct_el.distance = Math.sqrt( diff_x*diff_x + diff_y*diff_y ) // set the distance on the coord we're checking on the // element itself direct_el.coord_distance = direct_distance; break; // we found the `direct_el` we can stop now } // if `els_at` has `relative_el` then we reset // `direct_distance` if (els_at.includes(relative_el)) { direct_distance = 0; } else { // add `jump_distance` to `direct_distance`, because // we're no longer on the `relative_el` nor the // `direct_el` direct_distance += jump_distance; } // are we beyond the edges of the window if (check.x < 0 || check.y < 0 || check.x > innerWidth || check.y > innerHeight) { // did we find no elements? if (! els_at.length) { break; // stop searching } } } // this contains elements in the respective directions let positions = { up: [], down: [], left: [], right: [] } // gets the nearest elements from the selectable elements for (let i = 0; i < els.length; i++) { // get bounds let el_bounds = els[i].getBoundingClientRect(); // get centered coordinates let el_coords = { x: el_bounds.left + (el_bounds.width / 2), y: el_bounds.top + (el_bounds.height / 2) } // get the difference between `el_coords` and `direct_el`'s // coordinates, effectively their distance let diff_x = el_coords.x - relative.x; let diff_y = el_coords.y - relative.y; // is this element not an element that was previously a // `direct_el`? if (! els[i].is_direct_el) { // update centerd coordinates on the element itself els[i].coords = el_coords; // set the distance on the element itself els[i].distance = Math.sqrt( diff_x*diff_x + diff_y*diff_y ) // get and set the distance on the coord we're checking // on the element itself els[i].coord_distance = Math.abs( relative[coord] - el_coords[coord] ) } else { els[i].is_direct_el = false; continue; } // put `els[i]` in the correct place in `positions` if (el_coords.x < relative.x) { positions.left.push(els[i]); } if (el_coords.x > relative.x) { positions.right.push(els[i]); } if (el_coords.y < relative.y) { positions.up.push(els[i]); } if (el_coords.y > relative.y) { positions.down.push(els[i]); } } // this will contain the element closest to `relative_el` in the // correct direction, but not necessarily at the same // coordinates let closest_el; // set `closest_el` to the elements closest element in the // respective position using `direction` for (let i = 0; i < positions[direction].length; i++) { // get the element let el = positions[direction][i]; // is this the first check, or is it closer than the // previous `closest_el`, then update `closest_el` if (! closest_el || closest_el.distance > el.distance) { closest_el = el; } } // was there found a `closest_el` and `direct_el` if (closest_el && direct_el) { // simply return `direct_el` if its the same as `closest_el` if (closest_el == direct_el) { return direct_el; } // if the parent element of `closest_el` and `direct_el` is // the same, then we prefer the `direct_el` // // unless the parent is `document.body` if (closest_el.parentElement == direct_el.parentElement && direct_el.parentElement !== document.body) { return direct_el; } // get the difference between `relative_el` and `direct_el` // on the coordinate of `direction` let same_coord_diff = Math.abs( direct_el.coords[rev_coord] - relative_el.coords[rev_coord] ) // if the difference is less than 3 then we just return the // `direct_el` as its only a couple pixels off being on the // same coordinate as `relative_el` if (same_coord_diff < 3) { return direct_el; } // get the difference is distance on `direct_el` and // `closest_el` let difference = Math.abs( direct_el.distance - closest_el.distance ) // is the distance les than 50? if (difference < 50) { // get the difference between `direct_el` and // `relative_el` let direct_diff = Math.abs( direct_el.coords[rev_coord] - relative_el.coords[rev_coord] ) // get the difference between `closest_el` and // `relative_el` let closest_diff = Math.abs( closest_el.coords[rev_coord] - relative_el.coords[rev_coord] ) // if the `direct_el` is closer to `relative_el`, return // that, otherwise return `closet_el` if (direct_diff < closest_diff) { return direct_el; } else if (closest_diff < direct_diff) { return closest_el; } } // is `direct_el` closer than `closest_el` in either // `.coord_distance` or `.distance` // // if not just return `closest_el` if (direct_el.coord_distance <= closest_el.coord_distance || direct_el.distance <= closest_el.distance) { // if `direct_el` is closer in `.coord_distance` then // return `direct_el` if (direct_el.coord_distance <= closest_el.coord_distance) { return direct_el; } // if the difference in `.distance` is less than 50, // then return `direct_el` if (difference < 50) { return direct_el; } // if the `.distance` is overall closer on `direct_el` // than `closest_el` then we return `direct_el`, // otherwise we return `closest_el` if (direct_el.distance < closest_el.distance) { return direct_el; } else { return closest_el; } } else { // `direct_el` is unarguably too far away return closest_el; } } else if (! direct_el && ! closest_el) { // do nothing if no element at all was found return false; } // return whichever element we did find return direct_el || closest_el; } // translate `direction` into `get_el()` args switch(direction) { case "up": return get_el(0, -1); case "down": return get_el(0, 1); case "left": return get_el(-1, 0); case "right": return get_el(1, 0); } } // contains a list of the last selections we had before a popup was // opened, letting us go back to those selections when they're closed let last_popup_selections = []; // attempt to reselect the default selection when a popup is either // closed or opened events.on("popup-changed", (e) => { // get the active selection let active_el = document.querySelector(".active-selection"); // make sure there is a selection if (! active_el) { return; } // ignore if `active_el` is a `` let select_el = options[i].querySelector(".actions select"); if (select_el) { // get `