@snipsonian/redux-first-router
Version:
Redux-first-router snippets
59 lines (58 loc) • 2 kB
JavaScript
import isInteger from '@snipsonian/core/es/is/isInteger';
import { getRoute, getRouteKeyByPath } from '../route/routeManager';
import parseVirtualPage from './parseVirtualPage';
const NO_RERENDER = {
EMPTY_OBJECT: {},
};
let reducerKey = 'NOT_SET_YET';
export function setReducerKey(newReducerKey) {
reducerKey = newReducerKey;
}
export function getReducerState(state) {
return state[reducerKey];
}
export function getCurrentRouteKey(state) {
return getReducerState(state).type;
}
export function getCurrentRouteInfo(state) {
return getRoute({
routeKey: getCurrentRouteKey(state),
});
}
export function getCurrentRoutePayload(state) {
const payload = getReducerState(state).payload;
if (!payload || typeof payload !== 'object') {
return payload;
}
return Object.keys(payload)
.reduce((accumulator, current) => {
const value = payload[current];
if (isInteger(value)) {
accumulator[current] = Number(value);
}
else {
accumulator[current] = typeof value === 'string' ? decodeURIComponent(value) : value;
}
return accumulator;
}, {});
}
export function getPropertyFromCurrentRoutePayload(state, property) {
return getCurrentRoutePayload(state)[property];
}
export function getCurrentRouteQueryParams(state) {
return (getReducerState(state).query || NO_RERENDER.EMPTY_OBJECT);
}
export function getTopParentRouteKey(state) {
const currentRoutePathParts = getCurrentRouteInfo(state).path.split('/');
return getRouteKeyByPath({
path: `/${currentRoutePathParts[1]}`,
});
}
export function isChildRouteOf(routeKey, possibleParentRouteKey) {
const route = getRoute({ routeKey });
const possibleParentRoute = getRoute({ routeKey: possibleParentRouteKey });
return route.path.indexOf(possibleParentRoute.path) === 0;
}
export function getVirtualPageForRoute(state, route) {
return parseVirtualPage(state, route.virtualPage);
}