Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(Link): Keep link active on subpaths of the tracked path #1220

Merged
merged 1 commit into from
May 28, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading