Compare commits

...
Sign in to create a new pull request.

2 commits

Author SHA1 Message Date
Nuckyz
ffaaa7da59
Remove trailing new line 2025-02-01 01:56:47 -03:00
Nuckyz
03b302dc62
PlatformIndicators: Move indicators place in profiles & clean-up 2025-02-01 01:55:53 -03:00
8 changed files with 234 additions and 157 deletions

40
src/api/NicknameIcons.tsx Normal file
View file

@ -0,0 +1,40 @@
/*
* Vencord, a Discord client mod
* Copyright (c) 2025 Vendicated and contributors
* SPDX-License-Identifier: GPL-3.0-or-later
*/
import ErrorBoundary from "@components/ErrorBoundary";
import { Logger } from "@utils/Logger";
import { ReactNode } from "react";
export interface NicknameIconProps {
userId: string;
}
export type NicknameIconFactory = (props: NicknameIconProps) => ReactNode | Promise<ReactNode>;
export interface NicknameIcon {
priority: number;
factory: NicknameIconFactory;
}
const nicknameIcons = new Map<string, NicknameIcon>();
const logger = new Logger("NicknameIcons");
export function addNicknameIcon(id: string, factory: NicknameIconFactory, priority = 0) {
return nicknameIcons.set(id, {
priority,
factory: ErrorBoundary.wrap(factory, { noop: true, onError: error => logger.error(`Failed to render ${id}`, error) })
});
}
export function removeNicknameIcon(id: string) {
return nicknameIcons.delete(id);
}
export function _renderIcons(props: NicknameIconProps) {
return Array.from(nicknameIcons)
.sort((a, b) => b[1].priority - a[1].priority)
.map(([id, { factory: NicknameIcon }]) => <NicknameIcon key={id} {...props} />);
}

View file

@ -27,6 +27,7 @@ import * as $MessageDecorations from "./MessageDecorations";
import * as $MessageEventsAPI from "./MessageEvents";
import * as $MessagePopover from "./MessagePopover";
import * as $MessageUpdater from "./MessageUpdater";
import * as $NicknameIcons from "./NicknameIcons";
import * as $Notices from "./Notices";
import * as $Notifications from "./Notifications";
import * as $ServerList from "./ServerList";
@ -122,3 +123,8 @@ export const MessageUpdater = $MessageUpdater;
* An API allowing you to get an user setting
*/
export const UserSettings = $UserSettings;
/**
* An API allowing you to add icons to the nickname, in profiles
*/
export const NicknameIcons = $NicknameIcons;

View file

@ -0,0 +1,23 @@
/*
* Vencord, a Discord client mod
* Copyright (c) 2025 Vendicated and contributors
* SPDX-License-Identifier: GPL-3.0-or-later
*/
import { Devs } from "@utils/constants";
import definePlugin from "@utils/types";
export default definePlugin({
name: "NicknameIconsAPI",
description: "API to add icons to the nickname, in profiles",
authors: [Devs.Nuckyz],
patches: [
{
find: "#{intl::USER_PROFILE_LOAD_ERROR}",
replacement: {
match: /(\.fetchError.+?\?)null/,
replace: (_, rest) => `${rest}Vencord.Api.NicknameIcons._renderIcons(arguments[0])`
}
}
]
});

View file

