keycloak_theme/src/lib/usePrepareTemplate.ts

96 lines
2.3 KiB
TypeScript
Raw Normal View History

2023-03-17 20:40:29 +01:00
import { useReducer, useEffect } from "react";
2023-03-19 23:12:45 +01:00
import { headInsert } from "keycloakify/tools/headInsert";
import { clsx } from "keycloakify/tools/clsx";
2023-03-17 20:40:29 +01:00
export function usePrepareTemplate(params: {
doFetchDefaultThemeResources: boolean;
styles?: string[];
scripts?: string[];
htmlClassName: string | undefined;
bodyClassName: string | undefined;
2023-03-17 20:40:29 +01:00
}) {
2023-08-20 03:00:45 +02:00
const { doFetchDefaultThemeResources, styles = [], scripts = [], htmlClassName, bodyClassName } = params;
2023-03-17 20:40:29 +01:00
const [isReady, setReady] = useReducer(() => true, !doFetchDefaultThemeResources);
useEffect(() => {
if (!doFetchDefaultThemeResources) {
return;
}
let isUnmounted = false;
const removeArray: (() => void)[] = [];
(async () => {
const prLoadedArray: Promise<void>[] = [];
2023-08-20 03:00:45 +02:00
styles.reverse().forEach(href => {
const { prLoaded, remove } = headInsert({
"type": "css",
"position": "prepend",
href
});
2023-08-20 03:00:45 +02:00
removeArray.push(remove);
prLoadedArray.push(prLoaded);
});
await Promise.all(prLoadedArray);
2023-03-17 20:40:29 +01:00
if (isUnmounted) {
return;
}
setReady();
})();
2023-03-17 20:40:29 +01:00
2023-08-20 03:00:45 +02:00
scripts.forEach(src => {
const { remove } = headInsert({
2023-03-17 20:40:29 +01:00
"type": "javascript",
2023-08-20 03:00:45 +02:00
src
});
removeArray.push(remove);
});
2023-03-17 20:40:29 +01:00
return () => {
isUnmounted = true;
removeArray.forEach(remove => remove());
2023-03-17 20:40:29 +01:00
};
}, []);
useSetClassName({
"target": "html",
"className": htmlClassName
});
useSetClassName({
"target": "body",
"className": bodyClassName
});
return { isReady };
}
function useSetClassName(params: { target: "html" | "body"; className: string | undefined }) {
const { target, className } = params;
2023-03-17 20:40:29 +01:00
useEffect(() => {
if (className === undefined) {
return;
}
2023-03-21 03:01:49 +01:00
const htmlClassList = document.getElementsByTagName(target)[0].classList;
2023-03-17 20:40:29 +01:00
2023-03-21 03:01:49 +01:00
const tokens = clsx(className).split(" ");
2023-03-17 20:40:29 +01:00
htmlClassList.add(...tokens);
return () => {
htmlClassList.remove(...tokens);
};
}, [className]);
2023-03-17 20:40:29 +01:00
}