All files / src/components/SearchBarWithAI index.tsx

99.35% Statements 153/154
96.29% Branches 26/27
100% Functions 7/7
99.35% Lines 153/154

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  1x 1x         1x     1x 1x             1x               1x     1x     1x 1x   1x 7x 7x 7x 7x 7x 7x                         7x 7x 7x 7x 6x 7x 2x 2x   7x   5x 1x 1x   5x 3x 3x 5x   7x     7x 1x 1x   6x 6x                 1x 44x 44x 44x   44x 44x 44x 44x         44x 44x 44x 44x 44x 44x 44x 44x 44x 44x 44x 44x 44x 2x 2x 2x 2x   2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x   2x 44x     44x 21x 2x 2x 1x   2x 1x 1x 1x 2x   21x 21x 21x 44x   44x 6x 44x   44x 1x 1x       44x 1x   1x 1x 1x 1x 1x       44x   44x 2x 2x 44x   44x 1x 1x 44x   44x 44x 2x 1x 1x   2x 2x 44x 44x     44x 1x 1x 1x 44x   44x 44x 44x 44x 44x 44x 44x 44x 44x 44x 44x 44x   44x   44x 44x 44x 44x 44x 44x 44x 44x 44x 44x 44x 44x   44x  
// Libs
import { useCallback, useEffect, useRef, useState } from 'react';
import {
  useCopilotAction,
  useCopilotChat,
  useCopilotMessagesContext,
} from '@copilotkit/react-core';
import { Role, TextMessage } from '@copilotkit/runtime-client-gql';
 
// Constants
import { KEYBOARD_EVENT, KEYBOARD_SHORTCUT } from '@shared/constants';
import { KITCHEN_SEARCH_ACTIONS_PROMPT } from '@/constants';
 
// Hooks
import { useBreakpoint } from '@shared/hooks';
import { ArgsType } from '@/hooks/chat/useChatbotActions';
 
// Types
import {
  ACTION_HANDLER_STATUS,
  ActionHandler,
  ActionItemType,
  GetToken,
} from '@shared/types';
 
// UIs
import { CustomDialog } from '@shared/ui';
 
// Utils
import { combineClasses } from '@shared/utils';
 
// Components
import { SearchTrigger } from '../SearchTrigger';
import { SearchForm } from '../SearchForm';
 
