Merge branch 'feat/themes-rewrite' into dev
This commit is contained in:
commit
ada2480292
21 changed files with 718 additions and 375 deletions
|
|
@ -1,28 +1,28 @@
|
|||
import { CardWrapper } from "@core/ui/components/AddonCard";
|
||||
import { useProxy } from "@core/vendetta/storage";
|
||||
import { findAssetId } from "@lib/api/assets";
|
||||
import { settings } from "@lib/api/settings";
|
||||
import AlertModal, { AlertActionButton } from "@lib/ui/components/wrappers/AlertModal";
|
||||
import { dismissAlert, openAlert } from "@lib/ui/alerts";
|
||||
import { showSheet } from "@lib/ui/sheets";
|
||||
import isValidHttpUrl from "@lib/utils/isValidHttpUrl";
|
||||
import { lazyDestructure } from "@lib/utils/lazy";
|
||||
import { findByProps } from "@metro";
|
||||
import { clipboard } from "@metro/common";
|
||||
import { Button, FlashList, FloatingActionButton, HelpMessage, IconButton, Stack, Text, TextInput } from "@metro/common/components";
|
||||
import { clipboard, NavigationNative } from "@metro/common";
|
||||
import { AlertActionButton, AlertModal, Button, FlashList, FloatingActionButton, HelpMessage, IconButton, Stack, Text, TextInput } from "@metro/common/components";
|
||||
import { ErrorBoundary, Search } from "@ui/components";
|
||||
import { isNotNil } from "es-toolkit";
|
||||
import fuzzysort from "fuzzysort";
|
||||
import { ComponentType, ReactNode, useCallback, useMemo } from "react";
|
||||
import { ComponentType, ReactNode, useCallback, useEffect, useMemo } from "react";
|
||||
import { Image, ScrollView, View } from "react-native";
|
||||
|
||||
const { showSimpleActionSheet, hideActionSheet } = lazyDestructure(() => findByProps("showSimpleActionSheet"));
|
||||
const { openAlert, dismissAlert } = lazyDestructure(() => findByProps("openAlert", "dismissAlert"));
|
||||
|
||||
type SearchKeywords = Array<string | ((obj: any & {}) => string)>;
|
||||
type SearchKeywords<T> = Array<string | ((obj: T & {}) => string)>;
|
||||
|
||||
interface AddonPageProps<T extends object, I = any> {
|
||||
title: string;
|
||||
items: I[];
|
||||
searchKeywords: SearchKeywords;
|
||||
sortOptions?: Record<string, (a: I, b: I) => number>;
|
||||
searchKeywords: SearchKeywords<T>;
|
||||
sortOptions?: Record<string, (a: T, b: T) => number>;
|
||||
resolveItem?: (value: I) => T | undefined;
|
||||
safeModeHint?: {
|
||||
message?: string;
|
||||
|
|
@ -34,6 +34,9 @@ interface AddonPageProps<T extends object, I = any> {
|
|||
fetchFn?: (url: string) => Promise<void>;
|
||||
onPress?: () => void;
|
||||
};
|
||||
|
||||
OptionsActionSheetComponent?: ComponentType<any>;
|
||||
|
||||
CardComponent: ComponentType<CardWrapper<T>>;
|
||||
ListHeaderComponent?: ComponentType<any>;
|
||||
ListFooterComponent?: ComponentType<any>;
|
||||
|
|
@ -55,7 +58,7 @@ function InputAlert(props: { label: string, fetchFn: (url: string) => Promise<vo
|
|||
|
||||
return <AlertModal
|
||||
title={props.label}
|
||||
content="Enter the URL of the source you want to install from:"
|
||||
content="Type in the source URL you want to install from:"
|
||||
extraContent={
|
||||
<Stack style={{ marginTop: -12 }}>
|
||||
<TextInput
|
||||
|
|
@ -107,15 +110,27 @@ function InputAlert(props: { label: string, fetchFn: (url: string) => Promise<vo
|
|||
}
|
||||
|
||||
export default function AddonPage<T extends object>({ CardComponent, ...props }: AddonPageProps<T>) {
|
||||
useProxy(settings);
|
||||
|
||||
const [search, setSearch] = React.useState("");
|
||||
const [sortFn, setSortFn] = React.useState<((a: unknown, b: unknown) => number) | null>(() => null);
|
||||
const [sortFn, setSortFn] = React.useState<((a: T, b: T) => number) | null>(() => null);
|
||||
const navigation = NavigationNative.useNavigation();
|
||||
|
||||
useEffect(() => {
|
||||
if (props.OptionsActionSheetComponent) {
|
||||
navigation.setOptions({
|
||||
headerRight: () => <IconButton
|
||||
size="sm"
|
||||
variant="secondary"
|
||||
icon={findAssetId("MoreHorizontalIcon")}
|
||||
onPress={() => showSheet("AddonMoreSheet", props.OptionsActionSheetComponent!)}
|
||||
/>
|
||||
});
|
||||
}
|
||||
}, [navigation]);
|
||||
|
||||
const results = useMemo(() => {
|
||||
let values = props.items;
|
||||
if (props.resolveItem) values = values.map(props.resolveItem);
|
||||
const items = values.filter(i => i && typeof i === "object");
|
||||
if (props.resolveItem) values = values.map(props.resolveItem).filter(isNotNil);
|
||||
const items = values.filter(i => isNotNil(i) && typeof i === "object");
|
||||
if (!search && sortFn) items.sort(sortFn);
|
||||
|
||||
return fuzzysort.go(search, items, { keys: props.searchKeywords, all: true });
|
||||
|
|
@ -134,7 +149,7 @@ export default function AddonPage<T extends object>({ CardComponent, ...props }:
|
|||
if (results.length === 0 && !search) {
|
||||
return <View style={{ gap: 32, flexGrow: 1, justifyContent: "center", alignItems: "center" }}>
|
||||
<View style={{ gap: 8, alignItems: "center" }}>
|
||||
<Image source={findAssetId("empty_quick_switcher")} />
|
||||
<Image source={findAssetId("empty_quick_switcher")!} />
|
||||
<Text variant="text-lg/semibold" color="text-normal">
|
||||
Oops! Nothing to see here… yet!
|
||||
</Text>
|
||||
|
|
@ -175,7 +190,7 @@ export default function AddonPage<T extends object>({ CardComponent, ...props }:
|
|||
})}
|
||||
/>}
|
||||
</View>
|
||||
{props.ListHeaderComponent && !search && <props.ListHeaderComponent />}
|
||||
{props.ListHeaderComponent && <props.ListHeaderComponent />}
|
||||
</View>
|
||||
);
|
||||
|
||||
|
|
@ -187,12 +202,12 @@ export default function AddonPage<T extends object>({ CardComponent, ...props }:
|
|||
estimatedItemSize={136}
|
||||
ListHeaderComponent={headerElement}
|
||||
ListEmptyComponent={() => <View style={{ gap: 12, padding: 12, alignItems: "center" }}>
|
||||
<Image source={findAssetId("devices_not_found")} />
|
||||
<Image source={findAssetId("devices_not_found")!} />
|
||||
<Text variant="text-lg/semibold" color="text-normal">
|
||||
Hmmm... could not find that!
|
||||
</Text>
|
||||
</View>}
|
||||
contentContainerStyle={{ padding: 8, paddingHorizontal: 12 }}
|
||||
contentContainerStyle={{ padding: 8, paddingHorizontal: 12, paddingBottom: 90 }}
|
||||
ItemSeparatorComponent={() => <View style={{ height: 8 }} />}
|
||||
ListFooterComponent={props.ListFooterComponent}
|
||||
renderItem={({ item }: any) => <CardComponent item={item.obj} result={item} />}
|
||||
|
|
|
|||
|
|
@ -2,22 +2,21 @@ import { formatString, Strings } from "@core/i18n";
|
|||
import AddonCard, { CardWrapper } from "@core/ui/components/AddonCard";
|
||||
import { showConfirmationAlert } from "@core/vendetta/alerts";
|
||||
import { useProxy } from "@core/vendetta/storage";
|
||||
import { applyTheme, fetchTheme, removeTheme, selectTheme, Theme, themes } from "@lib/addons/themes";
|
||||
import { fetchTheme, removeTheme, selectTheme, themes, VdThemeInfo } from "@lib/addons/themes";
|
||||
import { findAssetId } from "@lib/api/assets";
|
||||
import { settings } from "@lib/api/settings";
|
||||
import { clipboard } from "@metro/common";
|
||||
import { showToast } from "@ui/toasts";
|
||||
|
||||
function selectAndApply(value: boolean, theme: Theme) {
|
||||
function selectAndApply(value: boolean, theme: VdThemeInfo) {
|
||||
try {
|
||||
selectTheme(value ? theme : null);
|
||||
applyTheme(value ? theme : null);
|
||||
} catch (e: any) {
|
||||
console.error("Error while selectAndApply,", e);
|
||||
}
|
||||
}
|
||||
|
||||
export default function ThemeCard({ item: theme }: CardWrapper<Theme>) {
|
||||
export default function ThemeCard({ item: theme }: CardWrapper<VdThemeInfo>) {
|
||||
useProxy(theme);
|
||||
|
||||
const [removed, setRemoved] = React.useState(false);
|
||||
|
|
|
|||
|
|
@ -2,26 +2,31 @@ import { formatString, Strings } from "@core/i18n";
|
|||
import AddonPage from "@core/ui/components/AddonPage";
|
||||
import ThemeCard from "@core/ui/settings/pages/Themes/ThemeCard";
|
||||
import { useProxy } from "@core/vendetta/storage";
|
||||
import { installTheme, Theme, themes } from "@lib/addons/themes";
|
||||
import { getCurrentTheme, installTheme, themes, VdThemeInfo } from "@lib/addons/themes";
|
||||
import { colorsPref } from "@lib/addons/themes/colors/preferences";
|
||||
import { updateBunnyColor } from "@lib/addons/themes/colors/updater";
|
||||
import { Author } from "@lib/addons/types";
|
||||
import { findAssetId } from "@lib/api/assets";
|
||||
import { settings } from "@lib/api/settings";
|
||||
import { Button } from "@metro/common/components";
|
||||
import { useObservable } from "@lib/api/storage";
|
||||
import { ActionSheet, BottomSheetTitleHeader, Button, TableRadioGroup, TableRadioRow, TableRowIcon } from "@metro/common/components";
|
||||
import { View } from "react-native";
|
||||
|
||||
export default function Themes() {
|
||||
useProxy(settings);
|
||||
useProxy(themes);
|
||||
|
||||
return (
|
||||
<AddonPage<Theme>
|
||||
<AddonPage<VdThemeInfo>
|
||||
title={Strings.THEMES}
|
||||
searchKeywords={[
|
||||
"data.name",
|
||||
"data.description",
|
||||
p => p.data.authors?.map((a: Author) => a.name).join(", ")
|
||||
p => p.data.authors?.map((a: Author) => a.name).join(", ") ?? ""
|
||||
]}
|
||||
sortOptions={{
|
||||
"Name (A-Z)": (a, b) => a.name.localeCompare(b.name),
|
||||
"Name (Z-A)": (a, b) => b.name.localeCompare(a.name)
|
||||
"Name (A-Z)": (a, b) => a.data.name.localeCompare(b.data.name),
|
||||
"Name (Z-A)": (a, b) => b.data.name.localeCompare(a.data.name)
|
||||
}}
|
||||
installAction={{
|
||||
label: "Install a theme",
|
||||
|
|
@ -38,6 +43,39 @@ export default function Themes() {
|
|||
/>
|
||||
}}
|
||||
CardComponent={ThemeCard}
|
||||
OptionsActionSheetComponent={() => {
|
||||
useObservable([colorsPref]);
|
||||
|
||||
return <ActionSheet>
|
||||
<BottomSheetTitleHeader title="Options" />
|
||||
<View style={{ paddingVertical: 20, gap: 12 }}>
|
||||
<TableRadioGroup
|
||||
title="Override Theme Type"
|
||||
value={colorsPref.type ?? "auto"}
|
||||
hasIcons={true}
|
||||
onChange={type => {
|
||||
colorsPref.type = type !== "auto" ? type as "dark" | "light" : undefined;
|
||||
getCurrentTheme()?.data && updateBunnyColor(getCurrentTheme()!.data!, { update: true });
|
||||
}}
|
||||
>
|
||||
<TableRadioRow icon={<TableRowIcon source={findAssetId("RobotIcon")} />} label="Auto" value="auto" />
|
||||
<TableRadioRow icon={<TableRowIcon source={findAssetId("ThemeDarkIcon")} />} label="Dark" value="dark" />
|
||||
<TableRadioRow icon={<TableRowIcon source={findAssetId("ThemeLightIcon")} />} label="Light" value="light" />
|
||||
</TableRadioGroup>
|
||||
<TableRadioGroup
|
||||
title="Chat Background"
|
||||
value={colorsPref.customBackground ?? "shown"}
|
||||
hasIcons={true}
|
||||
onChange={type => {
|
||||
colorsPref.customBackground = type !== "shown" ? type as "hidden" : null;
|
||||
}}
|
||||
>
|
||||
<TableRadioRow icon={<TableRowIcon source={findAssetId("ImageIcon")} />} label="Show" value={"shown"} />
|
||||
<TableRadioRow icon={<TableRowIcon source={findAssetId("DenyIcon")} />} label="Hide" value={"hidden"} />
|
||||
</TableRadioGroup>
|
||||
</View>
|
||||
</ActionSheet>;
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -142,7 +142,8 @@ export function wrapSync<T extends Promise<any>>(store: T): Awaited<T> {
|
|||
|
||||
export function awaitStorage(...stores: any[]) {
|
||||
return Promise.all(
|
||||
stores.map(store => new Promise<void>(res => store[syncAwaitSymbol](res)))
|
||||
stores.map(store =>
|
||||
new Promise<void>(res => store[syncAwaitSymbol](res)))
|
||||
);
|
||||
}
|
||||
|
||||
|
|
@ -150,11 +151,14 @@ export interface StorageBackend {
|
|||
get: () => unknown | Promise<unknown>;
|
||||
set: (data: unknown) => void | Promise<void>;
|
||||
}
|
||||
|
||||
const ILLEGAL_CHARS_REGEX = /[<>:"/\\|?*]/g;
|
||||
|
||||
const filePathFixer = (file: string): string => Platform.select({
|
||||
default: file,
|
||||
ios: FileManager.saveFileToGallery ? file : `Documents/${file}`,
|
||||
});
|
||||
|
||||
const getMMKVPath = (name: string): string => {
|
||||
if (ILLEGAL_CHARS_REGEX.test(name)) {
|
||||
// Replace forbidden characters with hyphens
|
||||
|
|
|
|||
21
src/index.ts
21
src/index.ts
|
|
@ -6,41 +6,24 @@ import { initVendettaObject } from "@core/vendetta/api";
|
|||
import { VdPluginManager } from "@core/vendetta/plugins";
|
||||
import { updateFonts } from "@lib/addons/fonts";
|
||||
import { initPlugins, updatePlugins } from "@lib/addons/plugins";
|
||||
import { initThemes, patchChatBackground } from "@lib/addons/themes";
|
||||
import { initThemes } from "@lib/addons/themes";
|
||||
import { patchCommands } from "@lib/api/commands";
|
||||
import { patchLogHook } from "@lib/api/debug";
|
||||
import { injectFluxInterceptor } from "@lib/api/flux";
|
||||
import { writeFile } from "@lib/api/native/fs";
|
||||
import { isPyonLoader, isThemeSupported } from "@lib/api/native/loader";
|
||||
import { patchJsx } from "@lib/api/react/jsx";
|
||||
import { logger } from "@lib/utils/logger";
|
||||
import { patchSettings } from "@ui/settings";
|
||||
|
||||
import * as lib from "./lib";
|
||||
|
||||
function maybeLoadThemes() {
|
||||
if (!isThemeSupported()) return;
|
||||
|
||||
try {
|
||||
if (isPyonLoader()) {
|
||||
writeFile("../vendetta_theme.json", "null");
|
||||
}
|
||||
initThemes();
|
||||
} catch (e) {
|
||||
console.error("Failed to initialize themes", e);
|
||||
}
|
||||
}
|
||||
|
||||
export default async () => {
|
||||
maybeLoadThemes();
|
||||
|
||||
// Load everything in parallel
|
||||
await Promise.all([
|
||||
initThemes(),
|
||||
injectFluxInterceptor(),
|
||||
patchSettings(),
|
||||
patchLogHook(),
|
||||
patchCommands(),
|
||||
patchChatBackground(),
|
||||
patchJsx(),
|
||||
initVendettaObject(),
|
||||
initFetchI18nStrings(),
|
||||
|
|
|
|||
19
src/lib/addons/themes/colors/index.ts
Normal file
19
src/lib/addons/themes/colors/index.ts
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
|
||||
import patchChatBackground from "./patches/background";
|
||||
import patchDefinitionAndResolver from "./patches/resolver";
|
||||
import patchStorage from "./patches/storage";
|
||||
import { ColorManifest } from "./types";
|
||||
import { updateBunnyColor } from "./updater";
|
||||
|
||||
/** @internal */
|
||||
export default function initColors(manifest: ColorManifest | null) {
|
||||
const patches = [
|
||||
patchStorage(),
|
||||
patchDefinitionAndResolver(),
|
||||
patchChatBackground()
|
||||
];
|
||||
|
||||
if (manifest) updateBunnyColor(manifest, { update: false });
|
||||
|
||||
return () => patches.forEach(p => p());
|
||||
}
|
||||
136
src/lib/addons/themes/colors/parser.ts
Normal file
136
src/lib/addons/themes/colors/parser.ts
Normal file
|
|
@ -0,0 +1,136 @@
|
|||
import { findByProps } from "@metro";
|
||||
import chroma from "chroma-js";
|
||||
import { omit } from "es-toolkit";
|
||||
import { Platform, processColor } from "react-native";
|
||||
|
||||
import { colorsPref } from "./preferences";
|
||||
import { ColorManifest, InternalColorDefinition } from "./types";
|
||||
|
||||
const tokenRef = findByProps("SemanticColor");
|
||||
|
||||
export function parseColorManifest(manifest: ColorManifest): InternalColorDefinition {
|
||||
const resolveType = (type = "dark") => (colorsPref.type ?? type) === "dark" ? "darker" : "light";
|
||||
|
||||
if (manifest.spec === 3) {
|
||||
const semanticColorDefinitions: InternalColorDefinition["semantic"] = {};
|
||||
|
||||
for (const [semanticColorKey, semanticColorValue] of Object.entries(manifest.semantic ?? {})) {
|
||||
if (typeof semanticColorValue === "object") {
|
||||
const { type, value, opacity: semanticColorOpacity } = semanticColorValue;
|
||||
|
||||
if (type === "raw") {
|
||||
semanticColorDefinitions[semanticColorKey] = {
|
||||
value,
|
||||
opacity: semanticColorOpacity ?? 1,
|
||||
};
|
||||
} else {
|
||||
const rawColorValue = tokenRef.RawColor[value];
|
||||
semanticColorDefinitions[semanticColorKey] = {
|
||||
value: rawColorValue,
|
||||
opacity: semanticColorOpacity ?? 1,
|
||||
};
|
||||
}
|
||||
} else if (typeof semanticColorValue === "string") {
|
||||
if (semanticColorValue.startsWith("#")) {
|
||||
semanticColorDefinitions[semanticColorKey] = {
|
||||
value: chroma.hex(semanticColorValue).hex(),
|
||||
opacity: 1,
|
||||
};
|
||||
} else {
|
||||
semanticColorDefinitions[semanticColorKey] = {
|
||||
value: tokenRef.RawColor[semanticColorValue],
|
||||
opacity: 1,
|
||||
};
|
||||
}
|
||||
} else {
|
||||
throw new Error(`Invalid semantic definitions: ${semanticColorValue}`);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
spec: 3,
|
||||
reference: resolveType(manifest.type),
|
||||
semantic: semanticColorDefinitions,
|
||||
raw: manifest.raw ?? {},
|
||||
background: manifest.background,
|
||||
};
|
||||
} else if (manifest.spec === 2) { // is Vendetta theme
|
||||
const semanticDefinitions: InternalColorDefinition["semantic"] = {};
|
||||
const background: InternalColorDefinition["background"] | undefined = manifest.background ? {
|
||||
...omit(manifest.background, ["alpha"]),
|
||||
opacity: manifest.background.alpha
|
||||
} : undefined;
|
||||
|
||||
if (manifest.semanticColors) {
|
||||
for (const key in manifest.semanticColors) {
|
||||
const values = manifest.semanticColors[key].map(c => c || undefined).slice(0, 2);
|
||||
if (!values[0]) continue;
|
||||
|
||||
semanticDefinitions[key] = {
|
||||
value: normalizeToHex(values[resolveType() === "light" ? 1 : 0])!,
|
||||
opacity: 1
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
if (manifest.rawColors) {
|
||||
for (const key in manifest.rawColors) {
|
||||
const value = manifest.rawColors[key];
|
||||
if (!value) continue;
|
||||
manifest.rawColors[key] = normalizeToHex(value)!;
|
||||
}
|
||||
|
||||
if (Platform.OS === "android") applyAndroidAlphaKeys(manifest.rawColors);
|
||||
}
|
||||
|
||||
|
||||
return {
|
||||
spec: 2,
|
||||
reference: resolveType(),
|
||||
semantic: semanticDefinitions,
|
||||
raw: manifest.rawColors ?? {},
|
||||
background
|
||||
};
|
||||
}
|
||||
|
||||
throw new Error("Invalid theme spec");
|
||||
}
|
||||
|
||||
export function applyAndroidAlphaKeys(rawColors?: Record<string, string>) {
|
||||
if (!rawColors) return;
|
||||
|
||||
// these are native Discord Android keys
|
||||
const alphaMap: Record<string, [string, number]> = {
|
||||
"BLACK_ALPHA_60": ["BLACK", 0.6],
|
||||
"BRAND_NEW_360_ALPHA_20": ["BRAND_360", 0.2],
|
||||
"BRAND_NEW_360_ALPHA_25": ["BRAND_360", 0.25],
|
||||
"BRAND_NEW_500_ALPHA_20": ["BRAND_500", 0.2],
|
||||
"PRIMARY_DARK_500_ALPHA_20": ["PRIMARY_500", 0.2],
|
||||
"PRIMARY_DARK_700_ALPHA_60": ["PRIMARY_700", 0.6],
|
||||
"STATUS_GREEN_500_ALPHA_20": ["GREEN_500", 0.2],
|
||||
"STATUS_RED_500_ALPHA_20": ["RED_500", 0.2],
|
||||
};
|
||||
|
||||
for (const key in alphaMap) {
|
||||
const [colorKey, alpha] = alphaMap[key];
|
||||
if (!rawColors[colorKey]) continue;
|
||||
rawColors[key] = chroma(rawColors[colorKey]).alpha(alpha).hex();
|
||||
}
|
||||
|
||||
return rawColors;
|
||||
}
|
||||
|
||||
export function normalizeToHex(colorString: string | undefined): string | undefined {
|
||||
if (colorString === undefined) return undefined;
|
||||
if (chroma.valid(colorString)) return chroma(colorString).hex();
|
||||
|
||||
const color = Number(processColor(colorString));
|
||||
|
||||
return chroma.rgb(
|
||||
color >> 16 & 0xff, // red
|
||||
color >> 8 & 0xff, // green
|
||||
color & 0xff, // blue
|
||||
color >> 24 & 0xff // alpha
|
||||
).hex();
|
||||
}
|
||||
|
||||
51
src/lib/addons/themes/colors/patches/background.tsx
Normal file
51
src/lib/addons/themes/colors/patches/background.tsx
Normal file
|
|
@ -0,0 +1,51 @@
|
|||
import { colorsPref } from "@lib/addons/themes/colors/preferences";
|
||||
import { _colorRef } from "@lib/addons/themes/colors/updater";
|
||||
import { after } from "@lib/api/patcher";
|
||||
import { useObservable } from "@lib/api/storage";
|
||||
import { findInReactTree } from "@lib/utils";
|
||||
import { lazyDestructure } from "@lib/utils/lazy";
|
||||
import { findByNameLazy, findByProps } from "@metro";
|
||||
import chroma from "chroma-js";
|
||||
import { ImageBackground } from "react-native";
|
||||
|
||||
const MessagesWrapperConnected = findByNameLazy("MessagesWrapperConnected", false);
|
||||
const { MessagesWrapper } = lazyDestructure(() => findByProps("MessagesWrapper"));
|
||||
|
||||
export default function patchChatBackground() {
|
||||
const patches = [
|
||||
after("default", MessagesWrapperConnected, (_, ret) => {
|
||||
useObservable([colorsPref]);
|
||||
if (!_colorRef.current || !_colorRef.current.background?.url || colorsPref.customBackground === "hidden") return ret;
|
||||
|
||||
return <ImageBackground
|
||||
style={{ flex: 1, height: "100%" }}
|
||||
source={_colorRef.current.background?.url && { uri: _colorRef.current.background.url } || 0}
|
||||
blurRadius={typeof _colorRef.current.background?.blur === "number" ? _colorRef.current.background?.blur : 0}
|
||||
>
|
||||
{ret}
|
||||
</ImageBackground>;
|
||||
}),
|
||||
after("render", MessagesWrapper.prototype, (_, ret) => {
|
||||
if (!_colorRef.current || !_colorRef.current.background?.url) return;
|
||||
const messagesComponent = findInReactTree(
|
||||
ret,
|
||||
x => x && "HACK_fixModalInteraction" in x.props && x?.props?.style
|
||||
);
|
||||
|
||||
if (messagesComponent) {
|
||||
const backgroundColor = chroma(
|
||||
messagesComponent.props.style.backgroundColor || "black"
|
||||
).alpha(
|
||||
1 - (_colorRef.current.background?.opacity ?? 1)
|
||||
);
|
||||
|
||||
messagesComponent.props.style = [
|
||||
messagesComponent.props.style,
|
||||
{ backgroundColor }
|
||||
];
|
||||
}
|
||||
})
|
||||
];
|
||||
|
||||
return () => patches.forEach(x => x());
|
||||
}
|
||||
88
src/lib/addons/themes/colors/patches/resolver.ts
Normal file
88
src/lib/addons/themes/colors/patches/resolver.ts
Normal file
|
|
@ -0,0 +1,88 @@
|
|||
import { _colorRef } from "@lib/addons/themes/colors/updater";
|
||||
import { ThemeManager } from "@lib/api/native/modules";
|
||||
import { before, instead } from "@lib/api/patcher";
|
||||
import { findByProps } from "@metro";
|
||||
import { byMutableProp } from "@metro/filters";
|
||||
import { createLazyModule } from "@metro/lazy";
|
||||
import chroma from "chroma-js";
|
||||
|
||||
const tokenReference = findByProps("SemanticColor");
|
||||
const isThemeModule = createLazyModule(byMutableProp("isThemeDark"));
|
||||
|
||||
const SEMANTIC_FALLBACK_MAP: Record<string, string> = {
|
||||
"BG_BACKDROP": "BACKGROUND_FLOATING",
|
||||
"BG_BASE_PRIMARY": "BACKGROUND_PRIMARY",
|
||||
"BG_BASE_SECONDARY": "BACKGROUND_SECONDARY",
|
||||
"BG_BASE_TERTIARY": "BACKGROUND_SECONDARY_ALT",
|
||||
"BG_MOD_FAINT": "BACKGROUND_MODIFIER_ACCENT",
|
||||
"BG_MOD_STRONG": "BACKGROUND_MODIFIER_ACCENT",
|
||||
"BG_MOD_SUBTLE": "BACKGROUND_MODIFIER_ACCENT",
|
||||
"BG_SURFACE_OVERLAY": "BACKGROUND_FLOATING",
|
||||
"BG_SURFACE_OVERLAY_TMP": "BACKGROUND_FLOATING",
|
||||
"BG_SURFACE_RAISED": "BACKGROUND_MOBILE_PRIMARY"
|
||||
};
|
||||
|
||||
export default function patchDefinitionAndResolver() {
|
||||
const callback = ([theme]: any[]) => theme === _colorRef.key ? [_colorRef.current!.reference] : void 0;
|
||||
|
||||
Object.keys(tokenReference.RawColor).forEach(key => {
|
||||
Object.defineProperty(tokenReference.RawColor, key, {
|
||||
configurable: true,
|
||||
enumerable: true,
|
||||
get: () => {
|
||||
const ret = _colorRef.current?.raw[key];
|
||||
return ret || _colorRef.origRaw[key];
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
const unpatches = [
|
||||
before("isThemeDark", isThemeModule, callback),
|
||||
before("isThemeLight", isThemeModule, callback),
|
||||
before("updateTheme", ThemeManager, callback),
|
||||
instead("resolveSemanticColor", tokenReference.default.meta ?? tokenReference.default.internal, (args: any[], orig: any) => {
|
||||
if (!_colorRef.current) return orig(...args);
|
||||
if (args[0] !== _colorRef.key) return orig(...args);
|
||||
|
||||
args[0] = _colorRef.current.reference;
|
||||
|
||||
const [name, colorDef] = extractInfo(_colorRef.current!.reference, args[1]);
|
||||
|
||||
let semanticDef = _colorRef.current.semantic[name];
|
||||
if (!semanticDef && _colorRef.current.spec === 2 && name in SEMANTIC_FALLBACK_MAP) {
|
||||
semanticDef = _colorRef.current.semantic[SEMANTIC_FALLBACK_MAP[name]];
|
||||
}
|
||||
|
||||
if (semanticDef?.value) {
|
||||
return chroma(semanticDef.value).alpha(semanticDef.opacity).hex();
|
||||
}
|
||||
|
||||
const rawValue = _colorRef.current.raw[colorDef.raw];
|
||||
if (rawValue) {
|
||||
// Set opacity if needed
|
||||
return colorDef.opacity === 1 ? rawValue : chroma(rawValue).alpha(colorDef.opacity).hex();
|
||||
}
|
||||
|
||||
// Fallback to default
|
||||
return orig(...args);
|
||||
}),
|
||||
() => {
|
||||
// Not the actual module but.. yeah.
|
||||
Object.defineProperty(tokenReference, "RawColor", {
|
||||
configurable: true,
|
||||
writable: true,
|
||||
value: _colorRef.origRaw
|
||||
});
|
||||
}
|
||||
];
|
||||
|
||||
return () => unpatches.forEach(p => p());
|
||||
}
|
||||
|
||||
function extractInfo(themeName: string, colorObj: any): [name: string, colorDef: any] {
|
||||
// @ts-ignore - assigning to extractInfo._sym
|
||||
const propName = colorObj[extractInfo._sym ??= Object.getOwnPropertySymbols(colorObj)[0]];
|
||||
const colorDef = tokenReference.SemanticColor[propName];
|
||||
|
||||
return [propName, colorDef[themeName]];
|
||||
}
|
||||
38
src/lib/addons/themes/colors/patches/storage.ts
Normal file
38
src/lib/addons/themes/colors/patches/storage.ts
Normal file
|
|
@ -0,0 +1,38 @@
|
|||
import { _colorRef } from "@lib/addons/themes/colors/updater";
|
||||
import { after, before } from "@lib/api/patcher";
|
||||
import { findInTree } from "@lib/utils";
|
||||
import { proxyLazy } from "@lib/utils/lazy";
|
||||
import { findByProps } from "@metro";
|
||||
|
||||
const mmkvStorage = proxyLazy(() => {
|
||||
const newModule = findByProps("impl");
|
||||
if (typeof newModule?.impl === "object") return newModule.impl;
|
||||
return findByProps("storage");
|
||||
});
|
||||
|
||||
export default function patchStorage() {
|
||||
const patchedKeys = new Set(["ThemeStore", "SelectivelySyncedUserSettingsStore"]);
|
||||
|
||||
const patches = [
|
||||
after("get", mmkvStorage, ([key], ret) => {
|
||||
if (!_colorRef.current || !patchedKeys.has(key)) return;
|
||||
|
||||
const state = findInTree(ret._state, s => typeof s.theme === "string");
|
||||
if (state) state.theme = _colorRef.key;
|
||||
}),
|
||||
before("set", mmkvStorage, ([key, value]) => {
|
||||
if (!patchedKeys.has(key)) return;
|
||||
|
||||
const json = JSON.stringify(value);
|
||||
const lastSetDiscordTheme = _colorRef.lastSetDiscordTheme ?? "darker";
|
||||
const replaced = json.replace(
|
||||
/"theme":"bn-theme-\d+"/,
|
||||
`"theme":${JSON.stringify(lastSetDiscordTheme)}`
|
||||
);
|
||||
|
||||
return [key, JSON.parse(replaced)];
|
||||
})
|
||||
];
|
||||
|
||||
return () => patches.forEach(p => p());
|
||||
}
|
||||
18
src/lib/addons/themes/colors/preferences.ts
Normal file
18
src/lib/addons/themes/colors/preferences.ts
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
import { createStorage } from "@lib/api/storage";
|
||||
|
||||
interface BunnyColorPreferencesStorage {
|
||||
selected: string | null;
|
||||
type?: "dark" | "light" | null;
|
||||
customBackground: "hidden" | null;
|
||||
per?: Record<string, { autoUpdate?: string; } | undefined>;
|
||||
}
|
||||
|
||||
export const colorsPref = createStorage<BunnyColorPreferencesStorage>(
|
||||
"themes/colors/preferences.json",
|
||||
{
|
||||
dflt: {
|
||||
selected: null,
|
||||
customBackground: null
|
||||
}
|
||||
}
|
||||
);
|
||||
49
src/lib/addons/themes/colors/types.ts
Normal file
49
src/lib/addons/themes/colors/types.ts
Normal file
|
|
@ -0,0 +1,49 @@
|
|||
import { Author, BunnyManifest } from "@lib/addons/types";
|
||||
|
||||
interface SemanticReference {
|
||||
type: "color" | "raw";
|
||||
value: string;
|
||||
opacity?: number;
|
||||
}
|
||||
|
||||
interface BackgroundDefinition {
|
||||
url: string;
|
||||
blur?: number;
|
||||
opacity?: number;
|
||||
}
|
||||
|
||||
export interface BunnyColorManifest extends BunnyManifest {
|
||||
spec: 3;
|
||||
type: "dark" | "light";
|
||||
semantic?: Record<string, string | SemanticReference>;
|
||||
raw?: Record<string, string>;
|
||||
background?: BackgroundDefinition;
|
||||
}
|
||||
|
||||
export interface VendettaThemeManifest {
|
||||
spec: 2;
|
||||
name: string;
|
||||
description?: string;
|
||||
authors?: Author[];
|
||||
semanticColors?: Record<string, (string | false)[]>;
|
||||
rawColors?: Record<string, string>;
|
||||
background?: {
|
||||
url: string;
|
||||
blur?: number;
|
||||
alpha?: number;
|
||||
};
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
export interface InternalColorDefinition {
|
||||
spec: 2 | 3;
|
||||
reference: "darker" | "light";
|
||||
semantic: Record<string, {
|
||||
value: string;
|
||||
opacity: number;
|
||||
}>;
|
||||
raw: Record<string, string>;
|
||||
background?: BackgroundDefinition;
|
||||
}
|
||||
|
||||
export type ColorManifest = BunnyColorManifest | VendettaThemeManifest;
|
||||
59
src/lib/addons/themes/colors/updater.ts
Normal file
59
src/lib/addons/themes/colors/updater.ts
Normal file
|
|
@ -0,0 +1,59 @@
|
|||
import { settings } from "@lib/api/settings";
|
||||
import { findByProps, findByPropsLazy, findByStoreNameLazy } from "@metro";
|
||||
|
||||
import { parseColorManifest } from "./parser";
|
||||
import { ColorManifest, InternalColorDefinition } from "./types";
|
||||
|
||||
const tokenRef = findByProps("SemanticColor");
|
||||
const origRawColor = { ...tokenRef.RawColor };
|
||||
const AppearanceManager = findByPropsLazy("updateTheme");
|
||||
const ThemeStore = findByStoreNameLazy("ThemeStore");
|
||||
const FormDivider = findByPropsLazy("DIVIDER_COLORS");
|
||||
|
||||
let _inc = 1;
|
||||
|
||||
interface InternalColorRef {
|
||||
key: `bn-theme-${string}`;
|
||||
current: InternalColorDefinition | null;
|
||||
readonly origRaw: Record<string, string>;
|
||||
lastSetDiscordTheme: string;
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
export const _colorRef: InternalColorRef = {
|
||||
current: null,
|
||||
key: `bn-theme-${_inc}`,
|
||||
origRaw: origRawColor,
|
||||
lastSetDiscordTheme: "darker"
|
||||
};
|
||||
|
||||
export function updateBunnyColor(colorManifest: ColorManifest | null, { update = true }) {
|
||||
if (settings.safeMode?.enabled) return;
|
||||
|
||||
const internalDef = colorManifest ? parseColorManifest(colorManifest) : null;
|
||||
const ref = Object.assign(_colorRef, {
|
||||
current: internalDef,
|
||||
key: `bn-theme-${++_inc}`,
|
||||
lastSetDiscordTheme: !ThemeStore.theme.startsWith("bn-theme-")
|
||||
? ThemeStore.theme
|
||||
: _colorRef.lastSetDiscordTheme
|
||||
});
|
||||
|
||||
if (internalDef != null) {
|
||||
tokenRef.Theme[ref.key.toUpperCase()] = ref.key;
|
||||
FormDivider.DIVIDER_COLORS[ref.key] = FormDivider.DIVIDER_COLORS[ref.current!.reference];
|
||||
|
||||
Object.keys(tokenRef.Shadow).forEach(k => tokenRef.Shadow[k][ref.key] = tokenRef.Shadow[k][ref.current!.reference]);
|
||||
Object.keys(tokenRef.SemanticColor).forEach(k => {
|
||||
tokenRef.SemanticColor[k][ref.key] = {
|
||||
...tokenRef.SemanticColor[k][ref.current!.reference]
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
if (update) {
|
||||
AppearanceManager.setShouldSyncAppearanceSettings(false);
|
||||
AppearanceManager.updateTheme(internalDef != null ? ref.key : ref.lastSetDiscordTheme);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -1,77 +1,25 @@
|
|||
/**
|
||||
* Theming system in Bunny is currently a prototype, expect an unreadable theme implementation below
|
||||
*/
|
||||
|
||||
import { awaitStorage, createFileBackend, createMMKVBackend, createStorage, wrapSync } from "@core/vendetta/storage";
|
||||
import { Author } from "@lib/addons/types";
|
||||
import { getStoredTheme, getThemeFilePath } from "@lib/api/native/loader";
|
||||
import { ThemeManager } from "@lib/api/native/modules";
|
||||
import { after, before, instead } from "@lib/api/patcher";
|
||||
import { findInReactTree, safeFetch } from "@lib/utils";
|
||||
import { lazyDestructure, proxyLazy } from "@lib/utils/lazy";
|
||||
import { byMutableProp } from "@metro/filters";
|
||||
import { createLazyModule } from "@metro/lazy";
|
||||
import { findByNameLazy, findByProps, findByPropsLazy, findByStoreNameLazy } from "@metro/wrappers";
|
||||
import chroma from "chroma-js";
|
||||
import { ImageBackground, Platform, processColor } from "react-native";
|
||||
import { writeFile } from "@lib/api/native/fs";
|
||||
import { getStoredTheme, getThemeFilePath, isPyonLoader, isThemeSupported } from "@lib/api/native/loader";
|
||||
import { awaitStorage as newAwaitStorage } from "@lib/api/storage";
|
||||
import { safeFetch } from "@lib/utils";
|
||||
import { Platform } from "react-native";
|
||||
|
||||
export interface ThemeData {
|
||||
name: string;
|
||||
description?: string;
|
||||
authors?: Author[];
|
||||
spec: number;
|
||||
semanticColors?: Record<string, (string | false)[]>;
|
||||
rawColors?: Record<string, string>;
|
||||
background?: {
|
||||
url: string;
|
||||
blur?: number;
|
||||
/**
|
||||
* The alpha value of the background.
|
||||
* `CHAT_BACKGROUND` of semanticColors alpha value will be ignored when this is specified
|
||||
*/
|
||||
alpha?: number;
|
||||
};
|
||||
}
|
||||
import initColors from "./colors";
|
||||
import { applyAndroidAlphaKeys, normalizeToHex } from "./colors/parser";
|
||||
import { colorsPref } from "./colors/preferences";
|
||||
import { VendettaThemeManifest } from "./colors/types";
|
||||
import { updateBunnyColor } from "./colors/updater";
|
||||
|
||||
export interface Theme {
|
||||
export interface VdThemeInfo {
|
||||
id: string;
|
||||
selected: boolean;
|
||||
data: ThemeData;
|
||||
data: VendettaThemeManifest;
|
||||
}
|
||||
|
||||
//! As of 173.10, early-finding this does not work.
|
||||
// Somehow, this is late enough, though?
|
||||
export const color = findByPropsLazy("SemanticColor");
|
||||
export const themes = wrapSync(createStorage<Record<string, VdThemeInfo>>(createMMKVBackend("VENDETTA_THEMES")));
|
||||
|
||||
const mmkvStorage = proxyLazy(() => {
|
||||
const newModule = findByProps("impl");
|
||||
if (typeof newModule?.impl === "object") return newModule.impl;
|
||||
return findByProps("storage");
|
||||
});
|
||||
|
||||
const appearanceManager = findByPropsLazy("updateTheme");
|
||||
const ThemeStore = findByStoreNameLazy("ThemeStore");
|
||||
const formDividerModule = findByPropsLazy("DIVIDER_COLORS");
|
||||
const MessagesWrapperConnected = findByNameLazy("MessagesWrapperConnected", false);
|
||||
const { MessagesWrapper } = lazyDestructure(() => findByProps("MessagesWrapper"));
|
||||
const isThemeModule = createLazyModule(byMutableProp("isThemeDark"));
|
||||
|
||||
export const themes = wrapSync(createStorage<Record<string, Theme>>(createMMKVBackend("VENDETTA_THEMES")));
|
||||
|
||||
const semanticAlternativeMap: Record<string, string> = {
|
||||
"BG_BACKDROP": "BACKGROUND_FLOATING",
|
||||
"BG_BASE_PRIMARY": "BACKGROUND_PRIMARY",
|
||||
"BG_BASE_SECONDARY": "BACKGROUND_SECONDARY",
|
||||
"BG_BASE_TERTIARY": "BACKGROUND_SECONDARY_ALT",
|
||||
"BG_MOD_FAINT": "BACKGROUND_MODIFIER_ACCENT",
|
||||
"BG_MOD_STRONG": "BACKGROUND_MODIFIER_ACCENT",
|
||||
"BG_MOD_SUBTLE": "BACKGROUND_MODIFIER_ACCENT",
|
||||
"BG_SURFACE_OVERLAY": "BACKGROUND_FLOATING",
|
||||
"BG_SURFACE_OVERLAY_TMP": "BACKGROUND_FLOATING",
|
||||
"BG_SURFACE_RAISED": "BACKGROUND_MOBILE_PRIMARY"
|
||||
};
|
||||
|
||||
async function writeTheme(theme: Theme | {}) {
|
||||
async function writeTheme(theme: VdThemeInfo | {}) {
|
||||
if (typeof theme !== "object") throw new Error("Theme must be an object");
|
||||
|
||||
// Save the current theme as current-theme.json. When supported by loader,
|
||||
|
|
@ -79,59 +27,14 @@ async function writeTheme(theme: Theme | {}) {
|
|||
await createFileBackend(getThemeFilePath() || "theme.json").set(theme);
|
||||
}
|
||||
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
export function patchChatBackground() {
|
||||
const patches = [
|
||||
after("default", MessagesWrapperConnected, (_, ret) => enabled ? React.createElement(ImageBackground, {
|
||||
style: { flex: 1, height: "100%" },
|
||||
source: currentTheme?.data?.background?.url && { uri: currentTheme.data.background.url } || 0,
|
||||
blurRadius: typeof currentTheme?.data?.background?.blur === "number" ? currentTheme?.data?.background?.blur : 0,
|
||||
children: ret,
|
||||
}) : ret),
|
||||
after("render", MessagesWrapper.prototype, (_, ret) => {
|
||||
if (!enabled || !currentTheme?.data?.background?.url) return;
|
||||
|
||||
// HORRIBLE
|
||||
const Messages = findInReactTree(ret, x => x && "HACK_fixModalInteraction" in x.props && x?.props?.style);
|
||||
if (Messages) {
|
||||
Messages.props.style = [
|
||||
Messages.props.style,
|
||||
{
|
||||
backgroundColor: chroma(Messages.props.style.backgroundColor || "black")
|
||||
.alpha(1 - (currentTheme?.data.background?.alpha ?? 1)).hex()
|
||||
},
|
||||
];
|
||||
}
|
||||
else console.error("Didn't find Messages when patching MessagesWrapper!");
|
||||
})
|
||||
];
|
||||
|
||||
return () => patches.forEach(x => x());
|
||||
}
|
||||
|
||||
function normalizeToHex(colorString: string): string {
|
||||
if (chroma.valid(colorString)) return chroma(colorString).hex();
|
||||
|
||||
const color = Number(processColor(colorString));
|
||||
|
||||
return chroma.rgb(
|
||||
color >> 16 & 0xff, // red
|
||||
color >> 8 & 0xff, // green
|
||||
color & 0xff, // blue
|
||||
color >> 24 & 0xff // alpha
|
||||
).hex();
|
||||
}
|
||||
|
||||
// Process data for some compatiblity with native side
|
||||
function processData(data: ThemeData) {
|
||||
function processData(data: VendettaThemeManifest) {
|
||||
if (data.semanticColors) {
|
||||
const { semanticColors } = data;
|
||||
|
||||
for (const key in semanticColors) {
|
||||
for (const index in semanticColors[key]) {
|
||||
semanticColors[key][index] &&= normalizeToHex(semanticColors[key][index] as string);
|
||||
semanticColors[key][index] &&= normalizeToHex(semanticColors[key][index] as string) || false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -140,7 +43,8 @@ function processData(data: ThemeData) {
|
|||
const { rawColors } = data;
|
||||
|
||||
for (const key in rawColors) {
|
||||
data.rawColors[key] = normalizeToHex(rawColors[key]);
|
||||
const normalized = normalizeToHex(rawColors[key]);
|
||||
if (normalized) data.rawColors[key] = normalized;
|
||||
}
|
||||
|
||||
if (Platform.OS === "android") applyAndroidAlphaKeys(rawColors);
|
||||
|
|
@ -153,26 +57,6 @@ function processData(data: ThemeData) {
|
|||
return data;
|
||||
}
|
||||
|
||||
function applyAndroidAlphaKeys(rawColors: Record<string, string>) {
|
||||
// these are native Discord Android keys
|
||||
const alphaMap: Record<string, [string, number]> = {
|
||||
"BLACK_ALPHA_60": ["BLACK", 0.6],
|
||||
"BRAND_NEW_360_ALPHA_20": ["BRAND_360", 0.2],
|
||||
"BRAND_NEW_360_ALPHA_25": ["BRAND_360", 0.25],
|
||||
"BRAND_NEW_500_ALPHA_20": ["BRAND_500", 0.2],
|
||||
"PRIMARY_DARK_500_ALPHA_20": ["PRIMARY_500", 0.2],
|
||||
"PRIMARY_DARK_700_ALPHA_60": ["PRIMARY_700", 0.6],
|
||||
"STATUS_GREEN_500_ALPHA_20": ["GREEN_500", 0.2],
|
||||
"STATUS_RED_500_ALPHA_20": ["RED_500", 0.2],
|
||||
};
|
||||
|
||||
for (const key in alphaMap) {
|
||||
const [colorKey, alpha] = alphaMap[key];
|
||||
if (!rawColors[colorKey]) continue;
|
||||
rawColors[key] = chroma(rawColors[colorKey]).alpha(alpha).hex();
|
||||
}
|
||||
}
|
||||
|
||||
export async function fetchTheme(id: string, selected = false) {
|
||||
let themeJSON: any;
|
||||
|
||||
|
|
@ -188,10 +72,9 @@ export async function fetchTheme(id: string, selected = false) {
|
|||
data: processData(themeJSON),
|
||||
};
|
||||
|
||||
// TODO: Should we prompt when the selected theme is updated?
|
||||
if (selected) {
|
||||
writeTheme(themes[id]);
|
||||
applyTheme(themes[id], vdThemeFallback);
|
||||
updateBunnyColor(themes[id].data, { update: true });
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -200,15 +83,17 @@ export async function installTheme(id: string) {
|
|||
await fetchTheme(id);
|
||||
}
|
||||
|
||||
export function selectTheme(theme: Theme | null, write = true) {
|
||||
export function selectTheme(theme: VdThemeInfo | null, write = true) {
|
||||
if (theme) theme.selected = true;
|
||||
Object.keys(themes).forEach(
|
||||
k => themes[k].selected = themes[k].id === theme?.id
|
||||
);
|
||||
|
||||
if (theme == null && write) {
|
||||
updateBunnyColor(null, { update: true });
|
||||
return writeTheme({});
|
||||
} else if (theme) {
|
||||
updateBunnyColor(theme.data, { update: true });
|
||||
return writeTheme(theme);
|
||||
}
|
||||
}
|
||||
|
|
@ -221,13 +106,6 @@ export async function removeTheme(id: string) {
|
|||
return theme.selected;
|
||||
}
|
||||
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
export function getThemeFromLoader(): Theme | null {
|
||||
return getStoredTheme();
|
||||
}
|
||||
|
||||
export async function updateThemes() {
|
||||
await awaitStorage(themes);
|
||||
const currentTheme = getThemeFromLoader();
|
||||
|
|
@ -235,176 +113,34 @@ export async function updateThemes() {
|
|||
}
|
||||
|
||||
export function getCurrentTheme() {
|
||||
return currentTheme;
|
||||
}
|
||||
|
||||
const origRawColor = { ...color.RawColor };
|
||||
|
||||
let inc = 0;
|
||||
let vdKey = "vd-theme";
|
||||
|
||||
let vdThemeFallback = "darker";
|
||||
let enabled = false;
|
||||
let currentTheme: Theme | null;
|
||||
let storageResolved = false;
|
||||
|
||||
const discordThemes = new Set(["darker", "midnight", "dark", "light"]);
|
||||
function isDiscordTheme(name: string) {
|
||||
return discordThemes.has(name);
|
||||
}
|
||||
|
||||
function patchColor() {
|
||||
const callback = ([theme]: any[]) => theme === vdKey ? [vdThemeFallback] : void 0;
|
||||
|
||||
Object.keys(color.RawColor).forEach(k => {
|
||||
Object.defineProperty(color.RawColor, k, {
|
||||
configurable: true,
|
||||
enumerable: true,
|
||||
get: () => {
|
||||
return enabled ? currentTheme?.data?.rawColors?.[k] ?? origRawColor[k] : origRawColor[k];
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
before("isThemeDark", isThemeModule, callback);
|
||||
before("isThemeLight", isThemeModule, callback);
|
||||
before("updateTheme", ThemeManager, callback);
|
||||
|
||||
after("get", mmkvStorage, ([a], ret) => {
|
||||
if (a === "SelectivelySyncedUserSettingsStore") {
|
||||
storageResolved = true;
|
||||
if (ret?._state?.appearance?.settings?.theme && enabled) {
|
||||
vdThemeFallback = ret._state.appearance.settings.theme;
|
||||
ret._state.appearance.settings.theme = vdKey;
|
||||
}
|
||||
} else if (a === "ThemeStore") {
|
||||
storageResolved = true;
|
||||
if (ret?._state?.theme && enabled) {
|
||||
vdThemeFallback = ret._state.theme;
|
||||
ret._state.theme = vdKey;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Prevent setting to real Discord settings
|
||||
before("set", mmkvStorage, args => {
|
||||
if (!args[1]) return;
|
||||
|
||||
const key = args[0];
|
||||
const value = JSON.parse(JSON.stringify(args[1]));
|
||||
|
||||
const interceptors: Record<string, () => void> = ({
|
||||
SelectivelySyncedUserSettingsStore: () => {
|
||||
if (value._state?.appearance?.settings?.theme) {
|
||||
const { theme } = value._state?.appearance?.settings ?? {};
|
||||
if (isDiscordTheme(theme)) {
|
||||
vdThemeFallback = theme;
|
||||
} else {
|
||||
value._state.appearance.settings.theme = vdThemeFallback;
|
||||
}
|
||||
}
|
||||
},
|
||||
ThemeStore: () => {
|
||||
if (value._state?.theme) {
|
||||
const { theme } = value._state;
|
||||
if (isDiscordTheme(theme)) {
|
||||
vdThemeFallback = theme;
|
||||
} else {
|
||||
value._state.theme = vdThemeFallback;
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
if (!(key in interceptors)) return args;
|
||||
|
||||
interceptors[key]();
|
||||
return [key, value];
|
||||
});
|
||||
|
||||
instead("resolveSemanticColor", color.default.meta ?? color.default.internal, (args, orig) => {
|
||||
if (!enabled || !currentTheme) return orig(...args);
|
||||
if (args[0] !== vdKey) return orig(...args);
|
||||
|
||||
args[0] = vdThemeFallback;
|
||||
|
||||
const [name, colorDef] = extractInfo(vdThemeFallback, args[1]);
|
||||
|
||||
const themeIndex = vdThemeFallback === "midnight" ? 2 : vdThemeFallback === "light" ? 1 : 0;
|
||||
|
||||
//! As of 192.7, Tabs v2 uses BG_ semantic colors instead of BACKGROUND_ ones
|
||||
const alternativeName = semanticAlternativeMap[name] ?? name;
|
||||
|
||||
const semanticColorVal = (currentTheme.data?.semanticColors?.[name] ?? currentTheme.data?.semanticColors?.[alternativeName])?.[themeIndex];
|
||||
|
||||
if (semanticColorVal) return semanticColorVal;
|
||||
|
||||
const rawValue = currentTheme.data?.rawColors?.[colorDef.raw];
|
||||
if (rawValue) {
|
||||
// Set opacity if needed
|
||||
return colorDef.opacity === 1 ? rawValue : chroma(rawValue).alpha(colorDef.opacity).hex();
|
||||
}
|
||||
|
||||
// Fallback to default
|
||||
return orig(...args);
|
||||
});
|
||||
}
|
||||
|
||||
function getDefaultFallbackTheme(fallback: string = vdThemeFallback) {
|
||||
const theme = ThemeStore.theme.toLowerCase() as string;
|
||||
|
||||
if (isDiscordTheme(theme)) {
|
||||
return theme;
|
||||
} else {
|
||||
return fallback;
|
||||
}
|
||||
}
|
||||
|
||||
export function applyTheme(appliedTheme: Theme | null, fallbackTheme?: string) {
|
||||
if (!fallbackTheme) fallbackTheme = getDefaultFallbackTheme();
|
||||
|
||||
currentTheme = appliedTheme;
|
||||
enabled = !!currentTheme;
|
||||
vdThemeFallback = fallbackTheme!!;
|
||||
vdKey = `vd-theme-${inc++}-${fallbackTheme}`;
|
||||
|
||||
if (appliedTheme) {
|
||||
color.Theme[vdKey.toUpperCase()] = vdKey;
|
||||
|
||||
formDividerModule.DIVIDER_COLORS[vdKey] = formDividerModule.DIVIDER_COLORS[vdThemeFallback];
|
||||
|
||||
Object.keys(color.Shadow).forEach(k => color.Shadow[k][vdKey] = color.Shadow[k][vdThemeFallback]);
|
||||
Object.keys(color.SemanticColor).forEach(k => {
|
||||
color.SemanticColor[k][vdKey] = {
|
||||
...color.SemanticColor[k][vdThemeFallback],
|
||||
override: appliedTheme?.data?.semanticColors?.[k]?.[0]
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
if (storageResolved) {
|
||||
appearanceManager.setShouldSyncAppearanceSettings(false);
|
||||
appearanceManager.updateTheme(appliedTheme ? vdKey : fallbackTheme);
|
||||
}
|
||||
return Object.values(themes).find(t => t.selected) ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
export function initThemes() {
|
||||
const currentTheme = getThemeFromLoader();
|
||||
enabled = Boolean(currentTheme);
|
||||
|
||||
patchColor();
|
||||
applyTheme(currentTheme, vdThemeFallback);
|
||||
|
||||
updateThemes().catch(e => console.error("Failed to update themes", e));
|
||||
export function getThemeFromLoader(): VdThemeInfo | null {
|
||||
return getStoredTheme();
|
||||
}
|
||||
|
||||
function extractInfo(themeName: string, colorObj: any): [name: string, colorDef: any] {
|
||||
// @ts-ignore - assigning to extractInfo._sym
|
||||
const propName = colorObj[extractInfo._sym ??= Object.getOwnPropertySymbols(colorObj)[0]];
|
||||
const colorDef = color.SemanticColor[propName];
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
export async function initThemes() {
|
||||
if (!isThemeSupported()) return;
|
||||
|
||||
return [propName, colorDef[themeName]];
|
||||
try {
|
||||
if (isPyonLoader()) {
|
||||
writeFile("../vendetta_theme.json", "null");
|
||||
}
|
||||
|
||||
await newAwaitStorage(colorsPref);
|
||||
|
||||
const currentTheme = getThemeFromLoader();
|
||||
initColors(currentTheme?.data ?? null);
|
||||
|
||||
updateThemes().catch(e => console.error("Failed to update themes", e));
|
||||
} catch (e) {
|
||||
console.error("Failed to initialize themes", e);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,4 +1,13 @@
|
|||
export interface Author {
|
||||
name: string;
|
||||
export type Author = { name: string, id?: `${bigint}`; };
|
||||
|
||||
export interface BunnyManifest {
|
||||
id: string;
|
||||
display: {
|
||||
name: string;
|
||||
description?: string;
|
||||
authors?: Author[];
|
||||
};
|
||||
extras?: {
|
||||
[key: string]: any;
|
||||
};
|
||||
}
|
||||
|
|
|
|||
4
src/lib/ui/alerts.ts
Normal file
4
src/lib/ui/alerts.ts
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
import { lazyDestructure } from "@lib/utils/lazy";
|
||||
import { findByProps } from "@metro";
|
||||
|
||||
export const { openAlert, dismissAlert } = lazyDestructure(() => findByProps("openAlert", "dismissAlert"));
|
||||
|
|
@ -1,6 +1,5 @@
|
|||
import { color } from "@lib/addons/themes";
|
||||
import { constants } from "@metro/common";
|
||||
import { findByStoreNameLazy } from "@metro/wrappers";
|
||||
import { findByProps, findByStoreNameLazy } from "@metro/wrappers";
|
||||
|
||||
//! This module is only found on 165.0+, under the assumption that iOS 165.0 is the same as Android 165.0.
|
||||
//* In 167.1, most if not all traces of the old color modules were removed.
|
||||
|
|
@ -10,6 +9,8 @@ import { findByStoreNameLazy } from "@metro/wrappers";
|
|||
// ? These comments are preserved for historical purposes.
|
||||
// const colorModule = findByPropsProxy("colors", "meta");
|
||||
|
||||
const color = findByProps("SemanticColor");
|
||||
|
||||
// ? SemanticColor and default.colors are effectively ThemeColorMap
|
||||
export const semanticColors = (color?.default?.colors ?? constants?.ThemeColorMap) as Record<string, any>;
|
||||
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
|
||||
export * as alerts from "./alerts";
|
||||
export * as components from "./components";
|
||||
export * as settings from "./settings";
|
||||
export * as sheets from "./sheets";
|
||||
|
|
|
|||
File diff suppressed because one or more lines are too long
|
|
@ -12,7 +12,7 @@ const bySingularProp = createFilterDefinition<[string]>(
|
|||
);
|
||||
|
||||
const findSingular = (prop: string) => proxyLazy(() => findExports(bySingularProp(prop))?.[prop]);
|
||||
const findProp = (prop: string) => proxyLazy(() => findByProps(prop)[prop]);
|
||||
const findProp = (...props: string[]) => proxyLazy(() => findByProps(...props)[props[0]]);
|
||||
|
||||
// Discord
|
||||
export const LegacyAlert = findByDisplayNameLazy("FluxContainer(Alert)");
|
||||
|
|
@ -27,18 +27,22 @@ export const ActionSheetRow = findProp("ActionSheetRow");
|
|||
|
||||
// Buttons
|
||||
export const Button = findSingular("Button") as t.Button;
|
||||
export const TwinButtons = findProp("TwinButtons");
|
||||
export const TwinButtons = findProp("TwinButtons") as t.TwinButtons;
|
||||
export const IconButton = findSingular("IconButton") as t.IconButton;
|
||||
export const RowButton = findProp("RowButton") as t.RowButton;
|
||||
|
||||
export const PressableScale = findProp("PressableScale");
|
||||
|
||||
// Tables
|
||||
export const TableRow = findProp("TableRow");
|
||||
export const TableRowIcon = findProp("TableRowIcon");
|
||||
export const TableRowTrailingText = findProp("TableRowTrailingText");
|
||||
export const TableRowGroup = findProp("TableRowGroup");
|
||||
export const TableSwitchRow = findProp("TableSwitchRow");
|
||||
export const TableRow = findProp("TableRow") as t.TableRow;
|
||||
export const TableRowIcon = findProp("TableRowIcon") as t.TableRowIcon;
|
||||
export const TableRowTrailingText = findProp("TableRowTrailingText") as t.TableRowTrailingText;
|
||||
export const TableRowGroup = findProp("TableRowGroup") as t.TableRowGroup;
|
||||
export const TableRadioGroup = findProp("TableRadioGroup") as t.TableRadioGroup;
|
||||
export const TableRadioRow = findProp("TableRadioRow") as t.TableRadioRow;
|
||||
export const TableSwitchRow = findProp("TableSwitchRow") as t.TableSwitchRow;
|
||||
export const TableCheckboxRow = findProp("TableCheckboxRow") as t.TableCheckboxRow;
|
||||
|
||||
export const TableSwitch = findSingular("FormSwitch");
|
||||
export const TableRadio = findSingular("FormRadio");
|
||||
export const TableCheckbox = findSingular("FormCheckbox");
|
||||
|
|
@ -51,11 +55,22 @@ export const FormCheckbox = findSingular("FormCheckbox");
|
|||
export const Card = findProp("Card");
|
||||
export const RedesignCompat = proxyLazy(() => findByProps("RedesignCompat").RedesignCompat);
|
||||
|
||||
// Alert
|
||||
export const AlertModal = findProp("AlertModal");
|
||||
export const AlertActionButton = findProp("AlertActionButton");
|
||||
export const AlertActions = findProp("AlertActions");
|
||||
|
||||
// Pile
|
||||
export const AvatarPile = findSingular("AvatarPile");
|
||||
|
||||
// Misc.
|
||||
export const Stack = findProp("Stack") as t.Stack;
|
||||
export const Avatar = findProp("default", "AvatarSizes", "getStatusSize");
|
||||
|
||||
|
||||
// Inputs
|
||||
export const TextInput = findSingular("TextInput") as t.TextInput;
|
||||
export const TextArea = findSingular("TextArea");
|
||||
|
||||
// SegmentedControl
|
||||
export const SegmentedControl = findProp("SegmentedControl") as t.SegmentedControl;
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
import { DiscordTextStyles } from "@ui/types";
|
||||
import { MutableRefObject, ReactNode, RefObject } from "react";
|
||||
import { TextStyles, ThemeColors } from "@lib/ui/types";
|
||||
import { Falsey } from "lodash";
|
||||
import { FC, MutableRefObject, PropsWithoutRef, ReactNode, RefObject } from "react";
|
||||
import type * as RN from "react-native";
|
||||
import { ImageSourcePropType, PressableProps } from "react-native";
|
||||
import { SharedValue } from "react-native-reanimated";
|
||||
|
|
@ -24,11 +25,16 @@ interface ButtonProps {
|
|||
scaleAmountInPx?: number;
|
||||
icon?: ImageSourcePropType | ReactNode;
|
||||
style?: Style;
|
||||
grow?: boolean;
|
||||
}
|
||||
|
||||
export type Button = React.ForwardRefExoticComponent<ButtonProps>;
|
||||
|
||||
interface TwinButtonsProps {
|
||||
children: ReactNode;
|
||||
}
|
||||
|
||||
export type TwinButtons = React.ComponentType<TwinButtonsProps>;
|
||||
|
||||
// Segmented Control
|
||||
interface SegmentedControlItem {
|
||||
id: string;
|
||||
|
|
@ -103,7 +109,7 @@ interface TextInputProps extends Omit<RN.TextInputProps, "onChange" | "onChangeT
|
|||
trailingIcon?: React.FC<any>;
|
||||
trailingPressableProps?: PressableProps;
|
||||
trailingText?: string;
|
||||
value?: string | RN.Falsy;
|
||||
value?: string | Falsey;
|
||||
}
|
||||
|
||||
export type TextInput = React.FC<TextInputProps>;
|
||||
|
|
@ -144,8 +150,8 @@ interface ActionSheetProps {
|
|||
export type ActionSheet = React.FC<React.PropsWithChildren<ActionSheetProps>>;
|
||||
|
||||
type TextProps = React.ComponentProps<typeof RN.Text> & {
|
||||
variant?: DiscordTextStyles;
|
||||
color?: string; // TODO: type this
|
||||
variant?: TextStyles;
|
||||
color?: ThemeColors;
|
||||
lineClamp?: number;
|
||||
maxFontSizeMultiplier?: number;
|
||||
style?: RN.TextStyle;
|
||||
|
|
@ -163,3 +169,76 @@ interface IconButtonProps {
|
|||
}
|
||||
|
||||
export type IconButton = React.FC<IconButtonProps>;
|
||||
|
||||
export type PressableScale = React.FC<PropsWithoutRef<typeof RN.Pressable>>;
|
||||
|
||||
interface TableRowBaseProps {
|
||||
arrow?: boolean;
|
||||
label: string | ReactNode;
|
||||
subLabel?: string | ReactNode;
|
||||
variant?: LiteralUnion<"danger", string>;
|
||||
icon?: JSX.Element | Falsey;
|
||||
disabled?: boolean;
|
||||
trailing?: ReactNode | React.ComponentType<any>;
|
||||
}
|
||||
|
||||
interface TableRowProps extends TableRowBaseProps {
|
||||
onPress?: () => void;
|
||||
}
|
||||
|
||||
export type TableRow = React.FC<TableRowProps> & {
|
||||
Icon: TableRowIcon;
|
||||
TrailingText: TableRowTrailingText;
|
||||
Arrow: FC<{}>;
|
||||
};
|
||||
|
||||
interface TableRowTrailingTextProps {
|
||||
text: string;
|
||||
}
|
||||
|
||||
export type TableRowTrailingText = FC<TableRowTrailingTextProps>;
|
||||
|
||||
interface TableRowIconProps {
|
||||
style?: RN.ImageStyle;
|
||||
variant?: LiteralUnion<"danger", string>,
|
||||
source: ImageSourcePropType | undefined;
|
||||
}
|
||||
|
||||
export type TableRowIcon = React.FC<TableRowIconProps>;
|
||||
|
||||
interface TableRowGroupProps {
|
||||
title: string;
|
||||
children: ReactNode;
|
||||
}
|
||||
|
||||
export type TableRowGroup = React.FC<TableRowGroupProps>;
|
||||
|
||||
interface TableRadioGroupProps {
|
||||
title: string;
|
||||
value: string;
|
||||
hasIcons?: boolean;
|
||||
onChange: <T extends string>(type: T) => void;
|
||||
children: ReactNode;
|
||||
}
|
||||
|
||||
export type TableRadioGroup = FC<TableRadioGroupProps>;
|
||||
|
||||
interface TableRadioRowProps extends TableRowBaseProps {
|
||||
value: string;
|
||||
}
|
||||
|
||||
export type TableRadioRow = FC<TableRadioRowProps>;
|
||||
|
||||
interface TableSwitchRowProps extends TableRowBaseProps {
|
||||
value: boolean;
|
||||
onValueChange: (value: boolean) => void;
|
||||
}
|
||||
|
||||
export type TableSwitchRow = FC<TableSwitchRowProps>;
|
||||
|
||||
interface TableCheckboxRowProps extends TableRowBaseProps {
|
||||
checked: boolean;
|
||||
onPress: () => void;
|
||||
}
|
||||
|
||||
export type TableCheckboxRow = FC<TableCheckboxRowProps>;
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue