diff --git a/__tests__/components/util/link.ts b/__tests__/components/util/link.ts new file mode 100644 index 000000000..2467c6775 --- /dev/null +++ b/__tests__/components/util/link.ts @@ -0,0 +1,18 @@ +import '../../test-utils/mock-window-url' + +import { isSubpath } from '../../../lib/components/util/link' + +describe('components > util > Link > isSubpath', () => { + it('should be true on a path that starts with the tracked path', () => { + expect(isSubpath('/', '/')).toBeTruthy() + expect(isSubpath('/trips', '/trips')).toBeTruthy() + expect(isSubpath('/trips/trip123', '/trips')).toBeTruthy() + }) + it('should be false on a path that starts differently than the tracked path', () => { + expect(isSubpath('/trips/trip123', '/route')).toBeFalsy() + expect(isSubpath('/', '/route')).toBeFalsy() + }) + it('should be false if tracking home (/) and on a path that is not home.', () => { + expect(isSubpath('/trips/trip123', '/')).toBeFalsy() + }) +}) diff --git a/lib/components/util/link.ts b/lib/components/util/link.ts index 9797a4733..253c71057 100644 --- a/lib/components/util/link.ts +++ b/lib/components/util/link.ts @@ -12,6 +12,11 @@ interface OwnProps extends AnchorHTMLAttributes { tracking?: boolean } +/** Determines whether the given path is a subpath of the 'to' prop. */ +export function isSubpath(path: string, to: string): boolean { + return !isBlank(to) && (path === to || path.startsWith(`${to}/`)) +} + /** * Renders an anchor element with specified path and query params, * that preserves other existing query params. @@ -25,8 +30,7 @@ const mapStateToProps = (state: AppReduxState, ownProps: OwnProps) => { const queryParams = combineQueryParams(toParams) const href = `#${to}${isBlank(queryParams) ? '' : `?${queryParams}`}` - const isActive = - tracking && !isBlank(to) && state.router.location.pathname === to + const isActive = tracking && isSubpath(state.router.location.pathname, to) return { className: className && isActive