-
-
Notifications
You must be signed in to change notification settings - Fork 169
Expand file tree
/
Copy path_client.tsx
More file actions
281 lines (254 loc) · 9.89 KB
/
Copy path_client.tsx
File metadata and controls
281 lines (254 loc) · 9.89 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
"use client";
import { Fragment, useEffect } from "react";
import { useInView } from "react-intersection-observer";
import { useSearchParams, useRouter } from "next/navigation";
import { api } from "@/server/trpc/react";
import { useSession } from "next-auth/react";
import {
FeedItemLoading,
FeedFilters,
OnboardingBanner,
} from "@/components/Feed";
import { UnifiedContentCard } from "@/components/UnifiedContentCard";
import { type RouterOutputs } from "@/server/trpc/shared";
import {
deriveFeedInput,
type FeedSort,
type FeedContentType,
} from "./feedQuery";
type FeedFirstPage = RouterOutputs["content"]["getFeed"];
type SortOption = FeedSort;
type ContentType = FeedContentType;
const FeedPage = ({ initialFeed }: { initialFeed?: FeedFirstPage | null }) => {
const searchParams = useSearchParams();
const router = useRouter();
const { data: session } = useSession();
// Same derivation the server page uses to SSR the first feed page — the
// inputs must match for initialFeed to attach to this query.
const { sort, type, category, tag, following, limit } = deriveFeedInput(
{
sort: searchParams?.get("sort"),
category: searchParams?.get("category"),
tag: searchParams?.get("tag"),
type: searchParams?.get("type"),
view: searchParams?.get("view"),
},
!!session?.user,
);
// Fetch feed data with infinite scroll using the unified content API. The
// server-fetched first page renders in the crawlable HTML; the client query
// refetches per its normal staleness rules afterwards.
const { status, data, isFetchingNextPage, fetchNextPage, hasNextPage } =
api.content.getFeed.useInfiniteQuery(
{
limit,
sort,
type,
category,
tag,
following,
},
{
getNextPageParam: (lastPage) => lastPage.nextCursor,
...(initialFeed
? { initialData: { pages: [initialFeed], pageParams: [null] } }
: {}),
},
);
// Popular tags power the "Topic" filter pill.
const { data: popularTags } = api.tag.getPopular.useQuery({ limit: 8 });
const topics = (popularTags?.data ?? []).flatMap((t) =>
t.slug ? [{ slug: t.slug, title: t.title }] : [],
);
// Intersection observer for infinite scroll
const { ref, inView } = useInView();
useEffect(() => {
if (inView && hasNextPage) {
fetchNextPage();
}
}, [inView, hasNextPage, fetchNextPage]);
// Handle filter changes. Each handler keeps the other active filters
// (and the For-you/Following view) intact while writing clean URL params.
const pushFilters = (next: {
sort?: SortOption;
type?: ContentType;
category?: string | null;
tag?: string | null;
}) => {
const nextSort = next.sort ?? sort;
const nextType = next.type !== undefined ? next.type : type;
const nextCategory = next.category !== undefined ? next.category : category;
const nextTag = next.tag !== undefined ? next.tag : tag;
const params = new URLSearchParams();
if (following) params.set("view", "following");
if (nextSort !== "recent") params.set("sort", nextSort);
// Lowercase in URL params for cleaner URLs.
if (nextType) params.set("type", nextType.toLowerCase());
if (nextCategory) params.set("category", nextCategory);
if (nextTag) params.set("tag", nextTag);
const queryString = params.toString();
router.push(`/${queryString ? `?${queryString}` : ""}`);
};
const handleSortChange = (newSort: SortOption) =>
pushFilters({ sort: newSort });
const handleTagChange = (newTag: string | null) =>
pushFilters({ tag: newTag });
const handleTypeChange = (newType: ContentType) =>
pushFilters({ type: newType });
const handleClearFilters = () => {
const params = new URLSearchParams();
if (following) params.set("view", "following");
const queryString = params.toString();
router.push(`/${queryString ? `?${queryString}` : ""}`);
};
const filterCluster = (
<FeedFilters
sort={sort}
type={type}
tag={tag}
topics={topics}
onSortChange={handleSortChange}
onTypeChange={handleTypeChange}
onTagChange={handleTagChange}
onClear={handleClearFilters}
showTypeFilter={true}
/>
);
return (
<div>
{/* For you / Following tabs (signed-in) with the flat filter cluster
pushed to the right of the same row. Signed-out users get the
filters in a matching row without the tabs. The feed opens straight
into this row (no page heading). */}
{session?.user ? (
<div className="flex flex-wrap items-center gap-x-7 gap-y-2 border-b border-hairline">
{[
{ label: "For you", href: "/", active: !following },
{
label: "Following",
href: "/?view=following",
active: following,
},
].map((t) => (
<button
key={t.label}
type="button"
onClick={() => router.push(t.href)}
aria-current={t.active ? "page" : undefined}
className={`-mb-px border-b-2 pb-2.5 text-sm font-semibold transition-colors ${
t.active
? "border-accent text-fg"
: "border-transparent text-muted hover:text-fg"
}`}
>
{t.label}
</button>
))}
{/* Mobile: filters drop to their own full-width row below the tabs
instead of cramming under them. Desktop: inline, pushed right.
No overflow clip here — it would hide the FilterPill popovers. */}
<div className="order-last flex w-full justify-end pt-1 min-[640px]:order-none min-[640px]:ml-auto min-[640px]:w-auto min-[640px]:pl-4 min-[640px]:pt-0">
{filterCluster}
</div>
</div>
) : (
<div className="flex items-center border-b border-hairline pb-2">
<div className="ml-auto">{filterCluster}</div>
</div>
)}
{/* First-run onboarding nudge (signed-in). Posting now lives behind the
single "+ Create" entry point in the top bar. */}
{session?.user && (
<div className="mt-4">
<OnboardingBanner />
</div>
)}
{/* Feed list (rails now live in the global app shell) */}
<div className="mt-5">
<div className="relative">
<section className="space-y-3">
{following &&
status === "success" &&
data.pages.every((p) => p.items.length === 0) && (
<div className="mt-4 rounded-xl border border-dashed border-hairline p-10 text-center">
<p className="font-medium text-fg">
Your Following feed is empty.
</p>
<p className="mt-1 text-sm text-muted">
Follow builders and sources to see their posts here.
</p>
</div>
)}
{status === "error" && (
<div className="mt-8 rounded-lg border border-hairline bg-surface p-4 text-sm text-danger">
Something went wrong loading the feed. Please refresh the page.
</div>
)}
{status === "pending" &&
Array.from({ length: 7 }, (_, i) => <FeedItemLoading key={i} />)}
{status === "success" &&
data.pages.map((page, pageIndex) => (
<Fragment key={pageIndex}>
{page.items.map((item) => (
<UnifiedContentCard
key={item.id}
type={item.type as "POST" | "LINK"}
kind={item.type}
id={item.id}
title={item.title}
excerpt={item.excerpt}
slug={item.slug}
urlId={item.urlId}
imageUrl={item.imageUrl || item.ogImageUrl}
externalUrl={item.externalUrl}
publishedAt={item.publishedAt}
readTimeMins={item.readTimeMins}
upvotes={item.upvotes}
downvotes={item.downvotes}
userVote={item.userVote}
isBookmarked={item.isBookmarked}
author={
item.userId && item.authorName && !item.sourceId
? {
name: item.authorName,
username: item.authorUsername || "",
image: item.authorImage,
}
: null
}
source={
item.sourceId && item.sourceName
? {
name: item.sourceName,
slug: item.sourceSlug,
logo: item.sourceLogo,
websiteUrl: item.sourceWebsite,
}
: null
}
linkAuthor={item.sourceAuthor}
/>
))}
</Fragment>
))}
{status === "success" && !data.pages[0].items.length && (
<div className="mt-8 rounded-lg border border-dashed border-hairline bg-surface p-8 text-center">
<h2 className="font-display text-lg font-bold text-fg">
No content yet
</h2>
<p className="mt-2 text-sm text-muted">
Check back soon for curated developer content.
</p>
</div>
)}
{isFetchingNextPage && <FeedItemLoading />}
<span className="invisible" ref={ref}>
intersection observer marker
</span>
</section>
</div>
</div>
</div>
);
};
export default FeedPage;