Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(settings): OptionType.ARRAY | OptionType.REGEX #696

Closed
wants to merge 5 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
171 changes: 163 additions & 8 deletions src/api/settings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ import { localStorage } from "@utils/localStorage";
import Logger from "@utils/Logger";
import { mergeDefaults } from "@utils/misc";
import { putCloudSettings } from "@utils/settingsSync";
import { DefinedSettings, OptionType, SettingsChecks, SettingsDefinition } from "@utils/types";
import { DefinedSettings, OptionType, PluginSettingPureDef, PluginSettingType, SettingsChecks, SettingsDefinition } from "@utils/types";
import { React } from "@webpack/common";

import plugins from "~plugins";
Expand Down Expand Up @@ -93,12 +93,24 @@ const DefaultSettings: Settings = {
}
};

try {
var settings = JSON.parse(VencordNative.ipc.sendSync(IpcEvents.GET_SETTINGS)) as Settings;
mergeDefaults(settings, DefaultSettings);
} catch (err) {
var settings = mergeDefaults({} as Settings, DefaultSettings);
logger.error("An error occurred while loading the settings. Corrupt settings file?\n", err);
const settings = {} as Settings;
let settingsInitialized = false;

export function initializeVencordSettings() {
if (settingsInitialized) throw new Error("Settings already initialized");
try {
Object.assign(settings, parseSettings(VencordNative.ipc.sendSync(IpcEvents.GET_SETTINGS)));
mergeDefaults(settings, DefaultSettings);
} catch (err) {
mergeDefaults(settings, DefaultSettings);
logger.error("An error occurred while loading the settings. Corrupt settings file?\n", err);
}

settingsInitialized = true;
for (const [pluginName, ...oldNames] of queuedMigrations) {
migratePluginSettings(pluginName, ...oldNames);
}
queuedMigrations.length = 0;
}

const saveSettingsOnFrequentAction = debounce(async () => {
Expand Down Expand Up @@ -170,15 +182,152 @@ function makeProxy(settings: any, root = settings, path = ""): Settings {
}
}
// And don't forget to persist the settings!

PlainSettings.cloud.settingsSyncVersion = Date.now();
localStorage.Vencord_settingsDirty = true;
saveSettingsOnFrequentAction();
VencordNative.ipc.invoke(IpcEvents.SET_SETTINGS, JSON.stringify(root, null, 4));
VencordNative.ipc.invoke(IpcEvents.SET_SETTINGS, stringifySettings(root));
return true;
}
});
}

const IMPURE_TYPES = new Set([
OptionType.REGEX,
OptionType.TABLE,
OptionType.ARRAY,
] as const);
type ImpureDef = Extract<PluginSettingPureDef, { type: typeof IMPURE_TYPES extends Set<infer T> ? T : never; }>;
type ImpureSerialized<D extends ImpureDef> = {
[OptionType.REGEX]: [string, string];
[OptionType.ARRAY]: any[];
[OptionType.TABLE]: Record<string, any>[];
}[D["type"]];
function isImpure(def: PluginSettingPureDef): def is ImpureDef {
return IMPURE_TYPES.has(def.type as ImpureDef["type"]);
}

/**
* Iterates over every plugin setting with an impure type with some context.
* Impure settings are settings that are not plainly JSON-serializable.
*/
function forEachImpure(settings: Settings, cb: (ctx: {
pluginName: string;
settingName: string;
def: ImpureDef;
value: any; // TODO: type this better
}) => void) {
for (const [pluginName, pluginSettings] of Object.entries(settings.plugins)) {
const plugin = plugins[pluginName];
if (!plugin) continue;

const settingDefs = plugin.settings;
if (!settingDefs) continue;

for (const [settingName, value] of Object.entries(pluginSettings)) {
const settingDef = settingDefs.def[settingName];
if (!settingDef || !isImpure(settingDef)) continue;

cb({ pluginName, settingName, def: settingDef, value });
}
}
}

function parseSettings(json: string) {
const settings = JSON.parse(json) as Settings;
forEachImpure(settings, ({
pluginName,
settingName,
def,
value,
}) => {
settings.plugins[pluginName][settingName] = deserialize(def, value);
});
return settings;
}
function stringifySettings(settings: Settings) {
const marked = new Map();

forEachImpure(settings, ({
def,
value,
}) => {
if (!marked.has(value))
marked.set(value, serialize(def, value));
});

return JSON.stringify(settings, (key, value) => {
if (marked.has(value)) return marked.get(value)!;
return value;
}, 4);
}

type Deserializer<D extends ImpureDef> = (def: D, serialized: ImpureSerialized<D>) => PluginSettingType<D>;
const deserializers: { [D in ImpureDef as D["type"]]: Deserializer<D> } = {
[OptionType.REGEX]: (def, serialized) => {
try {
return new RegExp(serialized[0], serialized[1]);
} catch {
return new RegExp("");
}
},
[OptionType.ARRAY]: (def, serialized) => {
if (!Array.isArray(serialized)) return [];
const itemDef = def.items;
if (isImpure(itemDef)) return serialized.map(v => deserialize(itemDef, v));
else return serialized;
},
[OptionType.TABLE]: (def, serialized) => {
const rows: Record<string, any>[] = [];
if (!Array.isArray(serialized)) return rows;
for (const serializedRow of serialized) {
const row: Record<string, any> = {};
for (const [key, value] of Object.entries(serializedRow)) {
const colDef = def.columns[key];
if (!colDef) continue;
if (isImpure(colDef)) row[key] = deserialize(colDef, value);
else row[key] = value;
}
rows.push(row);
}
return rows;
},
};
function deserialize<D extends ImpureDef>(def: D, serialized: ImpureSerialized<D>): PluginSettingType<D> {
// Typescript really hates function unions
return deserializers[def.type](def as any, serialized as any) as any;
}

