/* * 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 . */ import "./themesStyles.css"; import { Settings, useSettings } from "@api/Settings"; import { classNameFactory } from "@api/Styles"; import { Flex } from "@components/Flex"; import { CogWheel, DeleteIcon, FolderIcon, PaintbrushIcon, PencilIcon, PluginIcon, PlusIcon, RestartIcon } from "@components/Icons"; import { Link } from "@components/Link"; import { openPluginModal } from "@components/PluginSettings/PluginModal"; import { AddonCard } from "@components/VencordSettings/AddonCard"; import { QuickAction, QuickActionCard } from "@components/VencordSettings/quickActions"; import { SettingsTab, wrapTab } from "@components/VencordSettings/shared"; import { openInviteModal } from "@utils/discord"; import { openModal } from "@utils/modal"; import { showItemInFolder } from "@utils/native"; import { useAwaiter } from "@utils/react"; import type { ThemeHeader } from "@utils/themes"; import { getThemeInfo, stripBOM, type UserThemeHeader } from "@utils/themes/bd"; import { usercssParse } from "@utils/themes/usercss"; import { findLazy } from "@webpack"; import { Button, Card, Forms, React, showToast, TabBar, TextInput, Tooltip, useEffect, useMemo, useRef, useState } from "@webpack/common"; import type { ComponentType, Ref, SyntheticEvent } from "react"; import type { UserstyleHeader } from "usercss-meta"; import Plugins from "~plugins"; import { UserCSSSettingsModal } from "./UserCSSModal"; type FileInput = ComponentType<{ ref: Ref; onChange: (e: SyntheticEvent) => void; multiple?: boolean; filters?: { name?: string; extensions: string[]; }[]; }>; const FileInput: FileInput = findLazy(m => m.prototype?.activateUploadDialogue && m.prototype.setRef); const cl = classNameFactory("vc-settings-theme-"); function Validator({ link, onValidate }: { link: string; onValidate: (valid: boolean) => void; }) { const [res, err, pending] = useAwaiter(() => fetch(link).then(res => { if (res.status > 300) throw `${res.status} ${res.statusText}`; const contentType = res.headers.get("Content-Type"); if (!contentType?.startsWith("text/css") && !contentType?.startsWith("text/plain")) { onValidate(false); throw "Not a CSS file. Remember to use the raw link!"; } onValidate(true); return "Okay!"; })); const text = pending ? "Checking..." : err ? `Error: ${err instanceof Error ? err.message : String(err)}` : "Valid!"; return {text}; } interface OtherThemeCardProps { theme: UserThemeHeader; enabled: boolean; onChange: (enabled: boolean) => void; onDelete: () => void; showDeleteButton?: boolean; } interface UserCSSCardProps { theme: UserstyleHeader; enabled: boolean; onChange: (enabled: boolean) => void; onDelete: () => void; onSettingsReset: () => void; } function UserCSSThemeCard({ theme, enabled, onChange, onDelete, onSettingsReset }: UserCSSCardProps) { const missingPlugins = useMemo(() => theme.requiredPlugins?.filter(p => !Vencord.Plugins.isPluginEnabled(p)), [theme]); return ( 0} infoButton={ <> {missingPlugins && missingPlugins.length > 0 && ( {({ onMouseLeave, onMouseEnter }) => (
)}
)} {theme.vars && (
openModal(modalProps => ) }>
)} {IS_WEB && (
)} } footer={ {!!theme.homepageURL && Homepage} {!!(theme.homepageURL && theme.supportURL) && " • "} {!!theme.supportURL && Support} } /> ); } function OtherThemeCard({ theme, enabled, onChange, onDelete, showDeleteButton }: OtherThemeCardProps) { return ( ) } footer={ {!!theme.website && Website} {!!(theme.website && theme.invite) && " • "} {!!theme.invite && ( { e.preventDefault(); theme.invite != null && openInviteModal(theme.invite).catch(() => showToast("Invalid or expired invite")); }} > Discord Server )} } /> ); } enum ThemeTab { LOCAL, ONLINE } function ThemesTab() { const settings = useSettings(["themeLinks", "enabledThemeLinks", "enabledThemes"]); const fileInputRef = useRef(null); const [currentTab, setCurrentTab] = useState(ThemeTab.LOCAL); const [currentThemeLink, setCurrentThemeLink] = useState(""); const [themeLinkValid, setThemeLinkValid] = useState(false); const [userThemes, setUserThemes] = useState(null); const [onlineThemes, setOnlineThemes] = useState<(UserThemeHeader & { link: string; })[] | null>(null); const [themeDir, , themeDirPending] = useAwaiter(VencordNative.themes.getThemesDir); useEffect(() => { updateThemes(); }, []); async function updateThemes() { await changeThemeLibraryURLs(); refreshLocalThemes(); refreshOnlineThemes(); } async function changeThemeLibraryURLs() { settings.themeLinks = settings.themeLinks.map(link => { if (link.startsWith("https://themes-delta.vercel.app/api")) { return link.replace("https://themes-delta.vercel.app/api", "https://discord-themes.com/api"); } return link; }); } async function refreshLocalThemes() { const themes = await VencordNative.themes.getThemesList(); const themeInfo: ThemeHeader[] = []; for (const { fileName, content } of themes) { if (!fileName.endsWith(".css")) continue; if ((!IS_WEB || "legcord" in window) && fileName.endsWith(".user.css")) { // handle it as usercss const header = await usercssParse(content, fileName); themeInfo.push({ type: "usercss", header }); Settings.userCssVars[header.id] ??= {}; for (const [name, varInfo] of Object.entries(header.vars ?? {})) { let normalizedValue = ""; switch (varInfo.type) { case "text": case "color": case "checkbox": normalizedValue = varInfo.default; break; case "select": normalizedValue = varInfo.options.find(v => v.name === varInfo.default)!.value; break; case "range": normalizedValue = `${varInfo.default}${varInfo.units}`; break; case "number": normalizedValue = String(varInfo.default); break; } Settings.userCssVars[header.id][name] ??= normalizedValue; } } else { // presumably BD but could also be plain css themeInfo.push({ type: "other", header: getThemeInfo(stripBOM(content), fileName) }); } } setUserThemes(themeInfo); } // When a local theme is enabled/disabled, update the settings function onLocalThemeChange(fileName: string, value: boolean) { if (value) { if (settings.enabledThemes.includes(fileName)) return; settings.enabledThemes = [...settings.enabledThemes, fileName]; } else { settings.enabledThemes = settings.enabledThemes.filter(f => f !== fileName); } } async function onFileUpload(e: SyntheticEvent) { e.stopPropagation(); e.preventDefault(); if (!e.currentTarget?.files?.length) return; const { files } = e.currentTarget; const uploads = Array.from(files, file => { const { name } = file; if (!name.endsWith(".css")) return; return new Promise((resolve, reject) => { const reader = new FileReader(); reader.onload = () => { VencordNative.themes.uploadTheme(name, reader.result as string) .then(resolve) .catch(reject); }; reader.readAsText(file); }); }); await Promise.all(uploads); refreshLocalThemes(); } function LocalThemes() { return ( <> Find Themes:
BetterDiscord Themes GitHub
If using the BD site, click on "Download" and place the downloaded .theme.css file into your themes folder.
<> {IS_WEB ? ( Upload Theme } Icon={PlusIcon} /> ) : ( showItemInFolder(themeDir!)} disabled={themeDirPending} Icon={FolderIcon} /> )} VencordNative.quickCss.openEditor()} Icon={PaintbrushIcon} /> {Settings.plugins.ClientTheme.enabled && ( openPluginModal(Plugins.ClientTheme)} Icon={PencilIcon} /> )}
{userThemes?.map(({ type, header: theme }: ThemeHeader) => ( type === "other" ? ( onLocalThemeChange(theme.fileName, enabled)} onDelete={async () => { onLocalThemeChange(theme.fileName, false); await VencordNative.themes.deleteTheme(theme.fileName); refreshLocalThemes(); }} theme={theme as UserThemeHeader} /> ) : ( onLocalThemeChange(theme.fileName, enabled)} onDelete={async () => { onLocalThemeChange(theme.fileName, false); await VencordNative.themes.deleteTheme(theme.fileName); refreshLocalThemes(); }} onSettingsReset={refreshLocalThemes} theme={theme as UserstyleHeader} /> )))}
); } function addThemeLink(link: string) { if (!themeLinkValid) return; if (settings.themeLinks.includes(link)) return; settings.themeLinks = [...settings.themeLinks, link]; setCurrentThemeLink(""); refreshOnlineThemes(); } async function refreshOnlineThemes() { const themes = await Promise.all(settings.themeLinks.map(async link => { const css = await fetch(link).then(res => res.text()); return { ...getThemeInfo(css, link), link }; })); setOnlineThemes(themes); } function onThemeLinkEnabledChange(link: string, enabled: boolean) { if (enabled) { if (settings.enabledThemeLinks.includes(link)) return; settings.enabledThemeLinks = [...settings.enabledThemeLinks, link]; } else { settings.enabledThemeLinks = settings.enabledThemeLinks.filter(f => f !== link); } } function deleteThemeLink(link: string) { settings.themeLinks = settings.themeLinks.filter(f => f !== link); refreshOnlineThemes(); } function OnlineThemes() { return ( <> Make sure to use direct links to files (raw or github.io)! {currentThemeLink && }
{onlineThemes?.map(rawLink => { const { label, link } = (() => { const match = /^@(light|dark) (.*)/.exec(rawLink.link); if (!match) return { label: rawLink, link: rawLink }; const [, mode, link] = match; return { label: `[${mode} mode only] ${link}`, link }; })(); return onThemeLinkEnabledChange(rawLink.link, enabled)} onDelete={async () => { onThemeLinkEnabledChange(rawLink.link, false); deleteThemeLink(rawLink.link); }} showDeleteButton theme={rawLink} />; })}
); } return ( Local Themes Online Themes {currentTab === ThemeTab.LOCAL && } {currentTab === ThemeTab.ONLINE && } ); } export default wrapTab(ThemesTab, "Themes");