feat: add user search
This commit is contained in:
@@ -0,0 +1,49 @@
|
|||||||
|
/**
|
||||||
|
* Same-origin proxy for the user-search endpoint.
|
||||||
|
*
|
||||||
|
* Pattern mirrors /api/search (content search) — the browser can't talk
|
||||||
|
* to BFF_URL directly (server-only env var; no NEXT_PUBLIC_ prefix), so
|
||||||
|
* the search page fetches this same-origin route and we proxy through
|
||||||
|
* to /api/v1/users/search server-side. Returned payload is sanitized
|
||||||
|
* by the BFF (handle / name / avatar_url only — no email, role, plan).
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
|
|
||||||
|
const BFF_BASE = process.env.BFF_URL || "http://localhost:8080";
|
||||||
|
|
||||||
|
type EmptyShape = {
|
||||||
|
query: string;
|
||||||
|
results: Array<{ handle: string; name: string; avatar_url: string | null }>;
|
||||||
|
};
|
||||||
|
|
||||||
|
const empty = (q: string): EmptyShape => ({ query: q, results: [] });
|
||||||
|
|
||||||
|
export async function GET(request: NextRequest) {
|
||||||
|
const { searchParams } = request.nextUrl;
|
||||||
|
const q = (searchParams.get("q") || "").trim();
|
||||||
|
const limit = searchParams.get("limit") || "20";
|
||||||
|
|
||||||
|
if (!q) {
|
||||||
|
return NextResponse.json(empty(""));
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const url = new URL("/api/v1/users/search", BFF_BASE);
|
||||||
|
url.searchParams.set("q", q);
|
||||||
|
url.searchParams.set("limit", limit);
|
||||||
|
|
||||||
|
const res = await fetch(url.toString(), {
|
||||||
|
headers: { Accept: "application/json" },
|
||||||
|
});
|
||||||
|
if (!res.ok) {
|
||||||
|
return NextResponse.json(empty(q), { status: res.status });
|
||||||
|
}
|
||||||
|
const data = await res.json();
|
||||||
|
// Unwrap BFF envelope: { data: { query, results } } → { query, results }
|
||||||
|
const payload = data.data ?? data;
|
||||||
|
return NextResponse.json(payload);
|
||||||
|
} catch {
|
||||||
|
return NextResponse.json(empty(q), { status: 502 });
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,6 +2,7 @@
|
|||||||
|
|
||||||
import { useState, useEffect, useCallback, useRef, Suspense } from "react";
|
import { useState, useEffect, useCallback, useRef, Suspense } from "react";
|
||||||
import { useSearchParams, useRouter } from "next/navigation";
|
import { useSearchParams, useRouter } from "next/navigation";
|
||||||
|
import Image from "next/image";
|
||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
import { Input } from "@/components/ui/input";
|
import { Input } from "@/components/ui/input";
|
||||||
import { Badge } from "@/components/ui/badge";
|
import { Badge } from "@/components/ui/badge";
|
||||||
@@ -23,8 +24,24 @@ import {
|
|||||||
ChevronLeft,
|
ChevronLeft,
|
||||||
ChevronRight,
|
ChevronRight,
|
||||||
WholeWord,
|
WholeWord,
|
||||||
|
AtSign,
|
||||||
} from "lucide-react";
|
} from "lucide-react";
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// User search types
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
interface UserResult {
|
||||||
|
handle: string;
|
||||||
|
name: string;
|
||||||
|
avatar_url?: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface UserSearchResponse {
|
||||||
|
query: string;
|
||||||
|
results: UserResult[];
|
||||||
|
}
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
// Types
|
// Types
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
@@ -203,15 +220,33 @@ function SearchInner() {
|
|||||||
const urlTypeParam =
|
const urlTypeParam =
|
||||||
selectedTypes.size === 0 ? "all" : Array.from(selectedTypes).join(",");
|
selectedTypes.size === 0 ? "all" : Array.from(selectedTypes).join(",");
|
||||||
const [data, setData] = useState<SearchResponse | null>(null);
|
const [data, setData] = useState<SearchResponse | null>(null);
|
||||||
|
// Separate state slot for user-search results — keeps the content
|
||||||
|
// search response shape clean and lets the two branches render
|
||||||
|
// entirely different cards without a discriminated-union dance.
|
||||||
|
const [userData, setUserData] = useState<UserSearchResponse | null>(null);
|
||||||
const [isLoading, setIsLoading] = useState(false);
|
const [isLoading, setIsLoading] = useState(false);
|
||||||
|
|
||||||
const debouncedQuery = useDebouncedValue(inputValue, 300);
|
const debouncedQuery = useDebouncedValue(inputValue, 300);
|
||||||
const isQueryEmpty = !debouncedQuery.trim();
|
const isQueryEmpty = !debouncedQuery.trim();
|
||||||
|
|
||||||
|
// User-search mode is driven entirely by the input — when the query
|
||||||
|
// starts with "@" we strip it and hit /api/search/users instead of
|
||||||
|
// the regular content search. The Users chip is a UI shortcut that
|
||||||
|
// toggles the "@" prefix on / off; it never holds independent state.
|
||||||
|
const isUserSearch = debouncedQuery.trimStart().startsWith("@");
|
||||||
|
const userQuery = isUserSearch
|
||||||
|
? debouncedQuery.trimStart().slice(1).trim()
|
||||||
|
: "";
|
||||||
|
const isUserQueryEmpty = isUserSearch && userQuery.length === 0;
|
||||||
|
|
||||||
// When the query is empty, derive these as "no results" during render
|
// When the query is empty, derive these as "no results" during render
|
||||||
// instead of setting state inside an effect.
|
// instead of setting state inside an effect.
|
||||||
const effectiveData = isQueryEmpty ? null : data;
|
const effectiveData =
|
||||||
const hasSearched = isQueryEmpty ? false : !!debouncedQuery.trim();
|
isQueryEmpty || isUserSearch ? null : data;
|
||||||
|
const hasSearched =
|
||||||
|
isUserSearch
|
||||||
|
? !isUserQueryEmpty
|
||||||
|
: !isQueryEmpty;
|
||||||
|
|
||||||
// Sync URL when state changes
|
// Sync URL when state changes
|
||||||
const pushUrl = useCallback(
|
const pushUrl = useCallback(
|
||||||
@@ -244,10 +279,14 @@ function SearchInner() {
|
|||||||
setCurrentPage(1);
|
setCurrentPage(1);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Fetch search results
|
// Fetch search results — branches between user search (`@`-prefixed)
|
||||||
|
// and content search. We clear the *other* state slot on every run
|
||||||
|
// so the UI doesn't show stale results from a previous mode.
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const query = debouncedQuery.trim();
|
const query = debouncedQuery.trim();
|
||||||
if (!query) {
|
|
||||||
|
// Empty query in either mode — push a clean URL and bail.
|
||||||
|
if (!query || isUserQueryEmpty) {
|
||||||
pushUrl("", urlTypeParam, 1, exactMatch);
|
pushUrl("", urlTypeParam, 1, exactMatch);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -257,6 +296,30 @@ function SearchInner() {
|
|||||||
|
|
||||||
const controller = new AbortController();
|
const controller = new AbortController();
|
||||||
|
|
||||||
|
if (isUserSearch) {
|
||||||
|
// User-search branch — strip the @ prefix server-side too.
|
||||||
|
// Clear content data so we don't flash old content results.
|
||||||
|
setData(null);
|
||||||
|
const userParams = new URLSearchParams({ q: userQuery, limit: "20" });
|
||||||
|
fetch(`/api/search/users?${userParams.toString()}`, {
|
||||||
|
signal: controller.signal,
|
||||||
|
})
|
||||||
|
.then((res) => res.json())
|
||||||
|
.then((json: UserSearchResponse) => {
|
||||||
|
setUserData({ ...json, results: json.results ?? [] });
|
||||||
|
setIsLoading(false);
|
||||||
|
})
|
||||||
|
.catch((err) => {
|
||||||
|
if (err.name !== "AbortError") {
|
||||||
|
setIsLoading(false);
|
||||||
|
setUserData({ query: userQuery, results: [] });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
return () => controller.abort();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Content-search branch (unchanged from before — verbatim).
|
||||||
|
setUserData(null);
|
||||||
const params = new URLSearchParams({
|
const params = new URLSearchParams({
|
||||||
q: query,
|
q: query,
|
||||||
type: activeTypeParam,
|
type: activeTypeParam,
|
||||||
@@ -288,13 +351,40 @@ function SearchInner() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
return () => controller.abort();
|
return () => controller.abort();
|
||||||
}, [debouncedQuery, activeTypeParam, urlTypeParam, currentPage, exactMatch, pushUrl]);
|
}, [
|
||||||
|
debouncedQuery,
|
||||||
|
activeTypeParam,
|
||||||
|
urlTypeParam,
|
||||||
|
currentPage,
|
||||||
|
exactMatch,
|
||||||
|
pushUrl,
|
||||||
|
isUserSearch,
|
||||||
|
isUserQueryEmpty,
|
||||||
|
userQuery,
|
||||||
|
]);
|
||||||
|
|
||||||
// Auto-focus the input on mount
|
// Auto-focus the input on mount
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
inputRef.current?.focus();
|
inputRef.current?.focus();
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
|
// Users chip is "active" whenever the live input starts with "@".
|
||||||
|
// Clicking it toggles the prefix on / off — no separate state slot
|
||||||
|
// since the input is already the source of truth.
|
||||||
|
const isUserChipActive = inputValue.trimStart().startsWith("@");
|
||||||
|
const toggleUsersChip = () => {
|
||||||
|
const trimmed = inputValue.trimStart();
|
||||||
|
if (trimmed.startsWith("@")) {
|
||||||
|
// Strip the @ prefix (and the surrounding whitespace it carried).
|
||||||
|
setInputValue(trimmed.slice(1));
|
||||||
|
} else {
|
||||||
|
// Prepend @ — preserves whatever the user has already typed.
|
||||||
|
setInputValue("@" + trimmed);
|
||||||
|
}
|
||||||
|
// Focus the input so the cursor lands ready for typing.
|
||||||
|
inputRef.current?.focus();
|
||||||
|
};
|
||||||
|
|
||||||
const handleTypeChange = (type: string) => {
|
const handleTypeChange = (type: string) => {
|
||||||
if (type === "all") {
|
if (type === "all") {
|
||||||
// "All" clears all individual selections
|
// "All" clears all individual selections
|
||||||
@@ -385,17 +475,53 @@ function SearchInner() {
|
|||||||
|
|
||||||
{/* Content Type Tabs */}
|
{/* Content Type Tabs */}
|
||||||
<div className="mt-5 flex flex-wrap gap-2">
|
<div className="mt-5 flex flex-wrap gap-2">
|
||||||
|
{/* Users chip — toggles the "@" prefix on the input. Sits at
|
||||||
|
the start of the row so its at-sign icon reads as a kind
|
||||||
|
of "search mode" indicator. */}
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={toggleUsersChip}
|
||||||
|
aria-pressed={isUserChipActive}
|
||||||
|
className={cn(
|
||||||
|
"inline-flex items-center gap-1.5 rounded-lg px-3 py-1.5 text-sm font-medium transition-colors",
|
||||||
|
isUserChipActive
|
||||||
|
? "bg-primary text-primary-foreground"
|
||||||
|
: "bg-muted text-muted-foreground hover:bg-muted/80 hover:text-foreground",
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<AtSign className="size-4" />
|
||||||
|
Users
|
||||||
|
{userData &&
|
||||||
|
isUserChipActive &&
|
||||||
|
userData.results.length > 0 && (
|
||||||
|
<span
|
||||||
|
className={cn(
|
||||||
|
"ml-1 inline-flex items-center justify-center rounded-full px-1.5 py-0.5 text-xs font-semibold leading-none",
|
||||||
|
"bg-primary-foreground/20 text-primary-foreground",
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{userData.results.length}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</button>
|
||||||
|
|
||||||
{CONTENT_TABS.map((tab) => {
|
{CONTENT_TABS.map((tab) => {
|
||||||
const active = isTypeActive(tab.value);
|
const active = !isUserChipActive && isTypeActive(tab.value);
|
||||||
return (
|
return (
|
||||||
<button
|
<button
|
||||||
key={tab.value}
|
key={tab.value}
|
||||||
onClick={() => handleTypeChange(tab.value)}
|
onClick={() => handleTypeChange(tab.value)}
|
||||||
|
disabled={isUserChipActive}
|
||||||
className={cn(
|
className={cn(
|
||||||
"inline-flex items-center gap-1.5 rounded-lg px-3 py-1.5 text-sm font-medium transition-colors",
|
"inline-flex items-center gap-1.5 rounded-lg px-3 py-1.5 text-sm font-medium transition-colors",
|
||||||
active
|
active
|
||||||
? "bg-primary text-primary-foreground"
|
? "bg-primary text-primary-foreground"
|
||||||
: "bg-muted text-muted-foreground hover:bg-muted/80 hover:text-foreground",
|
: "bg-muted text-muted-foreground hover:bg-muted/80 hover:text-foreground",
|
||||||
|
// When the @ prefix is on, content tabs don't apply —
|
||||||
|
// grey them out so the chip group reads as "user
|
||||||
|
// mode is exclusive".
|
||||||
|
isUserChipActive &&
|
||||||
|
"opacity-40 cursor-not-allowed hover:bg-muted hover:text-muted-foreground",
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
{tab.label}
|
{tab.label}
|
||||||
@@ -431,8 +557,61 @@ function SearchInner() {
|
|||||||
page doubles as the browsing entry point. */}
|
page doubles as the browsing entry point. */}
|
||||||
{!isLoading && !hasSearched && <KnowledgebaseIndex />}
|
{!isLoading && !hasSearched && <KnowledgebaseIndex />}
|
||||||
|
|
||||||
{/* No results */}
|
{/* User search — empty state (just typed @) */}
|
||||||
|
{!isLoading && isUserSearch && isUserQueryEmpty && (
|
||||||
|
<div className="flex flex-col items-center justify-center py-16 text-center">
|
||||||
|
<AtSign className="size-12 text-muted-foreground/40 mb-4" />
|
||||||
|
<p className="text-lg text-muted-foreground">
|
||||||
|
Searching users
|
||||||
|
<br />
|
||||||
|
<span className="text-sm">
|
||||||
|
Type a name or handle after the “@” to find
|
||||||
|
someone.
|
||||||
|
</span>
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* User search — no matches */}
|
||||||
{!isLoading &&
|
{!isLoading &&
|
||||||
|
isUserSearch &&
|
||||||
|
!isUserQueryEmpty &&
|
||||||
|
userData &&
|
||||||
|
userData.results.length === 0 && (
|
||||||
|
<div className="flex flex-col items-center justify-center py-16 text-center">
|
||||||
|
<AtSign className="size-12 text-muted-foreground/40 mb-4" />
|
||||||
|
<p className="text-lg text-muted-foreground">
|
||||||
|
No users found for “@{userQuery}”.
|
||||||
|
<br />
|
||||||
|
<span className="text-sm">
|
||||||
|
Try a different name or handle.
|
||||||
|
</span>
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* User search — results */}
|
||||||
|
{!isLoading &&
|
||||||
|
isUserSearch &&
|
||||||
|
userData &&
|
||||||
|
userData.results.length > 0 && (
|
||||||
|
<>
|
||||||
|
<p className="mb-4 text-sm text-muted-foreground">
|
||||||
|
{userData.results.length}{" "}
|
||||||
|
{userData.results.length === 1 ? "user" : "users"} matching
|
||||||
|
“@{userQuery}”
|
||||||
|
</p>
|
||||||
|
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
|
||||||
|
{userData.results.map((u) => (
|
||||||
|
<UserResultCard key={u.handle} user={u} />
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Content search — no results */}
|
||||||
|
{!isLoading &&
|
||||||
|
!isUserSearch &&
|
||||||
hasSearched &&
|
hasSearched &&
|
||||||
effectiveData &&
|
effectiveData &&
|
||||||
effectiveData.results.length === 0 && (
|
effectiveData.results.length === 0 && (
|
||||||
@@ -448,8 +627,12 @@ function SearchInner() {
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Results */}
|
{/* Results (content search only — user-search has its own
|
||||||
{!isLoading && effectiveData && effectiveData.results.length > 0 && (
|
block above with avatar-flavoured cards) */}
|
||||||
|
{!isLoading &&
|
||||||
|
!isUserSearch &&
|
||||||
|
effectiveData &&
|
||||||
|
effectiveData.results.length > 0 && (
|
||||||
<>
|
<>
|
||||||
{/* Results count + top pagination */}
|
{/* Results count + top pagination */}
|
||||||
<div className="mb-4 flex items-center justify-between flex-wrap gap-3">
|
<div className="mb-4 flex items-center justify-between flex-wrap gap-3">
|
||||||
@@ -687,6 +870,46 @@ function ResultMeta({ result }: { result: SearchResult }) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// User result card
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
function UserResultCard({ user }: { user: UserResult }) {
|
||||||
|
const initial = user.name?.charAt(0)?.toUpperCase() || "?";
|
||||||
|
return (
|
||||||
|
<Link
|
||||||
|
href={`/u/${user.handle}`}
|
||||||
|
className={cn(
|
||||||
|
"flex items-center gap-3 rounded-xl bg-card ring-1 ring-foreground/10 p-4",
|
||||||
|
"hover:ring-foreground/25 hover:shadow-sm transition-all",
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{user.avatar_url ? (
|
||||||
|
<Image
|
||||||
|
src={user.avatar_url}
|
||||||
|
alt={user.name}
|
||||||
|
width={56}
|
||||||
|
height={56}
|
||||||
|
className="size-14 rounded-full object-cover ring-1 ring-foreground/10 shrink-0"
|
||||||
|
unoptimized
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
|
<div className="size-14 rounded-full bg-primary/15 text-primary flex items-center justify-center text-xl font-semibold ring-1 ring-foreground/10 shrink-0">
|
||||||
|
{initial}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
<div className="min-w-0 flex-1">
|
||||||
|
<p className="text-sm font-semibold text-foreground truncate">
|
||||||
|
{user.name}
|
||||||
|
</p>
|
||||||
|
<p className="text-xs text-muted-foreground truncate">
|
||||||
|
@{user.handle}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</Link>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
// Exported wrapper with Suspense boundary
|
// Exported wrapper with Suspense boundary
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
|
|||||||
+20
-47
@@ -1,55 +1,28 @@
|
|||||||
"use client";
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Public profile — Posts tab (default).
|
* /u/[handle] — public profile, Posts tab (default).
|
||||||
*
|
*
|
||||||
* The /u/[handle] layout owns the ProfileHeader + tab strip + container;
|
* Server shell that exists for two reasons:
|
||||||
* this page only renders the post grid. Tapping a thumbnail jumps to
|
*
|
||||||
* /u/[handle]/posts#post-<id> where the Instagram-style scroll feed
|
* 1. Export `generateMetadata` so direct shares of this URL
|
||||||
* shows the full passages.
|
* (https://prabhupadasays.org/u/<handle>) get a rich OG card
|
||||||
|
* pointing at /api/og/profile/<handle>. The layout and the body
|
||||||
|
* below are client components; only this file is server.
|
||||||
|
* 2. Mount the client tree (<PostsGrid />), which reads the
|
||||||
|
* ProfileContext provided by the parent layout for the post-grid
|
||||||
|
* hrefs and renders the feed.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { use, useEffect, useState } from "react";
|
import type { Metadata } from "next";
|
||||||
import { profile, type Post } from "@/lib/social";
|
import { PostsGrid } from "./posts-grid";
|
||||||
import { PostViews } from "@/components/social/post-views";
|
import { metadataForHandle } from "./profile-og";
|
||||||
import { usePublicProfile } from "./profile-context";
|
|
||||||
|
|
||||||
export default function PublicProfilePostsPage(props: {
|
type Props = { params: Promise<{ handle: string }> };
|
||||||
params: Promise<{ handle: string }>;
|
|
||||||
}) {
|
|
||||||
const { handle } = use(props.params);
|
|
||||||
const data = usePublicProfile();
|
|
||||||
const [feed, setFeed] = useState<Post[]>([]);
|
|
||||||
const [loading, setLoading] = useState(true);
|
|
||||||
|
|
||||||
useEffect(() => {
|
export async function generateMetadata({ params }: Props): Promise<Metadata> {
|
||||||
let cancelled = false;
|
const { handle } = await params;
|
||||||
setLoading(true);
|
return metadataForHandle(handle);
|
||||||
profile
|
}
|
||||||
.feed(handle, 30)
|
|
||||||
.then((rows) => {
|
|
||||||
if (!cancelled) setFeed(rows ?? []);
|
|
||||||
})
|
|
||||||
.catch(() => {
|
|
||||||
// Layout already 404'd if the handle is unknown; if the feed
|
|
||||||
// itself fails we just show an empty grid rather than blocking
|
|
||||||
// the page with an error toast.
|
|
||||||
})
|
|
||||||
.finally(() => !cancelled && setLoading(false));
|
|
||||||
return () => {
|
|
||||||
cancelled = true;
|
|
||||||
};
|
|
||||||
}, [handle]);
|
|
||||||
|
|
||||||
if (loading) {
|
export default function PublicProfilePage({ params }: Props) {
|
||||||
return <p className="text-sm text-muted-foreground">Loading…</p>;
|
return <PostsGrid params={params} />;
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<PostViews
|
|
||||||
posts={feed}
|
|
||||||
hrefFor={(p) => `/u/${data.handle}/posts#post-${p.id}`}
|
|
||||||
emptyMessage="No posts yet — quotes shared by this user will appear here."
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,60 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* PostsGrid — client-side body for /u/[handle] (Posts tab).
|
||||||
|
*
|
||||||
|
* Split out from page.tsx so the page itself can be a server component
|
||||||
|
* that exports `generateMetadata` for the public-profile OG card. The
|
||||||
|
* /u/[handle]/layout.tsx still owns ProfileHeader + tab strip + the
|
||||||
|
* outer max-w-3xl container; this grid just renders the post grid
|
||||||
|
* inside that shell. Tapping a thumbnail jumps to
|
||||||
|
* /u/[handle]/posts#post-<id> where the Instagram-style scroll feed
|
||||||
|
* shows the full passages.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { use, useEffect, useState } from "react";
|
||||||
|
import { profile, type Post } from "@/lib/social";
|
||||||
|
import { PostViews } from "@/components/social/post-views";
|
||||||
|
import { usePublicProfile } from "./profile-context";
|
||||||
|
|
||||||
|
export function PostsGrid({
|
||||||
|
params,
|
||||||
|
}: {
|
||||||
|
params: Promise<{ handle: string }>;
|
||||||
|
}) {
|
||||||
|
const { handle } = use(params);
|
||||||
|
const data = usePublicProfile();
|
||||||
|
const [feed, setFeed] = useState<Post[]>([]);
|
||||||
|
const [loading, setLoading] = useState(true);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
let cancelled = false;
|
||||||
|
setLoading(true);
|
||||||
|
profile
|
||||||
|
.feed(handle, 30)
|
||||||
|
.then((rows) => {
|
||||||
|
if (!cancelled) setFeed(rows ?? []);
|
||||||
|
})
|
||||||
|
.catch(() => {
|
||||||
|
// Layout already 404'd if the handle is unknown; if the feed
|
||||||
|
// itself fails we just show an empty grid rather than blocking
|
||||||
|
// the page with an error toast.
|
||||||
|
})
|
||||||
|
.finally(() => !cancelled && setLoading(false));
|
||||||
|
return () => {
|
||||||
|
cancelled = true;
|
||||||
|
};
|
||||||
|
}, [handle]);
|
||||||
|
|
||||||
|
if (loading) {
|
||||||
|
return <p className="text-sm text-muted-foreground">Loading…</p>;
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<PostViews
|
||||||
|
posts={feed}
|
||||||
|
hrefFor={(p) => `/u/${data.handle}/posts#post-${p.id}`}
|
||||||
|
emptyMessage="No posts yet — quotes shared by this user will appear here."
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,76 +1,28 @@
|
|||||||
"use client";
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* /u/[handle]/posts — public Instagram-style scroll feed.
|
* /u/[handle]/posts — public Instagram-style scroll feed.
|
||||||
*
|
*
|
||||||
* Mirrors /u/me/posts but read-only (no Delete / Update background). The
|
* Server shell so we can export `generateMetadata` for OG previews on
|
||||||
* grid thumbnail on /u/[handle] links here with a `#post-<id>` hash so
|
* direct shares of this URL. We re-use the same profile-OG metadata as
|
||||||
* the feed scrolls to the tapped post on mount.
|
* /u/[handle] — the post anchor (#post-<id>) that may be appended to
|
||||||
|
* the URL is a client-side fragment and never reaches server-rendered
|
||||||
|
* metadata, so we can't surface post-level OG here.
|
||||||
*
|
*
|
||||||
* The parent /u/[handle]/layout owns the ProfileHeader + tab strip + the
|
* (Post-level OG cards still work via the SharePostSheet → short link
|
||||||
* outer max-w-3xl container, so this page only needs the inner scroll
|
* → /share/[code] route, which DOES see the hash and dispatches to
|
||||||
* column. The max-w-xl cap matches /u/me/posts so the column reads at
|
* `ogForPost` in share-og.ts.)
|
||||||
* the same width on desktop; on mobile both pages fall back to viewport
|
|
||||||
* width with the layout-supplied gutters.
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { use, useEffect, useRef, useState } from "react";
|
import type { Metadata } from "next";
|
||||||
import { notFound } from "next/navigation";
|
import { metadataForHandle } from "../profile-og";
|
||||||
import { profile, SocialError, type Post } from "@/lib/social";
|
import { ScrollFeed } from "./scroll-feed";
|
||||||
import { PostScrollCard } from "@/components/social/post-scroll-card";
|
|
||||||
|
|
||||||
export default function PublicPostsFeedPage(props: {
|
type Props = { params: Promise<{ handle: string }> };
|
||||||
params: Promise<{ handle: string }>;
|
|
||||||
}) {
|
|
||||||
const { handle } = use(props.params);
|
|
||||||
const [feed, setFeed] = useState<Post[]>([]);
|
|
||||||
const [loading, setLoading] = useState(true);
|
|
||||||
const [missing, setMissing] = useState(false);
|
|
||||||
const scrolledToHashRef = useRef(false);
|
|
||||||
|
|
||||||
useEffect(() => {
|
export async function generateMetadata({ params }: Props): Promise<Metadata> {
|
||||||
let cancelled = false;
|
const { handle } = await params;
|
||||||
setLoading(true);
|
return metadataForHandle(handle);
|
||||||
profile
|
}
|
||||||
.feed(handle, 60)
|
|
||||||
.then((rows) => {
|
|
||||||
if (cancelled) return;
|
|
||||||
setFeed(rows ?? []);
|
|
||||||
})
|
|
||||||
.catch((err) => {
|
|
||||||
if (err instanceof SocialError && err.status === 404) {
|
|
||||||
setMissing(true);
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.finally(() => !cancelled && setLoading(false));
|
|
||||||
return () => {
|
|
||||||
cancelled = true;
|
|
||||||
};
|
|
||||||
}, [handle]);
|
|
||||||
|
|
||||||
useEffect(() => {
|
export default function PublicPostsFeedPage({ params }: Props) {
|
||||||
if (loading || feed.length === 0 || scrolledToHashRef.current) return;
|
return <ScrollFeed params={params} />;
|
||||||
if (typeof window === "undefined") return;
|
|
||||||
const hash = window.location.hash;
|
|
||||||
if (!hash) return;
|
|
||||||
scrolledToHashRef.current = true;
|
|
||||||
requestAnimationFrame(() => {
|
|
||||||
const el = document.getElementById(hash.slice(1));
|
|
||||||
if (el) el.scrollIntoView({ block: "start", behavior: "auto" });
|
|
||||||
});
|
|
||||||
}, [loading, feed.length]);
|
|
||||||
|
|
||||||
if (missing) notFound();
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="max-w-xl w-full mx-auto space-y-6">
|
|
||||||
{loading ? (
|
|
||||||
<p className="text-sm text-muted-foreground">Loading…</p>
|
|
||||||
) : feed.length === 0 ? (
|
|
||||||
<p className="text-sm text-muted-foreground">No posts yet.</p>
|
|
||||||
) : (
|
|
||||||
feed.map((p) => <PostScrollCard key={p.id} post={p} />)
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,78 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* ScrollFeed — client body for /u/[handle]/posts (public scroll feed).
|
||||||
|
*
|
||||||
|
* Split out from page.tsx so the page itself can be a server component
|
||||||
|
* exporting `generateMetadata` for the OG card. The layout owns the
|
||||||
|
* ProfileHeader + tabs + outer container; this component only renders
|
||||||
|
* the inner scroll column (the Instagram-style feed of full posts).
|
||||||
|
*
|
||||||
|
* Hash-anchor behaviour: when arriving with `#post-<id>`, we scroll to
|
||||||
|
* that post once the feed has loaded. Used by the SharePostSheet flow
|
||||||
|
* — share short URL resolves to /u/<handle>/posts#post-<id>, recipient
|
||||||
|
* lands here, and we scroll to the post that was actually shared.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { use, useEffect, useRef, useState } from "react";
|
||||||
|
import { notFound } from "next/navigation";
|
||||||
|
import { profile, SocialError, type Post } from "@/lib/social";
|
||||||
|
import { PostScrollCard } from "@/components/social/post-scroll-card";
|
||||||
|
|
||||||
|
export function ScrollFeed({
|
||||||
|
params,
|
||||||
|
}: {
|
||||||
|
params: Promise<{ handle: string }>;
|
||||||
|
}) {
|
||||||
|
const { handle } = use(params);
|
||||||
|
const [feed, setFeed] = useState<Post[]>([]);
|
||||||
|
const [loading, setLoading] = useState(true);
|
||||||
|
const [missing, setMissing] = useState(false);
|
||||||
|
const scrolledToHashRef = useRef(false);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
let cancelled = false;
|
||||||
|
setLoading(true);
|
||||||
|
profile
|
||||||
|
.feed(handle, 60)
|
||||||
|
.then((rows) => {
|
||||||
|
if (cancelled) return;
|
||||||
|
setFeed(rows ?? []);
|
||||||
|
})
|
||||||
|
.catch((err) => {
|
||||||
|
if (err instanceof SocialError && err.status === 404) {
|
||||||
|
setMissing(true);
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.finally(() => !cancelled && setLoading(false));
|
||||||
|
return () => {
|
||||||
|
cancelled = true;
|
||||||
|
};
|
||||||
|
}, [handle]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (loading || feed.length === 0 || scrolledToHashRef.current) return;
|
||||||
|
if (typeof window === "undefined") return;
|
||||||
|
const hash = window.location.hash;
|
||||||
|
if (!hash) return;
|
||||||
|
scrolledToHashRef.current = true;
|
||||||
|
requestAnimationFrame(() => {
|
||||||
|
const el = document.getElementById(hash.slice(1));
|
||||||
|
if (el) el.scrollIntoView({ block: "start", behavior: "auto" });
|
||||||
|
});
|
||||||
|
}, [loading, feed.length]);
|
||||||
|
|
||||||
|
if (missing) notFound();
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="max-w-xl w-full mx-auto space-y-6">
|
||||||
|
{loading ? (
|
||||||
|
<p className="text-sm text-muted-foreground">Loading…</p>
|
||||||
|
) : feed.length === 0 ? (
|
||||||
|
<p className="text-sm text-muted-foreground">No posts yet.</p>
|
||||||
|
) : (
|
||||||
|
feed.map((p) => <PostScrollCard key={p.id} post={p} />)
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
/**
|
||||||
|
* Shared `generateMetadata` helper for /u/[handle] routes.
|
||||||
|
*
|
||||||
|
* Both `/u/[handle]/page.tsx` (Posts tab) and `/u/[handle]/posts/page.tsx`
|
||||||
|
* (scroll feed) want the same profile-flavoured OG card on direct URL
|
||||||
|
* shares — the difference between the two is purely the rendered body,
|
||||||
|
* not the social preview. This helper fetches the profile via the
|
||||||
|
* server-side BFF client and hands it to the canonical `ogForProfile`
|
||||||
|
* builder.
|
||||||
|
*
|
||||||
|
* Failures (404 handle, BFF unreachable, malformed payload) fall back
|
||||||
|
* to the site-level `ogDefault` so unfurlers still get a valid card
|
||||||
|
* rather than nothing.
|
||||||
|
*
|
||||||
|
* Note: the page's underlying `app/u/[handle]/layout.tsx` is a client
|
||||||
|
* component and can't export `generateMetadata`. The metadata has to
|
||||||
|
* live on the (server) page that mounts the client tree, which is why
|
||||||
|
* we slim each page.tsx down to a server shell + a separate client
|
||||||
|
* content file.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import type { Metadata } from "next";
|
||||||
|
import { bff } from "@/lib/bff";
|
||||||
|
import { ogDefault, ogForProfile } from "@/lib/og";
|
||||||
|
|
||||||
|
type PublicProfileForOg = {
|
||||||
|
handle: string;
|
||||||
|
name: string;
|
||||||
|
post_count?: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
export async function metadataForHandle(handle: string): Promise<Metadata> {
|
||||||
|
try {
|
||||||
|
const profile = await bff<PublicProfileForOg>(
|
||||||
|
`/u/${encodeURIComponent(handle)}`,
|
||||||
|
{ revalidate: 60 },
|
||||||
|
);
|
||||||
|
if (!profile) return ogDefault();
|
||||||
|
return ogForProfile({
|
||||||
|
handle: profile.handle,
|
||||||
|
name: profile.name,
|
||||||
|
postCount: profile.post_count,
|
||||||
|
});
|
||||||
|
} catch {
|
||||||
|
return ogDefault();
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user