All files / src/components/SearchForm index.tsx

100% Statements 175/175
94.73% Branches 36/38
100% Functions 9/9
100% Lines 175/175

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 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 2531x                   1x             1x 1x 1x 1x     1x     1x       1x                                         1x 3x 3x 3x 1x 1x   3x 3x   1x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x   60x 60x 60x   60x 3x 3x 60x     60x 4x 3x 3x 3x 4x     60x 60x 60x 60x   60x 60x 60x 60x   60x 60x 5x 5x 5x 5x   5x 5x   60x 60x   60x 58x 58x 9x 9x   9x   9x   9x 9x 58x   58x 60x     60x 5x 5x 5x 5x     60x 2x 2x 2x 2x   60x 60x 49x 49x 49x 5x 5x 49x 49x 49x 3x 3x 3x 3x 3x 49x 60x 60x   60x 60x 60x 60x 60x 60x   60x 60x 60x 60x 60x   60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x   60x 12x 12x 12x 12x 12x 12x 12x   12x 12x 12x 12x 12x     60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x   60x 60x   60x 7x 7x 7x 7x 7x 3x   4x 4x 4x   7x 7x 7x   60x   60x  
import {
  useState,
  useRef,
  ChangeEvent,
  useCallback,
  useMemo,
  useEffect,
} from 'react';
 
// Constants
import {
  CHATBOT_MESSAGES,
  KEYBOARD_EVENT,
  SEARCH_PLACEHOLDER,
} from '@shared/constants';
 
// Components
import CloseIcon from '@shared/icons/CloseIcon';
import { Button, Separator } from '@shared/ui';
import { ThinkingIndicator } from '../Chatbot/ThinkingIndicator';
import { ChatbotResponse } from '../Chatbot/ChatbotResponse';
 
// Types
import { ActionItemType, ActionKind } from '@shared/types';
 
// Utils
import { combineClasses } from '@shared/utils';
import { Message, TextMessage } from '@copilotkit/runtime-client-gql';
 
// Helper
import {
  groupOptionsByGroup,
  handleActionClick as handleActionClickHelper,
} from './helper';
 
interface SearchFormProps {
  value?: string;
  actionItems?: ActionItemType[];
  isLoading?: boolean;
  onInputChange?: (value: string) => void;
  onSubmitSearch?: (value: string) => void;
  onClose?: () => void;
  onResetResult?: () => void;
  onClearKeyword?: () => void;
  requestConfig?: {
    token: string;
    userEmail: string;
  };
  visibleMessages?: Message[];
}
 
