Refactor roadmap search and suggestions

feat/ai-autocomplete
Kamran Ahmed 8 months ago
parent 4855d28144
commit 603ff23acf
  1. 39
      src/components/GenerateRoadmap/AITermSuggestionInput.tsx
  2. 24
      src/components/GenerateRoadmap/GenerateRoadmap.tsx
  3. 25
      src/components/GenerateRoadmap/RoadmapSearch.tsx

@ -1,16 +1,15 @@
import {
type InputHTMLAttributes,
useEffect,
useMemo,
useRef,
useState,
type InputHTMLAttributes,
} from 'react';
import { cn } from '../../lib/classname';
import { useOutsideClick } from '../../hooks/use-outside-click';
import { useDebounceValue } from '../../hooks/use-debounce';
import { httpGet } from '../../lib/http';
import { useToast } from '../../hooks/use-toast';
import { Loader2 } from 'lucide-react';
import { Spinner } from '../ReactIcons/Spinner.tsx';
import type { PageType } from '../CommandMenu/CommandMenu.tsx';
@ -24,7 +23,7 @@ type GetTopAIRoadmapTermResponse = {
type AITermSuggestionInputProps = {
value: string;
onValueChange: (value: string) => void;
onSelect?: (roadmapId: string) => void;
onSelect?: (roadmapId: string, roadmapTitle: string) => void;
inputClassName?: string;
wrapperClassName?: string;
placeholder?: string;
@ -62,7 +61,7 @@ export function AITermSuggestionInput(props: AITermSuggestionInputProps) {
useState<GetTopAIRoadmapTermResponse>([]);
const [searchedText, setSearchedText] = useState(defaultValue);
const [activeCounter, setActiveCounter] = useState(0);
const debouncedSearchValue = useDebounceValue(searchedText, 500);
const debouncedSearchValue = useDebounceValue(searchedText, 300);
const loadTopAIRoadmapTerm = async () => {
const trimmedValue = debouncedSearchValue.trim();
@ -133,16 +132,21 @@ export function AITermSuggestionInput(props: AITermSuggestionInputProps) {
setIsActive(true);
setIsLoading(true);
loadTopAIRoadmapTerm().then((results) => {
loadTopAIRoadmapTerm()
.then((results) => {
const normalizedSearchText = debouncedSearchValue.trim().toLowerCase();
const matchingOfficialRoadmaps = officialRoadmaps.filter((roadmap) => {
return roadmap.title.toLowerCase().indexOf(normalizedSearchText) !== -1;
return (
roadmap.title.toLowerCase().indexOf(normalizedSearchText) !== -1
);
});
setSearchResults(
[...matchingOfficialRoadmaps, ...results]?.slice(0, 5) || [],
);
setActiveCounter(0);
})
.finally(() => {
setIsLoading(false);
});
}, [debouncedSearchValue]);
@ -158,6 +162,8 @@ export function AITermSuggestionInput(props: AITermSuggestionInputProps) {
setIsActive(false);
});
const isFinishedTyping = debouncedSearchValue === searchedText;
return (
<div className={cn('relative', wrapperClassName)}>
<input
@ -196,21 +202,23 @@ export function AITermSuggestionInput(props: AITermSuggestionInputProps) {
setSearchedText('');
setIsActive(false);
} else if (e.key === 'Enter') {
if (searchResults.length > 0) {
if (!searchResults.length || !isFinishedTyping) {
return;
}
e.preventDefault();
const activeData = searchResults[activeCounter];
if (activeData) {
if (activeData.isOfficial) {
window.location.href = `/${activeData._id}`;
window.open(`/${activeData._id}`, '_blank')?.focus();
return;
}
onValueChange(activeData.term);
onSelect?.(activeData._id);
onSelect?.(activeData._id, activeData.title);
setIsActive(false);
}
}
}
}}
/>
@ -223,9 +231,12 @@ export function AITermSuggestionInput(props: AITermSuggestionInputProps) {
</div>
)}
{isActive && searchResults.length > 0 && searchedText.length > 0 && (
{isActive &&
isFinishedTyping &&
searchResults.length > 0 &&
searchedText.length > 0 && (
<div
className="absolute top-full z-50 mt-1 w-full rounded-md border bg-white px-2 py-2 shadow"
className="absolute top-full z-50 mt-1 w-full rounded-md border bg-white p-1 shadow"
ref={dropdownRef}
>
<div className="flex flex-col">
@ -246,7 +257,7 @@ export function AITermSuggestionInput(props: AITermSuggestionInputProps) {
}
onValueChange(result?.term);
onSelect?.(result._id);
onSelect?.(result._id, result.title);
setSearchedText('');
setIsActive(false);
}}
@ -259,7 +270,7 @@ export function AITermSuggestionInput(props: AITermSuggestionInputProps) {
: 'bg-blue-400 text-blue-50',
)}
>
{result.isOfficial ? 'Official' : 'Generated'}
{result.isOfficial ? 'Official' : 'AI Generated'}
</span>
{result?.title || result?.term}
</button>

@ -37,6 +37,7 @@ import { AIRoadmapAlert } from './AIRoadmapAlert.tsx';
import { OpenAISettings } from './OpenAISettings.tsx';
import { IS_KEY_ONLY_ROADMAP_GENERATION } from '../../lib/ai.ts';
import { AITermSuggestionInput } from './AITermSuggestionInput.tsx';
import { useParams } from '../../hooks/use-params.ts';
export type GetAIRoadmapLimitResponse = {
used: number;
@ -91,6 +92,7 @@ export function GenerateRoadmap() {
const [hasSubmitted, setHasSubmitted] = useState<boolean>(false);
const [isLoading, setIsLoading] = useState(false);
const [isLoadingResults, setIsLoadingResults] = useState(false);
const [roadmapTerm, setRoadmapTerm] = useState('');
const [generatedRoadmapContent, setGeneratedRoadmapContent] = useState('');
const [currentRoadmap, setCurrentRoadmap] =
@ -194,7 +196,7 @@ export function GenerateRoadmap() {
const handleSubmit = async (e: FormEvent<HTMLFormElement>) => {
e.preventDefault();
if (!roadmapTerm) {
if (!roadmapTerm || isLoadingResults) {
return;
}
@ -481,7 +483,7 @@ export function GenerateRoadmap() {
>
{roadmapLimitUsed} of {roadmapLimit}
</span>{' '}
roadmaps generated.
roadmaps generated today.
</span>
{!openAPIKey && (
<button
@ -523,8 +525,8 @@ export function GenerateRoadmap() {
onValueChange={(value) => setRoadmapTerm(value)}
placeholder="e.g. Try searching for Ansible or DevOps"
wrapperClassName="grow"
onSelect={(id) => {
setUrlParams({ id });
onSelect={(id, title) => {
loadTermRoadmap(title).finally(() => null);
}}
/>
<button
@ -540,14 +542,22 @@ export function GenerateRoadmap() {
}
}}
disabled={
isAuthenticatedUser &&
isLoadingResults ||
(isAuthenticatedUser &&
(!roadmapLimit ||
!roadmapTerm ||
roadmapLimitUsed >= roadmapLimit ||
roadmapTerm === currentRoadmap?.term ||
(isKeyOnly && !openAPIKey))
(isKeyOnly && !openAPIKey)))
}
>
{isLoadingResults && (
<>
<span>Please wait..</span>
</>
)}
{!isLoadingResults && (
<>
{!isAuthenticatedUser && (
<>
<Wand size={20} />
@ -574,6 +584,8 @@ export function GenerateRoadmap() {
)}
</>
)}
</>
)}
</button>
</form>
<div className="flex w-full items-center justify-between gap-2">

@ -1,12 +1,11 @@
import { ArrowUpRight, Ban, Cog, Telescope, Wand } from 'lucide-react';
import type { FormEvent } from 'react';
import { useEffect, useState } from 'react';
import { getOpenAIKey, isLoggedIn } from '../../lib/jwt';
import { showLoginPopup } from '../../lib/popup';
import { cn } from '../../lib/classname.ts';
import { useEffect, useState } from 'react';
import { OpenAISettings } from './OpenAISettings.tsx';
import { AITermSuggestionInput } from './AITermSuggestionInput.tsx';
import { setUrlParams } from '../../lib/browser.ts';
type RoadmapSearchProps = {
roadmapTerm: string;
@ -35,11 +34,12 @@ export function RoadmapSearch(props: RoadmapSearchProps) {
const [isConfiguring, setIsConfiguring] = useState(false);
const [openAPIKey, setOpenAPIKey] = useState('');
const [isAuthenticatedUser, setIsAuthenticatedUser] = useState(false);
const [isLoadingResults, setIsLoadingResults] = useState(false);
useEffect(() => {
setOpenAPIKey(getOpenAIKey() || '');
setIsAuthenticatedUser(isLoggedIn());
}, [getOpenAIKey(), isLoggedIn()]);
}, []);
const randomTerms = ['OAuth', 'APIs', 'UX Design', 'gRPC'];
@ -84,8 +84,8 @@ export function RoadmapSearch(props: RoadmapSearchProps) {
onValueChange={(value) => setRoadmapTerm(value)}
placeholder="Enter a topic to generate a roadmap for"
wrapperClassName="w-full"
onSelect={(roadmapId) => {
setUrlParams({ id: roadmapId });
onSelect={(roadmapId, roadmapTitle) => {
onLoadTerm(roadmapTitle);
}}
/>
<button
@ -100,13 +100,22 @@ export function RoadmapSearch(props: RoadmapSearchProps) {
}
}}
disabled={
isAuthenticatedUser &&
isLoadingResults ||
(isAuthenticatedUser &&
(!limit ||
!roadmapTerm ||
limitUsed >= limit ||
(isKeyOnly && !openAPIKey))
(isKeyOnly && !openAPIKey)))
}
>
{isLoadingResults && (
<>
<span>Please wait..</span>
</>
)}
{!isLoadingResults && (
<>
{!isAuthenticatedUser && (
<>
<Wand size={20} />
@ -130,6 +139,8 @@ export function RoadmapSearch(props: RoadmapSearchProps) {
)}
</>
)}
</>
)}
</button>
</form>
<div className="flex flex-row flex-wrap items-center justify-center gap-2">

Loading…
Cancel
Save