Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: search by cid #14

Merged
merged 2 commits into from
Sep 24, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 8 additions & 2 deletions frontend/src/app/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import "./globals.css";
import { UploadPopover } from "../components/UploadPopover";
import { Button } from "../components/common/Button";
import { FolderRoot, HelpCircle, Network } from "lucide-react";
import { SearchBar } from "../components/SearchBar";

const geistSans = localFont({
src: "./fonts/GeistVF.woff",
Expand Down Expand Up @@ -33,8 +34,13 @@ export default function RootLayout({
>
<div className="flex h-screen flex-col">
<header className="flex items-center justify-between border-b px-6 py-3">
<div className="flex items-center space-x-4">
<h1 className="text-2xl font-bold">Auto-Drive</h1>
<div className="flex items-center">
<div className="text-center w-[13.5rem]">
<h1 className="text-2xl font-bold">Auto-Drive</h1>
</div>
<div className="w-80">
<SearchBar />
</div>
</div>
<div className="flex items-center space-x-4">
<Button variant="outline">
Expand Down
59 changes: 59 additions & 0 deletions frontend/src/app/search/[cid]/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
'use client'

import { useEffect, useMemo, useState } from "react";
import { ApiService } from "../../../services/api";
import FileCard from "../../../components/common/FileCard";
import { UploadedObjectMetadata } from "../../../models/UploadedObjectMetadata";


export default function Page({ params: { cid } }: { params: { cid: string } }) {

const [objectsMetadata, setObjectsMetadata] = useState<UploadedObjectMetadata[]>();
const [error, setError] = useState<string>();

useEffect(() => {
ApiService.searchHeadCID(cid).then((e) => Promise.all(e.map(e => ApiService.fetchUploadedObjectMetadata(e)))).then(setObjectsMetadata).catch(() => {
setError("Error searching for objects");
});
}, [cid]);


const Content = useMemo(() => {
if (error) {
return <div className="text-center text-red-500 flex flex-col items-center justify-center h-[50%] w-full text-xl">
{error}
</div>
}

if (!objectsMetadata) {
return <div className="text-center text-gray-500 flex flex-col items-center justify-center h-[50%] w-full text-xl"></div>
}

if (objectsMetadata.length === 0) {
return <div className="text-center text-gray-500 flex flex-col items-center justify-center h-[50%] w-full text-xl">
No root objects, upload some!
</div>
}

return objectsMetadata.map(({ metadata, uploadStatus }) => {
switch (metadata.type) {
case "folder":
return <a key={metadata.dataCid} href={`/explorer/${metadata.dataCid}`} className="contents">
<FileCard metadata={metadata} uploadStatus={uploadStatus} />
</a>
case "file":
return <a key={metadata.dataCid} href={`/explorer/${metadata.dataCid}`} className="contents">
<FileCard metadata={metadata} uploadStatus={uploadStatus} />
</a>
}
})
}, [error, objectsMetadata])


marc-aurele-besner marked this conversation as resolved.
Show resolved Hide resolved

return (
<div className="grid grid-cols-4 gap-4">
{Content}
</div>
);
}
131 changes: 131 additions & 0 deletions frontend/src/components/SearchBar/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
'use client'

import { useState, useRef, useEffect, useMemo } from 'react'
import { Transition } from '@headlessui/react'
import { SearchIcon } from 'lucide-react'
import { ApiService } from '../../services/api'

export const SearchBar = () => {
const [query, setQuery] = useState('')
const [isOpen, setIsOpen] = useState(false)
const [error, setError] = useState<string | null>(null)
const inputRef = useRef<HTMLInputElement>(null)
const dropdownRef = useRef<HTMLUListElement>(null)
const [recommendations, setRecommendations] = useState<string[] | null>(null)

useEffect(() => {
if (query.length > 2) {
setError(null)
ApiService.searchHeadCID(query).then(setRecommendations).catch(() => setError('Error fetching recommendations'))
} else {
setRecommendations(null)
}
}, [query])

useEffect(() => {
const handleClickOutside = (event: MouseEvent) => {
if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node) &&
inputRef.current && !inputRef.current.contains(event.target as Node)) {
setIsOpen(false)
}
}

document.addEventListener('mousedown', handleClickOutside)
return () => {
document.removeEventListener('mousedown', handleClickOutside)
}
}, [])

const handleInputChange = (event: React.ChangeEvent<HTMLInputElement>) => {
setQuery(event.target.value)
setIsOpen(true)
}

const handleSelectItem = (item: string) => {
setQuery(item)
setIsOpen(false)
window.location.assign(`/search/${item}`)
inputRef.current?.focus()
}

const handleKeyDown = (event: React.KeyboardEvent<HTMLInputElement>) => {
if (event.key === 'Enter' && recommendations && recommendations.length > 0) {
window.location.assign(`/search/${query}`)
}
}

const searchBarResult = useMemo(() => {
if (query.length === 0 || !recommendations) {
return <></>
}

if (error) {
return <li className="relative cursor-default select-none py-2 px-4 text-red-500">
{error}
</li>
}

if (recommendations && recommendations.length === 0) {
return <li className="relative cursor-default select-none py-2 px-4 text-gray-700">
Nothing found.
</li>
}

return recommendations.map((item) => (
<li
key={item}
className="relative cursor-pointer select-none px-4 py-2 text-gray-900 hover:bg-blue-600 hover:text-white overflow-hidden text-ellipsis font-semibold"
onClick={() => handleSelectItem(item)}
>
{item}
</li>
))
}, [query, recommendations])

return (
<div className="w-full max-w-md mx-auto">
<div className="relative mt-1">
<div className="relative w-full">
<input
ref={inputRef}
type="text"
className="w-full rounded-lg border border-gray-300 bg-white py-2 pl-3 pr-10 text-sm leading-5 text-gray-900 focus:border-blue-500 focus:outline-none focus:ring-1 focus:ring-blue-500"
value={query}
onChange={handleInputChange}
onFocus={() => setIsOpen(true)}
onKeyDown={handleKeyDown}
placeholder="Search..."
/>
<button
type="button"
className="absolute inset-y-0 right-0 flex items-center pr-2"
onClick={() => inputRef.current?.focus()}
>
<SearchIcon
className="h-5 w-5 text-gray-400"
aria-hidden="true"
/>
</button>
</div>
{
<Transition
show={isOpen}
enter="transition ease-out duration-100"
enterFrom="transform opacity-0 scale-95"
enterTo="transform opacity-100 scale-100"
leave="transition ease-in duration-75"
leaveFrom="transform opacity-100 scale-100"
leaveTo="transform opacity-0 scale-95"
>
<ul
ref={dropdownRef}
className="absolute z-10 mt-1 max-h-60 w-full overflow-auto rounded-md bg-white py-1 text-base shadow-lg ring-1 ring-black ring-opacity-5 focus:outline-none sm:text-sm"
>
{searchBarResult}
</ul>
</Transition>
}
</div>
</div>
)
}
4 changes: 4 additions & 0 deletions frontend/src/services/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,4 +73,8 @@ export const ApiService = {
fetchDataURL: (cid: string): string => {
return `${API_BASE_URL}/retrieve/${cid}`;
},
searchHeadCID: async (query: string): Promise<string[]> => {
const response = await fetch(`${API_BASE_URL}/metadata/search/${query}`);
return response.json();
},
};