Merge branch 'immediate-finds' into immediate-finds-modules-proxy

This commit is contained in:
Nuckyz 2024-07-02 20:17:16 -03:00
commit d90bcdb063
No known key found for this signature in database
GPG key ID: 440BF8296E1C4AD9
12 changed files with 305 additions and 189 deletions

View file

@ -1,6 +1,12 @@
{ {
"extends": "stylelint-config-standard", "extends": "stylelint-config-standard",
"rules": { "rules": {
"indentation": 4 "indentation": 4,
"selector-class-pattern": [
"^[a-z][a-zA-Z0-9]*(-[a-z0-9][a-zA-Z0-9]*)*$",
{
"message": "Expected class selector to be kebab-case with camelCase segments"
}
]
} }
} }

View file

@ -392,6 +392,21 @@ export function PaintbrushIcon(props: IconProps) {
); );
} }
export function PencilIcon(props: IconProps) {
return (
<Icon
{...props}
className={classes(props.className, "vc-pencil-icon")}
viewBox="0 0 24 24"
>
<path
fill="currentColor"
d="m13.96 5.46 4.58 4.58a1 1 0 0 0 1.42 0l1.38-1.38a2 2 0 0 0 0-2.82l-3.18-3.18a2 2 0 0 0-2.82 0l-1.38 1.38a1 1 0 0 0 0 1.42ZM2.11 20.16l.73-4.22a3 3 0 0 1 .83-1.61l7.87-7.87a1 1 0 0 1 1.42 0l4.58 4.58a1 1 0 0 1 0 1.42l-7.87 7.87a3 3 0 0 1-1.6.83l-4.23.73a1.5 1.5 0 0 1-1.73-1.73Z"
/>
</Icon>
);
}
const WebsiteIconDark = "/assets/e1e96d89e192de1997f73730db26e94f.svg"; const WebsiteIconDark = "/assets/e1e96d89e192de1997f73730db26e94f.svg";
const WebsiteIconLight = "/assets/730f58bcfd5a57a5e22460c445a0c6cf.svg"; const WebsiteIconLight = "/assets/730f58bcfd5a57a5e22460c445a0c6cf.svg";
const GithubIconLight = "/assets/3ff98ad75ac94fa883af5ed62d17c459.svg"; const GithubIconLight = "/assets/3ff98ad75ac94fa883af5ed62d17c459.svg";

View file