const formalizeMsgContent = (content: string, actionLabel: string) => {
  const sanitized = content?.replace(/\s?\[.*?\]\(#\)\s?/g, '');
  const hasTSFormat = content.includes('```ts');
  if (hasTSFormat && actionLabel) {
    return CHATBOT_MESSAGES.SEARCH_SUCCESSFULLY(actionLabel);
  }
 
  return sanitized || CHATBOT_MESSAGES.SEARCH_SUCCESSFULLY(actionLabel);
};
 
export const SearchForm = ({
  value = '',
  actionItems = [],
  isLoading = false,
  onInputChange,
  onClose,
  onClearKeyword = () => {},
  onResetResult = () => {},
  onSubmitSearch = () => {},
  requestConfig,
  visibleMessages = [],
}: SearchFormProps) => {
  // Add state to track which item is currently loading
  const [searchQuery, setSearchQuery] = useState(value);
  const searchInputRef = useRef<HTMLInputElement>(null);
  const [optionExecuteBefore, setOptionExecuteBefore] = useState('');
 
  const handleSubmitSearch = useCallback(() => {
    onSubmitSearch?.(searchQuery);
    setOptionExecuteBefore('');
  }, [onSubmitSearch, searchQuery]);
 
  // Handle keyboard events
  const handleKeyDown = (event: React.KeyboardEvent) => {
    if (event.key === KEYBOARD_EVENT.ENTER) {
      handleSubmitSearch();
      return;
    }
  };
 
  // Group options by group
  const groupedOptions = useMemo(
    () => groupOptionsByGroup(actionItems),
    [actionItems],
  );
 
  const groupOptionsList = Object.entries(groupedOptions);
  const validationItem = actionItems.find(
    (item) => item.kind === ActionKind.VALIDATION,
  );
 
  const handleActionClick = useCallback(
    async (item: ActionItemType) => {
      await handleActionClickHelper({
        item,
        onClose,
      });
      // Clean action items after action is handled
      onResetResult();
    },
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [onClose, requestConfig],
  );
 
  useEffect(() => {
    const executeAction = async () => {
      if (groupOptionsList.length > 0 && !isLoading && !validationItem) {
        const result = groupOptionsList[0];
        const detectedAction = result?.[1][0];
 
        if (detectedAction?.label === optionExecuteBefore) return;
 
        setOptionExecuteBefore(detectedAction?.label || '');
 
        handleActionClick(detectedAction as ActionItemType);
      }
    };
 
    executeAction();
  }, [groupOptionsList, handleActionClick, isLoading, validationItem]);
 
  // Handle input changes and trigger mention detection
  const handleSearchInputChange = (event: ChangeEvent<HTMLInputElement>) => {
    const newValue = event.target.value;
    setSearchQuery(newValue);
    onInputChange?.(newValue);
  };
 
  // Clear input and reset all states
  const handleClearInput = () => {
    setSearchQuery('');
    onClearKeyword();
    searchInputRef.current?.focus();
  };
 
  const streamingMessage = useMemo(
    () =>
      visibleMessages
        .filter(
          (msg) =>
            (msg as TextMessage).role !== 'user' &&
            !!(msg as TextMessage)?.content,
        )
        .slice(-1)
        .map((msg) => ({
          content: formalizeMsgContent(
            (msg as TextMessage)?.content,
            actionItems[0]?.label || '',
          ),
          id: msg.id || '',
        })), // Only get the final message
    [visibleMessages, actionItems],
  );
 
  return (
    <div
      id="search-form"
      onKeyDown={handleKeyDown}
      role="presentation"
      className="w-full"
    >
      <div
        className={combineClasses(
          'flex items-center w-full relative',
          'pr-7 pl-7.5 my-5',
        )}
      >
        <div className="flex-1 relative">
          <div className="relative">
            <input
              ref={searchInputRef}
              role="combobox"
              aria-expanded={true}
              aria-haspopup="listbox"
              aria-controls="search-command-list"
              aria-describedby="search-instructions"
              aria-label="Search pages and navigate using keyboard commands"
              className={combineClasses(
                'flex min-h-[35px] w-full rounded-none border-0 outline-none py-3 p-0',
                'text-xs font-normal placeholder:text-frost-500 bg-transparent',
                'focus-visible:outline-none focus-visible:ring-0 focus-visible:ring-transparent hover:ring-0',
                'relative z-10',
              )}
              placeholder={SEARCH_PLACEHOLDER}
              value={searchQuery}
              onChange={handleSearchInputChange}
            />
          </div>
        </div>
 
        {searchQuery.length > 0 && (
          <Button
            size="icon"
            className={combineClasses(
              'min-w-0 p-0 sm:p-2',
              'bg-transparent hover:bg-transparent',
            )}
            onClick={handleClearInput}
          >
            <CloseIcon
              data-testid="close-icon"
              className="stroke-frost-500 size-4"
            />
          </Button>
        )}
 
        <Button
          data-testid="search-shortcut"
          size="sm"
          aria-hidden="true"
          aria-label="Keyboard shortcut: Esc"
          onClick={onClose}
          className={combineClasses(
            'hidden sm:flex sm:ml-2.5 hover:bg-transparent',
            'flex-center w-15 h-6 rounded-md px-0 min-w-0',
            'bg-white text-frost-900 border border-border-500',
          )}
        >
          Esc
        </Button>
      </div>
 
      {(streamingMessage.length > 0 || isLoading) && (
        <>
          <Separator />
          <div className="pt-2.5 pb-3.5">
            <div className="search-bar-result max-h-modal-content md:max-h-modal-content-md overflow-y-auto small-scrollbar">
              {isLoading ? (
                <ThinkingIndicator />
              ) : (
                streamingMessage.map((msg) => (
                  <ChatbotResponse msg={msg as TextMessage} key={msg.id} />
                ))
              )}
            </div>
          </div>
        </>
      )}
    </div>
  );
};