improve settings ui (again)

This commit is contained in:
Vendicated 2024-07-02 00:17:40 +02:00
parent 77492061f5
commit b333deb731
No known key found for this signature in database
GPG key ID: D66986BAF75ECF18
11 changed files with 309 additions and 186 deletions

View file

@ -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"
}
]
}
}

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 WebsiteIconLight = "/assets/730f58bcfd5a57a5e22460c445a0c6cf.svg";
const GithubIconLight = "/assets/3ff98ad75ac94fa883af5ed62d17c459.svg";

View file

@ -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() {
</Card>
<Forms.FormSection title="Local Themes">
<Card className="vc-settings-quick-actions-card">
<QuickActionCard>
<>
{IS_WEB ?
(
<Button
size={Button.Sizes.SMALL}
disabled={themeDirPending}
>
Upload Theme
<FileInput
ref={fileInputRef}
onChange={onFileUpload}
multiple={true}
filters={[{ extensions: ["css"] }]}
/>
</Button>
<QuickAction
text={
<span style={{ position: "relative" }}>
Upload Theme
<FileInput
ref={fileInputRef}
onChange={onFileUpload}
multiple={true}
filters={[{ extensions: ["css"] }]}
/>
</span>
}
Icon={PlusIcon}
/>
) : (
<Button
onClick={() => showItemInFolder(themeDir!)}
size={Button.Sizes.SMALL}
<QuickAction
text="Open Themes Folder"
action={() => showItemInFolder(themeDir!)}
disabled={themeDirPending}
>
Open Themes Folder
</Button>
Icon={FolderIcon}
/>
)}
<Button
onClick={refreshLocalThemes}
size={Button.Sizes.SMALL}
>
Load missing Themes
</Button>
<Button
onClick={() => VencordNative.quickCss.openEditor()}
size={Button.Sizes.SMALL}
>
Edit QuickCSS
</Button>
<QuickAction
text="Load missing Themes"
action={refreshLocalThemes}
Icon={RestartIcon}
/>
<QuickAction
text="Edit QuickCSS"
action={() => VencordNative.quickCss.openEditor()}
Icon={PaintbrushIcon}
/>
{Vencord.Settings.plugins.ClientTheme.enabled && (
<Button
onClick={() => openModal(modalProps => (
<PluginModal
{...modalProps}
plugin={Vencord.Plugins.plugins.ClientTheme}
onRestartNeeded={() => { }}
/>
))}
size={Button.Sizes.SMALL}
>
Edit ClientTheme
</Button>
<QuickAction
text="Edit ClientTheme"
action={() => openPluginModal(Vencord.Plugins.plugins.ClientTheme)}
Icon={PencilIcon}
/>
)}
</>
</Card>
</QuickActionCard>
<div className={cl("grid")}>
{userThemes?.map(theme => (

View file

@ -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<Object, Type> = {
[K in keyof Object]: Object[K] extends Type ? K : never;
}[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() {
const [settingsDir, , settingsDirPending] = useAwaiter(VencordNative.settings.getSettingsDir, {
@ -111,44 +101,37 @@ function VencordSettings() {
<SettingsTab title="Vencord Settings">
<DonateCard image={donateImage} />
<Forms.FormSection title="Quick Actions">
<Card className={cl("quick-actions-card")}>
<Button
onClick={openNotificationLogModal}
look={Button.Looks.BLANK}
>
<NotificationLogIcon />
</Button>
<Button
onClick={() => VencordNative.quickCss.openEditor()}
look={Button.Looks.BLANK}
>
<QuickCssIcon />
</Button>
<QuickActionCard>
<QuickAction
Icon={LogIcon}
text="Notification Log"
action={openNotificationLogModal}
/>
<QuickAction
Icon={PaintbrushIcon}
text="Edit QuickCSS"
action={() => VencordNative.quickCss.openEditor()}
/>
{!IS_WEB && (
<Button
onClick={relaunch}
look={Button.Looks.BLANK}
>
<RelaunchIcon />
</Button>
<QuickAction
Icon={RestartIcon}
text="Relaunch Discord"
action={relaunch}
/>
)}
{!IS_WEB && (
<Button
onClick={() => showItemInFolder(settingsDir)}
look={Button.Looks.BLANK}
disabled={settingsDirPending}
>
<OpenSettingsDirIcon />
</Button>
<QuickAction
Icon={FolderIcon}
text="Open Settings Folder"
action={() => showItemInFolder(settingsDir)}
/>
)}
<Button
onClick={() => VencordNative.native.openExternal("https://github.com/Vendicated/Vencord")}
look={Button.Looks.BLANK}
disabled={settingsDirPending}
>
<OpenGithubIcon />
</Button>
</Card>
<QuickAction
Icon={GithubIcon}
text="View Source Code"
action={() => VencordNative.native.openExternal("https://github.com/" + gitRemote)}
/>
</QuickActionCard>
</Forms.FormSection>
<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;
}
.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;

View file

@ -24,7 +24,7 @@ import { DevsById } from "./constants";
* Calls .join(" ") on the arguments
* 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(" ");
}

View file

@ -16,7 +16,7 @@
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
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;
}

View file

@ -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],\(\)=>/)
});

View file

@ -38,31 +38,43 @@ export let cache: WebpackInstance["c"];
export type FilterFn = (mod: any) => boolean;
type PropsFilter = Array<string>;
type CodeFilter = Array<string | RegExp>;
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<T extends object = any>(filter: FilterFn) {
/**
* Finds the first component that includes all the given code, lazily
*/
export function findComponentByCodeLazy<T extends object = any>(...code: string[]) {
export function findComponentByCodeLazy<T extends object = any>(...code: CodeFilter) {
if (IS_REPORTER) lazyWebpackSearchHistory.push(["findComponentByCode", code]);
return LazyComponent<T>(() => {
@ -421,7 +427,7 @@ export function findComponentByCodeLazy<T extends object = any>(...code: string[
/**
* Finds the first component that is exported by the first prop name, lazily
*/
export function findExportedComponentLazy<T extends object = any>(...props: string[]) {
export function findExportedComponentLazy<T extends object = any>(...props: PropsFilter) {
if (IS_REPORTER) lazyWebpackSearchHistory.push(["findExportedComponent", props]);
return LazyComponent<T>(() => {
@ -445,10 +451,13 @@ export function findExportedComponentLazy<T extends object = any>(...props: stri
* closeModal: filters.byCode("key==")
* })
*/
export const mapMangledModule = traceFunction("mapMangledModule", function mapMangledModule<S extends string>(code: string, mappers: Record<S, FilterFn>): Record<S, any> {
export const mapMangledModule = traceFunction("mapMangledModule", function mapMangledModule<S extends string>(code: string | RegExp | CodeFilter, mappers: Record<S, FilterFn>): Record<S, any> {
if (!Array.isArray(code)) code = [code];
code = code.map(canonicalizeMatch);
const exports = {} as Record<S, any>;
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<S extends string>(code: string, mappers: Record<S, FilterFn>): Record<S, any> {
export function mapMangledModuleLazy<S extends string>(code: string | RegExp | CodeFilter, mappers: Record<S, FilterFn>): Record<S, any> {
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<string | RegExp>) {
export function search(...code: CodeFilter) {
const results = {} as Record<number, Function>;
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;