Adds CONTRIBUTING and updates linting

- Adds CONTRIBUTING.md
- Updates eslintrc to be more comprehensive
- Adds linting to travis runs
This commit is contained in:
Zack Rauen 2020-07-25 04:22:57 -04:00
parent f8e3121600
commit 9cc70e0272
38 changed files with 797 additions and 548 deletions

View File

@ -21,30 +21,86 @@
}
},
"rules": {
"no-undef": "error",
"semi": "error",
"space-infix-ops": "error",
"quotes": ["error", "double", {"allowTemplateLiterals": true}],
"no-console": "error",
"no-shadow": ["warn", { "builtinGlobals": false, "hoist": "functions", "allow": [] }],
"no-redeclare": ["error", { "builtinGlobals": true }],
"accessor-pairs": "error",
"block-spacing": ["error", "never"],
"brace-style": ["error", "stroustrup", {"allowSingleLine": true}],
"keyword-spacing": "error",
"no-else-return": "error",
"curly": ["error", "multi-line", "consistent"],
"dot-location": ["error", "property"],
"dot-notation": "error",
"yoda": "error",
// "eqeqeq": ["error", "smart"],
"func-call-spacing": "error",
"handle-callback-err": "error",
"key-spacing": "error",
"keyword-spacing": "error",
"linebreak-style": ["error", "windows"],
"quote-props": ["error", "consistent-as-needed", {"keywords": true}],
"object-curly-spacing": ["error", "never", { "objectsInObjects": false }],
"no-var": "error",
"prefer-const": "error",
"new-cap": ["error", {"newIsCap": true}],
"no-array-constructor": "error",
"no-caller": "error",
"no-console": "error",
"no-duplicate-imports": "error",
"no-else-return": "error",
"no-eval": "error",
"no-floating-decimal": "error",
"no-implied-eval": "error",
"no-iterator": "error",
"no-label-var": "error",
"no-labels": "error",
"no-lone-blocks": "error",
"no-mixed-spaces-and-tabs": "error",
"no-multi-spaces": "error",
"no-multi-str": "error",
"no-new": "error",
"no-new-func": "error",
"no-new-object": "error",
"no-new-wrappers": "error",
"no-octal-escape": "error",
"no-path-concat": "error",
"no-proto": "error",
"no-prototype-builtins": "off",
"react/jsx-uses-react": "error",
"react/jsx-uses-vars": "error",
"no-redeclare": ["error", {"builtinGlobals": true}],
"no-self-compare": "error",
"no-sequences": "error",
"no-shadow": ["warn", {"builtinGlobals": false, "hoist": "functions"}],
"no-tabs": "error",
"no-template-curly-in-string": "error",
"no-throw-literal": "error",
// "no-trailing-spaces": "error",
"no-undef": "error",
"no-undef-init": "error",
"no-unmodified-loop-condition": "error",
"no-unneeded-ternary": "error",
"no-useless-call": "error",
"no-useless-computed-key": "error",
"no-useless-constructor": "error",
"no-useless-rename": "error",
"no-var": "error",
"no-whitespace-before-property": "error",
"object-curly-spacing": ["error", "never", {"objectsInObjects": false}],
"object-property-newline": ["error", {"allowAllPropertiesOnSameLine": true}],
"operator-linebreak": ["error", "none", {"overrides": {"?": "before", ":": "before"}}],
"prefer-const": "error",
"quote-props": ["error", "consistent-as-needed", {"keywords": true}],
"quotes": ["error", "double", {"allowTemplateLiterals": true}],
"rest-spread-spacing": "error",
"semi": "error",
"semi-spacing": "error",
"space-before-blocks": "error",
"space-in-parens": "error",
"space-infix-ops": "error",
"space-unary-ops": ["error", {"words": true, "nonwords": false, "overrides": {"typeof": false}}],
"spaced-comment": ["error", "always", {"exceptions": ["-", "*"]}],
"template-curly-spacing": "error",
"wrap-iife": ["error", "inside"],
"yield-star-spacing": "error",
"yoda": "error",
"react/display-name": "off",
"react/prop-types": "off",
"react/jsx-key": "off",
"react/jsx-no-target-blank": "error",
"react/jsx-key": "off"
"react/jsx-uses-react": "error",
"react/jsx-uses-vars": "error"
},
"globals": {
"webpackJsonp": "readonly",

View File

@ -13,6 +13,7 @@ install:
script:
- npm run build-all
- npm run test
- npm run lint
deploy:
provider: pages

211
CONTRIBUTING.md Normal file
View File

@ -0,0 +1,211 @@
# Contributing to BetterDiscord
Thanks for taking the time to contribute!
The following is a set of guidelines for contributing to BetterDiscord. These are mostly guidelines, not rules. Use your best judgment, and feel free to propose changes to this document in a pull request. These guidelines have been adapted from [Atom](https://github.com/atom/atom/blob/master/CONTRIBUTING.md).
#### Table Of Contents
[Code of Conduct](#code-of-conduct)
[What should I know before I get started?](#what-should-i-know-before-i-get-started)
* [BetterDiscord Architecture](#betterdiscord-architecture)
[How Can I Contribute?](#how-can-i-contribute)
* [Reporting Bugs](#reporting-bugs)
* [Suggesting Enhancements](#suggesting-enhancements)
* [Your First Code Contribution](#your-first-code-contribution)
* [Pull Requests](#pull-requests)
[Styleguides](#styleguides)
* [Git Commit Messages](#git-commit-messages)
* [JavaScript Styleguide](#javascript-styleguide)
* [CSS Styleguide](#css-styleguide)
[Additional Notes](#additional-notes)
* [Issue Labels](#issue-labels)
## Code of Conduct
This project and everyone participating in it is governed by the [Code of Conduct from the Contributor Covenant](https://www.contributor-covenant.org/version/1/4/code-of-conduct.html). By participating, you are expected to uphold this code. Please report unacceptable behavior.
## What should I know before I get started?
### BetterDiscord Architecture
BetterDiscord is currently broken up into two main pieces--the local injector, and the remote application.
#### Injector
The injector is the piece that runs on the user's computer, and the piece added by the [installer](https://github.com/rauenzi/BBDInstaller). The main job of this package is to inject into Discord and load the remote package. The injector and its code lives on the [injector branch](https://github.com/rauenzi/BetterDiscordApp/tree/injector).
#### Remote Application
This is the main payload of BetterDiscord. This is what gets linked remotely by the [injector](#injector). This portion is where most of the user interaction and development will be. This module is responsible for loading plugins and themes, as well as handling settings, emotes and more.
## How Can I Contribute?
### Reporting Bugs
This section guides you through submitting a bug report for BetterDiscord. Following these guidelines helps maintainers and the community understand your report, reproduce the behavior, and find related reports.
Before creating bug reports, please check [this list](#before-submitting-a-bug-report) as you might find out that you don't need to create one. When you are creating a bug report, please [include as many details as possible](#how-do-i-submit-a-good-bug-report). Fill out [the required template](https://github.com/rauenzi/BetterDiscordApp/blob/master/.github/ISSUE_TEMPLATE/bug-report.md), the information it asks for helps us resolve issues faster.
> **Note:** If you find a **Closed** issue that seems like it is the same thing that you're experiencing, open a new issue and include a link to the original issue in the body of your new one.
#### Before Submitting A Bug Report
* **Try [repairing your installation](https://github.com/rauenzi/BetterDiscordApp#installation).** This can often fix issues where Discord has overwritten the injector or corrupted data files.
* **Check the [#faq channel](https://discord.gg/2HScm8j)** on our support server for answers to many questions. Also check the **#announcements** channel for any recent announcements about breaking changes.
* **Perform a [search](https://github.com/rauenzi/BetterDiscordApp/issues)** to see if the problem has already been reported. If it has **and the issue is still open**, add a :+1: to the existing issue instead of opening a new one.
#### How Do I Submit A (Good) Bug Report?
Bugs are tracked as [GitHub issues](https://guides.github.com/features/issues/). After you've determined this is a new bug using the steps from above, create an issue and provide the following information by filling in [the template](https://github.com/rauenzi/BetterDiscordApp/blob/master/.github/ISSUE_TEMPLATE/bug-report.md).
Explain the problem and include additional details to help maintainers reproduce the problem:
* **Use a clear and descriptive title** for the issue to identify the problem.
* **Describe the exact steps which reproduce the problem** in as many details as possible. For example, start by explaining how you started Discord, e.g. which addons exactly you used, and what actions were taken. When listing steps, **don't just say what you did, but explain how you did it**. For example, if you opened a menu, explain if you used the mouse, or a keyboard shortcut or something else entirely.
* **Provide specific examples to demonstrate the steps**. Include links to files or GitHub projects, or copy/pasteable snippets, which you use in those examples. If you're providing snippets in the issue, use [Markdown code blocks](https://help.github.com/articles/markdown-basics/#multiple-lines).
* **Describe the behavior you observed after following the steps** and point out what exactly is the problem with that behavior.
* **Explain which behavior you expected to see instead and why.**
* **Include screenshots and animated GIFs** which show you following the described steps and clearly demonstrate the problem.
* **If you're reporting that Discord/BetterDiscord crashed**, include a crash report with a stack trace from the console. To open the [console](https://developers.google.com/web/tools/chrome-devtools/) press `ctrl`+`shift`+`i` and click the `console` tab at the top. You should see red errors toward the bottom of this page. Include the crash report in the issue in a [code block](https://help.github.com/articles/markdown-basics/#multiple-lines), a [file attachment](https://help.github.com/articles/file-attachments-on-issues-and-pull-requests/), a [gist](https://gist.github.com/) (and provide link to that gist), or even a screenshot of the error.
* **If the problem wasn't triggered by a specific action**, describe what you were doing before the problem happened and share more information using the guidelines below.
Provide more context by answering these questions:
* **Did the problem start happening recently** (e.g. after updating to a new version of Discord/BetterDiscord) or was this always a problem?
* If the problem started happening recently, what's the version and release channel as well as the versions of BetterDiscord?
* **Can you reliably reproduce the issue?** If not, provide details about how often the problem happens and under which conditions it normally happens.
Include details about your configuration and environment:
* **Which version and release channel of Discord are you using?** The version looks something like `0.0.306` and the release channels are stable, canary, and ptb.
* **What's the name and version of the OS you're using**? Ideally there are no cross-compatibility issues, but it does happen.
* **Which plugins/themes do you have installed?** You can provide a list or screenshot of the folder.
### Suggesting Enhancements
This section guides you through submitting an enhancement suggestion for BetterDiscord, including completely new features and minor improvements to existing functionality. Following these guidelines helps maintainers and the community understand your suggestion and find related suggestions.
Before creating enhancement suggestions, please check [this list](#before-submitting-an-enhancement-suggestion) as you might find out that you don't need to create one. When you are creating an enhancement suggestion, please [include as many details as possible](#how-do-i-submit-a-good-enhancement-suggestion). Fill in [the template](https://github.com/rauenzi/BetterDiscordApp/blob/master/.github/ISSUE_TEMPLATE/feature_request.md), including the steps that you imagine you would take if the feature you're requesting existed.
#### Before Submitting An Enhancement Suggestion
* **Check if there's already a plugin which provides that enhancement.**
* **Perform a [cursory search](https://guides.github.com/features/issues/)** to see if the enhancement has already been suggested. If it has, add a :+1: to the existing issue instead of opening a new one.
#### How Do I Submit A (Good) Enhancement Suggestion?
Enhancement suggestions are tracked as [GitHub issues](https://guides.github.com/features/issues/). After you've determined this is a new suggestion using the steps from above, create an issue and provide the following information:
* **Use a clear and descriptive title** for the issue to identify the suggestion.
* **Provide a step-by-step description of the suggested enhancement** in as many details as possible.
* **Provide specific examples to demonstrate the steps**. Include copy/pasteable snippets which you use in those examples, as [Markdown code blocks](https://help.github.com/articles/markdown-basics/#multiple-lines).
* **Describe the current behavior** and **explain which behavior you expected to see instead** and why.
* **Include screenshots and animated GIFs** which help you demonstrate the steps or point out the part of BetterDiscord which the suggestion is related to.
* **Explain why this enhancement would be useful** to most BetterDiscord users and isn't something that can or should be implemented as a plugin.
### Your First Code Contribution
Unsure where to begin contributing? You can start by looking through `help-wanted` issues or any issues labelled `can't reproduce`.
#### Local development
BetterDiscord and the injector can be developed locally. First, clone the repo and run `npm install && npm run build-all` and locate the `dist` folder. Next you'll need to setup the injector to use your local files. In order to do this, you'll need to locate your local injector installation. Relative to your `Discord.exe` it would be in `./resources/app`. Modify the `./resources/app/betterdiscord/config.json` file and set `localPath` to the **absolute** path of your `dist` folder from before. Then for this to take effect, you'll need to fully restart Discord. Any future modifications to the remote app (`dist` folder) will be picked up on Discord reload.
### Pull Requests
Please follow these steps to have your contribution considered by the maintainers:
1. Use a pull request template, if one exists.
2. Follow the [styleguides](#styleguides)
3. After you submit your pull request, verify that all [status checks](https://help.github.com/articles/about-status-checks/) are passing <details><summary>What if the status checks are failing?</summary>If a status check is failing, and you believe that the failure is unrelated to your change, please leave a comment on the pull request explaining why you believe the failure is unrelated. A maintainer will re-run the status check for you. If we conclude that the failure was a false positive, then we will open an issue to track that problem with our status check suite.</details>
While the prerequisites above must be satisfied prior to having your pull request reviewed, the reviewer(s) may ask you to complete additional design work, tests, or other changes before your pull request can be ultimately accepted.
## Styleguides
### Git Commit Messages
* Use the present tense ("Add feature" not "Added feature")
* Use the imperative mood ("Move cursor to..." not "Moves cursor to...")
* Limit the first line to 72 characters or less
* Reference issues and pull requests liberally after the first line
* When only changing documentation, include `[ci skip]` in the commit title
### JavaScript Styleguide
All JavaScript must adhere to the [ESLint rules](https://github.com/rauenzi/BetterDiscordApp/blob/master/.eslintrc) of the repo.
Some other style related points not covered by ESLint:
* Use verbose variable names
* Prefer to use react patches over DOM manipulation when possible
* Prefer to use separate components from Discord when possible
* Inline `export`s with expressions whenever possible
```js
// Use this:
export default class ClassName {
}
// Instead of:
class ClassName {
}
export default ClassName
```
* Place class properties in the following order:
* Class methods and properties (methods starting with `static`)
* Instance methods and properties
* Place requires in the following order:
* Built in Node Modules (such as `path`)
* Repo level global imports (such as `modules`, `builtins`)
* Local Modules (using relative paths)
* Prefer to import whole modules instead of singular functions
* Keep modules namespaced and organized
* This includes Node Modules (such as `fs`)
```js
const fs = require("fs"); // Use this
const {readFile, writeFile} = require("fs"); // Avoid this
import Utilities from "./utilities"; // Use this
import {deepclone, isEmpty} from "./utilties"; // Avoid this
```
### CSS Styleguide
All CSS must adhere to the [Stylelint rules](https://github.com/rauenzi/BetterDiscordApp/blob/development/.stylelintrc) of the repo.
Some other style related points not covered by ESLint:
* Use verbose class names where applicable
* Keep css files modular
* Avoid conflicts with Discord's classes
## Additional Notes
### Issue Labels
This section lists the labels we use to help us track and manage issues. Please open an issue if you have suggestions for new labels.
[GitHub search](https://help.github.com/articles/searching-issues/) makes it easy to use labels for finding groups of issues or pull requests you're interested in. For example, you might be interested in [bugs that have not been able to be reproduced](https://github.com/rauenzi/BetterDiscordApp/issues?q=is%3Aopen+label%3A%22can%27t+reproduce%22+label%3A%22bug%22). To help you find issues, each label is listed with search links for finding open items with that label. We encourage you to read about [other search filters](https://help.github.com/articles/searching-issues/) which will help you write more focused queries.
#### Type of Issue and Issue State
| Label name | Description | View All |
| --- | --- | --- |
| `awaiting response` | Waiting for a response from the user, issues with this tag are prone to pruning. | [View All](https://github.com/rauenzi/BetterDiscordApp/labels/bug) |
| `bug` | Issue related to a bug report, may or may not be yet confirmed. | [View All](https://github.com/rauenzi/BetterDiscordApp/labels/awaiting%20response) |
| `can't fix` | Issues which are invalid or are a limitation of something else like Electron. | [View All](https://github.com/rauenzi/BetterDiscordApp/labels/can%27t%20fix) |
| `can't reproduce` | Reported bugs that could not be confirmed, help welcome. | [View All](https://github.com/rauenzi/BetterDiscordApp/labels/can%27t%20reproduce) |
| `confirmed` | Confirmed bugs to be actively worked. | [View All](https://github.com/rauenzi/BetterDiscordApp/labels/confirmed) |
| `duplicate` | Issues which are duplicates of other issues, i.e. they have been reported before. | [View All](https://github.com/rauenzi/BetterDiscordApp/labels/duplicate) |
| `enhancement` | Feature or improvement suggestion. | [View All](https://github.com/rauenzi/BetterDiscordApp/labels/enhancement) |
| `help wanted` | Help from the community appreciated. | [View All](https://github.com/rauenzi/BetterDiscordApp/labels/help%20wanted) |
| `needs info` | Issue did not supply enough information to take action on. | [View All](https://github.com/rauenzi/BetterDiscordApp/labels/needs%20info) |
| `question` | Questions more than bug reports or feature requests (e.g. how do I do X). | [View All](https://github.com/rauenzi/BetterDiscordApp/labels/question) |
| `wontfix` | Decision has been made not to fix these issues at least for now. | [View All](https://github.com/rauenzi/BetterDiscordApp/labels/wontfix) |

View File

@ -18,7 +18,7 @@ export default new class ColoredText extends Builtin {
injectColoredText() {
this.after(MessageContent.prototype, "render", (thisObject, args, retVal) => {
this.after(retVal.props, "children", {silent: true, after: ({returnValue}) => {
this.after(retVal.props, "children", {after: ({returnValue}) => {
const markup = returnValue.props.children[1];
const roleColor = thisObject.props.message.colorString;
if (markup && roleColor) markup.props.style = {color: roleColor};

View File

@ -71,7 +71,6 @@ export default new class DeveloperMode extends Builtin {
}
getRules(element, css = element.ownerDocument.styleSheets) {
//if (window.getMatchedCSSRules) return window.getMatchedCSSRules(element);
const sheets = [...css].filter(s => !s.href || !s.href.includes("BetterDiscordApp"));
const rules = sheets.map(s => [...(s.cssRules || [])]).flat();
const elementRules = rules.filter(r => r && r.selectorText && element.matches(r.selectorText) && r.style.length && r.selectorText.split(", ").length < 8 && !r.selectorText.split(", ").includes("*"));

View File

@ -14,7 +14,7 @@ export default new class DeveloperMode extends Builtin {
}
debugListener(e) {
if (e.which === 119 || e.which == 118) { //F8
if (e.which === 119 || e.which == 118) { // F8
debugger; // eslint-disable-line no-debugger
e.preventDefault();
e.stopImmediatePropagation();

View File

@ -1,6 +1,7 @@
import Builtin from "../../structs/builtin";
import {Utilities, WebpackModules, React} from "modules";
import Tabs from "./tabs";
const EmojiPicker = WebpackModules.find(m => m.type && m.type.displayName == "ExpressionPicker");
export default new class EmoteMenu extends Builtin {
get name() {return "EmoteMenu";}
@ -10,36 +11,34 @@ export default new class EmoteMenu extends Builtin {
get hideEmojisID() {return "hideEmojiMenu";}
get hideEmojis() {return this.get(this.hideEmojisID);}
constructor() {
super();
}
enabled() {
this.before(EmojiPicker, "type", (_, [args], ret) => {
if(args.expressionPickerView == "emoji" && this.hideEmojis) args.expressionPickerView = "gif";
this.before(EmojiPicker, "type", (_, [props]) => {
if (props.expressionPickerView == "emoji" && this.hideEmojis) props.expressionPickerView = "gif";
});
this.after(EmojiPicker, "type", (_, [args], ret) => {
const head = Utilities.getNestedProp(ret, "props.children.props.children.1.props.children.0.props.children.props.children");
const body = Utilities.getNestedProp(ret, "props.children.props.children.1.props.children");
if(!head || !body) return ret;
const selected = args.expressionPickerView;
this.after(EmojiPicker, "type", (_, [props], returnValue) => {
const head = Utilities.getNestedProp(returnValue, "props.children.props.children.1.props.children.0.props.children.props.children");
const body = Utilities.getNestedProp(returnValue, "props.children.props.children.1.props.children");
if (!head || !body) return returnValue;
const selected = props.expressionPickerView;
const currentTab = Tabs.find(e => e.id === selected);
let tabProps = head[0].props;
head.push(
const tabProps = head[0].props;
head.push(
...Tabs.map(e => React.createElement("div", {
id: e.id+"-tab",
role: "tab",
"id": e.id + "-tab",
"role": "tab",
"aria-selected": selected == e.id,
className: tabProps.className,
"className": tabProps.className,
}, React.createElement(tabProps.children.type, {
viewType: e.id,
isActive: selected == e.id,
setActiveView: tabProps.children.props.setActiveView
}, e.label))
));
if(currentTab) body[2] = currentTab.element();
if(this.hideEmojis) head.splice(head.findIndex(e=>e.props.id == "emoji-picker-tab"), 1);
})
}
if (currentTab) body[2] = currentTab.element();
if (this.hideEmojis) head.splice(head.findIndex(e=>e.props.id == "emoji-picker-tab"), 1);
});
}
disabled() {
this.unpatchAll();

View File

@ -196,7 +196,7 @@ export default new class EmoteModule extends Builtin {
const etag = DataStore.getCacheHash("emotes", category);
if (!etag) return resolve(false);
request.head({url: this.getRemoteFile(category), headers: {"If-None-Match": etag}}, (err, resp) => {
resolve(resp.statusCode == 304);
resolve(!err && resp.statusCode == 304);
});
});
}

View File

@ -22,4 +22,4 @@ export default [
return React.createElement(EmoteIcon, {emote, url});
}))
}
]
];

View File

@ -1,45 +0,0 @@
export default {
"Custom css live update": {id: "bda-css-0", info: "", implemented: true, hidden: true, cat: "core"},
"Custom css auto udpate": {id: "bda-css-1", info: "", implemented: true, hidden: true, cat: "core"},
"BetterDiscord Blue": {id: "bda-gs-b", info: "Replace Discord blue with BD Blue", implemented: false, hidden: false, cat: "core"},
/* Core */
/* ====== */
"Public Servers": {id: "bda-gs-1", info: "Display public servers button", implemented: true, hidden: false, cat: "core", category: "modules"},
"Minimal Mode": {id: "bda-gs-2", info: "Hide elements and reduce the size of elements.", implemented: true, hidden: false, cat: "core", category: "modules"},
"Voice Mode": {id: "bda-gs-4", info: "Only show voice chat", implemented: true, hidden: false, cat: "core", category: "modules"},
"Hide Channels": {id: "bda-gs-3", info: "Hide channels in minimal mode", implemented: true, hidden: false, cat: "core", category: "modules"},
"Dark Mode": {id: "bda-gs-5", info: "Make certain elements dark by default(wip)", implemented: true, hidden: false, cat: "core", category: "modules"},
"Voice Disconnect": {id: "bda-dc-0", info: "Disconnect from voice server when closing Discord", implemented: true, hidden: false, cat: "core", category: "modules"},
"24 Hour Timestamps": {id: "bda-gs-6", info: "Replace 12hr timestamps with proper ones", implemented: true, hidden: false, cat: "core", category: "modules"},
"Coloured Text": {id: "bda-gs-7", info: "Make text colour the same as role colour", implemented: true, hidden: false, cat: "core", category: "modules"},
"Normalize Classes": {id: "fork-ps-4", info: "Adds stable classes to elements to help themes. (e.g. adds .da-channels to .channels-Ie2l6A)", implemented: true, hidden: false, cat: "core", category: "modules"},
/* Content */
"Content Error Modal": {id: "fork-ps-1", info: "Shows a modal with plugin/theme errors", implemented: true, hidden: false, cat: "core", category: "content manager"},
"Show Toasts": {id: "fork-ps-2", info: "Shows a small notification for important information", implemented: true, hidden: false, cat: "core", category: "content manager"},
"Scroll To Settings": {id: "fork-ps-3", info: "Auto-scrolls to a plugin's settings when the button is clicked (only if out of view)", implemented: true, hidden: false, cat: "core", category: "content manager"},
"Automatic Loading": {id: "fork-ps-5", info: "Automatically loads, reloads, and unloads plugins and themes", implemented: true, hidden: false, cat: "core", category: "content manager"},
/* Developer */
"Developer Mode": {id: "bda-gs-8", info: "Developer Mode", implemented: true, hidden: false, cat: "core", category: "developer settings"},
"Copy Selector": {id: "fork-dm-1", info: "Adds a \"Copy Selector\" option to context menus when developer mode is active", implemented: true, hidden: false, cat: "core", category: "developer settings"},
/* Window Prefs */
"Enable Transparency": {id: "fork-wp-1", info: "Enables the main window to be see-through (requires restart)", implemented: true, hidden: false, cat: "core", category: "window preferences"},
"Window Frame": {id: "fork-wp-2", info: "Adds the native os window frame to the main window", implemented: false, hidden: true, cat: "core", category: "window preferences"},
/* Emotes */
/* ====== */
"Download Emotes": {id: "fork-es-3", info: "Download emotes when the cache is expired", implemented: true, hidden: false, cat: "emote"},
"Twitch Emotes": {id: "bda-es-7", info: "Show Twitch emotes", implemented: true, hidden: false, cat: "emote"},
"FrankerFaceZ Emotes": {id: "bda-es-1", info: "Show FrankerFaceZ Emotes", implemented: true, hidden: false, cat: "emote"},
"BetterTTV Emotes": {id: "bda-es-2", info: "Show BetterTTV Emotes", implemented: true, hidden: false, cat: "emote"},
"Emote Menu": {id: "bda-es-0", info: "Show Twitch/Favourite emotes in emote menu", implemented: true, hidden: false, cat: "emote"},
"Emoji Menu": {id: "bda-es-9", info: "Show Discord emoji menu", implemented: true, hidden: false, cat: "emote"},
"Emote Auto Capitalization": {id: "bda-es-4", info: "Autocapitalize emote commands", implemented: true, hidden: false, cat: "emote"},
"Show Names": {id: "bda-es-6", info: "Show emote names on hover", implemented: true, hidden: false, cat: "emote"},
"Show emote modifiers": {id: "bda-es-8", info: "Enable emote mods (flip, spin, pulse, spin2, spin3, 1spin, 2spin, 3spin, tr, bl, br, shake, shake2, shake3, flap)", implemented: true, hidden: false, cat: "emote"},
"Animate On Hover": {id: "fork-es-2", info: "Only animate the emote modifiers on hover", implemented: true, hidden: false, cat: "emote"}
};

View File

@ -11,4 +11,4 @@ window.BdApi = BdApi;
// Add loading icon at the bottom right
LoadingIcon.show();
new BetterDiscord();
new BetterDiscord(); // eslint-disable-line no-new

View File

@ -98,7 +98,7 @@ export default new class ComponentPatcher {
const guildComponents = WebpackModules.getByProps("renderListItem");
if (!guildComponents || !Guilds) return;
const GuildSeparator = function() {
const returnValue = guildComponents.Separator(...arguments);
const returnValue = guildComponents.Separator(...arguments); // eslint-disable-line new-cap
returnValue.props.className += " bd-guild-separator";
return returnValue;
};

View File

@ -5,8 +5,6 @@ import LocaleManager from "./localemanager";
import Logger from "./logger";
import {Config, Changelog} from "data";
// import EmoteModule from "./emotes";
// import QuickEmoteMenu from "../builtins/emotemenu";
import DOMManager from "./dommanager";
import PluginManager from "./pluginmanager";
import ThemeManager from "./thememanager";
@ -20,7 +18,6 @@ import ComponentPatcher from "./componentpatcher";
import Strings from "./strings";
import LoadingIcon from "../loadingicon";
import Utilities from "./utilities";
import { DOM } from "modules";
const {ipcRenderer} = require("electron");
const GuildClasses = DiscordModules.GuildClasses;
@ -80,7 +77,7 @@ export default class Core {
confirmText: Strings.Startup.updateNow,
cancelText: Strings.Startup.maybeLater,
onConfirm: async () => {
const onUpdateFailed = () => { Modals.alert(Strings.Startup.updateFailed, Strings.Startup.manualUpdate); };
const onUpdateFailed = () => {Modals.alert(Strings.Startup.updateFailed, Strings.Startup.manualUpdate);};
try {
const didUpdate = await this.updateInjector();
if (!didUpdate) return onUpdateFailed();
@ -155,21 +152,21 @@ export default class Core {
}
const url = Utilities.formatString((Config.local && data.local != null) ? data.local : data.url, {repo: Config.repo, hash: Config.hash, localServer: Config.localServer});
Logger.log(`Startup`, `Loading Resource (${url})`);
const injector = (data.type == "script" ? DOMManager.injectScript : DOMManager.linkStyle).bind(DOMManager);
try {
await injector(data.name, url);
}
catch (err) {
const backup = Utilities.formatString(data.backup, {minified: Config.minified ? ".min" : ""});
Logger.stacktrace(`Startup`, `Could not load ${url}. Using backup ${backup}`, err);
try {
await injector(data.name, backup);
}
catch (e) {
const injector = (data.type == "script" ? DOMManager.injectScript : DOMManager.linkStyle).bind(DOMManager);
try {
await injector(data.name, url);
}
catch (err) {
const backup = Utilities.formatString(data.backup, {minified: Config.minified ? ".min" : ""});
Logger.stacktrace(`Startup`, `Could not load ${url}. Using backup ${backup}`, err);
try {
await injector(data.name, backup);
}
catch (e) {
Logger.stacktrace(`Startup`, `Could not load ${url}. Using backup ${backup}`, err);
if (data.name === "jquery") Modals.alert(Strings.Startup.jqueryFailed, Strings.Startup.jqueryFailedDetails);
}
}
if (data.name === "jquery") Modals.alert(Strings.Startup.jqueryFailed, Strings.Startup.jqueryFailedDetails);
}
}
}
}
@ -177,8 +174,9 @@ export default class Core {
const injectionPath = DataStore.injectionPath;
if (!injectionPath) return false;
const fs = require("fs");
const path = require("path");
// Currently in module scope
// const fs = require("fs");
// const path = require("path");
const rmrf = require("rimraf");
const yauzl = require("yauzl");
const mkdirp = require("mkdirp");
@ -210,7 +208,10 @@ export default class Core {
if (alreadyExists) await new Promise(res => fs.rename(extractedFolder, `${extractedFolder}.bak${Math.round(performance.now())}`, res));
// Unzip the downloaded zip file
const zipfile = await new Promise(r => yauzl.open(savedZip, {lazyEntries: true}, (err, zip) => r(zip)));
const zipfile = await new Promise((r, rej) => yauzl.open(savedZip, {lazyEntries: true}, (err, zip) => {
if (err) return rej(err);
r(zip);
}));
zipfile.on("entry", function (entry) {
// Skip directories, they are handled with mkdirp
if (entry.fileName.endsWith("/")) return zipfile.readEntry();
@ -221,7 +222,7 @@ export default class Core {
mkdirp.sync(path.dirname(fullPath));
zipfile.openReadStream(entry, function (err, readStream) {
if (err) return success = false;
readStream.on("end", function () { zipfile.readEntry(); }); // Go to next file after this
readStream.on("end", function () {zipfile.readEntry();}); // Go to next file after this
readStream.pipe(fs.createWriteStream(fullPath));
});
});

View File

@ -44,48 +44,48 @@ export default class DOMTools {
}
/**
* Adds a style to the document.
* @param {string} id - identifier to use as the element id
* @param {string} css - css to add to the document
*/
static addStyle(id, css) {
document.head.append(DOMTools.createElement(`<style id="${id}">${css}</style>`));
}
* Adds a style to the document.
* @param {string} id - identifier to use as the element id
* @param {string} css - css to add to the document
*/
static addStyle(id, css) {
document.head.append(DOMTools.createElement(`<style id="${id}">${css}</style>`));
}
/**
* Removes a style from the document.
* @param {string} id - original identifier used
*/
static removeStyle(id) {
const element = document.getElementById(id);
if (element) element.remove();
}
/**
* Removes a style from the document.
* @param {string} id - original identifier used
*/
static removeStyle(id) {
const element = document.getElementById(id);
if (element) element.remove();
}
/**
* Adds/requires a remote script to be loaded
* @param {string} id - identifier to use for this script
* @param {string} url - url from which to load the script
* @returns {Promise} promise that resolves when the script is loaded
*/
static addScript(id, url) {
return new Promise(resolve => {
const script = document.createElement("script");
script.id = id;
script.src = url;
script.type = "text/javascript";
script.onload = resolve;
document.head.append(script);
});
}
/**
* Adds/requires a remote script to be loaded
* @param {string} id - identifier to use for this script
* @param {string} url - url from which to load the script
* @returns {Promise} promise that resolves when the script is loaded
*/
static addScript(id, url) {
return new Promise(resolve => {
const script = document.createElement("script");
script.id = id;
script.src = url;
script.type = "text/javascript";
script.onload = resolve;
document.head.append(script);
});
}
/**
* Removes a remote script from the document.
* @param {string} id - original identifier used
*/
static removeScript(id) {
/**
* Removes a remote script from the document.
* @param {string} id - original identifier used
*/
static removeScript(id) {
id = this.escapeID(id);
const element = document.getElementById(id);
if (element) element.remove();
const element = document.getElementById(id);
if (element) element.remove();
}
// https://javascript.info/js-animation
@ -546,7 +546,7 @@ export default class DOMTools {
return element.getBoundingClientRect();
}
static get listeners() { return this._listeners || (this._listeners = {}); }
static get listeners() {return this._listeners || (this._listeners = {});}
/**
* This is similar to jQuery's `on` function and can *hopefully* be used in the same way.
@ -647,7 +647,10 @@ export default class DOMTools {
static __offAll(event, element) {
const [type, namespace] = event.split(".");
let matchFilter = listener => listener.event == type, defaultFilter = _ => _;
if (element) matchFilter = l => l.event == type && l.element == element, defaultFilter = l => l.element == element;
if (element) {
matchFilter = l => l.event == type && l.element == element;
defaultFilter = l => l.element == element;
}
const listeners = this.listeners[namespace] || [];
const list = type ? listeners.filter(matchFilter) : listeners.filter(defaultFilter);
for (let c = 0; c < list.length; c++) list[c].cancel();
@ -721,16 +724,16 @@ export default class DOMTools {
}
/** Shorthand for {@link module:DOMTools.onMountChange} with third parameter `true` */
static onMount(node, callback) { return this.onMountChange(node, callback); }
static onMount(node, callback) {return this.onMountChange(node, callback);}
/** Shorthand for {@link module:DOMTools.onMountChange} with third parameter `false` */
static onUnmount(node, callback) { return this.onMountChange(node, callback, false); }
static onUnmount(node, callback) {return this.onMountChange(node, callback, false);}
/** Alias for {@link module:DOMTools.onMount} */
static onAdded(node, callback) { return this.onMount(node, callback); }
static onAdded(node, callback) {return this.onMount(node, callback);}
/** Alias for {@link module:DOMTools.onUnmount} */
static onRemoved(node, callback) { return this.onUnmount(node, callback, false); }
static onRemoved(node, callback) {return this.onUnmount(node, callback, false);}
/**
* Helper function which combines multiple elements into one parent element

View File

@ -8,58 +8,58 @@ const request = require("request");
const {Dispatcher, DiscordConstants, UserSettingsStore} = DiscordModules;
export default new class LocaleManager {
get discordLocale() {return UserSettingsStore.locale.split("-")[0];}
get defaultLocale() {return "en";}
get discordLocale() {return UserSettingsStore.locale.split("-")[0];}
get defaultLocale() {return "en";}
constructor() {
constructor() {
this.locale = "";
this.strings = {};
}
}
async initialize() {
async initialize() {
await this.setLocale(this.discordLocale);
Dispatcher.subscribe(DiscordConstants.ActionTypes.USER_SETTINGS_UPDATE, ({settings}) => {
const newLocale = settings.locale;
if (newLocale && newLocale != this.locale) this.setLocale(newLocale.split("-")[0]);
});
}
}
async setLocale(newLocale) {
async setLocale(newLocale) {
let newStrings;
if (newLocale != this.defaultLocale) {
newStrings = await this.getLocaleStrings(newLocale);
newStrings = await this.getLocaleStrings(newLocale);
if (!newStrings) return this.setLocale(this.defaultLocale);
}
else {
newStrings = DefaultStrings;
}
this.locale = newLocale;
Utilities.extend(this.strings, newStrings);
Events.emit("strings-updated");
}
this.locale = newLocale;
Utilities.extend(this.strings, newStrings);
Events.emit("strings-updated");
}
async getLocaleStrings(locale) {
const hash = DataStore.getCacheHash("locales", locale);
if (!hash) return await this.downloadLocale(locale);
const invalid = await this.downloadLocale(locale, hash);
if (!invalid) return DataStore.getLocale(locale);
return invalid;
}
async getLocaleStrings(locale) {
const hash = DataStore.getCacheHash("locales", locale);
if (!hash) return await this.downloadLocale(locale);
const invalid = await this.downloadLocale(locale, hash);
if (!invalid) return DataStore.getLocale(locale);
return invalid;
}
downloadLocale(locale, hash = "") {
return new Promise(resolve => {
const options = {
url: Utilities.repoUrl(`assets/locales/${locale}.json`),
timeout: 2000,
json: true
};
if (hash) options.headers = {"If-None-Match": hash};
request.get(options, (err, resp, newStrings) => {
if (err || resp.statusCode !== 200) return resolve(null);
DataStore.saveLocale(locale, newStrings);
DataStore.setCacheHash("locales", locale, resp.headers.etag);
resolve(newStrings);
});
});
}
downloadLocale(locale, hash = "") {
return new Promise(resolve => {
const options = {
url: Utilities.repoUrl(`assets/locales/${locale}.json`),
timeout: 2000,
json: true
};
if (hash) options.headers = {"If-None-Match": hash};
request.get(options, (err, resp, newStrings) => {
if (err || resp.statusCode !== 200) return resolve(null);
DataStore.saveLocale(locale, newStrings);
DataStore.setCacheHash("locales", locale, resp.headers.etag);
resolve(newStrings);
});
});
}
};

View File

@ -29,10 +29,10 @@ export default class Logger {
*
* @param {string} module - Name of the calling module.
* @param {string} message - Message or error to have logged.
* @param {Error} error - Error object to log with the message.
* @param {Error} error - Error object to log with the message.
*/
static stacktrace(module, message, error) {
console.error(`%c[${module}]%c ${message}\n\n%c`, "color: #3a71c1; font-weight: 700;", "color: red; font-weight: 700;", "color: red;", error);
console.error(`%c[${module}]%c ${message}\n\n%c`, "color: #3a71c1; font-weight: 700;", "color: red; font-weight: 700;", "color: red;", error);
}
/**
@ -41,7 +41,7 @@ export default class Logger {
* @param {string} module - Name of the calling module.
* @param {string} message - Messages to have logged.
*/
static err(module, ...message) { Logger._log(module, message, "error"); }
static err(module, ...message) {Logger._log(module, message, "error");}
/**
* Logs a warning message.
@ -49,7 +49,7 @@ export default class Logger {
* @param {string} module - Name of the calling module.
* @param {...any} message - Messages to have logged.
*/
static warn(module, ...message) { Logger._log(module, message, "warn"); }
static warn(module, ...message) {Logger._log(module, message, "warn");}
/**
* Logs an informational message.
@ -57,7 +57,7 @@ export default class Logger {
* @param {string} module - Name of the calling module.
* @param {...any} message - Messages to have logged.
*/
static info(module, ...message) { Logger._log(module, message, "info"); }
static info(module, ...message) {Logger._log(module, message, "info");}
/**
* Logs used for debugging purposes.
@ -65,7 +65,7 @@ export default class Logger {
* @param {string} module - Name of the calling module.
* @param {...any} message - Messages to have logged.
*/
static debug(module, ...message) { Logger._log(module, message, "debug"); }
static debug(module, ...message) {Logger._log(module, message, "debug");}
/**
* Logs used for basic loggin.
@ -73,7 +73,7 @@ export default class Logger {
* @param {string} module - Name of the calling module.
* @param {...any} message - Messages to have logged.
*/
static log(module, ...message) { Logger._log(module, message); }
static log(module, ...message) {Logger._log(module, message);}
/**
* Logs strings using different console levels and a module label.
@ -86,7 +86,6 @@ export default class Logger {
type = Logger.parseType(type);
if (!Array.isArray(message)) message = [message];
console[type](`%c[BandagedBD]%c [${module}]%c`, "color: #3E82E5; font-weight: 700;", "color: #3a71c1;", "", ...message);
//console.log(`%c[BandagedBD]%c [${moduleName}]%c ${message}`, "color: #3a71c1; font-weight: 700;", "color: #3a71c1;", "");
}
static parseType(type) {

View File

@ -14,7 +14,7 @@ import WebpackModules from "./webpackmodules";
export default class Patcher {
static get patches() { return this._patches || (this._patches = []); }
static get patches() {return this._patches || (this._patches = []);}
/**
* Returns all the patches done by a specific caller
@ -22,12 +22,12 @@ export default class Patcher {
* @method
*/
static getPatchesByCaller(name) {
if (!name) return [];
if (!name) return [];
const patches = [];
for (const patch of this.patches) {
for (const childPatch of patch.children) {
if (childPatch.caller === name) patches.push(childPatch);
}
for (const childPatch of patch.children) {
if (childPatch.caller === name) patches.push(childPatch);
}
}
return patches;
}
@ -41,20 +41,20 @@ export default class Patcher {
if (typeof patches === "string") patches = this.getPatchesByCaller(patches);
for (const patch of patches) {
patch.unpatch();
patch.unpatch();
}
}
}
static resolveModule(module) {
static resolveModule(module) {
if (module instanceof Function || (module instanceof Object && !(module instanceof Array))) return module;
if (typeof module === "string") return DiscordModules[module];
if (module instanceof Array) return WebpackModules.findByUniqueProperties(module);
return null;
}
}
static makeOverride(patch) {
return function () {
let returnValue = undefined;
let returnValue;
if (!patch.children || !patch.children.length) return patch.originalFunction.apply(this, arguments);
for (const superPatch of patch.children.filter(c => c.type === "before")) {
try {
@ -70,7 +70,7 @@ export default class Patcher {
else {
for (const insteadPatch of insteads) {
try {
const tempReturn = insteadPatch.callback(this, arguments, patch.originalFunction.bind(this));
const tempReturn = insteadPatch.callback(this, arguments, patch.originalFunction.bind(this));
if (typeof(tempReturn) !== "undefined") returnValue = tempReturn;
}
catch (err) {
@ -81,7 +81,7 @@ export default class Patcher {
for (const slavePatch of patch.children.filter(c => c.type === "after")) {
try {
const tempReturn = slavePatch.callback(this, arguments, returnValue);
const tempReturn = slavePatch.callback(this, arguments, returnValue);
if (typeof(tempReturn) !== "undefined") returnValue = tempReturn;
}
catch (err) {
@ -98,7 +98,7 @@ export default class Patcher {
static makePatch(module, functionName, name) {
const patch = {
name,
name,
module,
functionName,
originalFunction: module[functionName],
@ -112,7 +112,8 @@ export default class Patcher {
children: []
};
patch.proxyFunction = module[functionName] = this.makeOverride(patch);
return this.patches.push(patch), patch;
this.patches.push(patch);
return patch;
}
/**
@ -145,7 +146,7 @@ export default class Patcher {
* @param {boolean} [options.forcePatch=true] Set to `true` to patch even if the function doesnt exist. (Adds noop function in place).
* @return {module:Patcher~unpatch} Function with no arguments and no return value that should be called to cancel (unpatch) this patch. You should save and run it when your plugin is stopped.
*/
static before(caller, moduleToPatch, functionName, callback, options = {}) { return this.pushChildPatch(caller, moduleToPatch, functionName, callback, Object.assign(options, {type: "before"})); }
static before(caller, moduleToPatch, functionName, callback, options = {}) {return this.pushChildPatch(caller, moduleToPatch, functionName, callback, Object.assign(options, {type: "before"}));}
/**
* This method patches onto another function, allowing your code to run after.
@ -160,7 +161,7 @@ export default class Patcher {
* @param {boolean} [options.forcePatch=true] Set to `true` to patch even if the function doesnt exist. (Adds noop function in place).
* @return {module:Patcher~unpatch} Function with no arguments and no return value that should be called to cancel (unpatch) this patch. You should save and run it when your plugin is stopped.
*/
static after(caller, moduleToPatch, functionName, callback, options = {}) { return this.pushChildPatch(caller, moduleToPatch, functionName, callback, Object.assign(options, {type: "after"})); }
static after(caller, moduleToPatch, functionName, callback, options = {}) {return this.pushChildPatch(caller, moduleToPatch, functionName, callback, Object.assign(options, {type: "after"}));}
/**
* This method patches onto another function, allowing your code to run instead.
@ -175,7 +176,7 @@ export default class Patcher {
* @param {boolean} [options.forcePatch=true] Set to `true` to patch even if the function doesnt exist. (Adds noop function in place).
* @return {module:Patcher~unpatch} Function with no arguments and no return value that should be called to cancel (unpatch) this patch. You should save and run it when your plugin is stopped.
*/
static instead(caller, moduleToPatch, functionName, callback, options = {}) { return this.pushChildPatch(caller, moduleToPatch, functionName, callback, Object.assign(options, {type: "instead"})); }
static instead(caller, moduleToPatch, functionName, callback, options = {}) {return this.pushChildPatch(caller, moduleToPatch, functionName, callback, Object.assign(options, {type: "instead"}));}
/**
* This method patches onto another function, allowing your code to run before, instead or after the original function.
@ -193,16 +194,16 @@ export default class Patcher {
* @return {module:Patcher~unpatch} Function with no arguments and no return value that should be called to cancel (unpatch) this patch. You should save and run it when your plugin is stopped.
*/
static pushChildPatch(caller, moduleToPatch, functionName, callback, options = {}) {
const {type = "after", forcePatch = true} = options;
const module = this.resolveModule(moduleToPatch);
if (!module) return null;
if (!module[functionName] && forcePatch) module[functionName] = function() {};
if (!(module[functionName] instanceof Function)) return null;
const {type = "after", forcePatch = true} = options;
const module = this.resolveModule(moduleToPatch);
if (!module) return null;
if (!module[functionName] && forcePatch) module[functionName] = function() {};
if (!(module[functionName] instanceof Function)) return null;
if (typeof moduleToPatch === "string") options.displayName = moduleToPatch;
if (typeof moduleToPatch === "string") options.displayName = moduleToPatch;
const displayName = options.displayName || module.displayName || module.name || module.constructor.displayName || module.constructor.name;
const patchId = `${displayName}.${functionName}`;
const patchId = `${displayName}.${functionName}`;
const patch = this.patches.find(p => p.module == module && p.functionName == functionName) || this.makePatch(module, functionName, patchId);
if (!patch.proxyFunction) this.rePatch(patch);
const child = {
@ -213,10 +214,10 @@ export default class Patcher {
unpatch: () => {
patch.children.splice(patch.children.findIndex(cpatch => cpatch.id === child.id && cpatch.type === type), 1);
if (patch.children.length <= 0) {
const patchNum = this.patches.findIndex(p => p.module == module && p.functionName == functionName);
this.patches[patchNum].revert();
this.patches.splice(patchNum, 1);
}
const patchNum = this.patches.findIndex(p => p.module == module && p.functionName == functionName);
this.patches[patchNum].revert();
this.patches.splice(patchNum, 1);
}
}
};
patch.children.push(child);

View File

@ -14,14 +14,16 @@ import Patcher from "./patcher";
import Emotes from "../builtins/emotes/emotes";
const BdApi = {
get React() { return DiscordModules.React; },
get ReactDOM() { return DiscordModules.ReactDOM; },
get React() {return DiscordModules.React;},
get ReactDOM() {return DiscordModules.ReactDOM;},
get WindowConfigFile() {return "";},
get settings() {return Settings.collections;},
get emotes() {return new Proxy(Emotes.Emotes, {
get() { return Emotes.Emotes},
set() { Logger.warn("Emotes", "Addon policy for plugins #5 https://github.com/rauenzi/BetterDiscordApp/wiki/Addon-Policies#plugins");}
});},
get emotes() {
return new Proxy(Emotes.Emotes, {
get() {return Emotes.Emotes;},
set() {Logger.warn("BdApi.emotes", "Addon policy for plugins #5 https://github.com/rauenzi/BetterDiscordApp/wiki/Addon-Policies#plugins");}
});
},
get version() {return Config.version;}
};
@ -39,28 +41,28 @@ BdApi.setWindowPreference = function(key, value) {
return DataStore.setData("windowprefs", prefs);
};
//Inject CSS to document head
//id = id of element
//css = custom css
// Inject CSS to document head
// id = id of element
// css = custom css
BdApi.injectCSS = function (id, css) {
DOMManager.injectStyle(id, css);
};
//Clear css/remove any element
//id = id of element
// Clear css/remove any element
// id = id of element
BdApi.clearCSS = function (id) {
DOMManager.removeStyle(id);
};
//Inject CSS to document head
//id = id of element
//css = custom css
// Inject CSS to document head
// id = id of element
// css = custom css
BdApi.linkJS = function (id, url) {
return DOMManager.injectScript(id, url);
};
//Clear css/remove any element
//id = id of element
// Clear css/remove any element
// id = id of element
BdApi.unlinkJS = function (id) {
DOMManager.removeScript(id);
};
@ -228,8 +230,8 @@ BdApi.testJSON = function(data) {
return Utilities.testJSON(data);
};
//Get another plugin
//name = name of plugin
// Get another plugin
// name = name of plugin
BdApi.getPlugin = function (name) {
Logger.warn("BdApi", "getPlugin is deprecated. Please make use of the addon api (BdApi.Plugins)");
return PluginManager.addonList.find(a => a.name == name);

View File

@ -72,7 +72,8 @@ export default new class PluginManager extends AddonManager {
initializeAddon(addon) {
if (!addon.type) return new AddonError(addon.name, addon.filename, "Plugin had no exports", {message: "Plugin had no exports or no name property.", stack: ""});
try {
const thePlugin = new addon.type();
const PluginClass = addon.type;
const thePlugin = new PluginClass();
addon.plugin = thePlugin;
addon.name = thePlugin.getName() || addon.name;
addon.author = thePlugin.getAuthor() || addon.author || "No author";
@ -160,8 +161,8 @@ export default new class PluginManager extends AddonManager {
const plugin = this.addonList[i].plugin;
if (!this.state[this.addonList[i].id]) continue;
if (typeof(plugin.onSwitch) === "function") {
try { plugin.onSwitch(); }
catch (err) { Logger.stacktrace(this.name, "Unable to fire onSwitch for " + this.addonList[i].name + ".", err); }
try {plugin.onSwitch();}
catch (err) {Logger.stacktrace(this.name, "Unable to fire onSwitch for " + this.addonList[i].name + ".", err);}
}
}
}
@ -171,8 +172,8 @@ export default new class PluginManager extends AddonManager {
const plugin = this.addonList[i].plugin;
if (!this.state[this.addonList[i].id]) continue;
if (typeof plugin.observer === "function") {
try { plugin.observer(mutation); }
catch (err) { Logger.stacktrace(this.name, "Unable to fire observer for " + this.addonList[i].name + ".", err); }
try {plugin.observer(mutation);}
catch (err) {Logger.stacktrace(this.name, "Unable to fire observer for " + this.addonList[i].name + ".", err);}
}
}
}

View File

@ -2,20 +2,20 @@ import LocaleManager from "./localemanager";
import FormattableString from "../structs/string";
export default new Proxy(LocaleManager.strings, {
get: function(strings, category) {
get: function(strings, category) {
if (!strings.hasOwnProperty(category)) {
return new Proxy({}, {
get: function() {
return `String group "${category}" not found.`;
}
});
}
return new Proxy(strings[category], {
get: function(obj, prop) {
if (typeof(obj[prop]) == "string") return new FormattableString(obj[prop]);
return obj[prop];
}
});
}
return new Proxy({}, {
get: function() {
return `String group "${category}" not found.`;
}
});
}
return new Proxy(strings[category], {
get: function(obj, prop) {
if (typeof(obj[prop]) == "string") return new FormattableString(obj[prop]);
return obj[prop];
}
});
}
});

View File

@ -28,221 +28,221 @@ import {EmulatedTooltip, Toasts} from "ui";
export default class PluginUpdater {
static get CSS() { return require("../styles/updates.css"); }
static get CSS() {return require("../styles/updates.css");}
/**
* Checks for updates for the specified plugin at the specified link. The final
* parameter should link to the raw text of the plugin and will compare semantic
* versions.
* @param {string} pluginName - name of the plugin
* @param {string} currentVersion - current version (semantic versioning only)
* @param {string} updateURL - url to check for update
* @param {module:PluginUpdater~versioner} [versioner] - versioner that finds the remote version. If not provided uses {@link module:PluginUpdater.defaultVersioner}.
* @param {module:PluginUpdater~comparator} [comparator] - comparator that determines if there is an update. If not provided uses {@link module:PluginUpdater.defaultComparator}.
*/
static checkForUpdate(pluginName, currentVersion, updateURL, versioner, comparator) {
let updateLink = "https://raw.githubusercontent.com/rauenzi/BetterDiscordAddons/master/Plugins/" + pluginName + "/" + pluginName + ".plugin.js";
if (updateURL) updateLink = updateURL;
if (typeof(versioner) != "function") versioner = this.defaultVersioner;
if (typeof(comparator) != "function") comparator = this.defaultComparator;
if (typeof window.PluginUpdates === "undefined") {
window.PluginUpdates = {
plugins: {},
checkAll: function() {
for (const key in this.plugins) {
const plugin = this.plugins[key];
if (!plugin.versioner) plugin.versioner = PluginUpdater.defaultVersioner;
if (!plugin.comparator) plugin.comparator = PluginUpdater.defaultComparator;
PluginUpdater.processUpdateCheck(plugin.name, plugin.raw);
}
},
interval: setInterval(() => {
window.PluginUpdates.checkAll();
}, 7200000)
};
this.patchPluginList();
}
/**
* Checks for updates for the specified plugin at the specified link. The final
* parameter should link to the raw text of the plugin and will compare semantic
* versions.
* @param {string} pluginName - name of the plugin
* @param {string} currentVersion - current version (semantic versioning only)
* @param {string} updateURL - url to check for update
* @param {module:PluginUpdater~versioner} [versioner] - versioner that finds the remote version. If not provided uses {@link module:PluginUpdater.defaultVersioner}.
* @param {module:PluginUpdater~comparator} [comparator] - comparator that determines if there is an update. If not provided uses {@link module:PluginUpdater.defaultComparator}.
*/
static checkForUpdate(pluginName, currentVersion, updateURL, versioner, comparator) {
let updateLink = "https://raw.githubusercontent.com/rauenzi/BetterDiscordAddons/master/Plugins/" + pluginName + "/" + pluginName + ".plugin.js";
if (updateURL) updateLink = updateURL;
if (typeof(versioner) != "function") versioner = this.defaultVersioner;
if (typeof(comparator) != "function") comparator = this.defaultComparator;
if (typeof window.PluginUpdates === "undefined") {
window.PluginUpdates = {
plugins: {},
checkAll: function() {
for (const key in this.plugins) {
const plugin = this.plugins[key];
if (!plugin.versioner) plugin.versioner = PluginUpdater.defaultVersioner;
if (!plugin.comparator) plugin.comparator = PluginUpdater.defaultComparator;
PluginUpdater.processUpdateCheck(plugin.name, plugin.raw);
}
},
interval: setInterval(() => {
window.PluginUpdates.checkAll();
}, 7200000)
};
this.patchPluginList();
}
window.PluginUpdates.plugins[updateLink] = {name: pluginName, raw: updateLink, version: currentVersion, versioner: versioner, comparator: comparator};
PluginUpdater.processUpdateCheck(pluginName, updateLink);
}
window.PluginUpdates.plugins[updateLink] = {name: pluginName, raw: updateLink, version: currentVersion, versioner: versioner, comparator: comparator};
PluginUpdater.processUpdateCheck(pluginName, updateLink);
}
/**
* Will check for updates and automatically show or remove the update notice
* bar based on the internal result. Better not to call this directly and to
* instead use {@link module:PluginUpdater.checkForUpdate}.
* @param {string} pluginName - name of the plugin to check
* @param {string} updateLink - link to the raw text version of the plugin
*/
static processUpdateCheck(pluginName, updateLink) {
const request = require("request");
request(updateLink, (error, response, result) => {
if (error) return;
const remoteVersion = window.PluginUpdates.plugins[updateLink].versioner(result);
const hasUpdate = window.PluginUpdates.plugins[updateLink].comparator(window.PluginUpdates.plugins[updateLink].version, remoteVersion);
if (hasUpdate) this.showUpdateNotice(pluginName, updateLink);
else this.removeUpdateNotice(pluginName);
});
}
/**
* Will check for updates and automatically show or remove the update notice
* bar based on the internal result. Better not to call this directly and to
* instead use {@link module:PluginUpdater.checkForUpdate}.
* @param {string} pluginName - name of the plugin to check
* @param {string} updateLink - link to the raw text version of the plugin
*/
static processUpdateCheck(pluginName, updateLink) {
const request = require("request");
request(updateLink, (error, response, result) => {
if (error) return;
const remoteVersion = window.PluginUpdates.plugins[updateLink].versioner(result);
const hasUpdate = window.PluginUpdates.plugins[updateLink].comparator(window.PluginUpdates.plugins[updateLink].version, remoteVersion);
if (hasUpdate) this.showUpdateNotice(pluginName, updateLink);
else this.removeUpdateNotice(pluginName);
});
}
/**
* The default versioner used as {@link module:PluginUpdater~versioner} for {@link module:PluginUpdater.checkForUpdate}.
* This works on basic semantic versioning e.g. "1.0.0". You do not need to provide this as a versioner if your plugin adheres
* to this style as this will be used as default.
* @param {string} currentVersion
* @param {string} content
*/
static defaultVersioner(content) {
const remoteVersion = content.match(/['"][0-9]+\.[0-9]+\.[0-9]+['"]/i);
if (!remoteVersion) return "0.0.0";
return remoteVersion.toString().replace(/['"]/g, "");
}
/**
* The default versioner used as {@link module:PluginUpdater~versioner} for {@link module:PluginUpdater.checkForUpdate}.
* This works on basic semantic versioning e.g. "1.0.0". You do not need to provide this as a versioner if your plugin adheres
* to this style as this will be used as default.
* @param {string} currentVersion
* @param {string} content
*/
static defaultVersioner(content) {
const remoteVersion = content.match(/['"][0-9]+\.[0-9]+\.[0-9]+['"]/i);
if (!remoteVersion) return "0.0.0";
return remoteVersion.toString().replace(/['"]/g, "");
}
/**
* The default comparator used as {@link module:PluginUpdater~comparator} for {@link module:PluginUpdater.checkForUpdate}.
* This works on basic semantic versioning e.g. "1.0.0". You do not need to provide this as a comparator if your plugin adheres
* to this style as this will be used as default.
* @param {string} currentVersion
* @param {string} content
*/
static defaultComparator(currentVersion, remoteVersion) {
currentVersion = currentVersion.split(".").map((e) => {return parseInt(e);});
remoteVersion = remoteVersion.split(".").map((e) => {return parseInt(e);});
if (remoteVersion[0] > currentVersion[0]) return true;
else if (remoteVersion[0] == currentVersion[0] && remoteVersion[1] > currentVersion[1]) return true;
else if (remoteVersion[0] == currentVersion[0] && remoteVersion[1] == currentVersion[1] && remoteVersion[2] > currentVersion[2]) return true;
return false;
}
/**
* The default comparator used as {@link module:PluginUpdater~comparator} for {@link module:PluginUpdater.checkForUpdate}.
* This works on basic semantic versioning e.g. "1.0.0". You do not need to provide this as a comparator if your plugin adheres
* to this style as this will be used as default.
* @param {string} currentVersion
* @param {string} content
*/
static defaultComparator(currentVersion, remoteVersion) {
currentVersion = currentVersion.split(".").map((e) => {return parseInt(e);});
remoteVersion = remoteVersion.split(".").map((e) => {return parseInt(e);});
if (remoteVersion[0] > currentVersion[0]) return true;
else if (remoteVersion[0] == currentVersion[0] && remoteVersion[1] > currentVersion[1]) return true;
else if (remoteVersion[0] == currentVersion[0] && remoteVersion[1] == currentVersion[1] && remoteVersion[2] > currentVersion[2]) return true;
return false;
}
static patchPluginList() {
// Patcher.after("ZeresLibrary", V2C_ContentColumn.prototype, "componentDidMount", (self) => {
// if (self._reactInternalFiber.key != "pcolumn") return;
// const column = DiscordModules.ReactDOM.findDOMNode(self);
// if (!column) return;
// const button = column.getElementsByClassName("bd-pfbtn")[0];
// if (!button || button.nextElementSibling.classList.contains("bd-updatebtn")) return;
// button.after(PluginUpdater.createUpdateButton());
// });
// const button = document.getElementsByClassName("bd-pfbtn")[0];
// if (!button || !button.textContent.toLowerCase().includes("plugin") || button.nextElementSibling.classList.contains("bd-updatebtn")) return;
// button.after(PluginUpdater.createUpdateButton());
}
static patchPluginList() {
// Patcher.after("ZeresLibrary", V2C_ContentColumn.prototype, "componentDidMount", (self) => {
// if (self._reactInternalFiber.key != "pcolumn") return;
// const column = DiscordModules.ReactDOM.findDOMNode(self);
// if (!column) return;
// const button = column.getElementsByClassName("bd-pfbtn")[0];
// if (!button || button.nextElementSibling.classList.contains("bd-updatebtn")) return;
// button.after(PluginUpdater.createUpdateButton());
// });
// const button = document.getElementsByClassName("bd-pfbtn")[0];
// if (!button || !button.textContent.toLowerCase().includes("plugin") || button.nextElementSibling.classList.contains("bd-updatebtn")) return;
// button.after(PluginUpdater.createUpdateButton());
}
/**
* Creates the update button found in the plugins page of BetterDiscord
* settings. Returned button will already have listeners to create the tooltip.
* @returns {HTMLElement} check for update button
*/
static createUpdateButton() {
const updateButton = DOMTools.createElement(`<button class="bd-pfbtn bd-updatebtn" style="left: 220px;">Check for Updates</button>`);
updateButton.onclick = function () {
window.PluginUpdates.checkAll();
};
const tooltip = new EmulatedTooltip(updateButton, "Checks for updates of plugins that support this feature. Right-click for a list.");
updateButton.oncontextmenu = function () {
if (!window.PluginUpdates || !window.PluginUpdates.plugins) return;
tooltip.label = Object.values(window.PluginUpdates.plugins).map(p => p.name).join(", ");
tooltip.side = "bottom";
tooltip.show();
updateButton.onmouseout = function() {
tooltip.label = "Checks for updates of plugins that support this feature. Right-click for a list.";
tooltip.side = "top";
};
};
return updateButton;
}
/**
* Creates the update button found in the plugins page of BetterDiscord
* settings. Returned button will already have listeners to create the tooltip.
* @returns {HTMLElement} check for update button
*/
static createUpdateButton() {
const updateButton = DOMTools.createElement(`<button class="bd-pfbtn bd-updatebtn" style="left: 220px;">Check for Updates</button>`);
updateButton.onclick = function () {
window.PluginUpdates.checkAll();
};
const tooltip = new EmulatedTooltip(updateButton, "Checks for updates of plugins that support this feature. Right-click for a list.");
updateButton.oncontextmenu = function () {
if (!window.PluginUpdates || !window.PluginUpdates.plugins) return;
tooltip.label = Object.values(window.PluginUpdates.plugins).map(p => p.name).join(", ");
tooltip.side = "bottom";
tooltip.show();
updateButton.onmouseout = function() {
tooltip.label = "Checks for updates of plugins that support this feature. Right-click for a list.";
tooltip.side = "top";
};
};
return updateButton;
}
/**
* Will download the latest version and replace the the old plugin version.
* Will also update the button in the update bar depending on if the user
* is using RestartNoMore plugin by square {@link https://github.com/Inve1951/BetterDiscordStuff/blob/master/plugins/restartNoMore.plugin.js}
* @param {string} pluginName - name of the plugin to download
* @param {string} updateLink - link to the raw text version of the plugin
*/
static downloadPlugin(pluginName, updateLink) {
const request = require("request");
const fileSystem = require("fs");
const path = require("path");
request(updateLink, async (error, response, body) => {
if (error) return Logger.warn("PluginUpdates", "Unable to get update for " + pluginName);
const remoteVersion = window.PluginUpdates.plugins[updateLink].versioner(body);
let filename = updateLink.split("/");
filename = filename[filename.length - 1];
const file = path.join(PluginUtilities.getPluginsFolder(), filename);
await new Promise(r => fileSystem.writeFile(file, body, r));
Toasts.success(`${pluginName} ${window.PluginUpdates.plugins[updateLink].version} has been replaced by ${pluginName} ${remoteVersion}`);
this.removeUpdateNotice(pluginName);
/**
* Will download the latest version and replace the the old plugin version.
* Will also update the button in the update bar depending on if the user
* is using RestartNoMore plugin by square {@link https://github.com/Inve1951/BetterDiscordStuff/blob/master/plugins/restartNoMore.plugin.js}
* @param {string} pluginName - name of the plugin to download
* @param {string} updateLink - link to the raw text version of the plugin
*/
static downloadPlugin(pluginName, updateLink) {
const request = require("request");
const fileSystem = require("fs");
const path = require("path");
request(updateLink, async (error, response, body) => {
if (error) return Logger.warn("PluginUpdates", "Unable to get update for " + pluginName);
const remoteVersion = window.PluginUpdates.plugins[updateLink].versioner(body);
let filename = updateLink.split("/");
filename = filename[filename.length - 1];
const file = path.join(PluginUtilities.getPluginsFolder(), filename);
await new Promise(r => fileSystem.writeFile(file, body, r));
Toasts.success(`${pluginName} ${window.PluginUpdates.plugins[updateLink].version} has been replaced by ${pluginName} ${remoteVersion}`);
this.removeUpdateNotice(pluginName);
const oldRNM = window.bdplugins["Restart-No-More"] && window.pluginCookie["Restart-No-More"];
const newRNM = window.bdplugins["Restart No More"] && window.pluginCookie["Restart No More"];
const BBDLoader = window.settingsCookie["fork-ps-5"];
if (oldRNM || newRNM || BBDLoader) return;
if (!window.PluginUpdates.downloaded) {
window.PluginUpdates.downloaded = [];
const button = DOMTools.createElement(`<button class="btn btn-reload ${DiscordClasses.Notices.btn} ${DiscordClasses.Notices.button}">Reload</button>`);
const tooltip = new EmulatedTooltip(button, window.PluginUpdates.downloaded.join(", "), {side: "top"});
button.addEventListener("click", (e) => {
e.preventDefault();
window.location.reload(false);
});
button.addEventListener("mouseenter", () => {
tooltip.label = window.PluginUpdates.downloaded.join(", ");
});
document.getElementById("pluginNotice").append(button);
}
window.PluginUpdates.plugins[updateLink].version = remoteVersion;
window.PluginUpdates.downloaded.push(pluginName);
});
}
const oldRNM = window.bdplugins["Restart-No-More"] && window.pluginCookie["Restart-No-More"];
const newRNM = window.bdplugins["Restart No More"] && window.pluginCookie["Restart No More"];
const BBDLoader = window.settingsCookie["fork-ps-5"];
if (oldRNM || newRNM || BBDLoader) return;
if (!window.PluginUpdates.downloaded) {
window.PluginUpdates.downloaded = [];
const button = DOMTools.createElement(`<button class="btn btn-reload ${DiscordClasses.Notices.btn} ${DiscordClasses.Notices.button}">Reload</button>`);
const tooltip = new EmulatedTooltip(button, window.PluginUpdates.downloaded.join(", "), {side: "top"});
button.addEventListener("click", (e) => {
e.preventDefault();
window.location.reload(false);
});
button.addEventListener("mouseenter", () => {
tooltip.label = window.PluginUpdates.downloaded.join(", ");
});
document.getElementById("pluginNotice").append(button);
}
window.PluginUpdates.plugins[updateLink].version = remoteVersion;
window.PluginUpdates.downloaded.push(pluginName);
});
}
/**
* Will show the update notice top bar seen in Discord. Better not to call
* this directly and to instead use {@link module:PluginUpdater.checkForUpdate}.
* @param {string} pluginName - name of the plugin
* @param {string} updateLink - link to the raw text version of the plugin
*/
static showUpdateNotice(pluginName, updateLink) {
if (!document.getElementById("pluginNotice")) {
const noticeElement = DOMTools.createElement(`<div class="${DiscordClasses.Notices.notice} ${DiscordClasses.Notices.noticeInfo}" id="pluginNotice">
<div class="${DiscordClasses.Notices.dismiss}" id="pluginNoticeDismiss"></div>
<span class="notice-message">The following plugins have updates:</span>&nbsp;&nbsp;<strong id="outdatedPlugins"></strong>
</div>`);
DOMTools.query("[class*='app-'] > [class*='app-']").prepend(noticeElement);
noticeElement.querySelector("#pluginNoticeDismiss").addEventListener("click", async () => {
noticeElement.classList.add("closing");
await new Promise(resolve => setTimeout(resolve, 400));
noticeElement.remove();
});
}
const pluginNoticeID = pluginName + "-notice";
if (document.getElementById(pluginNoticeID)) return;
const pluginNoticeElement = DOMTools.createElement(`<span id="${pluginNoticeID}">${pluginName}</span>`);
pluginNoticeElement.addEventListener("click", () => {
this.downloadPlugin(pluginName, updateLink);
});
if (document.getElementById("outdatedPlugins").querySelectorAll("span").length) document.getElementById("outdatedPlugins").append(DOMTools.createElement("<span class='separator'>, </span>"));
document.getElementById("outdatedPlugins").append(pluginNoticeElement);
}
/**
* Will show the update notice top bar seen in Discord. Better not to call
* this directly and to instead use {@link module:PluginUpdater.checkForUpdate}.
* @param {string} pluginName - name of the plugin
* @param {string} updateLink - link to the raw text version of the plugin
*/
static showUpdateNotice(pluginName, updateLink) {
if (!document.getElementById("pluginNotice")) {
const noticeElement = DOMTools.createElement(`<div class="${DiscordClasses.Notices.notice} ${DiscordClasses.Notices.noticeInfo}" id="pluginNotice">
<div class="${DiscordClasses.Notices.dismiss}" id="pluginNoticeDismiss"></div>
<span class="notice-message">The following plugins have updates:</span>&nbsp;&nbsp;<strong id="outdatedPlugins"></strong>
</div>`);
DOMTools.query("[class*='app-'] > [class*='app-']").prepend(noticeElement);
noticeElement.querySelector("#pluginNoticeDismiss").addEventListener("click", async () => {
noticeElement.classList.add("closing");
await new Promise(resolve => setTimeout(resolve, 400));
noticeElement.remove();
});
}
const pluginNoticeID = pluginName + "-notice";
if (document.getElementById(pluginNoticeID)) return;
const pluginNoticeElement = DOMTools.createElement(`<span id="${pluginNoticeID}">${pluginName}</span>`);
pluginNoticeElement.addEventListener("click", () => {
this.downloadPlugin(pluginName, updateLink);
});
if (document.getElementById("outdatedPlugins").querySelectorAll("span").length) document.getElementById("outdatedPlugins").append(DOMTools.createElement("<span class='separator'>, </span>"));
document.getElementById("outdatedPlugins").append(pluginNoticeElement);
}
/**
* Will remove the plugin from the update notice top bar seen in Discord.
* Better not to call this directly and to instead use {@link module:PluginUpdater.checkForUpdate}.
* @param {string} pluginName - name of the plugin
*/
static removeUpdateNotice(pluginName) {
if (!document.getElementById("outdatedPlugins")) return;
const notice = document.getElementById(pluginName + "-notice");
if (notice) {
if (notice.nextElementSibling && notice.nextElementSibling.matches(".separator")) notice.nextElementSibling.remove();
else if (notice.previousElementSibling && notice.previousElementSibling.matches(".separator")) notice.previousElementSibling.remove();
notice.remove();
}
/**
* Will remove the plugin from the update notice top bar seen in Discord.
* Better not to call this directly and to instead use {@link module:PluginUpdater.checkForUpdate}.
* @param {string} pluginName - name of the plugin
*/
static removeUpdateNotice(pluginName) {
if (!document.getElementById("outdatedPlugins")) return;
const notice = document.getElementById(pluginName + "-notice");
if (notice) {
if (notice.nextElementSibling && notice.nextElementSibling.matches(".separator")) notice.nextElementSibling.remove();
else if (notice.previousElementSibling && notice.previousElementSibling.matches(".separator")) notice.previousElementSibling.remove();
notice.remove();
}
if (!document.getElementById("outdatedPlugins").querySelectorAll("span").length) {
if (document.querySelector("#pluginNotice .btn-reload")) document.querySelector("#pluginNotice .notice-message").textContent = "To finish updating you need to reload.";
else document.getElementById("pluginNoticeDismiss").click();
}
}
if (!document.getElementById("outdatedPlugins").querySelectorAll("span").length) {
if (document.querySelector("#pluginNotice .btn-reload")) document.querySelector("#pluginNotice .notice-message").textContent = "To finish updating you need to reload.";
else document.getElementById("pluginNoticeDismiss").click();
}
}
}

View File

@ -53,8 +53,8 @@ export default class Utilities {
static suppressErrors(method, message) {
return (...params) => {
try { return method(...params); }
catch (e) { Logger.stacktrace("SuppressedError", "Error occurred in " + message, e); }
try {return method(...params);}
catch (e) {Logger.stacktrace("SuppressedError", "Error occurred in " + message, e);}
};
}
@ -129,9 +129,16 @@ export default class Utilities {
for (let i = 0; i < extenders.length; i++) {
for (const key in extenders[i]) {
if (extenders[i].hasOwnProperty(key)) {
if (typeof extendee[key] === "object" && typeof extenders[i][key] === "object") this.extend(extendee[key], extenders[i][key]);
else if (typeof extenders[i][key] === "object") extendee[key] = {}, this.extend(extendee[key], extenders[i][key]);
else extendee[key] = extenders[i][key];
if (typeof extendee[key] === "object" && typeof extenders[i][key] === "object") {
this.extend(extendee[key], extenders[i][key]);
}
else if (typeof extenders[i][key] === "object") {
extendee[key] = {};
this.extend(extendee[key], extenders[i][key]);
}
else {
extendee[key] = extenders[i][key];
}
}
}
}
@ -174,7 +181,7 @@ export default class Utilities {
if (typeof tree !== "object" || tree == null) return undefined;
let tempReturn = undefined;
let tempReturn;
if (tree instanceof Array) {
for (const value of tree) {
tempReturn = this.findInTree(value, searchFilter, {walkable, ignore});
@ -228,36 +235,36 @@ export default class Utilities {
}
/**
* Grabs a value from the react internal instance. Allows you to grab
* long depth values safely without accessing no longer valid properties.
* @param {HTMLElement} node - node to obtain react instance of
* @param {object} options - options for the search
* @param {array} [options.include] - list of items to include from the search
* @param {array} [options.exclude=["Popout", "Tooltip", "Scroller", "BackgroundFlash"]] - list of items to exclude from the search
* @param {callable} [options.filter=_=>_] - filter to check the current instance with (should return a boolean)
* @return {(*|null)} the owner instance or undefined if not found.
*/
static getOwnerInstance(node, {include, exclude = ["Popout", "Tooltip", "Scroller", "BackgroundFlash"], filter = _ => _} = {}) {
if (node === undefined) return undefined;
const excluding = include === undefined;
const nameFilter = excluding ? exclude : include;
function getDisplayName(owner) {
const type = owner.type;
if (!type) return null;
return type.displayName || type.name || null;
}
function classFilter(owner) {
const name = getDisplayName(owner);
return (name !== null && !!(nameFilter.includes(name) ^ excluding));
}
* Grabs a value from the react internal instance. Allows you to grab
* long depth values safely without accessing no longer valid properties.
* @param {HTMLElement} node - node to obtain react instance of
* @param {object} options - options for the search
* @param {array} [options.include] - list of items to include from the search
* @param {array} [options.exclude=["Popout", "Tooltip", "Scroller", "BackgroundFlash"]] - list of items to exclude from the search
* @param {callable} [options.filter=_=>_] - filter to check the current instance with (should return a boolean)
* @return {(*|null)} the owner instance or undefined if not found.
*/
static getOwnerInstance(node, {include, exclude = ["Popout", "Tooltip", "Scroller", "BackgroundFlash"], filter = _ => _} = {}) {
if (node === undefined) return undefined;
const excluding = include === undefined;
const nameFilter = excluding ? exclude : include;
function getDisplayName(owner) {
const type = owner.type;
if (!type) return null;
return type.displayName || type.name || null;
}
function classFilter(owner) {
const name = getDisplayName(owner);
return (name !== null && !!(nameFilter.includes(name) ^ excluding));
}
let curr = this.getReactInstance(node);
for (curr = curr && curr.return; curr !== null; curr = curr.return) {
if (curr === null) continue;
const owner = curr.stateNode;
if (curr !== null && !(owner instanceof HTMLElement) && classFilter(curr) && filter(owner)) return owner;
}
let curr = this.getReactInstance(node);
for (curr = curr && curr.return; curr !== null; curr = curr.return) {
if (curr === null) continue;
const owner = curr.stateNode;
if (curr !== null && !(owner instanceof HTMLElement) && classFilter(curr) && filter(owner)) return owner;
}
return null;
}
return null;
}
}

View File

@ -247,9 +247,7 @@ export default class WebpackModules {
static get require() {
if (this._require) return this._require;
const id = "bbd-webpackmodules";
const __webpack_require__ = typeof(window.webpackJsonp) == "function" ? window.webpackJsonp([], {
[id]: (module, exports, __internal_require__) => exports.default = __internal_require__
}, [id]).default : window.webpackJsonp.push([[], {
const __webpack_require__ = window.webpackJsonp.push([[], {
[id]: (module, exports, __internal_require__) => module.exports = __internal_require__
}, [[id]]]);
delete __webpack_require__.m[id];

View File

@ -1,6 +1,6 @@
export default class Screen {
/** Document/window width */
static get width() { return Math.max(document.documentElement.clientWidth, window.innerWidth || 0); }
static get width() {return Math.max(document.documentElement.clientWidth, window.innerWidth || 0);}
/** Document/window height */
static get height() { return Math.max(document.documentElement.clientHeight, window.innerHeight || 0); }
static get height() {return Math.max(document.documentElement.clientHeight, window.innerHeight || 0);}
}

View File

@ -128,6 +128,7 @@
.bd-qme-hidden #bd-qem-emojis {
display: none;
}
.bd-em-scroller {
height: 400px;
}

View File

@ -28,7 +28,7 @@ export default class CssEditor extends React.Component {
{label: React.createElement(Save, {size: "18px"}), tooltip: Strings.CustomCSS.save, onClick: this.saveCss},
{label: React.createElement(Edit, {size: "18px"}), tooltip: Strings.CustomCSS.openNative, onClick: this.openNative},
{label: React.createElement(Cog, {size: "18px"}), tooltip: Strings.CustomCSS.settings, onClick: "showSettings"},
{label: Strings.Collections.settings.customcss.liveUpdate.name, type:"checkbox", onChange: this.toggleLiveUpdate, checked: Settings.get("settings", "customcss", "liveUpdate"), side: "right"}
{label: Strings.Collections.settings.customcss.liveUpdate.name, type: "checkbox", onChange: this.toggleLiveUpdate, checked: Settings.get("settings", "customcss", "liveUpdate"), side: "right"}
];
if (this.openDetached) this.controls.push({label: React.createElement(Detach, {size: "18px"}), tooltip: Strings.CustomCSS.openDetached, onClick: this.openDetached, side: "right"});
}

View File

@ -1,30 +1,36 @@
import {React, WebpackModules, DiscordModules} from "modules";
import {React, WebpackModules} from "modules";
import EmoteModule from "../builtins/emotes/emotes";
const {openContextMenu, closeContextMenu} = WebpackModules.getByProps("openContextMenu");
const ContextMenuActions = WebpackModules.getByProps("openContextMenu");
const {MenuItem, MenuGroup} = WebpackModules.find(m => m.MenuRadioItem && !m.default);
const ContextMenu = WebpackModules.getByProps("default", "MenuStyle").default;
const {ComponentDispatch} = WebpackModules.getByProps("ComponentDispatch");
export default class EmoteIcon extends React.Component {
render() {
return <div className="emote-container" onClick={this.handleOnClick.bind(this)} onContextMenu={this.handleOnContextMenu.bind(this)}>
<img src={this.props.url} alt={this.props.emote} title={this.props.emote}/>
</div>
</div>;
}
handleOnClick() {
this.insertText(this.props.emote);
}
handleOnContextMenu(e) {
openContextMenu(e, () => <ContextMenu navId="EmoteContextMenu" onClose={closeContextMenu}>
ContextMenuActions.openContextMenu(e, () => <ContextMenu navId="EmoteContextMenu" onClose={ContextMenuActions.closeContextMenu}>
<MenuGroup>
<MenuItem label={EmoteModule.isFavorite(this.props.emote) ? "Remove Favorite" : "Add Favorite"} id="favorite" action={this.handlefavorite.bind(this)} onClose={closeContextMenu}/>
<MenuItem label={EmoteModule.isFavorite(this.props.emote) ? "Remove Favorite" : "Add Favorite"} id="favorite" action={this.handlefavorite.bind(this)} onClose={ContextMenuActions.closeContextMenu}/>
</MenuGroup>
</ContextMenu>);
}
handlefavorite() {
closeContextMenu();
ContextMenuActions.closeContextMenu();
EmoteModule.isFavorite(this.props.emote) ? EmoteModule.removeFavorite(this.props.emote) : EmoteModule.addFavorite(this.props.emote, this.props.url);
}
insertText(emote) {
ComponentDispatch.dispatchToLastSubscribed("INSERT_TEXT", {content: emote})
ComponentDispatch.dispatchToLastSubscribed("INSERT_TEXT", {content: emote});
}
}

View File

@ -8,6 +8,6 @@ export default class EmoteMenuCard extends React.Component {
{this.props.children}
</div>
</Scroller>
</div>
</div>;
}
}

View File

@ -99,7 +99,7 @@ export default class FloatingWindow extends React.Component {
render() {
const top = this.props.center ? (Screen.height / 2) - (this.props.height / 2) : this.props.top;
const left = this.props.center ? (Screen.width / 2) - (this.props.width / 2) : this.props.left ;
const left = this.props.center ? (Screen.width / 2) - (this.props.width / 2) : this.props.left;
// console.log(top, left);
const className = `floating-window${` ${this.props.className}` || ""}${this.props.resizable ? " resizable" : ""}${this.state.modalOpen ? " modal-open" : ""}`;
const styles = {height: this.props.height, width: this.props.width, left: left || 0, top: top || 0};

View File

@ -1,11 +1,17 @@
import {WebpackModules, React, ReactDOM, DOM, DOMManager} from "modules";
import FloatingWindowContainer from "./floating/container";
/* eslint-disable new-cap */
const LayerProviders = WebpackModules.getByProps("AppReferencePositionLayer");
export default class FloatingWindows {
static initialize() {
const containerRef = React.createRef();
const container = <FloatingWindowContainer ref={containerRef} />;
const wrapped = React.createElement(WebpackModules.getByProps("AppReferencePositionLayer").AppLayerProvider().props.layerContext.Provider, {value: [document.querySelector("#app-mount > .layerContainer-yqaFcK")]}, container);
const wrapped = LayerProviders
? React.createElement(LayerProviders.AppLayerProvider().props.layerContext.Provider, {value: [document.querySelector("#app-mount > .layerContainer-yqaFcK")]}, container) // eslint-disable-line new-cap
: container;
const div = DOM.createElement(`<div id="floating-windows-layer">`);
DOMManager.bdBody.append(div);
ReactDOM.render(wrapped, div);

View File

@ -36,11 +36,11 @@ export default class Modals {
</div>`);
modal.querySelector(".footer button").addEventListener("click", () => {
modal.classList.add("closing");
setTimeout(() => { modal.remove(); }, 300);
setTimeout(() => {modal.remove();}, 300);
});
modal.querySelector(".bd-backdrop").addEventListener("click", () => {
modal.classList.add("closing");
setTimeout(() => { modal.remove(); }, 300);
setTimeout(() => {modal.remove();}, 300);
});
document.querySelector("#app-mount").append(modal);
}
@ -153,11 +153,11 @@ export default class Modals {
modal.querySelector(".footer button").addEventListener("click", () => {
DOM.addClass(modal, "closing");
setTimeout(() => { modal.remove(); }, 300);
setTimeout(() => {modal.remove();}, 300);
});
modal.querySelector(".bd-backdrop").addEventListener("click", () => {
DOM.addClass(modal, "closing");
setTimeout(() => { modal.remove(); }, 300);
setTimeout(() => {modal.remove();}, 300);
});
DOM.query("#app-mount").append(modal);
if (pluginErrors.length) modal.querySelector(".tab-bar-item").click();

View File

@ -4,7 +4,7 @@ import ReloadIcon from "../icons/reload";
import EditIcon from "../icons/edit";
import DeleteIcon from "../icons/delete";
import Switch from "./components/switch";
import ErrorBoundary from "../errorboundary";
import ErrorBoundary from "../errorboundary";
const Tooltip = WebpackModules.getByDisplayName("Tooltip");
@ -41,7 +41,7 @@ export default class AddonCard extends React.Component {
const cBottom = cTop + container.clientHeight;
const eTop = element.offsetTop;
const eBottom = eTop + element.clientHeight;
return (eTop < cTop || eBottom > cBottom);
return (eTop < cTop || eBottom > cBottom);
};
const thisNode = this.panelRef.current;
@ -93,8 +93,8 @@ export default class AddonCard extends React.Component {
get settingsComponent() {
const addon = this.props.addon;
const name = this.getString(addon.name);
try { this.settingsPanel = this.props.getSettingsPanel(); }
catch (err) { Logger.stacktrace("Addon Settings", "Unable to get settings panel for " + name + ".", err); }
try {this.settingsPanel = this.props.getSettingsPanel();}
catch (err) {Logger.stacktrace("Addon Settings", "Unable to get settings panel for " + name + ".", err);}
const props = {id: `${name}-settings`, className: "addon-settings", ref: this.panelRef};
if (typeof(this.settingsPanel) == "string") {
@ -141,7 +141,7 @@ export default class AddonCard extends React.Component {
}
makeButton(title, children, action) {
return <Tooltip color="black" position="top" text={title}>
return <Tooltip color="black" position="top" text={title}>
{(props) => {
return <div {...props} className="bd-addon-button" onClick={action}>{children}</div>;
}}

View File

@ -6,7 +6,7 @@ import ReloadIcon from "../icons/reload";
import AddonCard from "./addoncard";
import Dropdown from "./components/dropdown";
import Search from "./components/search";
import ErrorBoundary from "../errorboundary";
import ErrorBoundary from "../errorboundary";
export default class AddonList extends React.Component {
@ -18,7 +18,7 @@ export default class AddonList extends React.Component {
this.search = this.search.bind(this);
this.update = this.update.bind(this);
}
componentDidMount() {
Events.on(`${this.props.prefix}-loaded`, this.update);
Events.on(`${this.props.prefix}-unloaded`, this.update);
@ -70,10 +70,12 @@ export default class AddonList extends React.Component {
render() {
const {title, folder, addonList, addonState, onChange, reload} = this.props;
const showReloadIcon = !Settings.get("settings", "addons", "autoReload");
const button = folder ? {title: Strings.Addons.openFolder.format({type: title}), onClick: () => {
const shell = require("electron").shell;
const open = shell.openItem || shell.openPath;
open(folder);
const button = folder ? {
title: Strings.Addons.openFolder.format({type: title}),
onClick: () => {
const shell = require("electron").shell;
const open = shell.openItem || shell.openPath;
open(folder);
}} : null;
const sortedAddons = addonList.sort((a, b) => {
const first = a[this.state.sort];

View File

@ -34,7 +34,7 @@ export default class Select extends React.Component {
get options() {
const selected = this.selected;
return <div className="bd-select-options">
{this.props.options.map(opt =>
{this.props.options.map(opt =>
<div className={`bd-select-option${selected.value == opt.value ? " selected" : ""}`} onClick={this.onChange.bind(this, opt.value)}>{opt.label}</div>
)}
</div>;
@ -43,7 +43,7 @@ export default class Select extends React.Component {
render() {
const style = this.props.style == "transparent" ? " bd-select-transparent" : "";
const isOpen = this.state.open ? " menu-open" : "";
return <div className={`bd-select${style}${isOpen}`} onClick={this.showMenu} ref={this.dropdown}>
return <div className={`bd-select${style}${isOpen}`} onClick={this.showMenu} ref={this.dropdown}>
<div className="bd-select-value">{this.selected.label}</div>
<Arrow className="bd-select-arrow" />
{this.state.open && this.options}

View File

@ -16,7 +16,7 @@ export default class Switch extends React.Component {
render() {
const enabledClass = this.props.disabled ? " bd-switch-disabled" : "";
const checkedClass = this.state.checked ? " bd-switch-checked" : "";
return <div className={`bd-switch` + enabledClass + checkedClass}>
return <div className={`bd-switch` + enabledClass + checkedClass}>
<input type="checkbox" id={this.props.id} className={`bd-checkbox`} disabled={this.props.disabled} checked={this.state.checked} onChange={this.onChange} />
</div>;
}

View File

@ -7,15 +7,11 @@ const SidebarComponents = WebpackModules.getModule(m => m.Header && m.Separator
const Tooltip = WebpackModules.getByDisplayName("Tooltip");
export default class SettingsTitle extends React.Component {
constructor(props) {
super(props);
}
render() {
return <div className="bd-sidebar-header">
<SidebarComponents.Header>BandagedBD</SidebarComponents.Header>
<Tooltip color="black" position="top" text="Changelog">
{props =>
{props =>
<div {...props} className="bd-changelog-button" onClick={() => Modals.showChangelogModal(Changelog)}>
<HistoryIcon className="bd-icon" size="16px" />
</div>

View File

@ -4,10 +4,6 @@ const className = "bd-settings-title h2-2gWE-o title-3sZWYQ size16-14cGz5 height
const className2 = "bd-settings-title bd-settings-group-title h5-18_1nd title-3sZWYQ size12-3R0845 height16-2Lv3qA weightSemiBold-NJexzi da-h5 da-title da-size12 da-height16 da-weightSemiBold marginBottom4-2qk4Hy da-marginBottom4 marginTop8-1DLZ1n da-marginTop8";
export default class SettingsTitle extends React.Component {
constructor(props) {
super(props);
}
//h2-2gWE-o title-3sZWYQ size16-14cGz5 height20-mO2eIN weightSemiBold-NJexzi da-h2 da-title da-size16 da-height20 da-weightSemiBold defaultColor-1_ajX0 da-defaultColor marginTop60-3PGbtK da-marginTop60 marginBottom20-32qID7 da-marginBottom20
render() {
const baseClass = this.props.isGroup ? className2 : className;
const titleClass = this.props.className ? `${baseClass} ${this.props.className}` : baseClass;

View File

@ -1,5 +1,6 @@
const path = require("path");
const CircularDependencyPlugin = require("circular-dependency-plugin");
const TerserPlugin = require("terser-webpack-plugin");
module.exports = {
mode: "development",
@ -50,6 +51,14 @@ module.exports = {
exclude: /node_modules/,
cwd: process.cwd(),
})
]
],
optimization: {
minimizer: [
new TerserPlugin({
terserOptions: {
compress: {drop_debugger:false}
}
})
]
}
};