-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathsearch.tsx
301 lines (263 loc) · 7.93 KB
/
search.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
import algoliasearch from 'algoliasearch/lite';
import { renderToString } from 'react-dom/server';
import {
Configure,
Highlight,
Hits,
InstantSearch,
InstantSearchServerState,
InstantSearchSSRProvider,
Pagination,
SearchBox,
useInstantSearch,
} from 'react-instantsearch';
import useSWR from 'swr';
import type { Hit as AlgoliaHit } from 'instantsearch.js';
import { history } from 'instantsearch.js/es/lib/routers/index.js';
import { GetServerSidePropsContext, GetServerSidePropsResult } from 'next';
import { getServerState } from 'react-instantsearch-core';
import Link from 'next/link';
import { useState } from 'react';
import { Userdata, useUserdata } from 'src/auth';
import GeneralLayout from 'src/layouts/general';
import style from 'src/search/search.module.css';
import clear from 'public/assets/illustrations/clear.svg';
import ButtonBlob from 'src/components/buttonBlobLink';
import useDebounce from 'src/utils/use-debounce';
import Button from 'src/components/button';
import Head from 'next/head';
const appId = process.env.NEXT_PUBLIC_ALGOLIA_APP_ID || '';
const apiKey = process.env.NEXT_PUBLIC_ALGOLIA_READ_KEY || '';
const searchClient = algoliasearch(appId, apiKey);
const SEARCH_HITS_PER_PAGE = 8;
type SearchPageProps = {
serverState?: InstantSearchServerState;
url?: string;
};
export default function Search(props: SearchPageProps) {
const userInfo = useUserdata();
const searchQuery = encodeURIComponent(
props.serverState?.initialResults.handbook_content.state.query ?? '',
);
const firstResultPotential = (
props.serverState?.initialResults.handbook_content.results[0]?.hits[0]
?.content ?? 'Ikke funnet'
).substring(0, 255);
console.log('Dsadsa\n\n\\n\n\n\n', firstResultPotential, '\n\n\\n\n\n\n');
return (
<GeneralLayout toc={[]} frontmatter={{ title: 'Søk' }} noSidebar>
<Head>
<meta
property="og:image"
content={`https://handbook.variant.no/api/og-search?query=${searchQuery}`}
key="og-image"
/>
<meta property="og:url" content={props.url} key="og-url" />
<meta
property="og:description"
content={`Søkeresultat: ${firstResultPotential}`}
key="og-desc"
/>
</Head>
<CloseSearch />
<h2 className={style.header}>Hva leter du etter?</h2>
<SearchPage {...props} userInfo={userInfo} />
</GeneralLayout>
);
}
type HitProps = {
hit: AlgoliaHit<{
slug: string;
urlPath: string;
title: string;
content: string;
}>;
};
function Hit({ hit }: HitProps) {
return (
<article className={style.searchItem}>
<h3>
<Link href={`${hit.urlPath}#${hit.slug}`}>
<Highlight attribute="title" hit={hit} />
</Link>
</h3>
<Highlight attribute="content" hit={hit} />
</article>
);
}
type SearchPagePropsWithUser = SearchPageProps & {
userInfo?: Userdata;
};
function SearchPage(props: SearchPagePropsWithUser) {
const { serverState, url } = props;
return (
<InstantSearchSSRProvider {...serverState}>
<InstantSearch
searchClient={searchClient}
indexName="handbook_content"
routing={{
router: history({
getLocation() {
if (typeof window === 'undefined') {
return new URL(url!) as unknown as Location;
}
return window.location;
},
}),
}}
>
<Configure hitsPerPage={SEARCH_HITS_PER_PAGE} />
<div>
<SearchBox autoFocus placeholder="Søk eller still spørsmål..." />
<div className={style.searchDivider} />
<RecentSearches />
</div>
<ChatGPTResults />
<Hits hitComponent={Hit} />
<HandleNoHits />
<Pagination />
</InstantSearch>
</InstantSearchSSRProvider>
);
}
const fetcher = (url: string) => fetch(url).then((r) => r.json());
function ChatGPTResults() {
const { indexUiState } = useInstantSearch();
const [hidden, setHidden] = useState(true);
const debouncedQuery = useDebounce(indexUiState.query);
const { data, isLoading } = useSWR<{ result: string[] }>(
() =>
debouncedQuery && !hidden ? `/api/chat?query=${debouncedQuery}` : null,
fetcher,
);
let buttonText = hidden ? 'Vis' : 'Skjul';
if (isLoading) {
buttonText = 'Laster...';
}
const header = (
<header>
<span className={style.beta__pill}>beta</span>
<div className={style.chatResult__title}>
<h3>GPT-svar*</h3>
<small className={style.chatResult__notice}>
(*bruk av GPT sender søketeksten din til OpenAI)
</small>
</div>
<div className={style.chatResult__button}>
<Button
onClick={() => setHidden((h) => !h)}
aria-expanded={!hidden}
aria-controls="gpt-result"
>
{buttonText}
</Button>
</div>
</header>
);
if (!indexUiState.query) {
return null;
}
if (hidden) {
return <aside className={style.chatResult}>{header}</aside>;
}
const result =
data?.result?.join('...') ?? 'Beep boop. Fant ingen resultater...';
return (
<aside className={style.chatResult}>
{header}
<div
className={style.chatResult__result}
role="region"
id="gpt-result"
aria-busy={isLoading}
aria-describedby="progress-bar"
>
{isLoading ? (
<div className={style.chatResult__loading}>
<progress id="progress-bar" aria-label="Laster..."></progress>
<p>Henter svar...</p>
</div>
) : (
<p>{result}</p>
)}
<hr />
<em className={style.chatResult__nb}>
OBS: Dette er i prøvefase og svaret kan i mange tilfeller ikke være
komplett eller korrekt. Verifiser alltid med håndboken direkte om det
er noe kritisk.
</em>
</div>
</aside>
);
}
function CloseSearch() {
return (
<div className={style.closeSearchContainer}>
<div className={style.closeSearch}>
<ButtonBlob
imgName={clear}
buttonText={'Lukk'}
altText={'Lukk illustrasjon'}
href={'/'}
height={15}
width={15}
/>
</div>
</div>
);
}
function RecentSearches() {
const { indexUiState, setIndexUiState } = useInstantSearch();
const recentSearches: any[] = [
{ label: 'Lønn', color: 'var(--color-primary__tint4)' },
{ label: 'Aksjer', color: 'var(--color-secondary1__tint4)' },
{ label: 'Fordeler', color: 'var(--color-secondary2__tint4)' },
{ label: 'Miljøfyrtårn', color: 'var(--color-secondary3__tint4)' },
];
if (!indexUiState.query)
return (
<div className={style.recentSearchesContainer}>
<h3 className={style.subHeader}>Andre har søkt etter</h3>
<div className={style.recentSearchChipsContainer}>
{recentSearches.map((search, index) => (
<button
type="button"
key={index}
style={{ backgroundColor: search.color, cursor: 'pointer' }}
className={style.recentSearchChip}
onClick={() => {
setIndexUiState({ query: search.label });
}}
>
{search.label}
</button>
))}
</div>
</div>
);
return null;
}
function HandleNoHits() {
const { results } = useInstantSearch();
if (results.nbHits > 0) return null;
return (
<div className={style.noHits}>🔎 Ingen direkte søkeresultater funnet.</div>
);
}
export async function getServerSideProps({
req,
}: GetServerSidePropsContext): Promise<
GetServerSidePropsResult<SearchPageProps>
> {
const protocol = req.headers.referer?.split('://')[0] || 'https';
const url = `${protocol}://${req.headers.host}${req.url}`;
const serverState = await getServerState(<SearchPage url={url} />, {
renderToString,
});
return {
props: {
serverState,
url,
},
};
}