Compare commits

..

No commits in common. "2af1cd19b56d6d7c6ce32f86f0b9b0d87647c91f" and "0779d4d1a8ad9111da4a4c0f67319c369e4d3003" have entirely different histories.

28 changed files with 299 additions and 425 deletions

View file

@ -90,20 +90,19 @@ export function removeGlobalContextMenuPatch(patch: GlobalContextMenuPatchCallba
* A helper function for finding the children array of a group nested inside a context menu based on the id(s) of its children * A helper function for finding the children array of a group nested inside a context menu based on the id(s) of its children
* @param id The id of the child. If an array is specified, all ids will be tried * @param id The id of the child. If an array is specified, all ids will be tried
* @param children The context menu children * @param children The context menu children
* @param matchSubstring Whether to check if the id is a substring of the child id
*/ */
export function findGroupChildrenByChildId(id: string | string[], children: Array<ReactElement | null | undefined>, matchSubstring = false): Array<ReactElement | null | undefined> | null { export function findGroupChildrenByChildId(id: string | string[], children: Array<ReactElement | null>): Array<ReactElement | null> | null {
for (const child of children) { for (const child of children) {
if (child == null) continue; if (child == null) continue;
if (Array.isArray(child)) { if (Array.isArray(child)) {
const found = findGroupChildrenByChildId(id, child, matchSubstring); const found = findGroupChildrenByChildId(id, child);
if (found !== null) return found; if (found !== null) return found;
} }
if ( if (
(Array.isArray(id) && id.some(id => matchSubstring ? child.props?.id?.includes(id) : child.props?.id === id)) (Array.isArray(id) && id.some(id => child.props?.id === id))
|| (matchSubstring ? child.props?.id?.includes(id) : child.props?.id === id) || child.props?.id === id
) return children; ) return children;
let nextChildren = child.props?.children; let nextChildren = child.props?.children;
@ -113,7 +112,7 @@ export function findGroupChildrenByChildId(id: string | string[], children: Arra
child.props.children = nextChildren; child.props.children = nextChildren;
} }
const found = findGroupChildrenByChildId(id, nextChildren, matchSubstring); const found = findGroupChildrenByChildId(id, nextChildren);
if (found !== null) return found; if (found !== null) return found;
} }
} }

View file

