diff options
author | Vendicated <vendicated@riseup.net> | 2022-08-31 20:47:07 +0200 |
---|---|---|
committer | Vendicated <vendicated@riseup.net> | 2022-08-31 20:47:07 +0200 |
commit | a7ccbcfca4f181790b86199a7f31d1ae19e0253f (patch) | |
tree | 56be6cef5437dff886dcefa04f930780d552c68c | |
parent | 98cb301df53305f397ac6e1b4e603c930820f228 (diff) | |
download | Vencord-a7ccbcfca4f181790b86199a7f31d1ae19e0253f.tar.gz Vencord-a7ccbcfca4f181790b86199a7f31d1ae19e0253f.tar.bz2 Vencord-a7ccbcfca4f181790b86199a7f31d1ae19e0253f.zip |
Refactor webpack; Add ErrorBoundary
-rw-r--r-- | src/Vencord.ts | 6 | ||||
-rw-r--r-- | src/VencordNative.ts | 4 | ||||
-rw-r--r-- | src/api/settings.ts | 2 | ||||
-rw-r--r-- | src/components/ErrorBoundary.tsx | 71 | ||||
-rw-r--r-- | src/components/Settings.tsx | 52 | ||||
-rw-r--r-- | src/utils/misc.tsx | 25 | ||||
-rw-r--r-- | src/webpack/common.ts | 31 | ||||
-rw-r--r-- | src/webpack/index.ts | 106 | ||||
-rw-r--r-- | src/webpack/webpack.ts | 84 | ||||
-rw-r--r-- | tsconfig.json | 2 |
10 files changed, 233 insertions, 150 deletions
diff --git a/src/Vencord.ts b/src/Vencord.ts index 8ef272b..0f2b25a 100644 --- a/src/Vencord.ts +++ b/src/Vencord.ts @@ -1,7 +1,11 @@ export * as Plugins from "./plugins"; export * as Webpack from "./webpack"; export * as Api from "./api"; -export * as Components from "./components"; import "./utils/patchWebpack"; import "./utils/quickCss"; +import { waitFor } from "./webpack"; + +export let Components; + +waitFor("useState", () => setTimeout(() => import("./components").then(mod => Components = mod), 0));
\ No newline at end of file diff --git a/src/VencordNative.ts b/src/VencordNative.ts index fc1e690..755c471 100644 --- a/src/VencordNative.ts +++ b/src/VencordNative.ts @@ -8,7 +8,7 @@ export default { if (event in IPC_EVENTS) ipcRenderer.send(event, ...args); else throw new Error(`Event ${event} not allowed.`); }, - sendSync(event: string, ...args: any[]) { + sendSync<T = any>(event: string, ...args: any[]): T { if (event in IPC_EVENTS) return ipcRenderer.sendSync(event, ...args); else throw new Error(`Event ${event} not allowed.`); }, @@ -16,7 +16,7 @@ export default { if (event in IPC_EVENTS) ipcRenderer.on(event, listener); else throw new Error(`Event ${event} not allowed.`); }, - invoke(event: string, ...args: any[]) { + invoke<T = any>(event: string, ...args: any[]): Promise<T> { if (event in IPC_EVENTS) return ipcRenderer.invoke(event, ...args); else throw new Error(`Event ${event} not allowed.`); } diff --git a/src/api/settings.ts b/src/api/settings.ts index 253c726..0b27b30 100644 --- a/src/api/settings.ts +++ b/src/api/settings.ts @@ -1,6 +1,6 @@ import plugins from "plugins"; import IpcEvents from "../utils/IpcEvents"; -import { React } from "../webpack"; +import { React } from "../webpack/common"; import { mergeDefaults } from '../utils/misc'; interface Settings { diff --git a/src/components/ErrorBoundary.tsx b/src/components/ErrorBoundary.tsx new file mode 100644 index 0000000..ae52838 --- /dev/null +++ b/src/components/ErrorBoundary.tsx @@ -0,0 +1,71 @@ +import Logger from "../utils/logger"; +import { Card, React } from "../webpack/common"; + +interface Props { + fallback?: React.ComponentType<React.PropsWithChildren<{ error: any; }>>; + onError?(error: Error, errorInfo: React.ErrorInfo): void; +} + +const color = "#e78284"; + +const logger = new Logger("React ErrorBoundary", color); + +const NO_ERROR = {}; + +export default class ErrorBoundary extends React.Component<React.PropsWithChildren<Props>> { + static wrap<T = any>(Component: React.ComponentType<T>): (props: T) => React.ReactElement { + return (props) => ( + <ErrorBoundary> + <Component {...props} /> + </ErrorBoundary> + ); + } + + state = { + error: NO_ERROR as any, + message: "" + }; + + static getDerivedStateFromError(error: any) { + + return { + error: error?.stack?.replace(/https:\/\/\S+\/assets\//g, "") || error?.message || String(error) + }; + } + + componentDidCatch(error: Error, errorInfo: React.ErrorInfo) { + this.props.onError?.(error, errorInfo); + logger.error("A component threw an Error\n", error); + logger.error("Component Stack", errorInfo.componentStack); + } + + render() { + if (this.state.error === NO_ERROR) return this.props.children; + + if (this.props.fallback) + return <this.props.fallback + children={this.props.children} + error={this.state.error} + />; + + return ( + <Card style={{ + overflow: "hidden", + padding: "2em", + backgroundColor: color + "30", + borderColor: color, + color: "var(--text-normal)" + }}> + <h1>Oh no!</h1> + <p> + An error occurred while rendering this Component. More info can be found below + and in your console. + </p> + <code> + <pre>{this.state.error} + </pre> + </code> + </Card> + ); + } +}
\ No newline at end of file diff --git a/src/components/Settings.tsx b/src/components/Settings.tsx index 4499c9f..19f6dd2 100644 --- a/src/components/Settings.tsx +++ b/src/components/Settings.tsx @@ -1,66 +1,50 @@ -import { lazy, LazyComponent, useAwaiter } from "../utils/misc"; -import { findByDisplayName, Forms } from '../webpack'; +import { useAwaiter } from "../utils/misc"; import Plugins from 'plugins'; import { useSettings } from "../api/settings"; -import { findByProps } from '../webpack/index'; import IpcEvents from "../utils/IpcEvents"; -// Lazy spam because this is ran before React is a thing. Todo: Fix that and clean this up lmao +import { Button, ButtonProps, Flex, Switch, Forms } from "../webpack/common"; +import ErrorBoundary from "./ErrorBoundary"; -const SwitchItem = LazyComponent<React.PropsWithChildren<{ - value: boolean; - onChange: (v: boolean) => void; - note?: string; - tooltipNote?: string; - disabled?: boolean; -}>>(() => findByDisplayName("SwitchItem").default); - -const getButton = lazy(() => findByProps("ButtonLooks", "default")); -const Button = LazyComponent(() => getButton().default); -const getFlex = lazy(() => findByDisplayName("Flex")); -const Flex = LazyComponent(() => getFlex().default); -const FlexChild = LazyComponent(() => getFlex().default.Child); -const getMargins = lazy(() => findByProps("marginTop8", "marginBottom8")); - -export default function Settings(props) { - const settingsDir = useAwaiter(() => VencordNative.ipc.invoke(IpcEvents.GET_SETTINGS_DIR), "Loading..."); +export default ErrorBoundary.wrap(function Settings(props) { + const [settingsDir, , settingsDirPending] = useAwaiter(() => VencordNative.ipc.invoke<string>(IpcEvents.GET_SETTINGS_DIR), "Loading..."); const settings = useSettings(); return ( <Forms.FormSection tag="h1" title="Vencord"> <Forms.FormText>SettingsDir: {settingsDir}</Forms.FormText> - <Flex className={getMargins().marginTop8 + " " + getMargins().marginBottom8}> - <FlexChild> + <Flex style={{ marginTop: "8px", marginBottom: "8px" }}> + <Flex.Child> <Button onClick={() => VencordNative.ipc.invoke(IpcEvents.OPEN_PATH, settingsDir)} - size={getButton().ButtonSizes.SMALL} - disabled={settingsDir === "Loading..."} + size={ButtonProps.ButtonSizes.SMALL} + disabled={settingsDirPending} > Launch Directory </Button> - </FlexChild> - <FlexChild> + </Flex.Child> + <Flex.Child> <Button onClick={() => VencordNative.ipc.invoke(IpcEvents.OPEN_PATH, settingsDir + "/quickCss.css")} - size={getButton().ButtonSizes.SMALL} + size={ButtonProps.ButtonSizes.SMALL} disabled={settingsDir === "Loading..."} > Open QuickCSS File </Button> - </FlexChild> + </Flex.Child> </Flex> <Forms.FormTitle tag="h5">Settings</Forms.FormTitle> - <SwitchItem + <Switch value={settings.unsafeRequire} onChange={v => settings.unsafeRequire = v} note="Enables VencordNative.require. Useful for testing, very bad for security. Leave this off unless you need it." > Enable Ensafe Require - </SwitchItem> + </Switch> <Forms.FormDivider /> <Forms.FormTitle tag="h5">Plugins</Forms.FormTitle> {Plugins.map(p => ( - <SwitchItem + <Switch disabled={p.required === true} key={p.name} value={settings.plugins[p.name].enabled} @@ -76,9 +60,9 @@ export default function Settings(props) { tooltipNote={p.required ? "This plugin is required. Thus you cannot disable it." : undefined} > {p.name} - </SwitchItem> + </Switch> )) } </Forms.FormSection > ); -}
\ No newline at end of file +});
\ No newline at end of file diff --git a/src/utils/misc.tsx b/src/utils/misc.tsx index ded052b..aca7661 100644 --- a/src/utils/misc.tsx +++ b/src/utils/misc.tsx @@ -1,4 +1,4 @@ -import { React } from "../webpack"; +import { React } from "../webpack/common"; /** * Makes a lazy function. On first call, the value is computed. @@ -16,17 +16,28 @@ export function lazy<T>(factory: () => T): () => T { * Await a promise * @param factory Factory * @param fallbackValue The fallback value that will be used until the promise resolved - * @returns A state that will either be null or the result of the promise + * @returns [value, error, isPending] */ -export function useAwaiter<T>(factory: () => Promise<T>, fallbackValue: T | null = null): T | null { - const [res, setRes] = React.useState<T | null>(fallbackValue); +export function useAwaiter<T>(factory: () => Promise<T>): [T | null, any, boolean]; +export function useAwaiter<T>(factory: () => Promise<T>, fallbackValue: T): [T, any, boolean]; +export function useAwaiter<T>(factory: () => Promise<T>, fallbackValue: T | null = null): [T | null, any, boolean] { + const [state, setState] = React.useState({ + value: fallbackValue, + error: null as any, + pending: true + }); React.useEffect(() => { - factory().then(setRes); + let isAlive = true; + factory() + .then(value => isAlive && setState({ value, error: null, pending: false })) + .catch(error => isAlive && setState({ value: null, error, pending: false })); + + return () => void (isAlive = false); }, []); - return res; -} + return [state.value, state.error, state.pending]; +}; /** * A lazy component. The factory method is called on first render. For example useful diff --git a/src/webpack/common.ts b/src/webpack/common.ts new file mode 100644 index 0000000..f678a94 --- /dev/null +++ b/src/webpack/common.ts @@ -0,0 +1,31 @@ +import { startAll } from "../plugins"; +import { waitFor, filters } from './webpack'; + +export let FluxDispatcher: any; +export let React: typeof import("react"); +export let UserStore: any; +export let Forms: any; +export let Button: any; +export let ButtonProps: any; +export let Switch: any; +export let Flex: any; +export let Card: any; + +waitFor("useState", m => React = m); +waitFor(["dispatch", "subscribe"], m => { + FluxDispatcher = m; + const cb = () => { + m.unsubscribe("CONNECTION_OPEN", cb); + startAll(); + }; + m.subscribe("CONNECTION_OPEN", cb); +}); +waitFor(["getCurrentUser", "initialize"], m => UserStore = m); +waitFor("FormSection", m => Forms = m); +waitFor(["ButtonLooks", "default"], m => { + Button = m.default; + ButtonProps = m; +}); +waitFor(filters.byDisplayName("SwitchItem"), m => Switch = m.default); +waitFor(filters.byDisplayName("Flex"), m => Flex = m.default); +waitFor(filters.byDisplayName("Card"), m => Card = m.default);
\ No newline at end of file diff --git a/src/webpack/index.ts b/src/webpack/index.ts index 2c5a455..a388dbd 100644 --- a/src/webpack/index.ts +++ b/src/webpack/index.ts @@ -1,104 +1,2 @@ -import { startAll } from "../plugins"; - -let webpackCache: typeof window.webpackChunkdiscord_app; - -export const subscriptions = new Map<FilterFn, CallbackFn>(); -export const listeners = new Set<CallbackFn>(); - -type FilterFn = (mod: any) => boolean; -type CallbackFn = (mod: any) => void; - -export let React: typeof import("react"); -export let FluxDispatcher: any; -export let Forms: any; -export let UserStore: any; - -export function _initWebpack(instance: typeof window.webpackChunkdiscord_app) { - if (webpackCache !== void 0) throw "no."; - - webpackCache = instance.push([[Symbol()], {}, (r) => r.c]); - instance.pop(); - - // Abandon Hope All Ye Who Enter Here - - let started = false; - waitFor("getCurrentUser", x => UserStore = x); - waitFor(["dispatch", "subscribe"], x => { - FluxDispatcher = x; - const cb = () => { - console.info("Connection open"); - x.unsubscribe("CONNECTION_OPEN", cb); - startAll(); - }; - x.subscribe("CONNECTION_OPEN", cb); - }); - waitFor("useState", x => (React = x)); - waitFor("FormSection", x => Forms = x); -} - -export function find(filter: FilterFn, getDefault = true) { - if (typeof filter !== "function") - throw new Error("Invalid filter. Expected a function got", filter); - - for (const key in webpackCache) { - const mod = webpackCache[key]; - if (mod?.exports && filter(mod.exports)) - return mod.exports; - if (mod?.exports?.default && filter(mod.exports.default)) - return getDefault ? mod.exports.default : mod.exports; - } - - return null; -} - -export function findAll(filter: FilterFn, getDefault = true) { - if (typeof filter !== "function") throw new Error("Invalid filter. Expected a function got", filter); - - const ret = [] as any[]; - for (const key in webpackCache) { - const mod = webpackCache[key]; - if (mod?.exports && filter(mod.exports)) ret.push(mod.exports); - if (mod?.exports?.default && filter(mod.exports.default)) ret.push(getDefault ? mod.exports.default : mod.exports); - } - - return ret; -} - -export const filters = { - byProps: (props: string[]): FilterFn => - props.length === 1 - ? m => m[props[0]] !== void 0 - : m => props.every(p => m[p] !== void 0), - byDisplayName: (deezNuts: string): FilterFn => m => m.default?.displayName === deezNuts -}; - -export function findByProps(...props: string[]) { - return find(filters.byProps(props)); -} - -export function findAllByProps(...props: string[]) { - return findAll(filters.byProps(props)); -} - -export function findByDisplayName(deezNuts: string) { - return find(filters.byDisplayName(deezNuts)); -} - -export function waitFor(filter: string | string[] | FilterFn, callback: CallbackFn) { - if (typeof filter === "string") filter = filters.byProps([filter]); - else if (Array.isArray(filter)) filter = filters.byProps(filter); - else if (typeof filter !== "function") throw new Error("filter must be a string, string[] or function, got", filter); - - const existing = find(filter!); - if (existing) return void callback(existing); - - subscriptions.set(filter, callback); -} - -export function addListener(callback: CallbackFn) { - listeners.add(callback); -} - -export function removeListener(callback: CallbackFn) { - listeners.delete(callback); -}
\ No newline at end of file +export * from "./webpack"; +export * as Common from "./common";
\ No newline at end of file diff --git a/src/webpack/webpack.ts b/src/webpack/webpack.ts new file mode 100644 index 0000000..a616ac2 --- /dev/null +++ b/src/webpack/webpack.ts @@ -0,0 +1,84 @@ +let webpackCache: typeof window.webpackChunkdiscord_app; + +export type FilterFn = (mod: any) => boolean; + +export const filters = { + byProps: (props: string[]): FilterFn => + props.length === 1 + ? m => m[props[0]] !== void 0 + : m => props.every(p => m[p] !== void 0), + byDisplayName: (deezNuts: string): FilterFn => m => m.default?.displayName === deezNuts +}; + +export const subscriptions = new Map<FilterFn, CallbackFn>(); +export const listeners = new Set<CallbackFn>(); + +export type CallbackFn = (mod: any) => void; + +export function _initWebpack(instance: typeof window.webpackChunkdiscord_app) { + if (webpackCache !== void 0) throw "no."; + + webpackCache = instance.push([[Symbol()], {}, (r) => r.c]); + instance.pop(); +} + +export function find(filter: FilterFn, getDefault = true) { + if (typeof filter !== "function") + throw new Error("Invalid filter. Expected a function got", filter); + + for (const key in webpackCache) { + const mod = webpackCache[key]; + if (mod?.exports && filter(mod.exports)) + return mod.exports; + if (mod?.exports?.default && filter(mod.exports.default)) + return getDefault ? mod.exports.default : mod.exports; + } + + return null; +} + +export function findAll(filter: FilterFn, getDefault = true) { + if (typeof filter !== "function") throw new Error("Invalid filter. Expected a function got", filter); + + const ret = [] as any[]; + for (const key in webpackCache) { + const mod = webpackCache[key]; + if (mod?.exports && filter(mod.exports)) ret.push(mod.exports); + if (mod?.exports?.default && filter(mod.exports.default)) ret.push(getDefault ? mod.exports.default : mod.exports); + } + + return ret; +} + + + +export function findByProps(...props: string[]) { + return find(filters.byProps(props)); +} + +export function findAllByProps(...props: string[]) { + return findAll(filters.byProps(props)); +} + +export function findByDisplayName(deezNuts: string) { + return find(filters.byDisplayName(deezNuts)); +} + +export function waitFor(filter: string | string[] | FilterFn, callback: CallbackFn) { + if (typeof filter === "string") filter = filters.byProps([filter]); + else if (Array.isArray(filter)) filter = filters.byProps(filter); + else if (typeof filter !== "function") throw new Error("filter must be a string, string[] or function, got", filter); + + const existing = find(filter!); + if (existing) return void callback(existing); + + subscriptions.set(filter, callback); +} + +export function addListener(callback: CallbackFn) { + listeners.add(callback); +} + +export function removeListener(callback: CallbackFn) { + listeners.delete(callback); +}
\ No newline at end of file diff --git a/tsconfig.json b/tsconfig.json index d17ff09..6489d93 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -9,7 +9,7 @@ "noImplicitAny": false, "target": "ESNEXT", // https://esbuild.github.io/api/#jsx-factory - "jsxFactory": "Vencord.Webpack.React.createElement", + "jsxFactory": "Vencord.Webpack.Common.React.createElement", "jsx": "react" }, "include": ["src/**/*"] |