@ -19,21 +19,21 @@
import { useSettings } from "@api/Settings"; import { useSettings } from "@api/Settings";
import { classNameFactory } from "@api/Styles"; import { classNameFactory } from "@api/Styles";
import { Flex } from "@components/Flex"; import { Flex } from "@components/Flex";
import { DeleteIcon } from "@components/Icons"; import { DeleteIcon, FolderIcon, PaintbrushIcon, PencilIcon, PlusIcon, RestartIcon } from "@components/Icons";
import { Link } from "@components/Link"; import { Link } from "@components/Link";
import PluginModal from "@components/PluginSettings/PluginModal"; import { openPluginModal } from "@components/PluginSettings/PluginModal";
import type { UserThemeHeader } from "@main/themes"; import type { UserThemeHeader } from "@main/themes";
import { openInviteModal } from "@utils/discord"; import { openInviteModal } from "@utils/discord";
import { Margins } from "@utils/margins"; import { Margins } from "@utils/margins";
import { classes } from "@utils/misc"; import { classes } from "@utils/misc";
import { openModal } from "@utils/modal";
import { showItemInFolder } from "@utils/native"; import { showItemInFolder } from "@utils/native";
import { useAwaiter } from "@utils/react"; import { useAwaiter } from "@utils/react";
import { findByProps, findComponent } from "@webpack"; import { findByProps, findComponent } from "@webpack";
import { Button, Card, Forms, React, showToast, TabBar, TextArea, useEffect, useRef, useState } from "@webpack/common"; import { Card, Forms, React, showToast, TabBar, TextArea, useEffect, useRef, useState } from "@webpack/common";
import type { Ref, SyntheticEvent } from "react"; import type { Ref, SyntheticEvent } from "react";
import { AddonCard } from "./AddonCard"; import { AddonCard } from "./AddonCard";
import { QuickAction, QuickActionCard } from "./quickActions";
import { SettingsTab, wrapTab } from "./shared"; import { SettingsTab, wrapTab } from "./shared";
type FileInputProps = { type FileInputProps = {
@ -212,14 +212,13 @@ function ThemesTab() {
</Card> </Card>
<Forms.FormSection title="Local Themes"> <Forms.FormSection title="Local Themes">
<Card className="vc-settings-quick-actions-card"> <QuickActionCard>
<> <>
{IS_WEB ? {IS_WEB ?
( (
<Button <QuickAction
size={Button.Sizes.SMALL} text={
disabled={themeDirPending} <span style={{ position: "relative" }}>
>
Upload Theme Upload Theme
<FileInput <FileInput
ref={fileInputRef} ref={fileInputRef}
@ -227,45 +226,38 @@ function ThemesTab() {
multiple={true} multiple={true}
filters={[{ extensions: ["css"] }]} filters={[{ extensions: ["css"] }]}
/> />
</Button> </span>
}
Icon={PlusIcon}
/>
) : ( ) : (
<Button <QuickAction
onClick={() => showItemInFolder(themeDir!)} text="Open Themes Folder"
size={Button.Sizes.SMALL} action={() => showItemInFolder(themeDir!)}
disabled={themeDirPending} disabled={themeDirPending}
> Icon={FolderIcon}
Open Themes Folder />
</Button>
)} )}
<Button <QuickAction
onClick={refreshLocalThemes} text="Load missing Themes"
size={Button.Sizes.SMALL} action={refreshLocalThemes}
> Icon={RestartIcon}
Load missing Themes />
</Button> <QuickAction
<Button text="Edit QuickCSS"
onClick={() => VencordNative.quickCss.openEditor()} action={() => VencordNative.quickCss.openEditor()}
size={Button.Sizes.SMALL} Icon={PaintbrushIcon}
> />
Edit QuickCSS
</Button>
{Vencord.Plugins.isPluginEnabled("ClientTheme") && ( {Vencord.Plugins.isPluginEnabled("ClientTheme") && (
<Button <QuickAction
onClick={() => openModal(modalProps => ( text="Edit ClientTheme"
<PluginModal action={() => openPluginModal(Vencord.Plugins.plugins.ClientTheme)}
{...modalProps} Icon={PencilIcon}
plugin={Vencord.Plugins.plugins.ClientTheme}
onRestartNeeded={() => { }}
/> />
))}
size={Button.Sizes.SMALL}
>
Edit ClientTheme
</Button>
)} )}
</> </>
</Card> </QuickActionCard>
<div className={cl("grid")}> <div className={cl("grid")}>
{userThemes?.map(theme => ( {userThemes?.map(theme => (
@ -282,7 +274,7 @@ function ThemesTab() {
/> />
))} ))}
</div> </div>
</Forms.FormSection> </Forms.FormSection >
</> </>
); );
} }

View file

@ -21,15 +21,16 @@ import { useSettings } from "@api/Settings";
import { classNameFactory } from "@api/Styles"; import { classNameFactory } from "@api/Styles";
import DonateButton from "@components/DonateButton"; import DonateButton from "@components/DonateButton";
import { openPluginModal } from "@components/PluginSettings/PluginModal"; import { openPluginModal } from "@components/PluginSettings/PluginModal";
import { gitRemote } from "@shared/vencordUserAgent";
import { Margins } from "@utils/margins"; import { Margins } from "@utils/margins";
import { identity } from "@utils/misc"; import { identity } from "@utils/misc";
import { relaunch, showItemInFolder } from "@utils/native"; import { relaunch, showItemInFolder } from "@utils/native";
import { useAwaiter } from "@utils/react"; import { useAwaiter } from "@utils/react";
import { Button, Card, Forms, React, Select, Switch, TooltipContainer } from "@webpack/common"; import { Button, Card, Forms, React, Select, Switch } from "@webpack/common";
import { ComponentType } from "react";
import { Flex, FolderIcon, GithubIcon, LogIcon, PaintbrushIcon, RestartIcon } from ".."; import { Flex, FolderIcon, GithubIcon, LogIcon, PaintbrushIcon, RestartIcon } from "..";
import { openNotificationSettingsModal } from "./NotificationSettings"; import { openNotificationSettingsModal } from "./NotificationSettings";
import { QuickAction, QuickActionCard } from "./quickActions";
import { SettingsTab, wrapTab } from "./shared"; import { SettingsTab, wrapTab } from "./shared";
const cl = classNameFactory("vc-settings-"); const cl = classNameFactory("vc-settings-");
@ -41,17 +42,6 @@ type KeysOfType<Object, Type> = {
[K in keyof Object]: Object[K] extends Type ? K : never; [K in keyof Object]: Object[K] extends Type ? K : never;
}[keyof Object]; }[keyof Object];
const iconWithTooltip = (Icon: ComponentType<{ className?: string; }>, tooltip: string) => () => (
<TooltipContainer text={tooltip}>
<Icon className={cl("quick-actions-img")} />
</TooltipContainer>
);
const NotificationLogIcon = iconWithTooltip(LogIcon, "Open Notification Log");
const QuickCssIcon = iconWithTooltip(PaintbrushIcon, "Edit QuickCSS");
const RelaunchIcon = iconWithTooltip(RestartIcon, "Relaunch Discord");
const OpenSettingsDirIcon = iconWithTooltip(FolderIcon, "Open Settings Directory");
const OpenGithubIcon = iconWithTooltip(GithubIcon, "View Vencord's GitHub Repository");
function VencordSettings() { function VencordSettings() {
const [settingsDir, , settingsDirPending] = useAwaiter(VencordNative.settings.getSettingsDir, { const [settingsDir, , settingsDirPending] = useAwaiter(VencordNative.settings.getSettingsDir, {
@ -111,44 +101,37 @@ function VencordSettings() {
<SettingsTab title="Vencord Settings"> <SettingsTab title="Vencord Settings">
<DonateCard image={donateImage} /> <DonateCard image={donateImage} />
<Forms.FormSection title="Quick Actions"> <Forms.FormSection title="Quick Actions">
<Card className={cl("quick-actions-card")}> <QuickActionCard>
<Button <QuickAction
onClick={openNotificationLogModal} Icon={LogIcon}
look={Button.Looks.BLANK} text="Notification Log"
> action={openNotificationLogModal}
<NotificationLogIcon /> />
</Button> <QuickAction
<Button Icon={PaintbrushIcon}
onClick={() => VencordNative.quickCss.openEditor()} text="Edit QuickCSS"
look={Button.Looks.BLANK} action={() => VencordNative.quickCss.openEditor()}
> />
<QuickCssIcon />
</Button>
{!IS_WEB && ( {!IS_WEB && (
<Button <QuickAction
onClick={relaunch} Icon={RestartIcon}
look={Button.Looks.BLANK} text="Relaunch Discord"
> action={relaunch}
<RelaunchIcon /> />
</Button>
)} )}
{!IS_WEB && ( {!IS_WEB && (
<Button <QuickAction
onClick={() => showItemInFolder(settingsDir)} Icon={FolderIcon}
look={Button.Looks.BLANK} text="Open Settings Folder"
disabled={settingsDirPending} action={() => showItemInFolder(settingsDir)}
> />
<OpenSettingsDirIcon />
</Button>
)} )}
<Button <QuickAction
onClick={() => VencordNative.native.openExternal("https://github.com/Vendicated/Vencord")} Icon={GithubIcon}
look={Button.Looks.BLANK} text="View Source Code"
disabled={settingsDirPending} action={() => VencordNative.native.openExternal("https://github.com/" + gitRemote)}
> />
<OpenGithubIcon /> </QuickActionCard>
</Button>
</Card>
</Forms.FormSection> </Forms.FormSection>
<Forms.FormDivider /> <Forms.FormDivider />

View file

@ -0,0 +1,34 @@
.vc-settings-quickActions-card {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(200px, max-content));
gap: 0.5em;
justify-content: center;
padding: 0.5em 0;
margin-bottom: 1em;
}
.vc-settings-quickActions-pill {
all: unset;
background: var(--background-secondary);
color: var(--header-secondary);
display: flex;
align-items: center;
gap: 0.5em;
padding: 8px 12px;
border-radius: 9999px;
}
.vc-settings-quickActions-pill:hover {
background: var(--background-secondary-alt);
}
.vc-settings-quickActions-pill:focus-visible {
outline: 2px solid var(--focus-primary);
outline-offset: 2px;
}
.vc-settings-quickActions-img {
width: 24px;
height: 24px;
}

View file

@ -0,0 +1,39 @@
/*
* Vencord, a Discord client mod
* Copyright (c) 2024 Vendicated and contributors
* SPDX-License-Identifier: GPL-3.0-or-later
*/
import "./quickActions.css";
import { classNameFactory } from "@api/Styles";
import { Card } from "@webpack/common";
import type { ComponentType, PropsWithChildren, ReactNode } from "react";
const cl = classNameFactory("vc-settings-quickActions-");
export interface QuickActionProps {
Icon: ComponentType<{ className?: string; }>;
text: ReactNode;
action?: () => void;
disabled?: boolean;
}
export function QuickAction(props: QuickActionProps) {
const { Icon, action, text, disabled } = props;
return (
<button className={cl("pill")} onClick={action} disabled={disabled}>
<Icon className={cl("img")} />
{text}
</button>
);
}
export function QuickActionCard(props: PropsWithChildren) {
return (
<Card className={cl("card")}>
{props.children}
</Card>
);
}

View file

@ -10,26 +10,6 @@
margin-bottom: -2px; margin-bottom: -2px;
} }
.vc-settings-quick-actions-card {
color: var(--text-normal);
padding: 1em;
display: flex;
justify-content: space-evenly;
gap: 1em;
flex-wrap: wrap;
align-items: center;
margin-bottom: 1em;
}
.vc-settings-quick-actions-card button {
min-width: unset;
}
.vc-settings-quick-actions-img {
width: 30px;
height: 30px;
}
.vc-settings-donate { .vc-settings-donate {
display: flex; display: flex;
flex-direction: row; flex-direction: row;

View file

@ -157,7 +157,7 @@ async function runReporter() {
if (filter.$$vencordProps != null) { if (filter.$$vencordProps != null) {
const filterName = filter.$$vencordProps[0]; const filterName = filter.$$vencordProps[0];
parsedFilter = `${filterName}(${filter.$$vencordProps.slice(1).map((arg: any) => JSON.stringify(arg)).join(", ")})`; parsedFilter = `${filterName}(${filter.$$vencordProps.slice(1).map((arg: any) => arg instanceof RegExp ? String(arg) : JSON.stringify(arg)).join(", ")})`;
} else { } else {
parsedFilter = String(filter).slice(0, 147) + "..."; parsedFilter = String(filter).slice(0, 147) + "...";
} }
@ -167,7 +167,7 @@ async function runReporter() {
logMessage += `(${JSON.stringify(code)}, {\n${parsedFailedMappers.map(([key, parsedFilter]) => `\t${key}: ${parsedFilter}`).join(",\n")}\n})`; logMessage += `(${JSON.stringify(code)}, {\n${parsedFailedMappers.map(([key, parsedFilter]) => `\t${key}: ${parsedFilter}`).join(",\n")}\n})`;
} else { } else {
logMessage += `(${filterName.length ? `${filterName}(` : ""}${parsedArgs.map(arg => JSON.stringify(arg)).join(", ")})${filterName.length ? ")" : ""}`; logMessage += `(${filterName.length ? `${filterName}(` : ""}${parsedArgs.map(arg => arg instanceof RegExp ? String(arg) : JSON.stringify(arg)).join(", ")})${filterName.length ? ")" : ""}`;
} }
ReporterLogger.log("Webpack Find Fail:", logMessage); ReporterLogger.log("Webpack Find Fail:", logMessage);

View file

@ -24,7 +24,7 @@ import { DevsById } from "./constants";
* Calls .join(" ") on the arguments * Calls .join(" ") on the arguments
* classes("one", "two") => "one two" * classes("one", "two") => "one two"
*/ */
export function classes(...classes: Array<string | null | undefined>) { export function classes(...classes: Array<string | null | undefined | false>) {
return classes.filter(Boolean).join(" "); return classes.filter(Boolean).join(" ");
} }

View file

@ -68,13 +68,24 @@ if (IS_DEV && IS_DISCORD_DESKTOP) {
}, 0); }, 0);
} }
export type PropsFilter = Array<string>;
export type CodeFilter = Array<string | RegExp>;
export type StoreNameFilter = string;
export type FilterFn = ((module: ModuleExports) => boolean) & { export type FilterFn = ((module: ModuleExports) => boolean) & {
$$vencordProps?: string[]; $$vencordProps?: Array<string | RegExp>;
$$vencordIsFactoryFilter?: boolean; $$vencordIsFactoryFilter?: boolean;
}; };
const stringMatches = (s: string, filter: CodeFilter) =>
filter.every(f =>
typeof f === "string"
? s.includes(f)
: (f.global && (f.lastIndex = 0), f.test(s))
);
export const filters = { export const filters = {
byProps: (...props: string[]): FilterFn => { byProps: (...props: PropsFilter): FilterFn => {
const filter: FilterFn = props.length === 1 const filter: FilterFn = props.length === 1
? m => m?.[props[0]] !== void 0 ? m => m?.[props[0]] !== void 0
: m => props.every(p => m?.[p] !== void 0); : m => props.every(p => m?.[p] !== void 0);
@ -83,28 +94,25 @@ export const filters = {
return filter; return filter;
}, },
byCode: (...code: string[]): FilterFn => { byCode: (...code: CodeFilter): FilterFn => {
code = code.map(canonicalizeMatch);
const filter: FilterFn = m => { const filter: FilterFn = m => {
if (typeof m !== "function") return false; if (typeof m !== "function") return false;
const s = String(m); return stringMatches(String(m), code);
for (const c of code) {
if (!s.includes(c)) return false;
}
return true;
}; };
filter.$$vencordProps = ["byCode", ...code]; filter.$$vencordProps = ["byCode", ...code];
return filter; return filter;
}, },
byStoreName: (name: string): FilterFn => { byStoreName: (name: StoreNameFilter): FilterFn => {
const filter: FilterFn = m => m?.constructor?.displayName === name; const filter: FilterFn = m => m?.constructor?.displayName === name;
filter.$$vencordProps = ["byStoreName", name]; filter.$$vencordProps = ["byStoreName", name];
return filter; return filter;
}, },
byComponentCode: (...code: string[]): FilterFn => { byComponentCode: (...code: CodeFilter): FilterFn => {
const byCodeFilter = filters.byCode(...code); const byCodeFilter = filters.byCode(...code);
const filter: FilterFn = m => { const filter: FilterFn = m => {
let inner = m; let inner = m;
@ -124,7 +132,7 @@ export const filters = {
return filter; return filter;
}, },
byFactoryCode: (...code: string[]): FilterFn => { byFactoryCode: (...code: CodeFilter): FilterFn => {
const byCodeFilter = filters.byCode(...code); const byCodeFilter = filters.byCode(...code);
byCodeFilter.$$vencordProps = ["byFactoryCode", ...code]; byCodeFilter.$$vencordProps = ["byFactoryCode", ...code];
@ -139,7 +147,7 @@ export const webpackSearchHistory = [] as Array<["waitFor" | "find" | "findCompo
function printFilter(filter: FilterFn) { function printFilter(filter: FilterFn) {
if (filter.$$vencordProps != null) { if (filter.$$vencordProps != null) {
const props = filter.$$vencordProps; const props = filter.$$vencordProps;
return `${props[0]}(${props.slice(1).map(arg => JSON.stringify(arg)).join(", ")})`; return `${props[0]}(${props.slice(1).map(arg => arg instanceof RegExp ? String(arg) : JSON.stringify(arg)).join(", ")})`;
} }
return String(filter); return String(filter);
@ -269,9 +277,9 @@ export function findComponent<T extends object = any>(filter: FilterFn, parse: (
* @param parse A function that takes the found component as its first argument and returns a component. Useful if you want to wrap the found component in something. Defaults to the original component * @param parse A function that takes the found component as its first argument and returns a component. Useful if you want to wrap the found component in something. Defaults to the original component
* @returns The component if found, or a noop component * @returns The component if found, or a noop component
*/ */
export function findExportedComponent<T extends object = any>(...props: string[] | [...string[], (component: ModuleExports) => LazyComponentType<T>]) { export function findExportedComponent<T extends object = any>(...props: PropsFilter | [...PropsFilter, (component: ModuleExports) => LazyComponentType<T>]) {
const parse = (typeof props.at(-1) === "function" ? props.pop() : m => m) as (component: ModuleExports) => LazyComponentType<T>; const parse = (typeof props.at(-1) === "function" ? props.pop() : m => m) as (component: ModuleExports) => LazyComponentType<T>;
const newProps = props as string[]; const newProps = props as PropsFilter;
const filter = filters.byProps(...newProps); const filter = filters.byProps(...newProps);
@ -314,9 +322,9 @@ export function findExportedComponent<T extends object = any>(...props: string[]
* @param parse A function that takes the found component as its first argument and returns a component. Useful if you want to wrap the found component in something. Defaults to the original component * @param parse A function that takes the found component as its first argument and returns a component. Useful if you want to wrap the found component in something. Defaults to the original component
* @returns The component if found, or a noop component * @returns The component if found, or a noop component
*/ */
export function findComponentByCode<T extends object = any>(...code: string[] | [...string[], (component: ModuleExports) => LazyComponentType<T>]) { export function findComponentByCode<T extends object = any>(...code: CodeFilter | [...CodeFilter, (component: ModuleExports) => LazyComponentType<T>]) {
const parse = (typeof code.at(-1) === "function" ? code.pop() : m => m) as (component: ModuleExports) => LazyComponentType<T>; const parse = (typeof code.at(-1) === "function" ? code.pop() : m => m) as (component: ModuleExports) => LazyComponentType<T>;
const newCode = code as string[]; const newCode = code as CodeFilter;
const ComponentResult = findComponent<T>(filters.byComponentCode(...newCode), parse, { isIndirect: true }); const ComponentResult = findComponent<T>(filters.byComponentCode(...newCode), parse, { isIndirect: true });
@ -333,9 +341,9 @@ export function findComponentByCode<T extends object = any>(...code: string[] |
* @param props A list of props to search the module or exports for * @param props A list of props to search the module or exports for
* @param parse A function that takes the find result as its first argument and returns something. Useful if you want to use a value from the find result, instead of all of it. Defaults to the find result itself * @param parse A function that takes the find result as its first argument and returns something. Useful if you want to use a value from the find result, instead of all of it. Defaults to the find result itself
*/ */
export function findByProps<T = any>(...props: string[] | [...string[], (module: ModuleExports) => T]) { export function findByProps<T = any>(...props: PropsFilter | [...PropsFilter, (module: ModuleExports) => T]) {
const parse = (typeof props.at(-1) === "function" ? props.pop() : m => m) as (module: ModuleExports) => T; const parse = (typeof props.at(-1) === "function" ? props.pop() : m => m) as (module: ModuleExports) => T;
const newProps = props as string[]; const newProps = props as PropsFilter;
const result = find<T>(filters.byProps(...newProps), parse, { isIndirect: true }); const result = find<T>(filters.byProps(...newProps), parse, { isIndirect: true });
@ -354,9 +362,9 @@ export function findByProps<T = any>(...props: string[] | [...string[], (module:
* @param props A list of props to search the module or exports for * @param props A list of props to search the module or exports for
* @param parse A function that takes the find result as its first argument and returns something. Useful if you want to use a value from the find result, instead of all of it. Defaults to the find result itself * @param parse A function that takes the find result as its first argument and returns something. Useful if you want to use a value from the find result, instead of all of it. Defaults to the find result itself
*/ */
export function findByPropsAndExtract<T = any>(...props: string[] | [...string[], (module: ModuleExports) => T]) { export function findByPropsAndExtract<T = any>(...props: PropsFilter | [...PropsFilter, (module: ModuleExports) => T]) {
const parse = (typeof props.at(-1) === "function" ? props.pop() : m => m) as (module: ModuleExports) => T; const parse = (typeof props.at(-1) === "function" ? props.pop() : m => m) as (module: ModuleExports) => T;
const newProps = props as string[]; const newProps = props as PropsFilter;
const result = find<T>(filters.byProps(...newProps), m => parse(m[newProps[0]]), { isIndirect: true }); const result = find<T>(filters.byProps(...newProps), m => parse(m[newProps[0]]), { isIndirect: true });
@ -373,9 +381,9 @@ export function findByPropsAndExtract<T = any>(...props: string[] | [...string[]
* @param code A list of code to search each export for * @param code A list of code to search each export for
* @param parse A function that takes the find result as its first argument and returns something. Useful if you want to use a value from the find result, instead of all of it. Defaults to the find result itself * @param parse A function that takes the find result as its first argument and returns something. Useful if you want to use a value from the find result, instead of all of it. Defaults to the find result itself
*/ */
export function findByCode<T = any>(...code: string[] | [...string[], (module: ModuleExports) => T]) { export function findByCode<T = any>(...code: CodeFilter | [...CodeFilter, (module: ModuleExports) => T]) {
const parse = (typeof code.at(-1) === "function" ? code.pop() : m => m) as (module: ModuleExports) => T; const parse = (typeof code.at(-1) === "function" ? code.pop() : m => m) as (module: ModuleExports) => T;
const newCode = code as string[]; const newCode = code as CodeFilter;
const result = find<T>(filters.byCode(...newCode), parse, { isIndirect: true }); const result = find<T>(filters.byCode(...newCode), parse, { isIndirect: true });
@ -391,7 +399,7 @@ export function findByCode<T = any>(...code: string[] | [...string[], (module: M
* *
* @param name The store name * @param name The store name
*/ */
export function findStore<T = GenericStore>(name: string) { export function findStore<T = GenericStore>(name: StoreNameFilter) {
const result = find<T>(filters.byStoreName(name), m => m, { isIndirect: true }); const result = find<T>(filters.byStoreName(name), m => m, { isIndirect: true });
if (IS_REPORTER) { if (IS_REPORTER) {
@ -407,9 +415,9 @@ export function findStore<T = GenericStore>(name: string) {
* @param code A list of code to search each factory for * @param code A list of code to search each factory for
* @param parse A function that takes the find result as its first argument and returns something. Useful if you want to use a value from the find result, instead of all of it. Defaults to the find result itself * @param parse A function that takes the find result as its first argument and returns something. Useful if you want to use a value from the find result, instead of all of it. Defaults to the find result itself
*/ */
export function findByFactoryCode<T = any>(...code: string[] | [...string[], (module: ModuleExports) => T]) { export function findByFactoryCode<T = any>(...code: CodeFilter | [...CodeFilter, (module: ModuleExports) => T]) {
const parse = (typeof code.at(-1) === "function" ? code.pop() : m => m) as (module: ModuleExports) => T; const parse = (typeof code.at(-1) === "function" ? code.pop() : m => m) as (module: ModuleExports) => T;
const newCode = code as string[]; const newCode = code as CodeFilter;
const result = find<T>(filters.byFactoryCode(...newCode), parse, { isIndirect: true }); const result = find<T>(filters.byFactoryCode(...newCode), parse, { isIndirect: true });
@ -434,7 +442,7 @@ export function findByFactoryCode<T = any>(...code: string[] | [...string[], (mo
* @param mappers Mappers to create the non mangled exports object * @param mappers Mappers to create the non mangled exports object
* @returns Unmangled exports as specified in mappers * @returns Unmangled exports as specified in mappers
*/ */
export function mapMangledModule<S extends PropertyKey>(code: string | string[], mappers: Record<S, FilterFn>) { export function mapMangledModule<S extends PropertyKey>(code: string | RegExp | CodeFilter, mappers: Record<S, FilterFn>) {
const mapping = {} as Record<S, any>; const mapping = {} as Record<S, any>;
const setters = {} as Record<S, (innerValue: ModuleExports) => void>; const setters = {} as Record<S, (innerValue: ModuleExports) => void>;
@ -487,7 +495,7 @@ export function mapMangledModule<S extends PropertyKey>(code: string | string[],
/** /**
* Find the first module factory that includes all the given code. * Find the first module factory that includes all the given code.
*/ */
export function findModuleFactory(...code: string[]) { export function findModuleFactory(...code: CodeFilter) {
const filter = filters.byFactoryCode(...code); const filter = filters.byFactoryCode(...code);
const [proxy, setInnerValue] = proxyInner<AnyModuleFactory>(`Webpack module factory find matched no module. Filter: ${printFilter(filter)}`, "Webpack find with proxy called on a primitive value."); const [proxy, setInnerValue] = proxyInner<AnyModuleFactory>(`Webpack module factory find matched no module. Filter: ${printFilter(filter)}`, "Webpack find with proxy called on a primitive value.");
@ -539,7 +547,7 @@ export const ChunkIdsRegex = /\("([^"]+?)"\)/g;
* @param matcher A RegExp that returns the chunk ids array as the first capture group and the entry point id as the second. Defaults to a matcher that captures the first lazy chunk loading found in the module factory * @param matcher A RegExp that returns the chunk ids array as the first capture group and the entry point id as the second. Defaults to a matcher that captures the first lazy chunk loading found in the module factory
* @returns A function that returns a promise that resolves with a boolean whether the chunks were loaded, on first call * @returns A function that returns a promise that resolves with a boolean whether the chunks were loaded, on first call
*/ */
export function extractAndLoadChunksLazy(code: string | string[], matcher: RegExp = DefaultExtractAndLoadChunksRegex) { export function extractAndLoadChunksLazy(code: string | RegExp | CodeFilter, matcher: RegExp = DefaultExtractAndLoadChunksRegex) {
const module = findModuleFactory(...Array.isArray(code) ? code : [code]); const module = findModuleFactory(...Array.isArray(code) ? code : [code]);
const extractAndLoadChunks = makeLazy(async () => { const extractAndLoadChunks = makeLazy(async () => {
@ -811,16 +819,9 @@ export const cacheFindBulk = traceFunction("cacheFindBulk", function cacheFindBu
/** /**
* Find the id of the first already loaded module factory that includes all the given code. * Find the id of the first already loaded module factory that includes all the given code.
*/ */
export const cacheFindModuleId = traceFunction("cacheFindModuleId", function cacheFindModuleId(...code: string[]) { export const cacheFindModuleId = traceFunction("cacheFindModuleId", function cacheFindModuleId(...code: CodeFilter) {
outer:
for (const id in wreq.m) { for (const id in wreq.m) {
const str = String(wreq.m[id]); if (stringMatches(String(wreq.m[id]), code)) return id;
for (const c of code) {
if (!str.includes(c)) continue outer;
}
return id;
} }
const err = new Error("Didn't find module with code(s):\n" + code.join("\n")); const err = new Error("Didn't find module with code(s):\n" + code.join("\n"));
@ -835,33 +836,31 @@ export const cacheFindModuleId = traceFunction("cacheFindModuleId", function cac
/** /**
* Find the first already loaded module factory that includes all the given code. * Find the first already loaded module factory that includes all the given code.
*/ */
export function cacheFindModuleFactory(...code: string[]) { export const cacheFindModuleFactory = traceFunction("cacheFindModuleFactory", function cacheFindModuleFactory(...code: CodeFilter) {
const id = cacheFindModuleId(...code); const id = cacheFindModuleId(...code);
if (id == null) return; if (id == null) return;
return wreq.m[id]; return wreq.m[id];
} });
/** /**
* Search modules by keyword. This searches the factory methods, * Search modules by keyword. This searches the factory methods,
* meaning you can search all sorts of things, methodName, strings somewhere in the code, etc. * meaning you can search all sorts of things, methodName, strings somewhere in the code, etc.
* *
* @param filters One or more strings or regexes * @param code One or more strings or regexes
* @returns Mapping of found modules * @returns Mapping of found modules
*/ */
export function search(...filters: Array<string | RegExp>) { export function search(...code: CodeFilter) {
const results: WebpackRequire["m"] = {}; const results: WebpackRequire["m"] = {};
const factories = wreq.m; const factories = wreq.m;
outer:
for (const id in factories) { for (const id in factories) {
const factory = factories[id]; const factory = factories[id];
const factoryStr = String(factory);
for (const filter of filters) { if (stringMatches(String(factory), code)) {
if (typeof filter === "string" && !factoryStr.includes(filter)) continue outer;
if (filter instanceof RegExp && !filter.test(factoryStr)) continue outer;
}
results[id] = factory; results[id] = factory;
} }
}
return results; return results;
} }

View file

@ -272,3 +272,63 @@ export interface PopoutActions {
close(key: string): void; close(key: string): void;
setAlwaysOnTop(key: string, alwaysOnTop: boolean): void; setAlwaysOnTop(key: string, alwaysOnTop: boolean): void;
} }
export type UserNameUtilsTagInclude = LiteralUnion<"auto" | "always" | "never", string>;
export interface UserNameUtilsTagOptions {
forcePomelo?: boolean;
identifiable?: UserNameUtilsTagInclude;
decoration?: UserNameUtilsTagInclude;
mode?: "full" | "username";
}
export interface UsernameUtils {
getGlobalName(user: User): string;
getFormattedName(user: User, useTagInsteadOfUsername?: boolean): string;
getName(user: User): string;
useName(user: User): string;
getUserTag(user: User, options?: UserNameUtilsTagOptions): string;
useUserTag(user: User, options?: UserNameUtilsTagOptions): string;
useDirectMessageRecipient: any;
humanizeStatus: any;
}
export class DisplayProfile {
userId: string;
banner?: string;
bio?: string;
pronouns?: string;
accentColor?: number;
themeColors?: number[];
popoutAnimationParticleType?: any;
profileEffectId?: string;
_userProfile?: any;
_guildMemberProfile?: any;
canUsePremiumProfileCustomization: boolean;
canEditThemes: boolean;
premiumGuildSince: Date | null;
premiumSince: Date | null;
premiumType?: number;
primaryColor?: number;
getBadges(): Array<{
id: string;
description: string;
icon: string;
link?: string;
}>;
getBannerURL(options: { canAnimate: boolean; size: number; }): string;
getLegacyUsername(): string | null;
hasFullProfile(): boolean;
hasPremiumCustomization(): boolean;
hasThemeColors(): boolean;
isUsingGuildMemberBanner(): boolean;
isUsingGuildMemberBio(): boolean;
isUsingGuildMemberPronouns(): boolean;
}
export interface DisplayProfileUtils {
getDisplayProfile(userId: string, guildId?: string, customStores?: any): DisplayProfile | null;
useDisplayProfile(userId: string, guildId?: string, customStores?: any): DisplayProfile | null;
}

View file

@ -69,6 +69,25 @@ const ToastPosition = {
BOTTOM: 1 BOTTOM: 1
}; };
export interface ToastData {
message: string,
id: string,
/**
* Toasts.Type
*/
type: number,
options?: ToastOptions;
}
export interface ToastOptions {
/**
* Toasts.Position
*/
position?: number;
component?: React.ReactNode,
duration?: number;
}
export const Toasts = { export const Toasts = {
Type: ToastType, Type: ToastType,
Position: ToastPosition, Position: ToastPosition,
@ -77,40 +96,23 @@ export const Toasts = {
// hack to merge with the following interface, dunno if there's a better way // hack to merge with the following interface, dunno if there's a better way
...{} as { ...{} as {
show(data: { show(data: ToastData): void;
message: string,
id: string,
/**
* Toasts.Type
*/
type: number,
options?: {
/**
* Toasts.Position
*/
position?: number;
component?: React.ReactNode,
duration?: number;
};
}): void;
pop(): void; pop(): void;
create(message: string, type: number, options?: ToastOptions): ToastData;
} }
}; };
waitFor(filters.byProps("showToast"), m => { waitFor(filters.byProps("showToast"), m => {
Toasts.show = m.showToast; Toasts.show = m.showToast;
Toasts.pop = m.popToast; Toasts.pop = m.popToast;
Toasts.create = m.createToast;
}); });
/** /**
* Show a simple toast. If you need more options, use Toasts.show manually * Show a simple toast. If you need more options, use Toasts.show manually
*/ */
export function showToast(message: string, type = ToastType.MESSAGE) { export function showToast(message: string, type = ToastType.MESSAGE, options?: ToastOptions) {
Toasts.show({ Toasts.show(Toasts.create(message, type, options));
id: Toasts.genId(),
message,
type
});
} }
export const UserUtils: t.UserUtils = { export const UserUtils: t.UserUtils = {
@ -162,3 +164,9 @@ export const PopoutActions: t.PopoutActions = mapMangledModule('type:"POPOUT_WIN
close: filters.byCode('type:"POPOUT_WINDOW_CLOSE"'), close: filters.byCode('type:"POPOUT_WINDOW_CLOSE"'),
setAlwaysOnTop: filters.byCode('type:"POPOUT_WINDOW_SET_ALWAYS_ON_TOP"'), setAlwaysOnTop: filters.byCode('type:"POPOUT_WINDOW_SET_ALWAYS_ON_TOP"'),
}); });
export const UsernameUtils: t.UsernameUtils = findByProps("useName", "getGlobalName");
export const DisplayProfileUtils: t.DisplayProfileUtils = mapMangledModule(/=\i\.getUserProfile\(\i\),\i=\i\.getGuildMemberProfile\(/, {
getDisplayProfile: filters.byCode(".getGuildMemberProfile("),
useDisplayProfile: filters.byCode(/\[\i\.\i,\i\.\i],\(\)=>/)
});