react-antd-admin-panel
Version:
Modern TypeScript-first React admin panel builder with Ant Design 6
339 lines (338 loc) • 9.18 kB
JavaScript
"use strict";
var __defProp = Object.defineProperty;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
const React = require("react");
const Post = require("./Post-CeaBs_p4.cjs");
class GlobalStore {
constructor() {
__publicField(this, "_data", /* @__PURE__ */ new Map());
__publicField(this, "_subscribers", /* @__PURE__ */ new Map());
}
/**
* Get a value from the store
*/
get(key) {
return this._data.get(key);
}
/**
* Set a value in the store
* Notifies all subscribers of the change
*/
set(key, value) {
const prevValue = this._data.get(key);
const newValue = typeof value === "function" ? value(prevValue) : value;
this._data.set(key, newValue);
this._notifySubscribers(key, newValue);
}
/**
* Remove a value from the store
*/
remove(key) {
this._data.delete(key);
this._notifySubscribers(key, void 0);
}
/**
* Clear all values from the store
*/
clear() {
const keys = Array.from(this._data.keys());
this._data.clear();
keys.forEach((key) => this._notifySubscribers(key, void 0));
}
/**
* Check if a key exists in the store
*/
has(key) {
return this._data.has(key);
}
/**
* Get all keys in the store
*/
keys() {
return Array.from(this._data.keys());
}
/**
* Subscribe to changes for a specific key
* Returns an unsubscribe function
*/
subscribe(key, callback) {
if (!this._subscribers.has(key)) {
this._subscribers.set(key, /* @__PURE__ */ new Set());
}
this._subscribers.get(key).add(callback);
return () => {
const subscribers = this._subscribers.get(key);
if (subscribers) {
subscribers.delete(callback);
if (subscribers.size === 0) {
this._subscribers.delete(key);
}
}
};
}
/**
* Notify all subscribers of a value change
*/
_notifySubscribers(key, value) {
const subscribers = this._subscribers.get(key);
if (subscribers) {
subscribers.forEach((callback) => callback(value));
}
}
/**
* Get the store as a plain object
*/
toObject() {
return Object.fromEntries(this._data);
}
}
class UserState {
constructor() {
__publicField(this, "_user", null);
__publicField(this, "_subscribers", /* @__PURE__ */ new Set());
}
/**
* Get the current user
*/
get() {
return this._user;
}
/**
* Set the current user
*/
set(user) {
this._user = user;
this._notifySubscribers();
}
/**
* Update user properties
*/
update(updates) {
if (this._user) {
this._user = { ...this._user, ...updates };
this._notifySubscribers();
}
}
/**
* Clear the current user (logout)
*/
clear() {
this._user = null;
this._notifySubscribers();
}
/**
* Check if a user is authenticated
*/
isAuthenticated() {
return this._user !== null;
}
/**
* Check if user has a specific role
*/
hasRole(role) {
var _a;
return ((_a = this._user) == null ? void 0 : _a.role) === role;
}
/**
* Check if user has any of the specified roles
*/
hasAnyRole(roles) {
var _a;
return roles.includes(((_a = this._user) == null ? void 0 : _a.role) ?? "");
}
/**
* Check if user has a specific permission
*/
hasPermission(permission) {
var _a, _b;
return ((_b = (_a = this._user) == null ? void 0 : _a.permissions) == null ? void 0 : _b.includes(permission)) ?? false;
}
/**
* Check if user has all specified permissions
*/
hasAllPermissions(permissions) {
var _a;
if (!((_a = this._user) == null ? void 0 : _a.permissions)) return false;
return permissions.every((p) => this._user.permissions.includes(p));
}
/**
* Check if user has any of the specified permissions
*/
hasAnyPermission(permissions) {
var _a;
if (!((_a = this._user) == null ? void 0 : _a.permissions)) return false;
return permissions.some((p) => this._user.permissions.includes(p));
}
/**
* Get a user property
*/
getProperty(key) {
var _a;
return (_a = this._user) == null ? void 0 : _a[key];
}
/**
* Subscribe to user changes
* Returns an unsubscribe function
*/
subscribe(callback) {
this._subscribers.add(callback);
return () => {
this._subscribers.delete(callback);
};
}
/**
* Notify all subscribers
*/
_notifySubscribers() {
this._subscribers.forEach((callback) => callback(this._user));
}
}
const MainContext = React.createContext(null);
function useMain() {
const context = React.useContext(MainContext);
if (!context) {
throw new Error("useMain must be used within a MainProvider");
}
return context;
}
function useUser() {
const main = useMain();
const [user, setUser] = React.useState(main.User().get());
React.useEffect(() => {
return main.User().subscribe(setUser);
}, [main]);
return user;
}
function useStore(key) {
const main = useMain();
const [value, setValue] = React.useState(main.Store().get(key));
React.useEffect(() => {
return main.Store().subscribe(key, setValue);
}, [main, key]);
return value;
}
function useStoreActions() {
const main = useMain();
return {
set: (key, value) => main.Store().set(key, value),
remove: (key) => main.Store().remove(key),
clear: () => main.Store().clear()
};
}
function MainProvider({ config, navigate, children }) {
const storeRef = React.useRef(new GlobalStore());
const userStateRef = React.useRef(new UserState());
const [booted, setBooted] = React.useState(false);
const [bootError, setBootError] = React.useState(null);
const mainInstance = React.useMemo(() => ({
User: () => userStateRef.current,
Store: () => storeRef.current,
config: config.config,
navigate,
canAccess: (route) => {
const user = userStateRef.current;
if (route.requiredRole && !user.hasRole(route.requiredRole)) {
return false;
}
if (route.requiredPermissions && !user.hasAllPermissions(route.requiredPermissions)) {
return false;
}
return true;
}
}), [config.config, navigate]);
React.useEffect(() => {
const httpConfig = config.config.http;
if (httpConfig) {
Post.Get.configure({
baseURL: httpConfig.baseURL || config.config.pathToApi,
timeout: httpConfig.timeout,
headers: httpConfig.headers
});
Post.Post.configure({
baseURL: httpConfig.baseURL || config.config.pathToApi,
timeout: httpConfig.timeout,
headers: httpConfig.headers
});
if (httpConfig.onRequest || httpConfig.onResponse || httpConfig.onError || httpConfig.onUnauthorized) {
const axios = Post.Get.getAxios();
if (httpConfig.onRequest) {
axios.interceptors.request.use(httpConfig.onRequest);
}
if (httpConfig.onResponse || httpConfig.onError || httpConfig.onUnauthorized) {
axios.interceptors.response.use(
httpConfig.onResponse,
(error) => {
var _a;
if (((_a = error.response) == null ? void 0 : _a.status) === 401 && httpConfig.onUnauthorized) {
httpConfig.onUnauthorized();
}
if (httpConfig.onError) {
return httpConfig.onError(error);
}
return Promise.reject(error);
}
);
}
}
}
}, [config.config.http, config.config.pathToApi]);
React.useEffect(() => {
const runBoot = async () => {
try {
if (config.config.boot) {
await config.config.boot(mainInstance);
}
setBooted(true);
} catch (error) {
setBootError(error);
}
};
runBoot();
}, [config.config.boot, mainInstance]);
if (bootError) {
return React.createElement(
"div",
{
style: {
display: "flex",
justifyContent: "center",
alignItems: "center",
height: "100vh",
flexDirection: "column",
gap: 16
}
},
React.createElement("h2", {}, "Application Error"),
React.createElement("p", { style: { color: "red" } }, bootError.message)
);
}
if (!booted && config.config.boot) {
return React.createElement(
"div",
{
style: {
display: "flex",
justifyContent: "center",
alignItems: "center",
height: "100vh"
}
},
React.createElement("span", {}, "Loading...")
);
}
return React.createElement(
MainContext.Provider,
{ value: mainInstance },
children
);
}
exports.GlobalStore = GlobalStore;
exports.MainContext = MainContext;
exports.MainProvider = MainProvider;
exports.UserState = UserState;
exports.useMain = useMain;
exports.useStore = useStore;
exports.useStoreActions = useStoreActions;
exports.useUser = useUser;
//# sourceMappingURL=MainContext-DBk-_ISe.cjs.map