File size: 1,029 Bytes
6111b2b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
type SidebarLikeItem = {
  href: string;
  exact?: boolean;
  external?: boolean;
};

export function matchesSidebarHref(

  pathname: string | null | undefined,

  href: string,

  exact = false

): boolean {
  if (!pathname) return false;
  if (exact) return pathname === href;
  return pathname === href || pathname.startsWith(`${href}/`);
}

export function getActiveSidebarHref(

  pathname: string | null | undefined,

  items: SidebarLikeItem[]

): string | null {
  let bestMatch: SidebarLikeItem | null = null;

  for (const item of items) {
    if (item.external) continue;
    if (!matchesSidebarHref(pathname, item.href, item.exact === true)) continue;

    if (!bestMatch) {
      bestMatch = item;
      continue;
    }

    if (item.href.length > bestMatch.href.length) {
      bestMatch = item;
      continue;
    }

    if (item.href.length === bestMatch.href.length && item.exact && !bestMatch.exact) {
      bestMatch = item;
    }
  }

  return bestMatch?.href || null;
}