type Serializer<D extends ImpureDef> = (def: D, impureVal: PluginSettingType<D>) => ImpureSerialized<D>;
const serializers: { [D in ImpureDef as D["type"]]: Serializer<D> } = {
[OptionType.REGEX]: (def, impureVal) => [impureVal.source, impureVal.flags],
[OptionType.ARRAY]: (def, impureVal) => {
if (!Array.isArray(impureVal)) return [];
const itemDef = def.items;
if (isImpure(itemDef)) return impureVal.map(v => serialize(itemDef, v));
else return impureVal;
},
[OptionType.TABLE]: (def, impureVal) => {
const rows: Record<string, any>[] = [];
if (!Array.isArray(impureVal)) return rows;
for (const impureRow of impureVal) {
const row: Record<string, any> = {};
for (const [key, value] of Object.entries(impureRow)) {
const colDef = def.columns[key];
if (!colDef) continue;
if (isImpure(colDef)) row[key] = serialize(colDef, value);
else row[key] = value;
}
rows.push(row);
}
return rows;
},
};
function serialize<D extends ImpureDef>(def: D, impureVal: PluginSettingType<D>): ImpureSerialized<D> {
// Typescript REALLY REALLY hates function unions
return serializers[def.type](def as any, impureVal as any) as any;
}

/**
* Same as {@link Settings} but unproxied. You should treat this as readonly,
* as modifying properties on this will not save to disk or call settings
Expand Down Expand Up @@ -240,7 +389,13 @@ export function addSettingsListener(path: string, onUpdate: (newValue: any, path
subscriptions.add(onUpdate);
}

const queuedMigrations: string[][] = [];
export function migratePluginSettings(name: string, ...oldNames: string[]) {
if (!settingsInitialized) {
queuedMigrations.push([name, ...oldNames]);
return;
}

const { plugins } = settings;
if (name in plugins) return;

Expand Down
7 changes: 6 additions & 1 deletion src/components/PluginSettings/PluginModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,8 @@ import {
SettingSliderComponent,
SettingTextComponent
} from "./components";
import { SettingArrayComponent } from "./components/SettingArrayComponent";
import { SettingRegexComponent } from "./components/SettingRegexComponent";

const UserSummaryItem = LazyComponent(() => findByCode("defaultRenderUser", "showDefaultAvatarsForNullUsers"));
const AvatarStyles = findByPropsLazy("moreUsers", "emptyUser", "avatarContainer", "clickableAvatar");
Expand Down Expand Up @@ -70,7 +72,10 @@ const Components: Record<OptionType, React.ComponentType<ISettingElementProps<an
[OptionType.BOOLEAN]: SettingBooleanComponent,
[OptionType.SELECT]: SettingSelectComponent,
[OptionType.SLIDER]: SettingSliderComponent,
[OptionType.COMPONENT]: SettingCustomComponent
[OptionType.COMPONENT]: SettingCustomComponent,
[OptionType.REGEX]: SettingRegexComponent,
[OptionType.ARRAY]: SettingArrayComponent,
[OptionType.TUPLE]: () => null,
};

export default function PluginModal({ plugin, onRestartNeeded, onClose, transitionState }: PluginModalProps) {
Expand Down
33 changes: 33 additions & 0 deletions src/components/PluginSettings/components/SettingArrayComponent.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
/*
* Vencord, a modification for Discord's desktop app
* Copyright (c) 2023 Vendicated and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/

import { PluginSettingArrayDef, PluginSettingAtomDef, PluginSettingCommon } from "@utils/types";

import { ISettingElementProps } from ".";

export function SettingArrayComponent({
option,
pluginSettings,
definedSettings,
id,
onChange,
onError,
}: ISettingElementProps<PluginSettingArrayDef<PluginSettingAtomDef> & PluginSettingCommon>) {
// TODO
return null;
}
33 changes: 33 additions & 0 deletions src/components/PluginSettings/components/SettingRegexComponent.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
/*
* Vencord, a modification for Discord's desktop app
* Copyright (c) 2023 Vendicated and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/

import { PluginSettingCommon, PluginSettingRegexDef } from "@utils/types";

import { ISettingElementProps } from ".";

export function SettingRegexComponent({
option,
pluginSettings,
definedSettings,
id,
onChange,
onError,
}: ISettingElementProps<PluginSettingRegexDef & PluginSettingCommon>) {
// TODO
return null;
}
4 changes: 3 additions & 1 deletion src/plugins/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
*/

import { registerCommand, unregisterCommand } from "@api/Commands";
import { Settings } from "@api/settings";
import { initializeVencordSettings, Settings } from "@api/settings";
import Logger from "@utils/Logger";
import { Patch, Plugin } from "@utils/types";
import { FluxDispatcher } from "@webpack/common";
Expand All @@ -33,6 +33,8 @@ export const PMLogger = logger;
export const plugins = Plugins;
export const patches = [] as Patch[];

initializeVencordSettings();

const settings = Settings.plugins;

export function isPluginEnabled(p: string) {
Expand Down
42 changes: 42 additions & 0 deletions src/plugins/textReplace.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
/*
* Vencord, a modification for Discord's desktop app
* Copyright (c) 2023 Vendicated and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/

import { definePluginSettings } from "@api/settings";
import { Devs } from "@utils/constants";
import definePlugin, { OptionType } from "@utils/types";

const settings = definePluginSettings({
patterns: {
type: OptionType.ARRAY,
description: "Patterns to replace",
default: [],
items: {
type: OptionType.REGEX,
},
},
});

export default definePlugin({
name: "TextReplace",
authors: [Devs.Vap],
description: "",

start() {
console.log(settings.store.patterns);
}
});
Loading