Skip to content

OpenRAG is a comprehensive, single package Retrieval-Augmented Generation platform built on Langflow, Docling, and Opensearch.

Python
22.5 KB
Raw Blame
import Fuse from "fuse.js";
import { ArrowRight, Check, Funnel, Loader2, Plus } from "lucide-react";
import { AnimatePresence, motion } from "motion/react";
import { useImperativeHandle, useMemo, useRef, useState } from "react";
import TextareaAutosize from "react-textarea-autosize";
import { Button } from "@/components/ui/button";
import {
  Popover,
  PopoverAnchor,
  PopoverContent,
} from "@/components/ui/popover";
import { useIsCloudBrand } from "@/contexts/brand-context";
import { useFileDrag } from "@/hooks/use-file-drag";
import { useImeComposition } from "@/hooks/use-ime-composition";
import { useSupportedFileTypes } from "@/hooks/use-supported-file-types";
import type { FilterColor } from "@/lib/filter-constants";
import type { ImeCompositionState } from "@/lib/ime-composition";
import { cn } from "@/lib/utils";
import { useGetAllFiltersQuery } from "../../api/queries/useGetAllFiltersQuery";
import type { KnowledgeFilterData } from "../_types/types";
import { FilePreview } from "./file-preview";
import { SelectedKnowledgeFilter } from "./selected-knowledge-filter";

export interface ChatInputHandle {
  focusInput: () => void;
  clickFileInput: () => void;
  /** Snapshot of the open or just-finished IME session, including `now`. */
  getImeState: () => ImeCompositionState;
}

interface ChatInputProps {
  input: string;
  loading: boolean;
  isUploading: boolean;
  ingestViaChat: boolean;
  selectedFilter: KnowledgeFilterData | null;
  parsedFilterData: { color?: FilterColor } | null;
  uploadedFile: File | null;
  onSubmit: (e: React.FormEvent) => void;
  onChange: (value: string) => void;
  onKeyDown: (
    e: React.KeyboardEvent<HTMLTextAreaElement>,
    imeState: ImeCompositionState,
  ) => void;
  onFilterSelect: (filter: KnowledgeFilterData | null) => void;
  onFilePickerClick: () => void;
  setSelectedFilter: (filter: KnowledgeFilterData | null) => void;
  setIsFilterHighlighted: (highlighted: boolean) => void;
  onFileSelected: (file: File | null) => void;
}

const SAFE_SINGLE_LINE_CHARS = 80; // Number of chars that can safely fit in one line without wrapping, used to determine when to switch to multi-line mode

