thelounge/server/plugins/packages/themes.ts

92 lines
1.9 KiB
TypeScript
Raw Normal View History

import fs from "fs";
import path from "path";
import _ from "lodash";
2018-01-05 18:40:34 +01:00
import Config from "../../config";
import Utils from "../../command-line/utils";
2018-01-05 18:40:34 +01:00
type Module = {
type?: string;
name?: string;
};
type ThemeModule = Module & {
type: "theme";
themeColor: string;
css: string;
};
export type ThemeForClient = {
displayName: string;
filename?: string;
name: string;
themeColor: string | null;
};
const themes = new Map<string, ThemeForClient>();
export default {
2018-01-05 18:40:34 +01:00
addTheme,
getAll,
2019-07-22 18:50:04 +02:00
getByName,
2018-01-05 18:40:34 +01:00
loadLocalThemes,
};
function loadLocalThemes() {
const builtInThemes = fs.readdirSync(Utils.getFileFromRelativeToRoot("public", "themes"));
2019-07-22 18:50:04 +02:00
builtInThemes
.filter((theme) => theme.endsWith(".css"))
.map(makeLocalThemeObject)
.forEach((theme) => themes.set(theme.name, theme));
2018-01-05 18:40:34 +01:00
}
function addTheme(packageName: string, packageObject: ThemeModule) {
2018-01-05 18:40:34 +01:00
const theme = makePackageThemeObject(packageName, packageObject);
2018-01-05 18:40:34 +01:00
if (theme) {
themes.set(theme.name, theme);
}
}
function getAll() {
const filteredThemes: ThemeForClient[] = [];
2018-01-05 18:40:34 +01:00
2019-07-22 18:50:04 +02:00
for (const theme of themes.values()) {
filteredThemes.push(_.pick(theme, ["displayName", "name", "themeColor"]));
2018-01-05 18:40:34 +01:00
}
2019-07-22 18:50:04 +02:00
return _.sortBy(filteredThemes, "displayName");
}
function getByName(name: string) {
2019-07-22 18:50:04 +02:00
return themes.get(name);
2018-01-05 18:40:34 +01:00
}
function makeLocalThemeObject(css: string) {
2018-01-05 18:40:34 +01:00
const themeName = css.slice(0, -4);
return {
displayName: themeName.charAt(0).toUpperCase() + themeName.slice(1),
name: themeName,
2019-07-22 18:50:04 +02:00
themeColor: null,
2018-01-05 18:40:34 +01:00
};
}
function makePackageThemeObject(
moduleName: string,
module: ThemeModule
): ThemeForClient | undefined {
2018-01-05 18:40:34 +01:00
if (!module || module.type !== "theme") {
return;
}
2019-07-22 18:50:04 +02:00
const themeColor = /^#[0-9A-F]{6}$/i.test(module.themeColor) ? module.themeColor : null;
const modulePath = Config.getPackageModulePath(moduleName);
2018-01-05 18:40:34 +01:00
return {
displayName: module.name || moduleName,
filename: path.join(modulePath, module.css),
2018-01-05 18:40:34 +01:00
name: moduleName,
2019-07-22 18:50:04 +02:00
themeColor: themeColor,
2018-01-05 18:40:34 +01:00
};
}