Clean up code, add more linting, update emote styling

This commit is contained in:
Zack Rauen 2021-04-12 01:07:00 -04:00
parent 2b4c077378
commit fd43ebf7b8
27 changed files with 60 additions and 106 deletions

View File

@ -1,5 +1,6 @@
{ {
"env": { "extends": "eslint:recommended",
"env": {
"node": true "node": true
}, },
"parserOptions": { "parserOptions": {

View File

@ -51,10 +51,6 @@
"hideGiftButton": { "hideGiftButton": {
"name": "Hide Gift Button", "name": "Hide Gift Button",
"note": "Hides the Nitro Gift button in the textarea" "note": "Hides the Nitro Gift button in the textarea"
},
"removeMinimumSize": {
"name": "Remove Minimum Size",
"note": "Removes Discord's forced minimum window size of 940x500"
} }
}, },
"addons": { "addons": {
@ -136,6 +132,10 @@
"frame": { "frame": {
"name": "Window Frame", "name": "Window Frame",
"note": "Adds the native os window frame to the main window" "note": "Adds the native os window frame to the main window"
},
"removeMinimumSize": {
"name": "Remove Minimum Size",
"note": "Removes Discord's forced minimum window size of 940x500"
} }
} }
}, },

View File

@ -108,7 +108,7 @@ export default class BetterDiscord {
browserWindow.webContents.send(IPCEvents.NAVIGATE); browserWindow.webContents.send(IPCEvents.NAVIGATE);
}); });
browserWindow.webContents.on("render-process-gone", (event, details) => { browserWindow.webContents.on("render-process-gone", () => {
hasCrashed = true; hasCrashed = true;
}); });
} }

View File

@ -1,4 +1,4 @@
import {ipcMain as ipc, BrowserWindow, app, dialog} from "electron"; import {ipcMain as ipc, BrowserWindow, app} from "electron";
import * as IPCEvents from "common/constants/ipcevents"; import * as IPCEvents from "common/constants/ipcevents";

View File