export function ChatInput({
  input,
  loading,
  isUploading,
  ingestViaChat,
  selectedFilter,
  parsedFilterData,
  uploadedFile,
  onSubmit,
  onChange,
  onKeyDown,
  onFilterSelect,
  onFilePickerClick,
  setSelectedFilter,
  setIsFilterHighlighted,
  onFileSelected,
  ref,
}: ChatInputProps & { ref?: React.Ref<ChatInputHandle> }) {
  const inputRef = useRef<HTMLTextAreaElement>(null);
  const fileInputRef = useRef<HTMLInputElement>(null);
  const ime = useImeComposition();
  const [isWrapped, setIsWrapped] = useState(false);
  const isMultiline = input.includes("\n") || isWrapped;
  const isDragging = useFileDrag();
  const isCloudBrand = useIsCloudBrand();
  const { supportedExtensions } = useSupportedFileTypes();

  // Internal state for filter dropdown
  const [isFilterDropdownOpen, setIsFilterDropdownOpen] = useState(false);
  const [filterSearchTerm, setFilterSearchTerm] = useState("");
  const [selectedFilterIndex, setSelectedFilterIndex] = useState(0);
  const [anchorPosition, setAnchorPosition] = useState<{
    x: number;
    y: number;
  } | null>(null);

  // Fetch all filters once when dropdown opens
  const { data: allFilters = [] } = useGetAllFiltersQuery({
    enabled: isFilterDropdownOpen,
  });

  // Use fuse.js for fuzzy search on client side
  const filteredFilters = useMemo(() => {
    if (!filterSearchTerm) {
      return allFilters.slice(0, 20); // Return first 20 when no search term
    }

    const fuse = new Fuse(allFilters, {
      keys: ["name", "description"],
      threshold: 0.3, // 0.0 = perfect match, 1.0 = match anything
      includeScore: true,
      minMatchCharLength: 1,
    });

    const results = fuse.search(filterSearchTerm);
    return results.map((result) => result.item).slice(0, 20);
  }, [allFilters, filterSearchTerm]);

  useImperativeHandle(ref, () => ({
    focusInput: () => {
      inputRef.current?.focus();
    },
    clickFileInput: () => {
      fileInputRef.current?.click();
    },
    getImeState: () => ime.readState(),
  }));

  const handleFilePickerChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const files = e.target.files;
    if (files && files.length > 0) {
      onFileSelected(files[0]);
    } else {
      onFileSelected(null);
    }
  };

  const onAtClick = () => {
    if (!isFilterDropdownOpen) {
      setIsFilterDropdownOpen(true);
      setFilterSearchTerm("");
      setSelectedFilterIndex(0);

      // Get button position for popover anchoring
      const button = document.querySelector(
        "[data-filter-button]",
      ) as HTMLElement;
      if (button) {
        const rect = button.getBoundingClientRect();
        setAnchorPosition({
          x: rect.left + rect.width / 2,
          y: rect.top + rect.height / 2 - 12,
        });
      }
    } else {
      setIsFilterDropdownOpen(false);
    }
  };

  const handleFilterSelect = (filter: KnowledgeFilterData | null) => {
    onFilterSelect(filter);

    // Remove the @searchTerm from the input
    const words = input.split(" ");
    const lastWord = words[words.length - 1];

    if (lastWord.startsWith("@")) {
      // Remove the @search term
      words.pop();
      onChange(words.join(" ") + (words.length > 0 ? " " : ""));
    }

    setIsFilterDropdownOpen(false);
    setFilterSearchTerm("");
    setSelectedFilterIndex(0);
  };

  const handleChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
    const newValue = e.target.value;
    onChange(newValue); // Call parent's onChange with the string value

    // Detect visual wrapping - only collapse when text is clearly short enough
    // to prevent flickering at the boundary (flex-row has less width than flex-col)
    if (!newValue.includes("\n") && newValue.length < SAFE_SINGLE_LINE_CHARS) {
      setIsWrapped(false);
    } else {
      const textarea = e.target;
      const lineHeight =
        parseFloat(getComputedStyle(textarea).lineHeight) || 20;
      const wrapping = textarea.scrollHeight > lineHeight * 1.5;
      if (wrapping) {
        setIsWrapped(true);
      }
    }

    // Find if there's an @ at the start of the last word
    const words = newValue.split(" ");
    const lastWord = words[words.length - 1];

    if (lastWord.startsWith("@")) {
      const searchTerm = lastWord.slice(1); // Remove the @
      setFilterSearchTerm(searchTerm);
      setSelectedFilterIndex(0);

      // Only set anchor position when @ is first detected (search term is empty)
      if (searchTerm === "") {
        const getCursorPosition = (textarea: HTMLTextAreaElement) => {
          // Create a hidden div with the same styles as the textarea
          const div = document.createElement("div");
          const computedStyle = getComputedStyle(textarea);

          // Copy all computed styles to the hidden div
          for (const style of computedStyle) {
            (div.style as unknown as Record<string, string>)[style] =
              computedStyle.getPropertyValue(style);
          }

          // Set the div to be hidden but not un-rendered
          div.style.position = "absolute";
          div.style.visibility = "hidden";
          div.style.whiteSpace = "pre-wrap";
          div.style.wordWrap = "break-word";
          div.style.overflow = "hidden";
          div.style.height = "auto";
          div.style.width = `${textarea.getBoundingClientRect().width}px`;

          // Get the text up to the cursor position
          const cursorPos = textarea.selectionStart || 0;
          const textBeforeCursor = textarea.value.substring(0, cursorPos);

          // Add the text before cursor
          div.textContent = textBeforeCursor;

          // Create a span to mark the end position
          const span = document.createElement("span");
          span.textContent = "|"; // Cursor marker
          div.appendChild(span);

          // Add the text after cursor to handle word wrapping
          const textAfterCursor = textarea.value.substring(cursorPos);
          div.appendChild(document.createTextNode(textAfterCursor));

          // Add the div to the document temporarily
          document.body.appendChild(div);

          // Get positions
          const inputRect = textarea.getBoundingClientRect();
          const divRect = div.getBoundingClientRect();
          const spanRect = span.getBoundingClientRect();

          // Calculate the cursor position relative to the input
          const x = inputRect.left + (spanRect.left - divRect.left);
          const y = inputRect.top + (spanRect.top - divRect.top);

          // Clean up
          document.body.removeChild(div);

          return { x, y };
        };

        const pos = getCursorPosition(e.target);
        setAnchorPosition(pos);
      }

      if (!isFilterDropdownOpen) {
        setIsFilterDropdownOpen(true);
      }
    } else if (isFilterDropdownOpen) {
      // Close dropdown if @ is no longer present
      setIsFilterDropdownOpen(false);
      setFilterSearchTerm("");
    }
  };

  const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
    // One snapshot for this keydown, shared with the parent submit handler.
    // Confirming a Kanji (or other IME) candidate fires Enter and must not
    // select a filter or submit the message.
    const imeState = ime.readState();
    if (ime.blockEnter(e, imeState)) {
      return;
    }

    if (isFilterDropdownOpen) {
      if (e.key === "Escape") {
        e.preventDefault();
        setIsFilterDropdownOpen(false);
        setFilterSearchTerm("");
        setSelectedFilterIndex(0);
        inputRef.current?.focus();
        return;
      }

      if (e.key === "ArrowDown") {
        e.preventDefault();
        setSelectedFilterIndex((prev) =>
          prev < filteredFilters.length - 1 ? prev + 1 : 0,
        );
        return;
      }

      if (e.key === "ArrowUp") {
        e.preventDefault();
        setSelectedFilterIndex((prev) =>
          prev > 0 ? prev - 1 : filteredFilters.length - 1,
        );
        return;
      }

      if (e.key === "Enter") {
        // Check if we're at the end of an @ mention
        const cursorPos = e.currentTarget.selectionStart || 0;
        const textBeforeCursor = input.slice(0, cursorPos);
        const words = textBeforeCursor.split(" ");
        const lastWord = words[words.length - 1];

        if (lastWord.startsWith("@") && filteredFilters[selectedFilterIndex]) {
          e.preventDefault();
          handleFilterSelect(filteredFilters[selectedFilterIndex]);
          return;
        }
      }

      if (e.key === " ") {
        // Space cycles IME candidates. A space after compositionend is a real space.
        if (ime.isImeCandidateKey(e.nativeEvent)) {
          return;
        }
        // Select filter on space if we're typing an @ mention
        const cursorPos = e.currentTarget.selectionStart || 0;
        const textBeforeCursor = input.slice(0, cursorPos);
        const words = textBeforeCursor.split(" ");
        const lastWord = words[words.length - 1];

        if (lastWord.startsWith("@") && filteredFilters[selectedFilterIndex]) {
          e.preventDefault();
          handleFilterSelect(filteredFilters[selectedFilterIndex]);
          return;
        }
      }
    }

    // Pass through to parent onKeyDown for other key handling
    onKeyDown(e, imeState);
  };

  return (
    <div className="w-full">
      <form onSubmit={onSubmit} className="relative">
        {/* Outer container - flex-col to stack file preview above input */}
        <div
          className={cn(
            "flex flex-col w-full p-2 rounded-xl border transition-all",
            isCloudBrand ? "border-(--chat-input-border)" : "border-input",
            isCloudBrand ? "bg-(--chat-prompt-bg)" : "bg-transparent",
            !isDragging &&
              (isCloudBrand
                ? "hover:not-focus-within:border-muted-foreground focus-within:border-(--chat-input-border)"
                : "hover:not-focus-within:border-muted-foreground focus-within:border-foreground"),
            isDragging && "border-dashed",
          )}
        >
          {/* File Preview Section - Always above */}
          <AnimatePresence>
            {uploadedFile && (
              <motion.div
                initial={{ opacity: 0, height: 0, marginBottom: 0 }}
                animate={{ opacity: 1, height: "auto", marginBottom: 8 }}
                exit={{ opacity: 0, height: 0, marginBottom: 0 }}
                className="overflow-hidden"
              >
                <FilePreview
                  uploadedFile={uploadedFile}
                  onClear={() => {
                    onFileSelected(null);
                  }}
                  isUploading={isUploading}
                />
              </motion.div>
            )}
          </AnimatePresence>
          <AnimatePresence>
            {isDragging && (
              <motion.div
                initial={{ opacity: 0, height: 0 }}
                animate={{ opacity: 1, height: 100 }}
                exit={{ opacity: 0, height: 0 }}
                className="overflow-hidden w-full flex flex-col items-center justify-center gap-2"
              >
                <p className="text-md font-medium text-primary">
                  Add files to conversation
                </p>
                <p className="text-sm text-muted-foreground">
                  Text formats and image files.{" "}
                  <span className="font-semibold">10</span> files per chat,{" "}
                  <span className="font-semibold">150 MB</span> each.
                </p>
              </motion.div>
            )}
          </AnimatePresence>
          {/* Main Input Container - flex-row or flex-col based on textarea height */}
          <div
            className={`relative flex w-full gap-2 ${
              isMultiline ? "flex-col" : "flex-row items-center"
            }`}
          >
            {/* Filter + Textarea Section */}
            <div
              className={`flex items-center gap-2 ${isMultiline ? "w-full" : "flex-1"}`}
            >
              {!isMultiline &&
                (selectedFilter ? (
                  <SelectedKnowledgeFilter
                    selectedFilter={selectedFilter}
                    parsedFilterData={parsedFilterData}
                    onClear={() => {
                      setSelectedFilter(null);
                      setIsFilterHighlighted(false);
                    }}
                  />
                ) : (
                  <Button
                    type="button"
                    variant="ghost"
                    size="iconSm"
                    className={cn(
                      "h-8 w-8 p-0 rounded-md",
                      isCloudBrand
                        ? "hover:bg-(--layered-select-bg)"
                        : "hover:bg-muted/50",
                    )}
                    onMouseDown={(e) => {
                      e.preventDefault();
                    }}
                    onClick={onAtClick}
                    data-filter-button
                  >
                    <Funnel className="h-4 w-4" />
                  </Button>
                ))}
              <div className="relative flex-1 flex items-center">
                <TextareaAutosize
                  ref={inputRef}
                  value={input}
                  onChange={handleChange}
                  {...ime.inputProps}
                  onKeyDown={handleKeyDown}
                  maxRows={7}
                  autoComplete="off"
                  minRows={1}
                  placeholder="Ask a question..."
                  data-testid="chat-input"
                  disabled={loading}
                  className={`w-full text-sm bg-transparent focus-visible:outline-hidden resize-none`}
                  rows={1}
                />
              </div>
            </div>

            {/* Action Buttons Section */}
            <div
              className={`flex items-center gap-2 ${isMultiline ? "justify-between w-full" : ""}`}
            >
              {isMultiline &&
                (selectedFilter ? (
                  <SelectedKnowledgeFilter
                    selectedFilter={selectedFilter}
                    parsedFilterData={parsedFilterData}
                    onClear={() => {
                      setSelectedFilter(null);
                      setIsFilterHighlighted(false);
                    }}
                  />
                ) : (
                  <Button
                    type="button"
                    variant="ghost"
                    size="iconSm"
                    className={cn(
                      "h-8 w-8 p-0 rounded-md",
                      isCloudBrand
                        ? "hover:bg-(--layered-select-bg)"
                        : "hover:bg-muted/50",
                    )}
                    onMouseDown={(e) => {
                      e.preventDefault();
                    }}
                    onClick={onAtClick}
                    data-filter-button
                  >
                    <Funnel className="h-4 w-4" />
                  </Button>
                ))}
              <div className="flex items-center gap-2">
                {ingestViaChat && (
                  <Button
                    type="button"
                    variant="ghost"
                    size="iconSm"
                    onClick={onFilePickerClick}
                    disabled={isUploading}
                    className={cn(
                      "h-8 w-8 p-0 rounded-md!",
                      isCloudBrand
                        ? "hover:bg-(--layered-select-bg)"
                        : "hover:bg-muted/50",
                    )}
                  >
                    <Plus className="h-4 w-4" />
                  </Button>
                )}
                <Button
                  variant="default"
                  type="submit"
                  size="iconSm"
                  disabled={(!input.trim() && !uploadedFile) || loading}
                  className="chat-submit rounded-md! h-8 w-8 p-0"
                  data-testid="send-button"
                >
                  {loading ? (
                    <Loader2 className="h-4 w-4 animate-spin" />
                  ) : (
                    <ArrowRight className="h-4 w-4" />
                  )}
                </Button>
              </div>
            </div>
          </div>
        </div>
        <input
          ref={fileInputRef}
          type="file"
          onChange={handleFilePickerChange}
          className="hidden"
          accept={supportedExtensions.join(",")}
        />

        <Popover
          open={isFilterDropdownOpen}
          onOpenChange={(open) => {
            setIsFilterDropdownOpen(open);
          }}
        >
          {anchorPosition && (
            <PopoverAnchor
              asChild
              style={{
                position: "fixed",
                left: anchorPosition.x,
                top: anchorPosition.y,
                width: 1,
                height: 1,
                pointerEvents: "none",
              }}
            >
              <div />
            </PopoverAnchor>
          )}
          <PopoverContent
            className="w-64 p-2"
            side="top"
            align="start"
            sideOffset={6}
            alignOffset={-18}
            onOpenAutoFocus={(e) => {
              // Prevent auto focus on the popover content
              e.preventDefault();
              // Keep focus on the input
            }}
          >
            <div className="space-y-1">
              {filterSearchTerm && (
                <div className="px-2 py-1.5 text-xs font-medium text-muted-foreground">
                  Searching: @{filterSearchTerm}
                </div>
              )}
              {allFilters.length === 0 ? (
                <div className="px-2 py-3 text-sm text-muted-foreground">
                  No knowledge filters available
                </div>
              ) : (
                <>
                  {!filterSearchTerm && (
                    <button
                      type="button"
                      onClick={() => handleFilterSelect(null)}
                      className={cn(
                        "w-full text-left px-2 py-2 text-sm rounded flex items-center justify-between",
                        isCloudBrand
                          ? "hover:bg-(--layered-select-bg)"
                          : "hover:bg-muted/50",
                        selectedFilterIndex === -1 &&
                          (isCloudBrand
                            ? "bg-(--layered-select-bg)"
                            : "bg-muted/50"),
                      )}
                    >
                      <span>No knowledge filter</span>
                      {!selectedFilter && (
                        <Check className="h-4 w-4 shrink-0" />
                      )}
                    </button>
                  )}
                  {filteredFilters.map((filter, index) => (
                    <button
                      key={filter.id}
                      type="button"
                      onClick={() => handleFilterSelect(filter)}
                      className={cn(
                        "w-full overflow-hidden text-left px-2 py-2 gap-2 text-sm rounded flex items-center justify-between",
                        isCloudBrand
                          ? "hover:bg-(--layered-select-bg)"
                          : "hover:bg-muted/50",
                        index === selectedFilterIndex &&
                          (isCloudBrand
                            ? "bg-(--layered-select-bg)"
                            : "bg-muted/50"),
                      )}
                    >
                      <div className="overflow-hidden">
                        <div className="font-medium truncate">
                          {filter.name}
                        </div>
                        {filter.description && (
                          <div className="text-xs text-muted-foreground truncate">
                            {filter.description}
                          </div>
                        )}
                      </div>
                      {selectedFilter?.id === filter.id && (
                        <Check className="h-4 w-4 shrink-0" />
                      )}
                    </button>
                  ))}
                  {filteredFilters.length === 0 && filterSearchTerm && (
                    <div className="px-2 py-3 text-sm text-muted-foreground">
                      No filters match &quot;{filterSearchTerm}&quot;
                    </div>
                  )}
                </>
              )}
            </div>
          </PopoverContent>
        </Popover>
      </form>
    </div>
  );
}