@ -16,8 +16,6 @@
* along with this program. If not, see <https://www.gnu.org/licenses/>. * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
import { Margins } from "@utils/margins";
import { wordsFromCamel, wordsToTitle } from "@utils/text";
import { OptionType, PluginOptionNumber } from "@utils/types"; import { OptionType, PluginOptionNumber } from "@utils/types";
import { Forms, React, TextInput } from "@webpack/common"; import { Forms, React, TextInput } from "@webpack/common";
@ -56,8 +54,7 @@ export function SettingNumericComponent({ option, pluginSettings, definedSetting
return ( return (
<Forms.FormSection> <Forms.FormSection>
<Forms.FormTitle>{wordsToTitle(wordsFromCamel(id))}</Forms.FormTitle> <Forms.FormTitle>{option.description}</Forms.FormTitle>
<Forms.FormText className={Margins.bottom20} type="description">{option.description}</Forms.FormText>
<TextInput <TextInput
type="number" type="number"
pattern="-?[0-9]+" pattern="-?[0-9]+"

View file

@ -16,8 +16,6 @@
* along with this program. If not, see <https://www.gnu.org/licenses/>. * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
import { Margins } from "@utils/margins";
import { wordsFromCamel, wordsToTitle } from "@utils/text";
import { PluginOptionSelect } from "@utils/types"; import { PluginOptionSelect } from "@utils/types";
import { Forms, React, Select } from "@webpack/common"; import { Forms, React, Select } from "@webpack/common";
@ -46,8 +44,7 @@ export function SettingSelectComponent({ option, pluginSettings, definedSettings
return ( return (
<Forms.FormSection> <Forms.FormSection>
<Forms.FormTitle>{wordsToTitle(wordsFromCamel(id))}</Forms.FormTitle> <Forms.FormTitle>{option.description}</Forms.FormTitle>
<Forms.FormText className={Margins.bottom16} type="description">{option.description}</Forms.FormText>
<Select <Select
isDisabled={option.disabled?.call(definedSettings) ?? false} isDisabled={option.disabled?.call(definedSettings) ?? false}
options={option.options} options={option.options}

View file

@ -16,8 +16,6 @@
* along with this program. If not, see <https://www.gnu.org/licenses/>. * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
import { Margins } from "@utils/margins";
import { wordsFromCamel, wordsToTitle } from "@utils/text";
import { PluginOptionSlider } from "@utils/types"; import { PluginOptionSlider } from "@utils/types";
import { Forms, React, Slider } from "@webpack/common"; import { Forms, React, Slider } from "@webpack/common";
@ -52,8 +50,7 @@ export function SettingSliderComponent({ option, pluginSettings, definedSettings
return ( return (
<Forms.FormSection> <Forms.FormSection>
<Forms.FormTitle>{wordsToTitle(wordsFromCamel(id))}</Forms.FormTitle> <Forms.FormTitle>{option.description}</Forms.FormTitle>
<Forms.FormText className={Margins.bottom20} type="description">{option.description}</Forms.FormText>
<Slider <Slider
disabled={option.disabled?.call(definedSettings) ?? false} disabled={option.disabled?.call(definedSettings) ?? false}
markers={option.markers} markers={option.markers}

View file

@ -16,8 +16,6 @@
* along with this program. If not, see <https://www.gnu.org/licenses/>. * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
import { Margins } from "@utils/margins";
import { wordsFromCamel, wordsToTitle } from "@utils/text";
import { PluginOptionString } from "@utils/types"; import { PluginOptionString } from "@utils/types";
import { Forms, React, TextInput } from "@webpack/common"; import { Forms, React, TextInput } from "@webpack/common";
@ -43,8 +41,7 @@ export function SettingTextComponent({ option, pluginSettings, definedSettings,
return ( return (
<Forms.FormSection> <Forms.FormSection>
<Forms.FormTitle>{wordsToTitle(wordsFromCamel(id))}</Forms.FormTitle> <Forms.FormTitle>{option.description}</Forms.FormTitle>
<Forms.FormText className={Margins.bottom20} type="description">{option.description}</Forms.FormText>
<TextInput <TextInput
type="text" type="text"
value={state} value={state}

View file

@ -200,8 +200,8 @@ export default definePlugin({
predicate: () => settings.store.sidebar, predicate: () => settings.store.sidebar,
replacement: { replacement: {
// Render the Better Folders sidebar // Render the Better Folders sidebar
match: /(container.{0,50}({className:\i\.guilds,themeOverride:\i})\))/, match: /(?<=({className:\i\.guilds,themeOverride:\i})\))/,
replace: "$1,$self.FolderSideBar({...$2})" replace: ",$self.FolderSideBar({...$1})"
} }
}, },
{ {

View file

@ -1,5 +1,5 @@
# ConsoleJanitor # ConsoleJanitor
Disables annoying console messages/errors. This plugin mainly removes errors/warnings that happen all the time and Discord logger messages. Disables annoying console messages/errors. This plugin mainly removes errors/warnings that happen all the time and noisy/spammy logging messages.
One of the disabled messages is the "Window state not initialized" warning, for example. Some of the disabled messages include the "notosans-400-normalitalic" error and MessageActionCreators, Routing/Utils loggers.

View file

@ -6,7 +6,7 @@
import { definePluginSettings } from "@api/Settings"; import { definePluginSettings } from "@api/Settings";
import { Devs } from "@utils/constants"; import { Devs } from "@utils/constants";
import definePlugin, { OptionType, StartAt } from "@utils/types"; import definePlugin, { OptionType } from "@utils/types";
const Noop = () => { }; const Noop = () => { };
const NoopLogger = { const NoopLogger = {
@ -22,12 +22,10 @@ const NoopLogger = {
fileOnly: Noop fileOnly: Noop
}; };
const logAllow = new Set();
const settings = definePluginSettings({ const settings = definePluginSettings({
disableLoggers: { disableNoisyLoggers: {
type: OptionType.BOOLEAN, type: OptionType.BOOLEAN,
description: "Disables Discords loggers", description: "Disable noisy loggers like the MessageActionCreators",
default: false, default: false,
restartNeeded: true restartNeeded: true
}, },
@ -36,34 +34,16 @@ const settings = definePluginSettings({
description: "Disable the Spotify logger, which leaks account information and access token", description: "Disable the Spotify logger, which leaks account information and access token",
default: true, default: true,
restartNeeded: true restartNeeded: true
},
whitelistedLoggers: {
type: OptionType.STRING,
description: "Semi colon separated list of loggers to allow even if others are hidden",
default: "GatewaySocket; Routing/Utils",
onChange(newVal: string) {
logAllow.clear();
newVal.split(";").map(x => x.trim()).forEach(logAllow.add.bind(logAllow));
}
} }
}); });
export default definePlugin({ export default definePlugin({
name: "ConsoleJanitor", name: "ConsoleJanitor",
description: "Disables annoying console messages/errors", description: "Disables annoying console messages/errors",
authors: [Devs.Nuckyz, Devs.sadan], authors: [Devs.Nuckyz],
settings, settings,
startAt: StartAt.Init,
start() {
logAllow.clear();
this.settings.store.whitelistedLoggers?.split(";").map(x => x.trim()).forEach(logAllow.add.bind(logAllow));
},
NoopLogger: () => NoopLogger, NoopLogger: () => NoopLogger,
shouldLog(logger: string) {
return logAllow.has(logger);
},
patches: [ patches: [
{ {
@ -123,13 +103,34 @@ export default definePlugin({
replace: "" replace: ""
} }
}, },
// Patches discords generic logger function ...[
{ '("MessageActionCreators")', '("ChannelMessages")',
find: "Σ:", '("Routing/Utils")', '("RTCControlSocket")',
predicate: () => settings.store.disableLoggers, '("ConnectionEventFramerateReducer")', '("RTCLatencyTestManager")',
'("OverlayBridgeStore")', '("RPCServer:WSS")', '("RPCServer:IPC")'
].map(logger => ({
find: logger,
predicate: () => settings.store.disableNoisyLoggers,
all: true,
replacement: { replacement: {
match: /(?<=&&)(?=console)/, match: new RegExp(String.raw`new \i\.\i${logger.replace(/([()])/g, "\\$1")}`),
replace: "$self.shouldLog(arguments[0])&&" replace: `$self.NoopLogger${logger}`
}
})),
{
find: '"Experimental codecs: "',
predicate: () => settings.store.disableNoisyLoggers,
replacement: {
match: /new \i\.\i\("Connection\("\.concat\(\i,"\)"\)\)/,
replace: "$self.NoopLogger()"
}
},
{
find: '"_handleLocalVideoDisabled: ',
predicate: () => settings.store.disableNoisyLoggers,
replacement: {
match: /new \i\.\i\("RTCConnection\("\.concat.+?\)\)(?=,)/,
replace: "$self.NoopLogger()"
} }
}, },
{ {
@ -140,5 +141,5 @@ export default definePlugin({
replace: "$self.NoopLogger()" replace: "$self.NoopLogger()"
} }
} }
], ]
}); });

View file

@ -1,7 +1,6 @@
.vc-cfc-button { .vc-cfc-button {
color: var(--interactive-normal); color: var(--interactive-normal);
cursor: pointer; cursor: pointer;
padding-left: 4px;
} }
.vc-cfc-button:hover { .vc-cfc-button:hover {

View file

@ -175,7 +175,7 @@ export default definePlugin({
} }
if (settings.store.attemptToNavigateToHome) { if (settings.store.attemptToNavigateToHome) {
try { try {
NavigationRouter.transitionToGuild("@me"); NavigationRouter.transitionTo("/channels/@me");
} catch (err) { } catch (err) {
CrashHandlerLogger.debug("Failed to navigate to home", err); CrashHandlerLogger.debug("Failed to navigate to home", err);
} }

View file

@ -203,15 +203,6 @@ export default definePlugin({
settings, settings,
patches: [ patches: [
// Patch the emoji picker in voice calls to not be bypassed by fake nitro
{
find: "emojiItemDisabled]",
predicate: () => settings.store.enableEmojiBypass,
replacement: {
match: /CHAT/,
replace: "STATUS"
}
},
{ {
find: ".PREMIUM_LOCKED;", find: ".PREMIUM_LOCKED;",
group: true, group: true,

View file

@ -16,25 +16,16 @@
* along with this program. If not, see <https://www.gnu.org/licenses/>. * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
import { findGroupChildrenByChildId, NavContextMenuPatchCallback } from "@api/ContextMenu";
import { migratePluginSettings } from "@api/Settings"; import { migratePluginSettings } from "@api/Settings";
import { Devs } from "@utils/constants"; import { Devs } from "@utils/constants";
import { NoopComponent } from "@utils/react";
import definePlugin from "@utils/types"; import definePlugin from "@utils/types";
import { filters, findByPropsLazy, waitFor } from "@webpack"; import { findByPropsLazy } from "@webpack";
import { ChannelStore, ContextMenuApi, i18n, UserStore } from "@webpack/common"; import { ChannelStore, ContextMenuApi, i18n, UserStore } from "@webpack/common";
import { Message } from "discord-types/general"; import { Message } from "discord-types/general";
import type { MouseEvent } from "react";
const { useMessageMenu } = findByPropsLazy("useMessageMenu"); const { useMessageMenu } = findByPropsLazy("useMessageMenu");
interface CopyIdMenuItemProps {
id: string;
label: string;
}
let CopyIdMenuItem: (props: CopyIdMenuItemProps) => React.ReactElement | null = NoopComponent;
waitFor(filters.componentByCode('"devmode-copy-id-".concat'), m => CopyIdMenuItem = m);
function MessageMenu({ message, channel, onHeightUpdate }) { function MessageMenu({ message, channel, onHeightUpdate }) {
const canReport = message.author && const canReport = message.author &&
!(message.author.id === UserStore.getCurrentUser().id || message.author.system); !(message.author.id === UserStore.getCurrentUser().id || message.author.system);
@ -57,25 +48,9 @@ function MessageMenu({ message, channel, onHeightUpdate }) {
itemSrc: void 0, itemSrc: void 0,
itemSafeSrc: void 0, itemSafeSrc: void 0,
itemTextContent: void 0, itemTextContent: void 0,
isFullSearchContextMenu: true
}); });
} }
interface MessageActionsProps {
message: Message;
isFullSearchContextMenu?: boolean;
}
const contextMenuPatch: NavContextMenuPatchCallback = (children, props: MessageActionsProps) => {
if (props?.isFullSearchContextMenu == null) return;
const group = findGroupChildrenByChildId("devmode-copy-id", children, true);
group?.push(
CopyIdMenuItem({ id: props.message.author.id, label: i18n.Messages.COPY_ID_AUTHOR })
);
};
migratePluginSettings("FullSearchContext", "SearchReply"); migratePluginSettings("FullSearchContext", "SearchReply");
export default definePlugin({ export default definePlugin({
name: "FullSearchContext", name: "FullSearchContext",
@ -90,7 +65,7 @@ export default definePlugin({
} }
}], }],
handleContextMenu(event: React.MouseEvent, message: Message) { handleContextMenu(event: MouseEvent, message: Message) {
const channel = ChannelStore.getChannel(message.channel_id); const channel = ChannelStore.getChannel(message.channel_id);
if (!channel) return; if (!channel) return;
@ -103,9 +78,5 @@ export default definePlugin({
onHeightUpdate={contextMenuProps.onHeightUpdate} onHeightUpdate={contextMenuProps.onHeightUpdate}
/> />
); );
},
contextMenus: {
"message-actions": contextMenuPatch
} }
}); });

View file

@ -19,7 +19,7 @@
import * as DataStore from "@api/DataStore"; import * as DataStore from "@api/DataStore";
import { Devs } from "@utils/constants"; import { Devs } from "@utils/constants";
import definePlugin from "@utils/types"; import definePlugin from "@utils/types";
import { ChannelRouter, SelectedChannelStore, SelectedGuildStore } from "@webpack/common"; import { ChannelStore, NavigationRouter, SelectedChannelStore, SelectedGuildStore } from "@webpack/common";
export interface LogoutEvent { export interface LogoutEvent {
type: "LOGOUT"; type: "LOGOUT";
@ -40,6 +40,11 @@ interface PreviousChannel {
let isSwitchingAccount = false; let isSwitchingAccount = false;
let previousCache: PreviousChannel | undefined; let previousCache: PreviousChannel | undefined;
function attemptToNavigateToChannel(guildId: string | null, channelId: string) {
if (!ChannelStore.hasChannel(channelId)) return;
NavigationRouter.transitionTo(`/channels/${guildId ?? "@me"}/${channelId}`);
}
export default definePlugin({ export default definePlugin({
name: "KeepCurrentChannel", name: "KeepCurrentChannel",
description: "Attempt to navigate to the channel you were in before switching accounts or loading Discord.", description: "Attempt to navigate to the channel you were in before switching accounts or loading Discord.",
@ -54,9 +59,8 @@ export default definePlugin({
if (!isSwitchingAccount) return; if (!isSwitchingAccount) return;
isSwitchingAccount = false; isSwitchingAccount = false;
if (previousCache?.channelId) { if (previousCache?.channelId)
ChannelRouter.transitionToChannel(previousCache.channelId); attemptToNavigateToChannel(previousCache.guildId, previousCache.channelId);
}
}, },
async CHANNEL_SELECT({ guildId, channelId }: ChannelSelectEvent) { async CHANNEL_SELECT({ guildId, channelId }: ChannelSelectEvent) {
@ -80,7 +84,7 @@ export default definePlugin({
await DataStore.set("KeepCurrentChannel_previousData", previousCache); await DataStore.set("KeepCurrentChannel_previousData", previousCache);
} else if (previousCache.channelId) { } else if (previousCache.channelId) {
ChannelRouter.transitionToChannel(previousCache.channelId); attemptToNavigateToChannel(previousCache.guildId, previousCache.channelId);
} }
} }
}); });

View file

@ -100,20 +100,6 @@ export default definePlugin({
replace: "true$1VencordNative.native.openExternal" replace: "true$1VencordNative.native.openExternal"
} }
}, },
{
find: "no artist ids in metadata",
predicate: () => !IS_DISCORD_DESKTOP && pluginSettings.store.spotify,
replacement: [
{
match: /\i\.\i\.isProtocolRegistered\(\)/g,
replace: "true"
},
{
match: /!\(0,\i\.isDesktop\)\(\)/,
replace: "false"
}
]
},
{ {
find: ".CONNECTED_ACCOUNT_VIEWED,", find: ".CONNECTED_ACCOUNT_VIEWED,",
replacement: { replacement: {

View file

@ -1,172 +0,0 @@
/*
* Vencord, a modification for Discord's desktop app
* Copyright (c) 2022 Vendicated and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import { getCurrentChannel } from "@utils/discord";
import { useAwaiter } from "@utils/react";
import { findStoreLazy } from "@webpack";
import { UserProfileStore, UserStore } from "@webpack/common";
import { settings } from "./settings";
import { PronounMapping, Pronouns, PronounsCache, PronounSets, PronounsFormat, PronounSource, PronounsResponse } from "./types";
const UserSettingsAccountStore = findStoreLazy("UserSettingsAccountStore");
const EmptyPronouns = { pronouns: undefined, source: "", hasPendingPronouns: false } as const satisfies Pronouns;
type RequestCallback = (pronounSets?: PronounSets) => void;
const pronounCache: Record<string, PronounsCache> = {};
const requestQueue: Record<string, RequestCallback[]> = {};
let isProcessing = false;
async function processQueue() {
if (isProcessing) return;
isProcessing = true;
let ids = Object.keys(requestQueue);
while (ids.length > 0) {
const idsChunk = ids.splice(0, 50);
const pronouns = await bulkFetchPronouns(idsChunk);
for (const id of idsChunk) {
const callbacks = requestQueue[id];
for (const callback of callbacks) {
callback(pronouns[id]?.sets);
}
delete requestQueue[id];
}
ids = Object.keys(requestQueue);
await new Promise(r => setTimeout(r, 2000));
}
isProcessing = false;
}
function fetchPronouns(id: string): Promise<string | undefined> {
return new Promise(resolve => {
if (pronounCache[id] != null) {
resolve(extractPronouns(pronounCache[id].sets));
return;
}
function handlePronouns(pronounSets?: PronounSets) {
const pronouns = extractPronouns(pronounSets);
resolve(pronouns);
}
if (requestQueue[id] != null) {
requestQueue[id].push(handlePronouns);
return;
}
requestQueue[id] = [handlePronouns];
processQueue();
});
}
async function bulkFetchPronouns(ids: string[]): Promise<PronounsResponse> {
const params = new URLSearchParams();
params.append("platform", "discord");
params.append("ids", ids.join(","));
try {
const req = await fetch("https://pronoundb.org/api/v2/lookup?" + String(params), {
method: "GET",
headers: {
"Accept": "application/json",
"X-PronounDB-Source": "WebExtension/0.14.5"
}
});
if (!req.ok) throw new Error(`Status ${req.status}`);
const res: PronounsResponse = await req.json();
Object.assign(pronounCache, res);
return res;
} catch (e) {
console.error("PronounDB request failed:", e);
const dummyPronouns: PronounsResponse = Object.fromEntries(ids.map(id => [id, { sets: {} }]));
Object.assign(pronounCache, dummyPronouns);
return dummyPronouns;
}
}
function extractPronouns(pronounSets?: PronounSets): string | undefined {
if (pronounSets == null) return undefined;
if (pronounSets.en == null) return PronounMapping.unspecified;
const pronouns = pronounSets.en;
if (pronouns.length === 0) return PronounMapping.unspecified;
const { pronounsFormat } = settings.store;
if (pronouns.length > 1) {
const pronounString = pronouns.map(p => p[0].toUpperCase() + p.slice(1)).join("/");
return pronounsFormat === PronounsFormat.Capitalized ? pronounString : pronounString.toLowerCase();
}
const pronoun = pronouns[0];
// For capitalized pronouns or special codes (any, ask, avoid), we always return the normal (capitalized) string
if (pronounsFormat === PronounsFormat.Capitalized || ["any", "ask", "avoid", "other", "unspecified"].includes(pronoun)) {
return PronounMapping[pronoun];
} else {
return PronounMapping[pronoun].toLowerCase();
}
}
function getDiscordPronouns(id: string, useGlobalProfile: boolean = false): string | undefined {
const globalPronouns = UserProfileStore.getUserProfile(id)?.pronouns;
if (useGlobalProfile) return globalPronouns;
return UserProfileStore.getGuildMemberProfile(id, getCurrentChannel()?.guild_id)?.pronouns || globalPronouns;
}
export function useFormattedPronouns(id: string, useGlobalProfile: boolean = false): Pronouns {
const discordPronouns = getDiscordPronouns(id, useGlobalProfile)?.trim().replace(/\n+/g, "");
const hasPendingPronouns = UserSettingsAccountStore.getPendingPronouns() != null;
const [pronouns] = useAwaiter(() => fetchPronouns(id));
if (settings.store.pronounSource === PronounSource.PreferDiscord && discordPronouns) {
return { pronouns: discordPronouns, source: "Discord", hasPendingPronouns };
}
if (pronouns != null && pronouns !== PronounMapping.unspecified) {
return { pronouns, source: "PronounDB", hasPendingPronouns };
}
return { pronouns: discordPronouns, source: "Discord", hasPendingPronouns };
}
export function useProfilePronouns(id: string, useGlobalProfile: boolean = false): Pronouns {
try {
const pronouns = useFormattedPronouns(id, useGlobalProfile);
if (!settings.store.showInProfile) return EmptyPronouns;
if (!settings.store.showSelf && id === UserStore.getCurrentUser()?.id) return EmptyPronouns;
return pronouns;
} catch (e) {
console.error(e);
return EmptyPronouns;
}
}

View file

@ -22,7 +22,7 @@ import { findByPropsLazy } from "@webpack";
import { UserStore } from "@webpack/common"; import { UserStore } from "@webpack/common";
import { Message } from "discord-types/general"; import { Message } from "discord-types/general";
import { useFormattedPronouns } from "../api"; import { useFormattedPronouns } from "../pronoundbUtils";
import { settings } from "../settings"; import { settings } from "../settings";
const styles: Record<string, string> = findByPropsLazy("timestampInline"); const styles: Record<string, string> = findByPropsLazy("timestampInline");
@ -53,21 +53,25 @@ export const CompactPronounsChatComponentWrapper = ErrorBoundary.wrap(({ message
}, { noop: true }); }, { noop: true });
function PronounsChatComponent({ message }: { message: Message; }) { function PronounsChatComponent({ message }: { message: Message; }) {
const { pronouns } = useFormattedPronouns(message.author.id); const [result] = useFormattedPronouns(message.author.id);
return pronouns && ( return result
? (
<span <span
className={classes(styles.timestampInline, styles.timestamp)} className={classes(styles.timestampInline, styles.timestamp)}
> {pronouns}</span> > {result}</span>
); )
: null;
} }
export const CompactPronounsChatComponent = ErrorBoundary.wrap(({ message }: { message: Message; }) => { export const CompactPronounsChatComponent = ErrorBoundary.wrap(({ message }: { message: Message; }) => {
const { pronouns } = useFormattedPronouns(message.author.id); const [result] = useFormattedPronouns(message.author.id);
return pronouns && ( return result
? (
<span <span
className={classes(styles.timestampInline, styles.timestamp, "vc-pronoundb-compact")} className={classes(styles.timestampInline, styles.timestamp, "vc-pronoundb-compact")}
> {pronouns}</span> > {result}</span>
); )
: null;
}, { noop: true }); }, { noop: true });

View file

@ -21,9 +21,9 @@ import "./styles.css";
import { Devs } from "@utils/constants"; import { Devs } from "@utils/constants";
import definePlugin from "@utils/types"; import definePlugin from "@utils/types";
import { useProfilePronouns } from "./api";
import PronounsAboutComponent from "./components/PronounsAboutComponent"; import PronounsAboutComponent from "./components/PronounsAboutComponent";
import { CompactPronounsChatComponentWrapper, PronounsChatComponentWrapper } from "./components/PronounsChatComponent"; import { CompactPronounsChatComponentWrapper, PronounsChatComponentWrapper } from "./components/PronounsChatComponent";
import { useProfilePronouns } from "./pronoundbUtils";
import { settings } from "./settings"; import { settings } from "./settings";
export default definePlugin({ export default definePlugin({
@ -53,15 +53,15 @@ export default definePlugin({
replacement: [ replacement: [
{ {
match: /\.PANEL},/, match: /\.PANEL},/,
replace: "$&{pronouns:vcPronoun,source:vcPronounSource,hasPendingPronouns:vcHasPendingPronouns}=$self.useProfilePronouns(arguments[0].user?.id)," replace: "$&[vcPronoun,vcPronounSource,vcHasPendingPronouns]=$self.useProfilePronouns(arguments[0].user?.id),"
}, },
{ {
match: /text:\i\.\i.Messages.USER_PROFILE_PRONOUNS/, match: /text:\i\.\i.Messages.USER_PROFILE_PRONOUNS/,
replace: '$&+(vcPronoun==null||vcHasPendingPronouns?"":` (${vcPronounSource})`)' replace: '$&+(vcHasPendingPronouns?"":` (${vcPronounSource})`)'
}, },
{ {
match: /(\.pronounsText.+?children:)(\i)/, match: /(\.pronounsText.+?children:)(\i)/,
replace: "$1(vcPronoun==null||vcHasPendingPronouns)?$2:vcPronoun" replace: "$1vcHasPendingPronouns?$2:vcPronoun"
} }
] ]
} }

View file

@ -0,0 +1,169 @@
/*
* Vencord, a modification for Discord's desktop app
* Copyright (c) 2022 Vendicated and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import { Settings } from "@api/Settings";
import { debounce } from "@shared/debounce";
import { VENCORD_USER_AGENT } from "@shared/vencordUserAgent";
import { getCurrentChannel } from "@utils/discord";
import { useAwaiter } from "@utils/react";
import { findStoreLazy } from "@webpack";
import { UserProfileStore, UserStore } from "@webpack/common";
import { settings } from "./settings";
import { CachePronouns, PronounCode, PronounMapping, PronounsResponse } from "./types";
const UserSettingsAccountStore = findStoreLazy("UserSettingsAccountStore");
type PronounsWithSource = [pronouns: string | null, source: string, hasPendingPronouns: boolean];
const EmptyPronouns: PronounsWithSource = [null, "", false];
export const enum PronounsFormat {
Lowercase = "LOWERCASE",
Capitalized = "CAPITALIZED"
}
export const enum PronounSource {
PreferPDB,
PreferDiscord
}
// A map of cached pronouns so the same request isn't sent twice
const cache: Record<string, CachePronouns> = {};
// A map of ids and callbacks that should be triggered on fetch
const requestQueue: Record<string, ((pronouns: string) => void)[]> = {};
// Executes all queued requests and calls their callbacks
const bulkFetch = debounce(async () => {
const ids = Object.keys(requestQueue);
const pronouns = await bulkFetchPronouns(ids);
for (const id of ids) {
// Call all callbacks for the id
requestQueue[id]?.forEach(c => c(pronouns[id] ? extractPronouns(pronouns[id].sets) : ""));
delete requestQueue[id];
}
});
function getDiscordPronouns(id: string, useGlobalProfile: boolean = false) {
const globalPronouns = UserProfileStore.getUserProfile(id)?.pronouns;
if (useGlobalProfile) return globalPronouns;
return (
UserProfileStore.getGuildMemberProfile(id, getCurrentChannel()?.guild_id)?.pronouns
|| globalPronouns
);
}
export function useFormattedPronouns(id: string, useGlobalProfile: boolean = false): PronounsWithSource {
// Discord is so stupid you can put tons of newlines in pronouns
const discordPronouns = getDiscordPronouns(id, useGlobalProfile)?.trim().replace(NewLineRe, " ");
const [result] = useAwaiter(() => fetchPronouns(id), {
fallbackValue: getCachedPronouns(id),
onError: e => console.error("Fetching pronouns failed: ", e)
});
const hasPendingPronouns = UserSettingsAccountStore.getPendingPronouns() != null;
if (settings.store.pronounSource === PronounSource.PreferDiscord && discordPronouns)
return [discordPronouns, "Discord", hasPendingPronouns];
if (result && result !== PronounMapping.unspecified)
return [result, "PronounDB", hasPendingPronouns];
return [discordPronouns, "Discord", hasPendingPronouns];
}
export function useProfilePronouns(id: string, useGlobalProfile: boolean = false): PronounsWithSource {
const pronouns = useFormattedPronouns(id, useGlobalProfile);
if (!settings.store.showInProfile) return EmptyPronouns;
if (!settings.store.showSelf && id === UserStore.getCurrentUser().id) return EmptyPronouns;
return pronouns;
}
const NewLineRe = /\n+/g;
// Gets the cached pronouns, if you're too impatient for a promise!
export function getCachedPronouns(id: string): string | null {
const cached = cache[id] ? extractPronouns(cache[id].sets) : undefined;
if (cached && cached !== PronounMapping.unspecified) return cached;
return cached || null;
}
// Fetches the pronouns for one id, returning a promise that resolves if it was cached, or once the request is completed
export function fetchPronouns(id: string): Promise<string> {
return new Promise(res => {
const cached = getCachedPronouns(id);
if (cached) return res(cached);
// If there is already a request added, then just add this callback to it
if (id in requestQueue) return requestQueue[id].push(res);
// If not already added, then add it and call the debounced function to make sure the request gets executed
requestQueue[id] = [res];
bulkFetch();
});
}
async function bulkFetchPronouns(ids: string[]): Promise<PronounsResponse> {
const params = new URLSearchParams();
params.append("platform", "discord");
params.append("ids", ids.join(","));
try {
const req = await fetch("https://pronoundb.org/api/v2/lookup?" + params.toString(), {
method: "GET",
headers: {
"Accept": "application/json",
"X-PronounDB-Source": VENCORD_USER_AGENT
}
});
return await req.json()
.then((res: PronounsResponse) => {
Object.assign(cache, res);
return res;
});
} catch (e) {
// If the request errors, treat it as if no pronouns were found for all ids, and log it
console.error("PronounDB fetching failed: ", e);
const dummyPronouns = Object.fromEntries(ids.map(id => [id, { sets: {} }] as const));
Object.assign(cache, dummyPronouns);
return dummyPronouns;
}
}
export function extractPronouns(pronounSet?: { [locale: string]: PronounCode[]; }): string {
if (!pronounSet || !pronounSet.en) return PronounMapping.unspecified;
// PronounDB returns an empty set instead of {sets: {en: ["unspecified"]}}.
const pronouns = pronounSet.en;
const { pronounsFormat } = Settings.plugins.PronounDB as { pronounsFormat: PronounsFormat, enabled: boolean; };
if (pronouns.length === 1) {
// For capitalized pronouns or special codes (any, ask, avoid), we always return the normal (capitalized) string
if (pronounsFormat === PronounsFormat.Capitalized || ["any", "ask", "avoid", "other", "unspecified"].includes(pronouns[0]))
return PronounMapping[pronouns[0]];
else return PronounMapping[pronouns[0]].toLowerCase();
}
const pronounString = pronouns.map(p => p[0].toUpperCase() + p.slice(1)).join("/");
return pronounsFormat === PronounsFormat.Capitalized ? pronounString : pronounString.toLowerCase();
}

View file

@ -19,7 +19,7 @@
import { definePluginSettings } from "@api/Settings"; import { definePluginSettings } from "@api/Settings";
import { OptionType } from "@utils/types"; import { OptionType } from "@utils/types";
import { PronounsFormat, PronounSource } from "./types"; import { PronounsFormat, PronounSource } from "./pronoundbUtils";
export const settings = definePluginSettings({ export const settings = definePluginSettings({
pronounsFormat: { pronounsFormat: {

View file

@ -25,12 +25,21 @@ export interface UserProfilePronounsProps {
hidePersonalInformation: boolean; hidePersonalInformation: boolean;
} }
export type PronounSets = Record<string, PronounCode[]>; export interface PronounsResponse {
export type PronounsResponse = Record<string, { sets?: PronounSets; }>; [id: string]: {
sets?: {
export interface PronounsCache { [locale: string]: PronounCode[];
sets?: PronounSets;
} }
}
}
export interface CachePronouns {
sets?: {
[locale: string]: PronounCode[];
}
}
export type PronounCode = keyof typeof PronounMapping;
export const PronounMapping = { export const PronounMapping = {
he: "He/Him", he: "He/Him",
@ -42,22 +51,4 @@ export const PronounMapping = {
ask: "Ask me my pronouns", ask: "Ask me my pronouns",
avoid: "Avoid pronouns, use my name", avoid: "Avoid pronouns, use my name",
unspecified: "No pronouns specified.", unspecified: "No pronouns specified.",
} as const satisfies Record<string, string>; } as const;
export type PronounCode = keyof typeof PronounMapping;
export interface Pronouns {
pronouns?: string;
source: string;
hasPendingPronouns: boolean;
}
export const enum PronounsFormat {
Lowercase = "LOWERCASE",
Capitalized = "CAPITALIZED"
}
export const enum PronounSource {
PreferPDB,
PreferDiscord
}

View file

@ -12,7 +12,7 @@ import { Flex, Menu } from "@webpack/common";
const DefaultEngines = { const DefaultEngines = {
Google: "https://www.google.com/search?q=", Google: "https://www.google.com/search?q=",
DuckDuckGo: "https://duckduckgo.com/?q=", DuckDuckGo: "https://duckduckgo.com/",
Brave: "https://search.brave.com/search?q=", Brave: "https://search.brave.com/search?q=",
Bing: "https://www.bing.com/search?q=", Bing: "https://www.bing.com/search?q=",
Yahoo: "https://search.yahoo.com/search?p=", Yahoo: "https://search.yahoo.com/search?p=",

View file

@ -91,7 +91,7 @@ export default definePlugin({
} }
}, },
{ {
find: 'location:"UserProfilePanel"', find: ".PANEL,interactionType:",
replacement: { replacement: {
match: /{profileType:\i\.\i\.PANEL,children:\[/, match: /{profileType:\i\.\i\.PANEL,children:\[/,
replace: "$&$self.BiteSizeReviewsButton({user:arguments[0].user})," replace: "$&$self.BiteSizeReviewsButton({user:arguments[0].user}),"

View file

@ -18,14 +18,10 @@
import { definePluginSettings } from "@api/Settings"; import { definePluginSettings } from "@api/Settings";
import ErrorBoundary from "@components/ErrorBoundary"; import ErrorBoundary from "@components/ErrorBoundary";
import { makeRange } from "@components/PluginSettings/components";
import { Devs } from "@utils/constants"; import { Devs } from "@utils/constants";
import definePlugin, { OptionType } from "@utils/types"; import definePlugin, { OptionType } from "@utils/types";
import { findByCodeLazy } from "@webpack";
import { ChannelStore, GuildMemberStore, GuildStore } from "@webpack/common"; import { ChannelStore, GuildMemberStore, GuildStore } from "@webpack/common";
const useMessageAuthor = findByCodeLazy('"Result cannot be null because the message is not null"');
const settings = definePluginSettings({ const settings = definePluginSettings({
chatMentions: { chatMentions: {
type: OptionType.BOOLEAN, type: OptionType.BOOLEAN,
@ -50,25 +46,13 @@ const settings = definePluginSettings({
default: true, default: true,
description: "Show role colors in the reactors list", description: "Show role colors in the reactors list",
restartNeeded: true restartNeeded: true
}, }
colorChatMessages: {
type: OptionType.BOOLEAN,
default: false,
description: "Color chat messages based on the author's role color",
restartNeeded: true,
},
messageSaturation: {
type: OptionType.SLIDER,
description: "Intensity of message coloring.",
markers: makeRange(0, 100, 10),
default: 30
},
}); });
export default definePlugin({ export default definePlugin({
name: "RoleColorEverywhere", name: "RoleColorEverywhere",
authors: [Devs.KingFish, Devs.lewisakura, Devs.AutumnVN, Devs.Kyuuhachi], authors: [Devs.KingFish, Devs.lewisakura, Devs.AutumnVN],
description: "Adds the top role color anywhere possible", description: "Adds the top role color anywhere possible",
patches: [ patches: [
// Chat Mentions // Chat Mentions
@ -130,15 +114,7 @@ export default definePlugin({
replace: "$&,style:{color:$self.getColor($2?.id,$1)}" replace: "$&,style:{color:$self.getColor($2?.id,$1)}"
}, },
predicate: () => settings.store.reactorsList, predicate: () => settings.store.reactorsList,
}, }
{
find: '.Messages.MESSAGE_EDITED,")"',
replacement: {
match: /(?<=isUnsupported\]:(\i)\.isUnsupported\}\),)(?=children:\[)/,
replace: "style:{color:$self.useMessageColor($1)},"
},
predicate: () => settings.store.colorChatMessages,
},
], ],
settings, settings,
@ -172,17 +148,5 @@ export default definePlugin({
color: this.getColor(userId, { guildId }) color: this.getColor(userId, { guildId })
} }
}; };
},
useMessageColor(message: any) {
try {
const { messageSaturation } = settings.use(["messageSaturation"]);
const author = useMessageAuthor(message);
if (author.colorString !== undefined && messageSaturation !== 0)
return `color-mix(in oklab, ${author.colorString} ${messageSaturation}%, var(--text-normal))`;
} catch (e) {
console.error("[RCE] failed to get message color", e);
} }
return undefined;
},
}); });

View file

@ -8,7 +8,7 @@ import { classNameFactory } from "@api/Styles";
import ErrorBoundary from "@components/ErrorBoundary"; import ErrorBoundary from "@components/ErrorBoundary";
import { classes } from "@utils/misc"; import { classes } from "@utils/misc";
import { filters, findByCodeLazy, findByPropsLazy, findComponentByCodeLazy, findStoreLazy, mapMangledModuleLazy } from "@webpack"; import { filters, findByCodeLazy, findByPropsLazy, findComponentByCodeLazy, findStoreLazy, mapMangledModuleLazy } from "@webpack";
import { ChannelRouter, ChannelStore, GuildStore, IconUtils, match, P, PermissionsBits, PermissionStore, React, showToast, Text, Toasts, Tooltip, useMemo, UserStore, useStateFromStores } from "@webpack/common"; import { ChannelStore, GuildStore, IconUtils, match, NavigationRouter, P, PermissionsBits, PermissionStore, React, showToast, Text, Toasts, Tooltip, useMemo, UserStore, useStateFromStores } from "@webpack/common";
import { Channel } from "discord-types/general"; import { Channel } from "discord-types/general";
const cl = classNameFactory("vc-uvs-"); const cl = classNameFactory("vc-uvs-");
@ -24,8 +24,6 @@ const UserSummaryItem = findComponentByCodeLazy("defaultRenderUser", "showDefaul
const Avatar = findComponentByCodeLazy(".AVATAR_STATUS_TYPING_16;"); const Avatar = findComponentByCodeLazy(".AVATAR_STATUS_TYPING_16;");
const GroupDMAvatars = findComponentByCodeLazy(".AvatarSizeSpecs[", "getAvatarURL"); const GroupDMAvatars = findComponentByCodeLazy(".AvatarSizeSpecs[", "getAvatarURL");
const ActionButtonClasses = findByPropsLazy("actionButton", "highlight");
interface IconProps extends React.ComponentPropsWithoutRef<"div"> { interface IconProps extends React.ComponentPropsWithoutRef<"div"> {
size?: number; size?: number;
} }
@ -76,10 +74,9 @@ function LockedSpeakerIcon(props: IconProps) {
interface VoiceChannelTooltipProps { interface VoiceChannelTooltipProps {
channel: Channel; channel: Channel;
isLocked: boolean;
} }
function VoiceChannelTooltip({ channel, isLocked }: VoiceChannelTooltipProps) { function VoiceChannelTooltip({ channel }: VoiceChannelTooltipProps) {
const voiceStates = useStateFromStores([VoiceStateStore], () => VoiceStateStore.getVoiceStatesForChannel(channel.id)); const voiceStates = useStateFromStores([VoiceStateStore], () => VoiceStateStore.getVoiceStatesForChannel(channel.id));
const users = useMemo( const users = useMemo(
@ -116,7 +113,7 @@ function VoiceChannelTooltip({ channel, isLocked }: VoiceChannelTooltipProps) {
<Text variant="text-sm/semibold">{channelName}</Text> <Text variant="text-sm/semibold">{channelName}</Text>
</div> </div>
<div className={cl("vc-members")}> <div className={cl("vc-members")}>
{isLocked ? <LockedSpeakerIcon size={18} /> : <SpeakerIcon size={18} />} <SpeakerIcon size={18} />
<UserSummaryItem <UserSummaryItem
users={users} users={users}
renderIcon={false} renderIcon={false}
@ -130,23 +127,19 @@ function VoiceChannelTooltip({ channel, isLocked }: VoiceChannelTooltipProps) {
interface VoiceChannelIndicatorProps { interface VoiceChannelIndicatorProps {
userId: string; userId: string;
isMessageIndicator?: boolean; size?: number;
isProfile?: boolean;
isActionButton?: boolean; isActionButton?: boolean;
shouldHighlight?: boolean;
} }
const clickTimers = {} as Record<string, any>; const clickTimers = {} as Record<string, any>;
export const VoiceChannelIndicator = ErrorBoundary.wrap(({ userId, isMessageIndicator, isProfile, isActionButton, shouldHighlight }: VoiceChannelIndicatorProps) => { export const VoiceChannelIndicator = ErrorBoundary.wrap(({ userId, size, isActionButton }: VoiceChannelIndicatorProps) => {
const channelId = useStateFromStores([VoiceStateStore], () => VoiceStateStore.getVoiceStateForUser(userId)?.channelId as string | undefined); const channelId = useStateFromStores([VoiceStateStore], () => VoiceStateStore.getVoiceStateForUser(userId)?.channelId as string | undefined);
const channel = channelId == null ? undefined : ChannelStore.getChannel(channelId); const channel = channelId == null ? undefined : ChannelStore.getChannel(channelId);
if (channel == null) return null; if (channel == null) return null;
const isDM = channel.isDM() || channel.isMultiUserDM(); const isDM = channel.isDM() || channel.isMultiUserDM();
if (!isDM && !PermissionStore.can(PermissionsBits.VIEW_CHANNEL, channel) && !Vencord.Plugins.isPluginEnabled("ShowHiddenChannels")) return null;
const isLocked = !isDM && (!PermissionStore.can(PermissionsBits.VIEW_CHANNEL, channel) || !PermissionStore.can(PermissionsBits.CONNECT, channel)); const isLocked = !isDM && (!PermissionStore.can(PermissionsBits.VIEW_CHANNEL, channel) || !PermissionStore.can(PermissionsBits.CONNECT, channel));
function onClick(e: React.MouseEvent) { function onClick(e: React.MouseEvent) {
@ -155,6 +148,11 @@ export const VoiceChannelIndicator = ErrorBoundary.wrap(({ userId, isMessageIndi
if (channel == null || channelId == null) return; if (channel == null || channelId == null) return;
if (!isDM && !PermissionStore.can(PermissionsBits.VIEW_CHANNEL, channel)) {
showToast("You cannot view the user's Voice Channel", Toasts.Type.FAILURE);
return;
}
clearTimeout(clickTimers[channelId]); clearTimeout(clickTimers[channelId]);
delete clickTimers[channelId]; delete clickTimers[channelId];
@ -167,7 +165,7 @@ export const VoiceChannelIndicator = ErrorBoundary.wrap(({ userId, isMessageIndi
selectVoiceChannel(channelId); selectVoiceChannel(channelId);
} else { } else {
clickTimers[channelId] = setTimeout(() => { clickTimers[channelId] = setTimeout(() => {
ChannelRouter.transitionToChannel(channelId); NavigationRouter.transitionTo(`/channels/${channel.getGuildId() ?? "@me"}/${channelId}`);
delete clickTimers[channelId]; delete clickTimers[channelId];
}, 250); }, 250);
} }
@ -175,16 +173,16 @@ export const VoiceChannelIndicator = ErrorBoundary.wrap(({ userId, isMessageIndi
return ( return (
<Tooltip <Tooltip
text={<VoiceChannelTooltip channel={channel} isLocked={isLocked} />} text={<VoiceChannelTooltip channel={channel} />}
tooltipClassName={cl("tooltip-container")} tooltipClassName={cl("tooltip-container")}
tooltipContentClassName={cl("tooltip-content")} tooltipContentClassName={cl("tooltip-content")}
> >
{props => { {props => {
const iconProps: IconProps = { const iconProps = {
...props, ...props,
className: classes(isMessageIndicator && cl("message-indicator"), (!isProfile && !isActionButton) && cl("speaker-margin"), isActionButton && ActionButtonClasses.actionButton, shouldHighlight && ActionButtonClasses.highlight), onClick,
size: isActionButton ? 20 : undefined, size,
onClick className: isActionButton ? cl("indicator-action-button") : cl("speaker-padding")
}; };
return isLocked ? return isLocked ?

View file

@ -19,7 +19,6 @@
import "./style.css"; import "./style.css";
import { addDecorator, removeDecorator } from "@api/MemberListDecorators"; import { addDecorator, removeDecorator } from "@api/MemberListDecorators";
import { addDecoration, removeDecoration } from "@api/MessageDecorations";
import { definePluginSettings } from "@api/Settings"; import { definePluginSettings } from "@api/Settings";
import { Devs } from "@utils/constants"; import { Devs } from "@utils/constants";
import definePlugin, { OptionType } from "@utils/types"; import definePlugin, { OptionType } from "@utils/types";
@ -38,20 +37,13 @@ const settings = definePluginSettings({
description: "Show a user's Voice Channel indicator in the member and DMs list", description: "Show a user's Voice Channel indicator in the member and DMs list",
default: true, default: true,
restartNeeded: true restartNeeded: true
},
showInMessages: {
type: OptionType.BOOLEAN,
description: "Show a user's Voice Channel indicator in messages",
default: true,
restartNeeded: true
} }
}); });
export default definePlugin({ export default definePlugin({
name: "UserVoiceShow", name: "UserVoiceShow",
description: "Shows an indicator when a user is in a Voice Channel", description: "Shows an indicator when a user is in a Voice Channel",
authors: [Devs.Nuckyz, Devs.LordElias], authors: [Devs.LordElias, Devs.Nuckyz],
dependencies: ["MemberListDecoratorsAPI", "MessageDecorationsAPI"],
settings, settings,
patches: [ patches: [
@ -60,7 +52,7 @@ export default definePlugin({
find: ".Messages.USER_PROFILE_LOAD_ERROR", find: ".Messages.USER_PROFILE_LOAD_ERROR",
replacement: { replacement: {
match: /(\.fetchError.+?\?)null/, match: /(\.fetchError.+?\?)null/,
replace: (_, rest) => `${rest}$self.VoiceChannelIndicator({userId:arguments[0]?.userId,isProfile:true})` replace: (_, rest) => `${rest}$self.VoiceChannelIndicator({userId:arguments[0]?.userId})`
}, },
predicate: () => settings.store.showInUserProfileModal predicate: () => settings.store.showInUserProfileModal
}, },
@ -87,8 +79,8 @@ export default definePlugin({
{ {
find: "null!=this.peopleListItemRef.current", find: "null!=this.peopleListItemRef.current",
replacement: { replacement: {
match: /\.actions,children:\[(?<=isFocused:(\i).+?)/, match: /\.actions,children:\[/,
replace: "$&$self.VoiceChannelIndicator({userId:this?.props?.user?.id,isActionButton:true,shouldHighlight:$1})," replace: "$&$self.VoiceChannelIndicator({userId:this?.props?.user?.id,size:20,isActionButton:true}),"
}, },
predicate: () => settings.store.showInMemberList predicate: () => settings.store.showInMemberList
} }
@ -98,14 +90,10 @@ export default definePlugin({
if (settings.store.showInMemberList) { if (settings.store.showInMemberList) {
addDecorator("UserVoiceShow", ({ user }) => user == null ? null : <VoiceChannelIndicator userId={user.id} />); addDecorator("UserVoiceShow", ({ user }) => user == null ? null : <VoiceChannelIndicator userId={user.id} />);
} }
if (settings.store.showInMessages) {
addDecoration("UserVoiceShow", ({ message }) => message?.author == null ? null : <VoiceChannelIndicator userId={message.author.id} isMessageIndicator />);
}
}, },
stop() { stop() {
removeDecorator("UserVoiceShow"); removeDecorator("UserVoiceShow");
removeDecoration("UserVoiceShow");
}, },
VoiceChannelIndicator VoiceChannelIndicator

View file

@ -13,14 +13,16 @@
color: var(--interactive-hover); color: var(--interactive-hover);
} }
.vc-uvs-speaker-margin { .vc-uvs-speaker-padding {
margin-left: 4px; padding: 0 4px;
} }
.vc-uvs-message-indicator { .vc-uvs-indicator-action-button {
display: inline-flex; background-color: var(--background-secondary);
top: 2.5px; border-radius: 100%;
position: relative; height: 36px;
width: 36px;
margin-left: 10px;
} }
.vc-uvs-tooltip-container { .vc-uvs-tooltip-container {

View file

@ -16,7 +16,7 @@
* along with this program. If not, see <https://www.gnu.org/licenses/>. * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
import { Channel, Guild, GuildMember, User } from "discord-types/general"; import { Guild, GuildMember, User } from "discord-types/general";
import type { ReactNode } from "react"; import type { ReactNode } from "react";
import { LiteralUnion } from "type-fest"; import { LiteralUnion } from "type-fest";
@ -173,11 +173,6 @@ export interface NavigationRouter {
transitionToGuild(guildId: string, ...args: unknown[]): void; transitionToGuild(guildId: string, ...args: unknown[]): void;
} }
export interface ChannelRouter {
transitionToChannel: (channelId: string) => void;
transitionToThread: (channel: Channel) => void;
}
export interface IconUtils { export interface IconUtils {
getUserAvatarURL(user: User, canAnimate?: boolean, size?: number, format?: string): string; getUserAvatarURL(user: User, canAnimate?: boolean, size?: number, format?: string): string;
getDefaultAvatarURL(id: string, discriminator?: string): string; getDefaultAvatarURL(id: string, discriminator?: string): string;

View file

@ -149,10 +149,6 @@ export const NavigationRouter: t.NavigationRouter = mapMangledModuleLazy("Transi
back: filters.byCode("goBack()"), back: filters.byCode("goBack()"),
forward: filters.byCode("goForward()"), forward: filters.byCode("goForward()"),
}); });
export const ChannelRouter: t.ChannelRouter = mapMangledModuleLazy('"Thread must have a parent ID."', {
transitionToChannel: filters.byCode(".preload"),
transitionToThread: filters.byCode('"Thread must have a parent ID."')
});
export let SettingsRouter: any; export let SettingsRouter: any;
waitFor(["open", "saveAccountChanges"], m => SettingsRouter = m); waitFor(["open", "saveAccountChanges"], m => SettingsRouter = m);