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

41.07% Statements 23/56
34.04% Branches 16/47
41.17% Functions 7/17
47.72% Lines 21/44

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                                            1x 2x 2x   1x                     1x 1x 1x 1x     1x     1x   1x 1x                       1x       1x                                 1x     2x 2x 2x     2x                         2x                                                                                                           1x                                                        
import React, { useState, useMemo, useCallback } from "react";
import { BookText, ChevronDown, ChevronRight, FileText } from "lucide-react";
import { MyButton } from "chainr-frontend-shared";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
 
export type DocNode = {
  title: string;
  icon?: React.ReactNode;
  url: string;
  children?: DocNode[];
};
 
type DocTreeProps = {
  data: DocNode[]; // root nodes
  initiallyOpen?: string[]; // ids of nodes to keep open initially
  className?: string;
  onNavigate?: (url: string) => void; // callback when link clicked
  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;
}
 
export default function DocTree({
  data,
  initiallyOpen = [],
  className = "",
  onNavigate,
  searchPlaceholder = "Search docs...",
}: DocTreeProps) {
  // track which node ids are expanded
  const [open, setOpen] = useState<Record<string, boolean>>(() => {
    const map: Record<string, boolean> = {};
    initiallyOpen.forEach((id) => (map[id] = true));
    return map;
  });
 
  const [query, setQuery] = useState("");
 
  // pre-flattened list for simple searching
  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((open) => ({ ...open, [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]
  );
 
  // render a tree recursively
  function TreeList({
    nodes,
    depth = 0,
  }: {
    nodes: DocNode[];
    depth?: number;
  }) {
    return (
      <ul className="space-y-1">
        {nodes.map((node) => {
          const hasChildren = !!node.children && node.children.length > 0;
          const isOpen = !!open[node.url];
          const isMatch = matches.has(node.url);
 
          // If query exists, only show nodes that match or are ancestors of matches
          Iif (query && !isMatch) {
            // check if any descendant matches
            const descMatch = (function checkDesc(n?: DocNode[]): boolean {
              if (!n) return false;
              for (const c of n) {
                if (matches.has(c.url)) return true;
                if (checkDesc(c.children)) return true;
              }
              return false;
            })(node.children);
            if (!descMatch) return null;
          }
 
          return (
            <li key={node.url}>
              <div
                className={`flex items-center justify-center p-2 gap-2 rounded-md hover:bg-slate-300/80 transition-colors duration-150 cursor-pointer ${
                  isMatch ? "" : "opacity-70"
                }`}
                style={{ paddingLeft: depth * 12 + 8 }}
              >
                {hasChildren ? (
                  <MyButton
                    name={
                      isOpen ? (
                        <ChevronDown className="text-white" />
                      ) : (
                        <ChevronRight className="text-black" />
                      )
                    }
                    onClick={() => toggle(node.url)}
                    classes={`!mb-0 size-2 bg-transparent w-16 bg-slate-800/80 flex items-center justify-center ${
                      isOpen ? "!bg-slate-800" : ""
                    }`}
                  ></MyButton>
                ) : (
                  <div style={{ width: 24 }}></div>
                )}
 
                <div className="flex-1 truncate">
                  <div className="flex items-center gap-2">
                    <a
                      onClick={() => handleClick(node.url)}
                      className="text-sm text-slate-100 hover:underline truncate flex flex-row gap-4"
                    >
                      {node.icon ?? (hasChildren ? <BookText /> : <FileText />)}
                      {node.title}
                    </a>
                    {node.url ? (
                      <span className="text-xs text-slate-400">{node.url}</span>
                    ) : null}
                  </div>
                </div>
              </div>
 
              {hasChildren && isOpen ? (
                <div className="mt-1 ml-10">
                  <TreeList nodes={node.children!} depth={depth + 1} />
                </div>
              ) : null}
            </li>
          );
        })}
      </ul>
    );
  }
 
  return (
    <div className={`w-full ${className}`}>
      <div className="flex items-center gap-3 mb-3 w-full">
        <Input
          value={query}
          onChange={(e) => setQuery(e.target.value)}
          placeholder={searchPlaceholder}
          // className="flex-1 text-slate-100 px-3 py-2 rounded-md placeholder:text-slate-400 focus:outline-none focus:ring-2 focus:ring-blue-500"
        />
        <Button
          onClick={() => {
            setQuery("");
            setOpen({});
          }}
          // className="px-3 py-2 rounded-md bg-slate-700 text-sm text-slate-200 hover:bg-slate-700"
          variant="outline"
          size="sm"
        >
          Reset
        </Button>
      </div>
 
      <nav aria-label="Documentation tree">
        <TreeList nodes={data} />
      </nav>
    </div>
  );
}