import axios from 'axios' import AwesomeDebouncePromise from 'awesome-debounce-promise' import { useAsync } from 'react-async-hook' import useConstant from 'use-constant' import { Dispatch, FC, Fragment, SetStateAction, useState } from 'react' import { Dialog, Transition } from '@headlessui/react' import Link from 'next/link' import Image from 'next/image' import { FontAwesomeIcon } from '@fortawesome/react-fontawesome' import { OdSearchResult } from '../types' import { getFileIcon } from '../utils/getFileIcon' import siteConfig from '../config/site.json' import { LoadingIcon } from './Loading' function useDriveItemSearch() { const [query, setQuery] = useState('') const searchDriveItem = async (q: string) => { const { data } = await axios.get(`/api/search?q=${q}`) // Extract the searched item's path and convert it to the absolute path in onedrive-vercel-index function mapAbsolutePath(path: string): string { return siteConfig.baseDirectory === '/' ? path.split('root:')[1] : path.split(siteConfig.baseDirectory)[1] } // Map parentReference to the absolute path of the search result data.map(item => { item['path'] = `${mapAbsolutePath(item.parentReference.path)}/${encodeURIComponent(item.name)}` }) return data } const debouncedNotionSearch = useConstant(() => AwesomeDebouncePromise(searchDriveItem, 1000)) const results = useAsync(async () => { if (query.length === 0) { return [] } else { return debouncedNotionSearch(query) } }, [query]) return { query, setQuery, results, } } function SearchModal({ searchOpen, setSearchOpen, }: { searchOpen: boolean setSearchOpen: Dispatch> }) { const closeSearchBox = () => setSearchOpen(false) const { query, setQuery, results } = useDriveItemSearch() return (
setQuery(e.target.value)} />
ESC
{results.loading && (
Loading ...
)} {results.error && (
Error: {results.error.message}
)} {results.result && ( <> {results.result.length === 0 ? (
Nothing here.
) : ( results.result.map(result => (
{result.name}
{decodeURIComponent(result.path)}
)) )} )}
) } export default SearchModal