@ -19,8 +19,8 @@ export default new class TwentyFourHour extends Builtin {
const convert = (thisObject, args, returnValue) => { const convert = (thisObject, args, returnValue) => {
const matched = returnValue.match(twelveHour); const matched = returnValue.match(twelveHour);
if (!matched || matched.length !== 4) return; if (!matched || matched.length !== 4) return;
if (matched[3] === "AM") return returnValue = returnValue.replace(matched[0], `${matched[1] === "12" ? "00" : matched[1].padStart(2, "0")}:${matched[2]}`); if (matched[3] === "AM") return returnValue.replace(matched[0], `${matched[1] === "12" ? "00" : matched[1].padStart(2, "0")}:${matched[2]}`);
return returnValue = returnValue.replace(matched[0], `${matched[1] === "12" ? "12" : parseInt(matched[1]) + 12}:${matched[2]}`); return returnValue.replace(matched[0], `${matched[1] === "12" ? "12" : parseInt(matched[1]) + 12}:${matched[2]}`);
}; };
this.after(DiscordModules.TimeFormatter, "calendarFormat", convert); // Called in Cozy mode this.after(DiscordModules.TimeFormatter, "calendarFormat", convert); // Called in Cozy mode

View File

@ -1,7 +1,6 @@
// Export these two first because they add settings/panels // Export these two first because they add settings/panels
export {default as CustomCSS} from "./customcss"; export {default as CustomCSS} from "./customcss";
export {default as WindowPrefs} from "./windowprefs";
export {default as PublicServers} from "./general/publicservers"; export {default as PublicServers} from "./general/publicservers";
export {default as VoiceDisconnect} from "./general/voicedisconnect"; export {default as VoiceDisconnect} from "./general/voicedisconnect";
@ -12,7 +11,6 @@ export {default as ColoredText} from "./appearance/coloredtext";
export {default as HideGIFButton} from "./appearance/hidegifbutton"; export {default as HideGIFButton} from "./appearance/hidegifbutton";
export {default as HideGiftButton} from "./appearance/hidegiftbutton"; export {default as HideGiftButton} from "./appearance/hidegiftbutton";
export {default as MinimalMode} from "./appearance/minimalmode"; export {default as MinimalMode} from "./appearance/minimalmode";
export {default as RemoveMinimumSize} from "./appearance/removeminimumsize";
export {default as EmoteModule} from "./emotes/emotes"; export {default as EmoteModule} from "./emotes/emotes";
export {default as EmoteMenu} from "./emotes/emotemenu"; export {default as EmoteMenu} from "./emotes/emotemenu";
@ -22,4 +20,7 @@ export {default as Debugger} from "./developer/debugger";
export {default as ReactDevTools} from "./developer/reactdevtools"; export {default as ReactDevTools} from "./developer/reactdevtools";
export {default as InspectElement} from "./developer/inspectelement"; export {default as InspectElement} from "./developer/inspectelement";
export {default as StopDevToolsWarning} from "./developer/devtoolswarning"; export {default as StopDevToolsWarning} from "./developer/devtoolswarning";
export {default as DebugLogs} from "./developer/debuglogs"; export {default as DebugLogs} from "./developer/debuglogs";
export {default as WindowPrefs} from "./window/transparency";
export {default as RemoveMinimumSize} from "./window/removeminimumsize";

View File

@ -2,9 +2,6 @@ import Builtin from "../../structs/builtin";
import Modals from "../../ui/modals"; import Modals from "../../ui/modals";
import {Strings, IPC} from "modules"; import {Strings, IPC} from "modules";
const fs = require("fs");
const path = require("path");
export default new class ReactDevTools extends Builtin { export default new class ReactDevTools extends Builtin {
get name() {return "ReactDevTools";} get name() {return "ReactDevTools";}
get category() {return "developer";} get category() {return "developer";}

View File

@ -3,7 +3,7 @@ import IPC from "../../modules/ipc";
export default new class RemoveMinimumSize extends Builtin { export default new class RemoveMinimumSize extends Builtin {
get name() {return "RemoveMinimumSize";} get name() {return "RemoveMinimumSize";}
get category() {return "appearance";} get category() {return "window";}
get id() {return "removeMinimumSize";} get id() {return "removeMinimumSize";}
enabled() { enabled() {

View File

@ -1,9 +1,9 @@
import Builtin from "../structs/builtin"; import Builtin from "../../structs/builtin";
import Modals from "../ui/modals"; import Modals from "../../ui/modals";
import {Strings, IPC} from "modules"; import {Strings, IPC} from "modules";
export default new class WindowPrefs extends Builtin { export default new class WindowTransparency extends Builtin {
get name() {return "WindowPrefs";} get name() {return "WindowTransparency";}
get category() {return "window";} get category() {return "window";}
get id() {return "transparency";} get id() {return "transparency";}

View File

@ -20,8 +20,7 @@ export default [
{type: "switch", id: "hideGiftButton", value: false}, {type: "switch", id: "hideGiftButton", value: false},
{type: "switch", id: "hideGIFButton", value: false}, {type: "switch", id: "hideGIFButton", value: false},
{type: "switch", id: "minimalMode", value: false}, {type: "switch", id: "minimalMode", value: false},
{type: "switch", id: "coloredText", value: false}, {type: "switch", id: "coloredText", value: false}
{type: "switch", id: "removeMinimumSize", value: false}
] ]
}, },
{ {
@ -66,6 +65,7 @@ export default [
shown: false, shown: false,
settings: [ settings: [
{type: "switch", id: "transparency", value: false}, {type: "switch", id: "transparency", value: false},
{type: "switch", id: "removeMinimumSize", value: false},
{type: "switch", id: "frame", value: false, hidden: true} {type: "switch", id: "frame", value: false, hidden: true}
] ]
} }

View File

@ -198,7 +198,7 @@ export default class AddonManager {
loadAddon(filename, shouldToast = false) { loadAddon(filename, shouldToast = false) {
if (typeof(filename) === "undefined") return; if (typeof(filename) === "undefined") return;
try { try {
const addon = __non_webpack_require__(path.resolve(this.addonFolder, filename)); __non_webpack_require__(path.resolve(this.addonFolder, filename));
} }
catch (error) { catch (error) {
return new AddonError(filename, filename, Strings.Addons.compileError, {message: error.message, stack: error.stack}, this.prefix); return new AddonError(filename, filename, Strings.Addons.compileError, {message: error.message, stack: error.stack}, this.prefix);

View File

@ -89,16 +89,13 @@ export default new class Core {
} }
waitForGuilds() { waitForGuilds() {
let timesChecked = 0;
return new Promise(resolve => { return new Promise(resolve => {
const checkForGuilds = function () { const checkForGuilds = function () {
timesChecked++;
if (document.readyState != "complete") setTimeout(checkForGuilds, 100); if (document.readyState != "complete") setTimeout(checkForGuilds, 100);
const wrapper = GuildClasses.wrapper.split(" ")[0]; const wrapper = GuildClasses.wrapper.split(" ")[0];
const guild = GuildClasses.listItem.split(" ")[0]; const guild = GuildClasses.listItem.split(" ")[0];
const blob = GuildClasses.blobContainer.split(" ")[0]; const blob = GuildClasses.blobContainer.split(" ")[0];
if (document.querySelectorAll(`.${wrapper} .${guild} .${blob}`).length > 0) return resolve(); if (document.querySelectorAll(`.${wrapper} .${guild} .${blob}`).length > 0) return resolve();
// else if (timesChecked >= 50) return resolve();
setTimeout(checkForGuilds, 100); setTimeout(checkForGuilds, 100);
}; };

View File

@ -6,9 +6,6 @@ const path = require("path");
const releaseChannel = window?.DiscordNative?.app?.getReleaseChannel?.() ?? "stable"; const releaseChannel = window?.DiscordNative?.app?.getReleaseChannel?.() ?? "stable";
const discordVersion = window?.DiscordNative?.remoteApp?.getVersion?.() ?? "0.0.309"; const discordVersion = window?.DiscordNative?.remoteApp?.getVersion?.() ?? "0.0.309";
// const releaseChannel = "stable";
// const discordVersion = "0.0.309";
// Schema // Schema
// ======================= // =======================
// %appdata%\BetterDiscord // %appdata%\BetterDiscord

View File

@ -36,20 +36,16 @@ const BdApi = {
}; };
BdApi.getAllWindowPreferences = function() { BdApi.getAllWindowPreferences = function() {
// return DataStore.getData("windowprefs") || {}; Logger.warn("Deprecated", "BdApi.getAllWindowPreferences() has been deprecated due to the new handling of window transparency.");
// TODO: mark deprecated
}; };
BdApi.getWindowPreference = function(key) { BdApi.getWindowPreference = function() {
// return this.getAllWindowPreferences()[key]; Logger.warn("Deprecated", "BdApi.getWindowPreference() has been deprecated due to the new handling of window transparency.");
// TODO: mark deprecated return null;
}; };
BdApi.setWindowPreference = function(key, value) { BdApi.setWindowPreference = function() {
// const prefs = this.getAllWindowPreferences(); Logger.warn("Deprecated", "BdApi.setWindowPreference() has been deprecated due to the new handling of window transparency.");
// prefs[key] = value;
// return DataStore.setData("windowprefs", prefs);
// TODO: mark deprecated
}; };
// Inject CSS to document head // Inject CSS to document head

View File

@ -4,7 +4,6 @@ import AddonManager from "./addonmanager";
import AddonError from "../structs/addonerror"; import AddonError from "../structs/addonerror";
import Settings from "./settingsmanager"; import Settings from "./settingsmanager";
import Strings from "./strings"; import Strings from "./strings";
import IPC from "./ipc";
import Events from "./emitter"; import Events from "./emitter";
import Toasts from "../ui/toasts"; import Toasts from "../ui/toasts";
@ -12,11 +11,7 @@ import Modals from "../ui/modals";
import SettingsRenderer from "../ui/settings"; import SettingsRenderer from "../ui/settings";
const path = require("path"); const path = require("path");
const electron = require("electron");
const vm = require("vm"); const vm = require("vm");
// const electronRemote = require("electron").remote;
// window.$ = window.jQuery = function() {}
export default new class PluginManager extends AddonManager { export default new class PluginManager extends AddonManager {
get name() {return "PluginManager";} get name() {return "PluginManager";}

View File

@ -81,7 +81,7 @@ export default class Utilities {
} }
static isEmpty(obj) { static isEmpty(obj) {
if (obj == null || obj == undefined || obj == "") return true; if (obj === null || typeof(undefined) === "undefined" || obj === "") return true;
if (typeof(obj) !== "object") return false; if (typeof(obj) !== "object") return false;
if (Array.isArray(obj)) return obj.length == 0; if (Array.isArray(obj)) return obj.length == 0;
for (const key in obj) { for (const key in obj) {
@ -121,6 +121,25 @@ export default class Utilities {
return proxy; return proxy;
} }
/**
* Protects prototypes from external assignment.
*
* Needs some work before full usage
* @param {Class} Component - component with prototype to protect
*/
static protectPrototype(Component) {
const descriptors = Object.getOwnPropertyDescriptors(Component.prototype);
for (const name in descriptors) {
const descriptor = descriptors[name];
descriptor.configurable = false;
descriptor.enumerable = false;
if (Object.prototype.hasOwnProperty.call(descriptor, "get")) descriptor.set = () => Logger.warn("protectPrototype", "Addon policy for plugins #5 https://github.com/rauenzi/BetterDiscordApp/wiki/Addon-Policies#plugins");
if (Object.prototype.hasOwnProperty.call(descriptor, "value") && typeof(descriptor.value) === "function") descriptor.value.bind(Component.prototype);
if (Object.prototype.hasOwnProperty.call(descriptor, "writable")) descriptor.writable = false;
}
Object.defineProperties(Component.prototype, descriptors);
}
/** /**
* Deep extends an object with a set of other objects. Objects later in the list * Deep extends an object with a set of other objects. Objects later in the list
* of `extenders` have priority, that is to say if one sets a key to be a primitive, * of `extenders` have priority, that is to say if one sets a key to be a primitive,
@ -265,9 +284,8 @@ export default class Utilities {
let curr = this.getReactInstance(node); let curr = this.getReactInstance(node);
for (curr = curr && curr.return; curr !== null; curr = curr.return) { for (curr = curr && curr.return; curr !== null; curr = curr.return) {
if (curr === null) continue;
const owner = curr.stateNode; const owner = curr.stateNode;
if (curr !== null && !(owner instanceof HTMLElement) && classFilter(curr) && filter(owner)) return owner; if (!(owner instanceof HTMLElement) && classFilter(curr) && filter(owner)) return owner;
} }
return null; return null;

View File

@ -170,19 +170,6 @@ export default class WebpackModules {
*/ */
static getModules(filter) {return this.getModule(filter, false);} static getModules(filter) {return this.getModule(filter, false);}
/**
* Finds a module by its name.
* @param {String} name The name of the module
* @param {Function} fallback A function to use to filter modules if not finding a known module
* @return {Any}
*/
// static getModuleByName(name, fallback) {
// if (DiscordModules.hasOwnProperty(name)) return DiscordModules[name];
// if (!fallback) return undefined;
// const module = this.getModule(fallback, true);
// return module ? DiscordModules[name] = module : undefined;
// }
/** /**
* Finds a module by its display name. * Finds a module by its display name.
* @param {String} name The display name of the module * @param {String} name The display name of the module

View File

@ -140,16 +140,6 @@ export default new class PublicServersConnection {
} }
async connect() { async connect() {
// return new Promise(resolve => {
// const joinWindow = new BrowserWindow(this.windowOptions);
// const url = `https://auth.discordservers.com/connect?scopes=guilds.join&previousUrl=${this.connectEndPoint}`;
// joinWindow.webContents.on("did-navigate", (event, navUrl) => {
// if (navUrl != this.connectEndPoint) return;
// joinWindow.close();
// resolve();
// });
// joinWindow.loadURL(url);
// });
await IPC.openWindow(this.authorizeEndPoint, { await IPC.openWindow(this.authorizeEndPoint, {
windowOptions: this.windowOptions, windowOptions: this.windowOptions,
closeOnUrl: this.connectEndPoint closeOnUrl: this.connectEndPoint

View File

@ -13,11 +13,16 @@
} }
.emote { .emote {
height: 1.45em; object-fit: contain;
width: 1.375em;
height: 1.375em;
vertical-align: bottom;
} }
.emote.jumboable { .emote.jumboable {
height: 2rem; width: 3rem;
height: 3rem;
min-height: 3rem;
} }
.fav { .fav {

View File

@ -31,8 +31,6 @@ export default class BDEmote extends React.Component {
onMouseEnter() { onMouseEnter() {
if (!this.state.shouldAnimate && this.animateOnHover) this.setState({shouldAnimate: true}); if (!this.state.shouldAnimate && this.animateOnHover) this.setState({shouldAnimate: true});
// if (!this.state.isFavorite && EmoteMenu.favoriteEmotes[this.label]) this.setState({isFavorite: true});
// else if (this.state.isFavorite && !EmoteMenu.favoriteEmotes[this.label]) this.setState({isFavorite: false});
} }
onMouseLeave() { onMouseLeave() {

View File

@ -195,7 +195,6 @@ export default class Modals {
componentDidMount() { componentDidMount() {
if (this.element instanceof Node) this.elementRef.current.appendChild(this.element); if (this.element instanceof Node) this.elementRef.current.appendChild(this.element);
// if (typeof(this.element) === "string") this.elementRef.current.appendChild(this.element);
} }
render() { render() {

View File

@ -20,7 +20,6 @@ export default class ServerCard extends React.Component {
super(props); super(props);
if (!this.props.server.iconUrl) this.props.server.iconUrl = this.props.defaultAvatar(); if (!this.props.server.iconUrl) this.props.server.iconUrl = this.props.defaultAvatar();
this.state = { this.state = {
imageError: false,
joined: this.props.joined joined: this.props.joined
}; };
this.join = this.join.bind(this); this.join = this.join.bind(this);
@ -60,7 +59,6 @@ export default class ServerCard extends React.Component {
handleError() { handleError() {
this.props.server.iconUrl = this.props.defaultAvatar(); this.props.server.iconUrl = this.props.defaultAvatar();
this.setState({imageError: true});
} }
async join() { async join() {

View File

@ -93,13 +93,14 @@ export default class PublicServers extends React.Component {
if (this.state.loading) return; if (this.state.loading) return;
await new Promise(resolve => this.setState({tab: id}, resolve)); await new Promise(resolve => this.setState({tab: id}, resolve));
if (this.state.tab === "Featured" || this.state.tab == "Popular") { if (this.state.tab === "Featured" || this.state.tab == "Popular") {
return this.setState({results: { const fakeResults = {
servers: this[this.state.tab.toLowerCase()], servers: this[this.state.tab.toLowerCase()],
size: this[this.state.tab.toLowerCase()].length, size: this[this.state.tab.toLowerCase()].length,
total: this[this.state.tab.toLowerCase()].length, total: this[this.state.tab.toLowerCase()].length,
page: 1, page: 1,
numPages: 1 numPages: 1
}}); };
return this.setState({results: fakeResults});
} }
this.search(); this.search();

View File

@ -89,9 +89,6 @@ export default new class SettingsRenderer {
if (typeof(panel.label) !== "string") panel.label = panel.label.toString(); if (typeof(panel.label) !== "string") panel.label = panel.label.toString();
insert(panel); insert(panel);
} }
// for (const tab of returnValue) {
// if (!tab.className) tab.className = `${DOM.escapeID(tab.section).toLowerCase()}-tab`;
// }
}); });
this.forceUpdate(); this.forceUpdate();
} }

View File

@ -36,9 +36,6 @@ export default class AddonCard extends React.Component {
constructor(props) { constructor(props) {
super(props); super(props);
this.state = {
settingsOpen: false
};
this.settingsPanel = ""; this.settingsPanel = "";
this.panelRef = React.createRef(); this.panelRef = React.createRef();

View File

@ -49,15 +49,4 @@ export default class Select extends React.Component {
{this.state.open && this.options} {this.state.open && this.options}
</div>; </div>;
} }
} }
// return <div className="bd-select-wrap">
// <label className="bd-label">{this.props.label}</label>
// <div className={`bd-select${style}${isOpen}`} onClick={this.showMenu} ref={this.dropdown}>
// <div className="bd-select-controls">
// <div className="bd-select-value">{this.selected.label}</div>
// <Arrow className="bd-select-arrow" />
// </div>
// </div>
// {this.state.open && this.options}
// </div>;

View File

@ -1,4 +1,3 @@
const fs = require("fs");
const path = require("path"); const path = require("path");
const asar = require("asar"); const asar = require("asar");
@ -8,14 +7,6 @@ const buildPackage = require("./package");
const dist = path.resolve(__dirname, "..", "dist"); const dist = path.resolve(__dirname, "..", "dist");
const bundleFile = path.join(dist, "betterdiscord.asar"); const bundleFile = path.join(dist, "betterdiscord.asar");
const cleanOldAsar = function() {
console.log("");
console.log("Ensuring clean build");
if (!fs.existsSync(bundleFile)) return console.log(" ✅ Nothing to clean up");
fs.unlinkSync(bundleFile);
console.log(` ✅ Removed old bundle ${bundleFile}`);
};
const makeBundle = function() { const makeBundle = function() {
console.log(""); console.log("");
console.log("Generating bundle"); console.log("Generating bundle");