From f9d9f6b0810c95576cc50a883b6c9d13bb90319b Mon Sep 17 00:00:00 2001 From: binh-dam-ibigroup <56846598+binh-dam-ibigroup@users.noreply.github.com> Date: Thu, 23 May 2024 14:04:31 -0400 Subject: [PATCH] fix(Link): Keep link active on subpaths of the tracked path --- __tests__/components/util/link.ts | 18 ++++++++++++++++++ lib/components/util/link.ts | 8 ++++++-- 2 files changed, 24 insertions(+), 2 deletions(-) create mode 100644 __tests__/components/util/link.ts 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