export const AwaitAndResponse = ({
  result = {},
  status,
  isProcessing,
  onProcessing,
  onComplete,
}: {
  args: Partial<ArgsType>;
  result: {
    action?: string;
    project?: string;
    user?: string;
    group?: string;
    error?: string;
  };
  status: ActionHandler;
  isProcessing: boolean;
  onProcessing: (value: boolean) => void;
  onComplete?: () => void;
}) => {
  useEffect(() => {
    if (
      status === ACTION_HANDLER_STATUS.INPROGRESS ||
      status === ACTION_HANDLER_STATUS.EXECUTING
    ) {
      onProcessing(true);
    }
 
    if (status === ACTION_HANDLER_STATUS.COMPLETE) {
      // Only update once after the action is complete
      if (isProcessing) {
        onProcessing(false);
      }
 
      if (result?.action) {
        onComplete?.();
      }
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [status, result]);
 
  /** Show one error issue from agent only, to avoid duplicate error */
  if (result?.error) {
    return <></>;
  }
 
  return <>{JSON.stringify(result)}</>;
};
 
export interface SearchBarProps {
  requestConfig?: {
    token: string;
    userEmail: string;
  };
}
 
export const SearchBar = ({ requestConfig }: SearchBarProps) => {
  const [isSearchOpen, setIsSearchOpen] = useState(false);
  const [isActionLoading, setIsActionLoading] = useState(false);
  const [actionItems, setActionItems] = useState<ActionItemType[]>([]);
 
  const queryRef = useRef('');
  const { messages, setMessages: setContextMessages } =
    useCopilotMessagesContext();
  const { appendMessage, isLoading: isAILoading, reset } = useCopilotChat();
 
  /**
   * MAIN ACTION TO RECOGNIZE AND EXTRACT KEY INFO FROM MESSAGE
   */
  useCopilotAction({
    name: KITCHEN_SEARCH_ACTIONS_PROMPT.key,
    description: KITCHEN_SEARCH_ACTIONS_PROMPT.description,
    parameters: [
      {
        name: 'rawMessage',
        type: 'string',
        description: 'Capture entire message',
        required: true,
      },
    ],
    available: 'disabled',
    renderAndWaitForResponse: ({ args, result, status }) => {
      const formalizedResult = {
        ...result,
        group: result?.group?.toLowerCase(),
      };
 
      return (
        <AwaitAndResponse
          args={args}
          result={formalizedResult}
          status={status}
          isProcessing={isActionLoading}
          onProcessing={setIsActionLoading}
          onComplete={() => {
            setActionItems([formalizedResult]);
          }}
        />
      );
    },
  });
 
  // keyboard shortcut to open
  useEffect(() => {
    const handleKeyDown = (event: KeyboardEvent) => {
      const isSearchShortcut =
        (event.metaKey || event.ctrlKey) &&
        event.key.toLowerCase() === KEYBOARD_SHORTCUT.SEARCH.toLowerCase();
 
      if (isSearchShortcut) {
        event.preventDefault();
        setIsSearchOpen(true);
      }
    };
 
    window.addEventListener(KEYBOARD_EVENT.KEYDOWN, handleKeyDown);
    return () =>
      window.removeEventListener(KEYBOARD_EVENT.KEYDOWN, handleKeyDown);
  }, []);
 
  const handleOpenSearchModal = useCallback(() => {
    setIsSearchOpen(true);
  }, []);
 
  const handleCloseAutoFocus = (event: Event) => {
    event.preventDefault();
  };
 
  // Controlled onOpenChange handler provided to the dialog.
  // It's crucial this uses the boolean `open` argument correctly.
  const handleDialogOpenChange = useCallback((open: boolean) => {
    if (!open) {
      // closing
      queryRef.current = '';
      setActionItems([]);
      setIsSearchOpen(false);
      return;
    }
 
    // opening
    setIsSearchOpen(true);
  }, []);
 
  const handleResetSearchBot = useCallback(() => {
    reset();
    setContextMessages([]);
  }, [reset, setContextMessages]);
 
  const handleCloseSearchModal = useCallback(() => {
    setIsSearchOpen(false);
    handleResetSearchBot();
  }, [handleResetSearchBot]);
 
  const handleInputChange = useCallback(
    (value: string) => {
      if (messages.length) {
        handleResetSearchBot();
      }
 
      queryRef.current = value;
    },
    [handleResetSearchBot, messages.length],
  );
 
  // Handle append message
  const handleSubmitSearch = useCallback(() => {
    appendMessage(
      new TextMessage({ content: queryRef.current, role: Role.User }),
    );
  }, [appendMessage]);
 
  return (
    <CustomDialog
      data-testid="search-dialog"
      className={combineClasses('p-0 translate-y-0 top-[10%] md:top-[30%]')}
      hideCloseButton
      onOpenChange={handleDialogOpenChange}
      open={isSearchOpen}
      trigger={
        <SearchTrigger
          isSearchOpen={isSearchOpen}
          handleOpenSearchModal={handleOpenSearchModal}
        />
      }
      onCloseAutoFocus={handleCloseAutoFocus}
    >
      <SearchForm
        onClearKeyword={handleResetSearchBot}
        onResetResult={() => setActionItems([])}
        actionItems={actionItems}
        onClose={handleCloseSearchModal}
        isLoading={isAILoading}
        onInputChange={handleInputChange}
        requestConfig={requestConfig}
        onSubmitSearch={handleSubmitSearch}
        visibleMessages={messages}
      />
    </CustomDialog>
  );
};