-
Notifications
You must be signed in to change notification settings - Fork 21
/
AllPostsList.tsx
188 lines (159 loc) · 5.16 KB
/
AllPostsList.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
import type { CollectionEntry } from 'astro:content'
import React from 'react'
import { TagReact } from '../icons/TagReact'
import { inflect } from '../utils'
import { Input } from './Inputs'
import { ShiftBy } from './ShiftBy'
function getFilteredPosts(posts: CollectionEntry<'posts'>[], search: string) {
if (!search) return posts
return posts.filter(post => {
const allText = `
${post.data?.title}
${post.data?.subtitle}
${post.data?.description}
${post.data?.excerpt}
${post.data?.tags?.join(' ')}
`.toLowerCase()
return allText.toLowerCase().includes(search.toLowerCase())
})
}
export function AllPostsList({ posts }: { posts: CollectionEntry<'posts'>[] }) {
const [search, setSearch] = React.useState(() => {
if (typeof window === 'undefined') return ''
return new URLSearchParams(window.location.search).get('search') || ''
})
const handleSearchChange = React.useCallback((value: string) => {
setSearch(value)
const params = new URLSearchParams(window.location.search)
if (value) {
params.set('search', value)
} else {
params.delete('search')
}
const paramStr = params.toString() ? `?${params.toString()}` : ''
window.history.replaceState(
{},
'',
`${window.location.pathname}${paramStr}`,
)
}, [])
const filteredPosts = getFilteredPosts(posts, search)
return (
<div className="stack gap-4">
<Input
variant="block"
label="Search posts"
helperText="Search by title or tags"
value={search}
onChange={e => handleSearchChange(e.target.value)}
placeholder="Search posts"
/>
{filteredPosts.length > 0 ? (
<div className="stack gap-2">
<div className="text-sm text-gray-700 dark:text-gray-200">
Displaying {filteredPosts.length}{' '}
{inflect('post')(filteredPosts.length)}
</div>
<div className="-ml-4 flex flex-col">
{filteredPosts.map(post => {
const { subtitle, title } = post.data
return (
<a
key={post.slug}
className="stack block gap-2 p-4 transition-colors hover:bg-gray-100 dark:hover:bg-gray-800"
href={`/${post.slug}`}
>
<div className="font-sans text-accent">
<HighlightedHTML
html={title}
search={search}
className="text-2xl"
/>
{subtitle && (
<HighlightedHTML
html={subtitle}
search={search}
className="font-bold"
/>
)}
</div>
<HighlightedHTML
html={post.data.description || post.data.excerpt || ''}
search={search}
className="text-gray-700 dark:text-gray-200"
/>
{post.data.tags?.length && (
<div className="flex items-center gap-4 pt-2 font-sans">
<span className="text-gray-300">
<ShiftBy y={2}>
<TagReact />
</ShiftBy>
</span>
{post.data.tags.map((tag: string) => (
<HighlightedHTML key={tag} html={tag} search={search} />
))}
</div>
)}
</a>
)
})}
</div>
</div>
) : (
<div>No posts found</div>
)}
</div>
)
}
const highlightHTML = (html: string, search: string): string => {
if (!search?.trim() || !html) return html
// Escape special characters in search term
const escapedSearch = search.trim().replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
// Create a temporary container
const tempDiv = document.createElement('div')
tempDiv.innerHTML = html
// Function to highlight text in a node
const highlightTextNode = (textNode: Text) => {
const regex = new RegExp(`(${escapedSearch})`, 'gi')
const text = textNode.textContent || ''
if (!regex.test(text)) return
const wrapper = document.createElement('span')
wrapper.innerHTML = text.replace(
regex,
'<mark class="bg-yellow-300 px-0.5">$1</mark>',
)
textNode.parentNode?.replaceChild(wrapper, textNode)
}
// Recursive function to process all text nodes
const processNode = (node: Node) => {
if (node.nodeType === Node.TEXT_NODE) {
highlightTextNode(node as Text)
return
}
const children = Array.from(node.childNodes)
children.forEach(processNode)
}
// Process all nodes
processNode(tempDiv)
return tempDiv.innerHTML
}
function HighlightedHTML({
html,
search,
className,
}: {
html: string
search: string
className?: string
}) {
const highlightedContent = React.useMemo(
() => highlightHTML(html, search),
[html, search],
)
return (
<div
className={className}
dangerouslySetInnerHTML={{ __html: highlightedContent }}
/>
)
}