Compare commits

...

26 Commits

Author SHA1 Message Date
V
53ff2532f4 bump to 1.2.3 2023-05-15 02:34:01 +02:00
Nuckyz
64b38348d4 feat(plugins): Permissions Viewer (#477)
Co-authored-by: V <vendicated@riseup.net>
2023-05-15 02:33:04 +02:00
V
9c1b3a9afd Update README.md (#1123) 2023-05-14 13:16:18 +02:00
outfoxxed
caf77a3d7f NoReplyMention: add option to only exclude specific users from pings (#1107)
Co-authored-by: V <vendicated@riseup.net>
2023-05-14 00:01:10 +00:00
Manti
7a27de8927 [ReviewDB] Improve UI & Use new RewviewDB api endpoints (#1104) 2023-05-14 01:29:13 +02:00
LordElias
1bc0678422 MoreUserTags: Fix & Add ability to customize text inside tag (#1077)
Co-authored-by: V <vendicated@riseup.net>
Co-authored-by: ActuallyTheSun <78964224+ActuallyTheSun@users.noreply.github.com>
2023-05-13 22:38:49 +00:00
V
cd53cf38fe ReverseImageSearch: Add engine icons 2023-05-14 00:10:01 +02:00
V
f13f9e80a9 ViewIcons: Add context menu icons 2023-05-13 23:49:47 +02:00
V
c062f9bdeb SpotifyControls: Add context menu icons 2023-05-13 23:47:13 +02:00
V
f2ef96a420 PlatformIndicators: Fix profile spacing 2023-05-13 22:56:46 +02:00
V
16365d3ea1 bump to 1.2.2 2023-05-13 18:48:40 +02:00
V
1ec28a345b EmoteCloner: Add Sticker cloning (#1118) 2023-05-13 18:47:46 +02:00
V
2fdc00b11e BadgesAPI: Fix canary crash (new pomelo badge, the horror) 2023-05-12 23:34:30 +02:00
V
3da112680d oops, add missing else 2023-05-12 04:17:12 +02:00
V
1d93162036 MessageClickActions: Add double click to reply 2023-05-12 04:15:35 +02:00
V
7dcd32e838 PlatformIndicators: Fix weird spacing in badges 2023-05-12 03:54:57 +02:00
V
ade31f993b Implement plugin tags 2023-05-12 03:41:15 +02:00
AutumnVN
3c7496ac6d TextReplace: Visible Linebreak in settings (#1063)
Co-authored-by: V <vendicated@riseup.net>
2023-05-12 02:59:51 +02:00
Supertiger
63387a48ee silentMessageToggle: Add setting to disable auto disable (#1062)
Co-authored-by: V <vendicated@riseup.net>
2023-05-12 00:58:53 +00:00
V
3bb68467bb Update README.md 2023-05-12 02:40:31 +02:00
V
2b337eace1 [skip ci] ShowHiddenChannel: Fix broken patch 2023-05-12 02:30:51 +02:00
V
5c5b009c41 Settings: Fix resetting scroll/search when getting a ping (#1106) 2023-05-12 01:40:43 +02:00
Nuckyz
0c54b1fa1d [skip ci] Fix InvisibleChat button being added to wrong chat box (#1100) 2023-05-11 17:44:33 +00:00
Kode
393f76749a USRBG: Hide Nitro badge if banner's source is USRBG (#1096)
* Hide Nitro badge if banner's source is USRBG, tweaks to description

* Rename function

* Update src/plugins/usrbg/index.tsx

---------

Co-authored-by: V <vendicated@riseup.net>
2023-05-11 19:33:08 +02:00
V
1fe7f3c297 ViewIcons: More consistent context menu position 2023-05-11 19:26:55 +02:00
V
622e8dc3e0 [skip ci] Translate: Shift/Right click shortcut 2023-05-11 19:00:18 +02:00
54 changed files with 1751 additions and 425 deletions

View File

@ -26,5 +26,8 @@ jobs:
- name: Lint & Test if desktop version compiles - name: Lint & Test if desktop version compiles
run: pnpm test run: pnpm test
- name: Lint & Test if web version compiles - name: Test if web version compiles
run: pnpm testWeb run: pnpm buildWeb
- name: Test if plugin structure is valid
run: pnpm generatePluginJson

View File

@ -10,7 +10,7 @@ The cutest Discord client mod
- Super easy to install (Download Installer, open, click install button, done) - Super easy to install (Download Installer, open, click install button, done)
- 100+ plugins built in: [See a list](https://vencord.dev/plugins) - 100+ plugins built in: [See a list](https://vencord.dev/plugins)
- Some highlights: SpotifyControls, GameActivityToggle, Experiments, NoTrack, MessageLogger, QuickReply, Free Emotes/Stickers, CustomCommands, ShowHiddenChannels, PronounDB - Some highlights: SpotifyControls, MessageLogger, Experiments, GameActivityToggle, Translate, NoTrack, QuickReply, Free Emotes/Stickers, PermissionsViewer, CustomCommands, ShowHiddenChannels, PronounDB
- Fairly lightweight despite the many inbuilt plugins - Fairly lightweight despite the many inbuilt plugins
- Excellent Browser Support: Run Vencord in your Browser via extension or UserScript - Excellent Browser Support: Run Vencord in your Browser via extension or UserScript
- Works on any Discord branch: Stable, Canary or PTB all work (though for the best experience I recommend stable!) - Works on any Discord branch: Stable, Canary or PTB all work (though for the best experience I recommend stable!)
@ -32,12 +32,21 @@ Click the below button to install Vencord to the Discord Desktop app
Or use the [UserScript](https://raw.githubusercontent.com/Vencord/builds/main/Vencord.user.js) - Please note that the CSS Editor, Themes loaded from remote sources and co. will not work in the UserScript. Use the extension if you need any of those Or use the [UserScript](https://raw.githubusercontent.com/Vencord/builds/main/Vencord.user.js) - Please note that the CSS Editor, Themes loaded from remote sources and co. will not work in the UserScript. Use the extension if you need any of those
## Installing our Desktop App <details>
<summary>Alternative Downloads</summary>
## Vencord Desktop
> **Warning**
> This is an alternative app. It currently doesn't support screensharing or keybinds. If you just want to install to the normal Discord Desktop app, scroll up
As an alternative to the Discord Desktop app, Vencord also has its own standalone Desktop app that is snappier and lighter than Discord's official Desktop app. It is currently in beta and we have yet to implement some features like screensharing, but you can try the beta nonetheless As an alternative to the Discord Desktop app, Vencord also has its own standalone Desktop app that is snappier and lighter than Discord's official Desktop app. It is currently in beta and we have yet to implement some features like screensharing, but you can try the beta nonetheless
[![Download Vencord Desktop](https://img.shields.io/github/v/release/Vencord/Desktop?label=Download%20Vencord%20Desktop&style=for-the-badge)](https://github.com/Vencord/Desktop#vencord-desktop) [![Download Vencord Desktop](https://img.shields.io/github/v/release/Vencord/Desktop?label=Download%20Vencord%20Desktop&style=for-the-badge)](https://github.com/Vencord/Desktop#vencord-desktop)
</details>
## Join our Support/Community Server ## Join our Support/Community Server
[![Vencord Discord Server](https://invidget.switchblade.xyz/D9uwnFnqmd?theme=dark)](https://discord.gg/D9uwnFnqmd) [![Vencord Discord Server](https://invidget.switchblade.xyz/D9uwnFnqmd?theme=dark)](https://discord.gg/D9uwnFnqmd)

View File

@ -1,7 +1,7 @@
{ {
"name": "vencord", "name": "vencord",
"private": "true", "private": "true",
"version": "1.2.1", "version": "1.2.3",
"description": "The cutest Discord client mod", "description": "The cutest Discord client mod",
"homepage": "https://github.com/Vendicated/Vencord#readme", "homepage": "https://github.com/Vendicated/Vencord#readme",
"bugs": { "bugs": {

View File

@ -29,6 +29,7 @@ interface Dev {
interface PluginData { interface PluginData {
name: string; name: string;
description: string; description: string;
tags: string[];
authors: Dev[]; authors: Dev[];
dependencies: string[]; dependencies: string[];
hasPatches: boolean; hasPatches: boolean;
@ -106,6 +107,7 @@ async function parseFile(fileName: string) {
hasCommands: false, hasCommands: false,
enabledByDefault: false, enabledByDefault: false,
required: false, required: false,
tags: [] as string[]
} as PluginData; } as PluginData;
for (const prop of pluginObj.properties) { for (const prop of pluginObj.properties) {
@ -131,6 +133,13 @@ async function parseFile(fileName: string) {
return devs[getName(e)!]; return devs[getName(e)!];
}); });
break; break;
case "tags":
if (!isArrayLiteralExpression(value)) throw fail("tags is not an array literal");
data.tags = value.elements.map(e => {
if (!isStringLiteral(e)) throw fail("tags array contains non-string literals");
return e.text;
});
break;
case "dependencies": case "dependencies":
if (!isArrayLiteralExpression(value)) throw fail("dependencies is not an array literal"); if (!isArrayLiteralExpression(value)) throw fail("dependencies is not an array literal");
const { elements } = value; const { elements } = value;

View File

@ -37,8 +37,6 @@ import { checkForUpdates, update, UpdateLogger } from "./utils/updater";
import { onceReady } from "./webpack"; import { onceReady } from "./webpack";
import { SettingsRouter } from "./webpack/common"; import { SettingsRouter } from "./webpack/common";
export let Components: any;
async function syncSettings() { async function syncSettings() {
if ( if (
Settings.cloud.settingsSync && // if it's enabled Settings.cloud.settingsSync && // if it's enabled
@ -65,7 +63,6 @@ async function syncSettings() {
async function init() { async function init() {
await onceReady; await onceReady;
startAllPlugins(); startAllPlugins();
Components = await import("./components");
syncSettings(); syncSettings();

View File

@ -28,6 +28,7 @@ import * as $MessagePopover from "./MessagePopover";
import * as $Notices from "./Notices"; import * as $Notices from "./Notices";
import * as $Notifications from "./Notifications"; import * as $Notifications from "./Notifications";
import * as $ServerList from "./ServerList"; import * as $ServerList from "./ServerList";
import * as $Settings from "./Settings";
import * as $SettingsStore from "./SettingsStore"; import * as $SettingsStore from "./SettingsStore";
import * as $Styles from "./Styles"; import * as $Styles from "./Styles";
@ -86,6 +87,10 @@ export const MessageDecorations = $MessageDecorations;
* An API allowing you to add components to member list users, in both DM's and servers * An API allowing you to add components to member list users, in both DM's and servers
*/ */
export const MemberListDecorators = $MemberListDecorators; export const MemberListDecorators = $MemberListDecorators;
/**
* An API allowing you to persist data
*/
export const Settings = $Settings;
/** /**
* An API allowing you to read, manipulate and automatically update components based on Discord settings * An API allowing you to read, manipulate and automatically update components based on Discord settings
*/ */

View File

@ -16,28 +16,31 @@
* 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 "./iconStyles.css";
import { classes } from "@utils/misc"; import { classes } from "@utils/misc";
import type { PropsWithChildren } from "react"; import { i18n } from "@webpack/common";
import type { PropsWithChildren, SVGProps } from "react";
interface BaseIconProps extends IconProps { interface BaseIconProps extends IconProps {
viewBox: string; viewBox: string;
} }
interface IconProps { interface IconProps extends SVGProps<SVGSVGElement> {
className?: string; className?: string;
height?: number; height?: number;
width?: number; width?: number;
} }
function Icon({ height = 24, width = 24, className, children, viewBox }: PropsWithChildren<BaseIconProps>) { function Icon({ height = 24, width = 24, className, children, viewBox, ...svgProps }: PropsWithChildren<BaseIconProps>) {
return ( return (
<svg <svg
className={classes(className, "vc-icon")} className={classes(className, "vc-icon")}
aria-hidden="true"
role="img" role="img"
width={width} width={width}
height={height} height={height}
viewBox={viewBox} viewBox={viewBox}
{...svgProps}
> >
{children} {children}
</svg> </svg>
@ -81,3 +84,65 @@ export function CopyIcon(props: IconProps) {
</Icon> </Icon>
); );
} }
/**
* Discord's open external icon, as seen in the user profile connections
*/
export function OpenExternalIcon(props: IconProps) {
return (
<Icon
{...props}
className={classes(props.className, "vc-open-external-icon")}
viewBox="0 0 24 24"
>
<polygon
fill="currentColor"
fill-rule="nonzero"
points="13 20 11 20 11 8 5.5 13.5 4.08 12.08 12 4.16 19.92 12.08 18.5 13.5 13 8"
/>
</Icon>
);
}
export function ImageIcon(props: IconProps) {
return (
<Icon
{...props}
className={classes(props.className, "vc-image-icon")}
viewBox="0 0 24 24"
>
<path fill="currentColor" d="M21,19V5c0,-1.1 -0.9,-2 -2,-2H5c-1.1,0 -2,0.9 -2,2v14c0,1.1 0.9,2 2,2h14c1.1,0 2,-0.9 2,-2zM8.5,13.5l2.5,3.01L14.5,12l4.5,6H5l3.5,-4.5z" />
</Icon>
);
}
export function InfoIcon(props: IconProps) {
return (
<Icon
{...props}
className={classes(props.className, "vc-info-icon")}
viewBox="0 0 12 12"
>
<path fill="currentColor" d="M6 1C3.243 1 1 3.244 1 6c0 2.758 2.243 5 5 5s5-2.242 5-5c0-2.756-2.243-5-5-5zm0 2.376a.625.625 0 110 1.25.625.625 0 010-1.25zM7.5 8.5h-3v-1h1V6H5V5h1a.5.5 0 01.5.5v2h1v1z" />
</Icon>
);
}
export function OwnerCrownIcon(props: IconProps) {
return (
<Icon
aria-label={i18n.Messages.GUILD_OWNER}
{...props}
className={classes(props.className, "vc-owner-crown-icon")}
role="img"
viewBox="0 0 16 16"
>
<path
fill="currentColor"
fill-rule="evenodd"
clip-rule="evenodd"
d="M13.6572 5.42868C13.8879 5.29002 14.1806 5.30402 14.3973 5.46468C14.6133 5.62602 14.7119 5.90068 14.6473 6.16202L13.3139 11.4954C13.2393 11.7927 12.9726 12.0007 12.6666 12.0007H3.33325C3.02725 12.0007 2.76058 11.792 2.68592 11.4954L1.35258 6.16202C1.28792 5.90068 1.38658 5.62602 1.60258 5.46468C1.81992 5.30468 2.11192 5.29068 2.34325 5.42868L5.13192 7.10202L7.44592 3.63068C7.46173 3.60697 7.48377 3.5913 7.50588 3.57559C7.5192 3.56612 7.53255 3.55663 7.54458 3.54535L6.90258 2.90268C6.77325 2.77335 6.77325 2.56068 6.90258 2.43135L7.76458 1.56935C7.89392 1.44002 8.10658 1.44002 8.23592 1.56935L9.09792 2.43135C9.22725 2.56068 9.22725 2.77335 9.09792 2.90268L8.45592 3.54535C8.46794 3.55686 8.48154 3.56651 8.49516 3.57618C8.51703 3.5917 8.53897 3.60727 8.55458 3.63068L10.8686 7.10202L13.6572 5.42868ZM2.66667 12.6673H13.3333V14.0007H2.66667V12.6673Z"
/>
</Icon>
);
}

View File

@ -20,20 +20,18 @@ import "./styles.css";
import * as DataStore from "@api/DataStore"; import * as DataStore from "@api/DataStore";
import { showNotice } from "@api/Notices"; import { showNotice } from "@api/Notices";
import { useSettings } from "@api/Settings"; import { Settings, useSettings } from "@api/Settings";
import { classNameFactory } from "@api/Styles"; import { classNameFactory } from "@api/Styles";
import ErrorBoundary from "@components/ErrorBoundary";
import { Flex } from "@components/Flex"; import { Flex } from "@components/Flex";
import { handleComponentFailed } from "@components/handleComponentFailed";
import { Badge } from "@components/PluginSettings/components"; import { Badge } from "@components/PluginSettings/components";
import PluginModal from "@components/PluginSettings/PluginModal"; import PluginModal from "@components/PluginSettings/PluginModal";
import { Switch } from "@components/Switch"; import { Switch } from "@components/Switch";
import { SettingsTab } from "@components/VencordSettings/shared";
import { ChangeList } from "@utils/ChangeList"; import { ChangeList } from "@utils/ChangeList";
import { Logger } from "@utils/Logger"; import { Logger } from "@utils/Logger";
import { Margins } from "@utils/margins"; import { Margins } from "@utils/margins";
import { classes } from "@utils/misc"; import { classes } from "@utils/misc";
import { openModalLazy } from "@utils/modal"; import { openModalLazy } from "@utils/modal";
import { onlyOnce } from "@utils/onlyOnce";
import { LazyComponent, useAwaiter } from "@utils/react"; import { LazyComponent, useAwaiter } from "@utils/react";
import { Plugin } from "@utils/types"; import { Plugin } from "@utils/types";
import { findByCode, findByPropsLazy } from "@webpack"; import { findByCode, findByPropsLazy } from "@webpack";
@ -96,7 +94,7 @@ interface PluginCardProps extends React.HTMLProps<HTMLDivElement> {
} }
function PluginCard({ plugin, disabled, onRestartNeeded, onMouseEnter, onMouseLeave, isNew }: PluginCardProps) { function PluginCard({ plugin, disabled, onRestartNeeded, onMouseEnter, onMouseLeave, isNew }: PluginCardProps) {
const settings = useSettings([`plugins.${plugin.name}.enabled`]).plugins[plugin.name]; const settings = Settings.plugins[plugin.name];
const isEnabled = () => settings.enabled ?? false; const isEnabled = () => settings.enabled ?? false;
@ -179,7 +177,7 @@ enum SearchStatus {
DISABLED DISABLED
} }
export default ErrorBoundary.wrap(function PluginSettings() { export default function PluginSettings() {
const settings = useSettings(); const settings = useSettings();
const changes = React.useMemo(() => new ChangeList<string>(), []); const changes = React.useMemo(() => new ChangeList<string>(), []);
@ -230,9 +228,12 @@ export default ErrorBoundary.wrap(function PluginSettings() {
if (enabled && searchValue.status === SearchStatus.DISABLED) return false; if (enabled && searchValue.status === SearchStatus.DISABLED) return false;
if (!enabled && searchValue.status === SearchStatus.ENABLED) return false; if (!enabled && searchValue.status === SearchStatus.ENABLED) return false;
if (!searchValue.value.length) return true; if (!searchValue.value.length) return true;
const v = searchValue.value.toLowerCase();
return ( return (
plugin.name.toLowerCase().includes(searchValue.value.toLowerCase()) || plugin.name.toLowerCase().includes(v) ||
plugin.description.toLowerCase().includes(searchValue.value.toLowerCase()) plugin.description.toLowerCase().includes(v) ||
plugin.tags?.some(t => t.toLowerCase().includes(v))
); );
}; };
@ -303,7 +304,7 @@ export default ErrorBoundary.wrap(function PluginSettings() {
} }
return ( return (
<Forms.FormSection className={Margins.top16}> <SettingsTab title="Plugins">
<ReloadRequiredCard required={changes.hasChanges} /> <ReloadRequiredCard required={changes.hasChanges} />
<Forms.FormTitle tag="h5" className={classes(Margins.top20, Margins.bottom8)}> <Forms.FormTitle tag="h5" className={classes(Margins.top20, Margins.bottom8)}>
@ -342,12 +343,9 @@ export default ErrorBoundary.wrap(function PluginSettings() {
<div className={cl("grid")}> <div className={cl("grid")}>
{requiredPlugins} {requiredPlugins}
</div> </div>
</Forms.FormSection > </SettingsTab >
); );
}, { }
message: "Failed to render the Plugin Settings. If this persists, try using the installer to reinstall!",
onError: onlyOnce(handleComponentFailed),
});
function makeDependencyList(deps: string[]) { function makeDependencyList(deps: string[]) {
return ( return (

View File

@ -16,16 +16,17 @@
* 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 ErrorBoundary from "@components/ErrorBoundary";
import { Flex } from "@components/Flex"; import { Flex } from "@components/Flex";
import { Margins } from "@utils/margins"; import { Margins } from "@utils/margins";
import { classes } from "@utils/misc"; import { classes } from "@utils/misc";
import { downloadSettingsBackup, uploadSettingsBackup } from "@utils/settingsSync"; import { downloadSettingsBackup, uploadSettingsBackup } from "@utils/settingsSync";
import { Button, Card, Forms, Text } from "@webpack/common"; import { Button, Card, Text } from "@webpack/common";
import { SettingsTab, wrapTab } from "./shared";
function BackupRestoreTab() { function BackupRestoreTab() {
return ( return (
<Forms.FormSection title="Settings Sync" className={Margins.top16}> <SettingsTab title="Backup & Restore">
<Card className={classes("vc-settings-card", "vc-backup-restore-card")}> <Card className={classes("vc-settings-card", "vc-backup-restore-card")}>
<Flex flexDirection="column"> <Flex flexDirection="column">
<strong>Warning</strong> <strong>Warning</strong>
@ -59,8 +60,8 @@ function BackupRestoreTab() {
Export Settings Export Settings
</Button> </Button>
</Flex> </Flex>
</Forms.FormSection> </SettingsTab>
); );
} }
export default ErrorBoundary.wrap(BackupRestoreTab); export default wrapTab(BackupRestoreTab, "Backup & Restore");

View File

@ -19,13 +19,14 @@
import { showNotification } from "@api/Notifications"; import { showNotification } from "@api/Notifications";
import { Settings, useSettings } from "@api/Settings"; import { Settings, useSettings } from "@api/Settings";
import { CheckedTextInput } from "@components/CheckedTextInput"; import { CheckedTextInput } from "@components/CheckedTextInput";
import ErrorBoundary from "@components/ErrorBoundary";
import { Link } from "@components/Link"; import { Link } from "@components/Link";
import { authorizeCloud, cloudLogger, deauthorizeCloud, getCloudAuth, getCloudUrl } from "@utils/cloud"; import { authorizeCloud, cloudLogger, deauthorizeCloud, getCloudAuth, getCloudUrl } from "@utils/cloud";
import { Margins } from "@utils/margins"; import { Margins } from "@utils/margins";
import { deleteCloudSettings, getCloudSettings, putCloudSettings } from "@utils/settingsSync"; import { deleteCloudSettings, getCloudSettings, putCloudSettings } from "@utils/settingsSync";
import { Alerts, Button, Forms, Switch, Tooltip } from "@webpack/common"; import { Alerts, Button, Forms, Switch, Tooltip } from "@webpack/common";
import { SettingsTab, wrapTab } from "./shared";
function validateUrl(url: string) { function validateUrl(url: string) {
try { try {
new URL(url); new URL(url);
@ -114,7 +115,7 @@ function CloudTab() {
const settings = useSettings(["cloud.authenticated", "cloud.url"]); const settings = useSettings(["cloud.authenticated", "cloud.url"]);
return ( return (
<> <SettingsTab title="Vencord Cloud">
<Forms.FormSection title="Cloud Settings" className={Margins.top16}> <Forms.FormSection title="Cloud Settings" className={Margins.top16}>
<Forms.FormText variant="text-md/normal" className={Margins.bottom20}> <Forms.FormText variant="text-md/normal" className={Margins.bottom20}>
Vencord comes with a cloud integration that adds goodies like settings sync across devices. Vencord comes with a cloud integration that adds goodies like settings sync across devices.
@ -157,8 +158,8 @@ function CloudTab() {
<Forms.FormDivider className={Margins.top16} /> <Forms.FormDivider className={Margins.top16} />
</Forms.FormSection > </Forms.FormSection >
<SettingsSyncSection /> <SettingsSyncSection />
</> </SettingsTab>
); );
} }
export default ErrorBoundary.wrap(CloudTab); export default wrapTab(CloudTab, "Cloud");

View File

@ -16,16 +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 { CheckedTextInput } from "@components/CheckedTextInput";
import { debounce } from "@utils/debounce"; import { debounce } from "@utils/debounce";
import { Margins } from "@utils/margins"; import { Margins } from "@utils/margins";
import { canonicalizeMatch, canonicalizeReplace } from "@utils/patches"; import { canonicalizeMatch, canonicalizeReplace } from "@utils/patches";
import { makeCodeblock } from "@utils/text"; import { makeCodeblock } from "@utils/text";
import { ReplaceFn } from "@utils/types"; import { ReplaceFn } from "@utils/types";
import { search } from "@webpack"; import { search } from "@webpack";
import { Button, Clipboard, Forms, Parser, React, Switch, Text, TextInput } from "@webpack/common"; import { Button, Clipboard, Forms, Parser, React, Switch, TextInput } from "@webpack/common";
import { CheckedTextInput } from "./CheckedTextInput"; import { SettingsTab, wrapTab } from "./shared";
import ErrorBoundary from "./ErrorBoundary";
// Do not include diff in non dev builds (side effects import) // Do not include diff in non dev builds (side effects import)
if (IS_DEV) { if (IS_DEV) {
@ -258,8 +258,7 @@ function PatchHelper() {
} }
return ( return (
<Forms.FormSection> <SettingsTab title="Patch Helper">
<Text variant="heading-md/normal" tag="h2" className={Margins.bottom8}>Patch Helper</Text>
<Forms.FormTitle>find</Forms.FormTitle> <Forms.FormTitle>find</Forms.FormTitle>
<TextInput <TextInput
type="text" type="text"
@ -304,8 +303,8 @@ function PatchHelper() {
<Button onClick={() => Clipboard.copy(code)}>Copy to Clipboard</Button> <Button onClick={() => Clipboard.copy(code)}>Copy to Clipboard</Button>
</> </>
)} )}
</Forms.FormSection> </SettingsTab>
); );
} }
export default IS_DEV ? ErrorBoundary.wrap(PatchHelper) : null; export default IS_DEV ? wrapTab(PatchHelper, "PatchHelper") : null;

View File

@ -16,7 +16,8 @@
* 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 ErrorBoundary from "@components/ErrorBoundary";
import PluginSettings from "@components/PluginSettings"; import PluginSettings from "@components/PluginSettings";
export default ErrorBoundary.wrap(PluginSettings); import { wrapTab } from "./shared";
export default wrapTab(PluginSettings, "Plugins");

View File

@ -17,13 +17,14 @@
*/ */
import { useSettings } from "@api/Settings"; import { useSettings } from "@api/Settings";
import ErrorBoundary from "@components/ErrorBoundary";
import { Link } from "@components/Link"; import { Link } from "@components/Link";
import { Margins } from "@utils/margins"; import { Margins } from "@utils/margins";
import { useAwaiter } from "@utils/react"; import { useAwaiter } from "@utils/react";
import { findLazy } from "@webpack"; import { findLazy } from "@webpack";
import { Card, Forms, React, TextArea } from "@webpack/common"; import { Card, Forms, React, TextArea } from "@webpack/common";
import { SettingsTab, wrapTab } from "./shared";
const TextAreaProps = findLazy(m => typeof m.textarea === "string"); const TextAreaProps = findLazy(m => typeof m.textarea === "string");
function Validator({ link }: { link: string; }) { function Validator({ link }: { link: string; }) {
@ -74,8 +75,8 @@ function Validators({ themeLinks }: { themeLinks: string[]; }) {
); );
} }
export default ErrorBoundary.wrap(function () { function ThemesTab() {
const settings = useSettings(); const settings = useSettings(["themeLinks"]);
const [themeText, setThemeText] = React.useState(settings.themeLinks.join("\n")); const [themeText, setThemeText] = React.useState(settings.themeLinks.join("\n"));
function onBlur() { function onBlur() {
@ -89,7 +90,7 @@ export default ErrorBoundary.wrap(function () {
} }
return ( return (
<> <SettingsTab title="Themes">
<Card className="vc-settings-card vc-text-selectable"> <Card className="vc-settings-card vc-text-selectable">
<Forms.FormTitle tag="h5">Paste links to .theme.css files here</Forms.FormTitle> <Forms.FormTitle tag="h5">Paste links to .theme.css files here</Forms.FormTitle>
<Forms.FormText>One link per line</Forms.FormText> <Forms.FormText>One link per line</Forms.FormText>
@ -124,6 +125,8 @@ export default ErrorBoundary.wrap(function () {
onBlur={onBlur} onBlur={onBlur}
/> />
<Validators themeLinks={settings.themeLinks} /> <Validators themeLinks={settings.themeLinks} />
</> </SettingsTab>
); );
}); }
export default wrapTab(ThemesTab, "Themes");

View File

@ -17,21 +17,20 @@
*/ */
import { useSettings } from "@api/Settings"; import { useSettings } from "@api/Settings";
import ErrorBoundary from "@components/ErrorBoundary";
import { ErrorCard } from "@components/ErrorCard"; import { ErrorCard } from "@components/ErrorCard";
import { Flex } from "@components/Flex"; import { Flex } from "@components/Flex";
import { handleComponentFailed } from "@components/handleComponentFailed";
import { Link } from "@components/Link"; import { Link } from "@components/Link";
import { Margins } from "@utils/margins"; import { Margins } from "@utils/margins";
import { classes } from "@utils/misc"; import { classes } from "@utils/misc";
import { relaunch } from "@utils/native"; import { relaunch } from "@utils/native";
import { onlyOnce } from "@utils/onlyOnce";
import { useAwaiter } from "@utils/react"; import { useAwaiter } from "@utils/react";
import { changes, checkForUpdates, getRepo, isNewer, update, updateError, UpdateLogger } from "@utils/updater"; import { changes, checkForUpdates, getRepo, isNewer, update, updateError, UpdateLogger } from "@utils/updater";
import { Alerts, Button, Card, Forms, Parser, React, Switch, Toasts } from "@webpack/common"; import { Alerts, Button, Card, Forms, Parser, React, Switch, Toasts } from "@webpack/common";
import gitHash from "~git-hash"; import gitHash from "~git-hash";
import { SettingsTab, wrapTab } from "./shared";
function withDispatcher(dispatcher: React.Dispatch<React.SetStateAction<boolean>>, action: () => any) { function withDispatcher(dispatcher: React.Dispatch<React.SetStateAction<boolean>>, action: () => any) {
return async () => { return async () => {
dispatcher(true); dispatcher(true);
@ -199,7 +198,7 @@ function Updater() {
}; };
return ( return (
<Forms.FormSection className={Margins.top16}> <SettingsTab title="Vencord Updater">
<Forms.FormTitle tag="h5">Updater Settings</Forms.FormTitle> <Forms.FormTitle tag="h5">Updater Settings</Forms.FormTitle>
<Switch <Switch
value={settings.notifyAboutUpdates} value={settings.notifyAboutUpdates}
@ -246,11 +245,8 @@ function Updater() {
<Forms.FormTitle tag="h5">Updates</Forms.FormTitle> <Forms.FormTitle tag="h5">Updates</Forms.FormTitle>
{isNewer ? <Newer {...commonProps} /> : <Updatable {...commonProps} />} {isNewer ? <Newer {...commonProps} /> : <Updatable {...commonProps} />}
</Forms.FormSection > </SettingsTab>
); );
} }
export default IS_WEB ? null : ErrorBoundary.wrap(Updater, { export default IS_WEB ? null : wrapTab(Updater, "Updater");
message: "Failed to render the Updater. If this persists, try using the installer to reinstall!",
onError: onlyOnce(handleComponentFailed),
});

View File

@ -21,7 +21,6 @@ import { openNotificationLogModal } from "@api/Notifications/notificationLog";
import { Settings, useSettings } from "@api/Settings"; import { Settings, useSettings } from "@api/Settings";
import { classNameFactory } from "@api/Styles"; import { classNameFactory } from "@api/Styles";
import DonateButton from "@components/DonateButton"; import DonateButton from "@components/DonateButton";
import ErrorBoundary from "@components/ErrorBoundary";
import { ErrorCard } from "@components/ErrorCard"; import { ErrorCard } from "@components/ErrorCard";
import { Margins } from "@utils/margins"; import { Margins } from "@utils/margins";
import { identity } from "@utils/misc"; import { identity } from "@utils/misc";
@ -29,6 +28,8 @@ import { relaunch, showItemInFolder } from "@utils/native";
import { useAwaiter } from "@utils/react"; import { useAwaiter } from "@utils/react";
import { Button, Card, Forms, React, Select, Slider, Switch } from "@webpack/common"; import { Button, Card, Forms, React, Select, Slider, Switch } from "@webpack/common";
import { SettingsTab, wrapTab } from "./shared";
const cl = classNameFactory("vc-settings-"); const cl = classNameFactory("vc-settings-");
const DEFAULT_DONATE_IMAGE = "https://cdn.discordapp.com/emojis/1026533090627174460.png"; const DEFAULT_DONATE_IMAGE = "https://cdn.discordapp.com/emojis/1026533090627174460.png";
@ -97,7 +98,7 @@ function VencordSettings() {
]; ];
return ( return (
<React.Fragment> <SettingsTab title="Vencord Settings">
<DonateCard image={donateImage} /> <DonateCard image={donateImage} />
<Forms.FormSection title="Quick Actions"> <Forms.FormSection title="Quick Actions">
<Card className={cl("quick-actions-card")}> <Card className={cl("quick-actions-card")}>
@ -153,7 +154,7 @@ function VencordSettings() {
{typeof Notification !== "undefined" && <NotificationSection settings={settings.notifications} />} {typeof Notification !== "undefined" && <NotificationSection settings={settings.notifications} />}
</React.Fragment> </SettingsTab>
); );
} }
@ -263,4 +264,4 @@ function DonateCard({ image }: DonateCardProps) {
); );
} }
export default ErrorBoundary.wrap(VencordSettings); export default wrapTab(VencordSettings, "Vencord Settings");

View File

@ -1,96 +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 "./settingsStyles.css";
import { classNameFactory } from "@api/Styles";
import ErrorBoundary from "@components/ErrorBoundary";
import { handleComponentFailed } from "@components/handleComponentFailed";
import { isMobile } from "@utils/misc";
import { onlyOnce } from "@utils/onlyOnce";
import { Forms, SettingsRouter, TabBar, Text } from "@webpack/common";
import BackupRestoreTab from "./BackupRestoreTab";
import CloudTab from "./CloudTab";
import PluginsTab from "./PluginsTab";
import ThemesTab from "./ThemesTab";
import Updater from "./Updater";
import VencordSettings from "./VencordTab";
const cl = classNameFactory("vc-settings-");
interface SettingsProps {
tab: string;
}
interface SettingsTab {
name: string;
component?: React.ComponentType;
}
const SettingsTabs: Record<string, SettingsTab> = {
VencordSettings: { name: "Vencord", component: () => <VencordSettings /> },
VencordPlugins: { name: "Plugins", component: () => <PluginsTab /> },
VencordThemes: { name: "Themes", component: () => <ThemesTab /> },
VencordUpdater: { name: "Updater" }, // Only show updater if IS_WEB is false
VencordCloud: { name: "Cloud", component: () => <CloudTab /> },
VencordSettingsSync: { name: "Backup & Restore", component: () => <BackupRestoreTab /> }
};
if (!IS_WEB) SettingsTabs.VencordUpdater.component = () => Updater && <Updater />;
function Settings(props: SettingsProps) {
const { tab = "VencordSettings" } = props;
const CurrentTab = SettingsTabs[tab]?.component ?? null;
if (isMobile) {
return CurrentTab && <CurrentTab />;
}
return <Forms.FormSection>
<Text variant="heading-lg/semibold" style={{ color: "var(--header-primary)" }} tag="h2">Vencord Settings</Text>
<TabBar
type="top"
look="brand"
className={cl("tab-bar")}
selectedItem={tab}
onItemSelect={SettingsRouter.open}
>
{Object.entries(SettingsTabs).map(([key, { name, component }]) => {
if (!component) return null;
return <TabBar.Item
id={key}
className={cl("tab-bar-item")}
key={key}>
{name}
</TabBar.Item>;
})}
</TabBar>
<Forms.FormDivider />
{CurrentTab && <CurrentTab />}
</Forms.FormSection >;
}
const onError = onlyOnce(handleComponentFailed);
export default function (props: SettingsProps) {
return <ErrorBoundary onError={onError}>
<Settings tab={props.tab} />
</ErrorBoundary>;
}

View File

@ -29,14 +29,12 @@
.vc-settings-card { .vc-settings-card {
padding: 1em; padding: 1em;
margin-bottom: 1em; margin-bottom: 1em;
margin-top: 1em;
} }
.vc-backup-restore-card { .vc-backup-restore-card {
background-color: var(--info-warning-background); background-color: var(--info-warning-background);
border-color: var(--info-warning-foreground); border-color: var(--info-warning-foreground);
color: var(--info-warning-text); color: var(--info-warning-text);
margin-top: 0;
} }
.vc-settings-theme-links { .vc-settings-theme-links {
@ -59,7 +57,7 @@
} }
.vc-text-selectable, .vc-text-selectable,
.vc-text-selectable :not(a, button, a *, button *) { .vc-text-selectable :not(a, button, a *, button *, input, input *) {
/* make text selectable, silly discord makes the entirety of settings not selectable */ /* make text selectable, silly discord makes the entirety of settings not selectable */
user-select: text; user-select: text;

View File

@ -0,0 +1,51 @@
/*
* Vencord, a modification for Discord's desktop app
* Copyright (c) 2023 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 "./settingsStyles.css";
import ErrorBoundary from "@components/ErrorBoundary";
import { handleComponentFailed } from "@components/handleComponentFailed";
import { Margins } from "@utils/margins";
import { onlyOnce } from "@utils/onlyOnce";
import { Forms, Text } from "@webpack/common";
import type { ComponentType, PropsWithChildren } from "react";
export function SettingsTab({ title, children }: PropsWithChildren<{ title: string; }>) {
return (
<Forms.FormSection>
<Text
variant="heading-lg/semibold"
tag="h2"
className={Margins.bottom16}
>
{title}
</Text>
{children}
</Forms.FormSection>
);
}
const onError = onlyOnce(handleComponentFailed);
export function wrapTab(component: ComponentType, tab: string) {
return ErrorBoundary.wrap(component, {
message: `Failed to render the ${tab} tab. If this issue persists, try using the installer to reinstall!`,
onError,
});
}

View File

@ -0,0 +1,7 @@
.vc-open-external-icon {
transform: rotate(45deg);
}
.vc-owner-crown-icon {
color: var(--text-warning);
}

View File

@ -1,21 +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/>.
*/
export { default as PatchHelper } from "./PatchHelper";
export { default as PluginSettings } from "./PluginSettings";
export { default as VencordSettings } from "./VencordSettings";

View File

@ -82,8 +82,8 @@ export default definePlugin({
find: "Messages.PROFILE_USER_BADGES,role:", find: "Messages.PROFILE_USER_BADGES,role:",
replacement: [ replacement: [
{ {
match: /null==\i\?void 0:(\i)\.getBadges\(\)/, match: /(?<=(\i)\.isTryItOutFlow,)(.{0,300})null==\i\?void 0:(\i)\.getBadges\(\)/,
replace: (_, badgesMod) => `Vencord.Api.Badges._getBadges(arguments[0]).concat(${badgesMod}?.getBadges()??[])`, replace: (_, props, restCode, badgesMod) => `vencordProps=${props},${restCode}Vencord.Api.Badges._getBadges(vencordProps).concat(${badgesMod}?.getBadges()??[])`,
}, },
{ {
// alt: "", aria-hidden: false, src: originalSrc // alt: "", aria-hidden: false, src: originalSrc

View File

@ -21,17 +21,102 @@ import { CheckedTextInput } from "@components/CheckedTextInput";
import { Devs } from "@utils/constants"; import { Devs } from "@utils/constants";
import { Logger } from "@utils/Logger"; import { Logger } from "@utils/Logger";
import { Margins } from "@utils/margins"; import { Margins } from "@utils/margins";
import { ModalContent, ModalHeader, ModalRoot, openModal } from "@utils/modal"; import { ModalContent, ModalHeader, ModalRoot, openModalLazy } from "@utils/modal";
import definePlugin from "@utils/types"; import definePlugin from "@utils/types";
import { findByCodeLazy, findByPropsLazy } from "@webpack"; import { findByCodeLazy, findStoreLazy } from "@webpack";
import { Forms, GuildStore, Menu, PermissionStore, React, Toasts, Tooltip, UserStore } from "@webpack/common"; import { FluxDispatcher, Forms, GuildStore, Menu, PermissionStore, React, RestAPI, Toasts, Tooltip, UserStore } from "@webpack/common";
import { Promisable } from "type-fest";
const MANAGE_EMOJIS_AND_STICKERS = 1n << 30n; const MANAGE_EMOJIS_AND_STICKERS = 1n << 30n;
const GuildEmojiStore = findByPropsLazy("getGuilds", "getGuildEmoji"); const GuildEmojiStore = findStoreLazy("EmojiStore");
const StickersStore = findStoreLazy("StickersStore");
const uploadEmoji = findByCodeLazy('"EMOJI_UPLOAD_START"', "GUILD_EMOJIS("); const uploadEmoji = findByCodeLazy('"EMOJI_UPLOAD_START"', "GUILD_EMOJIS(");
function getGuildCandidates(isAnimated: boolean) { interface Sticker {
t: "Sticker";
description: string;
format_type: number;
guild_id: string;
id: string;
name: string;
tags: string;
type: number;
}
interface Emoji {
t: "Emoji";
id: string;
name: string;
isAnimated: boolean;
}
type Data = Emoji | Sticker;
const StickerExt = [, "png", "png", "json", "gif"] as const;
function getUrl(data: Data) {
if (data.t === "Emoji")
return `${location.protocol}//${window.GLOBAL_ENV.CDN_HOST}/emojis/${data.id}.${data.isAnimated ? "gif" : "png"}`;
return `${location.origin}/stickers/${data.id}.${StickerExt[data.format_type]}`;
}
async function fetchSticker(id: string) {
const cached = StickersStore.getStickerById(id);
if (cached) return cached;
const { body } = await RestAPI.get({
url: `/stickers/${id}`
});
FluxDispatcher.dispatch({
type: "STICKER_FETCH_SUCCESS",
sticker: body
});
return body as Sticker;
}
async function cloneSticker(guildId: string, sticker: Sticker) {
const data = new FormData();
data.append("name", sticker.name);
data.append("tags", sticker.tags);
data.append("description", sticker.description);
data.append("file", await fetchBlob(getUrl(sticker)));
const { body } = await RestAPI.post({
url: `/guilds/${guildId}/stickers`,
body: data,
});
FluxDispatcher.dispatch({
type: "GUILD_STICKERS_CREATE_SUCCESS",
guildId,
sticker: {
...body,
user: UserStore.getCurrentUser()
}
});
}
async function cloneEmoji(guildId: string, emoji: Emoji) {
const data = await fetchBlob(getUrl(emoji));
const dataUrl = await new Promise<string>(resolve => {
const reader = new FileReader();
reader.onload = () => resolve(reader.result as string);
reader.readAsDataURL(data);
});
return uploadEmoji({
guildId,
name: emoji.name.split("~")[0],
image: dataUrl
});
}
function getGuildCandidates(data: Data) {
const meId = UserStore.getCurrentUser().id; const meId = UserStore.getCurrentUser().id;
return Object.values(GuildStore.getGuilds()).filter(g => { return Object.values(GuildStore.getGuilds()).filter(g => {
@ -39,6 +124,10 @@ function getGuildCandidates(isAnimated: boolean) {
BigInt(PermissionStore.getGuildPermissions({ id: g.id }) & MANAGE_EMOJIS_AND_STICKERS) === MANAGE_EMOJIS_AND_STICKERS; BigInt(PermissionStore.getGuildPermissions({ id: g.id }) & MANAGE_EMOJIS_AND_STICKERS) === MANAGE_EMOJIS_AND_STICKERS;
if (!canCreate) return false; if (!canCreate) return false;
if (data.t === "Sticker") return true;
const { isAnimated } = data as Emoji;
const emojiSlots = g.getMaxEmojiSlots(); const emojiSlots = g.getMaxEmojiSlots();
const { emojis } = GuildEmojiStore.getGuilds()[g.id]; const { emojis } = GuildEmojiStore.getGuilds()[g.id];
@ -49,33 +138,34 @@ function getGuildCandidates(isAnimated: boolean) {
}).sort((a, b) => a.name.localeCompare(b.name)); }).sort((a, b) => a.name.localeCompare(b.name));
} }
async function doClone(guildId: string, id: string, name: string, isAnimated: boolean) { async function fetchBlob(url: string) {
const data = await fetch(`${location.protocol}//${window.GLOBAL_ENV.CDN_HOST}/emojis/${id}.${isAnimated ? "gif" : "png"}`) const res = await fetch(url);
.then(r => r.blob()); if (!res.ok)
const reader = new FileReader(); throw new Error(`Failed to fetch ${url} - ${res.status}`);
return res.blob();
}
async function doClone(guildId: string, data: Sticker | Emoji) {
try {
if (data.t === "Sticker")
await cloneSticker(guildId, data);
else
await cloneEmoji(guildId, data);
reader.onload = () => {
uploadEmoji({
guildId,
name: name.split("~")[0],
image: reader.result
}).then(() => {
Toasts.show({ Toasts.show({
message: `Successfully cloned ${name}!`, message: `Successfully cloned ${data.name} to ${GuildStore.getGuild(guildId)?.name ?? "your server"}!`,
type: Toasts.Type.SUCCESS, type: Toasts.Type.SUCCESS,
id: Toasts.genId() id: Toasts.genId()
}); });
}).catch((e: any) => { } catch (e) {
new Logger("EmoteCloner").error("Failed to upload emoji", e); new Logger("EmoteCloner").error("Failed to clone", data.name, "to", guildId, e);
Toasts.show({ Toasts.show({
message: "Oopsie something went wrong :( Check console!!!", message: "Oopsie something went wrong :( Check console!!!",
type: Toasts.Type.FAILURE, type: Toasts.Type.FAILURE,
id: Toasts.genId() id: Toasts.genId()
}); });
}); }
};
reader.readAsDataURL(data);
} }
const getFontSize = (s: string) => { const getFontSize = (s: string) => {
@ -86,20 +176,23 @@ const getFontSize = (s: string) => {
const nameValidator = /^\w+$/i; const nameValidator = /^\w+$/i;
function CloneModal({ id, name: emojiName, isAnimated }: { id: string; name: string; isAnimated: boolean; }) { function CloneModal({ data }: { data: Sticker | Emoji; }) {
const [isCloning, setIsCloning] = React.useState(false); const [isCloning, setIsCloning] = React.useState(false);
const [name, setName] = React.useState(emojiName); const [name, setName] = React.useState(data.name);
const [x, invalidateMemo] = React.useReducer(x => x + 1, 0); const [x, invalidateMemo] = React.useReducer(x => x + 1, 0);
const guilds = React.useMemo(() => getGuildCandidates(isAnimated), [isAnimated, x]); const guilds = React.useMemo(() => getGuildCandidates(data), [data.id, x]);
return ( return (
<> <>
<Forms.FormTitle className={Margins.top20}>Custom Name</Forms.FormTitle> <Forms.FormTitle className={Margins.top20}>Custom Name</Forms.FormTitle>
<CheckedTextInput <CheckedTextInput
value={name} value={name}
onChange={setName} onChange={v => {
data.name = v;
setName(v);
}}
validate={v => validate={v =>
(v.length > 1 && v.length < 32 && nameValidator.test(v)) (v.length > 1 && v.length < 32 && nameValidator.test(v))
|| "Name must be between 2 and 32 characters and only contain alphanumeric characters" || "Name must be between 2 and 32 characters and only contain alphanumeric characters"
@ -135,7 +228,7 @@ function CloneModal({ id, name: emojiName, isAnimated }: { id: string; name: str
}} }}
onClick={isCloning ? void 0 : async () => { onClick={isCloning ? void 0 : async () => {
setIsCloning(true); setIsCloning(true);
doClone(g.id, id, name, isAnimated).finally(() => { doClone(g.id, data).finally(() => {
invalidateMemo(); invalidateMemo();
setIsCloning(false); setIsCloning(false);
}); });
@ -175,32 +268,38 @@ function CloneModal({ id, name: emojiName, isAnimated }: { id: string; name: str
); );
} }
function buildMenuItem(id: string, name: string, isAnimated: boolean) { function buildMenuItem(type: "Emoji" | "Sticker", fetchData: () => Promisable<Omit<Sticker | Emoji, "t">>) {
return ( return (
<Menu.MenuItem <Menu.MenuItem
id="emote-cloner" id="emote-cloner"
key="emote-cloner" key="emote-cloner"
label="Clone Emote" label={`Clone ${type}`}
action={() => action={() =>
openModal(modalProps => ( openModalLazy(async () => {
const res = await fetchData();
const data = { t: type, ...res } as Sticker | Emoji;
const url = getUrl(data);
return modalProps => (
<ModalRoot {...modalProps}> <ModalRoot {...modalProps}>
<ModalHeader> <ModalHeader>
<img <img
role="presentation" role="presentation"
aria-hidden aria-hidden
src={`${location.protocol}//${window.GLOBAL_ENV.CDN_HOST}/emojis/${id}.${isAnimated ? "gif" : "png"}`} src={url}
alt="" alt=""
height={24} height={24}
width={24} width={24}
style={{ marginRight: "0.5em" }} style={{ marginRight: "0.5em" }}
/> />
<Forms.FormText>Clone {name}</Forms.FormText> <Forms.FormText>Clone {data.name}</Forms.FormText>
</ModalHeader> </ModalHeader>
<ModalContent> <ModalContent>
<CloneModal id={id} name={name} isAnimated={isAnimated} /> <CloneModal data={data} />
</ModalContent> </ModalContent>
</ModalRoot> </ModalRoot>
)) );
})
} }
/> />
); );
@ -213,28 +312,53 @@ function isGifUrl(url: string) {
const messageContextMenuPatch: NavContextMenuPatchCallback = (children, props) => () => { const messageContextMenuPatch: NavContextMenuPatchCallback = (children, props) => () => {
const { favoriteableId, itemHref, itemSrc, favoriteableType } = props ?? {}; const { favoriteableId, itemHref, itemSrc, favoriteableType } = props ?? {};
if (!favoriteableId || favoriteableType !== "emoji") return; if (!favoriteableId) return;
const menuItem = (() => {
switch (favoriteableType) {
case "emoji":
const match = props.message.content.match(RegExp(`<a?:(\\w+)(?:~\\d+)?:${favoriteableId}>|https://cdn\\.discordapp\\.com/emojis/${favoriteableId}\\.`)); const match = props.message.content.match(RegExp(`<a?:(\\w+)(?:~\\d+)?:${favoriteableId}>|https://cdn\\.discordapp\\.com/emojis/${favoriteableId}\\.`));
if (!match) return; if (!match) return;
const name = match[1] ?? "FakeNitroEmoji"; const name = match[1] ?? "FakeNitroEmoji";
const group = findGroupChildrenByChildId("copy-link", children); return buildMenuItem("Emoji", () => ({
if (group) group.push(buildMenuItem(favoriteableId, name, isGifUrl(itemHref ?? itemSrc))); id: favoriteableId,
name,
isAnimated: isGifUrl(itemHref ?? itemSrc)
}));
case "sticker":
const sticker = props.message.stickerItems.find(s => s.id === favoriteableId);
if (sticker?.format_type === 3 /* LOTTIE */) return;
return buildMenuItem("Sticker", () => fetchSticker(favoriteableId));
}
})();
if (menuItem)
findGroupChildrenByChildId("copy-link", children)?.push(menuItem);
}; };
const expressionPickerPatch: NavContextMenuPatchCallback = (children, props: { target: HTMLElement; }) => () => { const expressionPickerPatch: NavContextMenuPatchCallback = (children, props: { target: HTMLElement; }) => () => {
const { id, name, type } = props?.target?.dataset ?? {}; const { id, name, type } = props?.target?.dataset ?? {};
if (!id || !name || type !== "emoji") return; if (!id) return;
if (type === "emoji" && name) {
const firstChild = props.target.firstChild as HTMLImageElement; const firstChild = props.target.firstChild as HTMLImageElement;
children.push(buildMenuItem(id, name, firstChild && isGifUrl(firstChild.src))); children.push(buildMenuItem("Emoji", () => ({
id,
name,
isAnimated: firstChild && isGifUrl(firstChild.src)
})));
} else if (type === "sticker" && !props.target.className?.includes("lottieCanvas")) {
children.push(buildMenuItem("Sticker", () => fetchSticker(id)));
}
}; };
export default definePlugin({ export default definePlugin({
name: "EmoteCloner", name: "EmoteCloner",
description: "Adds a Clone context menu item to emotes to clone them your own server", description: "Allows you to clone Emotes & Stickers to your own server (right click them)",
tags: ["StickerCloner"],
authors: [Devs.Ven, Devs.Nuckyz], authors: [Devs.Ven, Devs.Nuckyz],
start() { start() {

View File

@ -130,6 +130,8 @@ export default definePlugin({
name: "ImageZoom", name: "ImageZoom",
description: "Lets you zoom in to images and gifs. Use scroll wheel to zoom in and shift + scroll wheel to increase lens radius / size", description: "Lets you zoom in to images and gifs. Use scroll wheel to zoom in and shift + scroll wheel to increase lens radius / size",
authors: [Devs.Aria], authors: [Devs.Aria],
tags: ["ImageUtilities"],
patches: [ patches: [
{ {
find: '"renderLinkComponent","maxWidth"', find: '"renderLinkComponent","maxWidth"',

View File

@ -64,7 +64,13 @@ function Indicator() {
} }
function ChatBarIcon() { function ChatBarIcon(chatBoxProps: {
type: {
analyticsName: string;
};
}) {
if (chatBoxProps.type.analyticsName !== "normal") return null;
return ( return (
<Tooltip text="Encrypt Message"> <Tooltip text="Encrypt Message">
{({ onMouseEnter, onMouseLeave }) => ( {({ onMouseEnter, onMouseLeave }) => (
@ -133,7 +139,7 @@ export default definePlugin({
find: ".activeCommandOption", find: ".activeCommandOption",
replacement: { replacement: {
match: /(.)\.push.{1,30}disabled:(\i),.{1,20}\},"gift"\)\)/, match: /(.)\.push.{1,30}disabled:(\i),.{1,20}\},"gift"\)\)/,
replace: "$&;try{$2||$1.push($self.chatBarIcon())}catch{}", replace: "$&;try{$2||$1.push($self.chatBarIcon(arguments[0]))}catch{}",
} }
}, },
], ],

View File

@ -17,10 +17,11 @@
*/ */
import { addClickListener, removeClickListener } from "@api/MessageEvents"; import { addClickListener, removeClickListener } from "@api/MessageEvents";
import { definePluginSettings, Settings } 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";
import { findByPropsLazy } from "@webpack"; import { findByPropsLazy } from "@webpack";
import { PermissionStore, UserStore } from "@webpack/common"; import { FluxDispatcher, PermissionStore, UserStore } from "@webpack/common";
let isDeletePressed = false; let isDeletePressed = false;
const keydown = (e: KeyboardEvent) => e.key === "Backspace" && (isDeletePressed = true); const keydown = (e: KeyboardEvent) => e.key === "Backspace" && (isDeletePressed = true);
@ -28,13 +29,7 @@ const keyup = (e: KeyboardEvent) => e.key === "Backspace" && (isDeletePressed =
const MANAGE_CHANNELS = 1n << 4n; const MANAGE_CHANNELS = 1n << 4n;
export default definePlugin({ const settings = definePluginSettings({
name: "MessageClickActions",
description: "Hold Backspace and click to delete, double click to edit",
authors: [Devs.Ven],
dependencies: ["MessageEventsAPI"],
options: {
enableDeleteOnClick: { enableDeleteOnClick: {
type: OptionType.BOOLEAN, type: OptionType.BOOLEAN,
description: "Enable delete on click", description: "Enable delete on click",
@ -44,8 +39,26 @@ export default definePlugin({
type: OptionType.BOOLEAN, type: OptionType.BOOLEAN,
description: "Enable double click to edit", description: "Enable double click to edit",
default: true default: true
}
}, },
enableDoubleClickToReply: {
type: OptionType.BOOLEAN,
description: "Enable double click to reply",
default: true
},
requireModifier: {
type: OptionType.BOOLEAN,
description: "Only do double click actions when shift/ctrl is held",
default: false
}
});
export default definePlugin({
name: "MessageClickActions",
description: "Hold Backspace and click to delete, double click to edit/reply",
authors: [Devs.Ven],
dependencies: ["MessageEventsAPI"],
settings,
start() { start() {
const MessageActions = findByPropsLazy("deleteMessage", "startEditMessage"); const MessageActions = findByPropsLazy("deleteMessage", "startEditMessage");
@ -54,15 +67,30 @@ export default definePlugin({
document.addEventListener("keydown", keydown); document.addEventListener("keydown", keydown);
document.addEventListener("keyup", keyup); document.addEventListener("keyup", keyup);
this.onClick = addClickListener((msg, chan, event) => { this.onClick = addClickListener((msg, channel, event) => {
const isMe = msg.author.id === UserStore.getCurrentUser().id; const isMe = msg.author.id === UserStore.getCurrentUser().id;
if (!isDeletePressed) { if (!isDeletePressed) {
if (Vencord.Settings.plugins.MessageClickActions.enableDoubleClickToEdit && (isMe && event.detail >= 2 && !EditStore.isEditing(chan.id, msg.id))) { if (event.detail < 2) return;
MessageActions.startEditMessage(chan.id, msg.id, msg.content); if (settings.store.requireModifier && !event.ctrlKey && !event.shiftKey) return;
if (isMe) {
if (!settings.store.enableDoubleClickToEdit || EditStore.isEditing(channel.id, msg.id)) return;
MessageActions.startEditMessage(channel.id, msg.id, msg.content);
event.preventDefault(); event.preventDefault();
} else {
if (!settings.store.enableDoubleClickToReply) return;
FluxDispatcher.dispatch({
type: "CREATE_PENDING_REPLY",
channel,
message: msg,
shouldMention: !Settings.plugins.NoReplyMention.enabled,
showMentionToggle: channel.guild_id !== null
});
} }
} else if (Vencord.Settings.plugins.MessageClickActions.enableDeleteOnClick && (isMe || PermissionStore.can(MANAGE_CHANNELS, chan))) { } else if (settings.store.enableDeleteOnClick && (isMe || PermissionStore.can(MANAGE_CHANNELS, channel))) {
MessageActions.deleteMessage(chan.id, msg.id); MessageActions.deleteMessage(channel.id, msg.id);
event.preventDefault(); event.preventDefault();
} }
}); });

View File

@ -17,11 +17,13 @@
*/ */
import { definePluginSettings } from "@api/Settings"; import { definePluginSettings } from "@api/Settings";
import { Flex } from "@components/Flex";
import { Devs } from "@utils/constants"; import { Devs } from "@utils/constants";
import { proxyLazy } from "@utils/lazy.js"; import { Margins } from "@utils/margins";
import definePlugin, { OptionType } from "@utils/types"; import definePlugin, { OptionType } from "@utils/types";
import { find, findByPropsLazy } from "@webpack"; import { findByPropsLazy, findLazy } from "@webpack";
import { ChannelStore, GuildStore } from "@webpack/common"; import { Card, ChannelStore, Forms, GuildStore, Switch, TextInput, Tooltip, useState } from "@webpack/common";
import { RC } from "@webpack/types";
import { Channel, Message, User } from "discord-types/general"; import { Channel, Message, User } from "discord-types/general";
type PermissionName = "CREATE_INSTANT_INVITE" | "KICK_MEMBERS" | "BAN_MEMBERS" | "ADMINISTRATOR" | "MANAGE_CHANNELS" | "MANAGE_GUILD" | "CHANGE_NICKNAME" | "MANAGE_NICKNAMES" | "MANAGE_ROLES" | "MANAGE_WEBHOOKS" | "MANAGE_GUILD_EXPRESSIONS" | "CREATE_GUILD_EXPRESSIONS" | "VIEW_AUDIT_LOG" | "VIEW_CHANNEL" | "VIEW_GUILD_ANALYTICS" | "VIEW_CREATOR_MONETIZATION_ANALYTICS" | "MODERATE_MEMBERS" | "SEND_MESSAGES" | "SEND_TTS_MESSAGES" | "MANAGE_MESSAGES" | "EMBED_LINKS" | "ATTACH_FILES" | "READ_MESSAGE_HISTORY" | "MENTION_EVERYONE" | "USE_EXTERNAL_EMOJIS" | "ADD_REACTIONS" | "USE_APPLICATION_COMMANDS" | "MANAGE_THREADS" | "CREATE_PUBLIC_THREADS" | "CREATE_PRIVATE_THREADS" | "USE_EXTERNAL_STICKERS" | "SEND_MESSAGES_IN_THREADS" | "CONNECT" | "SPEAK" | "MUTE_MEMBERS" | "DEAFEN_MEMBERS" | "MOVE_MEMBERS" | "USE_VAD" | "PRIORITY_SPEAKER" | "STREAM" | "USE_EMBEDDED_ACTIVITIES" | "USE_SOUNDBOARD" | "USE_EXTERNAL_SOUNDS" | "REQUEST_TO_SPEAK" | "MANAGE_EVENTS" | "CREATE_EVENTS"; type PermissionName = "CREATE_INSTANT_INVITE" | "KICK_MEMBERS" | "BAN_MEMBERS" | "ADMINISTRATOR" | "MANAGE_CHANNELS" | "MANAGE_GUILD" | "CHANGE_NICKNAME" | "MANAGE_NICKNAMES" | "MANAGE_ROLES" | "MANAGE_WEBHOOKS" | "MANAGE_GUILD_EXPRESSIONS" | "CREATE_GUILD_EXPRESSIONS" | "VIEW_AUDIT_LOG" | "VIEW_CHANNEL" | "VIEW_GUILD_ANALYTICS" | "VIEW_CREATOR_MONETIZATION_ANALYTICS" | "MODERATE_MEMBERS" | "SEND_MESSAGES" | "SEND_TTS_MESSAGES" | "MANAGE_MESSAGES" | "EMBED_LINKS" | "ATTACH_FILES" | "READ_MESSAGE_HISTORY" | "MENTION_EVERYONE" | "USE_EXTERNAL_EMOJIS" | "ADD_REACTIONS" | "USE_APPLICATION_COMMANDS" | "MANAGE_THREADS" | "CREATE_PUBLIC_THREADS" | "CREATE_PRIVATE_THREADS" | "USE_EXTERNAL_STICKERS" | "SEND_MESSAGES_IN_THREADS" | "CONNECT" | "SPEAK" | "MUTE_MEMBERS" | "DEAFEN_MEMBERS" | "MOVE_MEMBERS" | "USE_VAD" | "PRIORITY_SPEAKER" | "STREAM" | "USE_EMBEDDED_ACTIVITIES" | "USE_SOUNDBOARD" | "USE_EXTERNAL_SOUNDS" | "REQUEST_TO_SPEAK" | "MANAGE_EVENTS" | "CREATE_EVENTS";
@ -36,6 +38,21 @@ interface Tag {
condition?(message: Message | null, user: User, channel: Channel): boolean; condition?(message: Message | null, user: User, channel: Channel): boolean;
} }
interface TagSetting {
text: string;
showInChat: boolean;
showInNotChat: boolean;
}
interface TagSettings {
WEBHOOK: TagSetting,
OWNER: TagSetting,
ADMINISTRATOR: TagSetting,
MODERATOR_STAFF: TagSetting,
MODERATOR: TagSetting,
VOICE_MODERATOR: TagSetting,
[k: string]: TagSetting;
}
const CLYDE_ID = "1081004946872352958"; const CLYDE_ID = "1081004946872352958";
// PermissionStore.computePermissions is not the same function and doesn't work here // PermissionStore.computePermissions is not the same function and doesn't work here
@ -44,7 +61,7 @@ const PermissionUtil = findByPropsLazy("computePermissions", "canEveryoneRole")
}; };
const Permissions = findByPropsLazy("SEND_MESSAGES", "VIEW_CREATOR_MONETIZATION_ANALYTICS") as Record<PermissionName, bigint>; const Permissions = findByPropsLazy("SEND_MESSAGES", "VIEW_CREATOR_MONETIZATION_ANALYTICS") as Record<PermissionName, bigint>;
const Tags = proxyLazy(() => find(m => m.Types?.[0] === "BOT").Types) as Record<string, number>; const Tag = findLazy(m => m.Types?.[0] === "BOT") as RC<{ type?: number, className?: string, useRemSizes?: boolean; }> & { Types: Record<string, number>; };
const isWebhook = (message: Message, user: User) => !!message?.webhookId && user.isNonUserBot(); const isWebhook = (message: Message, user: User) => !!message?.webhookId && user.isNonUserBot();
@ -81,64 +98,119 @@ const tags: Tag[] = [
permissions: ["MOVE_MEMBERS", "MUTE_MEMBERS", "DEAFEN_MEMBERS"] permissions: ["MOVE_MEMBERS", "MUTE_MEMBERS", "DEAFEN_MEMBERS"]
} }
]; ];
const defaultSettings = Object.fromEntries(
tags.map(({ name, displayName }) => [name, { text: displayName, showInChat: true, showInNotChat: true }])
) as TagSettings;
function SettingsComponent(props: { setValue(v: any): void; }) {
settings.store.tagSettings ??= defaultSettings;
const [tagSettings, setTagSettings] = useState(settings.store.tagSettings as TagSettings);
const setValue = (v: TagSettings) => {
setTagSettings(v);
props.setValue(v);
};
return (
<Flex flexDirection="column">
{tags.map(t => (
<Card style={{ padding: "1em 1em 0" }}>
<Forms.FormTitle style={{ width: "fit-content" }}>
<Tooltip text={t.description}>
{({ onMouseEnter, onMouseLeave }) => (
<div
onMouseEnter={onMouseEnter}
onMouseLeave={onMouseLeave}
>
{t.displayName} Tag <Tag type={Tag.Types[t.name]} />
</div>
)}
</Tooltip>
</Forms.FormTitle>
<TextInput
type="text"
value={tagSettings[t.name]?.text ?? t.displayName}
placeholder={`Text on tag (default: ${t.displayName})`}
onChange={v => {
tagSettings[t.name].text = v;
setValue(tagSettings);
}}
className={Margins.bottom16}
/>
<Switch
value={tagSettings[t.name]?.showInChat ?? true}
onChange={v => {
tagSettings[t.name].showInChat = v;
setValue(tagSettings);
}}
hideBorder
>
Show in messages
</Switch>
<Switch
value={tagSettings[t.name]?.showInNotChat ?? true}
onChange={v => {
tagSettings[t.name].showInNotChat = v;
setValue(tagSettings);
}}
hideBorder
>
Show in member list and profiles
</Switch>
</Card>
))}
</Flex>
);
}
const settings = definePluginSettings({ const settings = definePluginSettings({
dontShowForBots: { dontShowForBots: {
description: "Don't show tags (not including the webhook tag) for bots", description: "Don't show extra tags for bots (excluding webhooks)",
type: OptionType.BOOLEAN type: OptionType.BOOLEAN
}, },
dontShowBotTag: { dontShowBotTag: {
description: "Don't show [BOT] text for bots with other tags (verified bots will still have checkmark)", description: "Only show extra tags for bots / Hide [BOT] text",
type: OptionType.BOOLEAN type: OptionType.BOOLEAN
}, },
...Object.fromEntries(tags.map(({ name, displayName, description }) => [ tagSettings: {
`visibility_${name}`, { type: OptionType.COMPONENT,
description: `Show ${displayName} tags (${description})`, component: SettingsComponent,
type: OptionType.SELECT, description: "fill me",
options: [
{
label: "Always",
value: "always",
default: true
}, {
label: "Only in chat",
value: "chat"
}, {
label: "Only in member list and profiles",
value: "not-chat"
}, {
label: "Never",
value: "never"
} }
]
}
]))
}); });
export default definePlugin({ export default definePlugin({
name: "MoreUserTags", name: "MoreUserTags",
description: "Adds tags for webhooks and moderative roles (owner, admin, etc.)", description: "Adds tags for webhooks and moderative roles (owner, admin, etc.)",
authors: [Devs.Cyn, Devs.TheSun, Devs.RyanCaoDev], authors: [Devs.Cyn, Devs.TheSun, Devs.RyanCaoDev, Devs.LordElias],
settings, settings,
patches: [ patches: [
// add tags to the tag list // add tags to the tag list
{ {
find: '.BOT=0]="BOT"', find: '.BOT=0]="BOT"',
replacement: [ replacement: [
// add tags to the exported tags list (the Tags variable here) // add tags to the exported tags list (Tag.Types)
{ {
match: /(\i)\[.\.BOT=0\]="BOT";/, match: /(\i)\[.\.BOT=0\]="BOT";/,
replace: "$&$1=$self.addTagVariants($1);" replace: "$&$1=$self.addTagVariants($1);"
}
]
}, },
{
find: ".DISCORD_SYSTEM_MESSAGE_BOT_TAG_TOOLTIP;",
replacement: [
// make the tag show the right text // make the tag show the right text
{ {
match: /(switch\((\i)\){.+?)case (\i)\.BOT:default:(\i)=(\i\.\i\.Messages)\.BOT_TAG_BOT/, match: /(switch\((\i)\){.+?)case (\i(?:\.\i)?)\.BOT:default:(\i)=(\i\.\i\.Messages)\.BOT_TAG_BOT/,
replace: (_, origSwitch, variant, tags, displayedText, strings) => replace: (_, origSwitch, variant, tags, displayedText, strings) =>
`${origSwitch}default:{${displayedText} = $self.getTagText(${tags}[${variant}], ${strings})}` `${origSwitch}default:{${displayedText} = $self.getTagText(${tags}[${variant}], ${strings})}`
}, },
// show OP tags correctly // show OP tags correctly
{ {
match: /(\i)=(\i)===\i\.ORIGINAL_POSTER/, match: /(\i)=(\i)===\i(?:\.\i)?\.ORIGINAL_POSTER/,
replace: "$1=$self.isOPTag($2)" replace: "$1=$self.isOPTag($2)"
}, },
// add HTML data attributes (for easier theming) // add HTML data attributes (for easier theming)
@ -169,15 +241,15 @@ return type!==null?$2.botTag,type"
{ {
find: ".hasAvatarForGuild(null==", find: ".hasAvatarForGuild(null==",
replacement: { replacement: {
match: /\.usernameSection,user/, match: /(?=usernameIcon:)/,
replace: ".usernameSection,moreTags_channelId:arguments[0].channelId,user" replace: "moreTags_channelId:arguments[0].channelId,"
} }
}, },
{ {
find: 'copyMetaData:"User Tag"', find: 'copyMetaData:"User Tag"',
replacement: { replacement: {
match: /discriminatorClass:(.{1,100}),botClass:/, match: /(?=,botClass:)/,
replace: "discriminatorClass:$1,moreTags_channelId:arguments[0].moreTags_channelId,botClass:" replace: ",moreTags_channelId:arguments[0].moreTags_channelId"
} }
}, },
// in profiles // in profiles
@ -190,6 +262,37 @@ return type!==null?$2.botTag,type"
}, },
], ],
start() {
if (settings.store.tagSettings) return;
// @ts-ignore
if (!settings.store.visibility_WEBHOOK) settings.store.tagSettings = defaultSettings;
else {
const newSettings = { ...defaultSettings };
Object.entries(Vencord.PlainSettings.plugins.MoreUserTags).forEach(([name, value]) => {
const [setting, tag] = name.split("_");
if (setting === "visibility") {
switch (value) {
case "always":
// its the default
break;
case "chat":
newSettings[tag].showInNotChat = false;
break;
case "not-chat":
newSettings[tag].showInChat = false;
break;
case "never":
newSettings[tag].showInChat = false;
newSettings[tag].showInNotChat = false;
break;
}
}
settings.store.tagSettings = newSettings;
delete Vencord.Settings.plugins.MoreUserTags[name];
});
}
},
getPermissions(user: User, channel: Channel): string[] { getPermissions(user: User, channel: Channel): string[] {
const guild = GuildStore.getGuild(channel?.guild_id); const guild = GuildStore.getGuild(channel?.guild_id);
if (!guild) return []; if (!guild) return [];
@ -202,35 +305,36 @@ return type!==null?$2.botTag,type"
.filter(Boolean); .filter(Boolean);
}, },
addTagVariants(val: any /* i cant think of a good name */) { addTagVariants(tagConstant) {
let i = 100; let i = 100;
tags.forEach(({ name }) => { tags.forEach(({ name }) => {
val[name] = ++i; tagConstant[name] = ++i;
val[i] = name; tagConstant[i] = name;
val[`${name}-BOT`] = ++i; tagConstant[`${name}-BOT`] = ++i;
val[i] = `${name}-BOT`; tagConstant[i] = `${name}-BOT`;
val[`${name}-OP`] = ++i; tagConstant[`${name}-OP`] = ++i;
val[i] = `${name}-OP`; tagConstant[i] = `${name}-OP`;
}); });
return val; return tagConstant;
}, },
isOPTag: (tag: number) => tag === Tags.ORIGINAL_POSTER || tags.some(t => tag === Tags[`${t.name}-OP`]), isOPTag: (tag: number) => tag === Tag.Types.ORIGINAL_POSTER || tags.some(t => tag === Tag.Types[`${t.name}-OP`]),
getTagText(passedTagName: string, strings: Record<string, string>) { getTagText(passedTagName: string, strings: Record<string, string>) {
if (!passedTagName) return "BOT"; if (!passedTagName) return strings.BOT_TAG_BOT;
const [tagName, variant] = passedTagName.split("-"); const [tagName, variant] = passedTagName.split("-");
const tag = tags.find(({ name }) => tagName === name); const tag = tags.find(({ name }) => tagName === name);
if (!tag) return "BOT"; if (!tag) return strings.BOT_TAG_BOT;
if (variant === "BOT" && tagName !== "WEBHOOK" && this.settings.store.dontShowForBots) return strings.BOT_TAG_BOT; if (variant === "BOT" && tagName !== "WEBHOOK" && this.settings.store.dontShowForBots) return strings.BOT_TAG_BOT;
const tagText = settings.store.tagSettings?.[tag.name]?.text || tag.displayName;
switch (variant) { switch (variant) {
case "OP": case "OP":
return `${strings.BOT_TAG_FORUM_ORIGINAL_POSTER}${tag.displayName}`; return `${strings.BOT_TAG_FORUM_ORIGINAL_POSTER}${tagText}`;
case "BOT": case "BOT":
return `${strings.BOT_TAG_BOT}${tag.displayName}`; return `${strings.BOT_TAG_BOT}${tagText}`;
default: default:
return tag.displayName; return tagText;
} }
}, },
@ -242,12 +346,12 @@ return type!==null?$2.botTag,type"
channel?: Channel & { isForumPost(): boolean; }, channel?: Channel & { isForumPost(): boolean; },
channelId?: string; channelId?: string;
origType?: number; origType?: number;
location: string; location: "chat" | "not-chat";
}): number | null { }): number | null {
if (location === "chat" && user.id === "1") if (location === "chat" && user.id === "1")
return Tags.OFFICIAL; return Tag.Types.OFFICIAL;
if (user.id === CLYDE_ID) if (user.id === CLYDE_ID)
return Tags.AI; return Tag.Types.AI;
let type = typeof origType === "number" ? origType : null; let type = typeof origType === "number" ? origType : null;
@ -258,24 +362,19 @@ return type!==null?$2.botTag,type"
const perms = this.getPermissions(user, channel); const perms = this.getPermissions(user, channel);
for (const tag of tags) { for (const tag of tags) {
switch (settings[`visibility_${tag.name}`]) { if (location === "chat" && !settings.tagSettings[tag.name].showInChat) continue;
case "always": if (location === "not-chat" && !settings.tagSettings[tag.name].showInNotChat) continue;
case location:
break;
default:
continue;
}
if ( if (
tag.permissions?.some(perm => perms.includes(perm)) || tag.permissions?.some(perm => perms.includes(perm)) ||
(tag.condition?.(message!, user, channel)) (tag.condition?.(message!, user, channel))
) { ) {
if (channel.isForumPost() && channel.ownerId === user.id) if (channel.isForumPost() && channel.ownerId === user.id)
type = Tags[`${tag.name}-OP`]; type = Tag.Types[`${tag.name}-OP`];
else if (user.bot && !isWebhook(message!, user) && !settings.dontShowBotTag) else if (user.bot && !isWebhook(message!, user) && !settings.dontShowBotTag)
type = Tags[`${tag.name}-BOT`]; type = Tag.Types[`${tag.name}-BOT`];
else else
type = Tags[tag.name]; type = Tag.Types[tag.name];
break; break;
} }
} }

View File

@ -22,12 +22,27 @@ import definePlugin, { OptionType } from "@utils/types";
import type { Message } from "discord-types/general"; import type { Message } from "discord-types/general";
const settings = definePluginSettings({ const settings = definePluginSettings({
exemptList: { userList: {
description: description:
"List of users to exempt from this plugin (separated by commas or spaces)", "List of users to allow or exempt pings for (separated by commas or spaces)",
type: OptionType.STRING, type: OptionType.STRING,
default: "1234567890123445,1234567890123445", default: "1234567890123445,1234567890123445",
}, },
shouldPingListed: {
description: "Behaviour",
type: OptionType.SELECT,
options: [
{
label: "Do not ping the listed users",
value: false,
},
{
label: "Only ping the listed users",
value: true,
default: true,
},
],
},
inverseShiftReply: { inverseShiftReply: {
description: "Invert Discord's shift replying behaviour (enable to make shift reply mention user)", description: "Invert Discord's shift replying behaviour (enable to make shift reply mention user)",
type: OptionType.BOOLEAN, type: OptionType.BOOLEAN,
@ -38,11 +53,12 @@ const settings = definePluginSettings({
export default definePlugin({ export default definePlugin({
name: "NoReplyMention", name: "NoReplyMention",
description: "Disables reply pings by default", description: "Disables reply pings by default",
authors: [Devs.DustyAngel47, Devs.axyie, Devs.pylix], authors: [Devs.DustyAngel47, Devs.axyie, Devs.pylix, Devs.outfoxxed],
settings, settings,
shouldMention(message: Message, isHoldingShift: boolean) { shouldMention(message: Message, isHoldingShift: boolean) {
const isExempt = settings.store.exemptList.includes(message.author.id); const isListed = settings.store.userList.includes(message.author.id);
const isExempt = settings.store.shouldPingListed ? isListed : !isListed;
return settings.store.inverseShiftReply ? isHoldingShift !== isExempt : !isHoldingShift && isExempt; return settings.store.inverseShiftReply ? isHoldingShift !== isExempt : !isHoldingShift && isExempt;
}, },

View File

@ -0,0 +1,225 @@
/*
* Vencord, a modification for Discord's desktop app
* Copyright (c) 2023 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 ErrorBoundary from "@components/ErrorBoundary";
import { Flex } from "@components/Flex";
import { InfoIcon, OwnerCrownIcon } from "@components/Icons";
import { ModalCloseButton, ModalContent, ModalHeader, ModalProps, ModalRoot, ModalSize, openModal } from "@utils/modal";
import { ContextMenu, FluxDispatcher, GuildMemberStore, Menu, PermissionsBits, Text, Tooltip, useEffect, UserStore, useState, useStateFromStores } from "@webpack/common";
import type { Guild } from "discord-types/general";
import { cl, getPermissionDescription, getPermissionString } from "../utils";
import { PermissionAllowedIcon, PermissionDefaultIcon, PermissionDeniedIcon } from "./icons";
export const enum PermissionType {
Role = 0,
User = 1,
Owner = 2
}
export interface RoleOrUserPermission {
type: PermissionType;
id?: string;
permissions?: bigint;
overwriteAllow?: bigint;
overwriteDeny?: bigint;
}
function openRolesAndUsersPermissionsModal(permissions: Array<RoleOrUserPermission>, guild: Guild, header: string) {
return openModal(modalProps => (
<RolesAndUsersPermissions
modalProps={modalProps}
permissions={permissions}
guild={guild}
header={header}
/>
));
}
function RolesAndUsersPermissionsComponent({ permissions, guild, modalProps, header }: { permissions: Array<RoleOrUserPermission>; guild: Guild; modalProps: ModalProps; header: string; }) {
permissions.sort((a, b) => a.type - b.type);
useStateFromStores(
[GuildMemberStore],
() => GuildMemberStore.getMemberIds(guild.id),
null,
(old, current) => old.length === current.length
);
useEffect(() => {
const usersToRequest = permissions
.filter(p => p.type === PermissionType.User && !GuildMemberStore.isMember(guild.id, p.id!))
.map(({ id }) => id);
FluxDispatcher.dispatch({
type: "GUILD_MEMBERS_REQUEST",
guildIds: [guild.id],
userIds: usersToRequest
});
}, []);
const [selectedItemIndex, selectItem] = useState(0);
const selectedItem = permissions[selectedItemIndex];
return (
<ModalRoot
{...modalProps}
size={ModalSize.LARGE}
>
<ModalHeader>
<Text className={cl("perms-title")} variant="heading-lg/semibold">{header} permissions:</Text>
<ModalCloseButton onClick={modalProps.onClose} />
</ModalHeader>
<ModalContent>
{!selectedItem && (
<div className={cl("perms-no-perms")}>
<Text variant="heading-lg/normal">No permissions to display!</Text>
</div>
)}
{selectedItem && (
<div className={cl("perms-container")}>
<div className={cl("perms-list")}>
{permissions.map((permission, index) => {
const user = UserStore.getUser(permission.id ?? "");
const role = guild.roles[permission.id ?? ""];
return (
<button
className={cl("perms-list-item-btn")}
onClick={() => selectItem(index)}
>
<div
className={cl("perms-list-item", { "perms-list-item-active": selectedItemIndex === index })}
onContextMenu={e => {
if (permission.type === PermissionType.Role)
ContextMenu.open(e, () => (
<RoleContextMenu
guild={guild}
roleId={permission.id!}
onClose={modalProps.onClose}
/>
));
}}
>
{(permission.type === PermissionType.Role || permission.type === PermissionType.Owner) && (
<span
className={cl("perms-role-circle")}
style={{ backgroundColor: role?.colorString ?? "var(--primary-300)" }}
/>
)}
{permission.type === PermissionType.User && user !== undefined && (
<img
className={cl("perms-user-img")}
src={user.getAvatarURL(void 0, void 0, false)}
/>
)}
<Text variant="text-md/normal">
{
permission.type === PermissionType.Role
? role?.name || "Unknown Role"
: permission.type === PermissionType.User
? user?.tag || "Unknown User"
: (
<Flex style={{ gap: "0.2em", justifyItems: "center" }}>
@owner
<OwnerCrownIcon
height={18}
width={18}
aria-hidden="true"
/>
</Flex>
)
}
</Text>
</div>
</button>
);
})}
</div>
<div className={cl("perms-perms")}>
{Object.entries(PermissionsBits).map(([permissionName, bit]) => (
<div className={cl("perms-perms-item")}>
<div className={cl("perms-perms-item-icon")}>
{(() => {
const { permissions, overwriteAllow, overwriteDeny } = selectedItem;
if (permissions)
return (permissions & bit) === bit
? PermissionAllowedIcon()
: PermissionDeniedIcon();
if (overwriteAllow && (overwriteAllow & bit) === bit)
return PermissionAllowedIcon();
if (overwriteDeny && (overwriteDeny & bit) === bit)
return PermissionDeniedIcon();
return PermissionDefaultIcon();
})()}
</div>
<Text variant="text-md/normal">{getPermissionString(permissionName)}</Text>
<Tooltip text={getPermissionDescription(permissionName) || "No Description"}>
{props => <InfoIcon {...props} />}
</Tooltip>
</div>
))}
</div>
</div>
)}
</ModalContent>
</ModalRoot >
);
}
function RoleContextMenu({ guild, roleId, onClose }: { guild: Guild; roleId: string; onClose: () => void; }) {
return (
<Menu.Menu
navId={cl("role-context-menu")}
onClose={ContextMenu.close}
aria-label="Role Options"
>
<Menu.MenuItem
id="vc-pw-view-as-role"
label="View As Role"
action={() => {
const role = guild.roles[roleId];
if (!role) return;
onClose();
FluxDispatcher.dispatch({
type: "IMPERSONATE_UPDATE",
guildId: guild.id,
data: {
type: "ROLES",
roles: {
[roleId]: role
}
}
});
}}
/>
</Menu.Menu>
);
}
const RolesAndUsersPermissions = ErrorBoundary.wrap(RolesAndUsersPermissionsComponent);
export default openRolesAndUsersPermissionsModal;

View File

@ -0,0 +1,175 @@
/*
* Vencord, a modification for Discord's desktop app
* Copyright (c) 2023 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 ErrorBoundary from "@components/ErrorBoundary";
import { proxyLazy } from "@utils/lazy";
import { classes } from "@utils/misc";
import { filters, findBulk } from "@webpack";
import { i18n, PermissionsBits, Text, Tooltip, useMemo, UserStore, useState } from "@webpack/common";
import type { Guild, GuildMember } from "discord-types/general";
import { settings } from "..";
import { cl, getPermissionString, getSortedRoles, sortUserRoles } from "../utils";
import openRolesAndUsersPermissionsModal, { PermissionType, type RoleOrUserPermission } from "./RolesAndUsersPermissions";
interface UserPermission {
permission: string;
roleColor: string;
rolePosition: number;
}
type UserPermissions = Array<UserPermission>;
const Classes = proxyLazy(() => {
const modules = findBulk(
filters.byProps("roles", "rolePill", "rolePillBorder"),
filters.byProps("roleCircle", "dotBorderBase", "dotBorderColor"),
filters.byProps("roleNameOverflow", "root", "roleName", "roleRemoveButton")
);
return Object.assign({}, ...modules);
}) as Record<"roles" | "rolePill" | "rolePillBorder" | "desaturateUserColors" | "flex" | "alignCenter" | "justifyCenter" | "svg" | "background" | "dot" | "dotBorderColor" | "roleCircle" | "dotBorderBase" | "flex" | "alignCenter" | "justifyCenter" | "wrap" | "root" | "role" | "roleRemoveButton" | "roleDot" | "roleFlowerStar" | "roleRemoveIcon" | "roleRemoveIconFocused" | "roleVerifiedIcon" | "roleName" | "roleNameOverflow" | "actionButton" | "overflowButton" | "addButton" | "addButtonIcon" | "overflowRolesPopout" | "overflowRolesPopoutArrowWrapper" | "overflowRolesPopoutArrow" | "popoutBottom" | "popoutTop" | "overflowRolesPopoutHeader" | "overflowRolesPopoutHeaderIcon" | "overflowRolesPopoutHeaderText" | "roleIcon", string>;
function UserPermissionsComponent({ guild, guildMember }: { guild: Guild; guildMember: GuildMember; }) {
const [viewPermissions, setViewPermissions] = useState(settings.store.defaultPermissionsDropdownState);
const [rolePermissions, userPermissions] = useMemo(() => {
const userPermissions: UserPermissions = [];
const userRoles = getSortedRoles(guild, guildMember);
const rolePermissions: Array<RoleOrUserPermission> = userRoles.map(role => ({
type: PermissionType.Role,
...role
}));
if (guild.ownerId === guildMember.userId) {
rolePermissions.push({
type: PermissionType.Owner,
permissions: Object.values(PermissionsBits).reduce((prev, curr) => prev | curr, 0n)
});
const OWNER = i18n.Messages.GUILD_OWNER || "Server Owner";
userPermissions.push({
permission: OWNER,
roleColor: "var(--primary-300)",
rolePosition: Infinity
});
}
sortUserRoles(userRoles);
for (const [permission, bit] of Object.entries(PermissionsBits)) {
for (const { permissions, colorString, position, name } of userRoles) {
if ((permissions & bit) === bit) {
userPermissions.push({
permission: getPermissionString(permission),
roleColor: colorString || "var(--primary-300)",
rolePosition: position
});
break;
}
}
}
userPermissions.sort((a, b) => b.rolePosition - a.rolePosition);
return [rolePermissions, userPermissions];
}, []);
const { root, role, roleRemoveButton, roleNameOverflow, roles, rolePill, rolePillBorder, roleCircle, roleName } = Classes;
return (
<div>
<div className={cl("userperms-title-container")}>
<Text className={cl("userperms-title")} variant="eyebrow">Permissions</Text>
<div>
<Tooltip text="Role Details">
{tooltipProps => (
<button
{...tooltipProps}
className={cl("userperms-permdetails-btn")}
onClick={() =>
openRolesAndUsersPermissionsModal(
rolePermissions,
guild,
guildMember.nick || UserStore.getUser(guildMember.userId).username
)
}
>
<svg
width="24"
height="24"
viewBox="0 0 24 24"
>
<path fill="var(--text-normal)" d="M7 12.001C7 10.8964 6.10457 10.001 5 10.001C3.89543 10.001 3 10.8964 3 12.001C3 13.1055 3.89543 14.001 5 14.001C6.10457 14.001 7 13.1055 7 12.001ZM14 12.001C14 10.8964 13.1046 10.001 12 10.001C10.8954 10.001 10 10.8964 10 12.001C10 13.1055 10.8954 14.001 12 14.001C13.1046 14.001 14 13.1055 14 12.001ZM19 10.001C20.1046 10.001 21 10.8964 21 12.001C21 13.1055 20.1046 14.001 19 14.001C17.8954 14.001 17 13.1055 17 12.001C17 10.8964 17.8954 10.001 19 10.001Z" />
</svg>
</button>
)}
</Tooltip>
<Tooltip text={viewPermissions ? "Hide Permissions" : "View Permissions"}>
{tooltipProps => (
<button
{...tooltipProps}
className={cl("userperms-toggleperms-btn")}
onClick={() => setViewPermissions(v => !v)}
>
<svg
width="24"
height="24"
viewBox="0 0 24 24"
transform={viewPermissions ? "scale(1 -1)" : "scale(1 1)"}
>
<path fill="var(--text-normal)" d="M16.59 8.59003L12 13.17L7.41 8.59003L6 10L12 16L18 10L16.59 8.59003Z" />
</svg>
</button>
)}
</Tooltip>
</div>
</div>
{viewPermissions && userPermissions.length > 0 && (
<div className={classes(root, roles)}>
{userPermissions.map(({ permission, roleColor }) => (
<div className={classes(role, rolePill, rolePillBorder)}>
<div className={roleRemoveButton}>
<span
className={roleCircle}
style={{ backgroundColor: roleColor }}
/>
</div>
<div className={roleName}>
<Text
className={roleNameOverflow}
variant="text-xs/medium"
>
{permission}
</Text>
</div>
</div>
))}
</div>
)}
</div>
);
}
export default ErrorBoundary.wrap(UserPermissionsComponent, { noop: true });

View File

@ -0,0 +1,58 @@
/*
* Vencord, a modification for Discord's desktop app
* Copyright (c) 2023 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/>.
*/
export function PermissionDeniedIcon() {
return (
<svg
height="24"
width="24"
viewBox="0 0 24 24"
>
<title>Denied</title>
<path fill="var(--status-danger)" d="M18.4 4L12 10.4L5.6 4L4 5.6L10.4 12L4 18.4L5.6 20L12 13.6L18.4 20L20 18.4L13.6 12L20 5.6L18.4 4Z" />
</svg>
);
}
export function PermissionAllowedIcon() {
return (
<svg
height="24"
width="24"
viewBox="0 0 24 24"
>
<title>Allowed</title>
<path fill="var(--text-positive)" d="M8.99991 16.17L4.82991 12L3.40991 13.41L8.99991 19L20.9999 7.00003L19.5899 5.59003L8.99991 16.17ZZ" />
</svg>
);
}
export function PermissionDefaultIcon() {
return (
<svg
height="24"
width="24"
viewBox="0 0 16 16"
>
<g>
<title>Not overwritten</title>
<polygon fill="var(--text-normal)" points="12 2.32 10.513 2 4 13.68 5.487 14" />
</g>
</svg>
);
}

View File

@ -0,0 +1,180 @@
/*
* Vencord, a modification for Discord's desktop app
* Copyright (c) 2023 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 "./styles.css";
import { addContextMenuPatch, findGroupChildrenByChildId, NavContextMenuPatchCallback, removeContextMenuPatch } from "@api/ContextMenu";
import { definePluginSettings } from "@api/Settings";
import { Devs } from "@utils/constants";
import definePlugin, { OptionType } from "@utils/types";
import { ChannelStore, GuildMemberStore, GuildStore, Menu, PermissionsBits, UserStore } from "@webpack/common";
import type { Guild, GuildMember } from "discord-types/general";
import openRolesAndUsersPermissionsModal, { PermissionType, RoleOrUserPermission } from "./components/RolesAndUsersPermissions";
import UserPermissions from "./components/UserPermissions";
import { getSortedRoles } from "./utils";
export const enum PermissionsSortOrder {
HighestRole,
LowestRole
}
const enum MenuItemParentType {
User,
Channel,
Guild
}
export const settings = definePluginSettings({
permissionsSortOrder: {
description: "The sort method used for defining which role grants an user a certain permission",
type: OptionType.SELECT,
options: [
{ label: "Highest Role", value: PermissionsSortOrder.HighestRole, default: true },
{ label: "Lowest Role", value: PermissionsSortOrder.LowestRole }
],
},
defaultPermissionsDropdownState: {
description: "Whether the permissions dropdown on user popouts should be open by default",
type: OptionType.BOOLEAN,
default: false,
}
});
function MenuItem(guildId: string, id?: string, type?: MenuItemParentType) {
return (
<Menu.MenuItem
id="perm-viewer-permissions"
label="Permissions"
action={() => {
const guild = GuildStore.getGuild(guildId);
let permissions: RoleOrUserPermission[];
let header: string;
switch (type) {
case MenuItemParentType.User: {
const member = GuildMemberStore.getMember(guildId, id!);
permissions = getSortedRoles(guild, member)
.map(role => ({
type: PermissionType.Role,
...role
}));
if (guild.ownerId === id) {
permissions.push({
type: PermissionType.Owner,
permissions: Object.values(PermissionsBits).reduce((prev, curr) => prev | curr, 0n)
});
}
header = member.nick ?? UserStore.getUser(member.userId).username;
break;
}
case MenuItemParentType.Channel: {
const channel = ChannelStore.getChannel(id!);
permissions = Object.values(channel.permissionOverwrites).map(({ id, allow, deny, type }) => ({
type: type as PermissionType,
id,
overwriteAllow: allow,
overwriteDeny: deny
}));
header = channel.name;
break;
}
default: {
permissions = Object.values(guild.roles).map(role => ({
type: PermissionType.Role,
...role
}));
header = guild.name;
break;
}
}
openRolesAndUsersPermissionsModal(permissions, guild, header);
}}
/>
);
}
function makeContextMenuPatch(childId: string, type?: MenuItemParentType): NavContextMenuPatchCallback {
return (children, props) => () => {
if (!props) return children;
const group = findGroupChildrenByChildId(childId, children);
if (group) {
switch (type) {
case MenuItemParentType.User:
group.push(MenuItem(props.guildId, props.user.id, type));
break;
case MenuItemParentType.Channel:
group.push(MenuItem(props.guild.id, props.channel.id, type));
break;
case MenuItemParentType.Guild:
group.push(MenuItem(props.guild.id));
break;
}
}
};
}
export default definePlugin({
name: "PermissionsViewer",
description: "View the permissions a user or channel has, and the roles of a server",
authors: [Devs.Nuckyz, Devs.Ven],
settings,
patches: [
{
find: ".Messages.BOT_PROFILE_SLASH_COMMANDS",
replacement: {
match: /showBorder:.{0,60}}\),(?<=guild:(\i),guildMember:(\i),.+?)/,
replace: (m, guild, guildMember) => `${m}$self.UserPermissions(${guild},${guildMember}),`
}
}
],
UserPermissions: (guild: Guild, guildMember: GuildMember) => <UserPermissions guild={guild} guildMember={guildMember} />,
userContextMenuPatch: makeContextMenuPatch("roles", MenuItemParentType.User),
channelContextMenuPatch: makeContextMenuPatch("mute-channel", MenuItemParentType.Channel),
guildContextMenuPatch: makeContextMenuPatch("privacy", MenuItemParentType.Guild),
start() {
addContextMenuPatch("user-context", this.userContextMenuPatch);
addContextMenuPatch("channel-context", this.channelContextMenuPatch);
addContextMenuPatch("guild-context", this.guildContextMenuPatch);
},
stop() {
removeContextMenuPatch("user-context", this.userContextMenuPatch);
removeContextMenuPatch("channel-context", this.channelContextMenuPatch);
removeContextMenuPatch("guild-context", this.guildContextMenuPatch);
},
});

View File

@ -0,0 +1,128 @@
/* User Permissions Component */
.vc-permviewer-userperms-title-container {
display: flex;
justify-content: space-between;
}
.vc-permviewer-userperms-title {
margin-top: 10px;
margin-bottom: 6px;
}
.vc-permviewer-userperms-permdetails-btn {
all: unset;
cursor: pointer;
}
.vc-permviewer-userperms-toggleperms-btn {
all: unset;
cursor: pointer;
}
/* RolesAndUsersPermissions Component */
.vc-permviewer-perms-title {
flex-grow: 1;
}
.vc-permviewer-perms-no-perms {
width: 100%;
height: 100%;
display: flex;
align-items: center;
justify-content: center;
text-align: center;
}
.vc-permviewer-perms-container {
display: grid;
grid-template-columns: 1fr 2fr;
grid-template-areas: "list permissions";
padding: 16px 0;
}
.vc-permviewer-perms-list {
grid-area: list;
display: flex;
flex-direction: column;
border-right: 2px solid var(--background-modifier-active);
}
.vc-permviewer-perms-list-item-btn {
all: unset;
cursor: pointer;
}
.vc-permviewer-perms-list-item {
display: flex;
align-items: center;
padding: 8px 5px;
cursor: pointer;
width: 165px;
}
.vc-permviewer-perms-list-item > div {
text-overflow: ellipsis;
white-space: nowrap;
overflow: hidden;
}
.vc-permviewer-perms-list-item-active {
background-color: var(--background-modifier-selected);
border-radius: 5px;
}
.vc-permviewer-perms-role-circle {
border-radius: 50%;
width: 12px;
height: 12px;
margin-left: 3px;
margin-right: 11px;
flex-shrink: 0;
}
.vc-permviewer-perms-user-img {
border-radius: 50%;
width: 20px;
height: 20px;
margin-right: 6px;
}
.vc-permviewer-perms-perms {
grid-area: permissions;
display: flex;
flex-direction: column;
margin-left: 5px;
}
.vc-permviewer-perms-perms-item {
position: relative;
display: flex;
align-items: center;
padding: 10px;
border-bottom: 2px solid var(--background-modifier-active);
}
.vc-permviewer-perms-perms-item:last-child {
border: 0;
}
.vc-permviewer-perms-perms-item-icon {
border: 1px solid var(--background-modifier-selected);
width: 25px;
height: 25px;
margin-right: 5px;
}
.vc-permviewer-perms-perms-item .vc-info-icon {
color: var(--interactive-muted);
cursor: pointer;
position: absolute;
right: 0;
scale: 0.9;
}
.vc-permviewer-perms-perms-item .vc-info-icon:hover {
color: var(--interactive-active);
}

View File

@ -0,0 +1,84 @@
/*
* Vencord, a modification for Discord's desktop app
* Copyright (c) 2023 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 { classNameFactory } from "@api/Styles";
import { wordsToTitle } from "@utils/text";
import { i18n, Parser } from "@webpack/common";
import { Guild, GuildMember, Role } from "discord-types/general";
import type { ReactNode } from "react";
import { PermissionsSortOrder, settings } from ".";
export const cl = classNameFactory("vc-permviewer-");
function formatPermissionWithoutMatchingString(permission: string) {
return wordsToTitle(permission.toLowerCase().split("_"));
}
// because discord is unable to be consistent with their names
const PermissionKeyMap = {
MANAGE_GUILD: "MANAGE_SERVER",
MANAGE_GUILD_EXPRESSIONS: "MANAGE_EXPRESSIONS",
CREATE_GUILD_EXPRESSIONS: "CREATE_EXPRESSIONS",
MODERATE_MEMBERS: "MODERATE_MEMBER", // HELLOOOO ??????
STREAM: "VIDEO",
SEND_VOICE_MESSAGES: "ROLE_PERMISSIONS_SEND_VOICE_MESSAGE",
} as const;
export function getPermissionString(permission: string) {
permission = PermissionKeyMap[permission] || permission;
return i18n.Messages[permission] ||
// shouldn't get here but just in case
formatPermissionWithoutMatchingString(permission);
}
export function getPermissionDescription(permission: string): ReactNode {
// DISCORD PLEEEEEEEEAAAAASE IM BEGGING YOU :(
if (permission === "USE_APPLICATION_COMMANDS")
permission = "USE_APPLICATION_COMMANDS_GUILD";
else if (permission === "SEND_VOICE_MESSAGES")
permission = "SEND_VOICE_MESSAGE_GUILD";
else if (permission !== "STREAM")
permission = PermissionKeyMap[permission] || permission;
const msg = i18n.Messages[`ROLE_PERMISSIONS_${permission}_DESCRIPTION`] as any;
if (msg?.hasMarkdown)
return Parser.parse(msg.message);
if (typeof msg === "string") return msg;
return "";
}
export function getSortedRoles({ roles, id }: Guild, member: GuildMember) {
return [...member.roles, id]
.map(id => roles[id])
.sort((a, b) => b.position - a.position);
}
export function sortUserRoles(roles: Role[]) {
switch (settings.store.permissionsSortOrder) {
case PermissionsSortOrder.HighestRole:
return roles.sort((a, b) => b.position - a.position);
case PermissionsSortOrder.LowestRole:
return roles.sort((a, b) => a.position - b.position);
default:
return roles;
}
}

View File

@ -30,7 +30,7 @@ import { User } from "discord-types/general";
const SessionsStore = findStoreLazy("SessionsStore"); const SessionsStore = findStoreLazy("SessionsStore");
function Icon(path: string, viewBox = "0 0 24 24") { function Icon(path: string, viewBox = "0 0 24 24") {
return ({ color, tooltip, wantMargin }: { color: string; tooltip: string; wantMargin: boolean; }) => ( return ({ color, tooltip }: { color: string; tooltip: string; }) => (
<Tooltip text={tooltip} > <Tooltip text={tooltip} >
{(tooltipProps: any) => ( {(tooltipProps: any) => (
<svg <svg
@ -39,12 +39,6 @@ function Icon(path: string, viewBox = "0 0 24 24") {
width="20" width="20"
viewBox={viewBox} viewBox={viewBox}
fill={color} fill={color}
style={{
marginLeft: wantMargin ? 4 : 0,
verticalAlign: "top",
position: "relative",
top: wantMargin ? 1 : 0,
}}
> >
<path d={path} /> <path d={path} />
</svg> </svg>
@ -63,11 +57,11 @@ type Platform = keyof typeof Icons;
const getStatusColor = findByCodeLazy(".TWITCH", ".STREAMING", ".INVISIBLE"); const getStatusColor = findByCodeLazy(".TWITCH", ".STREAMING", ".INVISIBLE");
const PlatformIcon = ({ platform, status, wantMargin }: { platform: Platform, status: string; wantMargin: boolean; }) => { const PlatformIcon = ({ platform, status }: { platform: Platform, status: string; }) => {
const tooltip = platform[0].toUpperCase() + platform.slice(1); const tooltip = platform[0].toUpperCase() + platform.slice(1);
const Icon = Icons[platform] ?? Icons.desktop; const Icon = Icons[platform] ?? Icons.desktop;
return <Icon color={`var(--${getStatusColor(status)}`} tooltip={tooltip} wantMargin={wantMargin} />; return <Icon color={`var(--${getStatusColor(status)}`} tooltip={tooltip} />;
}; };
const getStatus = (id: string): Record<Platform, string> => PresenceStore.getState()?.clientStatuses?.[id]; const getStatus = (id: string): Record<Platform, string> => PresenceStore.getState()?.clientStatuses?.[id];
@ -105,14 +99,26 @@ const PlatformIndicator = ({ user, wantMargin = true }: { user: User; wantMargin
key={platform} key={platform}
platform={platform as Platform} platform={platform as Platform}
status={status} status={status}
wantMargin={wantMargin}
/> />
)); ));
if (!icons.length) return null; if (!icons.length) return null;
return ( return (
<span className="vc-platform-indicator"> <span
className="vc-platform-indicator"
style={{
display: "inline-flex",
justifyContent: "center",
marginLeft: wantMargin ? 4 : 0,
verticalAlign: "top",
position: "relative",
top: wantMargin ? 1 : 0,
padding: !wantMargin ? 1 : 0,
gap: 2
}}
>
{icons} {icons}
</span> </span>
); );
@ -154,7 +160,7 @@ const indicatorLocations = {
export default definePlugin({ export default definePlugin({
name: "PlatformIndicators", name: "PlatformIndicators",
description: "Adds platform indicators (Desktop, Mobile, Web...) to users", description: "Adds platform indicators (Desktop, Mobile, Web...) to users",
authors: [Devs.kemo, Devs.TheSun, Devs.Nuckyz], authors: [Devs.kemo, Devs.TheSun, Devs.Nuckyz, Devs.Ven],
dependencies: ["MessageDecorationsAPI", "MemberListDecoratorsAPI"], dependencies: ["MessageDecorationsAPI", "MemberListDecoratorsAPI"],
start() { start() {

View File

@ -17,6 +17,8 @@
*/ */
import { addContextMenuPatch, findGroupChildrenByChildId, NavContextMenuPatchCallback, removeContextMenuPatch } from "@api/ContextMenu"; import { addContextMenuPatch, findGroupChildrenByChildId, NavContextMenuPatchCallback, removeContextMenuPatch } from "@api/ContextMenu";
import { Flex } from "@components/Flex";
import { OpenExternalIcon } from "@components/Icons";
import { Devs } from "@utils/constants"; import { Devs } from "@utils/constants";
import definePlugin from "@utils/types"; import definePlugin from "@utils/types";
import { Menu } from "@webpack/common"; import { Menu } from "@webpack/common";
@ -28,7 +30,7 @@ const Engines = {
IQDB: "https://iqdb.org/?url=", IQDB: "https://iqdb.org/?url=",
TinEye: "https://www.tineye.com/search?url=", TinEye: "https://www.tineye.com/search?url=",
ImgOps: "https://imgops.com/start?url=" ImgOps: "https://imgops.com/start?url="
}; } as const;
function search(src: string, engine: string) { function search(src: string, engine: string) {
open(engine + encodeURIComponent(src), "_blank"); open(engine + encodeURIComponent(src), "_blank");
@ -50,13 +52,28 @@ const imageContextMenuPatch: NavContextMenuPatchCallback = (children, props) =>
key="search-image" key="search-image"
id="search-image" id="search-image"
> >
{Object.keys(Engines).map(engine => { {Object.keys(Engines).map((engine, i) => {
const key = "search-image-" + engine; const key = "search-image-" + engine;
return ( return (
<Menu.MenuItem <Menu.MenuItem
key={key} key={key}
id={key} id={key}
label={engine} label={
<Flex style={{ alignItems: "center", gap: "0.5em" }}>
<img
style={{
borderRadius: i >= 3 // Do not round Google, Yandex & SauceNAO
? "50%"
: void 0
}}
aria-hidden="true"
height={16}
width={16}
src={new URL("/favicon.ico", Engines[engine]).toString().replace("lens.", "")}
/>
{engine}
</Flex>
}
action={() => search(src, Engines[engine])} action={() => search(src, Engines[engine])}
/> />
); );
@ -64,7 +81,12 @@ const imageContextMenuPatch: NavContextMenuPatchCallback = (children, props) =>
<Menu.MenuItem <Menu.MenuItem
key="search-image-all" key="search-image-all"
id="search-image-all" id="search-image-all"
label="All" label={
<Flex style={{ alignItems: "center", gap: "0.5em" }}>
<OpenExternalIcon height={16} width={16} />
All
</Flex>
}
action={() => Object.values(Engines).forEach(e => search(src, e))} action={() => Object.values(Engines).forEach(e => search(src, e))}
/> />
</Menu.MenuItem> </Menu.MenuItem>
@ -76,6 +98,8 @@ export default definePlugin({
name: "ReverseImageSearch", name: "ReverseImageSearch",
description: "Adds ImageSearch to image context menus", description: "Adds ImageSearch to image context menus",
authors: [Devs.Ven, Devs.Nuckyz], authors: [Devs.Ven, Devs.Nuckyz],
tags: ["ImageUtilities"],
patches: [ patches: [
{ {
find: ".Messages.MESSAGE_ACTIONS_MENU_LABEL", find: ".Messages.MESSAGE_ACTIONS_MENU_LABEL",

View File

@ -44,20 +44,19 @@ export function authorize(callback?: any) {
{...props} {...props}
scopes={["identify"]} scopes={["identify"]}
responseType="code" responseType="code"
redirectUri="https://manti.vendicated.dev/URauth" redirectUri="https://manti.vendicated.dev/api/reviewdb/auth"
permissions={0n} permissions={0n}
clientId="915703782174752809" clientId="915703782174752809"
cancelCompletesFlow={false} cancelCompletesFlow={false}
callback={async (u: string) => { callback={async (u: string) => {
try { try {
const url = new URL(u); const url = new URL(u);
url.searchParams.append("returnType", "json");
url.searchParams.append("clientMod", "vencord"); url.searchParams.append("clientMod", "vencord");
const res = await fetch(url, { const res = await fetch(url, {
headers: new Headers({ Accept: "application/json" }) headers: new Headers({ Accept: "application/json" })
}); });
const { token, status } = await res.json(); const { token, success } = await res.json();
if (status === 0) { if (success) {
Settings.plugins.ReviewDB.token = token; Settings.plugins.ReviewDB.token = token;
showToast("Successfully logged in!"); showToast("Successfully logged in!");
callback?.(); callback?.();
@ -65,7 +64,7 @@ export function authorize(callback?: any) {
showToast("An Error occurred while logging in."); showToast("An Error occurred while logging in.");
} }
} catch (e) { } catch (e) {
new Logger("ReviewDB").error("Failed to authorise", e); new Logger("ReviewDB").error("Failed to authorize", e);
} }
}} }}
/> />
@ -86,5 +85,5 @@ export function showToast(text: string) {
export const sleep = (ms: number) => new Promise(r => setTimeout(r, ms)); export const sleep = (ms: number) => new Promise(r => setTimeout(r, ms));
export function canDeleteReview(review: Review, userId: string) { export function canDeleteReview(review: Review, userId: string) {
if (review.sender.discordID === userId || Settings.plugins.ReviewDB.userType === UserType.Admin) return true; if (review.sender.discordID === userId || Settings.plugins.ReviewDB.user?.type === UserType.Admin) return true;
} }

View File

@ -34,19 +34,17 @@ export default LazyComponent(() => {
const [ const [
{ cozyMessage, buttons, message, groupStart }, { cozyMessage, buttons, message, groupStart },
{ container, isHeader }, { container, isHeader },
{ avatar, clickable, username, messageContent, wrapper, cozy, timestampInline, timestamp }, { avatar, clickable, username, messageContent, wrapper, cozy },
{ contents },
buttonClasses, buttonClasses,
{ defaultColor }
] = findBulk( ] = findBulk(
p("cozyMessage"), p("cozyMessage"),
p("container", "isHeader"), p("container", "isHeader"),
p("avatar", "zalgo"), p("avatar", "zalgo"),
p("contents"),
p("button", "wrapper", "selected"), p("button", "wrapper", "selected"),
p("defaultColor")
); );
const dateFormat = new Intl.DateTimeFormat();
return function ReviewComponent({ review, refetch }: { review: Review; refetch(): void; }) { return function ReviewComponent({ review, refetch }: { review: Review; refetch(): void; }) {
function openModal() { function openModal() {
openUserProfileModal(review.sender.discordID); openUserProfileModal(review.sender.discordID);
@ -89,7 +87,7 @@ export default LazyComponent(() => {
} }
}> }>
<div className={contents} style={{ paddingLeft: "0px" }}> <div>
<img <img
className={classes(avatar, clickable)} className={classes(avatar, clickable)}
onClick={openModal} onClick={openModal}
@ -107,16 +105,14 @@ export default LazyComponent(() => {
{ {
!Settings.plugins.ReviewDB.hideTimestamps && ( !Settings.plugins.ReviewDB.hideTimestamps && (
<Timestamp <Timestamp timestamp={moment(review.timestamp * 1000)} >
timestamp={moment(review.timestamp * 1000)} {dateFormat.format(review.timestamp * 1000)}
compact={true} </Timestamp>)
/>
)
} }
<p <p
className={classes(messageContent, defaultColor)} className={classes(messageContent)}
style={{ fontSize: 15, marginTop: 4 }} style={{ fontSize: 15, marginTop: 4, color: "var(--text-normal)" }}
> >
{review.comment} {review.comment}
</p> </p>

View File

@ -19,7 +19,7 @@
import { Settings } from "@api/Settings"; import { Settings } from "@api/Settings";
import { classes } from "@utils/misc"; import { classes } from "@utils/misc";
import { useAwaiter } from "@utils/react"; import { useAwaiter } from "@utils/react";
import { findLazy } from "@webpack"; import { findByPropsLazy } from "@webpack";
import { Forms, React, Text, UserStore } from "@webpack/common"; import { Forms, React, Text, UserStore } from "@webpack/common";
import type { KeyboardEvent } from "react"; import type { KeyboardEvent } from "react";
@ -27,7 +27,7 @@ import { addReview, getReviews } from "../Utils/ReviewDBAPI";
import { authorize, showToast } from "../Utils/Utils"; import { authorize, showToast } from "../Utils/Utils";
import ReviewComponent from "./ReviewComponent"; import ReviewComponent from "./ReviewComponent";
const Classes = findLazy(m => typeof m.textarea === "string"); const Classes = findByPropsLazy("inputDefault", "editable");
export default function ReviewsView({ userId }: { userId: string; }) { export default function ReviewsView({ userId }: { userId: string; }) {
const { token } = Settings.plugins.ReviewDB; const { token } = Settings.plugins.ReviewDB;
@ -65,7 +65,7 @@ export default function ReviewsView({ userId }: { userId: string; }) {
tag="h2" tag="h2"
variant="eyebrow" variant="eyebrow"
style={{ style={{
marginBottom: "12px", marginBottom: "8px",
color: "var(--header-primary)" color: "var(--header-primary)"
}} }}
> >
@ -79,13 +79,17 @@ export default function ReviewsView({ userId }: { userId: string; }) {
/> />
)} )}
{reviews?.length === 0 && ( {reviews?.length === 0 && (
<Forms.FormText style={{ padding: "12px", paddingTop: "0px", paddingLeft: "4px", fontWeight: "bold", fontStyle: "italic" }}> <Forms.FormText style={{ paddingRight: "12px", paddingTop: "0px", paddingLeft: "0px", paddingBottom: "4px", fontWeight: "bold", fontStyle: "italic" }}>
Looks like nobody reviewed this user yet. You could be the first! Looks like nobody reviewed this user yet. You could be the first!
</Forms.FormText> </Forms.FormText>
)} )}
<textarea <textarea
className={classes(Classes.textarea.replace("textarea", ""), "enter-comment")} className={classes(Classes.inputDefault, "enter-comment")}
// this produces something like '-_59yqs ...' but since no class exists with that name its fine onKeyDownCapture={e => {
if (e.key === "Enter") {
e.preventDefault(); // prevent newlines
}
}}
placeholder={ placeholder={
token token
? (reviews?.some(r => r.sender.discordID === UserStore.getCurrentUser().id) ? (reviews?.some(r => r.sender.discordID === UserStore.getCurrentUser().id)
@ -106,6 +110,9 @@ export default function ReviewsView({ userId }: { userId: string; }) {
resize: "none", resize: "none",
marginBottom: "12px", marginBottom: "12px",
overflow: "hidden", overflow: "hidden",
background: "transparent",
border: "1px solid var(--profile-message-input-border-color)",
fontSize: "14px",
}} }}
/> />
</div> </div>

View File

@ -22,7 +22,23 @@ export const enum UserType {
Admin = 1 Admin = 1
} }
export interface ReviewDBUser { export interface BanInfo {
lastReviewID: number, id: string;
type: UserType; discordID: string;
reviewID: number;
reviewContent: string;
banEndDate: string;
}
export interface ReviewDBUser {
ID: number
discordID: string
username: string
profilePhoto: string
clientMod: string
warningCount: number
badges: any[]
banInfo: BanInfo | null
lastReviewID: number
type: UserType
} }

View File

@ -22,10 +22,11 @@ import { Settings } from "@api/Settings";
import ErrorBoundary from "@components/ErrorBoundary"; import ErrorBoundary from "@components/ErrorBoundary";
import { Devs } from "@utils/constants"; import { Devs } from "@utils/constants";
import definePlugin, { OptionType } from "@utils/types"; import definePlugin, { OptionType } from "@utils/types";
import { Button } from "@webpack/common"; import { Alerts, Button } from "@webpack/common";
import { User } from "discord-types/general"; import { User } from "discord-types/general";
import ReviewsView from "./components/ReviewsView"; import ReviewsView from "./components/ReviewsView";
import { UserType } from "./entities/User";
import { getCurrentUserInfo } from "./Utils/ReviewDBAPI"; import { getCurrentUserInfo } from "./Utils/ReviewDBAPI";
import { authorize, showToast } from "./Utils/Utils"; import { authorize, showToast } from "./Utils/Utils";
@ -47,10 +48,10 @@ export default definePlugin({
options: { options: {
authorize: { authorize: {
type: OptionType.COMPONENT, type: OptionType.COMPONENT,
description: "Authorise with ReviewDB", description: "Authorize with ReviewDB",
component: () => ( component: () => (
<Button onClick={authorize}> <Button onClick={authorize}>
Authorise with ReviewDB Authorize with ReviewDB
</Button> </Button>
) )
}, },
@ -68,7 +69,29 @@ export default definePlugin({
type: OptionType.BOOLEAN, type: OptionType.BOOLEAN,
description: "Hide timestamps on reviews", description: "Hide timestamps on reviews",
default: false, default: false,
} },
website: {
type: OptionType.COMPONENT,
description: "ReviewDB website",
component: () => (
<Button onClick={() => {
window.open("https://reviewdb.mantikafasi.dev");
}}>
ReviewDB website
</Button>
)
},
supportServer: {
type: OptionType.COMPONENT,
description: "ReviewDB Support Server",
component: () => (
<Button onClick={() => {
window.open("https://discord.gg/eWPBSbvznt");
}}>
ReviewDB Support Server
</Button>
)
},
}, },
async start() { async start() {
@ -82,7 +105,34 @@ export default definePlugin({
if (user.lastReviewID !== 0) if (user.lastReviewID !== 0)
showToast("You have new reviews on your profile!"); showToast("You have new reviews on your profile!");
} }
settings.userType = user.type;
if (user.banInfo) {
const endDate = new Date(user.banInfo.banEndDate);
if (endDate > new Date() && (settings.user?.banInfo?.banEndDate ?? 0) < endDate) {
Alerts.show({
title: "You have been banned from ReviewDB",
body: <>
<p>
You are banned from ReviewDB {(user.type === UserType.Banned) ? "permanently" : "until " + endDate.toLocaleString()}
</p>
<p>
Offending Review: {user.banInfo.reviewContent}
</p>
<p>
Continued offenses will result in a permanent ban.
</p>
</>,
cancelText: "Appeal",
confirmText: "Ok",
onCancel: () => {
window.open("https://forms.gle/Thj3rDYaMdKoMMuq6");
}
});
}
}
settings.user = user;
}, 4000); }, 4000);
}, },

View File

@ -18,17 +18,13 @@
import { addContextMenuPatch } from "@api/ContextMenu"; import { addContextMenuPatch } from "@api/ContextMenu";
import { Settings } from "@api/Settings"; import { Settings } from "@api/Settings";
import PatchHelper from "@components/PatchHelper";
import { Devs } from "@utils/constants"; import { Devs } from "@utils/constants";
import { Logger } from "@utils/Logger"; import { Logger } from "@utils/Logger";
import { LazyComponent } from "@utils/react";
import definePlugin, { OptionType } from "@utils/types"; import definePlugin, { OptionType } from "@utils/types";
import { SettingsRouter } from "@webpack/common"; import { React, SettingsRouter } from "@webpack/common";
import gitHash from "~git-hash"; import gitHash from "~git-hash";
const SettingsComponent = LazyComponent(() => require("../components/VencordSettings").default);
export default definePlugin({ export default definePlugin({
name: "Settings", name: "Settings",
description: "Adds Settings UI and debug info", description: "Adds Settings UI and debug info",
@ -95,37 +91,37 @@ export default definePlugin({
{ {
section: "VencordSettings", section: "VencordSettings",
label: "Vencord", label: "Vencord",
element: () => <SettingsComponent tab="VencordSettings" /> element: require("@components/VencordSettings/VencordTab").default
}, },
{ {
section: "VencordPlugins", section: "VencordPlugins",
label: "Plugins", label: "Plugins",
element: () => <SettingsComponent tab="VencordPlugins" />, element: require("@components/VencordSettings/PluginsTab").default,
}, },
{ {
section: "VencordThemes", section: "VencordThemes",
label: "Themes", label: "Themes",
element: () => <SettingsComponent tab="VencordThemes" />, element: require("@components/VencordSettings/ThemesTab").default,
}, },
!IS_WEB && { !IS_WEB && {
section: "VencordUpdater", section: "VencordUpdater",
label: "Updater", label: "Updater",
element: () => <SettingsComponent tab="VencordUpdater" />, element: require("@components/VencordSettings/UpdaterTab").default,
}, },
{ {
section: "VencordCloud", section: "VencordCloud",
label: "Cloud", label: "Cloud",
element: () => <SettingsComponent tab="VencordCloud" />, element: require("@components/VencordSettings/CloudTab").default,
}, },
{ {
section: "VencordSettingsSync", section: "VencordSettingsSync",
label: "Backup & Restore", label: "Backup & Restore",
element: () => <SettingsComponent tab="VencordSettingsSync" />, element: require("@components/VencordSettings/BackupAndRestoreTab").default,
}, },
IS_DEV && { IS_DEV && {
section: "VencordPatchHelper", section: "VencordPatchHelper",
label: "Patch Helper", label: "Patch Helper",
element: PatchHelper!, element: require("@components/VencordSettings/PatchHelperTab").default,
}, },
IS_VENCORD_DESKTOP && { IS_VENCORD_DESKTOP && {
section: "VencordDesktop", section: "VencordDesktop",

View File

@ -371,7 +371,7 @@ export default definePlugin({
}, },
{ {
// Remove the open chat button for the HiddenChannelLockScreen // Remove the open chat button for the HiddenChannelLockScreen
match: /"recents".+?null,(?=.{0,120}?channelId:(\i)\.id)/, match: /"recents".+?null,(?=.+?channelId:(\i)\.id,showRequestToSpeakSidebar)/,
replace: (m, channel) => `${m}!$self.isHiddenChannel(${channel})&&` replace: (m, channel) => `${m}!$self.isHiddenChannel(${channel})&&`
} }
], ],

View File

@ -33,6 +33,11 @@ const settings = definePluginSettings({
onChange(newValue: boolean) { onChange(newValue: boolean) {
if (newValue === false) lastState = false; if (newValue === false) lastState = false;
} }
},
autoDisable: {
type: OptionType.BOOLEAN,
description: "Automatically disable the silent message toggle again after sending one",
default: true
} }
}); });
@ -51,7 +56,7 @@ function SilentMessageToggle(chatBoxProps: {
React.useEffect(() => { React.useEffect(() => {
const listener: SendListener = (_, message) => { const listener: SendListener = (_, message) => {
if (enabled) { if (enabled) {
setEnabledValue(false); if (settings.store.autoDisable) setEnabledValue(false);
if (!message.content.startsWith("@silent ")) message.content = "@silent " + message.content; if (!message.content.startsWith("@silent ")) message.content = "@silent " + message.content;
} }
}; };
@ -96,7 +101,7 @@ function SilentMessageToggle(chatBoxProps: {
export default definePlugin({ export default definePlugin({
name: "SilentMessageToggle", name: "SilentMessageToggle",
authors: [Devs.Nuckyz], authors: [Devs.Nuckyz, Devs.CatNoir],
description: "Adds a button to the chat bar to toggle sending a silent message.", description: "Adds a button to the chat bar to toggle sending a silent message.",
dependencies: ["MessageEventsAPI"], dependencies: ["MessageEventsAPI"],

View File

@ -20,6 +20,7 @@ import "./spotifyStyles.css";
import ErrorBoundary from "@components/ErrorBoundary"; import ErrorBoundary from "@components/ErrorBoundary";
import { Flex } from "@components/Flex"; import { Flex } from "@components/Flex";
import { ImageIcon, LinkIcon, OpenExternalIcon } from "@components/Icons";
import { Link } from "@components/Link"; import { Link } from "@components/Link";
import { debounce } from "@utils/debounce"; import { debounce } from "@utils/debounce";
import { classes, copyWithToast } from "@utils/misc"; import { classes, copyWithToast } from "@utils/misc";
@ -88,12 +89,14 @@ function CopyContextMenu({ name, path }: { name: string; path: string; }) {
id={copyId} id={copyId}
label={`Copy ${name} Link`} label={`Copy ${name} Link`}
action={() => copyWithToast("https://open.spotify.com" + path)} action={() => copyWithToast("https://open.spotify.com" + path)}
icon={LinkIcon}
/> />
<Menu.MenuItem <Menu.MenuItem
key={openId} key={openId}
id={openId} id={openId}
label={`Open ${name} in Spotify`} label={`Open ${name} in Spotify`}
action={() => SpotifyStore.openExternal(path)} action={() => SpotifyStore.openExternal(path)}
icon={OpenExternalIcon}
/> />
</Menu.Menu> </Menu.Menu>
); );
@ -221,6 +224,7 @@ function AlbumContextMenu({ track }: { track: Track; }) {
id="open-album" id="open-album"
label="Open Album" label="Open Album"
action={() => SpotifyStore.openExternal(`/album/${track.album.id}`)} action={() => SpotifyStore.openExternal(`/album/${track.album.id}`)}
icon={OpenExternalIcon}
/> />
<Menu.MenuItem <Menu.MenuItem
key="view-cover" key="view-cover"
@ -228,6 +232,7 @@ function AlbumContextMenu({ track }: { track: Track; }) {
label="View Album Cover" label="View Album Cover"
// trolley // trolley
action={() => (Vencord.Plugins.plugins.ViewIcons as any).openImage(track.album.image.url)} action={() => (Vencord.Plugins.plugins.ViewIcons as any).openImage(track.album.image.url)}
icon={ImageIcon}
/> />
<Menu.MenuControlItem <Menu.MenuControlItem
id="spotify-volume" id="spotify-volume"

View File

@ -159,7 +159,7 @@ function TextReplace({ title, rulesArray, rulesKey, update }: TextReplaceProps)
<Input <Input
placeholder="Replace" placeholder="Replace"
initialValue={rule.replace} initialValue={rule.replace}
onChange={e => onChange(e.replaceAll("\\n", "\n"), index, "replace")} onChange={e => onChange(e, index, "replace")}
/> />
<Input <Input
placeholder="Only if includes" placeholder="Only if includes"
@ -220,7 +220,7 @@ function applyRules(content: string): string {
if (!rule.find || !rule.replace) continue; if (!rule.find || !rule.replace) continue;
if (rule.onlyIfIncludes && !content.includes(rule.onlyIfIncludes)) continue; if (rule.onlyIfIncludes && !content.includes(rule.onlyIfIncludes)) continue;
content = content.replaceAll(rule.find, rule.replace); content = content.replaceAll(rule.find, rule.replace.replaceAll("\\n", "\n"));
} }
} }
@ -231,7 +231,7 @@ function applyRules(content: string): string {
try { try {
const regex = stringToRegex(rule.find); const regex = stringToRegex(rule.find);
content = content.replace(regex, rule.replace); content = content.replace(regex, rule.replace.replaceAll("\\n", "\n"));
} catch (e) { } catch (e) {
new Logger("TextReplace").error(`Invalid regex: ${rule.find}`); new Logger("TextReplace").error(`Invalid regex: ${rule.find}`);
} }

View File

@ -43,6 +43,8 @@ export function TranslateChatBarIcon({ slateProps }: { slateProps: { type: { ana
if (slateProps.type.analyticsName !== "normal") if (slateProps.type.analyticsName !== "normal")
return null; return null;
const toggle = () => settings.store.autoTranslate = !autoTranslate;
return ( return (
<Tooltip text="Open Translate Modal"> <Tooltip text="Open Translate Modal">
{({ onMouseEnter, onMouseLeave }) => ( {({ onMouseEnter, onMouseLeave }) => (
@ -55,11 +57,14 @@ export function TranslateChatBarIcon({ slateProps }: { slateProps: { type: { ana
onMouseEnter={onMouseEnter} onMouseEnter={onMouseEnter}
onMouseLeave={onMouseLeave} onMouseLeave={onMouseLeave}
innerClassName={ButtonWrapperClasses.button} innerClassName={ButtonWrapperClasses.button}
onClick={() => onClick={e => {
if (e.shiftKey) return toggle();
openModal(props => ( openModal(props => (
<TranslateModal rootProps={props} /> <TranslateModal rootProps={props} />
)) ));
} }}
onContextMenu={() => toggle()}
style={{ padding: "0 4px" }} style={{ padding: "0 4px" }}
> >
<div className={ButtonWrapperClasses.buttonWrapper}> <div className={ButtonWrapperClasses.buttonWrapper}>

View File

@ -46,7 +46,7 @@ export const settings = definePluginSettings({
}, },
autoTranslate: { autoTranslate: {
type: OptionType.BOOLEAN, type: OptionType.BOOLEAN,
description: "Automatically translate your messages before sending", description: "Automatically translate your messages before sending. You can also shift/right click the translate button to toggle this",
default: false default: false
} }
}); });

View File

@ -47,8 +47,8 @@ const settings = definePluginSettings({
export default definePlugin({ export default definePlugin({
name: "USRBG", name: "USRBG",
description: "USRBG is a community maintained database of Discord banners, allowing anyone to get a banner without requiring Nitro", description: "Displays user banners from USRBG, allowing anyone to get a banner without Nitro",
authors: [Devs.AutumnVN, Devs.pylix], authors: [Devs.AutumnVN, Devs.pylix, Devs.TheKodeToad],
settings, settings,
patches: [ patches: [
{ {
@ -61,6 +61,10 @@ export default definePlugin({
{ {
match: /(\i)\.bannerSrc,/, match: /(\i)\.bannerSrc,/,
replace: "$self.useBannerHook($1)," replace: "$self.useBannerHook($1),"
},
{
match: /\?\(0,\i\.jsx\)\(\i,{type:\i,shown/,
replace: "&&$self.shouldShowBadge(arguments[0])$&"
} }
] ]
}, },
@ -104,6 +108,10 @@ export default definePlugin({
if (data[userId]) return 2; if (data[userId]) return 2;
}, },
shouldShowBadge({ displayProfile, user }: any) {
return displayProfile?.banner && (!data[user.id] || settings.store.nitroFirst);
},
async start() { async start() {
enableStyle(style); enableStyle(style);

View File

@ -116,6 +116,7 @@ export default definePlugin({
name: "ValidUser", name: "ValidUser",
description: "Fix mentions for unknown users showing up as '<@343383572805058560>' (hover over a mention to fix it)", description: "Fix mentions for unknown users showing up as '<@343383572805058560>' (hover over a mention to fix it)",
authors: [Devs.Ven], authors: [Devs.Ven],
tags: ["MentionCacheFix"],
patches: [{ patches: [{
find: 'className:"mention"', find: 'className:"mention"',

View File

@ -18,6 +18,7 @@
import { addContextMenuPatch, NavContextMenuPatchCallback, removeContextMenuPatch } from "@api/ContextMenu"; import { addContextMenuPatch, NavContextMenuPatchCallback, removeContextMenuPatch } from "@api/ContextMenu";
import { definePluginSettings } from "@api/Settings"; import { definePluginSettings } from "@api/Settings";
import { ImageIcon } from "@components/Icons";
import { Devs } from "@utils/constants"; import { Devs } from "@utils/constants";
import { ModalRoot, ModalSize, openModal } from "@utils/modal"; import { ModalRoot, ModalSize, openModal } from "@utils/modal";
import { LazyComponent } from "@utils/react"; import { LazyComponent } from "@utils/react";
@ -84,12 +85,13 @@ function openImage(url: string) {
const UserContext: NavContextMenuPatchCallback = (children, { user, guildId }: UserContextProps) => () => { const UserContext: NavContextMenuPatchCallback = (children, { user, guildId }: UserContextProps) => () => {
const memberAvatar = GuildMemberStore.getMember(guildId!, user.id)?.avatar || null; const memberAvatar = GuildMemberStore.getMember(guildId!, user.id)?.avatar || null;
children.splice(1, 0, ( children.splice(-1, 0, (
<Menu.MenuGroup> <Menu.MenuGroup>
<Menu.MenuItem <Menu.MenuItem
id="view-avatar" id="view-avatar"
label="View Avatar" label="View Avatar"
action={() => openImage(BannerStore.getUserAvatarURL(user, true, 512))} action={() => openImage(BannerStore.getUserAvatarURL(user, true, 512))}
icon={ImageIcon}
/> />
{memberAvatar && ( {memberAvatar && (
<Menu.MenuItem <Menu.MenuItem
@ -100,6 +102,7 @@ const UserContext: NavContextMenuPatchCallback = (children, { user, guildId }: U
avatar: memberAvatar, avatar: memberAvatar,
guildId guildId
}, true))} }, true))}
icon={ImageIcon}
/> />
)} )}
</Menu.MenuGroup> </Menu.MenuGroup>
@ -109,13 +112,7 @@ const UserContext: NavContextMenuPatchCallback = (children, { user, guildId }: U
const GuildContext: NavContextMenuPatchCallback = (children, { guild: { id, icon, banner } }: GuildContextProps) => () => { const GuildContext: NavContextMenuPatchCallback = (children, { guild: { id, icon, banner } }: GuildContextProps) => () => {
if (!banner && !icon) return; if (!banner && !icon) return;
// before copy id (if it exists) children.splice(-1, 0, (
const idx = children.length +
children[children.length - 1]?.props?.children?.props?.id === "devmode-copy-id"
? -2
: -1;
children.splice(idx, 0, (
<Menu.MenuGroup> <Menu.MenuGroup>
{icon ? ( {icon ? (
<Menu.MenuItem <Menu.MenuItem
@ -129,6 +126,7 @@ const GuildContext: NavContextMenuPatchCallback = (children, { guild: { id, icon
canAnimate: true canAnimate: true
})) }))
} }
icon={ImageIcon}
/> />
) : null} ) : null}
{banner ? ( {banner ? (
@ -141,6 +139,7 @@ const GuildContext: NavContextMenuPatchCallback = (children, { guild: { id, icon
banner, banner,
}, true)) }, true))
} }
icon={ImageIcon}
/> />
) : null} ) : null}
</Menu.MenuGroup> </Menu.MenuGroup>
@ -151,6 +150,7 @@ export default definePlugin({
name: "ViewIcons", name: "ViewIcons",
authors: [Devs.Ven, Devs.TheKodeToad, Devs.Nuckyz], authors: [Devs.Ven, Devs.TheKodeToad, Devs.Nuckyz],
description: "Makes avatars and banners in user profiles clickable, and adds View Icon/Banner entries in the user and server context menu", description: "Makes avatars and banners in user profiles clickable, and adds View Icon/Banner entries in the user and server context menu",
tags: ["ImageUtilities"],
settings, settings,

View File

@ -286,5 +286,13 @@ export const Devs = /* #__PURE__*/ Object.freeze({
carince: { carince: {
name: "carince", name: "carince",
id: 818323528755314698n id: 818323528755314698n
} },
CatNoir: {
name: "CatNoir",
id: 260371016348336128n
},
outfoxxed: {
name: "outfoxxed",
id: 837425748435796060n
},
}); });

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 type { ComponentType, CSSProperties, MouseEvent, PropsWithChildren, UIEvent } from "react"; import type { ComponentType, CSSProperties, MouseEvent, PropsWithChildren, ReactNode, UIEvent } from "react";
type RC<C> = ComponentType<PropsWithChildren<C & Record<string, any>>>; type RC<C> = ComponentType<PropsWithChildren<C & Record<string, any>>>;
@ -35,11 +35,12 @@ export interface Menu {
}>; }>;
MenuItem: RC<{ MenuItem: RC<{
id: string; id: string;
label: string; label: ReactNode;
action?(e: MouseEvent): void; action?(e: MouseEvent): void;
icon?: ComponentType<any>;
color?: string; color?: string;
render?: ComponentType; render?: ComponentType<any>;
onChildrenScroll?: Function; onChildrenScroll?: Function;
childRowHeight?: number; childRowHeight?: number;
listClassName?: string; listClassName?: string;

View File

@ -85,6 +85,51 @@ export type RestAPI = Record<"delete" | "get" | "patch" | "post" | "put", (data:
getAPIBaseURL(withVersion?: boolean): string; getAPIBaseURL(withVersion?: boolean): string;
}; };
export type Permissions = "CREATE_INSTANT_INVITE"
| "KICK_MEMBERS"
| "BAN_MEMBERS"
| "ADMINISTRATOR"
| "MANAGE_CHANNELS"
| "MANAGE_GUILD"
| "CHANGE_NICKNAME"
| "MANAGE_NICKNAMES"
| "MANAGE_ROLES"
| "MANAGE_WEBHOOKS"
| "MANAGE_GUILD_EXPRESSIONS"
| "VIEW_AUDIT_LOG"
| "VIEW_CHANNEL"
| "VIEW_GUILD_ANALYTICS"
| "VIEW_CREATOR_MONETIZATION_ANALYTICS"
| "MODERATE_MEMBERS"
| "SEND_MESSAGES"
| "SEND_TTS_MESSAGES"
| "MANAGE_MESSAGES"
| "EMBED_LINKS"
| "ATTACH_FILES"
| "READ_MESSAGE_HISTORY"
| "MENTION_EVERYONE"
| "USE_EXTERNAL_EMOJIS"
| "ADD_REACTIONS"
| "USE_APPLICATION_COMMANDS"
| "MANAGE_THREADS"
| "CREATE_PUBLIC_THREADS"
| "CREATE_PRIVATE_THREADS"
| "USE_EXTERNAL_STICKERS"
| "SEND_MESSAGES_IN_THREADS"
| "CONNECT"
| "SPEAK"
| "MUTE_MEMBERS"
| "DEAFEN_MEMBERS"
| "MOVE_MEMBERS"
| "USE_VAD"
| "PRIORITY_SPEAKER"
| "STREAM"
| "USE_EMBEDDED_ACTIVITIES"
| "REQUEST_TO_SPEAK"
| "MANAGE_EVENTS";
export type PermissionsBits = Record<Permissions, bigint>;
export interface Locale { export interface Locale {
name: string; name: string;
value: string; value: string;

View File

@ -114,3 +114,5 @@ waitFor("parseTopic", m => Parser = m);
export let SettingsRouter: any; export let SettingsRouter: any;
waitFor(["open", "saveAccountChanges"], m => SettingsRouter = m); waitFor(["open", "saveAccountChanges"], m => SettingsRouter = m);
export const PermissionsBits: t.PermissionsBits = findLazy(m => typeof m.ADMINISTRATOR === "bigint");