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 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 4x 4x 72x 72x 4x 3x 3x 3x 4x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 6x 6x 6x 6x 6x 6x 72x 72x 72x 70x 70x 11x 11x 11x 11x 11x 11x 70x 70x 72x 72x 6x 6x 6x 6x 72x 2x 2x 2x 2x 72x 72x 58x 58x 58x 9x 9x 58x 58x 58x 72x 72x 72x 72x 72x 72x 72x 72x 72x 58x 53x 51x 72x 59x 59x 59x 59x 68x 68x 59x 72x 72x 72x 1x 1x 1x 1x 1x 1x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 40x 40x 40x 40x 40x 40x 40x 72x 7x 7x 7x 7x 7x 2x 5x 5x 5x 5x 5x 7x 7x 7x 72x 72x | import {
useState,
useRef,
ChangeEvent,
useCallback,
useMemo,
useEffect,
} from 'react';
// Constants
import {
KEYBOARD_EVENT,
SEARCH_PLACEHOLDER,
UserRole,
} 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';
import { SearchSuggestions } from './SearchSuggestions';
// Constants
import { PRIVATE_ROUTES } from '@/constants';
// Providers
import { useAuthContext } from '@/providers';
// Types
import { ActionItemType, ActionKind, UserGroup } from '@shared/types';
// Utils
import { combineClasses } from '@shared/utils';
import { checkPermission, findMatchedRoute, isValidMember } from '@/utils';
import { TextMessage } from '@copilotkit/runtime-client-gql';
// Helper
import {
ChatMessage,
getContextualNavigationSuggestions,
getMessageDisplayContent,
getRedirectPath,
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?: ChatMessage[];
}
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 { user: userProfile } = useAuthContext();
// Only admin, or a user in the chef/kitchen_manager group, sees suggestions
const canSeeSuggestions = isValidMember(
userProfile?.role,
userProfile?.groups,
[UserGroup.CHEF, UserGroup.KITCHEN_MANAGER],
);
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 actionLabel = actionItems[0]?.label || '';
// Keep only the latest message worth displaying
const streamingMessage = useMemo(() => {
const latest = [...visibleMessages]
.reverse()
.map((message) => ({
id: message.id || '',
content: getMessageDisplayContent(message, actionLabel),
}))
.find(({ content }) => content);
return latest?.content ? { id: latest.id, content: latest.content } : null;
}, [visibleMessages, actionLabel]);
// Thinking only when a user message is awaiting a reply.
const hasPendingRequest = useMemo(
() => visibleMessages.some((msg) => msg.role === UserRole.USER),
[visibleMessages],
);
const isThinking = isLoading && hasPendingRequest;
const showSuggestions =
canSeeSuggestions &&
!searchQuery &&
!streamingMessage &&
!isThinking &&
!actionItems.length;
// Hide the suggestion for the page we're already on, replacing it with a
// shortcut to a different page instead
const navigationSuggestions = useMemo(() => {
const suggestions = getContextualNavigationSuggestions(
typeof window === 'undefined' ? undefined : window.location.pathname,
);
// Drop shortcuts to routes the current user is not allowed to open
return suggestions.filter((item) => {
const route = findMatchedRoute(getRedirectPath(item), PRIVATE_ROUTES);
return !route || checkPermission(userProfile, route);
});
}, [userProfile]);
const handleSuggestionSelect = useCallback(
(item: ActionItemType) => {
const query = item.label ?? '';
if (!query) return;
setSearchQuery(query);
onInputChange?.(query);
handleSubmitSearch();
},
[onInputChange, handleSubmitSearch],
);
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>
{showSuggestions && (
<>
<Separator className="opacity-30" />
<SearchSuggestions
suggestions={navigationSuggestions}
onSelect={handleSuggestionSelect}
/>
</>
)}
{(streamingMessage || isThinking) && (
<>
<Separator className="opacity-30" />
<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">
{isThinking ? (
<ThinkingIndicator />
) : (
streamingMessage && (
<ChatbotResponse
msg={streamingMessage as TextMessage}
key={streamingMessage.id}
/>
)
)}
</div>
</div>
</>
)}
</div>
);
};
|