From c73c3fa6360ee2c929d2dfe0c2709a4768dee9f4 Mon Sep 17 00:00:00 2001 From: Vendicated Date: Tue, 2 Jul 2024 00:17:40 +0200 Subject: [PATCH 1/6] sajidfjiasdjiodjioasjiod --- src/plugins/editUsers/data.ts | 43 +++++++++++++++ src/plugins/editUsers/index.tsx | 95 +++++++++++++++++++++++++++++++++ src/plugins/editUsers/modal.tsx | 43 +++++++++++++++ 3 files changed, 181 insertions(+) create mode 100644 src/plugins/editUsers/data.ts create mode 100644 src/plugins/editUsers/index.tsx create mode 100644 src/plugins/editUsers/modal.tsx diff --git a/src/plugins/editUsers/data.ts b/src/plugins/editUsers/data.ts new file mode 100644 index 000000000..e70c68cb6 --- /dev/null +++ b/src/plugins/editUsers/data.ts @@ -0,0 +1,43 @@ +/* + * Vencord, a Discord client mod + * Copyright (c) 2024 Vendicated and contributors + * SPDX-License-Identifier: GPL-3.0-or-later + */ + +import { definePluginSettings } from "@api/Settings"; + +export const enum OverrideFlags { + None = 0, + PreferServerNicks = 1 << 0, + DisableNicks = 1 << 1, + KeepServerAvatar = 1 << 2, + DisableServerAvatars = 1 << 3, + KeepServerBanner = 1 << 4, + DisableServerBanners = 1 << 5, +} + +export interface UserOverride { + username: string; + avatarUrl: string | null; + bannerUrl: string | null; + flags: OverrideFlags; +} + +export function makeBlankUserOverride(): UserOverride { + return { + username: "", + avatarUrl: "", + bannerUrl: "", + flags: OverrideFlags.None, + }; +} + +const emptyConstantOverride = makeBlankUserOverride(); + +export const settings = definePluginSettings({}) + .withPrivateSettings<{ + users?: Record; + }>(); + +export const getUserOverride = (userId: string) => settings.store.users?.[userId] ?? emptyConstantOverride; +export const hasFlag = (field: OverrideFlags, flag: OverrideFlags) => (field & flag) === flag; diff --git a/src/plugins/editUsers/index.tsx b/src/plugins/editUsers/index.tsx new file mode 100644 index 000000000..ad998f610 --- /dev/null +++ b/src/plugins/editUsers/index.tsx @@ -0,0 +1,95 @@ +/* + * Vencord, a Discord client mod + * Copyright (c) 2024 Vendicated and contributors + * SPDX-License-Identifier: GPL-3.0-or-later + */ + +import { Devs } from "@utils/constants"; +import definePlugin from "@utils/types"; +import { Menu } from "@webpack/common"; +import { User } from "discord-types/general"; + +import { getUserOverride, hasFlag, OverrideFlags, settings } from "./data"; +import { openUserEditModal } from "./modal"; + + + +export default definePlugin({ + name: "EditUsers", + description: "Edit users", + authors: [Devs.Ven], + + settings, + + contextMenus: { + "user-context"(children, { user }: { user?: User; }) { + if (!user) return; + + children.push( + openUserEditModal(user)} + /> + ); + } + }, + + patches: [ + { + find: ",getUserTag:", + replacement: { + match: /if\(\i\((\i)\.global_name\)\)return(?=.{0,100}return"\?\?\?")/, + replace: "const vcEuName=$self.getUsername($1);if(vcEuName)return vcEuName;$&" + } + }, + { + find: "=this.guildMemberAvatars[", + replacement: [ + { + match: /&&null!=this\.guildMemberAvatars\[\i\]/, + replace: "$& && !$self.shouldIgnoreGuildAvatar(this)" + }, + { + match: /(?<=:)\i\.\i\.getUserAvatarURL\(this/, + replace: "$self.getAvatarUrl(this)||$&" + } + ] + }, + { + find: "this.isUsingGuildMemberBanner()", + replacement: [ + { + match: /:\i\.banner\)!=null/, + replace: "$& && !$self.shouldIgnoreGuildBanner(this.userId)" + }, + { + match: /(?<=:).{0,10}\(\{id:this\.userId,banner/, + replace: "$self.getBannerUrl(this.userId)||$&" + } + ] + } + ], + + getUsername: (user: User) => getUserOverride(user.id).username, + getAvatarUrl: (user: User) => getUserOverride(user.id).avatarUrl, + getBannerUrl: (userId: string) => getUserOverride(userId).bannerUrl, + + shouldIgnoreGuildAvatar(user: User) { + const { avatarUrl, flags } = getUserOverride(user.id); + + if (avatarUrl && !hasFlag(flags, OverrideFlags.KeepServerAvatar)) + return true; + + return hasFlag(flags, OverrideFlags.DisableServerAvatars); + }, + + shouldIgnoreGuildBanner(userId: string) { + const { bannerUrl, flags } = getUserOverride(userId); + + if (bannerUrl && !hasFlag(flags, OverrideFlags.KeepServerBanner)) + return true; + + return hasFlag(flags, OverrideFlags.DisableServerBanners); + } +}); diff --git a/src/plugins/editUsers/modal.tsx b/src/plugins/editUsers/modal.tsx new file mode 100644 index 000000000..bb5d91918 --- /dev/null +++ b/src/plugins/editUsers/modal.tsx @@ -0,0 +1,43 @@ +/* + * Vencord, a Discord client mod + * Copyright (c) 2024 Vendicated and contributors + * SPDX-License-Identifier: GPL-3.0-or-later + */ + +import { Flex } from "@components/Flex"; +import { ModalCloseButton, ModalContent, ModalFooter, ModalHeader, ModalRoot, openModal } from "@utils/modal"; +import { Button, Text } from "@webpack/common"; +import { User } from "discord-types/general"; + +function EditModal({ user }: { user: User; }) { + // TODO trolley + return null; +} + +export function openUserEditModal(user) { + openModal(props => ( + + + Notification Log + + + + + + + + + + + + + + + )); +} From e0bb9bf77ddec4f4b3d2dfd77f3ef095596b7e7e Mon Sep 17 00:00:00 2001 From: Vendicated Date: Tue, 2 Jul 2024 17:39:48 +0200 Subject: [PATCH 2/6] add ui and stuffs --- .stylelintrc.json | 8 +- src/plugins/editUsers/data.ts | 23 ++--- src/plugins/editUsers/index.tsx | 4 +- src/plugins/editUsers/modal.tsx | 155 +++++++++++++++++++++++++--- src/plugins/editUsers/styles.css | 14 +++ src/utils/misc.ts | 2 +- src/webpack/common/types/utils.d.ts | 62 ++++++++++- src/webpack/common/utils.ts | 52 ++++++---- src/webpack/webpack.ts | 98 +++++++++--------- 9 files changed, 318 insertions(+), 100 deletions(-) create mode 100644 src/plugins/editUsers/styles.css diff --git a/.stylelintrc.json b/.stylelintrc.json index 6449c3f29..ec2549762 100644 --- a/.stylelintrc.json +++ b/.stylelintrc.json @@ -1,6 +1,12 @@ { "extends": "stylelint-config-standard", "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" + } + ] } } diff --git a/src/plugins/editUsers/data.ts b/src/plugins/editUsers/data.ts index e70c68cb6..57d589fd4 100644 --- a/src/plugins/editUsers/data.ts +++ b/src/plugins/editUsers/data.ts @@ -18,26 +18,23 @@ export const enum OverrideFlags { export interface UserOverride { username: string; - avatarUrl: string | null; - bannerUrl: string | null; + avatarUrl: string; + bannerUrl: string; flags: OverrideFlags; } -export function makeBlankUserOverride(): UserOverride { - return { - username: "", - avatarUrl: "", - bannerUrl: "", - flags: OverrideFlags.None, - }; -} - -const emptyConstantOverride = makeBlankUserOverride(); +export const emptyOverride: UserOverride = Object.freeze({ + username: "", + avatarUrl: "", + bannerUrl: "", + flags: OverrideFlags.None, +}); export const settings = definePluginSettings({}) .withPrivateSettings<{ users?: Record; }>(); -export const getUserOverride = (userId: string) => settings.store.users?.[userId] ?? emptyConstantOverride; +export const getUserOverride = (userId: string) => settings.store.users?.[userId] ?? emptyOverride; + export const hasFlag = (field: OverrideFlags, flag: OverrideFlags) => (field & flag) === flag; diff --git a/src/plugins/editUsers/index.tsx b/src/plugins/editUsers/index.tsx index ad998f610..563a16fba 100644 --- a/src/plugins/editUsers/index.tsx +++ b/src/plugins/editUsers/index.tsx @@ -4,6 +4,8 @@ * SPDX-License-Identifier: GPL-3.0-or-later */ +import "./styles.css"; + import { Devs } from "@utils/constants"; import definePlugin from "@utils/types"; import { Menu } from "@webpack/common"; @@ -12,8 +14,6 @@ import { User } from "discord-types/general"; import { getUserOverride, hasFlag, OverrideFlags, settings } from "./data"; import { openUserEditModal } from "./modal"; - - export default definePlugin({ name: "EditUsers", description: "Edit users", diff --git a/src/plugins/editUsers/modal.tsx b/src/plugins/editUsers/modal.tsx index bb5d91918..ba0c127d0 100644 --- a/src/plugins/editUsers/modal.tsx +++ b/src/plugins/editUsers/modal.tsx @@ -4,40 +4,167 @@ * SPDX-License-Identifier: GPL-3.0-or-later */ +import { classNameFactory } from "@api/Styles"; import { Flex } from "@components/Flex"; -import { ModalCloseButton, ModalContent, ModalFooter, ModalHeader, ModalRoot, openModal } from "@utils/modal"; -import { Button, Text } from "@webpack/common"; +import { Margins } from "@utils/margins"; +import { ModalCloseButton, ModalContent, ModalFooter, ModalHeader, ModalProps, ModalRoot, ModalSize, openModal } from "@utils/modal"; +import { Button, DisplayProfileUtils, showToast, Switch, TabBar, Text, TextInput, Toasts, UsernameUtils, useState } from "@webpack/common"; import { User } from "discord-types/general"; +import type { Dispatch, SetStateAction } from "react"; -function EditModal({ user }: { user: User; }) { - // TODO trolley - return null; +import { emptyOverride, hasFlag, OverrideFlags, settings, UserOverride } from "./data"; + +const cl = classNameFactory("vc-editUsers-"); + +interface OverrideProps { + override: UserOverride; + setOverride: Dispatch>; } -export function openUserEditModal(user) { - openModal(props => ( - +interface SettingsRowProps extends OverrideProps { + overrideKey: keyof Omit; + name: string; + flagDisable: OverrideFlags; + flagPrefer: OverrideFlags; + placeholder: string; +} + +function SettingsRow(props: SettingsRowProps) { + const { name, override, setOverride, overrideKey, placeholder, flagDisable, flagPrefer } = props; + const namePlural = name + "s"; + const { flags } = override; + + const toggleFlag = (on: boolean, flag: OverrideFlags) => + on + ? flags | flag + : flags & ~flag; + + return ( + <> + setOverride(o => ({ ...o, [overrideKey]: v }))} + placeholder={placeholder} + autoFocus + /> + setOverride(o => ({ ...o, flags: toggleFlag(v, flagDisable) }))} + note={`Will use the user's global ${name} (or your EditUser configured ${name}) over server specific ${namePlural}`} + > + Disable server specific {namePlural} + + setOverride(o => ({ ...o, flags: toggleFlag(v, flagPrefer) }))} + note={`Will use server specific ${namePlural} over the EditUser configured ${name}`} + hideBorder + > + Prefer server specific {namePlural} + + + ); +} + +const Tabs = { + username: { + name: "Username", + flagDisable: OverrideFlags.DisableNicks, + flagPrefer: OverrideFlags.PreferServerNicks, + placeholder: (user: User) => UsernameUtils.getName(user), + }, + avatarUrl: { + name: "Avatar", + flagDisable: OverrideFlags.DisableServerAvatars, + flagPrefer: OverrideFlags.KeepServerAvatar, + placeholder: (user: User) => user.getAvatarURL(), + }, + bannerUrl: { + name: "Banner", + flagDisable: OverrideFlags.DisableServerBanners, + flagPrefer: OverrideFlags.KeepServerBanner, + placeholder: (user: User) => DisplayProfileUtils.getDisplayProfile(user.id)?.getBannerURL({ canAnimate: true, size: 64 }) ?? "", + }, +} as const; +const TabKeys = Object.keys(Tabs) as (keyof typeof Tabs)[]; + +function EditTabs({ user, override, setOverride }: { user: User; } & OverrideProps) { + const [currentTabName, setCurrentTabName] = useState(TabKeys[0]); + + const currentTab = Tabs[currentTabName]; + + return ( + <> + + {TabKeys.map(key => ( + + {Tabs[key].name} + + ))} + + + + + ); +} + +function EditModal({ user, modalProps }: { user: User; modalProps: ModalProps; }) { + const [override, setOverride] = useState(() => ({ ...settings.store.users?.[user.id] ?? emptyOverride })); + + return ( + - Notification Log - + Edit User {user.username} + - +
+ +
-
- )); + ); +} + +export function openUserEditModal(user: User) { + openModal(props => ); } diff --git a/src/plugins/editUsers/styles.css b/src/plugins/editUsers/styles.css new file mode 100644 index 000000000..61746abbf --- /dev/null +++ b/src/plugins/editUsers/styles.css @@ -0,0 +1,14 @@ +.vc-editUsers-modal { + padding: 1em 0; +} + +.vc-editUsers-tabBar { + gap: 1em; + margin-bottom: 16px; + border-bottom: 2px solid var(--background-modifier-accent); +} + +.vc-editUsers-tab { + padding-bottom: 8px; +} + diff --git a/src/utils/misc.ts b/src/utils/misc.ts index 7d6b4affc..28c371c5b 100644 --- a/src/utils/misc.ts +++ b/src/utils/misc.ts @@ -24,7 +24,7 @@ import { DevsById } from "./constants"; * Calls .join(" ") on the arguments * classes("one", "two") => "one two" */ -export function classes(...classes: Array) { +export function classes(...classes: Array) { return classes.filter(Boolean).join(" "); } diff --git a/src/webpack/common/types/utils.d.ts b/src/webpack/common/types/utils.d.ts index ee3f69944..ce1e3e268 100644 --- a/src/webpack/common/types/utils.d.ts +++ b/src/webpack/common/types/utils.d.ts @@ -16,7 +16,7 @@ * along with this program. If not, see . */ -import { Guild, GuildMember } from "discord-types/general"; +import { Guild, GuildMember, User } from "discord-types/general"; import type { ReactNode } from "react"; import { LiteralUnion } from "type-fest"; @@ -256,3 +256,63 @@ export interface PopoutActions { close(key: string): 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; +} diff --git a/src/webpack/common/utils.ts b/src/webpack/common/utils.ts index a6853c84a..280b2ba90 100644 --- a/src/webpack/common/utils.ts +++ b/src/webpack/common/utils.ts @@ -73,6 +73,25 @@ const ToastPosition = { 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 = { Type: ToastType, Position: ToastPosition, @@ -81,23 +100,9 @@ export const Toasts = { // hack to merge with the following interface, dunno if there's a better way ...{} as { - show(data: { - message: string, - id: string, - /** - * Toasts.Type - */ - type: number, - options?: { - /** - * Toasts.Position - */ - position?: number; - component?: React.ReactNode, - duration?: number; - }; - }): void; + show(data: ToastData): void; pop(): void; + create(message: string, type: number, options?: ToastOptions): ToastData; } }; @@ -105,18 +110,15 @@ export const Toasts = { waitFor("showToast", m => { Toasts.show = m.showToast; Toasts.pop = m.popToast; + Toasts.create = m.createToast; }); /** * Show a simple toast. If you need more options, use Toasts.show manually */ -export function showToast(message: string, type = ToastType.MESSAGE) { - Toasts.show({ - id: Toasts.genId(), - message, - type - }); +export function showToast(message: string, type = ToastType.MESSAGE, options?: ToastOptions) { + Toasts.show(Toasts.create(message, type, options)); } export const UserUtils = { @@ -172,3 +174,9 @@ export const PopoutActions: t.PopoutActions = mapMangledModuleLazy('type:"POPOUT close: filters.byCode('type:"POPOUT_WINDOW_CLOSE"'), setAlwaysOnTop: filters.byCode('type:"POPOUT_WINDOW_SET_ALWAYS_ON_TOP"'), }); + +export const UsernameUtils: t.UsernameUtils = findByPropsLazy("useName", "getGlobalName"); +export const DisplayProfileUtils: t.DisplayProfileUtils = mapMangledModuleLazy(/=\i\.getUserProfile\(\i\),\i=\i\.getGuildMemberProfile\(/, { + getDisplayProfile: filters.byCode(".getGuildMemberProfile("), + useDisplayProfile: filters.byCode(/\[\i\.\i,\i\.\i],\(\)=>/) +}); diff --git a/src/webpack/webpack.ts b/src/webpack/webpack.ts index f776ab1c3..f21a38d67 100644 --- a/src/webpack/webpack.ts +++ b/src/webpack/webpack.ts @@ -38,31 +38,43 @@ export let cache: WebpackInstance["c"]; export type FilterFn = (mod: any) => boolean; +type PropsFilter = Array; +type CodeFilter = Array; +type StoreNameFilter = string; + +const stringMatches = (s: string, filter: CodeFilter) => + filter.every(f => + typeof f === "string" + ? s.includes(f) + : f.test(s) + ); + export const filters = { - byProps: (...props: string[]): FilterFn => + byProps: (...props: PropsFilter): FilterFn => props.length === 1 ? m => m[props[0]] !== void 0 : m => props.every(p => m[p] !== void 0), - byCode: (...code: string[]): FilterFn => m => { - if (typeof m !== "function") return false; - const s = Function.prototype.toString.call(m); - for (const c of code) { - if (!s.includes(c)) return false; - } - return true; + byCode: (...code: CodeFilter): FilterFn => { + code = code.map(canonicalizeMatch); + return m => { + if (typeof m !== "function") return false; + return stringMatches(Function.prototype.toString.call(m), code); + }; }, - byStoreName: (name: string): FilterFn => m => + byStoreName: (name: StoreNameFilter): FilterFn => m => m.constructor?.displayName === name, - componentByCode: (...code: string[]): FilterFn => { + componentByCode: (...code: CodeFilter): FilterFn => { const filter = filters.byCode(...code); return m => { if (filter(m)) return true; if (!m.$$typeof) return false; - if (m.type && m.type.render) return filter(m.type.render); // memo + forwardRef - if (m.type) return filter(m.type); // memos - if (m.render) return filter(m.render); // forwardRefs + if (m.type) + return m.type.render + ? filter(m.type.render) // memo + forwardRef + : filter(m.type); // memo + if (m.render) return filter(m.render); // forwardRef return false; }; } @@ -245,15 +257,9 @@ export const findBulk = traceFunction("findBulk", function findBulk(...filterFns * Find the id of the first module factory that includes all the given code * @returns string or null */ -export const findModuleId = traceFunction("findModuleId", function findModuleId(...code: string[]) { - outer: +export const findModuleId = traceFunction("findModuleId", function findModuleId(...code: CodeFilter) { for (const id in wreq.m) { - const str = wreq.m[id].toString(); - - for (const c of code) { - if (!str.includes(c)) continue outer; - } - return id; + if (stringMatches(wreq.m[id].toString(), code)) return id; } const err = new Error("Didn't find module with code(s):\n" + code.join("\n")); @@ -272,7 +278,7 @@ export const findModuleId = traceFunction("findModuleId", function findModuleId( * Find the first module factory that includes all the given code * @returns The module factory or null */ -export function findModuleFactory(...code: string[]) { +export function findModuleFactory(...code: CodeFilter) { const id = findModuleId(...code); if (!id) return null; @@ -325,7 +331,7 @@ export function findLazy(filter: FilterFn) { /** * Find the first module that has the specified properties */ -export function findByProps(...props: string[]) { +export function findByProps(...props: PropsFilter) { const res = find(filters.byProps(...props), { isIndirect: true }); if (!res) handleModuleNotFound("findByProps", ...props); @@ -335,7 +341,7 @@ export function findByProps(...props: string[]) { /** * Find the first module that has the specified properties, lazily */ -export function findByPropsLazy(...props: string[]) { +export function findByPropsLazy(...props: PropsFilter) { if (IS_REPORTER) lazyWebpackSearchHistory.push(["findByProps", props]); return proxyLazy(() => findByProps(...props)); @@ -344,7 +350,7 @@ export function findByPropsLazy(...props: string[]) { /** * Find the first function that includes all the given code */ -export function findByCode(...code: string[]) { +export function findByCode(...code: CodeFilter) { const res = find(filters.byCode(...code), { isIndirect: true }); if (!res) handleModuleNotFound("findByCode", ...code); @@ -354,7 +360,7 @@ export function findByCode(...code: string[]) { /** * Find the first function that includes all the given code, lazily */ -export function findByCodeLazy(...code: string[]) { +export function findByCodeLazy(...code: CodeFilter) { if (IS_REPORTER) lazyWebpackSearchHistory.push(["findByCode", code]); return proxyLazy(() => findByCode(...code)); @@ -363,7 +369,7 @@ export function findByCodeLazy(...code: string[]) { /** * Find a store by its displayName */ -export function findStore(name: string) { +export function findStore(name: StoreNameFilter) { const res = find(filters.byStoreName(name), { isIndirect: true }); if (!res) handleModuleNotFound("findStore", name); @@ -373,7 +379,7 @@ export function findStore(name: string) { /** * Find a store by its displayName, lazily */ -export function findStoreLazy(name: string) { +export function findStoreLazy(name: StoreNameFilter) { if (IS_REPORTER) lazyWebpackSearchHistory.push(["findStore", [name]]); return proxyLazy(() => findStore(name)); @@ -382,7 +388,7 @@ export function findStoreLazy(name: string) { /** * Finds the component which includes all the given code. Checks for plain components, memos and forwardRefs */ -export function findComponentByCode(...code: string[]) { +export function findComponentByCode(...code: CodeFilter) { const res = find(filters.componentByCode(...code), { isIndirect: true }); if (!res) handleModuleNotFound("findComponentByCode", ...code); @@ -407,7 +413,7 @@ export function findComponentLazy(filter: FilterFn) { /** * Finds the first component that includes all the given code, lazily */ -export function findComponentByCodeLazy(...code: string[]) { +export function findComponentByCodeLazy(...code: CodeFilter) { if (IS_REPORTER) lazyWebpackSearchHistory.push(["findComponentByCode", code]); return LazyComponent(() => { @@ -421,7 +427,7 @@ export function findComponentByCodeLazy(...code: string[ /** * Finds the first component that is exported by the first prop name, lazily */ -export function findExportedComponentLazy(...props: string[]) { +export function findExportedComponentLazy(...props: PropsFilter) { if (IS_REPORTER) lazyWebpackSearchHistory.push(["findExportedComponent", props]); return LazyComponent(() => { @@ -445,10 +451,13 @@ export function findExportedComponentLazy(...props: stri * closeModal: filters.byCode("key==") * }) */ -export const mapMangledModule = traceFunction("mapMangledModule", function mapMangledModule(code: string, mappers: Record): Record { +export const mapMangledModule = traceFunction("mapMangledModule", function mapMangledModule(code: string | RegExp | CodeFilter, mappers: Record): Record { + if (!Array.isArray(code)) code = [code]; + code = code.map(canonicalizeMatch); + const exports = {} as Record; - const id = findModuleId(code); + const id = findModuleId(...code); if (id === null) return exports; @@ -482,7 +491,7 @@ export const mapMangledModule = traceFunction("mapMangledModule", function mapMa * closeModal: filters.byCode("key==") * }) */ -export function mapMangledModuleLazy(code: string, mappers: Record): Record { +export function mapMangledModuleLazy(code: string | RegExp | CodeFilter, mappers: Record): Record { if (IS_REPORTER) lazyWebpackSearchHistory.push(["mapMangledModule", [code, mappers]]); return proxyLazy(() => mapMangledModule(code, mappers)); @@ -497,7 +506,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 * @returns A promise that resolves with a boolean whether the chunks were loaded */ -export async function extractAndLoadChunks(code: string[], matcher: RegExp = DefaultExtractAndLoadChunksRegex) { +export async function extractAndLoadChunks(code: CodeFilter, matcher: RegExp = DefaultExtractAndLoadChunksRegex) { const module = findModuleFactory(...code); if (!module) { const err = new Error("extractAndLoadChunks: Couldn't find module factory"); @@ -562,7 +571,7 @@ export async function extractAndLoadChunks(code: string[], matcher: RegExp = Def * @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 */ -export function extractAndLoadChunksLazy(code: string[], matcher = DefaultExtractAndLoadChunksRegex) { +export function extractAndLoadChunksLazy(code: CodeFilter, matcher = DefaultExtractAndLoadChunksRegex) { if (IS_REPORTER) lazyWebpackSearchHistory.push(["extractAndLoadChunks", [code, matcher]]); return makeLazy(() => extractAndLoadChunks(code, matcher)); @@ -572,7 +581,7 @@ export function extractAndLoadChunksLazy(code: string[], matcher = DefaultExtrac * Wait for a module that matches the provided filter to be registered, * then call the callback with the module as the first argument */ -export function waitFor(filter: string | string[] | FilterFn, callback: CallbackFn, { isIndirect = false }: { isIndirect?: boolean; } = {}) { +export function waitFor(filter: string | PropsFilter | FilterFn, callback: CallbackFn, { isIndirect = false }: { isIndirect?: boolean; } = {}) { if (IS_REPORTER && !isIndirect) lazyWebpackSearchHistory.push(["waitFor", Array.isArray(filter) ? filter : [filter]]); if (typeof filter === "string") @@ -593,21 +602,18 @@ export function waitFor(filter: string | string[] | FilterFn, callback: Callback /** * Search modules by keyword. This searches the factory methods, * meaning you can search all sorts of things, displayName, 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 */ -export function search(...filters: Array) { +export function search(...code: CodeFilter) { const results = {} as Record; const factories = wreq.m; - outer: + for (const id in factories) { const factory = factories[id].original ?? factories[id]; - const str: string = factory.toString(); - for (const filter of filters) { - if (typeof filter === "string" && !str.includes(filter)) continue outer; - if (filter instanceof RegExp && !filter.test(str)) continue outer; - } - results[id] = factory; + + if (stringMatches(factory.toString(), code)) + results[id] = factory; } return results; From b333deb7312107a629920737a0e9cd56936a35a5 Mon Sep 17 00:00:00 2001 From: Vendicated Date: Tue, 2 Jul 2024 00:17:40 +0200 Subject: [PATCH 3/6] improve settings ui (again) --- .stylelintrc.json | 8 +- src/components/Icons.tsx | 15 +++ src/components/VencordSettings/ThemesTab.tsx | 88 ++++++++--------- src/components/VencordSettings/VencordTab.tsx | 77 ++++++--------- .../VencordSettings/quickActions.css | 34 +++++++ .../VencordSettings/quickActions.tsx | 39 ++++++++ .../VencordSettings/settingsStyles.css | 20 ---- src/utils/misc.ts | 2 +- src/webpack/common/types/utils.d.ts | 62 +++++++++++- src/webpack/common/utils.ts | 52 +++++----- src/webpack/webpack.ts | 98 ++++++++++--------- 11 files changed, 309 insertions(+), 186 deletions(-) create mode 100644 src/components/VencordSettings/quickActions.css create mode 100644 src/components/VencordSettings/quickActions.tsx diff --git a/.stylelintrc.json b/.stylelintrc.json index 6449c3f29..ec2549762 100644 --- a/.stylelintrc.json +++ b/.stylelintrc.json @@ -1,6 +1,12 @@ { "extends": "stylelint-config-standard", "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" + } + ] } } diff --git a/src/components/Icons.tsx b/src/components/Icons.tsx index d82ce0b00..7ba078d33 100644 --- a/src/components/Icons.tsx +++ b/src/components/Icons.tsx @@ -392,6 +392,21 @@ export function PaintbrushIcon(props: IconProps) { ); } +export function PencilIcon(props: IconProps) { + return ( + + + + ); +} + const WebsiteIconDark = "/assets/e1e96d89e192de1997f73730db26e94f.svg"; const WebsiteIconLight = "/assets/730f58bcfd5a57a5e22460c445a0c6cf.svg"; const GithubIconLight = "/assets/3ff98ad75ac94fa883af5ed62d17c459.svg"; diff --git a/src/components/VencordSettings/ThemesTab.tsx b/src/components/VencordSettings/ThemesTab.tsx index 2eb91cb82..016371bed 100644 --- a/src/components/VencordSettings/ThemesTab.tsx +++ b/src/components/VencordSettings/ThemesTab.tsx @@ -19,21 +19,21 @@ import { useSettings } from "@api/Settings"; import { classNameFactory } from "@api/Styles"; 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 PluginModal from "@components/PluginSettings/PluginModal"; +import { openPluginModal } from "@components/PluginSettings/PluginModal"; import type { UserThemeHeader } from "@main/themes"; import { openInviteModal } from "@utils/discord"; import { Margins } from "@utils/margins"; import { classes } from "@utils/misc"; -import { openModal } from "@utils/modal"; import { showItemInFolder } from "@utils/native"; import { useAwaiter } from "@utils/react"; import { findByPropsLazy, findLazy } 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 { ComponentType, Ref, SyntheticEvent } from "react"; import { AddonCard } from "./AddonCard"; +import { QuickAction, QuickActionCard } from "./quickActions"; import { SettingsTab, wrapTab } from "./shared"; type FileInput = ComponentType<{ @@ -213,60 +213,52 @@ function ThemesTab() { - + <> {IS_WEB ? ( - + + Upload Theme + + + } + Icon={PlusIcon} + /> ) : ( - + Icon={FolderIcon} + /> )} - - + + VencordNative.quickCss.openEditor()} + Icon={PaintbrushIcon} + /> {Vencord.Settings.plugins.ClientTheme.enabled && ( - + openPluginModal(Vencord.Plugins.plugins.ClientTheme)} + Icon={PencilIcon} + /> )} - +
{userThemes?.map(theme => ( diff --git a/src/components/VencordSettings/VencordTab.tsx b/src/components/VencordSettings/VencordTab.tsx index d13b43fb2..97f82e777 100644 --- a/src/components/VencordSettings/VencordTab.tsx +++ b/src/components/VencordSettings/VencordTab.tsx @@ -21,15 +21,16 @@ import { useSettings } from "@api/Settings"; import { classNameFactory } from "@api/Styles"; import DonateButton from "@components/DonateButton"; import { openPluginModal } from "@components/PluginSettings/PluginModal"; +import { gitRemote } from "@shared/vencordUserAgent"; import { Margins } from "@utils/margins"; import { identity } from "@utils/misc"; import { relaunch, showItemInFolder } from "@utils/native"; import { useAwaiter } from "@utils/react"; -import { Button, Card, Forms, React, Select, Switch, TooltipContainer } from "@webpack/common"; -import { ComponentType } from "react"; +import { Button, Card, Forms, React, Select, Switch } from "@webpack/common"; import { Flex, FolderIcon, GithubIcon, LogIcon, PaintbrushIcon, RestartIcon } from ".."; import { openNotificationSettingsModal } from "./NotificationSettings"; +import { QuickAction, QuickActionCard } from "./quickActions"; import { SettingsTab, wrapTab } from "./shared"; const cl = classNameFactory("vc-settings-"); @@ -41,17 +42,6 @@ type KeysOfType = { [K in keyof Object]: Object[K] extends Type ? K : never; }[keyof Object]; -const iconWithTooltip = (Icon: ComponentType<{ className?: string; }>, tooltip: string) => () => ( - - - -); - -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() { const [settingsDir, , settingsDirPending] = useAwaiter(VencordNative.settings.getSettingsDir, { @@ -111,44 +101,37 @@ function VencordSettings() { - - - + + + VencordNative.quickCss.openEditor()} + /> {!IS_WEB && ( - + )} {!IS_WEB && ( - + showItemInFolder(settingsDir)} + /> )} - - + VencordNative.native.openExternal("https://github.com/" + gitRemote)} + /> + diff --git a/src/components/VencordSettings/quickActions.css b/src/components/VencordSettings/quickActions.css new file mode 100644 index 000000000..897bc8c81 --- /dev/null +++ b/src/components/VencordSettings/quickActions.css @@ -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; +} diff --git a/src/components/VencordSettings/quickActions.tsx b/src/components/VencordSettings/quickActions.tsx new file mode 100644 index 000000000..6cc57180a --- /dev/null +++ b/src/components/VencordSettings/quickActions.tsx @@ -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 ( + + ); +} + +export function QuickActionCard(props: PropsWithChildren) { + return ( + + {props.children} + + ); +} diff --git a/src/components/VencordSettings/settingsStyles.css b/src/components/VencordSettings/settingsStyles.css index 6e8826c52..13558be21 100644 --- a/src/components/VencordSettings/settingsStyles.css +++ b/src/components/VencordSettings/settingsStyles.css @@ -10,26 +10,6 @@ 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 { display: flex; flex-direction: row; diff --git a/src/utils/misc.ts b/src/utils/misc.ts index 7d6b4affc..28c371c5b 100644 --- a/src/utils/misc.ts +++ b/src/utils/misc.ts @@ -24,7 +24,7 @@ import { DevsById } from "./constants"; * Calls .join(" ") on the arguments * classes("one", "two") => "one two" */ -export function classes(...classes: Array) { +export function classes(...classes: Array) { return classes.filter(Boolean).join(" "); } diff --git a/src/webpack/common/types/utils.d.ts b/src/webpack/common/types/utils.d.ts index ee3f69944..ce1e3e268 100644 --- a/src/webpack/common/types/utils.d.ts +++ b/src/webpack/common/types/utils.d.ts @@ -16,7 +16,7 @@ * along with this program. If not, see . */ -import { Guild, GuildMember } from "discord-types/general"; +import { Guild, GuildMember, User } from "discord-types/general"; import type { ReactNode } from "react"; import { LiteralUnion } from "type-fest"; @@ -256,3 +256,63 @@ export interface PopoutActions { close(key: string): 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; +} diff --git a/src/webpack/common/utils.ts b/src/webpack/common/utils.ts index a6853c84a..280b2ba90 100644 --- a/src/webpack/common/utils.ts +++ b/src/webpack/common/utils.ts @@ -73,6 +73,25 @@ const ToastPosition = { 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 = { Type: ToastType, Position: ToastPosition, @@ -81,23 +100,9 @@ export const Toasts = { // hack to merge with the following interface, dunno if there's a better way ...{} as { - show(data: { - message: string, - id: string, - /** - * Toasts.Type - */ - type: number, - options?: { - /** - * Toasts.Position - */ - position?: number; - component?: React.ReactNode, - duration?: number; - }; - }): void; + show(data: ToastData): void; pop(): void; + create(message: string, type: number, options?: ToastOptions): ToastData; } }; @@ -105,18 +110,15 @@ export const Toasts = { waitFor("showToast", m => { Toasts.show = m.showToast; Toasts.pop = m.popToast; + Toasts.create = m.createToast; }); /** * Show a simple toast. If you need more options, use Toasts.show manually */ -export function showToast(message: string, type = ToastType.MESSAGE) { - Toasts.show({ - id: Toasts.genId(), - message, - type - }); +export function showToast(message: string, type = ToastType.MESSAGE, options?: ToastOptions) { + Toasts.show(Toasts.create(message, type, options)); } export const UserUtils = { @@ -172,3 +174,9 @@ export const PopoutActions: t.PopoutActions = mapMangledModuleLazy('type:"POPOUT close: filters.byCode('type:"POPOUT_WINDOW_CLOSE"'), setAlwaysOnTop: filters.byCode('type:"POPOUT_WINDOW_SET_ALWAYS_ON_TOP"'), }); + +export const UsernameUtils: t.UsernameUtils = findByPropsLazy("useName", "getGlobalName"); +export const DisplayProfileUtils: t.DisplayProfileUtils = mapMangledModuleLazy(/=\i\.getUserProfile\(\i\),\i=\i\.getGuildMemberProfile\(/, { + getDisplayProfile: filters.byCode(".getGuildMemberProfile("), + useDisplayProfile: filters.byCode(/\[\i\.\i,\i\.\i],\(\)=>/) +}); diff --git a/src/webpack/webpack.ts b/src/webpack/webpack.ts index f776ab1c3..f21a38d67 100644 --- a/src/webpack/webpack.ts +++ b/src/webpack/webpack.ts @@ -38,31 +38,43 @@ export let cache: WebpackInstance["c"]; export type FilterFn = (mod: any) => boolean; +type PropsFilter = Array; +type CodeFilter = Array; +type StoreNameFilter = string; + +const stringMatches = (s: string, filter: CodeFilter) => + filter.every(f => + typeof f === "string" + ? s.includes(f) + : f.test(s) + ); + export const filters = { - byProps: (...props: string[]): FilterFn => + byProps: (...props: PropsFilter): FilterFn => props.length === 1 ? m => m[props[0]] !== void 0 : m => props.every(p => m[p] !== void 0), - byCode: (...code: string[]): FilterFn => m => { - if (typeof m !== "function") return false; - const s = Function.prototype.toString.call(m); - for (const c of code) { - if (!s.includes(c)) return false; - } - return true; + byCode: (...code: CodeFilter): FilterFn => { + code = code.map(canonicalizeMatch); + return m => { + if (typeof m !== "function") return false; + return stringMatches(Function.prototype.toString.call(m), code); + }; }, - byStoreName: (name: string): FilterFn => m => + byStoreName: (name: StoreNameFilter): FilterFn => m => m.constructor?.displayName === name, - componentByCode: (...code: string[]): FilterFn => { + componentByCode: (...code: CodeFilter): FilterFn => { const filter = filters.byCode(...code); return m => { if (filter(m)) return true; if (!m.$$typeof) return false; - if (m.type && m.type.render) return filter(m.type.render); // memo + forwardRef - if (m.type) return filter(m.type); // memos - if (m.render) return filter(m.render); // forwardRefs + if (m.type) + return m.type.render + ? filter(m.type.render) // memo + forwardRef + : filter(m.type); // memo + if (m.render) return filter(m.render); // forwardRef return false; }; } @@ -245,15 +257,9 @@ export const findBulk = traceFunction("findBulk", function findBulk(...filterFns * Find the id of the first module factory that includes all the given code * @returns string or null */ -export const findModuleId = traceFunction("findModuleId", function findModuleId(...code: string[]) { - outer: +export const findModuleId = traceFunction("findModuleId", function findModuleId(...code: CodeFilter) { for (const id in wreq.m) { - const str = wreq.m[id].toString(); - - for (const c of code) { - if (!str.includes(c)) continue outer; - } - return id; + if (stringMatches(wreq.m[id].toString(), code)) return id; } const err = new Error("Didn't find module with code(s):\n" + code.join("\n")); @@ -272,7 +278,7 @@ export const findModuleId = traceFunction("findModuleId", function findModuleId( * Find the first module factory that includes all the given code * @returns The module factory or null */ -export function findModuleFactory(...code: string[]) { +export function findModuleFactory(...code: CodeFilter) { const id = findModuleId(...code); if (!id) return null; @@ -325,7 +331,7 @@ export function findLazy(filter: FilterFn) { /** * Find the first module that has the specified properties */ -export function findByProps(...props: string[]) { +export function findByProps(...props: PropsFilter) { const res = find(filters.byProps(...props), { isIndirect: true }); if (!res) handleModuleNotFound("findByProps", ...props); @@ -335,7 +341,7 @@ export function findByProps(...props: string[]) { /** * Find the first module that has the specified properties, lazily */ -export function findByPropsLazy(...props: string[]) { +export function findByPropsLazy(...props: PropsFilter) { if (IS_REPORTER) lazyWebpackSearchHistory.push(["findByProps", props]); return proxyLazy(() => findByProps(...props)); @@ -344,7 +350,7 @@ export function findByPropsLazy(...props: string[]) { /** * Find the first function that includes all the given code */ -export function findByCode(...code: string[]) { +export function findByCode(...code: CodeFilter) { const res = find(filters.byCode(...code), { isIndirect: true }); if (!res) handleModuleNotFound("findByCode", ...code); @@ -354,7 +360,7 @@ export function findByCode(...code: string[]) { /** * Find the first function that includes all the given code, lazily */ -export function findByCodeLazy(...code: string[]) { +export function findByCodeLazy(...code: CodeFilter) { if (IS_REPORTER) lazyWebpackSearchHistory.push(["findByCode", code]); return proxyLazy(() => findByCode(...code)); @@ -363,7 +369,7 @@ export function findByCodeLazy(...code: string[]) { /** * Find a store by its displayName */ -export function findStore(name: string) { +export function findStore(name: StoreNameFilter) { const res = find(filters.byStoreName(name), { isIndirect: true }); if (!res) handleModuleNotFound("findStore", name); @@ -373,7 +379,7 @@ export function findStore(name: string) { /** * Find a store by its displayName, lazily */ -export function findStoreLazy(name: string) { +export function findStoreLazy(name: StoreNameFilter) { if (IS_REPORTER) lazyWebpackSearchHistory.push(["findStore", [name]]); return proxyLazy(() => findStore(name)); @@ -382,7 +388,7 @@ export function findStoreLazy(name: string) { /** * Finds the component which includes all the given code. Checks for plain components, memos and forwardRefs */ -export function findComponentByCode(...code: string[]) { +export function findComponentByCode(...code: CodeFilter) { const res = find(filters.componentByCode(...code), { isIndirect: true }); if (!res) handleModuleNotFound("findComponentByCode", ...code); @@ -407,7 +413,7 @@ export function findComponentLazy(filter: FilterFn) { /** * Finds the first component that includes all the given code, lazily */ -export function findComponentByCodeLazy(...code: string[]) { +export function findComponentByCodeLazy(...code: CodeFilter) { if (IS_REPORTER) lazyWebpackSearchHistory.push(["findComponentByCode", code]); return LazyComponent(() => { @@ -421,7 +427,7 @@ export function findComponentByCodeLazy(...code: string[ /** * Finds the first component that is exported by the first prop name, lazily */ -export function findExportedComponentLazy(...props: string[]) { +export function findExportedComponentLazy(...props: PropsFilter) { if (IS_REPORTER) lazyWebpackSearchHistory.push(["findExportedComponent", props]); return LazyComponent(() => { @@ -445,10 +451,13 @@ export function findExportedComponentLazy(...props: stri * closeModal: filters.byCode("key==") * }) */ -export const mapMangledModule = traceFunction("mapMangledModule", function mapMangledModule(code: string, mappers: Record): Record { +export const mapMangledModule = traceFunction("mapMangledModule", function mapMangledModule(code: string | RegExp | CodeFilter, mappers: Record): Record { + if (!Array.isArray(code)) code = [code]; + code = code.map(canonicalizeMatch); + const exports = {} as Record; - const id = findModuleId(code); + const id = findModuleId(...code); if (id === null) return exports; @@ -482,7 +491,7 @@ export const mapMangledModule = traceFunction("mapMangledModule", function mapMa * closeModal: filters.byCode("key==") * }) */ -export function mapMangledModuleLazy(code: string, mappers: Record): Record { +export function mapMangledModuleLazy(code: string | RegExp | CodeFilter, mappers: Record): Record { if (IS_REPORTER) lazyWebpackSearchHistory.push(["mapMangledModule", [code, mappers]]); return proxyLazy(() => mapMangledModule(code, mappers)); @@ -497,7 +506,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 * @returns A promise that resolves with a boolean whether the chunks were loaded */ -export async function extractAndLoadChunks(code: string[], matcher: RegExp = DefaultExtractAndLoadChunksRegex) { +export async function extractAndLoadChunks(code: CodeFilter, matcher: RegExp = DefaultExtractAndLoadChunksRegex) { const module = findModuleFactory(...code); if (!module) { const err = new Error("extractAndLoadChunks: Couldn't find module factory"); @@ -562,7 +571,7 @@ export async function extractAndLoadChunks(code: string[], matcher: RegExp = Def * @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 */ -export function extractAndLoadChunksLazy(code: string[], matcher = DefaultExtractAndLoadChunksRegex) { +export function extractAndLoadChunksLazy(code: CodeFilter, matcher = DefaultExtractAndLoadChunksRegex) { if (IS_REPORTER) lazyWebpackSearchHistory.push(["extractAndLoadChunks", [code, matcher]]); return makeLazy(() => extractAndLoadChunks(code, matcher)); @@ -572,7 +581,7 @@ export function extractAndLoadChunksLazy(code: string[], matcher = DefaultExtrac * Wait for a module that matches the provided filter to be registered, * then call the callback with the module as the first argument */ -export function waitFor(filter: string | string[] | FilterFn, callback: CallbackFn, { isIndirect = false }: { isIndirect?: boolean; } = {}) { +export function waitFor(filter: string | PropsFilter | FilterFn, callback: CallbackFn, { isIndirect = false }: { isIndirect?: boolean; } = {}) { if (IS_REPORTER && !isIndirect) lazyWebpackSearchHistory.push(["waitFor", Array.isArray(filter) ? filter : [filter]]); if (typeof filter === "string") @@ -593,21 +602,18 @@ export function waitFor(filter: string | string[] | FilterFn, callback: Callback /** * Search modules by keyword. This searches the factory methods, * meaning you can search all sorts of things, displayName, 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 */ -export function search(...filters: Array) { +export function search(...code: CodeFilter) { const results = {} as Record; const factories = wreq.m; - outer: + for (const id in factories) { const factory = factories[id].original ?? factories[id]; - const str: string = factory.toString(); - for (const filter of filters) { - if (typeof filter === "string" && !str.includes(filter)) continue outer; - if (filter instanceof RegExp && !filter.test(str)) continue outer; - } - results[id] = factory; + + if (stringMatches(factory.toString(), code)) + results[id] = factory; } return results; From 3a7499644eeb45d770e8746783ff846637c66dee Mon Sep 17 00:00:00 2001 From: Vendicated Date: Wed, 3 Jul 2024 17:24:29 +0200 Subject: [PATCH 4/6] add pronouns, add nicks (kinda) --- src/plugins/editUsers/data.ts | 2 ++ src/plugins/editUsers/index.tsx | 30 ++++++++++++++++++++++++++++++ 2 files changed, 32 insertions(+) diff --git a/src/plugins/editUsers/data.ts b/src/plugins/editUsers/data.ts index 57d589fd4..7957d2ce8 100644 --- a/src/plugins/editUsers/data.ts +++ b/src/plugins/editUsers/data.ts @@ -20,6 +20,7 @@ export interface UserOverride { username: string; avatarUrl: string; bannerUrl: string; + pronouns: string; flags: OverrideFlags; } @@ -27,6 +28,7 @@ export const emptyOverride: UserOverride = Object.freeze({ username: "", avatarUrl: "", bannerUrl: "", + pronouns: "", flags: OverrideFlags.None, }); diff --git a/src/plugins/editUsers/index.tsx b/src/plugins/editUsers/index.tsx index 563a16fba..82e5130fe 100644 --- a/src/plugins/editUsers/index.tsx +++ b/src/plugins/editUsers/index.tsx @@ -66,14 +66,33 @@ export default definePlugin({ { match: /(?<=:).{0,10}\(\{id:this\.userId,banner/, replace: "$self.getBannerUrl(this.userId)||$&" + }, + { + match: /isUsingGuildMemberPronouns\(\)\{/, + replace: + "set pronouns(v){this._vcPronouns=v}" + + "get pronouns(){return $self.getPronouns(this.userId)||this._vcPronouns}" + + "isUsingGuildMemberPronouns(){" + }, + { + match: /\i\(this,"pronouns",void 0\),/, + replace: "" } ] + }, + { + find: '"GuildMemberStore"', + replacement: { + match: /getNick\(\i,(\i)\)\{/, + replace: "$& if ($self.shouldIgnoreNick($1)) return null;" + } } ], getUsername: (user: User) => getUserOverride(user.id).username, getAvatarUrl: (user: User) => getUserOverride(user.id).avatarUrl, getBannerUrl: (userId: string) => getUserOverride(userId).bannerUrl, + getPronouns: (userId: string) => getUserOverride(userId).pronouns, shouldIgnoreGuildAvatar(user: User) { const { avatarUrl, flags } = getUserOverride(user.id); @@ -91,5 +110,16 @@ export default definePlugin({ return true; return hasFlag(flags, OverrideFlags.DisableServerBanners); + }, + + shouldIgnoreNick(userId?: string) { + if (!userId) return false; + + const { username, flags } = getUserOverride(userId); + + if (username && !hasFlag(flags, OverrideFlags.PreferServerNicks)) + return true; + + return hasFlag(flags, OverrideFlags.DisableNicks); } }); From f4572d0377e5579af35e39eda246fe9c74ec3126 Mon Sep 17 00:00:00 2001 From: Vendicated Date: Wed, 3 Jul 2024 18:07:11 +0200 Subject: [PATCH 5/6] fix overriding avatars in guilds --- src/plugins/editUsers/index.tsx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/plugins/editUsers/index.tsx b/src/plugins/editUsers/index.tsx index 82e5130fe..f96563f2b 100644 --- a/src/plugins/editUsers/index.tsx +++ b/src/plugins/editUsers/index.tsx @@ -51,8 +51,8 @@ export default definePlugin({ replace: "$& && !$self.shouldIgnoreGuildAvatar(this)" }, { - match: /(?<=:)\i\.\i\.getUserAvatarURL\(this/, - replace: "$self.getAvatarUrl(this)||$&" + match: /(?<=null!=(\i))\?(\i\.\i\.getGuildMemberAvatarURLSimple.+?):(?=\i\.\i\.getUserAvatarURL\(this)/, + replace: "&& this.hasAvatarForGuild?.($1) ? $2 : $self.getAvatarUrl(this)||" } ] }, From 560fb982e6f8b3960dd540f50ff5aab590491cbc Mon Sep 17 00:00:00 2001 From: Vendicated Date: Wed, 3 Jul 2024 21:38:21 +0200 Subject: [PATCH 6/6] BetterNotes: fix crashing --- src/components/VencordSettings/ThemesTab.tsx | 8 ++-- src/plugins/banger/index.ts | 22 ++++++---- src/plugins/betterNotes/index.tsx | 43 +++++++++++--------- 3 files changed, 43 insertions(+), 30 deletions(-) diff --git a/src/components/VencordSettings/ThemesTab.tsx b/src/components/VencordSettings/ThemesTab.tsx index 016371bed..aa8761d76 100644 --- a/src/components/VencordSettings/ThemesTab.tsx +++ b/src/components/VencordSettings/ThemesTab.tsx @@ -16,7 +16,7 @@ * along with this program. If not, see . */ -import { useSettings } from "@api/Settings"; +import { Settings, useSettings } from "@api/Settings"; import { classNameFactory } from "@api/Styles"; import { Flex } from "@components/Flex"; import { DeleteIcon, FolderIcon, PaintbrushIcon, PencilIcon, PlusIcon, RestartIcon } from "@components/Icons"; @@ -32,6 +32,8 @@ import { findByPropsLazy, findLazy } from "@webpack"; import { Card, Forms, React, showToast, TabBar, TextArea, useEffect, useRef, useState } from "@webpack/common"; import type { ComponentType, Ref, SyntheticEvent } from "react"; +import Plugins from "~plugins"; + import { AddonCard } from "./AddonCard"; import { QuickAction, QuickActionCard } from "./quickActions"; import { SettingsTab, wrapTab } from "./shared"; @@ -250,10 +252,10 @@ function ThemesTab() { Icon={PaintbrushIcon} /> - {Vencord.Settings.plugins.ClientTheme.enabled && ( + {Settings.plugins.ClientTheme.enabled && ( openPluginModal(Vencord.Plugins.plugins.ClientTheme)} + action={() => openPluginModal(Plugins.ClientTheme)} Icon={PencilIcon} /> )} diff --git a/src/plugins/banger/index.ts b/src/plugins/banger/index.ts index 7e0d2df73..eca80f9ee 100644 --- a/src/plugins/banger/index.ts +++ b/src/plugins/banger/index.ts @@ -16,28 +16,34 @@ * along with this program. If not, see . */ +import { definePluginSettings } from "@api/Settings"; import { Devs } from "@utils/constants"; import definePlugin, { OptionType } from "@utils/types"; +const settings = definePluginSettings({ + source: { + description: "Source to replace ban GIF with (Video or Gif)", + type: OptionType.STRING, + default: "https://i.imgur.com/wp5q52C.mp4", + restartNeeded: true, + } +}); + export default definePlugin({ name: "BANger", description: "Replaces the GIF in the ban dialogue with a custom one.", authors: [Devs.Xinto, Devs.Glitch], + settings, patches: [ { find: "BAN_CONFIRM_TITLE.", replacement: { match: /src:\i\("?\d+"?\)/g, - replace: "src: Vencord.Settings.plugins.BANger.source" + replace: "src:$self.source" } } ], - options: { - source: { - description: "Source to replace ban GIF with (Video or Gif)", - type: OptionType.STRING, - default: "https://i.imgur.com/wp5q52C.mp4", - restartNeeded: true, - } + get source() { + return settings.store.source; } }); diff --git a/src/plugins/betterNotes/index.tsx b/src/plugins/betterNotes/index.tsx index cacdba5fd..b97076bf4 100644 --- a/src/plugins/betterNotes/index.tsx +++ b/src/plugins/betterNotes/index.tsx @@ -16,7 +16,7 @@ * along with this program. If not, see . */ -import { Settings } from "@api/Settings"; +import { definePluginSettings, Settings } from "@api/Settings"; import ErrorBoundary from "@components/ErrorBoundary"; import { Devs } from "@utils/constants"; import { canonicalizeMatch } from "@utils/patches"; @@ -25,10 +25,26 @@ import { findByPropsLazy } from "@webpack"; const UserPopoutSectionCssClasses = findByPropsLazy("section", "lastSection"); +const settings = definePluginSettings({ + hide: { + type: OptionType.BOOLEAN, + description: "Hide notes", + default: false, + restartNeeded: true + }, + noSpellCheck: { + type: OptionType.BOOLEAN, + description: "Disable spellcheck in notes", + disabled: () => Settings.plugins.BetterNotesBox.hide, + default: false + } +}); + export default definePlugin({ name: "BetterNotesBox", description: "Hide notes or disable spellcheck (Configure in settings!!)", authors: [Devs.Ven], + settings, patches: [ { @@ -36,7 +52,7 @@ export default definePlugin({ all: true, // Some modules match the find but the replacement is returned untouched noWarn: true, - predicate: () => Vencord.Settings.plugins.BetterNotesBox.hide, + predicate: () => settings.store.hide, replacement: { match: /hideNote:.+?(?=([,}].*?\)))/g, replace: (m, rest) => { @@ -54,7 +70,7 @@ export default definePlugin({ find: "Messages.NOTE_PLACEHOLDER", replacement: { match: /\.NOTE_PLACEHOLDER,/, - replace: "$&spellCheck:!Vencord.Settings.plugins.BetterNotesBox.noSpellCheck," + replace: "$&spellCheck:!$self.noSpellCheck," } }, { @@ -66,25 +82,14 @@ export default definePlugin({ } ], - options: { - hide: { - type: OptionType.BOOLEAN, - description: "Hide notes", - default: false, - restartNeeded: true - }, - noSpellCheck: { - type: OptionType.BOOLEAN, - description: "Disable spellcheck in notes", - disabled: () => Settings.plugins.BetterNotesBox.hide, - default: false - } - }, - patchPadding: ErrorBoundary.wrap(({ lastSection }) => { if (!lastSection) return null; return (
); - }) + }), + + get noSpellCheck() { + return settings.store.noSpellCheck; + } });