/** * @license * Copyright Stbui All Rights Reserved. * https://github.com/stbui */ import React, { useEffect, useMemo, FunctionComponent, ComponentType, } from 'react'; import { useDispatch, useSelector } from 'react-redux'; import { useRouteMatch, Switch, Route } from 'react-router-dom'; import { WithPermissions } from '../auth'; import { registerResource, unregisterResource } from '../actions'; export interface ResourceProps { name: string; label?: string; match?: any; list?: ComponentType; create?: ComponentType; edit?: ComponentType; show?: ComponentType; options?: any; icon?: any; intent?: 'route' | 'registration'; } const ResourceRegister: FunctionComponent = ({ label, name, list, create, edit, show, icon, options = {}, }) => { const dispatch = useDispatch(); useEffect(() => { const resource = { name, label, options, icon, hasList: !!list, hasEdit: !!edit, hasCreate: !!create, hasShow: !!show, }; dispatch(registerResource(resource)); return () => { dispatch(unregisterResource(name)); }; }, [dispatch, label, name, list, create, edit, show]); return null; }; const ResourceRoutes: FunctionComponent = ({ label, name, list, create, edit, show, options = {}, }) => { const match = useRouteMatch(); const isRegistered = useSelector((state: any) => !!state.resources[name]); const basePath = match ? match.url : ''; return useMemo(() => { if (!isRegistered) { return null; } const resource = { resource: name, options, label, hasList: !!list, hasEdit: !!edit, hasCreate: !!create, hasShow: !!show, }; return ( {create && ( ( )} /> )} {show && ( ( )} /> )} {edit && ( ( )} /> )} {list && ( ( )} /> )} ); }, [ basePath, label, name, create, edit, list, show, options, isRegistered, ]); }; const Resource: FunctionComponent = ({ intent = 'route', ...props }) => { return intent === 'registration' ? ( ) : ( ); }; export default Resource;