@ -25,6 +25,7 @@ import { addMessageAccessory, removeMessageAccessory } from "@api/MessageAccesso
import { addMessageDecoration, removeMessageDecoration } from "@api/MessageDecorations";
import { addMessageClickListener, addMessagePreEditListener, addMessagePreSendListener, removeMessageClickListener, removeMessagePreEditListener, removeMessagePreSendListener } from "@api/MessageEvents";
import { addMessagePopoverButton, removeMessagePopoverButton } from "@api/MessagePopover";
import { addNicknameIcon, removeNicknameIcon } from "@api/NicknameIcons";
import { Settings, SettingsStore } from "@api/Settings";
import { Logger } from "@utils/Logger";
import { canonicalizeFind } from "@utils/patches";
@ -92,7 +93,7 @@ function isReporterTestable(p: Plugin, part: ReporterTestable) {
const pluginKeysToBind: Array<keyof PluginDef & `${"on" | "render"}${string}`> = [
"onBeforeMessageEdit", "onBeforeMessageSend", "onMessageClick",
"renderChatBarButton", "renderMemberListDecorator", "renderMessageAccessory", "renderMessageDecoration", "renderMessagePopoverButton"
"renderChatBarButton", "renderMemberListDecorator", "renderNicknameIcon", "renderMessageAccessory", "renderMessageDecoration", "renderMessagePopoverButton"
];
const neededApiPlugins = new Set<string>();
@ -124,6 +125,7 @@ for (const p of pluginsValues) if (isPluginEnabled(p.name)) {
if (p.onBeforeMessageEdit || p.onBeforeMessageSend || p.onMessageClick) neededApiPlugins.add("MessageEventsAPI");
if (p.renderChatBarButton) neededApiPlugins.add("ChatInputButtonAPI");
if (p.renderMemberListDecorator) neededApiPlugins.add("MemberListDecoratorsAPI");
if (p.renderNicknameIcon) neededApiPlugins.add("NicknameIconsAPI");
if (p.renderMessageAccessory) neededApiPlugins.add("MessageAccessoriesAPI");
if (p.renderMessageDecoration) neededApiPlugins.add("MessageDecorationsAPI");
if (p.renderMessagePopoverButton) neededApiPlugins.add("MessagePopoverAPI");
@ -256,7 +258,7 @@ export const startPlugin = traceFunction("startPlugin", function startPlugin(p:
const {
name, commands, contextMenus, userProfileBadge,
onBeforeMessageEdit, onBeforeMessageSend, onMessageClick,
renderChatBarButton, renderMemberListDecorator, renderMessageAccessory, renderMessageDecoration, renderMessagePopoverButton
renderChatBarButton, renderMemberListDecorator, renderNicknameIcon, renderMessageAccessory, renderMessageDecoration, renderMessagePopoverButton
} = p;
if (p.start) {
@ -306,6 +308,7 @@ export const startPlugin = traceFunction("startPlugin", function startPlugin(p:
if (renderChatBarButton) addChatBarButton(name, renderChatBarButton);
if (renderMemberListDecorator) addMemberListDecorator(name, renderMemberListDecorator);
if (renderNicknameIcon) addNicknameIcon(name, renderNicknameIcon);
if (renderMessageDecoration) addMessageDecoration(name, renderMessageDecoration);
if (renderMessageAccessory) addMessageAccessory(name, renderMessageAccessory);
if (renderMessagePopoverButton) addMessagePopoverButton(name, renderMessagePopoverButton);
@ -317,7 +320,7 @@ export const stopPlugin = traceFunction("stopPlugin", function stopPlugin(p: Plu
const {
name, commands, contextMenus, userProfileBadge,
onBeforeMessageEdit, onBeforeMessageSend, onMessageClick,
renderChatBarButton, renderMemberListDecorator, renderMessageAccessory, renderMessageDecoration, renderMessagePopoverButton
renderChatBarButton, renderMemberListDecorator, renderNicknameIcon, renderMessageAccessory, renderMessageDecoration, renderMessagePopoverButton
} = p;
if (p.stop) {
@ -365,6 +368,7 @@ export const stopPlugin = traceFunction("stopPlugin", function stopPlugin(p: Plu
if (renderChatBarButton) removeChatBarButton(name);
if (renderMemberListDecorator) removeMemberListDecorator(name);
if (renderNicknameIcon) removeNicknameIcon(name);
if (renderMessageDecoration) removeMessageDecoration(name);
if (renderMessageAccessory) removeMessageAccessory(name);
if (renderMessagePopoverButton) removeMessagePopoverButton(name);

View file

@ -18,15 +18,15 @@
import "./style.css";
import { addProfileBadge, BadgePosition, BadgeUserArgs, ProfileBadge, removeProfileBadge } from "@api/Badges";
import { addMemberListDecorator, removeMemberListDecorator } from "@api/MemberListDecorators";
import { addMessageDecoration, removeMessageDecoration } from "@api/MessageDecorations";
import { Settings } from "@api/Settings";
import ErrorBoundary from "@components/ErrorBoundary";
import { addNicknameIcon, removeNicknameIcon } from "@api/NicknameIcons";
import { definePluginSettings, migratePluginSetting } from "@api/Settings";
import { Devs } from "@utils/constants";
import { classes } from "@utils/misc";
import definePlugin, { OptionType } from "@utils/types";
import { filters, findStoreLazy, mapMangledModuleLazy } from "@webpack";
import { PresenceStore, Tooltip, UserStore } from "@webpack/common";
import { PresenceStore, Tooltip, UserStore, useStateFromStores } from "@webpack/common";
import { User } from "discord-types/general";
export interface Session {
@ -44,10 +44,26 @@ const SessionsStore = findStoreLazy("SessionsStore") as {
getSessions(): Record<string, Session>;
};
function Icon(path: string, opts?: { viewBox?: string; width?: number; height?: number; }) {
return ({ color, tooltip, small }: { color: string; tooltip: string; small: boolean; }) => (
const { useStatusFillColor } = mapMangledModuleLazy(".concat(.5625*", {
useStatusFillColor: filters.byCode(".hex")
});
interface IconFactoryOpts {
viewBox?: string;
width?: number;
height?: number;
}
interface IconProps {
color: string;
tooltip: string;
small?: boolean;
}
function Icon(path: string, opts?: IconFactoryOpts) {
return ({ color, tooltip, small }: IconProps) => (
<Tooltip text={tooltip} >
{(tooltipProps: any) => (
{tooltipProps => (
<svg
{...tooltipProps}
height={(opts?.height ?? 20) - (small ? 3 : 0)}
@ -68,13 +84,17 @@ const Icons = {
mobile: Icon("M 187 0 L 813 0 C 916.277 0 1000 83.723 1000 187 L 1000 1313 C 1000 1416.277 916.277 1500 813 1500 L 187 1500 C 83.723 1500 0 1416.277 0 1313 L 0 187 C 0 83.723 83.723 0 187 0 Z M 125 1000 L 875 1000 L 875 250 L 125 250 Z M 500 1125 C 430.964 1125 375 1180.964 375 1250 C 375 1319.036 430.964 1375 500 1375 C 569.036 1375 625 1319.036 625 1250 C 625 1180.964 569.036 1125 500 1125 Z", { viewBox: "0 0 1000 1500", height: 17, width: 17 }),
embedded: Icon("M14.8 2.7 9 3.1V47h3.3c1.7 0 6.2.3 10 .7l6.7.6V2l-4.2.2c-2.4.1-6.9.3-10 .5zm1.8 6.4c1 1.7-1.3 3.6-2.7 2.2C12.7 10.1 13.5 8 15 8c.5 0 1.2.5 1.6 1.1zM16 33c0 6-.4 10-1 10s-1-4-1-10 .4-10 1-10 1 4 1 10zm15-8v23.3l3.8-.7c2-.3 4.7-.6 6-.6H43V3h-2.2c-1.3 0-4-.3-6-.6L31 1.7V25z", { viewBox: "0 0 50 50" }),
};
type Platform = keyof typeof Icons;
const { useStatusFillColor } = mapMangledModuleLazy(".concat(.5625*", {
useStatusFillColor: filters.byCode(".hex")
});
interface PlatformIconProps {
platform: Platform;
status: string;
small?: boolean;
isProfile?: boolean;
}
const PlatformIcon = ({ platform, status, small }: { platform: Platform, status: string; small: boolean; }) => {
const PlatformIcon = ({ platform, status, small }: PlatformIconProps) => {
const tooltip = platform === "embedded"
? "Console"
: platform[0].toUpperCase() + platform.slice(1);
@ -84,9 +104,12 @@ const PlatformIcon = ({ platform, status, small }: { platform: Platform, status:
return <Icon color={useStatusFillColor(status)} tooltip={tooltip} small={small} />;
};
function ensureOwnStatus(user: User) {
if (user.id === UserStore.getCurrentUser().id) {
const sessions = SessionsStore.getSessions();
function useEnsureOwnStatus(user: User) {
if (user.id !== UserStore.getCurrentUser()?.id) {
return;
}
const sessions = useStateFromStores([SessionsStore], () => SessionsStore.getSessions());
if (typeof sessions !== "object") return null;
const sortedSessions = Object.values(sessions).sort(({ status: a }, { status: b }) => {
if (a === b) return 0;
@ -105,134 +128,122 @@ function ensureOwnStatus(user: User) {
const { clientStatuses } = PresenceStore.getState();
clientStatuses[UserStore.getCurrentUser().id] = ownStatus;
}
interface PlatformIndicatorProps {
user: User;
isProfile?: boolean;
isMessage?: boolean;
isMemberList?: boolean;
}
const PlatformIndicator = ({ user, isProfile, isMessage, isMemberList }: PlatformIndicatorProps) => {
if (user == null || user.bot) return null;
useEnsureOwnStatus(user);
const status: Record<Platform, string> | undefined = useStateFromStores([PresenceStore], () => PresenceStore.getState()?.clientStatuses?.[user.id]);
if (status == null) {
return null;
}
}
function getBadges({ userId }: BadgeUserArgs): ProfileBadge[] {
const user = UserStore.getUser(userId);
if (!user || user.bot) return [];
ensureOwnStatus(user);
const status = PresenceStore.getState()?.clientStatuses?.[user.id] as Record<Platform, string>;
if (!status) return [];
return Object.entries(status).map(([platform, status]) => ({
component: () => (
<span className="vc-platform-indicator">
const icons = Array.from(Object.entries(status), ([platform, status]) => (
<PlatformIcon
key={platform}
platform={platform as Platform}
status={status}
small={false}
/>
</span>
),
key: `vc-platform-indicator-${platform}`
}));
}
const PlatformIndicator = ({ user, wantMargin = true, wantTopMargin = false, small = false }: { user: User; wantMargin?: boolean; wantTopMargin?: boolean; small?: boolean; }) => {
if (!user || user.bot) return null;
ensureOwnStatus(user);
const status = PresenceStore.getState()?.clientStatuses?.[user.id] as Record<Platform, string>;
if (!status) return null;
const icons = Object.entries(status).map(([platform, status]) => (
<PlatformIcon
key={platform}
platform={platform as Platform}
status={status}
small={small}
small={isProfile || isMemberList}
/>
));
if (!icons.length) return null;
if (!icons.length) {
return null;
}
return (
<span
className="vc-platform-indicator"
style={{
marginLeft: wantMargin ? 4 : 0,
top: wantTopMargin ? 2 : 0,
gap: 2
}}
<div
className={classes("vc-platform-indicator", isProfile && "vc-platform-indicator-profile", isMessage && "vc-platform-indicator-message")}
style={{ marginLeft: isMemberList ? "4px" : undefined }}
>
{icons}
</span>
</div>
);
};
const badge: ProfileBadge = {
getBadges,
position: BadgePosition.START,
};
function toggleMemberListDecorators(enabled: boolean) {
if (enabled) {
addMemberListDecorator("PlatformIndicators", props => <PlatformIndicator user={props.user} isMemberList />);
} else {
removeMemberListDecorator("PlatformIndicators");
}
}
const indicatorLocations = {
function toggleNicknameIcons(enabled: boolean) {
if (enabled) {
addNicknameIcon("PlatformIndicators", props => <PlatformIndicator user={UserStore.getUser(props.userId)} isProfile />, 1);
} else {
removeNicknameIcon("PlatformIndicators");
}
}
function toggleMessageDecorators(enabled: boolean) {
if (enabled) {
addMessageDecoration("PlatformIndicators", props => <PlatformIndicator user={props.message?.author} isMessage />);
} else {
removeMessageDecoration("PlatformIndicators");
}
}
migratePluginSetting("PlatformIndicators", "badges", "profiles");
const settings = definePluginSettings({
list: {
description: "In the member list",
onEnable: () => addMemberListDecorator("platform-indicator", props =>
<ErrorBoundary noop>
<PlatformIndicator user={props.user} small={true} />
</ErrorBoundary>
),
onDisable: () => removeMemberListDecorator("platform-indicator")
type: OptionType.BOOLEAN,
description: "Show indicators in the member list",
default: true,
onChange: toggleMemberListDecorators
},
badges: {
description: "In user profiles, as badges",
onEnable: () => addProfileBadge(badge),
onDisable: () => removeProfileBadge(badge)
profiles: {
type: OptionType.BOOLEAN,
description: "Show indicators in user profiles",
default: true,
onChange: toggleNicknameIcons
},
messages: {
description: "Inside messages",
onEnable: () => addMessageDecoration("platform-indicator", props =>
<ErrorBoundary noop>
<PlatformIndicator user={props.message?.author} wantTopMargin={true} />
</ErrorBoundary>
),
onDisable: () => removeMessageDecoration("platform-indicator")
type: OptionType.BOOLEAN,
description: "Show indicators inside messages",
default: true,
onChange: toggleMessageDecorators
},
colorMobileIndicator: {
type: OptionType.BOOLEAN,
description: "Whether to make the mobile indicator match the color of the user status.",
default: true,
restartNeeded: true
}
};
});
export default definePlugin({
name: "PlatformIndicators",
description: "Adds platform indicators (Desktop, Mobile, Web...) to users",
authors: [Devs.kemo, Devs.TheSun, Devs.Nuckyz, Devs.Ven],
dependencies: ["MessageDecorationsAPI", "MemberListDecoratorsAPI"],
dependencies: ["MemberListDecoratorsAPI", "NicknameIconsAPI", "MessageDecorationsAPI"],
settings,
start() {
const settings = Settings.plugins.PlatformIndicators;
const { displayMode } = settings;
// transfer settings from the old ones, which had a select menu instead of booleans
if (displayMode) {
if (displayMode !== "both") settings[displayMode] = true;
else {
settings.list = true;
settings.badges = true;
}
settings.messages = true;
delete settings.displayMode;
}
Object.entries(indicatorLocations).forEach(([key, value]) => {
if (settings[key]) value.onEnable();
});
if (settings.store.list) toggleMemberListDecorators(true);
if (settings.store.profiles) toggleNicknameIcons(true);
if (settings.store.messages) toggleMessageDecorators(true);
},
stop() {
Object.entries(indicatorLocations).forEach(([_, value]) => {
value.onDisable();
});
if (settings.store.list) toggleMemberListDecorators(false);
if (settings.store.profiles) toggleNicknameIcons;
if (settings.store.messages) toggleMessageDecorators(false);
},
patches: [
{
find: ".Masks.STATUS_ONLINE_MOBILE",
predicate: () => Settings.plugins.PlatformIndicators.colorMobileIndicator,
predicate: () => settings.store.colorMobileIndicator,
replacement: [
{
// Return the STATUS_ONLINE_MOBILE mask if the user is on mobile, no matter the status
@ -248,7 +259,7 @@ export default definePlugin({
},
{
find: ".AVATAR_STATUS_MOBILE_16;",
predicate: () => Settings.plugins.PlatformIndicators.colorMobileIndicator,
predicate: () => settings.store.colorMobileIndicator,
replacement: [
{
// Return the AVATAR_STATUS_MOBILE size mask if the user is on mobile, no matter the status
@ -269,32 +280,12 @@ export default definePlugin({
},
{
find: "}isMobileOnline(",
predicate: () => Settings.plugins.PlatformIndicators.colorMobileIndicator,
predicate: () => settings.store.colorMobileIndicator,
replacement: {
// Make isMobileOnline return true no matter what is the user status
match: /(?<=\i\[\i\.\i\.MOBILE\])===\i\.\i\.ONLINE/,
replace: "!= null"
}
}
],
options: {
...Object.fromEntries(
Object.entries(indicatorLocations).map(([key, value]) => {
return [key, {
type: OptionType.BOOLEAN,
description: `Show indicators ${value.description.toLowerCase()}`,
// onChange doesn't give any way to know which setting was changed, so restart required
restartNeeded: true,
default: true
}];
})
),
colorMobileIndicator: {
type: OptionType.BOOLEAN,
description: "Whether to make the mobile indicator match the color of the user status.",
default: true,
restartNeeded: true
}
}
]
});

View file

@ -2,6 +2,20 @@
display: inline-flex;
justify-content: center;
align-items: center;
vertical-align: top;
position: relative;
gap: 2px;
}
.vc-platform-indicator-profile {
background: rgb(var(--bg-overlay-color) / var(--bg-overlay-opacity-6));
border: 1px solid var(--border-faint);
border-radius: var(--radius-xs);
border-color: var(--profile-body-border-color);
margin: 0 1px;
padding: 0 1px;
}
.vc-platform-indicator-message {
position: relative;
vertical-align: top;
top: 2px;
}

View file

@ -20,6 +20,7 @@ import "./style.css";
import { addMemberListDecorator, removeMemberListDecorator } from "@api/MemberListDecorators";
import { addMessageDecoration, removeMessageDecoration } from "@api/MessageDecorations";
import { addNicknameIcon, removeNicknameIcon } from "@api/NicknameIcons";
import { definePluginSettings } from "@api/Settings";
import { Devs } from "@utils/constants";
import definePlugin, { OptionType } from "@utils/types";
@ -51,19 +52,10 @@ export default definePlugin({
name: "UserVoiceShow",
description: "Shows an indicator when a user is in a Voice Channel",
authors: [Devs.Nuckyz, Devs.LordElias],
dependencies: ["MemberListDecoratorsAPI", "MessageDecorationsAPI"],
dependencies: ["NicknameIconsAPI", "MemberListDecoratorsAPI", "MessageDecorationsAPI"],
settings,
patches: [
// User Popout, Full Size Profile, Direct Messages Side Profile
{
find: "#{intl::USER_PROFILE_LOAD_ERROR}",
replacement: {
match: /(\.fetchError.+?\?)null/,
replace: (_, rest) => `${rest}$self.VoiceChannelIndicator({userId:arguments[0]?.userId,isProfile:true})`
},
predicate: () => settings.store.showInUserProfileModal
},
// To use without the MemberList decorator API
/* // Guild Members List
{
@ -95,6 +87,9 @@ export default definePlugin({
],
start() {
if (settings.store.showInUserProfileModal) {
addNicknameIcon("UserVoiceShow", ({ userId }) => <VoiceChannelIndicator userId={userId} isProfile />);
}
if (settings.store.showInMemberList) {
addMemberListDecorator("UserVoiceShow", ({ user }) => user == null ? null : <VoiceChannelIndicator userId={user.id} />);
}
@ -104,6 +99,7 @@ export default definePlugin({
},
stop() {
removeNicknameIcon("UserVoiceShow");
removeMemberListDecorator("UserVoiceShow");
removeMessageDecoration("UserVoiceShow");
},

View file

@ -25,9 +25,11 @@ import { MessageAccessoryFactory } from "@api/MessageAccessories";
import { MessageDecorationFactory } from "@api/MessageDecorations";
import { MessageClickListener, MessageEditListener, MessageSendListener } from "@api/MessageEvents";
import { MessagePopoverButtonFactory } from "@api/MessagePopover";
import { NicknameIconFactory } from "@api/NicknameIcons";
import { FluxEvents } from "@webpack/types";
import { JSX } from "react";
import { Promisable } from "type-fest";
import { LiteralStringUnion } from "type-fest/source/literal-union";
// exists to export default definePlugin({...})
export default function definePlugin<P extends PluginDef>(p: P & Record<string, any>) {
@ -88,7 +90,7 @@ export interface PluginDef {
* These will automatically be enabled and loaded before your plugin
* Generally these will be API plugins
*/
dependencies?: string[],
dependencies?: Array<LiteralStringUnion<"BadgeAPI" | "ChatInputButtonAPI" | "CommandsAPI" | "ContextMenuAPI" | "DynamicImageModalAPI" | "NicknameIconsAPI" | "MemberListDecoratorsAPI" | "MenuItemDemanglerAPI" | "MessageAccessoriesAPI" | "MessageDecorationsAPI" | "MessageEventsAPI" | "MessagePopoverAPI" | "MessageUpdaterAPI" | "NoticesAPI" | "ServerListAPI" | "UserSettingsAPI">>,
/**
* Whether this plugin is required and forcefully enabled
*/
@ -161,6 +163,7 @@ export interface PluginDef {
renderMessageDecoration?: MessageDecorationFactory;
renderMemberListDecorator?: MemberListDecoratorFactory;
renderNicknameIcon?: NicknameIconFactory;
renderChatBarButton?: ChatBarButtonFactory;
}