colorSchemes.ts

 1import fs from "fs"
 2import path from "path"
 3import { ColorScheme, Meta } from "./themes/common/colorScheme"
 4
 5const THEMES_DIRECTORY = path.resolve(`${__dirname}/themes`)
 6const STAFF_DIRECTORY = path.resolve(`${__dirname}/themes/staff`)
 7const IGNORE_ITEMS = ["staff", "common", "template.ts"]
 8const ACCEPT_EXTENSION = ".ts"
 9
10function getAllTsFiles(directoryPath: string) {
11    const files = fs.readdirSync(directoryPath)
12    const fileList: string[] = []
13
14    for (const file of files) {
15        if (!IGNORE_ITEMS.includes(file)) {
16            const filePath = path.join(directoryPath, file)
17
18            if (fs.statSync(filePath).isDirectory()) {
19                fileList.push(...getAllTsFiles(filePath))
20            } else if (path.extname(file) === ACCEPT_EXTENSION) {
21                fileList.push(filePath)
22            }
23        }
24    }
25
26    return fileList
27}
28
29function getAllColorSchemes(directoryPath: string) {
30    const files = getAllTsFiles(directoryPath)
31    return files.map((filePath) => ({
32        colorScheme: require(filePath),
33        filePath: path.basename(filePath),
34    }))
35}
36
37function getColorSchemes(directoryPath: string) {
38    const colorSchemes: ColorScheme[] = []
39
40    for (const { colorScheme } of getAllColorSchemes(directoryPath)) {
41        if (colorScheme.dark) colorSchemes.push(colorScheme.dark)
42        else if (colorScheme.light) colorSchemes.push(colorScheme.light)
43    }
44
45    return colorSchemes
46}
47
48function getMeta(directoryPath: string) {
49    const meta: Meta[] = []
50
51    for (const { colorScheme, filePath } of getAllColorSchemes(directoryPath)) {
52        if (colorScheme.meta) {
53            meta.push(colorScheme.meta)
54        } else {
55            throw Error(`Public theme ${filePath} must have a meta field`)
56        }
57    }
58
59    return meta
60}
61
62export const colorSchemes = getColorSchemes(THEMES_DIRECTORY)
63export const staffColorSchemes = getColorSchemes(STAFF_DIRECTORY)
64export const schemeMeta = getMeta(THEMES_DIRECTORY)