| 34 | > |
| 35 | |
| 36 | function useAutocomplete({ close }: { close: () => void }) { |
| 37 | let id = useId() |
| 38 | let router = useRouter() |
| 39 | let [autocompleteState, setAutocompleteState] = useState< |
| 40 | AutocompleteState<Result> | EmptyObject |
| 41 | >({}) |
| 42 | |
| 43 | function navigate({ itemUrl }: { itemUrl?: string }) { |
| 44 | if (!itemUrl) { |
| 45 | return |
| 46 | } |
| 47 | |
| 48 | const visibleUrl = itemUrl.replace('(docs)/', '') |
| 49 | |
| 50 | router.push(visibleUrl) |
| 51 | |
| 52 | if ( |
| 53 | visibleUrl === |
| 54 | window.location.pathname + window.location.search + window.location.hash |
| 55 | ) { |
| 56 | close() |
| 57 | } |
| 58 | } |
| 59 | |
| 60 | let [autocomplete] = useState<Autocomplete>(() => |
| 61 | createAutocomplete< |
| 62 | Result, |
| 63 | React.SyntheticEvent, |
| 64 | React.MouseEvent, |
| 65 | React.KeyboardEvent |
| 66 | >({ |
| 67 | id, |
| 68 | placeholder: 'Find something...', |
| 69 | defaultActiveItemId: 0, |
| 70 | onStateChange({ state }) { |
| 71 | setAutocompleteState(state) |
| 72 | }, |
| 73 | shouldPanelOpen({ state }) { |
| 74 | return state.query !== '' |
| 75 | }, |
| 76 | navigator: { |
| 77 | navigate, |
| 78 | }, |
| 79 | getSources({ query }) { |
| 80 | return import('@/mdx/search.mjs').then(({ search }) => { |
| 81 | return [ |
| 82 | { |
| 83 | sourceId: 'documentation', |
| 84 | getItems() { |
| 85 | return search(query, { limit: 5 }) |
| 86 | }, |
| 87 | getItemUrl({ item }) { |
| 88 | return item.url |
| 89 | }, |
| 90 | onSelect: navigate, |
| 91 | }, |
| 92 | ] |
| 93 | }) |