prasi-lib/preset/menu/Layout.tsx

107 lines
2.6 KiB
TypeScript
Executable File

import { getPathname } from "lib/utils/pathname";
import { FC, ReactNode, useEffect, useLayoutEffect, useState } from "react";
import { loadSession } from "../login/utils/load";
import { useLocal } from "lib/utils/use-local";
import { FieldLoading } from "lib/exports";
const w = window as any;
const initResponsive = function () {
const mode = localStorage.getItem("prasi-editor-mode");
if (isEditor) {
setTimeout(() => {
if (mode === "mobile") {
w.isMobile = true;
w.isDesktop = false;
} else {
w.isMobile = false;
w.isDesktop = true;
}
}, 50);
} else {
if (mode === "desktop") {
if (window.matchMedia("screen and (max-width: 768px)").matches) {
w.isMobile = true;
w.isDesktop = false;
} else {
w.isMobile = false;
w.isDesktop = true;
}
}
}
};
type LYTChild = {
mobile?: ReactNode;
desktop?: ReactNode;
tablet?: ReactNode;
child?: ReactNode;
default_layout: ReactNode;
exception?: Array<string>;
blank_layout: ReactNode;
login_url: string;
PassProp: any;
};
export const Layout: FC<LYTChild> = (props) => {
const local = useLocal({ loading: false });
const render = local.render;
useLayoutEffect(() => {
if (!isEditor) {
window.addEventListener("resize", render);
return () => {
window.removeEventListener("resize", render);
};
} else {
const el = document.querySelector(".main-editor-content");
if (el) {
const rx = new ResizeObserver(render);
rx.observe(el);
return () => {
rx.disconnect();
};
}
}
}, []);
initResponsive();
const path = getPathname();
const no_layout = props.exception;
if (!w.user) {
local.loading = true;
loadSession(props.login_url || "/auth/login");
}
if (!isEditor && Array.isArray(no_layout)) {
if (no_layout.length) {
if (no_layout.includes(path)) {
return <>{props.blank_layout}</>;
}
}
}
if (path === props.login_url) return props.blank_layout;
if (!w.user && !isEditor)
return (
<div className={cx("c-w-full c-h-full c-flex c-items-center c-justify-center c-flex-1")}>
<FieldLoading />
</div>
);
return (
<props.PassProp
is_loading={local.loading}
page_load={(on_load: (done: () => void) => void) => {
local.loading = true;
local.render();
on_load(() => {
local.loading = false;
local.render();
});
}}
>
{props.default_layout}
</props.PassProp>
);
};