All files / src/components/docs/DocTree DocTree.tsx

32.18% Statements 28/87
28.76% Branches 21/73
36.36% Functions 8/22
38.46% Lines 25/65

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212                                          1x 2x 2x   1x                                               1x 1x 1x 1x     1x     1x 1x                                 1x   1x   1x 1x                   1x       1x                   1x     2x 2x 2x 2x   2x                       2x                                                                                                                         1x                                                  
import React, { useState, useMemo, useCallback, useEffect } from "react";
import { BookText, ChevronDown, ChevronRight, FileText } from "lucide-react";
 
export type DocNode = {
  title: string;
  icon?: React.ReactNode;
  url: string;
  description?: string;
  children?: DocNode[];
};
 
type DocTreeProps = {
  data: DocNode[];
  initiallyOpen?: string[];
  activeUrl?: string;
  className?: string;
  onNavigate?: (url: string) => void;
  searchPlaceholder?: string;
};
 
function flattenNodes(nodes: DocNode[], acc: DocNode[] = []) {
  for (const n of nodes) {
    acc.push(n);
    Iif (n.children) flattenNodes(n.children, acc);
  }
  return acc;
}
 
function ancestorUrls(nodes: DocNode[], targetUrl: string, trail: string[] = []): string[] {
  for (const n of nodes) {
    if (n.url === targetUrl) return trail;
    if (n.children) {
      const childTrail = [...trail, n.url];
      if (n.children.some((c) => c.url === targetUrl)) return childTrail;
      const deeper = ancestorUrls(n.children, targetUrl, childTrail);
      if (deeper.length) return deeper;
    }
  }
  return [];
}
 
export default function DocTree({
  data,
  initiallyOpen = [],
  activeUrl,
  className = "",
  onNavigate,
  searchPlaceholder = "Search docs...",
}: DocTreeProps) {
  const [open, setOpen] = useState<Record<string, boolean>>(() => {
    const map: Record<string, boolean> = {};
    initiallyOpen.forEach((id) => (map[id] = true));
    Iif (activeUrl) {
      ancestorUrls(data, activeUrl).forEach((id) => (map[id] = true));
    }
    return map;
  });
 
  useEffect(() => {
    Eif (!activeUrl) return;
    const ancestors = ancestorUrls(data, activeUrl);
    if (!ancestors.length) return;
    setOpen((o) => {
      const next = { ...o };
      let changed = false;
      for (const id of ancestors) {
        if (!next[id]) {
          next[id] = true;
          changed = true;
        }
      }
      return changed ? next : o;
    });
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [activeUrl]);
 
  const [query, setQuery] = useState("");
 
  const flat = useMemo(() => flattenNodes(data), [data]);
 
  const matches = useMemo(() => {
    Eif (!query.trim()) return new Set<string>();
    const q = query.trim().toLowerCase();
    const matched = new Set<string>();
    for (const node of flat) {
      setOpen((o) => ({ ...o, [node.url]: true }));
      if (node.title.toLowerCase().includes(q)) matched.add(node.url);
    }
    return matched;
  }, [query, flat]);
 
  const toggle = useCallback((id: string) => {
    setOpen((s) => ({ ...s, [id]: !s[id] }));
  }, []);
 
  const handleClick = useCallback(
    (url?: string) => {
      if (!url) return;
      if (onNavigate) onNavigate(url);
      else window.location.href = url;
    },
    [onNavigate],
  );
 
  function TreeList({ nodes, depth = 0 }: { nodes: DocNode[]; depth?: number }) {
    return (
      <ul className="space-y-0.5">
        {nodes.map((node) => {
          const hasChildren = !!node.children?.length;
          const isOpen = !!open[node.url];
          const isMatch = matches.has(node.url);
          const isActive = node.url === activeUrl;
 
          Iif (query && !isMatch) {
            const descMatch = (function check(n?: DocNode[]): boolean {
              if (!n) return false;
              for (const c of n) {
                if (matches.has(c.url)) return true;
                if (check(c.children)) return true;
              }
              return false;
            })(node.children);
            if (!descMatch) return null;
          }
 
          return (
            <li key={node.url}>
              <div
                className={`flex items-center gap-2 py-1.5 pr-2 rounded-md transition-colors duration-150 cursor-pointer hover:bg-gray-100 dark:hover:bg-gray-800 ${
                  isMatch && query ? "bg-gray-100 dark:bg-gray-800" : ""
                }`}
                style={{ paddingLeft: depth * 16 + 8 }}
              >
                <button
                  onClick={() => hasChildren && toggle(node.url)}
                  className="flex items-center justify-center size-5 rounded shrink-0 text-gray-400 dark:text-gray-500"
                  style={{
                    cursor: hasChildren ? "pointer" : "default",
                    background: "none",
                    border: "none",
                    padding: 0,
                  }}
                  tabIndex={hasChildren ? 0 : -1}
                >
                  {hasChildren ? (
                    isOpen
                      ? <ChevronDown className="size-3.5" />
                      : <ChevronRight className="size-3.5" />
                  ) : (
                    <span className="size-3.5" />
                  )}
                </button>
 
                <span
                  className={`shrink-0 size-4 flex items-center ${
                    isActive ? "text-blue-600 dark:text-blue-400" : "text-gray-400 dark:text-gray-500"
                  }`}
                >
                  {node.icon ?? (hasChildren ? <BookText className="size-4" /> : <FileText className="size-4" />)}
                </span>
 
                <a
                  onClick={(e) => { e.preventDefault(); handleClick(node.url); }}
                  href={node.url}
                  className={`flex-1 text-sm truncate no-underline ${
                    isActive
                      ? "font-semibold text-blue-600 dark:text-blue-400"
                      : "font-medium text-gray-700 dark:text-gray-300"
                  }`}
                >
                  {node.title}
                </a>
              </div>
 
              {hasChildren && isOpen && (
                <div className="ml-5 mt-0.5 mb-0.5 border-l border-gray-200 dark:border-gray-700">
                  <TreeList nodes={node.children!} depth={depth + 1} />
                </div>
              )}
            </li>
          );
        })}
      </ul>
    );
  }
 
  return (
    <div className={`w-full ${className}`}>
      <div className="flex items-center gap-2 mb-4">
        <input
          value={query}
          onChange={(e) => setQuery(e.target.value)}
          placeholder={searchPlaceholder}
          className="flex-1 text-sm px-3 py-2 rounded-md outline-none border border-gray-200 dark:border-gray-700 bg-transparent text-inherit focus:border-gray-400 dark:focus:border-gray-500"
        />
        {query && (
          <button
            onClick={() => { setQuery(""); setOpen({}); }}
            className="shrink-0 text-xs font-semibold px-3 py-2 rounded-md border border-gray-200 dark:border-gray-700 text-gray-500 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-800"
          >
            Clear
          </button>
        )}
      </div>
 
      <nav aria-label="Documentation tree">
        <TreeList nodes={data} />
      </nav>
    </div>
  );
}