Skip to content

Commit

Permalink
DEV stash
Browse files Browse the repository at this point in the history
  • Loading branch information
cdcabrera committed Feb 8, 2023
1 parent 55cbab5 commit e7c4828
Show file tree
Hide file tree
Showing 4 changed files with 81 additions and 136 deletions.
17 changes: 3 additions & 14 deletions src/components/authentication/authenticationContext.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import React, { useContext, useState } from 'react';
import { useMount, useUnmount } from 'react-use';
import React, { useContext } from 'react';
import { useMount } from 'react-use';
import { reduxActions, storeHooks } from '../../redux';
import { helpers } from '../../common';
import { routerContext, routerHelpers } from '../router';
import { routerHelpers } from '../router';

/**
* Base context.
Expand All @@ -28,10 +28,8 @@ const useAuthContext = () => useContext(AuthenticationContext);
* @param {Function} options.authorizeUser
* @param {Function} options.hideGlobalFilter
* @param {Function} options.initializeChrome
* @param {Function} options.onNavigation
* @param {Function} options.setAppName
* @param {Function} options.useDispatch
* @param {Function} options.useNavigate
* @param {Function} options.useSelectorsResponse
* @returns {{data: {errorCodes, errorStatus: *, locale}, pending: boolean, fulfilled: boolean, error: boolean}}
*/
Expand All @@ -40,14 +38,10 @@ const useGetAuthorization = ({
authorizeUser = reduxActions.platform.authorizeUser,
hideGlobalFilter = reduxActions.platform.hideGlobalFilter,
initializeChrome = reduxActions.platform.initializeChrome,
onNavigation = reduxActions.platform.onNavigation,
setAppName = reduxActions.platform.setAppName,
useDispatch: useAliasDispatch = storeHooks.reactRedux.useDispatch,
useNavigate: useAliasNavigate = routerContext.useNavigate,
useSelectorsResponse: useAliasSelectorsResponse = storeHooks.reactRedux.useSelectorsResponse
} = {}) => {
const [unregister, setUnregister] = useState(() => helpers.noop);
const navigate = useAliasNavigate();
const dispatch = useAliasDispatch();
const { data, error, fulfilled, pending, responses } = useAliasSelectorsResponse([
{ id: 'auth', selector: ({ user }) => user?.auth },
Expand All @@ -61,11 +55,6 @@ const useGetAuthorization = ({
useMount(async () => {
await dispatch(authorizeUser());
dispatch([initializeChrome(), setAppName(appName), hideGlobalFilter()]);
setUnregister(() => dispatch(onNavigation(event => navigate(event.navId, { isLeftNav: true }))));
});

useUnmount(() => {
unregister();
});

const [user = {}, app = {}] = (Array.isArray(data.auth) && data.auth) || [];
Expand Down
18 changes: 11 additions & 7 deletions src/components/router/router.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React from 'react';
import React, { useMemo } from 'react';
import PropTypes from 'prop-types';
import { Navigate, Routes, Route } from 'react-router-dom';
import { routerHelpers } from './routerHelpers';
Expand All @@ -14,12 +14,16 @@ import { Loader } from '../loader/loader';
* @returns {React.ReactNode}
*/
const Router = ({ redirectRoute, routes } = {}) => {
const updatedRoutes = routes
.filter(item => !item.disabled)
.map(item => {
const View = routerHelpers.importView(item.component);
return <Route key={item.path} path={item.path} element={<View />} />;
});
const updatedRoutes = useMemo(
() =>
routes
.filter(item => !item.disabled)
.map(item => {
const View = routerHelpers.importView(item.component);
return <Route key={item.path} path={item.path} element={<View />} />;
}),
[routes]
);

return (
<React.Suspense fallback={<Loader variant="title" />}>
Expand Down
72 changes: 12 additions & 60 deletions src/components/router/routerContext.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,40 +3,10 @@ import {
useLocation as useLocationRRD,
useNavigate as useRRDNavigate,
useParams,
useResolvedPath,
useSearchParams as useRRDSearchParams
} from 'react-router-dom';
import { routerHelpers } from './routerHelpers';

/**
* Pass useHistory methods. Proxy useHistory push with Platform specific navigation update.
*
* @param {object} options
* @param {Function} options.useHistory
* @returns {object}
*/
/*
const useHistory = ({ useHistory: useAliasHistory = useHistoryRRD } = {}) => {
const history = useAliasHistory();
return {
...history,
push: (pathLocation, historyState) => {
const pathName = (typeof pathLocation === 'string' && pathLocation) || pathLocation?.pathname;
const { firstMatch } = routerHelpers.getRouteConfigByPath({ pathName });
const { hash, search } = window.location;
return history?.push(
(firstMatch?.productPath && `${routerHelpers.pathJoin('/', firstMatch?.productPath)}${search}${hash}`) ||
(pathName && `${pathName}${search}${hash}`) ||
pathLocation,
historyState
);
}
};
};
*/

/**
* Combine react-router-dom useLocation with actual window location.
* Focused on exposing replace and href.
Expand Down Expand Up @@ -107,22 +77,13 @@ const useRedirect = ({ useLocation: useAliasLocation = useLocation } = {}) => {
* Get a route detail from router context.
*
* @param {object} options
* @param {Function} options.useRedirect
* @param {Function} options.useParams
* @returns {{baseName: string, errorRoute: object}}
*/
const useRouteDetail = ({
useRedirect: useAliasRedirect = useRedirect,
useParams: useAliasParams = useParams
} = {}) => {
const redirect = useAliasRedirect();
const useRouteDetail = ({ useParams: useAliasParams = useParams } = {}) => {
const { productPath } = useAliasParams();
const { allConfigs, configs, firstMatch } = routerHelpers.getRouteConfigByPath({ pathName: productPath });

if (!firstMatch) {
redirect(routerHelpers.redirectRoute.redirect);
}

return {
allProductConfigs: allConfigs,
firstMatch,
Expand All @@ -132,43 +93,34 @@ const useRouteDetail = ({
};
};

// ToDo: align useNavigate with updates from the useHistory proxy
/**
* useNavigate wrapper, apply application config context routing
*
* @param {object} options
* @param {Function} options.useLocation
* @param {Function} options.useNavigate
* @param {Function} options.useResolvedPath
* @returns {Function}
*/
const useNavigate = ({
useLocation: useAliasLocation = useLocation,
useNavigate: useAliasNavigate = useRRDNavigate,
useResolvedPath: useAliasResolvedPath = useResolvedPath
useNavigate: useAliasNavigate = useRRDNavigate
} = {}) => {
const { search, hash } = useAliasLocation();
const navigate = useAliasNavigate();
const { pathname } = useAliasResolvedPath();

return useCallback(
(path, { isLeftNav = false, isPassSearchHash = true, ...options } = {}) => {
if (isLeftNav) {
return undefined;
}

const { firstMatch } = routerHelpers.getRouteConfigByPath({ pathName: path });

if (firstMatch) {
const dynamicBaseName = routerHelpers.dynamicBaseName({ pathName: pathname });
const updatedPath = `${dynamicBaseName}/${firstMatch.productPath}`;

return navigate((isPassSearchHash && `${updatedPath}${search}${hash}`) || updatedPath, options);
}
(pathLocation, options) => {
const pathName = (typeof pathLocation === 'string' && pathLocation) || pathLocation?.pathname;
const { firstMatch } = routerHelpers.getRouteConfigByPath({ pathName });

return navigate((isPassSearchHash && `${path}${search}${hash}`) || path, options);
return navigate(
(firstMatch?.productPath && `${routerHelpers.pathJoin('.', firstMatch?.productPath)}${search}${hash}`) ||
(pathName && `${pathName}${search}${hash}`) ||
pathLocation,
options
);
},
[hash, navigate, pathname, search]
[hash, navigate, search]
);
};

Expand Down
110 changes: 55 additions & 55 deletions src/components/router/routerHelpers.js
Original file line number Diff line number Diff line change
Expand Up @@ -63,60 +63,60 @@ const routes = routesConfig;
* @param {Array} params.config
* @returns {{configs: Array, configFirstMatch: object, configsById: object}}
*/
const getRouteConfigByPath = _memoize(
({ pathName = window.location.pathname, configs = productConfig.configs } = {}) => {
const updatedPathName = (/^http/i.test(pathName) && new URL(pathName).pathname) || pathName;
const basePathDirs = updatedPathName
?.split('#')?.[0]
?.split('?')?.[0]
?.split('/')
.filter(str => str.length > 0)
?.reverse();
const filteredConfigs = [];
const filteredConfigsById = {};
const filteredConfigsByGroup = {};
const allConfigs = configs;

const findConfig = dir => {
configs.forEach(configItem => {
const { productId, productGroup, aliases } = configItem;

if (
!(productId in filteredConfigsById) &&
dir &&
(new RegExp(dir, 'i').test(aliases?.toString()) ||
new RegExp(dir, 'i').test(productGroup?.toString()) ||
new RegExp(dir, 'i').test(productId?.toString()))
) {
filteredConfigsByGroup[productGroup] ??= [];
filteredConfigsByGroup[productGroup].push(configItem);

filteredConfigsById[productId] = configItem;
filteredConfigs.push(configItem);
}
});
};

if (basePathDirs?.length) {
basePathDirs.forEach(dir => {
if (dir) {
const decodedDir = window.decodeURI(dir);
findConfig(decodedDir);
}
});
} else {
findConfig();
}

return {
allConfigs,
configs: filteredConfigs,
configsById: filteredConfigsById,
configsByGroup: filteredConfigsByGroup,
firstMatch: filteredConfigs?.[0]
};
const getRouteConfigByPath = _memoize(({ pathName, configs = productConfig.configs } = {}) => {
const updatedPathName =
(/^http/i.test(pathName) && new URL(pathName).pathname) || pathName || window.location.pathname;

const basePathDirs = updatedPathName
?.split('#')?.[0]
?.split('?')?.[0]
?.split('/')
.filter(str => str.length > 0)
?.reverse();
const filteredConfigs = [];
const filteredConfigsById = {};
const filteredConfigsByGroup = {};
const allConfigs = configs;

const findConfig = dir => {
configs.forEach(configItem => {
const { productId, productGroup, aliases } = configItem;

if (
!(productId in filteredConfigsById) &&
dir &&
(new RegExp(dir, 'i').test(aliases?.toString()) ||
new RegExp(dir, 'i').test(productGroup?.toString()) ||
new RegExp(dir, 'i').test(productId?.toString()))
) {
filteredConfigsByGroup[productGroup] ??= [];
filteredConfigsByGroup[productGroup].push(configItem);

filteredConfigsById[productId] = configItem;
filteredConfigs.push(configItem);
}
});
};

if (basePathDirs?.length) {
basePathDirs.forEach(dir => {
if (dir) {
const decodedDir = window.decodeURI(dir);
findConfig(decodedDir);
}
});
} else {
findConfig();
}
);

return {
allConfigs,
configs: filteredConfigs,
configsById: filteredConfigsById,
configsByGroup: filteredConfigsByGroup,
firstMatch: filteredConfigs?.[0]
};
});

/**
* Import a route component.
Expand Down Expand Up @@ -160,7 +160,7 @@ const parseSearchParams = _memoize((currentPathAndOrSearch = window.location.sea
* @param {object} paths
* @returns {string}
*/
const pathJoin = (...paths) => {
const pathJoin = _memoize((...paths) => {
let updatedPath = Array.from(paths);
const hasLead = /^\/\//.test(updatedPath[0]);
updatedPath = updatedPath
Expand All @@ -174,7 +174,7 @@ const pathJoin = (...paths) => {
}

return updatedPath;
};
});

const routerHelpers = {
appName,
Expand Down

0 comments on commit e7c4828

Please sign in to comment.