-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathSearch.tsx
More file actions
191 lines (166 loc) · 5.1 KB
/
Search.tsx
File metadata and controls
191 lines (166 loc) · 5.1 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
"use client";
import { useState, useEffect } from "react";
import { TagList } from "./TagList";
import styles from "./Search.module.scss";
import { ProjectCard, TextInput } from "@/components";
export interface Tag {
id: string;
label: string;
lucideIcon: string;
borderColor: string;
backgroundColor: string;
}
export interface Project {
id: string;
title: string;
description: string;
author: string;
tags: string[];
previewImageUrl?: string;
githubUrl: string;
liveUrl?: string;
}
interface SearchProps {
tags: Tag[];
}
export function Search({ tags }: SearchProps) {
const [selectedTagIds, setSelectedTagIds] = useState<string[]>([]);
const [searchText, setSearchText] = useState("");
const [projects, setProjects] = useState<Project[]>([]);
const [page, setPage] = useState(1);
const [hasMore, setHasMore] = useState(true);
const [isLoadingMore, setIsLoadingMore] = useState(false);
const fetchProjects = async (pageToFetch = 1, reset = false) => {
if (isLoadingMore || (!hasMore && !reset)) return;
if (reset) setProjects([]);
setIsLoadingMore(true);
await new Promise((resolve) => setTimeout(resolve, 500));
const params = new URLSearchParams();
params.set("page", pageToFetch.toString());
params.set("pageSize", "20");
if (searchText.trim()) params.set("search", searchText);
if (selectedTagIds.length > 0) {
selectedTagIds.forEach((tag) => params.append("tags", tag));
}
try {
const res = await fetch(`/api/projects?${params.toString()}`);
const data = await res.json();
setProjects((prev) =>
pageToFetch === 1 || reset
? (data.results ?? [])
: [...prev, ...(data.results ?? [])]
);
setHasMore((data.results?.length ?? 0) >= 20);
setPage(pageToFetch);
} catch (err) {
console.error("Failed to load projects", err);
} finally {
setIsLoadingMore(false);
}
};
useEffect(() => {
window.scrollTo({ top: 0, behavior: "smooth" });
setPage(1);
setHasMore(true);
fetchProjects(1, true);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [selectedTagIds, searchText]);
useEffect(() => {
const handleScroll = () => {
const nearBottom =
window.innerHeight + window.scrollY >= document.body.offsetHeight - 200;
if (nearBottom && hasMore && !isLoadingMore) {
fetchProjects(page + 1);
}
};
window.addEventListener("scroll", handleScroll);
return () => window.removeEventListener("scroll", handleScroll);
}, [page, hasMore, isLoadingMore]);
const onTagClick = (tag: Tag) => {
setSelectedTagIds((prev) =>
prev.includes(tag.id)
? prev.filter((id) => id !== tag.id)
: [...prev, tag.id]
);
};
const clearSelectedTags = () => setSelectedTagIds([]);
const unSelectTag = (tagId: string) =>
setSelectedTagIds((prev) => prev.filter((id) => id !== tagId));
const SelectionMarkup = selectedTagIds.length > 0 && (
<div className={styles.activeFilters}>
<span className={styles.activeFiltersLabel}>Active filters:</span>
<div className={styles.selectedTags}>
{selectedTagIds
.map((id) => tags.find((tag) => tag.id === id))
.filter(Boolean)
.map((tag) => (
<span
key={tag!.id}
className={styles.selectedTag}
onClick={() => unSelectTag(tag!.id)}
>
<strong>{tag!.label}</strong> <span className={styles.x}>×</span>
</span>
))}
</div>
<div>
<button className={styles.button} onClick={() => clearSelectedTags()}>
Clear filters
</button>
</div>
</div>
);
const SpinnerMarkup = (
<div style={{ textAlign: "center", marginTop: "1rem", width: "100%" }}>
<div className={styles.spinner}></div>
</div>
);
const NoResultsMarkup = (
<div className={styles.noResults}>
<h2>No Projects Found 🔍</h2>
<p>Try adjusting your search or removing some filters.</p>
</div>
);
const ProjectsMarkup = (
<div className={styles.projectList}>
{projects.map((p, i) => (
<div key={`project-${i}`}>
<ProjectCard
title={p.title}
description={p.description}
previewImageUrl={p.previewImageUrl}
githubUrl={p.githubUrl}
liveUrl={p.liveUrl}
tags={p.tags}
author={p.author}
/>
</div>
))}
</div>
);
return (
<div className={styles.search}>
<div className={styles.searchInner}>
<TextInput
value={searchText}
onChange={(e) => setSearchText(e.target.value)}
/>
<br />
<TagList
tags={tags}
onTagClick={onTagClick}
selectedTagIds={selectedTagIds}
/>
{SelectionMarkup}
<div className={styles.space} />
{isLoadingMore && SpinnerMarkup}
{!isLoadingMore &&
(projects.length === 0 ? (
<>{NoResultsMarkup}</>
) : (
<>{ProjectsMarkup}</>
))}
</div>
</div>
);
}