Skip to content

Commit

Permalink
fix(Link): Keep link active on subpaths of the tracked path
Browse files Browse the repository at this point in the history
  • Loading branch information
binh-dam-ibigroup committed May 23, 2024
1 parent 61b6795 commit f9d9f6b
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 2 deletions.
18 changes: 18 additions & 0 deletions __tests__/components/util/link.ts
Original file line number Diff line number Diff line change
@@ -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()
})
})
8 changes: 6 additions & 2 deletions lib/components/util/link.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,11 @@ interface OwnProps extends AnchorHTMLAttributes<HTMLAnchorElement> {
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 <a> with specified path and query params,
* that preserves other existing query params.
Expand All @@ -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
Expand Down

0 comments on commit f9d9f6b

Please sign in to comment.