Skip to content

Commit

Permalink
feat: add hidden option, contribute guide md file path option
Browse files Browse the repository at this point in the history
  • Loading branch information
thebestluck committed Feb 27, 2024
1 parent 63b377b commit b983424
Show file tree
Hide file tree
Showing 10 changed files with 99 additions and 63 deletions.
1 change: 1 addition & 0 deletions app.config.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
"type": "filesystem",
"path": "backgrounds"
},
"contributeGuide": "./CONTRIBUTING.md",
"fonts": {
"sizes": {
"large": "6rem",
Expand Down
2 changes: 1 addition & 1 deletion src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ import locales from "@/locales/common.json";
import styles from "./App.module.scss";

function App() {
const { keyColor, title } = config as Config;
const { keyColor, title } = config as unknown as Config;
const imageAreaRef = useRef<HTMLDivElement>(null);
const { saveImage, loading } = useSnapshot(imageAreaRef);
const { logo, text } = title;
Expand Down
8 changes: 5 additions & 3 deletions src/components/GuideDialog/GuideDialog.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,10 @@
* under the License.
*/
import { useEffect, useState } from "react";
import readmeFile from "~/CONTRIBUTING.md";
import config from "~/app.config.json";
import Markdown from "react-markdown";

import { Config } from "@/constants/config";
import styles from "./GuideDialog.module.scss";

interface Props {
Expand All @@ -26,13 +27,14 @@ interface Props {

const GuideDialog = (props: Props) => {
const { isVisible, onClose } = props;
const { contributeGuide } = config as unknown as Config;
const [markdown, setMarkdown] = useState("");

useEffect(() => {
fetch(readmeFile)
fetch(contributeGuide)
.then((response) => response.text())
.then(setMarkdown);
}, []);
}, [contributeGuide]);

if (!isVisible) {
return <></>;
Expand Down
1 change: 1 addition & 0 deletions src/constants/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ export interface Config {
type: string;
path: string;
};
contributeGuide: string;
fonts: {
sizes: Record<string, string>;
styles: Array<string>;
Expand Down
2 changes: 1 addition & 1 deletion src/constants/font.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import config from "~/output.config.json";

import { Config } from "@/constants/config";

const { fonts } = config as Config;
const { fonts } = config as unknown as Config;

export const FontSizes: Record<string, string> = {} as const;
Object.keys(fonts.sizes).forEach(
Expand Down
1 change: 1 addition & 0 deletions src/constants/theme.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,5 @@ export interface Theme {
backgrounds: Array<Image>;
inputFields?: Array<InputFieldGroup>;
isNew?: boolean;
isHidden?: boolean;
}
67 changes: 39 additions & 28 deletions src/hooks/useAppConfiguration/AppContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,11 @@ export const AppContext = createContext<ContextProps>({

export const AppProvider = (props: PropsWithChildren) => {
const { children } = props;
const { backgroundsUri, defaultInputFields } = config as Config;
const {
backgroundsUri,
defaultInputFields,
themes: configThemes,
} = config as unknown as Config;
const [themes, setThemes] = useState<Array<Theme>>([]);
const [selectedImage, setSelectedImage] = useState<Image>({
src: "",
Expand All @@ -79,32 +83,39 @@ export const AppProvider = (props: PropsWithChildren) => {
const [customImages, setCustomImages] = useState<Array<Image>>([]);
const [isSyncing, setIsSyncing] = useState(false);

const resetThemes = async (path: string, type: string) => {
const lowerCasedType = type.trim().toLowerCase();
switch (lowerCasedType) {
case "filesystem":
case "cdn":
setThemes(config.themes as Array<Theme>);
setSelectedImage((config.themes[0] as Theme)?.backgrounds[0] ?? []);
break;
case "github":
try {
const themes = await readConfigurationFromGithub(githubAxios, path);
if (themes) {
setThemes(themes);
setSelectedImage(themes[0].backgrounds[0]);
}
} catch (error) {
console.error(
`Error reading configuration from github:`,
(error as AxiosError).message,
const resetThemes = useCallback(
async (path: string, type: string) => {
const lowerCasedType = type.trim().toLowerCase();
switch (lowerCasedType) {
case "filesystem":
case "cdn":
setThemes(
configThemes.filter(
({ isHidden = false }) => !isHidden,
) as Array<Theme>,
);
}
break;
default:
console.warn("Unknown type:", type);
}
};
setSelectedImage((configThemes[0] as Theme)?.backgrounds[0] ?? []);
break;
case "github":
try {
const themes = await readConfigurationFromGithub(githubAxios, path);
if (themes) {
setThemes(themes.filter(({ isHidden = false }) => !isHidden));
setSelectedImage(themes[0].backgrounds[0]);
}
} catch (error) {
console.error(
`Error reading configuration from github:`,
(error as AxiosError).message,
);
}
break;
default:
console.warn("Unknown type:", type);
}
},
[configThemes],
);

const handleDropCustomImages = (event: DragEvent) => {
const file = ((event.dataTransfer as DataTransfer).files as FileList)[0];
Expand Down Expand Up @@ -147,11 +158,11 @@ export const AppProvider = (props: PropsWithChildren) => {
}, 2000);

return () => clearTimeout(timer);
}, [backgroundsUri]);
}, [backgroundsUri, resetThemes]);

useEffect(() => {
backgroundsUri && resetThemes(backgroundsUri.path, backgroundsUri.type);
}, [backgroundsUri]);
}, [backgroundsUri, resetThemes]);

useEffect(() => {
if (selectedTheme === "custom") {
Expand Down
3 changes: 1 addition & 2 deletions tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,5 @@

"types": ["vite-plugin-svgr/client", "node"]
},
"include": ["src"],
"references": [{ "path": "./tsconfig.node.json" }]
"include": ["src", "vite.config.ts", "app.config.json"]
}
10 changes: 0 additions & 10 deletions tsconfig.node.json

This file was deleted.

67 changes: 49 additions & 18 deletions vite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ import stylelint from "vite-plugin-stylelint";
import svgr from "vite-plugin-svgr";
import tsconfigPaths from "vite-tsconfig-paths";

import type { Config } from "@/constants/config.ts";
import type { Image } from "@/constants/image.ts";
import config from "./app.config.json";

// https://vitejs.dev/config/
Expand All @@ -19,6 +21,7 @@ export default defineConfig({
stylelint({
fix: true,
}),
copyContributeGuide(),
copyBackgroundsForFileSystem(),
],
css: {
Expand All @@ -31,36 +34,64 @@ export default defineConfig({
assetsInclude: ["**/*.md"],
});

function copyContributeGuide() {
const { contributeGuide } = config as unknown as Config;
const targetDirectory = "dist";

return copy({
targets: [
{
src: contributeGuide,
dest: targetDirectory,
},
],
hook: "writeBundle",
});
}

/**
* If config has `filesystem` type for `backgroundsUri`, copy local backgrounds path to dist folder
*/
function copyBackgroundsForFileSystem() {
const { backgroundsUri, themes } = config as unknown as Config;

if (
config.backgroundsUri &&
config.backgroundsUri.type === "filesystem" &&
config.backgroundsUri.path
backgroundsUri &&
backgroundsUri.type === "filesystem" &&
backgroundsUri.path
) {
const dir = path.resolve();
const sourceDirectory = config.backgroundsUri.path;
const sourceDirectory = backgroundsUri.path;
const targetDirectory = "dist";
const order = config.themes.map(({ name }) => name);
const order = themes.map(({ name }) => name);
const filteredOrder = themes
.filter(({ isHidden }) => !isHidden)
.map(({ name }) => name);

const fileContentsArray = readFilesRecursively(sourceDirectory);

order.map((theme, index) => {
const isThemeHidden =
themes.filter(({ name }) => name === theme)[0]?.isHidden ?? false;
const filteredFileContentsArray = fileContentsArray.filter(
({ theme: fileTheme }) => fileTheme === theme,
);
config.themes[index]["backgrounds"] = filteredFileContentsArray.map(
({ src, fontColor }) => (fontColor ? { src, fontColor } : { src }),
);

themes[index]["backgrounds"] = isThemeHidden
? []
: filteredFileContentsArray.map(({ src, fontColor }) =>
fontColor ? { src, fontColor } : { src },
);
});

const configJsonPath = path.join(dir, "output.config.json");
fs.writeFileSync(configJsonPath, JSON.stringify(config, null, 2));

return copy({
targets: [{ src: sourceDirectory, dest: targetDirectory }],
targets: filteredOrder.map((theme) => ({
src: path.join(sourceDirectory, theme),
dest: path.join(targetDirectory, backgroundsUri.path),
})),
hook: "writeBundle",
});
} else {
Expand All @@ -70,22 +101,22 @@ function copyBackgroundsForFileSystem() {
}
}

function readFilesRecursively(dir) {
const fileContentsArray = [];
function readFilesRecursively(dir: string) {
const { backgroundsUri, themes } = config as unknown as Config;
const fileContentsArray: Image[] = [];

const readFiles = (dir) => {
const readFiles = (dir: string) => {
const files = fs.readdirSync(dir);
const order = config.themes.map(({ name }) => name);
const order = themes
.filter(({ isHidden = false }) => !isHidden)
.map(({ name }) => name);
const sortedFiles = files.sort(
(a, b) => order.indexOf(a) - order.indexOf(b),
);

sortedFiles.forEach((file) => {
const filePath = path.join(dir, file);
const theme = dir.replace(
path.join(config.backgroundsUri.path, path.sep),
"",
);
const theme = dir.replace(path.join(backgroundsUri.path, path.sep), "");

if (fs.statSync(filePath).isDirectory()) {
readFiles(filePath);
Expand All @@ -110,7 +141,7 @@ function readFilesRecursively(dir) {
return fileContentsArray;
}

function isImageFile(filePath) {
function isImageFile(filePath: string) {
const allowedExtensions = [".jpg", ".jpeg", ".png", ".gif", ".bmp", ".webp"];
const extension = path.extname(filePath).toLowerCase();
return allowedExtensions.includes(extension);
Expand Down

0 comments on commit b983424

Please sign in to comment.