Compare commits

..

87 Commits

Author SHA1 Message Date
V
a94787a9f3 Bump to 1.2.5 2023-05-23 03:50:21 +02:00
V
368d2bcdbb DiscordUtils: Add sendMessage 2023-05-23 03:47:09 +02:00
UwU
bc46bfa467 New plugin : Party mode 🎉 (#1161)
Co-authored-by: ArjixWasTaken <53124886+ArjixWasTaken@users.noreply.github.com>
Co-authored-by: V <vendicated@riseup.net>
2023-05-23 03:32:27 +02:00
V
dab48288a8 TypingTweaks: Fix type error 2023-05-23 03:22:48 +02:00
alexia
9aef97c771 fix(TypingTweaks): use global displayName over username (#1165)
Co-authored-by: V <vendicated@riseup.net>
2023-05-23 03:19:26 +02:00
PandaNinjas
9d62dec6b9 Uwufy: Add option to uwufy all messages (#1036)
Co-authored-by: V <vendicated@riseup.net>
2023-05-23 03:13:21 +02:00
V
6bf6583e7d FakeNitro: Fix unavailable emotes; Discord Stickers are now free (#1184)
Co-authored-by: Nuckyz <61953774+Nuckyz@users.noreply.github.com>
2023-05-23 03:02:48 +02:00
Nuckyz
5219fb700f PermViewer: Add ability to change sort order; Properly center (#1182) 2023-05-23 02:22:25 +02:00
V
184c03b28e PluginModal: Anonymise authors (#1176) 2023-05-23 01:55:39 +02:00
Nuckyz
ec091a7959 Fix SHC broken patches; Sort PermViewer channel overwrites roles (#1166) 2023-05-20 02:24:56 +02:00
V
89a6c575c9 lastfm: Fix discord application 2023-05-18 05:11:06 +02:00
V
60325c6aa5 bump to 1.2.4 2023-05-17 04:42:50 +02:00
Hunter
c2a1c4cbf6 Urban Dictionary: better embed (#1127)
Co-authored-by: V <vendicated@riseup.net>
2023-05-17 04:40:40 +02:00
Syncx
1d6b78f6c6 feat(plugin): FavoriteEmojiFirst (#1110)
Co-authored-by: V <vendicated@riseup.net>
2023-05-17 04:38:15 +02:00
Sammy
341151a718 feat(InvisibleChat): use discords embed api (#1162) 2023-05-17 04:38:01 +02:00
Nuckyz
f6fd7cf37a PlatformIndicators: make mobile icon match Discord's (#1160) 2023-05-17 04:37:47 +02:00
Kay Alizer
d53476a32a VcNarrator: Add 'Narrate Self' option (#1120)
* Add 'Narrate Self' option

if anyone wishes to hear their own name on join this should work

* Apply suggestions from code review

Co-authored-by: V <vendicated@riseup.net>

* Update vcNarrator.tsx

---------

Co-authored-by: V <vendicated@riseup.net>
2023-05-16 19:23:10 +02:00
Animal
fc943b7778 emoteCloner: allow other characters in sticker names (#1140)
* allow spaces and other characters in cloning sticker names

* fix

* stickers have a different character limit
2023-05-16 19:22:46 +02:00
Nuckyz
3f2bcd2cab SHC: Permissions viewer integration (#475) 2023-05-16 17:15:56 +00:00
Nuckyz
235000cf41 Fix handleProtoChange erroring when userSettingsProto is undefined (#1150) 2023-05-16 14:53:17 +00:00
V
263884cbd8 PermViewer: Fix context menu for roleless users & muted channels (#1138)
Co-authored-by: V <vendicated@riseup.net>
Co-authored-by: Nuckyz <61953774+Nuckyz@users.noreply.github.com>
2023-05-16 00:19:20 +02:00
V
bb83c0b672 [skip ci] PronounDB: Do not add pronouns to automod messages 2023-05-15 18:20:34 +02:00
V
2815509c00 UserScript: Fix fetch().res.ok 2023-05-15 02:49:34 +02:00
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
V
a8b6aea26f bump to 1.2.1 2023-05-11 02:39:59 +02:00
V
e50c2fafa5 Settings > Plugins: Hide API plugins 2023-05-11 02:38:59 +02:00
V
6e3cafce42 Translate: Only add button in chat box 2023-05-11 02:35:06 +02:00
V
4d0a064425 WebContextMenus: Fix slate menu 2023-05-11 02:35:05 +02:00
V
d1ad6c47a7 Fix ServerListAPI 2023-05-11 02:35:05 +02:00
V
d5c35055f3 experiments: Add a warning card to experiments page (#1097) 2023-05-11 02:34:39 +02:00
V
cb385d1b28 New Plugin: Translate (#1089)
Co-authored-by: Nuckyz <61953774+Nuckyz@users.noreply.github.com>
2023-05-10 23:14:04 +02:00
V
195f1a032f ShowConnections: Add verified & copy/link icons in tooltip (#1092) 2023-05-10 23:13:47 +02:00
V
dfda9e7f84 New plugin: ValidUser (#1081) 2023-05-10 23:13:28 +02:00
Vendicated
0d5e2d0696 [skip ci] Refactor utils 2023-05-06 01:36:00 +02:00
Vendicated
2834bed518 MemberCount: Do not count offline group lol 2023-05-06 01:06:48 +02:00
Vendicated
0b2c3c834a MemberCount: Fix not properly updating on channel switch 2023-05-05 18:41:04 +02:00
AutumnVN
3a54a24c70 VencordToolbox: Change img icon to svg (#1059)
Co-authored-by: V <vendicated@riseup.net>
2023-05-05 16:41:01 +00:00
Vendicated
244d10dc9e [skip ci] Fix handleComponentFailed spam 2023-05-05 16:57:58 +02:00
Đỗ Văn Hoài Tuân
c25bc0ff4b USRBG: Add VoiceBackground (#1038)
Co-authored-by: V <vendicated@riseup.net>
2023-05-05 02:54:33 +02:00
Kode
22334663cf TextReplace: Test rules section (#1039) 2023-05-05 02:51:01 +02:00
Đỗ Văn Hoài Tuân
8813f81bde ShowConnections: Remove "(click to copy/open)" from tooltip (#1041) 2023-05-05 02:47:59 +02:00
Đỗ Văn Hoài Tuân
84371ed456 TextReplace: Fix Linebreak (#1057) 2023-05-05 02:47:31 +02:00
Nuckyz
8f61119b99 ShowAllMessageButtons plugin (#1029) 2023-05-05 02:47:26 +02:00
JSEverything
0a89d09727 style(Settings): Make the text about raw theme links bold (#1052) 2023-05-05 02:47:18 +02:00
Nuckyz
474932161f Fix FakeNitro Stickers (#1048) 2023-05-05 02:47:08 +02:00
Vendicated
bd95a25f4c TextReplace: Do not apply rules in #textreplace-rules channel 2023-05-02 04:39:27 +02:00
Vendicated
6a57ecc22b Delete FxTwitter & NoCanaryMessageLinks: Use TextReplace 2023-05-02 04:37:16 +02:00
Vendicated
0d665b7e0b Badge duplication glitch was too good to be true 2023-05-02 03:11:40 +02:00
Vendicated
d94b28fb8e Fix VencordToolbox 2023-05-02 02:57:25 +02:00
V
bc1d8694d4 new plugin: VencordToolbox (#998) 2023-05-02 02:55:38 +02:00
V
7bc1362cbd MessageEvents: Support sendMessage with attachments (#1023) 2023-05-02 02:55:21 +02:00
Vendicated
4dce836ff7 RelationshipNotifier: Fix false positives when using AccountSwitcher 2023-05-02 02:52:09 +02:00
Vendicated
9f534c0685 SupportHelper: Add OpenAsar info 2023-05-02 02:52:03 +02:00
V
c62d05e1b3 Refactor ipc to be strongly typed and hide impl details (#1018) 2023-05-02 02:50:51 +02:00
Nuckyz
6a1cb133cd Fix blank errors on plugin reports (#1021) 2023-05-01 07:26:27 +00:00
Vendicated
c6196dff81 [skip ci] PlatformIndicator: Fix 1px misalignment 2023-04-30 21:47:33 +02:00
Vendicated
acdb390302 [skip ci] Bump deps 2023-04-30 17:11:38 +02:00
Nuckyz
08d88b326d Fix Plugin Reporting false dependency errors and other stuff (#1017) 2023-04-30 13:34:38 +00:00
LordElias
a73858d131 UserVoiceShow: Fix lack of bottom padding for popout on current user and broken modal patch (#873) 2023-04-30 10:29:45 -03:00
Đỗ Văn Hoài Tuân
b0caa6f4db feat(plugin): TextReplace (#994)
Co-authored-by: Vendicated <vendicated@riseup.net>
2023-04-30 01:19:08 +00:00
Vendicated
168d4b4cd9 PlatformIndicators: Fix layout reflows - The trilogy 2023-04-30 02:07:57 +02:00
Vendicated
06cee75a56 PlatformIndicators: Fix layout reflows 2: Electric Boogaloo 2023-04-30 01:56:12 +02:00
183 changed files with 5162 additions and 1653 deletions

View File

@ -62,7 +62,7 @@
"indent": ["error", 4, { "SwitchCase": 1 }], "indent": ["error", 4, { "SwitchCase": 1 }],
"arrow-parens": ["error", "as-needed"], "arrow-parens": ["error", "as-needed"],
"eol-last": ["error", "always"], "eol-last": ["error", "always"],
"func-call-spacing": ["error", "never"], "@typescript-eslint/func-call-spacing": ["error", "never"],
"no-multi-spaces": "error", "no-multi-spaces": "error",
"no-trailing-spaces": "error", "no-trailing-spaces": "error",
"no-whitespace-before-property": "error", "no-whitespace-before-property": "error",

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

@ -16,20 +16,6 @@
* along with this program. If not, see <https://www.gnu.org/licenses/>. * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
function fetchOptions(url) {
return new Promise((resolve, reject) => {
const opt = {
method: "OPTIONS",
url: url,
};
opt.onload = resp => resolve(resp.responseHeaders);
opt.ontimeout = () => reject("fetch timeout");
opt.onerror = () => reject("fetch error");
opt.onabort = () => reject("fetch abort");
GM_xmlhttpRequest(opt);
});
}
function parseHeaders(headers) { function parseHeaders(headers) {
if (!headers) if (!headers)
return {}; return {};
@ -52,21 +38,6 @@ function parseHeaders(headers) {
return result; return result;
} }
// returns true if CORS permits request
async function checkCors(url, method) {
const headers = parseHeaders(await fetchOptions(url));
const origin = headers["access-control-allow-origin"];
if (origin !== "*" && origin !== window.location.origin) return false;
const methods = headers["access-control-allow-methods"]?.toLowerCase()
.split(",")
.map(s => s.trim());
if (methods && !methods.includes(method.toLowerCase())) return false;
return true;
}
function blobTo(to, blob) { function blobTo(to, blob) {
if (to === "arrayBuffer" && blob.arrayBuffer) return blob.arrayBuffer(); if (to === "arrayBuffer" && blob.arrayBuffer) return blob.arrayBuffer();
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
@ -80,9 +51,6 @@ function blobTo(to, blob) {
function GM_fetch(url, opt) { function GM_fetch(url, opt) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
checkCors(url, opt?.method || "GET")
.then(can => {
if (can) {
// https://www.tampermonkey.net/documentation.php?ext=dhdg#GM_xmlhttpRequest // https://www.tampermonkey.net/documentation.php?ext=dhdg#GM_xmlhttpRequest
const options = opt || {}; const options = opt || {};
options.url = url; options.url = url;
@ -95,16 +63,13 @@ function GM_fetch(url, opt) {
resp.text = () => blobTo("text", blob); resp.text = () => blobTo("text", blob);
resp.json = async () => JSON.parse(await blobTo("text", blob)); resp.json = async () => JSON.parse(await blobTo("text", blob));
resp.headers = new Headers(parseHeaders(resp.responseHeaders)); resp.headers = new Headers(parseHeaders(resp.responseHeaders));
resp.ok = resp.status >= 200 && resp.status < 300;
resolve(resp); resolve(resp);
}; };
options.ontimeout = () => reject("fetch timeout"); options.ontimeout = () => reject("fetch timeout");
options.onerror = () => reject("fetch error"); options.onerror = () => reject("fetch error");
options.onabort = () => reject("fetch abort"); options.onabort = () => reject("fetch abort");
GM_xmlhttpRequest(options); GM_xmlhttpRequest(options);
} else {
reject("CORS issue");
}
});
}); });
} }
export const fetch = GM_fetch; export const fetch = GM_fetch;

View File

@ -16,51 +16,70 @@
* along with this program. If not, see <https://www.gnu.org/licenses/>. * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
/// <reference path="../src/modules.d.ts" />
/// <reference path="../src/globals.d.ts" />
import monacoHtml from "~fileContent/../src/components/monacoWin.html";
import * as DataStore from "../src/api/DataStore"; import * as DataStore from "../src/api/DataStore";
import IpcEvents from "../src/utils/IpcEvents"; import { debounce } from "../src/utils";
import { getTheme, Theme } from "../src/utils/discord";
// Discord deletes this so need to store in variable // Discord deletes this so need to store in variable
const { localStorage } = window; const { localStorage } = window;
// listeners for ipc.on // listeners for ipc.on
const listeners = {} as Record<string, Set<Function>>; const cssListeners = new Set<(css: string) => void>();
const NOOP = () => { };
const NOOP_ASYNC = async () => { };
const handlers = { const setCssDebounced = debounce((css: string) => VencordNative.quickCss.set(css));
[IpcEvents.GET_REPO]: () => "https://github.com/Vendicated/Vencord", // shrug
[IpcEvents.GET_SETTINGS_DIR]: () => "LocalStorage",
[IpcEvents.GET_QUICK_CSS]: () => DataStore.get("VencordQuickCss").then(s => s ?? ""),
[IpcEvents.SET_QUICK_CSS]: (css: string) => {
DataStore.set("VencordQuickCss", css);
listeners[IpcEvents.QUICK_CSS_UPDATE]?.forEach(l => l(null, css));
},
[IpcEvents.GET_SETTINGS]: () => localStorage.getItem("VencordSettings") || "{}",
[IpcEvents.SET_SETTINGS]: (s: string) => localStorage.setItem("VencordSettings", s),
[IpcEvents.GET_UPDATES]: () => ({ ok: true, value: [] }),
[IpcEvents.OPEN_EXTERNAL]: (url: string) => open(url, "_blank"),
};
function onEvent(event: string, ...args: any[]) {
const handler = handlers[event];
if (!handler) throw new Error(`Event ${event} not implemented.`);
return handler(...args);
}
// probably should make this less cursed at some point // probably should make this less cursed at some point
window.VencordNative = { window.VencordNative = {
native: {
getVersions: () => ({}), getVersions: () => ({}),
ipc: { openExternal: async (url) => void open(url, "_blank")
send: (event: string, ...args: any[]) => void onEvent(event, ...args),
sendSync: onEvent,
on(event: string, listener: () => {}) {
(listeners[event] ??= new Set()).add(listener);
}, },
off(event: string, listener: () => {}) {
return listeners[event]?.delete(listener); updater: {
getRepo: async () => ({ ok: true, value: "https://github.com/Vendicated/Vencord" }),
getUpdates: async () => ({ ok: true, value: [] }),
update: async () => ({ ok: true, value: false }),
rebuild: async () => ({ ok: true, value: true }),
}, },
invoke: (event: string, ...args: any[]) => Promise.resolve(onEvent(event, ...args))
quickCss: {
get: () => DataStore.get("VencordQuickCss").then(s => s ?? ""),
set: async (css: string) => {
await DataStore.set("VencordQuickCss", css);
cssListeners.forEach(l => l(css));
}, },
addChangeListener(cb) {
cssListeners.add(cb);
},
openFile: NOOP_ASYNC,
async openEditor() {
const features = `popup,width=${Math.min(window.innerWidth, 1000)},height=${Math.min(window.innerHeight, 1000)}`;
const win = open("about:blank", "VencordQuickCss", features);
if (!win) {
alert("Failed to open QuickCSS popup. Make sure to allow popups!");
return;
}
win.setCss = setCssDebounced;
win.getCurrentCss = () => VencordNative.quickCss.get();
win.getTheme = () =>
getTheme() === Theme.Light
? "vs-light"
: "vs-dark";
win.document.write(monacoHtml);
},
},
settings: {
get: () => localStorage.getItem("VencordSettings") || "{}",
set: async (s: string) => localStorage.setItem("VencordSettings", s),
getSettingsDir: async () => "LocalStorage"
}
}; };

View File

@ -26,10 +26,6 @@ export default definePlugin({
name: "Your Name", name: "Your Name",
}, },
], ],
// Delete `patches` if you are not using code patches, as it will make
// your plugin require restarts, and your stop() method will not be
// invoked at all. The presence of the key in the object alone is
// enough to trigger this behavior, even if the value is an empty array.
patches: [], patches: [],
// Delete these two below if you are only using code patches // Delete these two below if you are only using code patches
start() {}, start() {},

View File

@ -1,7 +1,7 @@
{ {
"name": "vencord", "name": "vencord",
"private": "true", "private": "true",
"version": "1.2.0", "version": "1.2.5",
"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": {
@ -32,20 +32,20 @@
}, },
"dependencies": { "dependencies": {
"@vap/core": "0.0.12", "@vap/core": "0.0.12",
"@vap/shiki": "0.10.3", "@vap/shiki": "0.10.5",
"fflate": "^0.7.4", "fflate": "^0.7.4",
"nanoid": "^4.0.2", "nanoid": "^4.0.2",
"virtual-merge": "^1.0.1" "virtual-merge": "^1.0.1"
}, },
"devDependencies": { "devDependencies": {
"@types/diff": "^5.0.2", "@types/diff": "^5.0.3",
"@types/lodash": "^4.14.191", "@types/lodash": "^4.14.194",
"@types/node": "^18.11.18", "@types/node": "^18.16.3",
"@types/react": "^18.0.27", "@types/react": "^18.2.0",
"@types/react-dom": "^18.0.10", "@types/react-dom": "^18.2.1",
"@types/yazl": "^2.4.2", "@types/yazl": "^2.4.2",
"@typescript-eslint/eslint-plugin": "^5.49.0", "@typescript-eslint/eslint-plugin": "^5.59.1",
"@typescript-eslint/parser": "^5.49.0", "@typescript-eslint/parser": "^5.59.1",
"diff": "^5.1.0", "diff": "^5.1.0",
"discord-types": "^1.3.26", "discord-types": "^1.3.26",
"esbuild": "^0.15.18", "esbuild": "^0.15.18",
@ -53,17 +53,17 @@
"eslint-import-resolver-alias": "^1.1.2", "eslint-import-resolver-alias": "^1.1.2",
"eslint-plugin-header": "^3.1.1", "eslint-plugin-header": "^3.1.1",
"eslint-plugin-path-alias": "^1.0.0", "eslint-plugin-path-alias": "^1.0.0",
"eslint-plugin-simple-import-sort": "^8.0.0", "eslint-plugin-simple-import-sort": "^10.0.0",
"eslint-plugin-unused-imports": "^2.0.0", "eslint-plugin-unused-imports": "^2.0.0",
"highlight.js": "10.6.0", "highlight.js": "10.6.0",
"moment": "^2.29.4", "moment": "^2.29.4",
"puppeteer-core": "^19.6.0", "puppeteer-core": "^19.11.1",
"standalone-electron-types": "^1.0.0", "standalone-electron-types": "^1.0.0",
"stylelint": "^14.16.1", "stylelint": "^15.6.0",
"stylelint-config-standard": "^29.0.0", "stylelint-config-standard": "^33.0.0",
"tsx": "^3.12.6", "tsx": "^3.12.7",
"type-fest": "^3.5.3", "type-fest": "^3.9.0",
"typescript": "^4.9.4" "typescript": "^5.0.4"
}, },
"packageManager": "pnpm@8.1.1", "packageManager": "pnpm@8.1.1",
"pnpm": { "pnpm": {

734
pnpm-lock.yaml generated

File diff suppressed because it is too large Load Diff

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

@ -130,7 +130,7 @@ async function printReport() {
}, },
{ {
title: "Discord Errors", title: "Discord Errors",
description: toCodeBlock(report.otherErrors.join("\n")), description: report.otherErrors.length ? toCodeBlock(report.otherErrors.join("\n")) : "None",
color: report.otherErrors.length ? 0xff0000 : 0x00ff00 color: report.otherErrors.length ? 0xff0000 : 0x00ff00
} }
] ]
@ -194,9 +194,10 @@ page.on("console", async e => {
return a.toString(); return a.toString();
} }
}) })
).then(a => a.join(" ")); ).then(a => a.join(" ").trim());
if (!text.startsWith("Failed to load resource: the server responded with a status of")) {
if (text.length && !text.startsWith("Failed to load resource: the server responded with a status of")) {
console.error("Got unexpected error", text); console.error("Got unexpected error", text);
report.otherErrors.push(text); report.otherErrors.push(text);
} }
@ -233,7 +234,7 @@ function runTime(token: string) {
// Needs native server to run // Needs native server to run
if (p.name === "WebRichPresence (arRPC)") return; if (p.name === "WebRichPresence (arRPC)") return;
p.required = true; Vencord.Settings.plugins[p.name].enabled = true;
p.patches?.forEach(patch => { p.patches?.forEach(patch => {
patch.plugin = p.name; patch.plugin = p.name;
delete patch.predicate; delete patch.predicate;

View File

@ -28,17 +28,15 @@ import "./utils/quickCss";
import "./webpack/patchWebpack"; import "./webpack/patchWebpack";
import { showNotification } from "./api/Notifications"; import { showNotification } from "./api/Notifications";
import { PlainSettings, Settings } from "./api/settings"; import { PlainSettings, Settings } from "./api/Settings";
import { patches, PMLogger, startAllPlugins } from "./plugins"; import { patches, PMLogger, startAllPlugins } from "./plugins";
import { localStorage } from "./utils/localStorage"; import { localStorage } from "./utils/localStorage";
import { relaunch } from "./utils/native"; import { relaunch } from "./utils/native";
import { getCloudSettings, putCloudSettings } from "./utils/settingsSync"; import { getCloudSettings, putCloudSettings } from "./utils/settingsSync";
import { checkForUpdates, rebuild, update, UpdateLogger } from "./utils/updater"; 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();
@ -76,7 +73,6 @@ async function init() {
if (Settings.autoUpdate) { if (Settings.autoUpdate) {
await update(); await update();
await rebuild();
if (Settings.autoUpdateNotification) if (Settings.autoUpdateNotification)
setTimeout(() => showNotification({ setTimeout(() => showNotification({
title: "Vencord has been updated!", title: "Vencord has been updated!",

View File

@ -16,34 +16,46 @@
* 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 IPC_EVENTS from "@utils/IpcEvents"; import { IpcEvents } from "@utils/IpcEvents";
import { IpcRenderer, ipcRenderer } from "electron"; import { IpcRes } from "@utils/types";
import { ipcRenderer } from "electron";
function assertEventAllowed(event: string) { function invoke<T = any>(event: IpcEvents, ...args: any[]) {
if (!(event in IPC_EVENTS)) throw new Error(`Event ${event} not allowed.`); return ipcRenderer.invoke(event, ...args) as Promise<T>;
} }
export function sendSync<T = any>(event: IpcEvents, ...args: any[]) {
return ipcRenderer.sendSync(event, ...args) as T;
}
export default { export default {
getVersions: () => process.versions, updater: {
ipc: { getUpdates: () => invoke<IpcRes<Record<"hash" | "author" | "message", string>[]>>(IpcEvents.GET_UPDATES),
send(event: string, ...args: any[]) { update: () => invoke<IpcRes<boolean>>(IpcEvents.UPDATE),
assertEventAllowed(event); rebuild: () => invoke<IpcRes<boolean>>(IpcEvents.BUILD),
ipcRenderer.send(event, ...args); getRepo: () => invoke<IpcRes<string>>(IpcEvents.GET_REPO),
}, },
sendSync<T = any>(event: string, ...args: any[]): T {
assertEventAllowed(event); settings: {
return ipcRenderer.sendSync(event, ...args); get: () => sendSync<string>(IpcEvents.GET_SETTINGS),
set: (settings: string) => invoke<void>(IpcEvents.SET_SETTINGS, settings),
getSettingsDir: () => invoke<string>(IpcEvents.GET_SETTINGS_DIR),
}, },
on(event: string, listener: Parameters<IpcRenderer["on"]>[1]) {
assertEventAllowed(event); quickCss: {
ipcRenderer.on(event, listener); get: () => invoke<string>(IpcEvents.GET_QUICK_CSS),
set: (css: string) => invoke<void>(IpcEvents.SET_QUICK_CSS, css),
addChangeListener(cb: (newCss: string) => void) {
ipcRenderer.on(IpcEvents.QUICK_CSS_UPDATE, (_, css) => cb(css));
}, },
off(event: string, listener: Parameters<IpcRenderer["off"]>[1]) {
assertEventAllowed(event); openFile: () => invoke<void>(IpcEvents.OPEN_QUICKCSS),
ipcRenderer.off(event, listener); openEditor: () => invoke<void>(IpcEvents.OPEN_MONACO_EDITOR),
},
native: {
getVersions: () => process.versions as Partial<NodeJS.ProcessVersions>,
openExternal: (url: string) => invoke<void>(IpcEvents.OPEN_EXTERNAL, url)
}, },
invoke<T = any>(event: string, ...args: any[]): Promise<T> {
assertEventAllowed(event);
return ipcRenderer.invoke(event, ...args);
}
}
}; };

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 { makeCodeblock } from "@utils/misc"; import { makeCodeblock } from "@utils/text";
import { sendBotMessage } from "./commandHelpers"; import { sendBotMessage } from "./commandHelpers";
import { ApplicationCommandInputType, ApplicationCommandOptionType, ApplicationCommandType, Argument, Command, CommandContext, Option } from "./types"; import { ApplicationCommandInputType, ApplicationCommandOptionType, ApplicationCommandType, Argument, Command, CommandContext, Option } from "./types";

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 Logger from "@utils/Logger"; import { Logger } from "@utils/Logger";
import type { ReactElement } from "react"; import type { ReactElement } from "react";
type ContextMenuPatchCallbackReturn = (() => void) | void; type ContextMenuPatchCallbackReturn = (() => void) | void;
@ -25,14 +25,14 @@ type ContextMenuPatchCallbackReturn = (() => void) | void;
* @param args Any arguments passed into making the context menu, like the guild, channel, user or message for example * @param args Any arguments passed into making the context menu, like the guild, channel, user or message for example
* @returns A callback which is only ran once used to modify the context menu elements (Use to avoid duplicates) * @returns A callback which is only ran once used to modify the context menu elements (Use to avoid duplicates)
*/ */
export type NavContextMenuPatchCallback = (children: Array<React.ReactElement>, ...args: Array<any>) => ContextMenuPatchCallbackReturn; export type NavContextMenuPatchCallback = (children: Array<ReactElement | null>, ...args: Array<any>) => ContextMenuPatchCallbackReturn;
/** /**
* @param navId The navId of the context menu being patched * @param navId The navId of the context menu being patched
* @param children The rendered context menu elements * @param children The rendered context menu elements
* @param args Any arguments passed into making the context menu, like the guild, channel, user or message for example * @param args Any arguments passed into making the context menu, like the guild, channel, user or message for example
* @returns A callback which is only ran once used to modify the context menu elements (Use to avoid duplicates) * @returns A callback which is only ran once used to modify the context menu elements (Use to avoid duplicates)
*/ */
export type GlobalContextMenuPatchCallback = (navId: string, children: Array<React.ReactElement>, ...args: Array<any>) => ContextMenuPatchCallbackReturn; export type GlobalContextMenuPatchCallback = (navId: string, children: Array<ReactElement | null>, ...args: Array<any>) => ContextMenuPatchCallbackReturn;
const ContextMenuLogger = new Logger("ContextMenu"); const ContextMenuLogger = new Logger("ContextMenu");
@ -89,15 +89,18 @@ export function removeGlobalContextMenuPatch(patch: GlobalContextMenuPatchCallba
} }
/** /**
* A helper function for finding the children array of a group nested inside a context menu based on the id of one of its childs * A helper function for finding the children array of a group nested inside a context menu based on the id(s) of its children
* @param id The id of the child * @param id The id of the child. If an array is specified, all ids will be tried
* @param children The context menu children * @param children The context menu children
*/ */
export function findGroupChildrenByChildId(id: string, children: Array<React.ReactElement>, _itemsArray?: Array<React.ReactElement>): Array<React.ReactElement> | null { export function findGroupChildrenByChildId(id: string | string[], children: Array<ReactElement | null>, _itemsArray?: Array<ReactElement | null>): Array<ReactElement | null> | null {
for (const child of children) { for (const child of children) {
if (child == null) continue; if (child == null) continue;
if (child.props?.id === id) return _itemsArray ?? null; if (
(Array.isArray(id) && id.some(id => child.props?.id === id))
|| child.props?.id === id
) return _itemsArray ?? null;
let nextChildren = child.props?.children; let nextChildren = child.props?.children;
if (nextChildren) { if (nextChildren) {
@ -117,7 +120,7 @@ export function findGroupChildrenByChildId(id: string, children: Array<React.Rea
interface ContextMenuProps { interface ContextMenuProps {
contextMenuApiArguments?: Array<any>; contextMenuApiArguments?: Array<any>;
navId: string; navId: string;
children: Array<ReactElement>; children: Array<ReactElement | null>;
"aria-label": string; "aria-label": string;
onSelect: (() => void) | undefined; onSelect: (() => void) | undefined;
onClose: (callback: (...args: Array<any>) => any) => void; onClose: (callback: (...args: Array<any>) => any) => void;

View File

@ -16,30 +16,61 @@
* 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 Logger from "@utils/Logger"; import { Logger } from "@utils/Logger";
import { MessageStore } from "@webpack/common"; import { MessageStore } from "@webpack/common";
import { CustomEmoji } from "@webpack/types";
import type { Channel, Message } from "discord-types/general"; import type { Channel, Message } from "discord-types/general";
import type { Promisable } from "type-fest"; import type { Promisable } from "type-fest";
const MessageEventsLogger = new Logger("MessageEvents", "#e5c890"); const MessageEventsLogger = new Logger("MessageEvents", "#e5c890");
export interface Emoji {
require_colons: boolean,
originalName: string,
animated: boolean;
guildId: string,
name: string,
url: string,
id: string,
}
export interface MessageObject { export interface MessageObject {
content: string, content: string,
validNonShortcutEmojis: Emoji[]; validNonShortcutEmojis: CustomEmoji[];
invalidEmojis: any[];
tts: boolean;
}
export interface Upload {
classification: string;
currentSize: number;
description: string | null;
filename: string;
id: string;
isImage: boolean;
isVideo: boolean;
item: {
file: File;
platform: number;
};
loaded: number;
mimeType: string;
preCompressionSize: number;
responseUrl: string;
sensitive: boolean;
showLargeMessageDialog: boolean;
spoiler: boolean;
status: "NOT_STARTED" | "STARTED" | "UPLOADING" | "ERROR" | "COMPLETED" | "CANCELLED";
uniqueId: string;
uploadedFilename: string;
}
export interface MessageReplyOptions {
messageReference: Message["messageReference"];
allowedMentions?: {
parse: Array<string>;
repliedUser: boolean;
};
} }
export interface MessageExtra { export interface MessageExtra {
stickerIds?: string[]; stickers?: string[];
uploads?: Upload[];
replyOptions: MessageReplyOptions;
content: string;
channel: Channel;
type?: any;
openWarningPopout: (props: any) => any;
} }
export type SendListener = (channelId: string, messageObj: MessageObject, extra: MessageExtra) => Promisable<void | { cancel: boolean; }>; export type SendListener = (channelId: string, messageObj: MessageObject, extra: MessageExtra) => Promisable<void | { cancel: boolean; }>;
@ -48,7 +79,8 @@ export type EditListener = (channelId: string, messageId: string, messageObj: Me
const sendListeners = new Set<SendListener>(); const sendListeners = new Set<SendListener>();
const editListeners = new Set<EditListener>(); const editListeners = new Set<EditListener>();
export async function _handlePreSend(channelId: string, messageObj: MessageObject, extra: MessageExtra) { export async function _handlePreSend(channelId: string, messageObj: MessageObject, extra: MessageExtra, replyOptions: MessageReplyOptions) {
extra.replyOptions = replyOptions;
for (const listener of sendListeners) { for (const listener of sendListeners) {
try { try {
const result = await listener(channelId, messageObj, extra); const result = await listener(channelId, messageObj, extra);

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 Logger from "@utils/Logger"; import { Logger } from "@utils/Logger";
import { Channel, Message } from "discord-types/general"; import { Channel, Message } from "discord-types/general";
import type { MouseEventHandler } from "react"; import type { MouseEventHandler } from "react";

View File

@ -18,7 +18,7 @@
import "./styles.css"; import "./styles.css";
import { useSettings } from "@api/settings"; import { useSettings } from "@api/Settings";
import ErrorBoundary from "@components/ErrorBoundary"; import ErrorBoundary from "@components/ErrorBoundary";
import { classes } from "@utils/misc"; import { classes } from "@utils/misc";
import { React, useEffect, useMemo, useState, useStateFromStores, WindowStore } from "@webpack/common"; import { React, useEffect, useMemo, useState, useStateFromStores, WindowStore } from "@webpack/common";

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 { Settings } from "@api/settings"; import { Settings } from "@api/Settings";
import { Queue } from "@utils/Queue"; import { Queue } from "@utils/Queue";
import { ReactDOM } from "@webpack/common"; import { ReactDOM } from "@webpack/common";
import type { ReactNode } from "react"; import type { ReactNode } from "react";

View File

@ -17,10 +17,10 @@
*/ */
import * as DataStore from "@api/DataStore"; import * as DataStore from "@api/DataStore";
import { Settings } from "@api/settings"; import { Settings } from "@api/Settings";
import { classNameFactory } from "@api/Styles"; import { classNameFactory } from "@api/Styles";
import { useAwaiter } from "@utils/misc";
import { closeModal, ModalCloseButton, ModalContent, ModalFooter, ModalHeader, ModalProps, ModalRoot, ModalSize, openModal } from "@utils/modal"; import { closeModal, ModalCloseButton, ModalContent, ModalFooter, ModalHeader, ModalProps, ModalRoot, ModalSize, openModal } from "@utils/modal";
import { useAwaiter } from "@utils/react";
import { Alerts, Button, Forms, moment, React, Text, Timestamp, useEffect, useReducer, useState } from "@webpack/common"; import { Alerts, Button, Forms, moment, React, Text, Timestamp, useEffect, useReducer, useState } from "@webpack/common";
import { nanoid } from "nanoid"; import { nanoid } from "nanoid";
import type { DispatchWithoutAction } from "react"; import type { DispatchWithoutAction } from "react";

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 Logger from "@utils/Logger"; import { Logger } from "@utils/Logger";
const logger = new Logger("ServerListAPI"); const logger = new Logger("ServerListAPI");

View File

@ -17,9 +17,8 @@
*/ */
import { debounce } from "@utils/debounce"; import { debounce } from "@utils/debounce";
import IpcEvents from "@utils/IpcEvents";
import { localStorage } from "@utils/localStorage"; import { localStorage } from "@utils/localStorage";
import Logger from "@utils/Logger"; import { Logger } from "@utils/Logger";
import { mergeDefaults } from "@utils/misc"; import { mergeDefaults } from "@utils/misc";
import { putCloudSettings } from "@utils/settingsSync"; import { putCloudSettings } from "@utils/settingsSync";
import { DefinedSettings, OptionType, SettingsChecks, SettingsDefinition } from "@utils/types"; import { DefinedSettings, OptionType, SettingsChecks, SettingsDefinition } from "@utils/types";
@ -94,7 +93,7 @@ const DefaultSettings: Settings = {
}; };
try { try {
var settings = JSON.parse(VencordNative.ipc.sendSync(IpcEvents.GET_SETTINGS)) as Settings; var settings = JSON.parse(VencordNative.settings.get()) as Settings;
mergeDefaults(settings, DefaultSettings); mergeDefaults(settings, DefaultSettings);
} catch (err) { } catch (err) {
var settings = mergeDefaults({} as Settings, DefaultSettings); var settings = mergeDefaults({} as Settings, DefaultSettings);
@ -173,7 +172,7 @@ function makeProxy(settings: any, root = settings, path = ""): Settings {
PlainSettings.cloud.settingsSyncVersion = Date.now(); PlainSettings.cloud.settingsSyncVersion = Date.now();
localStorage.Vencord_settingsDirty = true; localStorage.Vencord_settingsDirty = true;
saveSettingsOnFrequentAction(); saveSettingsOnFrequentAction();
VencordNative.ipc.invoke(IpcEvents.SET_SETTINGS, JSON.stringify(root, null, 4)); VencordNative.settings.set(JSON.stringify(root, null, 4));
return true; return true;
} }
}); });
@ -249,10 +248,7 @@ export function migratePluginSettings(name: string, ...oldNames: string[]) {
logger.info(`Migrating settings from old name ${oldName} to ${name}`); logger.info(`Migrating settings from old name ${oldName} to ${name}`);
plugins[name] = plugins[oldName]; plugins[name] = plugins[oldName];
delete plugins[oldName]; delete plugins[oldName];
VencordNative.ipc.invoke( VencordNative.settings.set(JSON.stringify(settings, null, 4));
IpcEvents.SET_SETTINGS,
JSON.stringify(settings, null, 4)
);
break; break;
} }
} }

View File

@ -16,11 +16,11 @@
* 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 Logger from "@utils/Logger"; import { proxyLazy } from "@utils/lazy";
import { proxyLazy } from "@utils/proxyLazy"; import { Logger } from "@utils/Logger";
import { findModuleId, wreq } from "@webpack"; import { findModuleId, wreq } from "@webpack";
import { Settings } from "./settings"; import { Settings } from "./Settings";
interface Setting<T> { interface Setting<T> {
/** /**

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,7 +16,6 @@
* along with this program. If not, see <https://www.gnu.org/licenses/>. * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
import IpcEvents from "@utils/IpcEvents";
import { Button } from "@webpack/common"; import { Button } from "@webpack/common";
import { Heart } from "./Heart"; import { Heart } from "./Heart";
@ -27,9 +26,7 @@ export default function DonateButton(props: any) {
{...props} {...props}
look={Button.Looks.LINK} look={Button.Looks.LINK}
color={Button.Colors.TRANSPARENT} color={Button.Colors.TRANSPARENT}
onClick={() => onClick={() => VencordNative.native.openExternal("https://github.com/sponsors/Vendicated")}
VencordNative.ipc.invoke(IpcEvents.OPEN_EXTERNAL, "https://github.com/sponsors/Vendicated")
}
> >
<Heart /> <Heart />
Donate Donate

View File

@ -16,9 +16,9 @@
* 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 Logger from "@utils/Logger"; import { Logger } from "@utils/Logger";
import { Margins } from "@utils/margins"; import { Margins } from "@utils/margins";
import { LazyComponent } from "@utils/misc"; import { LazyComponent } from "@utils/react";
import { React } from "@webpack/common"; import { React } from "@webpack/common";
import { ErrorCard } from "./ErrorCard"; import { ErrorCard } from "./ErrorCard";

148
src/components/Icons.tsx Normal file
View File

@ -0,0 +1,148 @@
/*
* 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 "./iconStyles.css";
import { classes } from "@utils/misc";
import { i18n } from "@webpack/common";
import type { PropsWithChildren, SVGProps } from "react";
interface BaseIconProps extends IconProps {
viewBox: string;
}
interface IconProps extends SVGProps<SVGSVGElement> {
className?: string;
height?: number;
width?: number;
}
function Icon({ height = 24, width = 24, className, children, viewBox, ...svgProps }: PropsWithChildren<BaseIconProps>) {
return (
<svg
className={classes(className, "vc-icon")}
role="img"
width={width}
height={height}
viewBox={viewBox}
{...svgProps}
>
{children}
</svg>
);
}
/**
* Discord's link icon, as seen in the Message context menu "Copy Message Link" option
*/
export function LinkIcon({ height = 24, width = 24, className }: IconProps) {
return (
<Icon
height={height}
width={width}
className={classes(className, "vc-link-icon")}
viewBox="0 0 24 24"
>
<g fill="none" fill-rule="evenodd">
<path fill="currentColor" d="M10.59 13.41c.41.39.41 1.03 0 1.42-.39.39-1.03.39-1.42 0a5.003 5.003 0 0 1 0-7.07l3.54-3.54a5.003 5.003 0 0 1 7.07 0 5.003 5.003 0 0 1 0 7.07l-1.49 1.49c.01-.82-.12-1.64-.4-2.42l.47-.48a2.982 2.982 0 0 0 0-4.24 2.982 2.982 0 0 0-4.24 0l-3.53 3.53a2.982 2.982 0 0 0 0 4.24zm2.82-4.24c.39-.39 1.03-.39 1.42 0a5.003 5.003 0 0 1 0 7.07l-3.54 3.54a5.003 5.003 0 0 1-7.07 0 5.003 5.003 0 0 1 0-7.07l1.49-1.49c-.01.82.12 1.64.4 2.43l-.47.47a2.982 2.982 0 0 0 0 4.24 2.982 2.982 0 0 0 4.24 0l3.53-3.53a2.982 2.982 0 0 0 0-4.24.973.973 0 0 1 0-1.42z" />
<rect width={width} height={height} />
</g>
</Icon>
);
}
/**
* Discord's copy icon, as seen in the user popout right of the username when clicking
* your own username in the bottom left user panel
*/
export function CopyIcon(props: IconProps) {
return (
<Icon
{...props}
className={classes(props.className, "vc-copy-icon")}
viewBox="0 0 24 24"
>
<g fill="currentColor">
<path d="M16 1H4c-1.1 0-2 .9-2 2v14h2V3h12V1z" />
<path d="M15 5H8c-1.1 0-1.99.9-1.99 2L6 21c0 1.1.89 2 1.99 2H19c1.1 0 2-.9 2-2V11l-6-6zM8 21V7h6v5h5v9H8z" />
</g>
</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

@ -1,51 +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 { debounce } from "@utils/debounce";
import IpcEvents from "@utils/IpcEvents";
import { Queue } from "@utils/Queue";
import { find } from "@webpack";
import monacoHtml from "~fileContent/monacoWin.html";
const queue = new Queue();
const setCss = debounce((css: string) => {
queue.push(() => VencordNative.ipc.invoke(IpcEvents.SET_QUICK_CSS, css));
});
export async function launchMonacoEditor() {
const features = `popup,width=${Math.min(window.innerWidth, 1000)},height=${Math.min(window.innerHeight, 1000)}`;
const win = open("about:blank", "VencordQuickCss", features);
if (!win) {
alert("Failed to open QuickCSS popup. Make sure to allow popups!");
return;
}
win.setCss = setCss;
win.getCurrentCss = () => VencordNative.ipc.invoke(IpcEvents.GET_QUICK_CSS);
win.getTheme = () =>
find(m =>
m.ProtoClass?.typeName.endsWith("PreloadedUserSettings")
)?.getCurrentValue()?.appearance?.theme === 2
? "vs-light"
: "vs-dark";
win.document.write(monacoHtml);
window.__VENCORD_MONACO_WIN__ = new WeakRef(win);
}

View File

@ -17,13 +17,15 @@
*/ */
import { generateId } from "@api/Commands"; import { generateId } from "@api/Commands";
import { useSettings } from "@api/settings"; import { useSettings } from "@api/Settings";
import { disableStyle, enableStyle } from "@api/Styles";
import ErrorBoundary from "@components/ErrorBoundary"; import ErrorBoundary from "@components/ErrorBoundary";
import { Flex } from "@components/Flex"; import { Flex } from "@components/Flex";
import { proxyLazy } from "@utils/lazy";
import { Margins } from "@utils/margins"; import { Margins } from "@utils/margins";
import { classes, LazyComponent } from "@utils/misc"; import { classes } from "@utils/misc";
import { ModalCloseButton, ModalContent, ModalFooter, ModalHeader, ModalProps, ModalRoot, ModalSize } from "@utils/modal"; import { ModalCloseButton, ModalContent, ModalFooter, ModalHeader, ModalProps, ModalRoot, ModalSize } from "@utils/modal";
import { proxyLazy } from "@utils/proxyLazy"; import { LazyComponent } from "@utils/react";
import { OptionType, Plugin } from "@utils/types"; import { OptionType, Plugin } from "@utils/types";
import { findByCode, findByPropsLazy } from "@webpack"; import { findByCode, findByPropsLazy } from "@webpack";
import { Button, FluxDispatcher, Forms, React, Text, Tooltip, UserStore, UserUtils } from "@webpack/common"; import { Button, FluxDispatcher, Forms, React, Text, Tooltip, UserStore, UserUtils } from "@webpack/common";
@ -39,6 +41,7 @@ import {
SettingSliderComponent, SettingSliderComponent,
SettingTextComponent SettingTextComponent
} from "./components"; } from "./components";
import hideBotTagStyle from "./userPopoutHideBotTag.css?managed";
const UserSummaryItem = LazyComponent(() => findByCode("defaultRenderUser", "showDefaultAvatarsForNullUsers")); const UserSummaryItem = LazyComponent(() => findByCode("defaultRenderUser", "showDefaultAvatarsForNullUsers"));
const AvatarStyles = findByPropsLazy("moreUsers", "emptyUser", "avatarContainer", "clickableAvatar"); const AvatarStyles = findByPropsLazy("moreUsers", "emptyUser", "avatarContainer", "clickableAvatar");
@ -49,11 +52,12 @@ interface PluginModalProps extends ModalProps {
onRestartNeeded(): void; onRestartNeeded(): void;
} }
/** To stop discord making unwanted requests... */ function makeDummyUser(user: { username: string; id?: string; avatar?: string; }) {
function makeDummyUser(user: { name: string, id: BigInt; }) {
const newUser = new UserRecord({ const newUser = new UserRecord({
username: user.name, username: user.username,
id: generateId(), id: user.id ?? generateId(),
avatar: user.avatar,
/** To stop discord making unwanted requests... */
bot: true, bot: true,
}); });
FluxDispatcher.dispatch({ FluxDispatcher.dispatch({
@ -88,14 +92,27 @@ export default function PluginModal({ plugin, onRestartNeeded, onClose, transiti
const hasSettings = Boolean(pluginSettings && plugin.options); const hasSettings = Boolean(pluginSettings && plugin.options);
React.useEffect(() => { React.useEffect(() => {
enableStyle(hideBotTagStyle);
let originalUser: User;
(async () => { (async () => {
for (const user of plugin.authors.slice(0, 6)) { for (const user of plugin.authors.slice(0, 6)) {
const author = user.id const author = user.id
? await UserUtils.fetchUser(`${user.id}`).catch(() => makeDummyUser(user)) ? await UserUtils.fetchUser(`${user.id}`)
: makeDummyUser(user); // only show name & pfp and no actions so users cannot harass plugin devs for support (send dms, add as friend, etc)
.then(u => (originalUser = u, makeDummyUser(u)))
.catch(() => makeDummyUser({ username: user.name }))
: makeDummyUser({ username: user.name });
setAuthors(a => [...a, author]); setAuthors(a => [...a, author]);
} }
})(); })();
return () => {
disableStyle(hideBotTagStyle);
if (originalUser)
FluxDispatcher.dispatch({ type: "USER_UPDATE", user: originalUser });
};
}, []); }, []);
async function saveAndClose() { async function saveAndClose() {
@ -128,6 +145,8 @@ export default function PluginModal({ plugin, onRestartNeeded, onClose, transiti
return <Forms.FormText>There are no settings for this plugin.</Forms.FormText>; return <Forms.FormText>There are no settings for this plugin.</Forms.FormText>;
} else { } else {
const options = Object.entries(plugin.options).map(([key, setting]) => { const options = Object.entries(plugin.options).map(([key, setting]) => {
if (setting.hidden) return null;
function onChange(newValue: any) { function onChange(newValue: any) {
setTempSettings(s => ({ ...s, [key]: newValue })); setTempSettings(s => ({ ...s, [key]: newValue }));
} }

View File

@ -20,19 +20,19 @@ 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, LazyComponent, useAwaiter } from "@utils/misc"; import { classes } from "@utils/misc";
import { openModalLazy } from "@utils/modal"; import { openModalLazy } from "@utils/modal";
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";
import { Alerts, Button, Card, Forms, Parser, React, Select, Text, TextInput, Toasts, Tooltip } from "@webpack/common"; import { Alerts, Button, Card, Forms, Parser, React, Select, Text, TextInput, Toasts, Tooltip } from "@webpack/common";
@ -94,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;
@ -125,7 +125,7 @@ function PluginCard({ plugin, disabled, onRestartNeeded, onMouseEnter, onMouseLe
} }
// if the plugin has patches, dont use stopPlugin/startPlugin. Wait for restart to apply changes. // if the plugin has patches, dont use stopPlugin/startPlugin. Wait for restart to apply changes.
if (plugin.patches) { if (plugin.patches?.length) {
settings.enabled = !wasEnabled; settings.enabled = !wasEnabled;
onRestartNeeded(plugin.name); onRestartNeeded(plugin.name);
return; return;
@ -177,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>(), []);
@ -228,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))
); );
}; };
@ -258,6 +261,9 @@ export default ErrorBoundary.wrap(function PluginSettings() {
requiredPlugins = []; requiredPlugins = [];
for (const p of sortedPlugins) { for (const p of sortedPlugins) {
if (!p.options && p.name.endsWith("API") && searchValue.value !== "API")
continue;
if (!pluginFilter(p)) continue; if (!pluginFilter(p)) continue;
const isRequired = p.required || depMap[p.name]?.some(d => settings.plugins[d].enabled); const isRequired = p.required || depMap[p.name]?.some(d => settings.plugins[d].enabled);
@ -298,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)}>
@ -337,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: handleComponentFailed,
});
function makeDependencyList(deps: string[]) { function makeDependencyList(deps: string[]) {
return ( return (

View File

@ -0,0 +1,3 @@
[class|="userPopoutOuter"] [class*="botTag"] {
display: none;
}

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

@ -17,15 +17,16 @@
*/ */
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 { makeCodeblock } from "@utils/misc";
import { canonicalizeMatch, canonicalizeReplace } from "@utils/patches"; import { canonicalizeMatch, canonicalizeReplace } from "@utils/patches";
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

@ -16,14 +16,15 @@
* 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 { 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/misc"; 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,11 +90,11 @@ 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>
<Forms.FormText>Make sure to use the raw links or github.io links!</Forms.FormText> <Forms.FormText><strong>Make sure to use the raw links or github.io links!</strong></Forms.FormText>
<Forms.FormDivider className={Margins.top8 + " " + Margins.bottom8} /> <Forms.FormDivider className={Margins.top8 + " " + Margins.bottom8} />
<Forms.FormTitle tag="h5">Find Themes:</Forms.FormTitle> <Forms.FormTitle tag="h5">Find Themes:</Forms.FormTitle>
<div style={{ marginBottom: ".5em" }}> <div style={{ marginBottom: ".5em" }}>
@ -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

@ -16,20 +16,21 @@
* 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 { 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, useAwaiter } from "@utils/misc"; import { classes } from "@utils/misc";
import { relaunch } from "@utils/native"; import { relaunch } from "@utils/native";
import { changes, checkForUpdates, getRepo, isNewer, rebuild, update, updateError, UpdateLogger } from "@utils/updater"; import { useAwaiter } from "@utils/react";
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);
@ -125,7 +126,6 @@ function Updatable(props: CommonProps) {
onClick={withDispatcher(setIsUpdating, async () => { onClick={withDispatcher(setIsUpdating, async () => {
if (await update()) { if (await update()) {
setUpdates([]); setUpdates([]);
await rebuild();
await new Promise<void>(r => { await new Promise<void>(r => {
Alerts.show({ Alerts.show({
title: "Update Success!", title: "Update Success!",
@ -198,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}
@ -245,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: handleComponentFailed,
});

View File

@ -18,17 +18,18 @@
import { openNotificationLogModal } from "@api/Notifications/notificationLog"; 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 IpcEvents from "@utils/IpcEvents";
import { Margins } from "@utils/margins"; import { Margins } from "@utils/margins";
import { identity, useAwaiter } from "@utils/misc"; import { identity } from "@utils/misc";
import { relaunch, showItemInFolder } from "@utils/native"; import { relaunch, showItemInFolder } from "@utils/native";
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";
@ -39,7 +40,7 @@ type KeysOfType<Object, Type> = {
}[keyof Object]; }[keyof Object];
function VencordSettings() { function VencordSettings() {
const [settingsDir, , settingsDirPending] = useAwaiter(() => VencordNative.ipc.invoke<string>(IpcEvents.GET_SETTINGS_DIR), { const [settingsDir, , settingsDirPending] = useAwaiter(VencordNative.settings.getSettingsDir, {
fallbackValue: "Loading..." fallbackValue: "Loading..."
}); });
const settings = useSettings(); const settings = useSettings();
@ -97,44 +98,39 @@ 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")}>
{IS_WEB ? (
<Button
onClick={() => require("../Monaco").launchMonacoEditor()}
size={Button.Sizes.SMALL}
disabled={settingsDir === "Loading..."}>
Open QuickCSS File
</Button>
) : (
<React.Fragment> <React.Fragment>
{!IS_WEB && (
<Button <Button
onClick={relaunch} onClick={relaunch}
size={Button.Sizes.SMALL}> size={Button.Sizes.SMALL}>
Restart Client Restart Client
</Button> </Button>
)}
<Button <Button
onClick={() => VencordNative.ipc.invoke(IpcEvents.OPEN_MONACO_EDITOR)} onClick={() => VencordNative.quickCss.openEditor()}
size={Button.Sizes.SMALL} size={Button.Sizes.SMALL}
disabled={settingsDir === "Loading..."}> disabled={settingsDir === "Loading..."}>
Open QuickCSS File Open QuickCSS File
</Button> </Button>
{!IS_WEB && (
<Button <Button
onClick={() => showItemInFolder(settingsDir)} onClick={() => showItemInFolder(settingsDir)}
size={Button.Sizes.SMALL} size={Button.Sizes.SMALL}
disabled={settingsDirPending}> disabled={settingsDirPending}>
Open Settings Folder Open Settings Folder
</Button> </Button>
)}
<Button <Button
onClick={() => VencordNative.ipc.invoke(IpcEvents.OPEN_EXTERNAL, "https://github.com/Vendicated/Vencord")} onClick={() => VencordNative.native.openExternal("https://github.com/Vendicated/Vencord")}
size={Button.Sizes.SMALL} size={Button.Sizes.SMALL}
disabled={settingsDirPending}> disabled={settingsDirPending}>
Open in GitHub Open in GitHub
</Button> </Button>
</React.Fragment> </React.Fragment>
)}
</Card> </Card>
</Forms.FormSection> </Forms.FormSection>
@ -158,7 +154,7 @@ function VencordSettings() {
{typeof Notification !== "undefined" && <NotificationSection settings={settings.notifications} />} {typeof Notification !== "undefined" && <NotificationSection settings={settings.notifications} />}
</React.Fragment> </SettingsTab>
); );
} }
@ -268,4 +264,4 @@ function DonateCard({ image }: DonateCardProps) {
); );
} }
export default ErrorBoundary.wrap(VencordSettings); export default wrapTab(VencordSettings, "Vencord Settings");

View File

@ -1,93 +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 { 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 >;
}
export default function (props: SettingsProps) {
return <ErrorBoundary onError={handleComponentFailed}>
<Settings tab={props.tab} />
</ErrorBoundary>;
}

View File

@ -15,7 +15,7 @@
display: flex; display: flex;
gap: 1em; gap: 1em;
align-items: center; align-items: center;
justify-content: space-between; justify-content: space-evenly;
flex-grow: 1; flex-grow: 1;
flex-flow: row wrap; flex-flow: row wrap;
margin-bottom: 1em; margin-bottom: 1em;
@ -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) { .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

@ -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 Logger from "@utils/Logger"; import { Logger } from "@utils/Logger";
if (IS_DEV) { if (IS_DEV) {
var traces = {} as Record<string, [number, any[]]>; var traces = {} as Record<string, [number, any[]]>;

View File

@ -19,7 +19,7 @@
import "./updater"; import "./updater";
import { debounce } from "@utils/debounce"; import { debounce } from "@utils/debounce";
import IpcEvents from "@utils/IpcEvents"; import { IpcEvents } from "@utils/IpcEvents";
import { Queue } from "@utils/Queue"; import { Queue } from "@utils/Queue";
import { BrowserWindow, ipcMain, shell } from "electron"; import { BrowserWindow, ipcMain, shell } from "electron";
import { mkdirSync, readFileSync, watch } from "fs"; import { mkdirSync, readFileSync, watch } from "fs";
@ -44,7 +44,7 @@ export function readSettings() {
} }
} }
export function getSettings(): typeof import("@api/settings").Settings { export function getSettings(): typeof import("@api/Settings").Settings {
try { try {
return JSON.parse(readSettings()); return JSON.parse(readSettings());
} catch { } catch {

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 IpcEvents from "@utils/IpcEvents"; import { IpcEvents } from "@utils/IpcEvents";
import { execFile as cpExecFile } from "child_process"; import { execFile as cpExecFile } from "child_process";
import { ipcMain } from "electron"; import { ipcMain } from "electron";
import { join } from "path"; import { join } from "path";

View File

@ -17,7 +17,7 @@
*/ */
import { VENCORD_USER_AGENT } from "@utils/constants"; import { VENCORD_USER_AGENT } from "@utils/constants";
import IpcEvents from "@utils/IpcEvents"; import { IpcEvents } from "@utils/IpcEvents";
import { ipcMain } from "electron"; import { ipcMain } from "electron";
import { writeFile } from "fs/promises"; import { writeFile } from "fs/promises";
import { join } from "path"; import { join } from "path";

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 { Settings } from "@api/settings"; import { 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";

View File

@ -22,18 +22,15 @@ import ErrorBoundary from "@components/ErrorBoundary";
import { Flex } from "@components/Flex"; import { Flex } from "@components/Flex";
import { Heart } from "@components/Heart"; import { Heart } from "@components/Heart";
import { Devs } from "@utils/constants"; import { Devs } from "@utils/constants";
import IpcEvents from "@utils/IpcEvents"; import { Logger } from "@utils/Logger";
import Logger from "@utils/Logger";
import { Margins } from "@utils/margins"; import { Margins } from "@utils/margins";
import { isPluginDev } from "@utils/misc";
import { closeModal, Modals, openModal } from "@utils/modal"; import { closeModal, Modals, openModal } from "@utils/modal";
import definePlugin from "@utils/types"; import definePlugin from "@utils/types";
import { Forms } from "@webpack/common"; import { Forms, Toasts } from "@webpack/common";
const CONTRIBUTOR_BADGE = "https://cdn.discordapp.com/attachments/1033680203433660458/1092089947126780035/favicon.png"; const CONTRIBUTOR_BADGE = "https://cdn.discordapp.com/attachments/1033680203433660458/1092089947126780035/favicon.png";
/** List of vencord contributor IDs */
const contributorIds: string[] = Object.values(Devs).map(d => d.id.toString());
const ContributorBadge: ProfileBadge = { const ContributorBadge: ProfileBadge = {
description: "Vencord Contributor", description: "Vencord Contributor",
image: CONTRIBUTOR_BADGE, image: CONTRIBUTOR_BADGE,
@ -44,11 +41,33 @@ const ContributorBadge: ProfileBadge = {
transform: "scale(0.9)" // The image is a bit too big compared to default badges transform: "scale(0.9)" // The image is a bit too big compared to default badges
} }
}, },
shouldShow: ({ user }) => contributorIds.includes(user.id), shouldShow: ({ user }) => isPluginDev(user.id),
link: "https://github.com/Vendicated/Vencord" link: "https://github.com/Vendicated/Vencord"
}; };
const DonorBadges = {} as Record<string, Pick<ProfileBadge, "image" | "description">[]>; let DonorBadges = {} as Record<string, Pick<ProfileBadge, "image" | "description">[]>;
async function loadBadges(noCache = false) {
DonorBadges = {};
const init = {} as RequestInit;
if (noCache)
init.cache = "no-cache";
const badges = await fetch("https://gist.githubusercontent.com/Vendicated/51a3dd775f6920429ec6e9b735ca7f01/raw/badges.csv", init)
.then(r => r.text());
const lines = badges.trim().split("\n");
if (lines.shift() !== "id,tooltip,image") {
new Logger("BadgeAPI").error("Invalid badges.csv file!");
return;
}
for (const line of lines) {
const [id, description, image] = line.split(",");
(DonorBadges[id] ??= []).push({ image, description });
}
}
export default definePlugin({ export default definePlugin({
name: "BadgeAPI", name: "BadgeAPI",
@ -61,8 +80,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
@ -82,24 +101,27 @@ export default definePlugin({
} }
], ],
toolboxActions: {
async "Refetch Badges"() {
await loadBadges(true);
Toasts.show({
id: Toasts.genId(),
message: "Successfully refetched badges!",
type: Toasts.Type.SUCCESS
});
}
},
async start() {
Vencord.Api.Badges.addBadge(ContributorBadge);
await loadBadges();
},
renderBadgeComponent: ErrorBoundary.wrap((badge: ProfileBadge & BadgeUserArgs) => { renderBadgeComponent: ErrorBoundary.wrap((badge: ProfileBadge & BadgeUserArgs) => {
const Component = badge.component!; const Component = badge.component!;
return <Component {...badge} />; return <Component {...badge} />;
}, { noop: true }), }, { noop: true }),
async start() {
Vencord.Api.Badges.addBadge(ContributorBadge);
const badges = await fetch("https://gist.githubusercontent.com/Vendicated/51a3dd775f6920429ec6e9b735ca7f01/raw/badges.csv").then(r => r.text());
const lines = badges.trim().split("\n");
if (lines.shift() !== "id,tooltip,image") {
new Logger("BadgeAPI").error("Invalid badges.csv file!");
return;
}
for (const line of lines) {
const [id, description, image] = line.split(",");
(DonorBadges[id] ??= []).push({ image, description });
}
},
getDonorBadges(userId: string) { getDonorBadges(userId: string) {
return DonorBadges[userId]?.map(badge => ({ return DonorBadges[userId]?.map(badge => ({
@ -115,7 +137,7 @@ export default definePlugin({
const modalKey = openModal(props => ( const modalKey = openModal(props => (
<ErrorBoundary noop onError={() => { <ErrorBoundary noop onError={() => {
closeModal(modalKey); closeModal(modalKey);
VencordNative.ipc.invoke(IpcEvents.OPEN_EXTERNAL, "https://github.com/sponsors/Vendicated"); VencordNative.native.openExternal("https://github.com/sponsors/Vendicated");
}}> }}>
<Modals.ModalRoot {...props}> <Modals.ModalRoot {...props}>
<Modals.ModalHeader> <Modals.ModalHeader>

View File

@ -22,17 +22,29 @@ import definePlugin from "@utils/types";
export default definePlugin({ export default definePlugin({
name: "MessageEventsAPI", name: "MessageEventsAPI",
description: "Api required by anything using message events.", description: "Api required by anything using message events.",
authors: [Devs.Arjix, Devs.hunt], authors: [Devs.Arjix, Devs.hunt, Devs.Ven],
patches: [ patches: [
{ {
find: '"MessageActionCreators"', find: '"MessageActionCreators"',
replacement: [{ replacement: {
match: /_sendMessage:(function\([^)]+\)){/, // editMessage: function (...) {
replace: "_sendMessage:async $1{if(await Vencord.Api.MessageEvents._handlePreSend(...arguments))return;" match: /\beditMessage:(function\(.+?\))\{/,
}, { // editMessage: async function (...) { await handlePreEdit(...); ...
match: /\beditMessage:(function\([^)]+\)){/,
replace: "editMessage:async $1{await Vencord.Api.MessageEvents._handlePreEdit(...arguments);" replace: "editMessage:async $1{await Vencord.Api.MessageEvents._handlePreEdit(...arguments);"
}] }
},
{
find: ".handleSendMessage=",
replacement: {
// props.chatInputType...then((function(isMessageValid)... var parsedMessage = b.c.parse(channel,... var replyOptions = f.g.getSendMessageOptionsForReply(pendingReply);
// Lookbehind: validateMessage)({openWarningPopout:..., type: i.props.chatInputType, content: t, stickers: r, ...}).then((function(isMessageValid)
match: /(props\.chatInputType.+?\.then\(\()(function.+?var (\i)=\i\.\i\.parse\((\i),.+?var (\i)=\i\.\i\.getSendMessageOptionsForReply\(\i\);)(?<=\)\(({.+?})\)\.then.+?)/,
// props.chatInputType...then((async function(isMessageValid)... var replyOptions = f.g.getSendMessageOptionsForReply(pendingReply); if(await Vencord.api...) return { shoudClear:true, shouldRefocus:true };
replace: (_, rest1, rest2, parsedMessage, channel, replyOptions, extra) => "" +
`${rest1}async ${rest2}` +
`if(await Vencord.Api.MessageEvents._handlePreSend(${channel}.id,${parsedMessage},${extra},${replyOptions}))` +
"return{shoudClear:true,shouldRefocus:true};"
}
}, },
{ {
find: '("interactionUsernameProfile', find: '("interactionUsernameProfile',

View File

@ -32,7 +32,7 @@ export default definePlugin({
} }
}, },
{ {
find: "Messages.SERVERS", find: "Messages.SERVERS,children",
replacement: { replacement: {
match: /(Messages\.SERVERS,children:)(.+?default:return null\}\}\)\))/, match: /(Messages\.SERVERS,children:)(.+?default:return null\}\}\)\))/,
replace: "$1Vencord.Api.ServerList.renderAll(Vencord.Api.ServerList.ServerListRenderPosition.In).concat($2)" replace: "$1Vencord.Api.ServerList.renderAll(Vencord.Api.ServerList.ServerListRenderPosition.In).concat($2)"

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 { Settings } from "@api/settings"; import { Settings } from "@api/Settings";
import { classNameFactory } from "@api/Styles"; import { classNameFactory } from "@api/Styles";
import ErrorBoundary from "@components/ErrorBoundary"; import ErrorBoundary from "@components/ErrorBoundary";
import { findByPropsLazy, findStoreLazy } from "@webpack"; import { findByPropsLazy, findStoreLazy } from "@webpack";

View File

@ -18,7 +18,7 @@
import "./betterFolders.css"; import "./betterFolders.css";
import { definePluginSettings } from "@api/settings"; import { definePluginSettings } from "@api/Settings";
import { Devs } from "@utils/constants"; import { Devs } from "@utils/constants";
import definePlugin, { OptionType } from "@utils/types"; import definePlugin, { OptionType } from "@utils/types";
import { findByPropsLazy, findLazy, findStoreLazy } from "@webpack"; import { findByPropsLazy, findLazy, findStoreLazy } from "@webpack";

View File

@ -16,9 +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 { Settings } from "@api/settings"; import { Settings } from "@api/Settings";
import { Devs } from "@utils/constants"; import { Devs } from "@utils/constants";
import { makeLazy } from "@utils/misc";
import definePlugin, { OptionType } from "@utils/types"; import definePlugin, { OptionType } from "@utils/types";
export default definePlugin({ export default definePlugin({
@ -30,7 +29,7 @@ export default definePlugin({
{ {
find: "hideNote:", find: "hideNote:",
all: true, all: true,
predicate: makeLazy(() => Vencord.Settings.plugins.BetterNotesBox.hide), predicate: () => Vencord.Settings.plugins.BetterNotesBox.hide,
replacement: { replacement: {
match: /hideNote:.+?(?=[,}])/g, match: /hideNote:.+?(?=[,}])/g,
replace: "hideNote:true", replace: "hideNote:true",

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 { Settings } from "@api/settings"; import { 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 { Clipboard, Toasts } from "@webpack/common"; import { Clipboard, Toasts } from "@webpack/common";

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 { Settings } from "@api/settings"; import { 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";

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 { Settings } from "@api/settings"; 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";

View File

@ -17,9 +17,9 @@
*/ */
import { showNotification } from "@api/Notifications"; import { showNotification } from "@api/Notifications";
import { definePluginSettings } from "@api/settings"; import { definePluginSettings } from "@api/Settings";
import { Devs } from "@utils/constants"; import { Devs } from "@utils/constants";
import Logger from "@utils/Logger"; import { Logger } from "@utils/Logger";
import { closeAllModals } from "@utils/modal"; import { closeAllModals } from "@utils/modal";
import definePlugin, { OptionType } from "@utils/types"; import definePlugin, { OptionType } from "@utils/types";
import { maybePromptToUpdate } from "@utils/updater"; import { maybePromptToUpdate } from "@utils/updater";

View File

@ -16,11 +16,11 @@
* 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 { definePluginSettings } from "@api/settings"; import { definePluginSettings } from "@api/Settings";
import { Link } from "@components/Link"; import { Link } from "@components/Link";
import { Devs } from "@utils/constants"; import { Devs } from "@utils/constants";
import { isTruthy } from "@utils/guards"; import { isTruthy } from "@utils/guards";
import { useAwaiter } from "@utils/misc"; import { useAwaiter } from "@utils/react";
import definePlugin, { OptionType } from "@utils/types"; import definePlugin, { OptionType } from "@utils/types";
import { filters, findByCodeLazy, findByPropsLazy, mapMangledModuleLazy } from "@webpack"; import { filters, findByCodeLazy, findByPropsLazy, mapMangledModuleLazy } from "@webpack";
import { import {

View File

@ -16,15 +16,13 @@
* 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 { addContextMenuPatch, NavContextMenuPatchCallback, removeContextMenuPatch } from "@api/ContextMenu";
import { showNotification } from "@api/Notifications"; import { showNotification } from "@api/Notifications";
import { definePluginSettings } from "@api/settings"; import { definePluginSettings } from "@api/Settings";
import { Devs } from "@utils/constants"; import { Devs } from "@utils/constants";
import Logger from "@utils/Logger"; import { Logger } from "@utils/Logger";
import { canonicalizeMatch, canonicalizeReplace } from "@utils/patches"; import { canonicalizeMatch, canonicalizeReplace } from "@utils/patches";
import definePlugin, { OptionType } from "@utils/types"; import definePlugin, { OptionType } from "@utils/types";
import { filters, findAll, search } from "@webpack"; import { filters, findAll, search } from "@webpack";
import { Menu } from "@webpack/common";
const PORT = 8485; const PORT = 8485;
const NAV_ID = "dev-companion-reconnect"; const NAV_ID = "dev-companion-reconnect";
@ -238,33 +236,25 @@ function initWs(isManual = false) {
}); });
} }
const contextMenuPatch: NavContextMenuPatchCallback = children => () => {
children.unshift(
<Menu.MenuItem
id={NAV_ID}
label="Reconnect Dev Companion"
action={() => {
socket?.close(1000, "Reconnecting");
initWs(true);
}}
/>
);
};
export default definePlugin({ export default definePlugin({
name: "DevCompanion", name: "DevCompanion",
description: "Dev Companion Plugin", description: "Dev Companion Plugin",
authors: [Devs.Ven], authors: [Devs.Ven],
settings, settings,
toolboxActions: {
"Reconnect"() {
socket?.close(1000, "Reconnecting");
initWs(true);
}
},
start() { start() {
initWs(); initWs();
addContextMenuPatch("user-settings-cog", contextMenuPatch);
}, },
stop() { stop() {
socket?.close(1000, "Plugin Stopped"); socket?.close(1000, "Plugin Stopped");
socket = void 0; socket = void 0;
removeContextMenuPatch("user-settings-cog", contextMenuPatch);
} }
}); });

View File

@ -19,19 +19,103 @@
import { addContextMenuPatch, findGroupChildrenByChildId, NavContextMenuPatchCallback, removeContextMenuPatch } from "@api/ContextMenu"; import { addContextMenuPatch, findGroupChildrenByChildId, NavContextMenuPatchCallback, removeContextMenuPatch } from "@api/ContextMenu";
import { CheckedTextInput } from "@components/CheckedTextInput"; 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 { EmojiStore, 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 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,8 +123,12 @@ 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 } = EmojiStore.getGuilds()[g.id];
let count = 0; let count = 0;
for (const emoji of emojis) for (const emoji of emojis)
@ -49,33 +137,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,22 +175,26 @@ 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)) (data.t === "Emoji" && v.length > 2 && v.length < 32 && nameValidator.test(v))
|| (data.t === "Sticker" && v.length > 2 && v.length < 30)
|| "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

@ -16,8 +16,11 @@
* 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 { definePluginSettings } from "@api/settings"; import { definePluginSettings } from "@api/Settings";
import ErrorBoundary from "@components/ErrorBoundary";
import { ErrorCard } from "@components/ErrorCard";
import { Devs } from "@utils/constants"; import { Devs } from "@utils/constants";
import { Margins } from "@utils/margins";
import definePlugin, { OptionType } from "@utils/types"; import definePlugin, { OptionType } from "@utils/types";
import { findByPropsLazy } from "@webpack"; import { findByPropsLazy } from "@webpack";
import { Forms, React } from "@webpack/common"; import { Forms, React } from "@webpack/common";
@ -87,6 +90,13 @@ export default definePlugin({
match: /"staging"===window\.GLOBAL_ENV\.RELEASE_CHANNEL/, match: /"staging"===window\.GLOBAL_ENV\.RELEASE_CHANNEL/,
replace: "true" replace: "true"
} }
},
{
find: 'H1,title:"Experiments"',
replacement: {
match: 'title:"Experiments",children:[',
replace: "$&$self.WarningCard(),"
}
} }
], ],
@ -109,5 +119,19 @@ export default definePlugin({
</Forms.FormText> </Forms.FormText>
</React.Fragment> </React.Fragment>
); );
} },
WarningCard: ErrorBoundary.wrap(() => (
<ErrorCard id="vc-experiments-warning-card" className={Margins.bottom16}>
<Forms.FormTitle tag="h2">Hold on!!</Forms.FormTitle>
<Forms.FormText>
Experiments are unreleased Discord features. They might not work, or even break your client or get your account disabled.
</Forms.FormText>
<Forms.FormText className={Margins.top8}>
Only use experiments if you know what you're doing. Vencord is not responsible for any damage caused by enabling experiments.
</Forms.FormText>
</ErrorCard>
), { noop: true })
}); });

View File

@ -17,14 +17,14 @@
*/ */
import { addPreEditListener, addPreSendListener, removePreEditListener, removePreSendListener } from "@api/MessageEvents"; import { addPreEditListener, addPreSendListener, removePreEditListener, removePreSendListener } from "@api/MessageEvents";
import { definePluginSettings, Settings } from "@api/settings"; import { definePluginSettings, Settings } from "@api/Settings";
import { Devs } from "@utils/constants"; import { Devs } from "@utils/constants";
import { ApngBlendOp, ApngDisposeOp, getGifEncoder, importApngJs } from "@utils/dependencies"; import { ApngBlendOp, ApngDisposeOp, getGifEncoder, importApngJs } from "@utils/dependencies";
import { getCurrentGuild } from "@utils/discord"; import { getCurrentGuild } from "@utils/discord";
import { proxyLazy } from "@utils/proxyLazy"; import { proxyLazy } from "@utils/lazy";
import definePlugin, { OptionType } from "@utils/types"; import definePlugin, { OptionType } from "@utils/types";
import { findByCodeLazy, findByPropsLazy, findLazy, findStoreLazy } from "@webpack"; import { findByCodeLazy, findByPropsLazy, findLazy, findStoreLazy } from "@webpack";
import { ChannelStore, FluxDispatcher, Parser, PermissionStore, UserStore } from "@webpack/common"; import { ChannelStore, EmojiStore, FluxDispatcher, Parser, PermissionStore, UserStore } from "@webpack/common";
import type { Message } from "discord-types/general"; import type { Message } from "discord-types/general";
import type { ReactNode } from "react"; import type { ReactNode } from "react";
@ -38,8 +38,6 @@ const StickerStore = findStoreLazy("StickersStore") as {
getAllGuildStickers(): Map<string, Sticker[]>; getAllGuildStickers(): Map<string, Sticker[]>;
getStickerById(id: string): Sticker | undefined; getStickerById(id: string): Sticker | undefined;
}; };
const EmojiStore = findStoreLazy("EmojiStore");
function searchProtoClass(localName: string, parentProtoClass: any) { function searchProtoClass(localName: string, parentProtoClass: any) {
if (!parentProtoClass) return; if (!parentProtoClass) return;
@ -57,7 +55,7 @@ const ClientThemeSettingsProto = proxyLazy(() => searchProtoClass("clientThemeSe
const USE_EXTERNAL_EMOJIS = 1n << 18n; const USE_EXTERNAL_EMOJIS = 1n << 18n;
const USE_EXTERNAL_STICKERS = 1n << 37n; const USE_EXTERNAL_STICKERS = 1n << 37n;
enum EmojiIntentions { const enum EmojiIntentions {
REACTION = 0, REACTION = 0,
STATUS = 1, STATUS = 1,
COMMUNITY_CONTENT = 2, COMMUNITY_CONTENT = 2,
@ -68,6 +66,14 @@ enum EmojiIntentions {
SOUNDBOARD = 7 SOUNDBOARD = 7
} }
const enum StickerType {
PNG = 1,
APNG = 2,
LOTTIE = 3,
// don't think you can even have gif stickers but the docs have it
GIF = 4
}
interface BaseSticker { interface BaseSticker {
available: boolean; available: boolean;
description: string; description: string;
@ -173,6 +179,10 @@ export default definePlugin({
{ {
match: /(&&!\i&&)!(\i)(?=\)return \i\.\i\.DISALLOW_EXTERNAL;)/, match: /(&&!\i&&)!(\i)(?=\)return \i\.\i\.DISALLOW_EXTERNAL;)/,
replace: (_, rest, canUseExternal) => `${rest}(!${canUseExternal}&&(typeof fakeNitroIntention==="undefined"||![${EmojiIntentions.CHAT},${EmojiIntentions.GUILD_STICKER_RELATED_EMOJI}].includes(fakeNitroIntention)))` replace: (_, rest, canUseExternal) => `${rest}(!${canUseExternal}&&(typeof fakeNitroIntention==="undefined"||![${EmojiIntentions.CHAT},${EmojiIntentions.GUILD_STICKER_RELATED_EMOJI}].includes(fakeNitroIntention)))`
},
{
match: /if\(!\i\.available/,
replace: m => `${m}&&(typeof fakeNitroIntention==="undefined"||![${EmojiIntentions.CHAT},${EmojiIntentions.GUILD_STICKER_RELATED_EMOJI}].includes(fakeNitroIntention))`
} }
] ]
}, },
@ -321,7 +331,7 @@ export default definePlugin({
}, },
handleProtoChange(proto: any, user: any) { handleProtoChange(proto: any, user: any) {
if ((!proto.appearance && !AppearanceSettingsProto) || !UserSettingsProtoStore) return; if (proto == null || typeof proto === "string" || !UserSettingsProtoStore || (!proto.appearance && !AppearanceSettingsProto)) return;
const premiumType: number = user?.premium_type ?? UserStore?.getCurrentUser()?.premiumType ?? 0; const premiumType: number = user?.premium_type ?? UserStore?.getCurrentUser()?.premiumType ?? 0;
@ -544,7 +554,7 @@ export default definePlugin({
} }
}, },
hasPermissionToUseExternalEmojis(channelId: string) { hasPermissionToUseExternalEmojis(channelId: string): boolean {
const channel = ChannelStore.getChannel(channelId); const channel = ChannelStore.getChannel(channelId);
if (!channel || channel.isDM() || channel.isGroupDM() || channel.isMultiUserDM()) return true; if (!channel || channel.isDM() || channel.isGroupDM() || channel.isMultiUserDM()) return true;
@ -625,8 +635,9 @@ export default definePlugin({
}, },
start() { start() {
const settings = Settings.plugins.FakeNitro; const s = settings.store;
if (!settings.enableEmojiBypass && !settings.enableStickerBypass) {
if (!s.enableEmojiBypass && !s.enableStickerBypass) {
return; return;
} }
@ -638,39 +649,37 @@ export default definePlugin({
const { guildId } = this; const { guildId } = this;
stickerBypass: { stickerBypass: {
if (!settings.enableStickerBypass) if (!s.enableStickerBypass)
break stickerBypass; break stickerBypass;
const sticker = StickerStore.getStickerById(extra?.stickerIds?.[0]!); const sticker = StickerStore.getStickerById(extra.stickers?.[0]!);
if (!sticker) if (!sticker)
break stickerBypass; break stickerBypass;
if (sticker.available !== false && ((this.canUseStickers && this.hasPermissionToUseExternalStickers(channelId)) || (sticker as GuildSticker)?.guild_id === guildId)) // Discord Stickers are now free yayyy!! :D
if ("pack_id" in sticker)
break stickerBypass; break stickerBypass;
let link = this.getStickerLink(sticker.id); const canUseStickers = this.canUseStickers && this.hasPermissionToUseExternalStickers(channelId);
if (sticker.format_type === 2) { if (sticker.available !== false && (canUseStickers || sticker.guild_id === guildId))
break stickerBypass;
const link = this.getStickerLink(sticker.id);
if (sticker.format_type === StickerType.APNG) {
this.sendAnimatedSticker(link, sticker.id, channelId); this.sendAnimatedSticker(link, sticker.id, channelId);
return { cancel: true }; return { cancel: true };
} else { } else {
if ("pack_id" in sticker) { extra.stickers!.length = 0;
const packId = sticker.pack_id === "847199849233514549" messageObj.content += ` ${link}&name=${encodeURIComponent(sticker.name)}`;
// Discord moved these stickers into a different pack at some point, but
// Distok still uses the old id
? "749043879713701898"
: sticker.pack_id;
link = `https://distok.top/stickers/${packId}/${sticker.id}.gif`;
}
delete extra.stickerIds;
messageObj.content += " " + link + `&name=${encodeURIComponent(sticker.name)}`;
} }
} }
if ((!this.canUseEmotes || !this.hasPermissionToUseExternalEmojis(channelId)) && settings.enableEmojiBypass) { if (s.enableEmojiBypass) {
const canUseEmotes = this.canUseEmotes && this.hasPermissionToUseExternalEmojis(channelId);
for (const emoji of messageObj.validNonShortcutEmojis) { for (const emoji of messageObj.validNonShortcutEmojis) {
if (!emoji.require_colons) continue; if (!emoji.require_colons) continue;
if (emoji.available !== false && canUseEmotes) continue;
if (emoji.guildId === guildId && !emoji.animated) continue; if (emoji.guildId === guildId && !emoji.animated) continue;
const emojiString = `<${emoji.animated ? "a" : ""}:${emoji.originalName || emoji.name}:${emoji.id}>`; const emojiString = `<${emoji.animated ? "a" : ""}:${emoji.originalName || emoji.name}:${emoji.id}>`;
@ -688,23 +697,25 @@ export default definePlugin({
}); });
this.preEdit = addPreEditListener((channelId, __, messageObj) => { this.preEdit = addPreEditListener((channelId, __, messageObj) => {
if (this.canUseEmotes && this.hasPermissionToUseExternalEmojis(channelId)) return; if (!s.enableEmojiBypass) return;
const canUseEmotes = this.canUseEmotes && this.hasPermissionToUseExternalEmojis(channelId);
const { guildId } = this; const { guildId } = this;
for (const [emojiStr, _, emojiId] of messageObj.content.matchAll(/(?<!\\)<a?:(\w+):(\d+)>/ig)) { messageObj.content = messageObj.content.replace(/(?<!\\)<a?:(?:\w+):(\d+)>/ig, (emojiStr, emojiId, offset, origStr) => {
const emoji = EmojiStore.getCustomEmojiById(emojiId); const emoji = EmojiStore.getCustomEmojiById(emojiId);
if (emoji == null || (emoji.guildId === guildId && !emoji.animated)) continue; if (emoji == null) return emojiStr;
if (!emoji.require_colons) continue; if (!emoji.require_colons) return emojiStr;
if (emoji.available !== false && canUseEmotes) return emojiStr;
if (emoji.guildId === guildId && !emoji.animated) return emojiStr;
const url = emoji.url.replace(/\?size=\d+/, "?" + new URLSearchParams({ const url = emoji.url.replace(/\?size=\d+/, "?" + new URLSearchParams({
size: Settings.plugins.FakeNitro.emojiSize, size: Settings.plugins.FakeNitro.emojiSize,
name: encodeURIComponent(emoji.name) name: encodeURIComponent(emoji.name)
})); }));
messageObj.content = messageObj.content.replace(emojiStr, (match, offset, origStr) => { return `${getWordBoundary(origStr, offset - 1)}${url}${getWordBoundary(origStr, offset + emojiStr.length)}`;
return `${getWordBoundary(origStr, offset - 1)}${url}${getWordBoundary(origStr, offset + match.length)}`;
}); });
}
}); });
}, },

View File

@ -17,7 +17,7 @@
*/ */
// This plugin is a port from Alyxia's Vendetta plugin // This plugin is a port from Alyxia's Vendetta plugin
import { definePluginSettings } from "@api/settings"; import { definePluginSettings } from "@api/Settings";
import ErrorBoundary from "@components/ErrorBoundary"; import ErrorBoundary from "@components/ErrorBoundary";
import { Devs } from "@utils/constants"; import { Devs } from "@utils/constants";
import { Margins } from "@utils/margins"; import { Margins } from "@utils/margins";

View File

@ -17,7 +17,7 @@
*/ */
import { ApplicationCommandOptionType } from "@api/Commands"; import { ApplicationCommandOptionType } from "@api/Commands";
import { Settings } from "@api/settings"; import { Settings } from "@api/Settings";
import { makeRange } from "@components/PluginSettings/components"; import { makeRange } from "@components/PluginSettings/components";
import { Devs } from "@utils/constants"; import { Devs } from "@utils/constants";
import definePlugin, { OptionType } from "@utils/types"; import definePlugin, { OptionType } from "@utils/types";

View File

@ -0,0 +1,83 @@
/*
* 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 { Devs } from "@utils/constants";
import definePlugin from "@utils/types";
import { EmojiStore } from "@webpack/common";
import { Emoji } from "@webpack/types";
interface EmojiAutocompleteState {
query?: {
type: string;
typeInfo: {
sentinel: string;
};
results: {
emojis: Emoji[] & { sliceTo?: number; };
};
};
}
export default definePlugin({
name: "FavoriteEmojiFirst",
authors: [Devs.Aria, Devs.Ven],
description: "Puts your favorite emoji first in the emoji autocomplete.",
patches: [
{
find: ".activeCommandOption",
replacement: [
{
// = someFunc(a.selectedIndex); ...trackEmojiSearch({ state: theState, isInPopoutExperimental: someBool })
match: /=\i\(\i\.selectedIndex\);(?=.+?state:(\i),isInPopoutExperiment:\i)/,
// self.sortEmojis(theState)
replace: "$&$self.sortEmojis($1);"
},
// set maxCount to Infinity so our sortEmojis callback gets the entire list, not just the first 10
// and remove Discord's emojiResult slice, storing the endIndex on the array for us to use later
{
// searchEmojis(...,maxCount: stuff) ... endEmojis = emojis.slice(0, maxCount - gifResults.length)
match: /,maxCount:(\i)(.+?)=(\i)\.slice\(0,(\1-\i\.length)\)/,
// ,maxCount:Infinity ... endEmojis = (emojis.sliceTo = n, emojis)
replace: ",maxCount:Infinity$2=($3.sliceTo=$4,$3)"
}
]
}
],
sortEmojis({ query }: EmojiAutocompleteState) {
if (
query?.type !== "EMOJIS_AND_STICKERS"
|| query.typeInfo?.sentinel !== ":"
|| !query.results?.emojis?.length
) return;
const emojiContext = EmojiStore.getDisambiguatedEmojiContext();
query.results.emojis = query.results.emojis.sort((a, b) => {
const aIsFavorite = emojiContext.isFavoriteEmojiWithoutFetchingLatest(a);
const bIsFavorite = emojiContext.isFavoriteEmojiWithoutFetchingLatest(b);
if (aIsFavorite && !bIsFavorite) return -1;
if (!aIsFavorite && bIsFavorite) return 1;
return 0;
}).slice(0, query.results.emojis.sliceTo ?? 10);
}
});

View File

@ -19,7 +19,7 @@
import * as DataStore from "@api/DataStore"; import * as DataStore from "@api/DataStore";
import ErrorBoundary from "@components/ErrorBoundary"; import ErrorBoundary from "@components/ErrorBoundary";
import { Devs } from "@utils/constants"; import { Devs } from "@utils/constants";
import { useForceUpdater } from "@utils/misc"; import { useForceUpdater } from "@utils/react";
import definePlugin from "@utils/types"; import definePlugin from "@utils/types";
import { findByPropsLazy, findStoreLazy } from "@webpack"; import { findByPropsLazy, findStoreLazy } from "@webpack";
import { Tooltip } from "webpack/common"; import { Tooltip } from "webpack/common";

View File

@ -17,7 +17,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 { disableStyle, enableStyle } from "@api/Styles"; import { disableStyle, enableStyle } from "@api/Styles";
import { makeRange } from "@components/PluginSettings/components"; import { makeRange } from "@components/PluginSettings/components";
import { Devs } from "@utils/constants"; import { Devs } from "@utils/constants";
@ -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

@ -17,8 +17,8 @@
*/ */
import { registerCommand, unregisterCommand } from "@api/Commands"; import { registerCommand, unregisterCommand } from "@api/Commands";
import { Settings } from "@api/settings"; import { Settings } from "@api/Settings";
import Logger from "@utils/Logger"; import { Logger } from "@utils/Logger";
import { Patch, Plugin } from "@utils/types"; import { Patch, Plugin } from "@utils/types";
import { FluxDispatcher } from "@webpack/common"; import { FluxDispatcher } from "@webpack/common";
import { FluxEvents } from "@webpack/types"; import { FluxEvents } from "@webpack/types";
@ -99,9 +99,9 @@ export function startDependenciesRecursive(p: Plugin) {
if (!Settings.plugins[dep].enabled) { if (!Settings.plugins[dep].enabled) {
startDependenciesRecursive(Plugins[dep]); startDependenciesRecursive(Plugins[dep]);
// If the plugin has patches, don't start the plugin, just enable it. // If the plugin has patches, don't start the plugin, just enable it.
Settings.plugins[dep].enabled = true;
if (Plugins[dep].patches) { if (Plugins[dep].patches) {
logger.warn(`Enabling dependency ${dep} requires restart.`); logger.warn(`Enabling dependency ${dep} requires restart.`);
Settings.plugins[dep].enabled = true;
restartNeeded = true; restartNeeded = true;
return; return;
} }

View File

@ -17,12 +17,12 @@
*/ */
import { addButton, removeButton } from "@api/MessagePopover"; import { addButton, removeButton } from "@api/MessagePopover";
import { definePluginSettings } from "@api/settings"; import { definePluginSettings } from "@api/Settings";
import ErrorBoundary from "@components/ErrorBoundary"; import ErrorBoundary from "@components/ErrorBoundary";
import { Devs } from "@utils/constants"; import { Devs } from "@utils/constants";
import { getStegCloak } from "@utils/dependencies"; import { getStegCloak } from "@utils/dependencies";
import definePlugin, { OptionType } from "@utils/types"; import definePlugin, { OptionType } from "@utils/types";
import { Button, ButtonLooks, ButtonWrapperClasses, ChannelStore, FluxDispatcher, Tooltip } from "@webpack/common"; import { Button, ButtonLooks, ButtonWrapperClasses, ChannelStore, FluxDispatcher, RestAPI, Tooltip } from "@webpack/common";
import { Message } from "discord-types/general"; import { Message } from "discord-types/general";
import { buildDecModal } from "./components/DecryptionModal"; import { buildDecModal } from "./components/DecryptionModal";
@ -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 }) => (
@ -85,7 +91,7 @@ function ChatBarIcon() {
onMouseLeave={onMouseLeave} onMouseLeave={onMouseLeave}
innerClassName={ButtonWrapperClasses.button} innerClassName={ButtonWrapperClasses.button}
onClick={() => buildEncModal()} onClick={() => buildEncModal()}
style={{ padding: "0 4px" }} style={{ padding: "0 2px", scale: "0.9" }}
> >
<div className={ButtonWrapperClasses.buttonWrapper}> <div className={ButtonWrapperClasses.buttonWrapper}>
<svg <svg
@ -117,7 +123,7 @@ const settings = definePluginSettings({
export default definePlugin({ export default definePlugin({
name: "InvisibleChat", name: "InvisibleChat",
description: "Encrypt your Messages in a non-suspicious way! This plugin makes requests to >>https://embed.sammcheese.net<< to provide embeds to decrypted links!", description: "Encrypt your Messages in a non-suspicious way!",
authors: [Devs.SammCheese], authors: [Devs.SammCheese],
dependencies: ["MessagePopoverAPI"], dependencies: ["MessagePopoverAPI"],
patches: [ patches: [
@ -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{}",
} }
}, },
], ],
@ -172,25 +178,13 @@ export default definePlugin({
// Gets the Embed of a Link // Gets the Embed of a Link
async getEmbed(url: URL): Promise<Object | {}> { async getEmbed(url: URL): Promise<Object | {}> {
const controller = new AbortController(); const { body } = await RestAPI.post({
const timeout = setTimeout(() => controller.abort(), 5000); url: "/unfurler/embed-urls",
body: {
const options: RequestInit = { urls: [url]
signal: controller.signal, }
method: "POST", });
headers: { return await body.embeds[0];
"Content-Type": "application/json",
},
body: JSON.stringify({
url,
}),
};
// AWS hosted url to discord embed object
const rawRes = await fetch(this.EMBED_API_URL, options);
clearTimeout(timeout);
return await rawRes.json();
}, },
async buildEmbed(message: any, revealed: string): Promise<void> { async buildEmbed(message: any, revealed: string): Promise<void> {

View File

@ -16,10 +16,10 @@
* 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 { definePluginSettings } from "@api/settings"; import { definePluginSettings } from "@api/Settings";
import { Link } from "@components/Link"; import { Link } from "@components/Link";
import { Devs } from "@utils/constants"; import { Devs } from "@utils/constants";
import Logger from "@utils/Logger"; import { Logger } from "@utils/Logger";
import definePlugin, { OptionType } from "@utils/types"; import definePlugin, { OptionType } from "@utils/types";
import { filters, findByPropsLazy, mapMangledModuleLazy } from "@webpack"; import { filters, findByPropsLazy, mapMangledModuleLazy } from "@webpack";
import { FluxDispatcher, Forms } from "@webpack/common"; import { FluxDispatcher, Forms } from "@webpack/common";
@ -72,7 +72,7 @@ enum ActivityFlag {
INSTANCE = 1 << 0, INSTANCE = 1 << 0,
} }
const applicationId = "1043533871037284423"; const applicationId = "1108588077900898414";
const placeholderId = "2a96cbd8b46e442fc41c2b86b821562f"; const placeholderId = "2a96cbd8b46e442fc41c2b86b821562f";
const logger = new Logger("LastFMRichPresence"); const logger = new Logger("LastFMRichPresence");
@ -167,6 +167,7 @@ export default definePlugin({
settings, settings,
start() { start() {
this.updatePresence();
this.updateInterval = setInterval(() => { this.updatePresence(); }, 16000); this.updateInterval = setInterval(() => { this.updatePresence(); }, 16000);
}, },
@ -198,7 +199,7 @@ export default definePlugin({
const trackData = json.recenttracks?.track[0]; const trackData = json.recenttracks?.track[0];
if (!trackData || !trackData["@attr"]?.nowplaying) if (!trackData?.["@attr"]?.nowplaying)
return null; return null;
// why does the json api have xml structure // why does the json api have xml structure

View File

@ -20,31 +20,34 @@ import ErrorBoundary from "@components/ErrorBoundary";
import { Flex } from "@components/Flex"; import { Flex } from "@components/Flex";
import { Devs } from "@utils/constants"; import { Devs } from "@utils/constants";
import { getCurrentChannel } from "@utils/discord"; import { getCurrentChannel } from "@utils/discord";
import { useForceUpdater } from "@utils/misc";
import definePlugin from "@utils/types"; import definePlugin from "@utils/types";
import { findStoreLazy } from "@webpack"; import { findStoreLazy } from "@webpack";
import { Tooltip } from "@webpack/common"; import { SelectedChannelStore, Tooltip, useStateFromStores } from "@webpack/common";
import { FluxStore } from "@webpack/types";
const counts = {} as Record<string, [number, number]>; const GuildMemberCountStore = findStoreLazy("GuildMemberCountStore") as FluxStore & { getMemberCount(guildId: string): number | null; };
let forceUpdate: () => void; const ChannelMemberStore = findStoreLazy("ChannelMemberStore") as FluxStore & {
getProps(guildId: string, channelId: string): { groups: { count: number; id: string; }[]; };
const GuildMemberCountStore = findStoreLazy("GuildMemberCountStore"); };
function MemberCount() { function MemberCount() {
const guildId = getCurrentChannel().guild_id; const { id: channelId, guild_id: guildId } = useStateFromStores([SelectedChannelStore], () => getCurrentChannel());
const c = counts[guildId]; const { groups } = useStateFromStores(
[ChannelMemberStore],
() => ChannelMemberStore.getProps(guildId, channelId)
);
const total = useStateFromStores(
[GuildMemberCountStore],
() => GuildMemberCountStore.getMemberCount(guildId)
);
forceUpdate = useForceUpdater(); if (total == null)
return null;
if (!c) return null; const online =
(groups.length === 1 && groups[0].id === "unknown")
let total = c[0].toLocaleString(); ? 0
if (total === "0" && c[1] > 0) { : groups.reduce((count, curr) => count + (curr.id === "offline" ? 0 : curr.count), 0);
const approx = GuildMemberCountStore.getMemberCount(guildId);
total = approx ? approx.toLocaleString() : "Loading...";
}
const online = c[1].toLocaleString();
return ( return (
<Flex id="vc-membercount" style={{ <Flex id="vc-membercount" style={{
@ -55,7 +58,7 @@ function MemberCount() {
alignContent: "center", alignContent: "center",
gap: 0 gap: 0
}}> }}>
<Tooltip text={`${online} Online`} position="bottom"> <Tooltip text={`${online} Online in this Channel`} position="bottom">
{props => ( {props => (
<div {...props}> <div {...props}>
<span <span
@ -72,7 +75,7 @@ function MemberCount() {
</div> </div>
)} )}
</Tooltip> </Tooltip>
<Tooltip text={`${total} Total Members`} position="bottom"> <Tooltip text={`${total} Total Server Members`} position="bottom">
{props => ( {props => (
<div {...props}> <div {...props}>
<span <span
@ -102,31 +105,10 @@ export default definePlugin({
patches: [{ patches: [{
find: ".isSidebarVisible,", find: ".isSidebarVisible,",
replacement: { replacement: {
match: /(var (.)=.\.className.+?children):\[(.\.useMemo[^}]+"aria-multiselectable")/, match: /(var (\i)=\i\.className.+?children):\[(\i\.useMemo[^}]+"aria-multiselectable")/,
replace: "$1:[$2.startsWith('members')?$self.render():null,$3" replace: "$1:[$2.startsWith('members')?$self.render():null,$3"
} }
}], }],
flux: { render: ErrorBoundary.wrap(MemberCount, { noop: true })
GUILD_MEMBER_LIST_UPDATE({ guildId, groups, memberCount, id }) {
// eeeeeh - sometimes it has really wrong counts??? like 10 times less than actual
// but if we only listen to everyone updates, sometimes we never get the count?
// this seems to work but isn't optional
if (id !== "everyone" && counts[guildId]) return;
let count = 0;
for (const group of groups) {
if (group.id !== "offline")
count += group.count;
}
counts[guildId] = [memberCount, count];
forceUpdate?.();
}
},
render: () => (
<ErrorBoundary noop>
<MemberCount />
</ErrorBoundary>
)
}); });

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,12 @@
*/ */
import { addAccessory } from "@api/MessageAccessories"; import { addAccessory } from "@api/MessageAccessories";
import { definePluginSettings } from "@api/settings"; import { definePluginSettings } from "@api/Settings";
import ErrorBoundary from "@components/ErrorBoundary"; import ErrorBoundary from "@components/ErrorBoundary";
import { Devs } from "@utils/constants.js"; import { Devs } from "@utils/constants.js";
import { classes, LazyComponent } from "@utils/misc"; import { classes } from "@utils/misc";
import { Queue } from "@utils/Queue"; import { Queue } from "@utils/Queue";
import { LazyComponent } from "@utils/react";
import definePlugin, { OptionType } from "@utils/types"; import definePlugin, { OptionType } from "@utils/types";
import { find, findByCode, findByPropsLazy } from "@webpack"; import { find, findByCode, findByPropsLazy } from "@webpack";
import { import {

View File

@ -19,11 +19,11 @@
import "./messageLogger.css"; import "./messageLogger.css";
import { addContextMenuPatch, NavContextMenuPatchCallback, removeContextMenuPatch } from "@api/ContextMenu"; import { addContextMenuPatch, NavContextMenuPatchCallback, removeContextMenuPatch } from "@api/ContextMenu";
import { Settings } from "@api/settings"; import { Settings } from "@api/Settings";
import { disableStyle, enableStyle } from "@api/Styles"; import { disableStyle, enableStyle } from "@api/Styles";
import ErrorBoundary from "@components/ErrorBoundary"; import ErrorBoundary from "@components/ErrorBoundary";
import { Devs } from "@utils/constants"; import { Devs } from "@utils/constants";
import Logger from "@utils/Logger"; import { Logger } from "@utils/Logger";
import definePlugin, { OptionType } from "@utils/types"; import definePlugin, { OptionType } from "@utils/types";
import { findByPropsLazy } from "@webpack"; import { findByPropsLazy } from "@webpack";
import { FluxDispatcher, i18n, Menu, moment, Parser, Timestamp, UserStore } from "@webpack/common"; import { FluxDispatcher, i18n, Menu, moment, Parser, Timestamp, UserStore } from "@webpack/common";

View File

@ -18,7 +18,7 @@
import { ApplicationCommandInputType, ApplicationCommandOptionType, findOption, registerCommand, sendBotMessage, unregisterCommand } from "@api/Commands"; import { ApplicationCommandInputType, ApplicationCommandOptionType, findOption, registerCommand, sendBotMessage, unregisterCommand } from "@api/Commands";
import * as DataStore from "@api/DataStore"; import * as DataStore from "@api/DataStore";
import { Settings } from "@api/settings"; import { 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";

View File

@ -16,12 +16,14 @@
* 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 { 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/proxyLazy.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

@ -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 { definePluginSettings } from "@api/settings"; import { definePluginSettings } from "@api/Settings";
import { makeRange } from "@components/PluginSettings/components/SettingSliderComponent"; import { makeRange } from "@components/PluginSettings/components/SettingSliderComponent";
import { Devs } from "@utils/constants"; import { Devs } from "@utils/constants";
import { sleep } from "@utils/misc"; import { sleep } from "@utils/misc";

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 { definePluginSettings } from "@api/settings"; import { definePluginSettings } from "@api/Settings";
import { Devs } from "@utils/constants"; import { Devs } from "@utils/constants";
import { ModalContent, ModalFooter, ModalProps, ModalRoot, ModalSize, openModal } from "@utils/modal"; import { ModalContent, ModalFooter, ModalProps, ModalRoot, ModalSize, openModal } from "@utils/modal";
import definePlugin, { OptionType } from "@utils/types"; import definePlugin, { OptionType } from "@utils/types";

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 { Settings } from "@api/settings"; import { 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";

View File

@ -1,59 +0,0 @@
/*
* Vencord, a modification for Discord's desktop app
* Copyright (c) 2022 Samu and Linnea Gräf
*
* 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 { addPreSendListener, MessageObject, removePreSendListener } from "@api/MessageEvents";
import { Settings } from "@api/settings";
import { Devs } from "@utils/constants";
import definePlugin, { OptionType } from "@utils/types";
export default definePlugin({
name: "NoCanaryMessageLinks",
description: "Allows you to change/remove the subdomain of discord message and channel links",
authors: [Devs.Samu, Devs.nea],
options: {
linkPrefix: {
description: "The subdomain for your discord message links",
type: OptionType.STRING,
default: "",
restartNeeded: false,
},
alwaysUseDiscordHost: {
description: "Always use discord.com host (replace discordapp.com)",
type: OptionType.BOOLEAN,
default: false,
restartNeeded: false,
},
},
dependencies: ["MessageEventsAPI"],
removeBetas(msg: MessageObject) {
const settings = Settings.plugins.NoCanaryMessageLinks;
msg.content = msg.content.replace(
/https:\/\/(?:canary\.|ptb\.)?(discord(?:app)?\.com)(\/channels\/(?:\d{17,20}|@me)\/\d{17,20}(?:\/\d{17,20})?)/g,
(_, host, path) => "https://" + (settings.linkPrefix ? settings.linkPrefix + "." : "") + (settings.alwaysUseDiscordHost ? "discord.com" : host) + path
);
},
start() {
this.preSend = addPreSendListener((_, msg) => this.removeBetas(msg));
},
stop() {
removePreSendListener(this.preSend);
}
});

View File

@ -16,18 +16,33 @@
* 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 { definePluginSettings } from "@api/settings"; import { definePluginSettings } from "@api/Settings";
import { Devs } from "@utils/constants"; import { Devs } from "@utils/constants";
import definePlugin, { OptionType } from "@utils/types"; import definePlugin, { OptionType } from "@utils/types";
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;
}, },

105
src/plugins/partyMode.ts Normal file
View File

@ -0,0 +1,105 @@
/*
* 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 { definePluginSettings } from "@api/Settings";
import { Devs } from "@utils/constants";
import definePlugin, { OptionType } from "@utils/types";
import { findStoreLazy } from "@webpack";
import { GenericStore } from "@webpack/common";
const PoggerModeSettingsStore: GenericStore = findStoreLazy("PoggermodeSettingsStore");
const enum Intensity {
Normal,
Better,
ProjectX,
}
const settings = definePluginSettings({
superIntensePartyMode: {
description: "Party intensity",
type: OptionType.SELECT,
options: [
{ label: "Normal", value: Intensity.Normal, default: true },
{ label: "Better", value: Intensity.Better },
{ label: "Project X", value: Intensity.ProjectX },
],
restartNeeded: false,
onChange: setSettings
},
});
export default definePlugin({
name: "Party mode 🎉",
description: "Allows you to use party mode cause the party never ends ✨",
authors: [Devs.UwUDev],
settings,
start() {
setPoggerState(true);
setSettings(settings.store.superIntensePartyMode);
},
stop() {
setPoggerState(false);
},
});
function setPoggerState(state: boolean) {
Object.assign(PoggerModeSettingsStore.__getLocalVars().state, {
enabled: state,
settingsVisible: state
});
}
function setSettings(intensity: Intensity) {
const state = {
screenshakeEnabledLocations: { 0: true, 1: true, 2: true },
shakeIntensity: 1,
confettiSize: 16,
confettiCount: 5,
combosRequiredCount: 1
};
switch (intensity) {
case Intensity.Normal: {
Object.assign(state, {
screenshakeEnabledLocations: { 0: true, 1: false, 2: false },
combosRequiredCount: 5
});
break;
}
case Intensity.Better: {
Object.assign(state, {
confettiSize: 12,
confettiCount: 8,
});
break;
}
case Intensity.ProjectX: {
Object.assign(state, {
shakeIntensity: 20,
confettiSize: 25,
confettiCount: 15,
});
break;
}
}
Object.assign(PoggerModeSettingsStore.__getLocalVars().state, state);
}

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,197 @@
/*
* 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 { PermissionsSortOrder, 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 stns = settings.use(["permissionsSortOrder"]);
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];
}, [stns.permissionsSortOrder]);
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 className={cl("userperms-btns-container")}>
<Tooltip text={`Sorting by ${stns.permissionsSortOrder === PermissionsSortOrder.HighestRole ? "Highest Role" : "Lowest Role"}`}>
{tooltipProps => (
<button
{...tooltipProps}
className={cl("userperms-sortorder-btn")}
onClick={() => {
stns.permissionsSortOrder = stns.permissionsSortOrder === PermissionsSortOrder.HighestRole ? PermissionsSortOrder.LowestRole : PermissionsSortOrder.HighestRole;
}}
>
<svg
width="20"
height="20"
viewBox="0 96 960 960"
transform={stns.permissionsSortOrder === PermissionsSortOrder.HighestRole ? "scale(1 1)" : "scale(1 -1)"}
>
<path fill="var(--text-normal)" d="M440 896V409L216 633l-56-57 320-320 320 320-56 57-224-224v487h-80Z" />
</svg>
</button>
)}
</Tooltip>
<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,189 @@
/*
* 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, sortPermissionOverwrites } 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) {
if (type === MenuItemParentType.User && !GuildMemberStore.isMember(guildId, id!)) return null;
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 = sortPermissionOverwrites(Object.values(channel.permissionOverwrites).map(({ id, allow, deny, type }) => ({
type: type as PermissionType,
id,
overwriteAllow: allow,
overwriteDeny: deny
})), guildId);
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 | string[], type?: MenuItemParentType): NavContextMenuPatchCallback {
return (children, props) => () => {
if (!props) return children;
const group = findGroupChildrenByChildId(childId, children);
const item = (() => {
switch (type) {
case MenuItemParentType.User:
return MenuItem(props.guildId, props.user.id, type);
case MenuItemParentType.Channel:
return MenuItem(props.guild.id, props.channel.id, type);
case MenuItemParentType.Guild:
return MenuItem(props.guild.id);
default:
return null;
}
})();
if (item == null) return;
if (group)
group.push(item);
else if (childId === "roles" && props.guildId)
// "roles" may not be present due to the member not having any roles. In that case, add it above "Copy ID"
children.splice(-1, 0, <Menu.MenuGroup>{item}</Menu.MenuGroup>);
};
}
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) => !!guildMember && <UserPermissions guild={guild} guildMember={guildMember} />,
userContextMenuPatch: makeContextMenuPatch("roles", MenuItemParentType.User),
channelContextMenuPatch: makeContextMenuPatch(["mute-channel", "unmute-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,146 @@
/* User Permissions Component */
.vc-permviewer-userperms-title-container {
display: flex;
justify-content: space-between;
align-items: center;
margin-top: 10px;
margin-bottom: 6px;
}
.vc-permviewer-userperms-btns-container {
display: flex;
align-items: center;
}
.vc-permviewer-userperms-sortorder-btn {
all: unset;
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
width: 24px;
height: 24px;
}
.vc-permviewer-userperms-permdetails-btn {
all: unset;
cursor: pointer;
display: flex;
align-items: center;
}
.vc-permviewer-userperms-toggleperms-btn {
all: unset;
cursor: pointer;
display: flex;
align-items: center;
}
/* 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: 230px;
}
.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: 24px;
height: 24px;
margin-right: 5px;
}
.vc-permviewer-perms-perms-item .vc-info-icon {
color: var(--interactive-muted);
cursor: pointer;
position: absolute;
right: 0;
scale: 0.9;
transition: color ease-in 0.1s;
}
.vc-permviewer-perms-perms-item .vc-info-icon:hover {
color: var(--interactive-active);
}

View File

@ -0,0 +1,98 @@
/*
* 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 { GuildStore, i18n, Parser } from "@webpack/common";
import { Guild, GuildMember, Role } from "discord-types/general";
import type { ReactNode } from "react";
import { PermissionsSortOrder, settings } from ".";
import { PermissionType } from "./components/RolesAndUsersPermissions";
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;
}
}
export function sortPermissionOverwrites<T extends { id: string; type: number; }>(overwrites: T[], guildId: string) {
const guild = GuildStore.getGuild(guildId);
return overwrites.sort((a, b) => {
if (a.type !== PermissionType.Role || b.type !== PermissionType.Role) return 0;
const roleA = guild.roles[a.id];
const roleB = guild.roles[b.id];
return roleB.position - roleA.position;
});
}

View File

@ -19,7 +19,7 @@
import { ApplicationCommandInputType, ApplicationCommandOptionType, Argument, CommandContext, findOption, sendBotMessage } from "@api/Commands"; import { ApplicationCommandInputType, ApplicationCommandOptionType, Argument, CommandContext, findOption, sendBotMessage } from "@api/Commands";
import { Devs } from "@utils/constants"; import { Devs } from "@utils/constants";
import { getGifEncoder } from "@utils/dependencies"; import { getGifEncoder } from "@utils/dependencies";
import { makeLazy } from "@utils/misc"; import { makeLazy } from "@utils/lazy";
import definePlugin from "@utils/types"; import definePlugin from "@utils/types";
import { findByCodeLazy, findByPropsLazy } from "@webpack"; import { findByCodeLazy, findByPropsLazy } from "@webpack";

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 { definePluginSettings, Settings, useSettings } from "@api/settings"; import { definePluginSettings, Settings, useSettings } from "@api/Settings";
import { OptionType } from "@utils/types"; import { OptionType } from "@utils/types";
import { findStoreLazy } from "@webpack"; import { findStoreLazy } from "@webpack";

View File

@ -19,7 +19,7 @@
import { addBadge, BadgePosition, ProfileBadge, removeBadge } from "@api/Badges"; import { addBadge, BadgePosition, ProfileBadge, removeBadge } from "@api/Badges";
import { addDecorator, removeDecorator } from "@api/MemberListDecorators"; import { addDecorator, removeDecorator } from "@api/MemberListDecorators";
import { addDecoration, removeDecoration } from "@api/MessageDecorations"; import { addDecoration, removeDecoration } from "@api/MessageDecorations";
import { Settings } from "@api/settings"; 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";
@ -29,15 +29,15 @@ 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, opts?: { viewBox?: string; width?: number; height?: number; }) {
return ({ color, tooltip }: { color: string; tooltip: string; }) => ( return ({ color, tooltip }: { color: string; tooltip: string; }) => (
<Tooltip text={tooltip} > <Tooltip text={tooltip} >
{(tooltipProps: any) => ( {(tooltipProps: any) => (
<svg <svg
{...tooltipProps} {...tooltipProps}
height="20" height={opts?.height ?? 20}
width="20" width={opts?.width ?? 20}
viewBox={viewBox} viewBox={opts?.viewBox ?? "0 0 24 24"}
fill={color} fill={color}
> >
<path d={path} /> <path d={path} />
@ -50,8 +50,8 @@ function Icon(path: string, viewBox = "0 0 24 24") {
const Icons = { const Icons = {
desktop: Icon("M4 2.5c-1.103 0-2 .897-2 2v11c0 1.104.897 2 2 2h7v2H7v2h10v-2h-4v-2h7c1.103 0 2-.896 2-2v-11c0-1.103-.897-2-2-2H4Zm16 2v9H4v-9h16Z"), desktop: Icon("M4 2.5c-1.103 0-2 .897-2 2v11c0 1.104.897 2 2 2h7v2H7v2h10v-2h-4v-2h7c1.103 0 2-.896 2-2v-11c0-1.103-.897-2-2-2H4Zm16 2v9H4v-9h16Z"),
web: Icon("M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2Zm-1 17.93c-3.95-.49-7-3.85-7-7.93 0-.62.08-1.21.21-1.79L9 15v1c0 1.1.9 2 2 2v1.93Zm6.9-2.54c-.26-.81-1-1.39-1.9-1.39h-1v-3c0-.55-.45-1-1-1H8v-2h2c.55 0 1-.45 1-1V7h2c1.1 0 2-.9 2-2v-.41c2.93 1.19 5 4.06 5 7.41 0 2.08-.8 3.97-2.1 5.39Z"), web: Icon("M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2Zm-1 17.93c-3.95-.49-7-3.85-7-7.93 0-.62.08-1.21.21-1.79L9 15v1c0 1.1.9 2 2 2v1.93Zm6.9-2.54c-.26-.81-1-1.39-1.9-1.39h-1v-3c0-.55-.45-1-1-1H8v-2h2c.55 0 1-.45 1-1V7h2c1.1 0 2-.9 2-2v-.41c2.93 1.19 5 4.06 5 7.41 0 2.08-.8 3.97-2.1 5.39Z"),
mobile: Icon("M15.5 1h-8A2.5 2.5 0 0 0 5 3.5v17A2.5 2.5 0 0 0 7.5 23h8a2.5 2.5 0 0 0 2.5-2.5v-17A2.5 2.5 0 0 0 15.5 1zm-4 21c-.83 0-1.5-.67-1.5-1.5s.67-1.5 1.5-1.5 1.5.67 1.5 1.5-.67 1.5-1.5 1.5zm4.5-4H7V4h9v14z"), mobile: Icon("M 187 0 L 813 0 C 916.277 0 1000 83.723 1000 187 L 1000 1313 C 1000 1416.277 916.277 1500 813 1500 L 187 1500 C 83.723 1500 0 1416.277 0 1313 L 0 187 C 0 83.723 83.723 0 187 0 Z M 125 1000 L 875 1000 L 875 250 L 125 250 Z M 500 1125 C 430.964 1125 375 1180.964 375 1250 C 375 1319.036 430.964 1375 500 1375 C 569.036 1375 625 1319.036 625 1250 C 625 1180.964 569.036 1125 500 1125 Z", { viewBox: "0 0 1000 1500", height: 17, width: 17 }),
console: Icon("M14.8 2.7 9 3.1V47h3.3c1.7 0 6.2.3 10 .7l6.7.6V2l-4.2.2c-2.4.1-6.9.3-10 .5zm1.8 6.4c1 1.7-1.3 3.6-2.7 2.2C12.7 10.1 13.5 8 15 8c.5 0 1.2.5 1.6 1.1zM16 33c0 6-.4 10-1 10s-1-4-1-10 .4-10 1-10 1 4 1 10zm15-8v23.3l3.8-.7c2-.3 4.7-.6 6-.6H43V3h-2.2c-1.3 0-4-.3-6-.6L31 1.7V25z", "0 0 50 50"), console: Icon("M14.8 2.7 9 3.1V47h3.3c1.7 0 6.2.3 10 .7l6.7.6V2l-4.2.2c-2.4.1-6.9.3-10 .5zm1.8 6.4c1 1.7-1.3 3.6-2.7 2.2C12.7 10.1 13.5 8 15 8c.5 0 1.2.5 1.6 1.1zM16 33c0 6-.4 10-1 10s-1-4-1-10 .4-10 1-10 1 4 1 10zm15-8v23.3l3.8-.7c2-.3 4.7-.6 6-.6H43V3h-2.2c-1.3 0-4-.3-6-.6L31 1.7V25z", { viewBox: "0 0 50 50" }),
}; };
type Platform = keyof typeof Icons; type Platform = keyof typeof Icons;
@ -66,7 +66,7 @@ const PlatformIcon = ({ platform, status }: { platform: Platform, status: string
const getStatus = (id: string): Record<Platform, string> => PresenceStore.getState()?.clientStatuses?.[id]; const getStatus = (id: string): Record<Platform, string> => PresenceStore.getState()?.clientStatuses?.[id];
const PlatformIndicator = ({ user, inline = false, marginLeft = "4px" }: { user: User; inline?: boolean; marginLeft?: string; }) => { const PlatformIndicator = ({ user, wantMargin = true, wantTopMargin = false }: { user: User; wantMargin?: boolean; wantTopMargin?: boolean; }) => {
if (!user || user.bot) return null; if (!user || user.bot) return null;
if (user.id === UserStore.getCurrentUser().id) { if (user.id === UserStore.getCurrentUser().id) {
@ -105,23 +105,28 @@ const PlatformIndicator = ({ user, inline = false, marginLeft = "4px" }: { user:
if (!icons.length) return null; if (!icons.length) return null;
return ( return (
<div <span
className="vc-platform-indicator" className="vc-platform-indicator"
style={{ style={{
marginLeft, display: "inline-flex",
gap: "4px", justifyContent: "center",
display: inline ? "inline-flex" : "flex",
alignItems: "center", alignItems: "center",
translate: inline ? "0 3px 0" : undefined marginLeft: wantMargin ? 4 : 0,
verticalAlign: "top",
position: "relative",
top: wantTopMargin ? 2 : 0,
padding: !wantMargin ? 1 : 0,
gap: 2
}} }}
> >
{icons} {icons}
</div> </span>
); );
}; };
const badge: ProfileBadge = { const badge: ProfileBadge = {
component: p => <PlatformIndicator {...p} marginLeft="" />, component: p => <PlatformIndicator {...p} wantMargin={false} />,
position: BadgePosition.START, position: BadgePosition.START,
shouldShow: userInfo => !!Object.keys(getStatus(userInfo.user.id) ?? {}).length, shouldShow: userInfo => !!Object.keys(getStatus(userInfo.user.id) ?? {}).length,
key: "indicator" key: "indicator"
@ -146,7 +151,7 @@ const indicatorLocations = {
description: "Inside messages", description: "Inside messages",
onEnable: () => addDecoration("platform-indicator", props => onEnable: () => addDecoration("platform-indicator", props =>
<ErrorBoundary noop> <ErrorBoundary noop>
<PlatformIndicator user={props.message?.author} inline /> <PlatformIndicator user={props.message?.author} wantTopMargin={true} />
</ErrorBoundary> </ErrorBoundary>
), ),
onDisable: () => removeDecoration("platform-indicator") onDisable: () => removeDecoration("platform-indicator")
@ -156,7 +161,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

@ -26,10 +26,12 @@ import { settings } from "../settings";
const styles: Record<string, string> = findByPropsLazy("timestampInline"); const styles: Record<string, string> = findByPropsLazy("timestampInline");
const AUTO_MODERATION_ACTION = 24;
function shouldShow(message: Message): boolean { function shouldShow(message: Message): boolean {
if (!settings.store.showInMessages) if (!settings.store.showInMessages)
return false; return false;
if (message.author.bot || message.author.system) if (message.author.bot || message.author.system || message.type === AUTO_MODERATION_ACTION)
return false; return false;
if (!settings.store.showSelf && message.author.id === UserStore.getCurrentUser().id) if (!settings.store.showSelf && message.author.id === UserStore.getCurrentUser().id)
return false; return false;

View File

@ -16,10 +16,10 @@
* 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 { Settings } from "@api/settings"; import { Settings } from "@api/Settings";
import { VENCORD_USER_AGENT } from "@utils/constants"; import { VENCORD_USER_AGENT } from "@utils/constants";
import { debounce } from "@utils/debounce"; import { debounce } from "@utils/debounce";
import { useAwaiter } from "@utils/misc"; import { useAwaiter } from "@utils/react";
import { UserStore } from "@webpack/common"; import { UserStore } from "@webpack/common";
import { settings } from "./settings"; import { settings } from "./settings";

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 { definePluginSettings } from "@api/settings"; import { definePluginSettings } from "@api/Settings";
import { OptionType } from "@utils/types"; import { OptionType } from "@utils/types";
import { PronounsFormat } from "./pronoundbUtils"; import { PronounsFormat } from "./pronoundbUtils";

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 { definePluginSettings, Settings } from "@api/settings"; 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";

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 { definePluginSettings } from "@api/settings"; import { definePluginSettings } from "@api/Settings";
import { OptionType } from "@utils/types"; import { OptionType } from "@utils/types";
export default definePluginSettings({ export default definePluginSettings({

View File

@ -18,7 +18,7 @@
import { DataStore, Notices } from "@api/index"; import { DataStore, Notices } from "@api/index";
import { showNotification } from "@api/Notifications"; import { showNotification } from "@api/Notifications";
import { ChannelStore, GuildStore, RelationshipStore, UserStore, UserUtils } from "@webpack/common"; import { ChannelStore, GuildMemberStore, GuildStore, RelationshipStore, UserStore, UserUtils } from "@webpack/common";
import settings from "./settings"; import settings from "./settings";
import { ChannelType, RelationshipType, SimpleGroupChannel, SimpleGuild } from "./types"; import { ChannelType, RelationshipType, SimpleGroupChannel, SimpleGuild } from "./types";
@ -106,7 +106,11 @@ export function deleteGuild(id: string) {
} }
export async function syncGuilds() { export async function syncGuilds() {
guilds.clear();
const me = UserStore.getCurrentUser().id;
for (const [id, { name, icon }] of Object.entries(GuildStore.getGuilds())) { for (const [id, { name, icon }] of Object.entries(GuildStore.getGuilds())) {
if (GuildMemberStore.isMember(id, me))
guilds.set(id, { guilds.set(id, {
id, id,
name, name,
@ -126,6 +130,8 @@ export function deleteGroup(id: string) {
} }
export async function syncGroups() { export async function syncGroups() {
groups.clear();
for (const { type, id, name, rawRecipients, icon } of ChannelStore.getSortedPrivateChannels()) { for (const { type, id, name, rawRecipients, icon } of ChannelStore.getSortedPrivateChannels()) {
if (type === ChannelType.GROUP_DM) if (type === ChannelType.GROUP_DM)
groups.set(id, { groups.set(id, {

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

@ -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 { Settings } from "@api/settings"; import { Settings } from "@api/Settings";
import { Review } from "../entities/Review"; import { Review } from "../entities/Review";
import { ReviewDBUser } from "../entities/User"; import { ReviewDBUser } from "../entities/User";

View File

@ -16,8 +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 { Settings } from "@api/settings"; import { Settings } from "@api/Settings";
import Logger from "@utils/Logger"; import { Logger } from "@utils/Logger";
import { openModal } from "@utils/modal"; import { openModal } from "@utils/modal";
import { findByProps } from "@webpack"; import { findByProps } from "@webpack";
import { FluxDispatcher, React, SelectedChannelStore, Toasts, UserUtils } from "@webpack/common"; import { FluxDispatcher, React, SelectedChannelStore, Toasts, UserUtils } from "@webpack/common";
@ -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

@ -16,11 +16,12 @@
* 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 { classes, LazyComponent } from "@utils/misc"; import { classes } from "@utils/misc";
import { LazyComponent } from "@utils/react";
import { findByProps } from "@webpack"; import { findByProps } from "@webpack";
export default LazyComponent(() => { export default LazyComponent(() => {
const { button, dangerous } = findByProps("button", "wrapper", "disabled","separator"); const { button, dangerous } = findByProps("button", "wrapper", "disabled", "separator");
return function MessageButton(props) { return function MessageButton(props) {
return props.type === "delete" return props.type === "delete"

Some files were not shown because too many files have changed in this diff Show More