All files / src/apps/user/pages/knowledge AddSourceMenu.tsx

78.94% Statements 15/19
60% Branches 6/10
75% Functions 6/8
75% Lines 12/16

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              6x       25x 25x   25x 14x 1x       1x 1x     25x     1x                         1x 1x                                          
import { sourceIcon } from "@/apps/user/pages/knowledge/util";
import { Knowledge } from "@/objects/Knowledge";
import { ChevronDown, Plus } from "lucide-react";
import React, { useEffect, useRef, useState } from "react";
 
/** "Add source": the workspace's sources not yet in a repository, one click
 *  each. Used on the repository cards and the repository's page. */
export const AddSourceMenu: React.FC<{
  available: Knowledge[];
  onAdd: (knowledgeId: string) => void;
}> = ({ available, onAdd }) => {
  const [open, setOpen] = useState(false);
  const ref = useRef<HTMLDivElement>(null);
 
  useEffect(() => {
    if (!open) return;
    const handler = (e: MouseEvent) => {
      if (ref.current && !ref.current.contains(e.target as Node))
        setOpen(false);
    };
    document.addEventListener("mousedown", handler);
    return () => document.removeEventListener("mousedown", handler);
  }, [open]);
 
  return (
    <div ref={ref} className="relative">
      <button
        onClick={() => setOpen((v) => !v)}
        disabled={available.length === 0}
        className="flex items-center gap-1 text-xs font-medium text-gray-500 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-100 transition-colors disabled:opacity-40"
      >
        <Plus className="size-3.5" />
        Add source
        <ChevronDown
          className={`size-3 transition-transform ${open ? "rotate-180" : ""}`}
        />
      </button>
      {open && (
        <div className="absolute right-0 bottom-full mb-1.5 z-50 min-w-56 max-h-56 overflow-y-auto rounded-xl border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800 shadow-lg py-1">
          {available.map((kb) => {
            const Icon = sourceIcon(kb.source_type);
            return (
              <button
                key={kb.id}
                onClick={() => {
                  onAdd(kb.id);
                  setOpen(false);
                }}
                className="flex items-center gap-2 w-full px-3 py-1.5 text-xs text-left text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700/60 transition-colors"
              >
                <Icon className="size-3.5 shrink-0 text-gray-400" />
                <span className="truncate">{kb.name}</span>
              </button>
            );
          })}
        </div>
      )}
    </div>
  );
};
 
export default AddSourceMenu;