Skip to content

Commit

Permalink
allow isSamePath to accept undefined values
Browse files Browse the repository at this point in the history
  • Loading branch information
slorber committed Nov 2, 2020
1 parent d88d4da commit 1724fee
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 4 deletions.
10 changes: 10 additions & 0 deletions packages/docusaurus-theme-classic/src/__tests__/utils.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,4 +19,14 @@ describe('isSamePath', () => {
test('should be false for compared path with double trailing slash', () => {
expect(isSamePath('/docs', '/docs//')).toBeFalsy();
});

test('should be true for twice undefined/null', () => {
expect(isSamePath(undefined, undefined)).toBeTruthy();
expect(isSamePath(undefined, undefined)).toBeTruthy();
});

test('should be false when one undefined', () => {
expect(isSamePath('/docs', undefined)).toBeFalsy();
expect(isSamePath(undefined, '/docs')).toBeFalsy();
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,7 @@ function NavItemMobile({
const menuListRef = useRef<HTMLUListElement>(null);
const {pathname} = useLocation();
const [collapsed, setCollapsed] = useState(
() => !items?.filter((item) => item.to).some((item) => isSamePath(item.to, pathname)) ?? true,
() => !items?.some((item) => isSamePath(item.to, pathname)) ?? true,
);

const navLinkClassNames = (extraClassName?: string, isSubList = false) =>
Expand Down
11 changes: 8 additions & 3 deletions packages/docusaurus-theme-classic/src/utils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,12 @@
*/

// Compare the 2 paths, ignoring trailing /
export const isSamePath = (path1, path2) => {
const normalize = (str) => (str?.endsWith('/') ? str : `${str}/`);
return normalize(path1) === normalize(path2);
export const isSamePath = (
path1: string | undefined,
path2: string | undefined,
) => {
const normalize = (pathname: string | undefined) => {
return !pathname || pathname?.endsWith('/') ? pathname : `${pathname}/`;
};
return normalize(path1) === normalize(path2);
};

0 comments on commit 1724fee

Please sign in to comment.