-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSearchContent.vue
More file actions
513 lines (456 loc) · 14 KB
/
SearchContent.vue
File metadata and controls
513 lines (456 loc) · 14 KB
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
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
<template>
<UtilitySection
title="Search Content"
description="Search through pages, blog posts, or collections for content matching your search term. Results will highlight exactly where matches were found."
>
<ComingSoon style="padding: 1rem"
>Search <span style="text-transform: uppercase">everything</span></ComingSoon
>
<!-- Search Scope Selection -->
<div class="search-content__scope-selection">
<label class="search-content__scope-label">Search Scope</label>
<div class="search-content__scope-options">
<label class="search-content__radio-option">
<input type="radio" v-model="searchScope" value="pages" :disabled="hasResults" />
<span>Page Type</span>
</label>
<label class="search-content__radio-option">
<input type="radio" v-model="searchScope" value="blog" :disabled="hasResults" />
<span>Blog Posts</span>
</label>
<label class="search-content__radio-option">
<input type="radio" v-model="searchScope" value="collections" :disabled="hasResults" />
<span>Collection</span>
</label>
</div>
</div>
<!-- Conditional inputs based on scope -->
<TextInput
v-if="searchScope === 'pages'"
id="search-content-page-type"
type="text"
:required="true"
placeholder="page_type_1, page_type_2, etc."
v-model="pageType"
>
<template v-slot:label>Page Type</template>
<template v-slot:error v-if="showMissingPageTypeError">Please enter a page type</template>
</TextInput>
<TextInput
v-if="searchScope === 'collections'"
id="search-content-collection-key"
type="text"
placeholder="collection_key_1, collection_key_2, etc."
:required="true"
v-model="collectionKey"
>
<template v-slot:label>Collection Key</template>
<template v-slot:error v-if="showMissingCollectionKeyError"
>Please enter a collection key</template
>
</TextInput>
<!-- Search Term -->
<TextInput
id="search-content-search-term"
type="text"
:required="true"
v-model="searchTerm"
@keypress.enter="executeSearch"
>
<template v-slot:label>Search Term</template>
<template v-slot:error v-if="showMissingSearchTermError">Please enter a search term</template>
</TextInput>
<Btn @click="executeSearch" v-if="!hasResults" :disabled="isLoading">
{{ isLoading ? 'Searching...' : 'Search' }}
</Btn>
<Btn v-if="hasResults || statusMessage" type="reset" status="secondary" @click="resetSearch">
Reset
</Btn>
<InfoBanner v-if="statusMessage" class="status-message" :status="statusType" role="alert">
<p v-if="isLoading" class="search-content__loading-text">{{ statusMessage }}</p>
<div v-else>{{ statusMessage }}</div>
</InfoBanner>
<!-- Results -->
<div v-if="results.length > 0" id="resultsContainer" class="search-content__results-container">
<div class="search-content__summary">
Found <strong>{{ results.length }}</strong>
{{ pluralize(results.length, getScopeItemName(), getScopeItemNamePlural()) }} containing
"<strong>{{ searchTerm }}</strong
>" with <strong>{{ totalMatches }}</strong> total
{{ pluralize(totalMatches, 'match', 'matches') }}
</div>
<div class="results-list">
<div
v-for="(result, index) in results"
:key="index"
v-memo="[result, searchTerm]"
class="search-content__result-item"
>
<div class="search-content__result-header search-content__result-header--desktop">
<div>
<div class="search-content__result-title-wrapper">
<Chip class="search-content__source-badge">{{ getResultSourceBadge(result) }}</Chip>
<span class="search-content__result-title">{{ result.title }}</span>
</div>
<div class="search-content__result-slug">{{ result.slug }}</div>
</div>
<Chip
>{{ getResultMatchCount(result) }}
{{ pluralize(getResultMatchCount(result), 'match', 'matches') }}</Chip
>
</div>
<div class="search-content__matches-list">
<div
v-for="(match, mIndex) in result.matches"
:key="mIndex"
class="search-content__match-item"
>
<div class="search-content__match-path">{{ match.path }}</div>
<div
class="search-content__match-value"
v-html="highlightMatches(match.value, searchTerm)"
></div>
</div>
</div>
</div>
</div>
</div>
<!-- Failed items -->
<div v-if="failedResource" class="search-content__failed-items">
<h4 class="search-content__failed-items-title">⚠️ Failed to retrieve content</h4>
<p>{{ failedError }}</p>
</div>
</UtilitySection>
</template>
<script lang="ts" setup>
import { ref, computed } from 'vue'
import { useStore } from '@/stores/index'
import UtilitySection from '../UtilitySection.vue'
import TextInput from '../TextInput.vue'
import Btn from '../Btn.vue'
import InfoBanner from '../InfoBanner.vue'
import Chip from '../Chip.vue'
import ComingSoon from '../ComingSoon.vue'
import { searchContent } from '@/features/searchContent'
import type { AsyncReturnType } from 'type-fest'
const store = useStore()
const searchScope = ref<'pages' | 'blog' | 'collections'>('pages')
const pageType = ref('')
const collectionKey = ref('')
const searchTerm = ref('')
const showMissingPageTypeError = ref(false)
const showMissingCollectionKeyError = ref(false)
const showMissingSearchTermError = ref(false)
const isLoading = ref(false)
const statusMessage = ref('')
const statusType = ref<'info' | 'success' | 'error' | 'warning'>('info')
const results = ref<AsyncReturnType<typeof searchContent>['results']>([])
const failedResource = ref<string | null>(null)
const failedError = ref<string | null>(null)
const totalItems = ref(0)
const hasResults = computed(() => results.value.length > 0)
// Utility functions
function pluralize(count: number, singular: string, plural: string): string {
return count === 1 ? singular : plural
}
function escapeHtml(str: string): string {
const div = document.createElement('div')
div.textContent = str
return div.innerHTML
}
function highlightMatches(text: string, searchTerm: string): string {
const escapedText = escapeHtml(text)
const escapedSearchTerm = searchTerm.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
const regex = new RegExp(`(${escapedSearchTerm})`, 'gi')
return escapedText.replace(regex, '<mark>$1</mark>')
}
function resetSearch(): void {
results.value = []
failedResource.value = null
failedError.value = null
statusMessage.value = ''
pageType.value = ''
collectionKey.value = ''
searchTerm.value = ''
showMissingPageTypeError.value = false
showMissingCollectionKeyError.value = false
showMissingSearchTermError.value = false
}
function setStatus(
message: string,
type: 'info' | 'success' | 'error' | 'warning' = 'info',
loading = false,
): void {
statusMessage.value = message
statusType.value = type
isLoading.value = loading
}
function getScopeItemName(): string {
switch (searchScope.value) {
case 'pages':
return 'page'
case 'blog':
return 'blog post'
case 'collections':
return 'collection item'
default:
return 'item'
}
}
function getScopeItemNamePlural(): string {
switch (searchScope.value) {
case 'pages':
return 'pages'
case 'blog':
return 'blog posts'
case 'collections':
return 'collection items'
default:
return 'items'
}
}
function getResultSourceBadge(
result: AsyncReturnType<typeof searchContent>['results'][number],
): string {
if (searchScope.value === 'pages' && result.sourceType) {
return `Page (${result.sourceType})`
} else if (searchScope.value === 'collections' && result.sourceType) {
return `Collection (${result.sourceType})`
} else if (searchScope.value === 'blog') {
return 'Blog'
}
return 'Unknown'
}
function parseCommaSeparatedInput(input: string): string[] {
return input
.split(',')
.map((item) => item.trim())
.filter((item) => item.length > 0)
}
// Main search execution
async function executeSearch(): Promise<void> {
const token = store.token
const searchTermValue = searchTerm.value.trim()
results.value = []
failedResource.value = null
failedError.value = null
statusMessage.value = ''
if (!token) {
setStatus('Please enter your API token', 'error')
return
}
showMissingSearchTermError.value = !searchTerm.value
showMissingPageTypeError.value = searchScope.value === 'pages' && !pageType.value
showMissingCollectionKeyError.value = searchScope.value === 'collections' && !collectionKey.value
if (
showMissingSearchTermError.value ||
showMissingPageTypeError.value ||
showMissingCollectionKeyError.value
)
return
isLoading.value = true
setStatus('Searching...', 'info', true)
try {
const pageTypesArray =
searchScope.value === 'pages' ? parseCommaSeparatedInput(pageType.value) : undefined
const collectionKeysArray =
searchScope.value === 'collections'
? parseCommaSeparatedInput(collectionKey.value)
: undefined
const searchResponse = await searchContent(
searchScope.value,
searchTermValue,
token,
store.includePreview,
pageTypesArray,
collectionKeysArray,
)
if (!searchResponse.success) {
failedResource.value = searchResponse.error!
failedError.value = searchResponse.error!
setStatus(searchResponse.error!, 'error')
return
}
totalItems.value = searchResponse.totalItems!
if (searchResponse.results.length === 0) {
setStatus(
`No matches found for "${searchTermValue}" in ${searchResponse.totalItems} ${pluralize(searchResponse.totalItems!, getScopeItemName(), getScopeItemNamePlural())}`,
'info',
false,
)
} else {
setStatus(
`Found ${searchResponse.results.length} ${pluralize(searchResponse.results.length, getScopeItemName(), getScopeItemNamePlural())} with matches out of ${searchResponse.totalItems} total ${pluralize(searchResponse.totalItems!, getScopeItemName(), getScopeItemNamePlural())}`,
'success',
false,
)
results.value = searchResponse.results
}
} catch (error) {
setStatus(`Error: ${(error as Error).message}`, 'error')
} finally {
isLoading.value = false
}
}
const totalMatches = computed(() => {
return results.value.reduce((sum, r) => {
return sum + r.matches.reduce((matchSum, m) => matchSum + (m.count || 1), 0)
}, 0)
})
function getResultMatchCount(
result: AsyncReturnType<typeof searchContent>['results'][number],
): number {
return result.matches.reduce((sum, m) => sum + (m.count || 1), 0)
}
</script>
<style lang="scss" scoped>
.search-content {
// Scope selection
&__scope-selection {
margin-bottom: 1rem;
}
&__scope-label {
display: block;
font-weight: 500;
margin-bottom: 0.5rem;
color: var(--text-primary);
font-size: 0.9375rem;
}
&__scope-options {
display: flex;
gap: 1.5rem;
flex-wrap: wrap;
}
&__radio-option {
display: flex;
align-items: center;
gap: 0.5rem;
cursor: pointer;
font-size: 0.9375rem;
input[type='radio'] {
cursor: pointer;
}
&--disabled {
opacity: 0.5;
cursor: not-allowed;
input[type='radio'] {
cursor: not-allowed;
}
}
}
// Source badge
&__source-badge {
font-size: 0.75rem;
padding: 0.125rem 0.5rem;
}
&__result-title-wrapper {
display: flex;
align-items: center;
gap: 0.5rem;
flex-wrap: wrap;
}
// Loading text
&__loading-text {
font-weight: 500;
color: var(--text-secondary);
}
// Summary section
&__summary {
background-color: white;
border: 1px solid var(--butter-border);
border-radius: 6px;
padding: 1rem;
font-weight: 500;
position: sticky;
top: 0;
z-index: 10;
}
// Result item
&__result-item {
background-color: var(--butter-light-gray);
border: 1px solid var(--butter-border);
border-radius: 6px;
padding: 1.25rem;
margin-bottom: 1rem;
}
// Result header
&__result-header {
display: flex;
flex-direction: column;
gap: 1rem;
margin-bottom: 0.75rem;
&--desktop {
@media (min-width: 769px) {
flex-direction: row;
justify-content: space-between;
align-items: start;
}
}
}
// Result title
&__result-title {
font-weight: 600;
color: var(--butter-dark);
font-size: 1rem;
}
// Result slug
&__result-slug {
color: var(--text-secondary);
font-size: 0.875rem;
font-family: 'Courier New', monospace;
margin-top: 0.25rem;
}
// Matches list
&__matches-list {
margin-top: 0.75rem;
}
// Match item
&__match-item {
background-color: white;
border-left: 3px solid var(--butter-yellow);
padding: 0.75rem;
margin-bottom: 0.5rem;
border-radius: 4px;
line-height: 1.4;
}
// Match path
&__match-path {
color: var(--butter-gray);
font-size: 0.8125rem;
font-family: 'Courier New', monospace;
margin-bottom: 0.25rem;
}
// Match value
&__match-value {
color: var(--text-primary);
font-size: 0.9375rem;
word-break: break-word;
:deep(mark) {
background-color: var(--butter-yellow);
color: var(--butter-dark);
padding: 0.125rem 0.25rem;
border-radius: 2px;
font-weight: 600;
}
}
// Failed items section
&__failed-items {
background-color: #fef3f2;
border: 1px solid #fda29b;
border-radius: 6px;
padding: 1rem;
margin-top: 1.5rem;
}
&__failed-items-title {
color: var(--error);
font-size: 1rem;
margin-top: 0;
margin-bottom: 0.5rem;
font-weight: 600;
}
&__failed-items-list {
margin-left: 1.5rem;
color: #b42318;
}
}
</style>