37 lines
1.5 KiB
TypeScript
37 lines
1.5 KiB
TypeScript
import { matchPath } from 'react-router-dom';
|
|
import { DIRECT_PATH, EXPLORE_PATH, HOME_PATH, INBOX_PATH, SPACE_PATH } from '../pages/paths';
|
|
import {
|
|
getDirectPath,
|
|
getExplorePath,
|
|
getHomePath,
|
|
getInboxPath,
|
|
getSpacePath,
|
|
} from '../pages/pathUtils';
|
|
|
|
/**
|
|
* Returns the section-root parent path for the given pathname, or null
|
|
* when pathname is not under a known section or is already at the root
|
|
* of its section. Shared by the UI back arrow (BackRouteHandler) and the
|
|
* Android hardware back button (useAndroidBackButton) so they can't drift.
|
|
*/
|
|
export const getRouteSectionParent = (pathname: string): string | null => {
|
|
const atRoot = (path: string) =>
|
|
matchPath({ path, caseSensitive: true, end: true }, pathname) !== null;
|
|
const under = (path: string) =>
|
|
matchPath({ path, caseSensitive: true, end: false }, pathname) !== null;
|
|
|
|
if (under(HOME_PATH)) return atRoot(HOME_PATH) ? null : getHomePath();
|
|
if (under(DIRECT_PATH)) return atRoot(DIRECT_PATH) ? null : getDirectPath();
|
|
|
|
const spaceMatch = matchPath({ path: SPACE_PATH, caseSensitive: true, end: false }, pathname);
|
|
const encodedSpaceIdOrAlias = spaceMatch?.params.spaceIdOrAlias;
|
|
if (encodedSpaceIdOrAlias) {
|
|
const spacePath = getSpacePath(decodeURIComponent(encodedSpaceIdOrAlias));
|
|
return pathname === spacePath ? null : spacePath;
|
|
}
|
|
|
|
if (under(EXPLORE_PATH)) return atRoot(EXPLORE_PATH) ? null : getExplorePath();
|
|
if (under(INBOX_PATH)) return atRoot(INBOX_PATH) ? null : getInboxPath();
|
|
|
|
return null;
|
|
};
|