aboutsummaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
authorJustice Almanzar <superdash993@gmail.com>2022-12-02 10:43:37 -0500
committerGitHub <noreply@github.com>2022-12-02 16:43:37 +0100
commit41dddc9eee6f19fb5055545811aff1e282790a9c (patch)
treebf38148e87242e169adfa39919aa636a9d0551ce /src
parent4760af7f0ee275caa1eee440f4945032057d2b56 (diff)
downloadVencord-41dddc9eee6f19fb5055545811aff1e282790a9c.tar.gz
Vencord-41dddc9eee6f19fb5055545811aff1e282790a9c.tar.bz2
Vencord-41dddc9eee6f19fb5055545811aff1e282790a9c.zip
feat(plugin): ShikiCodeblocks (#267)
Co-authored-by: ArjixWasTaken <53124886+ArjixWasTaken@users.noreply.github.com> Co-authored-by: Ven <vendicated@riseup.net>
Diffstat (limited to 'src')
-rw-r--r--src/api/settings.ts11
-rw-r--r--src/components/VencordSettings/Updater.tsx2
-rw-r--r--src/components/VencordSettings/VencordTab.tsx4
-rw-r--r--src/patcher.ts30
-rw-r--r--src/plugins/pronoundb/components/PronounsChatComponent.tsx9
-rw-r--r--src/plugins/pronoundb/components/PronounsProfileWrapper.tsx9
-rw-r--r--src/plugins/reviewDB/components/ReviewsView.tsx14
-rw-r--r--src/plugins/shikiCodeblocks/api/languages.ts74
-rw-r--r--src/plugins/shikiCodeblocks/api/shiki.ts119
-rw-r--r--src/plugins/shikiCodeblocks/api/themes.ts67
-rw-r--r--src/plugins/shikiCodeblocks/components/ButtonRow.tsx46
-rw-r--r--src/plugins/shikiCodeblocks/components/Code.tsx92
-rw-r--r--src/plugins/shikiCodeblocks/components/CopyButton.tsx41
-rw-r--r--src/plugins/shikiCodeblocks/components/Header.tsx42
-rw-r--r--src/plugins/shikiCodeblocks/components/Highlighter.tsx123
-rw-r--r--src/plugins/shikiCodeblocks/hooks/useCopyCooldown.ts34
-rw-r--r--src/plugins/shikiCodeblocks/hooks/useShikiSettings.ts25
-rw-r--r--src/plugins/shikiCodeblocks/hooks/useTheme.ts49
-rw-r--r--src/plugins/shikiCodeblocks/index.ts154
-rw-r--r--src/plugins/shikiCodeblocks/style.css100
-rw-r--r--src/plugins/shikiCodeblocks/types.ts78
-rw-r--r--src/plugins/shikiCodeblocks/utils/color.ts32
-rw-r--r--src/plugins/shikiCodeblocks/utils/createStyle.ts36
-rw-r--r--src/plugins/shikiCodeblocks/utils/misc.ts50
-rw-r--r--src/utils/constants.ts6
-rw-r--r--src/utils/dependencies.ts4
-rw-r--r--src/utils/misc.tsx49
-rw-r--r--src/utils/react.ts62
-rw-r--r--src/utils/text.ts36
-rw-r--r--src/webpack/common.tsx2
30 files changed, 1366 insertions, 34 deletions
diff --git a/src/api/settings.ts b/src/api/settings.ts
index b7c143a..2617903 100644
--- a/src/api/settings.ts
+++ b/src/api/settings.ts
@@ -141,14 +141,19 @@ export const Settings = makeProxy(settings);
* Settings hook for React components. Returns a smart settings
* object that automagically triggers a rerender if any properties
* are altered
+ * @param paths An optional list of paths to whitelist for rerenders
* @returns Settings
*/
-export function useSettings() {
+export function useSettings(paths?: string[]) {
const [, forceUpdate] = React.useReducer(() => ({}), {});
+ const onUpdate: SubscriptionCallback = paths
+ ? (value, path) => paths.includes(path) && forceUpdate()
+ : forceUpdate;
+
React.useEffect(() => {
- subscriptions.add(forceUpdate);
- return () => void subscriptions.delete(forceUpdate);
+ subscriptions.add(onUpdate);
+ return () => void subscriptions.delete(onUpdate);
}, []);
return Settings;
diff --git a/src/components/VencordSettings/Updater.tsx b/src/components/VencordSettings/Updater.tsx
index bb344f5..3369069 100644
--- a/src/components/VencordSettings/Updater.tsx
+++ b/src/components/VencordSettings/Updater.tsx
@@ -179,7 +179,7 @@ function Newer(props: CommonProps) {
}
function Updater() {
- const [repo, err, repoPending] = useAwaiter(getRepo, "Loading...");
+ const [repo, err, repoPending] = useAwaiter(getRepo, { fallbackValue: "Loading..." });
React.useEffect(() => {
if (err)
diff --git a/src/components/VencordSettings/VencordTab.tsx b/src/components/VencordSettings/VencordTab.tsx
index 746fcf0..ad8fe14 100644
--- a/src/components/VencordSettings/VencordTab.tsx
+++ b/src/components/VencordSettings/VencordTab.tsx
@@ -27,7 +27,9 @@ import { Button, Card, Forms, Margins, React, Switch } from "@webpack/common";
const st = (style: string) => `vcSettings${style}`;
function VencordSettings() {
- const [settingsDir, , settingsDirPending] = useAwaiter(() => VencordNative.ipc.invoke<string>(IpcEvents.GET_SETTINGS_DIR), "Loading...");
+ const [settingsDir, , settingsDirPending] = useAwaiter(() => VencordNative.ipc.invoke<string>(IpcEvents.GET_SETTINGS_DIR), {
+ fallbackValue: "Loading..."
+ });
const settings = useSettings();
const [donateImage] = React.useState(
diff --git a/src/patcher.ts b/src/patcher.ts
index 0849e5a..0cf7e24 100644
--- a/src/patcher.ts
+++ b/src/patcher.ts
@@ -109,16 +109,36 @@ if (!process.argv.includes("--vanilla")) {
// Remove CSP
+ type PolicyResult = Record<string, string[]>;
+
+ const parsePolicy = (policy: string): PolicyResult => {
+ const result: PolicyResult = {};
+ policy.split(";").forEach(directive => {
+ const [directiveKey, ...directiveValue] = directive.trim().split(/\s+/g);
+ if (directiveKey && !Object.prototype.hasOwnProperty.call(result, directiveKey)) {
+ result[directiveKey] = directiveValue;
+ }
+ });
+ return result;
+ };
+ const stringifyPolicy = (policy: PolicyResult): string =>
+ Object.entries(policy)
+ .filter(([, values]) => values?.length)
+ .map(directive => directive.flat().join(" "))
+ .join("; ");
+
function patchCsp(headers: Record<string, string[]>, header: string) {
if (header in headers) {
- let patchedHeader = headers[header][0];
- for (const directive of ["style-src", "connect-src", "img-src", "font-src", "media-src"]) {
- patchedHeader = patchedHeader.replace(new RegExp(`${directive}.+?;`), `${directive} * blob: data: 'unsafe-inline';`);
+ const csp = parsePolicy(headers[header][0]);
+
+ for (const directive of ["style-src", "connect-src", "img-src", "font-src", "media-src", "worker-src"]) {
+ csp[directive] = ["*", "blob:", "data:", "'unsafe-inline'"];
}
// TODO: Restrict this to only imported packages with fixed version.
// Perhaps auto generate with esbuild
- patchedHeader = patchedHeader.replace(/script-src.+?(?=;)/, "$& 'unsafe-eval' https://unpkg.com https://cdnjs.cloudflare.com");
- headers[header] = [patchedHeader];
+ csp["script-src"] ??= [];
+ csp["script-src"].push("'unsafe-eval'", "https://unpkg.com", "https://cdnjs.cloudflare.com");
+ headers[header] = [stringifyPolicy(csp)];
}
}
diff --git a/src/plugins/pronoundb/components/PronounsChatComponent.tsx b/src/plugins/pronoundb/components/PronounsChatComponent.tsx
index 9225fc5..ce67754 100644
--- a/src/plugins/pronoundb/components/PronounsChatComponent.tsx
+++ b/src/plugins/pronoundb/components/PronounsChatComponent.tsx
@@ -39,11 +39,10 @@ export default function PronounsChatComponentWrapper({ message }: { message: Mes
}
function PronounsChatComponent({ message }: { message: Message; }) {
- const [result, , isPending] = useAwaiter(
- () => fetchPronouns(message.author.id),
- null,
- e => console.error("Fetching pronouns failed: ", e)
- );
+ const [result, , isPending] = useAwaiter(() => fetchPronouns(message.author.id), {
+ fallbackValue: null,
+ onError: e => console.error("Fetching pronouns failed: ", e)
+ });
// If the promise completed, the result was not "unspecified", and there is a mapping for the code, then return a span with the pronouns
if (!isPending && result && result !== "unspecified" && PronounMapping[result]) {
diff --git a/src/plugins/pronoundb/components/PronounsProfileWrapper.tsx b/src/plugins/pronoundb/components/PronounsProfileWrapper.tsx
index 9540bb9..79fce23 100644
--- a/src/plugins/pronoundb/components/PronounsProfileWrapper.tsx
+++ b/src/plugins/pronoundb/components/PronounsProfileWrapper.tsx
@@ -45,11 +45,10 @@ function ProfilePronouns(
leProps: UserProfilePronounsProps;
}
) {
- const [result, , isPending] = useAwaiter(
- () => fetchPronouns(userId),
- null,
- e => console.error("Fetching pronouns failed: ", e)
- );
+ const [result, , isPending] = useAwaiter(() => fetchPronouns(userId), {
+ fallbackValue: null,
+ onError: e => console.error("Fetching pronouns failed: ", e),
+ });
// If the promise completed, the result was not "unspecified", and there is a mapping for the code, then render
if (!isPending && result && result !== "unspecified" && PronounMapping[result]) {
diff --git a/src/plugins/reviewDB/components/ReviewsView.tsx b/src/plugins/reviewDB/components/ReviewsView.tsx
index 999b970..57f974e 100644
--- a/src/plugins/reviewDB/components/ReviewsView.tsx
+++ b/src/plugins/reviewDB/components/ReviewsView.tsx
@@ -18,7 +18,7 @@
import { classes, useAwaiter } from "@utils/misc";
import { findLazy } from "@webpack";
-import { Forms, Text, UserStore } from "@webpack/common";
+import { Forms, React, Text, UserStore } from "@webpack/common";
import type { KeyboardEvent } from "react";
import { addReview, getReviews } from "../Utils/ReviewDBAPI";
@@ -27,7 +27,13 @@ import ReviewComponent from "./ReviewComponent";
const Classes = findLazy(m => typeof m.textarea === "string");
export default function ReviewsView({ userId }: { userId: string; }) {
- const [reviews, _, isLoading, refetch] = useAwaiter(() => getReviews(userId), []);
+ const [refetchCount, setRefetchCount] = React.useState(0);
+ const [reviews, _, isLoading] = useAwaiter(() => getReviews(userId), {
+ fallbackValue: [],
+ deps: [refetchCount],
+ });
+
+ const dirtyRefetch = () => setRefetchCount(refetchCount + 1);
if (isLoading) return null;
@@ -40,7 +46,7 @@ export default function ReviewsView({ userId }: { userId: string; }) {
}).then(res => {
if (res === 0 || res === 1) {
(target as HTMLInputElement).value = ""; // clear the input
- refetch();
+ dirtyRefetch();
}
});
}
@@ -64,7 +70,7 @@ export default function ReviewsView({ userId }: { userId: string; }) {
<ReviewComponent
key={review.id}
review={review}
- refetch={refetch}
+ refetch={dirtyRefetch}
/>
)}
{reviews?.length === 0 && (
diff --git a/src/plugins/shikiCodeblocks/api/languages.ts b/src/plugins/shikiCodeblocks/api/languages.ts
new file mode 100644
index 0000000..f14a4dc
--- /dev/null
+++ b/src/plugins/shikiCodeblocks/api/languages.ts
@@ -0,0 +1,74 @@
+/*
+ * 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 { ILanguageRegistration } from "@vap/shiki";
+
+export const VPC_REPO = "Vap0r1ze/vapcord";
+export const VPC_REPO_COMMIT = "88a7032a59cca40da170926651b08201ea3b965a";
+export const vpcRepoAssets = `https://raw.githubusercontent.com/${VPC_REPO}/${VPC_REPO_COMMIT}/assets/shiki-codeblocks`;
+export const vpcRepoGrammar = (fileName: string) => `${vpcRepoAssets}/${fileName}`;
+export const vpcRepoLanguages = `${vpcRepoAssets}/languages.json`;
+
+export interface Language {
+ name: string;
+ id: string;
+ devicon?: string;
+ grammarUrl: string,
+ grammar?: ILanguageRegistration["grammar"];
+ scopeName: string;
+ aliases?: string[];
+ custom?: boolean;
+}
+export interface LanguageJson {
+ name: string;
+ id: string;
+ fileName: string;
+ devicon?: string;
+ scopeName: string;
+ aliases?: string[];
+}
+
+export const languages: Record<string, Language> = {};
+
+export const loadLanguages = async () => {
+ const langsJson: LanguageJson[] = await fetch(vpcRepoLanguages).then(res => res.json());
+ const loadedLanguages = Object.fromEntries(
+ langsJson.map(lang => [lang.id, {
+ ...lang,
+ grammarUrl: vpcRepoGrammar(lang.fileName),
+ }])
+ );
+ Object.assign(languages, loadedLanguages);
+};
+
+export const getGrammar = (lang: Language): Promise<NonNullable<ILanguageRegistration["grammar"]>> => {
+ if (lang.grammar) return Promise.resolve(lang.grammar);
+ return fetch(lang.grammarUrl).then(res => res.json());
+};
+
+const aliasCache = new Map<string, Language>();
+export function resolveLang(idOrAlias: string) {
+ if (Object.prototype.hasOwnProperty.call(languages, idOrAlias)) return languages[idOrAlias];
+
+ const lang = Object.values(languages).find(lang => lang.aliases?.includes(idOrAlias));
+
+ if (!lang) return null;
+
+ aliasCache.set(idOrAlias, lang);
+ return lang;
+}
diff --git a/src/plugins/shikiCodeblocks/api/shiki.ts b/src/plugins/shikiCodeblocks/api/shiki.ts
new file mode 100644
index 0000000..e7691ce
--- /dev/null
+++ b/src/plugins/shikiCodeblocks/api/shiki.ts
@@ -0,0 +1,119 @@
+/*
+ * 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 { shikiOnigasmSrc, shikiWorkerSrc } from "@utils/dependencies";
+import { WorkerClient } from "@vap/core/ipc";
+import type { IShikiTheme, IThemedToken } from "@vap/shiki";
+
+import { dispatchTheme } from "../hooks/useTheme";
+import type { ShikiSpec } from "../types";
+import { getGrammar, languages, loadLanguages, resolveLang } from "./languages";
+import { themes } from "./themes";
+
+const themeUrls = Object.values(themes);
+
+let resolveClient: (client: WorkerClient<ShikiSpec>) => void;
+
+export const shiki = {
+ client: null as WorkerClient<ShikiSpec> | null,
+ currentTheme: null as IShikiTheme | null,
+ currentThemeUrl: null as string | null,
+ timeoutMs: 10000,
+ languages,
+ themes,
+ loadedThemes: new Set<string>(),
+ loadedLangs: new Set<string>(),
+ clientPromise: new Promise<WorkerClient<ShikiSpec>>(resolve => resolveClient = resolve),
+
+ init: async (initThemeUrl: string | undefined) => {
+ /** https://stackoverflow.com/q/58098143 */
+ const workerBlob = await fetch(shikiWorkerSrc).then(res => res.blob());
+
+ const client = shiki.client = new WorkerClient<ShikiSpec>(
+ "shiki-client",
+ "shiki-host",
+ workerBlob,
+ { name: "ShikiWorker" },
+ );
+ await client.init();
+
+ const themeUrl = initThemeUrl || themeUrls[0];
+
+ await loadLanguages();
+ await client.run("setOnigasm", { wasm: shikiOnigasmSrc });
+ await client.run("setHighlighter", { theme: themeUrl, langs: [] });
+ shiki.loadedThemes.add(themeUrl);
+ await shiki._setTheme(themeUrl);
+ resolveClient(client);
+ },
+ _setTheme: async (themeUrl: string) => {
+ shiki.currentThemeUrl = themeUrl;
+ const { themeData } = await shiki.client!.run("getTheme", { theme: themeUrl });
+ shiki.currentTheme = JSON.parse(themeData);
+ dispatchTheme({ id: themeUrl, theme: shiki.currentTheme });
+ },
+ loadTheme: async (themeUrl: string) => {
+ const client = await shiki.clientPromise;
+ if (shiki.loadedThemes.has(themeUrl)) return;
+
+ await client.run("loadTheme", { theme: themeUrl });
+
+ shiki.loadedThemes.add(themeUrl);
+ },
+ setTheme: async (themeUrl: string) => {
+ await shiki.clientPromise;
+ themeUrl ||= themeUrls[0];
+ if (!shiki.loadedThemes.has(themeUrl)) await shiki.loadTheme(themeUrl);
+
+ await shiki._setTheme(themeUrl);
+ },
+ loadLang: async (langId: string) => {
+ const client = await shiki.clientPromise;
+ const lang = resolveLang(langId);
+
+ if (!lang || shiki.loadedLangs.has(lang.id)) return;
+
+ await client.run("loadLanguage", {
+ lang: {
+ ...lang,
+ grammar: lang.grammar ?? await getGrammar(lang),
+ }
+ });
+ shiki.loadedLangs.add(lang.id);
+ },
+ tokenizeCode: async (code: string, langId: string): Promise<IThemedToken[][]> => {
+ const client = await shiki.clientPromise;
+ const lang = resolveLang(langId);
+ if (!lang) return [];
+
+ if (!shiki.loadedLangs.has(lang.id)) await shiki.loadLang(lang.id);
+
+ return await client.run("codeToThemedTokens", {
+ code,
+ lang: langId,
+ theme: shiki.currentThemeUrl ?? themeUrls[0],
+ });
+ },
+ destroy() {
+ shiki.currentTheme = null;
+ shiki.currentThemeUrl = null;
+ dispatchTheme({ id: null, theme: null });
+ shiki.client?.destroy();
+ }
+};
diff --git a/src/plugins/shikiCodeblocks/api/themes.ts b/src/plugins/shikiCodeblocks/api/themes.ts
new file mode 100644
index 0000000..f31ce60
--- /dev/null
+++ b/src/plugins/shikiCodeblocks/api/themes.ts
@@ -0,0 +1,67 @@
+/*
+ * 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 { IShikiTheme } from "@vap/shiki";
+
+export const SHIKI_REPO = "shikijs/shiki";
+export const SHIKI_REPO_COMMIT = "0b28ad8ccfbf2615f2d9d38ea8255416b8ac3043";
+export const shikiRepoTheme = (name: string) => `https://raw.githubusercontent.com/${SHIKI_REPO}/${SHIKI_REPO_COMMIT}/packages/shiki/themes/${name}.json`;
+
+export const themes = {
+ // Default
+ DarkPlus: shikiRepoTheme("dark-plus"),
+
+ // Dev Choices
+ MaterialCandy: "https://raw.githubusercontent.com/millsp/material-candy/master/material-candy.json",
+
+ // More from Shiki repo
+ DraculaSoft: shikiRepoTheme("dracula-soft"),
+ Dracula: shikiRepoTheme("dracula"),
+ GithubDarkDimmed: shikiRepoTheme("github-dark-dimmed"),
+ GithubDark: shikiRepoTheme("github-dark"),
+ GithubLight: shikiRepoTheme("github-light"),
+ LightPlus: shikiRepoTheme("light-plus"),
+ MaterialDarker: shikiRepoTheme("material-darker"),
+ MaterialDefault: shikiRepoTheme("material-default"),
+ MaterialLighter: shikiRepoTheme("material-lighter"),
+ MaterialOcean: shikiRepoTheme("material-ocean"),
+ MaterialPalenight: shikiRepoTheme("material-palenight"),
+ MinDark: shikiRepoTheme("min-dark"),
+ MinLight: shikiRepoTheme("min-light"),
+ Monokai: shikiRepoTheme("monokai"),
+ Nord: shikiRepoTheme("nord"),
+ OneDarkPro: shikiRepoTheme("one-dark-pro"),
+ Poimandres: shikiRepoTheme("poimandres"),
+ RosePineDawn: shikiRepoTheme("rose-pine-dawn"),
+ RosePineMoon: shikiRepoTheme("rose-pine-moon"),
+ RosePine: shikiRepoTheme("rose-pine"),
+ SlackDark: shikiRepoTheme("slack-dark"),
+ SlackOchin: shikiRepoTheme("slack-ochin"),
+ SolarizedDark: shikiRepoTheme("solarized-dark"),
+ SolarizedLight: shikiRepoTheme("solarized-light"),
+ VitesseDark: shikiRepoTheme("vitesse-dark"),
+ VitesseLight: shikiRepoTheme("vitesse-light"),
+ CssVariables: shikiRepoTheme("css-variables"),
+};
+
+export const themeCache = new Map<string, IShikiTheme>();
+
+export const getTheme = (url: string): Promise<IShikiTheme> => {
+ if (themeCache.has(url)) return Promise.resolve(themeCache.get(url)!);
+ return fetch(url).then(res => res.json());
+};
diff --git a/src/plugins/shikiCodeblocks/components/ButtonRow.tsx b/src/plugins/shikiCodeblocks/components/ButtonRow.tsx
new file mode 100644
index 0000000..e73eb72
--- /dev/null
+++ b/src/plugins/shikiCodeblocks/components/ButtonRow.tsx
@@ -0,0 +1,46 @@
+/*
+ * 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 { Clipboard } from "@webpack/common";
+
+import { cl } from "../utils/misc";
+import { CopyButton } from "./CopyButton";
+
+export interface ButtonRowProps {
+ theme: import("./Highlighter").ThemeBase;
+ content: string;
+}
+
+export function ButtonRow({ content, theme }: ButtonRowProps) {
+ const buttons: JSX.Element[] = [];
+
+ if (Clipboard.SUPPORTS_COPY) {
+ buttons.push(
+ <CopyButton
+ content={content}
+ className={cl("btn")}
+ style={{
+ backgroundColor: theme.accentBgColor,
+ color: theme.accentFgColor,
+ }}
+ />
+ );
+ }
+
+ return <div className={cl("btns")}>{buttons}</div>;
+}
diff --git a/src/plugins/shikiCodeblocks/components/Code.tsx b/src/plugins/shikiCodeblocks/components/Code.tsx
new file mode 100644
index 0000000..ae41113
--- /dev/null
+++ b/src/plugins/shikiCodeblocks/components/Code.tsx
@@ -0,0 +1,92 @@
+/*
+ * 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 type { IThemedToken } from "@vap/shiki";
+
+import { cl } from "../utils/misc";
+import { ThemeBase } from "./Highlighter";
+
+export interface CodeProps {
+ theme: ThemeBase;
+ useHljs: boolean;
+ lang?: string;
+ content: string;
+ tokens: IThemedToken[][] | null;
+}
+
+export const Code = ({
+ theme,
+ useHljs,
+ lang,
+ content,
+ tokens,
+}: CodeProps) => {
+ let lines!: JSX.Element[];
+
+ if (useHljs) {
+ try {
+ const { value: hljsHtml } = hljs.highlight(lang!, content, true);
+ lines = hljsHtml
+ .split("\n")
+ .map((line, i) => <span key={i} dangerouslySetInnerHTML={{ __html: line }} />);
+ } catch {
+ lines = content.split("\n").map(line => <span>{line}</span>);
+ }
+ } else {
+ const renderTokens =
+ tokens ??
+ content
+ .split("\n")
+ .map(line => [{ color: theme.plainColor, content: line } as IThemedToken]);
+
+ lines = renderTokens.map(line => {
+ // [Cynthia] this makes it so when you highlight the codeblock
+ // empty lines are also selected and copied when you Ctrl+C.
+ if (line.length === 0) {
+ return <span>{"\n"}</span>;
+ }
+
+ return (
+ <>
+ {line.map(({ content, color, fontStyle }, i) => (
+ <span
+ key={i}
+ style={{
+ color,
+ fontStyle: (fontStyle ?? 0) & 1 ? "italic" : undefined,
+ fontWeight: (fontStyle ?? 0) & 2 ? "bold" : undefined,
+ textDecoration: (fontStyle ?? 0) & 4 ? "underline" : undefined,
+ }}
+ >
+ {content}
+ </span>
+ ))}
+ </>
+ );
+ });
+ }
+
+ const codeTableRows = lines.map((line, i) => (
+ <tr key={i}>
+ <td style={{ color: theme.plainColor }}>{i + 1}</td>
+ <td>{line}</td>
+ </tr>
+ ));
+
+ return <table className={cl("table")}>{...codeTableRows}</table>;
+};
diff --git a/src/plugins/shikiCodeblocks/components/CopyButton.tsx b/src/plugins/shikiCodeblocks/components/CopyButton.tsx
new file mode 100644
index 0000000..153b3cd
--- /dev/null
+++ b/src/plugins/shikiCodeblocks/components/CopyButton.tsx
@@ -0,0 +1,41 @@
+/*
+ * 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 { useCopyCooldown } from "../hooks/useCopyCooldown";
+
+export interface CopyButtonProps extends React.DetailedHTMLProps<React.ButtonHTMLAttributes<HTMLButtonElement>, HTMLButtonElement> {
+ content: string;
+}
+
+export function CopyButton({ content, ...props }: CopyButtonProps) {
+ const [copyCooldown, copy] = useCopyCooldown(1000);
+
+ return (
+ <button
+ {...props}
+ style={{
+ ...props.style,
+ cursor: copyCooldown ? "default" : undefined,
+ }}
+ onClick={() => copy(content)}
+ >
+ {copyCooldown ? "Copied!" : "Copy"}
+ </button>
+
+ );
+}
diff --git a/src/plugins/shikiCodeblocks/components/Header.tsx b/src/plugins/shikiCodeblocks/components/Header.tsx
new file mode 100644
index 0000000..c2db386
--- /dev/null
+++ b/src/plugins/shikiCodeblocks/components/Header.tsx
@@ -0,0 +1,42 @@
+/*
+ * Vencord, a modification for Discord's desktop app
+ * Copyrigh