|
| 1 | +/** |
| 2 | + * Copyright (c) 2022 Gitpod GmbH. All rights reserved. |
| 3 | + * Licensed under the GNU Affero General Public License (AGPL). |
| 4 | + * See License-AGPL.txt in the project root for license information. |
| 5 | + */ |
| 6 | + |
| 7 | +import { User } from "@gitpod/gitpod-protocol"; |
| 8 | +import React, { useContext, useState } from "react"; |
| 9 | +import { getGitpodService } from "../service/service"; |
| 10 | +import { UserContext } from "../user-context"; |
| 11 | + |
| 12 | +type SearchResult = string; |
| 13 | +type SearchData = SearchResult[]; |
| 14 | + |
| 15 | +const LOCAL_STORAGE_KEY = 'open-in-gitpod-search-data'; |
| 16 | +const MAX_DISPLAYED_ITEMS = 20; |
| 17 | + |
| 18 | +export default function RepositoryFinder(props: { initialQuery?: string }) { |
| 19 | + const { user } = useContext(UserContext); |
| 20 | + const [searchQuery, setSearchQuery] = useState<string>(props.initialQuery || ''); |
| 21 | + const [searchResults, setSearchResults] = useState<SearchResult[]>([]); |
| 22 | + const [selectedSearchResult, setSelectedSearchResult] = useState<SearchResult | undefined>(); |
| 23 | + |
| 24 | + const onResults = (results: SearchResult[]) => { |
| 25 | + if (JSON.stringify(results) !== JSON.stringify(searchResults)) { |
| 26 | + setSearchResults(results); |
| 27 | + setSelectedSearchResult(results[0]); |
| 28 | + } |
| 29 | + } |
| 30 | + |
| 31 | + const search = async (query: string) => { |
| 32 | + setSearchQuery(query); |
| 33 | + await findResults(query, onResults); |
| 34 | + if (await refreshSearchData(query, user)) { |
| 35 | + // Re-run search if the underlying search data has changed |
| 36 | + await findResults(query, onResults); |
| 37 | + } |
| 38 | + } |
| 39 | + |
| 40 | + // Up/Down keyboard navigation between results |
| 41 | + const onKeyDown = (event: React.KeyboardEvent) => { |
| 42 | + if (!selectedSearchResult) { |
| 43 | + return; |
| 44 | + } |
| 45 | + const selectedIndex = searchResults.indexOf(selectedSearchResult); |
| 46 | + const select = (index: number) => { |
| 47 | + // Implement a true modulus in order to "wrap around" (e.g. `select(-1)` should select the last result) |
| 48 | + // Source: https://stackoverflow.com/a/4467559/3461173 |
| 49 | + const n = Math.min(searchResults.length, MAX_DISPLAYED_ITEMS); |
| 50 | + setSelectedSearchResult(searchResults[((index % n) + n) % n]); |
| 51 | + } |
| 52 | + if (event.key === 'ArrowDown') { |
| 53 | + event.preventDefault(); |
| 54 | + select(selectedIndex + 1); |
| 55 | + return; |
| 56 | + } |
| 57 | + if (event.key === 'ArrowUp') { |
| 58 | + event.preventDefault(); |
| 59 | + select(selectedIndex - 1); |
| 60 | + return; |
| 61 | + } |
| 62 | + } |
| 63 | + |
| 64 | + const onSubmit = (event: React.FormEvent) => { |
| 65 | + event.preventDefault(); |
| 66 | + if (selectedSearchResult) { |
| 67 | + window.location.href = '/#' + selectedSearchResult; |
| 68 | + } |
| 69 | + } |
| 70 | + |
| 71 | + return <form onSubmit={onSubmit}> |
| 72 | + <div className="flex px-4 rounded-xl border border-gray-300 dark:border-gray-500"> |
| 73 | + <div className="py-4"> |
| 74 | + <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 16 16" width="16" height="16"><path fill="#A8A29E" d="M6 2a4 4 0 100 8 4 4 0 000-8zM0 6a6 6 0 1110.89 3.477l4.817 4.816a1 1 0 01-1.414 1.414l-4.816-4.816A6 6 0 010 6z" /></svg> |
| 75 | + </div> |
| 76 | + <input type="search" className="flex-grow" placeholder="Repository" autoFocus value={searchQuery} onChange={e => search(e.target.value)} onKeyDown={onKeyDown} /> |
| 77 | + </div> |
| 78 | + <div className="rounded-xl bg-gray-50 dark:bg-gray-800 flex flex-col" id="search-results"> |
| 79 | + {searchResults.slice(0, MAX_DISPLAYED_ITEMS).map((result, index) => |
| 80 | + <a className={`px-4 py-2 rounded-xl` + (result === selectedSearchResult ? ' bg-gray-100 dark:bg-gray-700' : '')} href={`/#${result}`} key={`search-result-${index}`}> |
| 81 | + {result.split(searchQuery).map((segment, index) => <span> |
| 82 | + {index === 0 ? <></> : <strong>{searchQuery}</strong>} |
| 83 | + {segment} |
| 84 | + </span>)} |
| 85 | + </a> |
| 86 | + )} |
| 87 | + {searchResults.length > MAX_DISPLAYED_ITEMS && |
| 88 | + <span className="px-4 py-2 italic text-sm">{searchResults.length - MAX_DISPLAYED_ITEMS} results not shown</span>} |
| 89 | + </div> |
| 90 | + </form>; |
| 91 | +} |
| 92 | + |
| 93 | +function loadSearchData(): SearchData { |
| 94 | + const string = localStorage.getItem(LOCAL_STORAGE_KEY); |
| 95 | + if (!string) { |
| 96 | + return []; |
| 97 | + } |
| 98 | + try { |
| 99 | + const data = JSON.parse(string); |
| 100 | + return data; |
| 101 | + } catch (error) { |
| 102 | + console.warn('Could not load search data from local storage', error); |
| 103 | + return []; |
| 104 | + } |
| 105 | +} |
| 106 | + |
| 107 | +function saveSearchData(searchData: SearchData): void { |
| 108 | + try { |
| 109 | + window.localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(searchData)); |
| 110 | + } catch (error) { |
| 111 | + console.warn('Could not save search data into local storage', error); |
| 112 | + } |
| 113 | +} |
| 114 | + |
| 115 | +let refreshSearchDataPromise: Promise<boolean> | undefined; |
| 116 | +export async function refreshSearchData(query: string, user: User | undefined): Promise<boolean> { |
| 117 | + if (refreshSearchDataPromise) { |
| 118 | + // Another refresh is already in progress, no need to run another one in parallel. |
| 119 | + return refreshSearchDataPromise; |
| 120 | + } |
| 121 | + refreshSearchDataPromise = actuallyRefreshSearchData(query, user); |
| 122 | + const didChange = await refreshSearchDataPromise; |
| 123 | + refreshSearchDataPromise = undefined; |
| 124 | + return didChange; |
| 125 | +} |
| 126 | + |
| 127 | +// Fetch all possible search results and cache them into local storage |
| 128 | +async function actuallyRefreshSearchData(query: string, user: User | undefined): Promise<boolean> { |
| 129 | + console.log('refreshing search data'); |
| 130 | + const oldData = loadSearchData(); |
| 131 | + const newData = await getGitpodService().server.getSuggestedContextURLs(); |
| 132 | + if (JSON.stringify(oldData) !== JSON.stringify(newData)) { |
| 133 | + console.log('new data:', newData); |
| 134 | + saveSearchData(newData); |
| 135 | + return true; |
| 136 | + } |
| 137 | + return false; |
| 138 | +} |
| 139 | + |
| 140 | +async function findResults(query: string, onResults: (results: string[]) => void) { |
| 141 | + const searchData = loadSearchData(); |
| 142 | + try { |
| 143 | + // If the query is a URL, and it's not present in the proposed results, "artificially" add it here. |
| 144 | + new URL(query); |
| 145 | + if (!searchData.includes(query)) { |
| 146 | + searchData.push(query); |
| 147 | + } |
| 148 | + } catch { |
| 149 | + } |
| 150 | + // console.log('searching', query, 'in', searchData); |
| 151 | + onResults(searchData.filter(result => result.includes(query))); |
| 152 | +} |
0 commit comments