feat: add policy pages

This commit is contained in:
gosangam
2026-06-02 01:57:08 +05:30
parent 0352cb2003
commit 91d5d272d2
168 changed files with 1326 additions and 81 deletions
+27
View File
@@ -0,0 +1,27 @@
"use client";
/**
* /u/[handle]/collections — public collections for a profile.
*
* The list comes from the layout's profile fetch (`public_collections`),
* so this page only has to decide between the empty state and the grid.
* Layout owns the ProfileHeader + tabs + container.
*/
import { CollectionViews } from "@/components/social/collection-views";
import { usePublicProfile } from "../profile-context";
export default function PublicProfileCollectionsPage() {
const data = usePublicProfile();
const list = data.public_collections ?? [];
if (list.length === 0) {
return (
<p className="text-sm text-muted-foreground">
No public collections yet.
</p>
);
}
return <CollectionViews collections={list} hrefFor={(c) => `/c/${c.id}`} />;
}
+135
View File
@@ -0,0 +1,135 @@
"use client";
/**
* /u/[handle] shared layout — public profile shell.
*
* Mirrors /u/me's layout so visitors see the same ProfileHeader + tab
* strip whether they're on the grid (`/u/<h>`) or the scroll feed
* (`/u/<h>/posts`). Without this layout, /u/<h>/posts rendered a bare
* `<main>` with extra padding — visually disconnected from /u/<h> and
* narrower than expected on mobile.
*
* Profile data is fetched once here and exposed via PublicProfileContext
* so child pages (which need `public_collections`, etc.) don't refetch.
*
* If the logged-in user lands on their own /u/<handle>, redirect to
* /u/me — preserving the `/posts` sub-path when present.
*/
import { use, useEffect, useState } from "react";
import { notFound, usePathname, useRouter } from "next/navigation";
import { AtSign, FolderClosed, LayoutGrid } from "lucide-react";
import { profile, SocialError, type PublicProfile } from "@/lib/social";
import { useAuth } from "@/components/auth/auth-provider";
import { ProfileHeader } from "@/components/profile/profile-header";
import {
ProfileTabs,
type ProfileTab,
} from "@/components/profile/profile-tabs";
import { PublicProfileContext } from "./profile-context";
export default function PublicProfileLayout(props: {
params: Promise<{ handle: string }>;
children: React.ReactNode;
}) {
const { handle } = use(props.params);
const router = useRouter();
const pathname = usePathname();
const { user } = useAuth();
// Store the request handle alongside the result. The view derives
// `loading` from "do we have a result whose handle matches the current
// route?" — that lets us skip a synchronous setLoading(true) inside the
// fetch effect (which would trigger a cascading render on every mount).
type Result =
| { handle: string; data: PublicProfile; missing: false }
| { handle: string; data: null; missing: true };
const [result, setResult] = useState<Result | null>(null);
const isOwn = !!user && user.handle.toLowerCase() === handle.toLowerCase();
useEffect(() => {
if (!isOwn) return;
// Preserve whatever sub-path the visitor is on so /u/<own>/collections
// jumps to /u/me/collections (and so on for /posts, /mentions).
const m = pathname.match(/^\/u\/[^/]+(\/.*)?$/);
const suffix = m?.[1] ?? "";
router.replace(`/u/me${suffix}`);
}, [isOwn, router, pathname]);
useEffect(() => {
if (isOwn) return;
let cancelled = false;
profile
.get(handle)
.then((p) => {
if (!cancelled) setResult({ handle, data: p, missing: false });
})
.catch((err) => {
if (
!cancelled &&
err instanceof SocialError &&
err.status === 404
) {
setResult({ handle, data: null, missing: true });
}
});
return () => {
cancelled = true;
};
}, [handle, isOwn]);
// A result for a previous handle is treated as "still loading the new
// one" — so when the route changes we automatically show the spinner
// again without any setState during render or in an effect body.
const fresh = result?.handle === handle ? result : null;
const missing = fresh?.missing === true;
const data = fresh && fresh.missing === false ? fresh.data : null;
const loading = fresh === null;
if (missing) notFound();
if (isOwn) return null;
if (loading || !data) {
return (
<main className="flex-1 max-w-3xl w-full mx-auto px-4 sm:px-6 py-12">
<p className="text-sm text-muted-foreground">Loading profile…</p>
</main>
);
}
const tabs: ProfileTab[] = [
{
href: `/u/${data.handle}`,
label: "Posts",
icon: <LayoutGrid className="size-5" />,
activeFor: [`/u/${data.handle}/posts`],
},
{
href: `/u/${data.handle}/collections`,
label: "Collections",
icon: <FolderClosed className="size-5" />,
},
{
href: `/u/${data.handle}/mentions`,
label: "Tagged",
icon: <AtSign className="size-5" />,
},
];
return (
<main className="flex-1 max-w-3xl w-full mx-auto px-4 sm:px-6">
<ProfileHeader
avatarURL={data.avatar_url}
name={data.name}
handle={data.handle}
postCount={data.post_count}
joinedAt={data.joined_at}
/>
<ProfileTabs tabs={tabs} />
<PublicProfileContext.Provider value={data}>
<div className="py-6">{props.children}</div>
</PublicProfileContext.Provider>
</main>
);
}
+25
View File
@@ -0,0 +1,25 @@
"use client";
/**
* /u/[handle]/mentions — posts that tag this user.
*
* Mirror of /u/me/mentions: the tab is wired into the public profile
* shell so visitors see an empty state instead of a 404. Will swap to
* a real feed once the Mentions feature ships.
*/
import { AtSign } from "lucide-react";
import { usePublicProfile } from "../profile-context";
export default function PublicProfileMentionsPage() {
const data = usePublicProfile();
return (
<div className="flex flex-col items-center text-center gap-3 py-12 text-muted-foreground">
<AtSign className="size-8" />
<p className="text-sm">
Posts that tag <span className="text-foreground">@{data.handle}</span>{" "}
will appear here. Coming soon.
</p>
</div>
);
}
+28
View File
@@ -0,0 +1,28 @@
/**
* /u/[handle] — public profile, Posts tab (default).
*
* Server shell that exists for two reasons:
*
* 1. Export `generateMetadata` so direct shares of this URL
* (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 type { Metadata } from "next";
import { PostsGrid } from "./posts-grid";
import { metadataForHandle } from "./profile-og";
type Props = { params: Promise<{ handle: string }> };
export async function generateMetadata({ params }: Props): Promise<Metadata> {
const { handle } = await params;
return metadataForHandle(handle);
}
export default function PublicProfilePage({ params }: Props) {
return <PostsGrid params={params} />;
}
+60
View File
@@ -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."
/>
);
}
+28
View File
@@ -0,0 +1,28 @@
/**
* /u/[handle]/posts — public Instagram-style scroll feed.
*
* Server shell so we can export `generateMetadata` for OG previews on
* direct shares of this URL. We re-use the same profile-OG metadata as
* /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.
*
* (Post-level OG cards still work via the SharePostSheet → short link
* → /share/[code] route, which DOES see the hash and dispatches to
* `ogForPost` in share-og.ts.)
*/
import type { Metadata } from "next";
import { metadataForHandle } from "../profile-og";
import { ScrollFeed } from "./scroll-feed";
type Props = { params: Promise<{ handle: string }> };
export async function generateMetadata({ params }: Props): Promise<Metadata> {
const { handle } = await params;
return metadataForHandle(handle);
}
export default function PublicPostsFeedPage({ params }: Props) {
return <ScrollFeed params={params} />;
}
@@ -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>
);
}
+19
View File
@@ -0,0 +1,19 @@
"use client";
import { createContext, useContext } from "react";
import type { PublicProfile } from "@/lib/social";
/** Set by the /u/[handle] layout after it fetches the profile. Child
* pages read it to render content (e.g. the Collections tab needs the
* profile's `public_collections` array) without a second fetch. */
export const PublicProfileContext = createContext<PublicProfile | null>(null);
export function usePublicProfile(): PublicProfile {
const v = useContext(PublicProfileContext);
if (!v) {
throw new Error(
"usePublicProfile must be used inside the /u/[handle] layout",
);
}
return v;
}
+47
View File
@@ -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();
}
}
+117
View File
@@ -0,0 +1,117 @@
"use client";
import { useEffect, useState } from "react";
import Link from "next/link";
import { Trash2, ExternalLink } from "lucide-react";
import { bookmarks, SocialError, type Bookmark } from "@/lib/social";
import { useAuth } from "@/components/auth/auth-provider";
import { appendHighlight, hasHighlight } from "@/lib/text-highlight";
import { displaySourceLabel } from "@/lib/source-reference";
const FREE_LIMIT = 1;
const PREMIUM_LIMIT = 5;
export default function MyBookmarksPage() {
const { user } = useAuth();
const [list, setList] = useState<Bookmark[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
setLoading(true);
bookmarks
.list()
.then((r) => setList(r ?? []))
.catch((err) =>
setError(
err instanceof SocialError ? err.message : "Could not load bookmarks.",
),
)
.finally(() => setLoading(false));
}, []);
async function remove(id: string) {
const prev = list;
setList((rows) => rows.filter((b) => b.id !== id));
try {
await bookmarks.delete(id);
} catch (err) {
setList(prev);
setError(err instanceof SocialError ? err.message : "Could not delete.");
}
}
const limit = user?.role === "admin" || user?.plan === "premium" ? PREMIUM_LIMIT : FREE_LIMIT;
if (loading) return <p className="text-sm text-muted-foreground">Loading…</p>;
return (
<div className="space-y-5">
<div className="rounded-lg bg-card/60 ring-1 ring-foreground/8 px-4 py-3 text-sm flex items-center justify-between">
<span className="text-muted-foreground">
Bookmarks used:{" "}
<span className="text-foreground tabular-nums">
{list.length} / {limit}
</span>
</span>
{user?.plan !== "premium" && list.length >= limit ? (
<span className="text-xs text-amber-600 dark:text-amber-400">
Upgrade to premium for 5 bookmarks
</span>
) : null}
</div>
{error ? <p className="text-sm text-destructive">{error}</p> : null}
{list.length === 0 ? (
<p className="text-sm text-muted-foreground">
No bookmarks yet. Select text anywhere and use “Add bookmark” in the
more menu.
</p>
) : (
<ul className="space-y-3">
{list.map((b) => {
// If the stored URL doesn't already carry a `?hl=` (old data, or
// a bookmark saved without a selection), synthesise one from the
// excerpt so clicking still scrolls to + highlights the passage.
const href =
hasHighlight(b.source_url) || !b.excerpt
? b.source_url
: appendHighlight(b.source_url, b.excerpt);
return (
<li
key={b.id}
className="rounded-xl bg-card ring-1 ring-foreground/10 p-4 flex items-start gap-3"
>
<div className="flex-1 min-w-0">
<Link
href={href}
className="font-[family-name:var(--font-title)] text-base text-foreground hover:underline inline-flex items-center gap-1"
>
<ExternalLink className="size-3.5" />
{displaySourceLabel(b.source_url, b.source_title)}
</Link>
{b.excerpt ? (
<p className="mt-1 text-sm text-muted-foreground italic line-clamp-2">
“{b.excerpt}”
</p>
) : null}
<p className="text-xs text-muted-foreground mt-2">
Saved {new Date(b.created_at).toLocaleDateString()}
</p>
</div>
<button
onClick={() => remove(b.id)}
aria-label="Delete bookmark"
className="size-9 inline-flex items-center justify-center rounded-md text-muted-foreground hover:text-destructive hover:bg-destructive/10 transition-colors"
>
<Trash2 className="size-4" />
</button>
</li>
);
})}
</ul>
)}
</div>
);
}
+91
View File
@@ -0,0 +1,91 @@
"use client";
/**
* /u/me/collections/[id] — single-collection view.
*
* The whole page is the collection's CollectionScrollCard (carousel of
* cover + posts) and an Edit button below it. All editing — title,
* description, cover, member posts, delete — lives in the EditCollectionDrawer
* so the page itself stays focused on the carousel preview.
*/
import { use, useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { ArrowLeft } from "lucide-react";
import {
collections,
SocialError,
type Collection,
type Post,
} from "@/lib/social";
import { CollectionScrollCard } from "@/components/social/collection-scroll-card";
import { EditCollectionDrawer } from "@/components/social/edit-collection-drawer";
export default function CollectionDetailPage(props: {
params: Promise<{ id: string }>;
}) {
const { id } = use(props.params);
const router = useRouter();
const [c, setC] = useState<Collection | null>(null);
const [posts, setPosts] = useState<Post[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [editOpen, setEditOpen] = useState(false);
useEffect(() => {
let cancelled = false;
setLoading(true);
collections
.get(id)
.then(({ collection, posts }) => {
if (cancelled) return;
setC(collection);
setPosts(posts ?? []);
})
.catch((err) => {
setError(
err instanceof SocialError ? err.message : "Could not load collection.",
);
})
.finally(() => !cancelled && setLoading(false));
return () => {
cancelled = true;
};
}, [id]);
if (loading) return <p className="text-sm text-muted-foreground">Loading…</p>;
if (error && !c) return <p className="text-sm text-destructive">{error}</p>;
if (!c) return null;
return (
<div className="space-y-6">
<button
type="button"
onClick={() => router.push("/u/me/collections")}
className="inline-flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground"
>
<ArrowLeft className="size-4" /> All collections
</button>
<CollectionScrollCard
collection={c}
href={`/u/me/collections/${c.id}`}
initialPosts={posts}
onEdit={() => setEditOpen(true)}
/>
<EditCollectionDrawer
open={editOpen}
onClose={() => setEditOpen(false)}
collection={c}
currentPosts={posts}
onSaved={({ collection, posts: rows }) => {
setC(collection);
setPosts(rows);
}}
onDeleted={() => router.push("/u/me/collections")}
/>
</div>
);
}
+150
View File
@@ -0,0 +1,150 @@
"use client";
import { useEffect, useState } from "react";
import { Plus } from "lucide-react";
import { collections, SocialError, type Collection } from "@/lib/social";
import { useAuth } from "@/components/auth/auth-provider";
import { CollectionViews } from "@/components/social/collection-views";
export default function MyCollectionsPage() {
const { user } = useAuth();
const [list, setList] = useState<Collection[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
// Inline create form
const [showCreate, setShowCreate] = useState(false);
const [title, setTitle] = useState("");
const [description, setDescription] = useState("");
const [isPublic, setIsPublic] = useState(true);
const [creating, setCreating] = useState(false);
useEffect(() => {
setLoading(true);
collections
.mine()
.then((r) => setList(r ?? []))
.catch((err) =>
setError(
err instanceof SocialError ? err.message : "Could not load collections.",
),
)
.finally(() => setLoading(false));
}, []);
async function createOne(e: React.SyntheticEvent) {
e.preventDefault();
if (!title.trim()) return;
setCreating(true);
setError(null);
try {
const c = await collections.create({
title,
description: description || undefined,
is_public: isPublic,
});
setList((rows) => [c, ...rows]);
setTitle("");
setDescription("");
setShowCreate(false);
} catch (err) {
setError(err instanceof SocialError ? err.message : "Could not create.");
} finally {
setCreating(false);
}
}
const isPremium = user?.plan === "premium";
const publicCount = list.filter((c) => c.is_public).length;
const privateCount = list.filter((c) => !c.is_public).length;
return (
<div className="space-y-5">
<div className="flex items-center justify-between">
<p className="text-sm text-muted-foreground">
{isPremium ? (
<>Premium — unlimited collections.</>
) : (
<>
<span className="tabular-nums">{publicCount}</span> / 5 public ·{" "}
<span className="tabular-nums">{privateCount}</span> / 5 private
</>
)}
</p>
{!showCreate ? (
<button
onClick={() => setShowCreate(true)}
className="inline-flex items-center gap-1.5 rounded-lg bg-primary text-primary-foreground px-3 h-10 text-sm font-medium"
>
<Plus className="size-4" />
New
</button>
) : null}
</div>
{showCreate ? (
<form
onSubmit={createOne}
className="rounded-xl bg-card ring-1 ring-foreground/10 p-4 space-y-3"
>
<input
value={title}
onChange={(e) => setTitle(e.target.value)}
placeholder="Collection title"
maxLength={120}
required
className="w-full bg-background text-foreground text-base rounded-md border border-border px-3 py-2 outline-none focus-visible:ring-2 focus-visible:ring-primary/40"
/>
<textarea
value={description}
onChange={(e) => setDescription(e.target.value)}
placeholder="Description (optional)"
rows={2}
className="w-full bg-background text-foreground text-sm rounded-md border border-border px-3 py-2 outline-none focus-visible:ring-2 focus-visible:ring-primary/40 resize-none"
/>
<div className="flex items-center justify-between text-sm">
<label className="flex items-center gap-2 cursor-pointer">
<input
type="checkbox"
checked={isPublic}
onChange={(e) => setIsPublic(e.target.checked)}
/>
<span className="text-foreground">Public</span>
</label>
<div className="flex items-center gap-2">
<button
type="button"
onClick={() => {
setShowCreate(false);
setTitle("");
}}
className="px-3 h-9 rounded-md text-muted-foreground hover:bg-muted"
>
Cancel
</button>
<button
type="submit"
disabled={creating || !title.trim()}
className="px-3 h-9 rounded-md bg-primary text-primary-foreground disabled:opacity-60"
>
{creating ? "Creating…" : "Create"}
</button>
</div>
</div>
</form>
) : null}
{error ? <p className="text-sm text-destructive">{error}</p> : null}
{loading ? (
<p className="text-sm text-muted-foreground">Loading…</p>
) : (
<CollectionViews
collections={list}
hrefFor={(c) => `/u/me/collections/${c.id}`}
emptyMessage="No collections yet — create one above, or save a quote into a new collection from the selection toolbar."
/>
)}
</div>
);
}
+114
View File
@@ -0,0 +1,114 @@
"use client";
/**
* /u/me shared layout — auth gate + Instagram-style profile shell.
*
* • Anonymous visitors trigger the global AuthModal and are bounced
* home if they dismiss it (unchanged from before).
* • Renders the ProfileHeader + ProfileTabs above every /u/me/* page.
* Tabs: Posts / Collections / Bookmarks / Mentions.
*
* The old left ProfileSidebar is gone. The "Edit profile" affordance
* moved onto the header as a button that toggles edit mode on /u/me
* via a query param (kept simple — no new route for the form).
*/
import { Suspense, useEffect } from "react";
import { usePathname, useRouter, useSearchParams } from "next/navigation";
import {
AtSign,
Bookmark,
FolderClosed,
LayoutGrid,
} from "lucide-react";
import { useAuth } from "@/components/auth/auth-provider";
import { useAuthGate } from "@/components/auth/auth-gate";
import { ProfileHeader } from "@/components/profile/profile-header";
import { ProfileTabs, type ProfileTab } from "@/components/profile/profile-tabs";
export default function MeLayout({ children }: { children: React.ReactNode }) {
const { user, loading } = useAuth();
const { requireAuth } = useAuthGate();
const router = useRouter();
useEffect(() => {
if (loading || user) return;
let cancelled = false;
(async () => {
const ok = await requireAuth();
if (!ok && !cancelled) router.replace("/");
})();
return () => {
cancelled = true;
};
}, [loading, user, requireAuth, router]);
if (loading || !user) {
return (
<main className="flex-1 flex items-center justify-center px-4 py-12">
<p className="text-sm text-muted-foreground">
{loading ? "Loading…" : "Sign in to view your library."}
</p>
</main>
);
}
const tabs: ProfileTab[] = [
{
href: "/u/me",
label: "Posts",
icon: <LayoutGrid className="size-5" />,
activeFor: ["/u/me/posts"],
},
{
href: "/u/me/collections",
label: "Collections",
icon: <FolderClosed className="size-5" />,
},
{
href: "/u/me/bookmarks",
label: "Bookmarks",
icon: <Bookmark className="size-5" />,
},
{
href: "/u/me/mentions",
label: "Mentions",
icon: <AtSign className="size-5" />,
},
];
return (
<main className="flex-1 max-w-3xl w-full mx-auto px-4 sm:px-6">
<ProfileHeader
avatarURL={user.avatar_url}
name={user.name}
handle={user.handle}
joinedAt={user.created_at}
editHref="/u/me?edit=1"
/>
{/* Tab strip hides on /u/me?edit=1 (see ConditionalTabs). The
Suspense boundary is required by Next.js because useSearchParams
forces a CSR bailout during prerender. Without it, every
/u/me/* route fails to build. Fallback renders the tabs as-is
so the visual default (tabs visible) is what users see while
the search params resolve. */}
<Suspense fallback={<ProfileTabs tabs={tabs} />}>
<ConditionalTabs tabs={tabs} />
</Suspense>
<div className="py-6">{children}</div>
</main>
);
}
function ConditionalTabs({ tabs }: { tabs: ProfileTab[] }) {
const searchParams = useSearchParams();
const pathname = usePathname();
// Hide tabs when the user is in a focused subview:
// • /u/me?edit=1 — the inline profile-edit form
// • /u/me/settings — the reading-prefs page
// In either case the strip is visual noise that distracts from the
// task they navigated in to do.
const editMode = searchParams.get("edit") === "1";
const settingsMode = pathname.startsWith("/u/me/settings");
return editMode || settingsMode ? null : <ProfileTabs tabs={tabs} />;
}
+21
View File
@@ -0,0 +1,21 @@
"use client";
/**
* /u/me/mentions — placeholder until the Mentions feature ships.
*
* The tab itself is wired into the profile shell already so users see
* an empty state instead of a 404 when they tap it.
*/
import { AtSign } from "lucide-react";
export default function MentionsPage() {
return (
<div className="flex flex-col items-center text-center gap-3 py-12 text-muted-foreground">
<AtSign className="size-8" />
<p className="text-sm">
Mentions of you across posts will appear here. Coming soon.
</p>
</div>
);
}
+139
View File
@@ -0,0 +1,139 @@
"use client";
/**
* /u/me — owner Posts grid (the default tab).
*
* Grid-only — no Grid/Scroll toggle. Tapping a thumbnail jumps to
* /u/me/posts#post-<id> where the Instagram-style scroll feed renders
* the full passages.
*
* `?edit=1` (set by the header's Edit profile button) swaps the grid
* for the inline edit form. Saving returns to /u/me. Keeps the URL
* shareable while avoiding a separate route + layout.
*/
import { Suspense, useEffect, useState } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { LayoutGrid } from "lucide-react";
import { useAuth } from "@/components/auth/auth-provider";
import { ProfileEditForm } from "@/components/profile/profile-edit-form";
import { PostGridCard } from "@/components/social/post-grid-card";
import { ConfirmModal } from "@/components/ui/confirm-modal";
import { posts, SocialError, type Post } from "@/lib/social";
export default function MyProfilePage() {
// useSearchParams() forces a CSR bailout during prerender; the
// Suspense boundary is required by Next.js so the build doesn't fail
// (the same wrapping is in app/u/me/layout.tsx for its own check).
// The fallback matches the page's idle loading state so the brief
// moment before search params resolve doesn't flash an empty section.
return (
<Suspense
fallback={<p className="text-sm text-muted-foreground">Loading…</p>}
>
<MyProfilePageInner />
</Suspense>
);
}
function MyProfilePageInner() {
const { user } = useAuth();
const router = useRouter();
const searchParams = useSearchParams();
const editMode = searchParams.get("edit") === "1";
const [feed, setFeed] = useState<Post[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
// Post id pending confirmation — modal opens when non-null and runs
// the actual delete on confirm.
const [pendingDelete, setPendingDelete] = useState<string | null>(null);
useEffect(() => {
if (!user) return;
setLoading(true);
posts
.mine()
.then((rows) => setFeed(rows ?? []))
.catch((err) =>
setError(
err instanceof SocialError ? err.message : "Could not load posts.",
),
)
.finally(() => setLoading(false));
}, [user]);
// Card delete buttons stage an id; ConfirmModal runs `performDelete`
// when the user confirms. We throw on failure so the modal stays open
// with an inline error message.
async function performDelete() {
const id = pendingDelete;
if (!id) return;
const prev = feed;
setFeed((rows) => rows.filter((p) => p.id !== id));
try {
await posts.delete(id);
} catch (err) {
setFeed(prev);
const msg =
err instanceof SocialError ? err.message : "Could not delete.";
setError(msg);
throw new Error(msg);
}
}
function onPostUpdated(updated: Post) {
setFeed((rows) => rows.map((p) => (p.id === updated.id ? updated : p)));
}
if (!user) return null;
if (editMode) {
return <ProfileEditForm user={user} onDone={() => router.replace("/u/me")} />;
}
return (
<section>
{error ? (
<p className="text-sm text-destructive">{error}</p>
) : loading ? (
<p className="text-sm text-muted-foreground">Loading…</p>
) : feed.length === 0 ? (
<EmptyPosts />
) : (
<div className="grid grid-cols-2 gap-2 sm:gap-3">
{feed.map((p) => (
<PostGridCard
key={p.id}
post={p}
onDelete={(id) => setPendingDelete(id)}
onUpdated={onPostUpdated}
href={`/u/me/posts#post-${p.id}`}
/>
))}
</div>
)}
<ConfirmModal
open={!!pendingDelete}
onClose={() => setPendingDelete(null)}
title="Delete this post?"
message="The post will be removed permanently from your feed and from any collections it's in. This can't be undone."
confirmLabel="Delete post"
onConfirm={performDelete}
/>
</section>
);
}
function EmptyPosts() {
return (
<div className="flex flex-col items-center text-center gap-3 py-12 text-muted-foreground">
<LayoutGrid className="size-8" />
<p className="text-sm">
You haven&apos;t posted anything yet. Select any passage in the
knowledgebase and use the toolbar to share it to your feed.
</p>
</div>
);
}
+108
View File
@@ -0,0 +1,108 @@
"use client";
/**
* /u/me/posts — the owner's Instagram-style scroll feed.
*
* Reached by tapping a thumbnail from the /u/me Posts grid. The clicked
* post's id arrives as a `#post-<id>` hash, and `scroll-mt-*` on each
* card spaces it below the sticky header so the anchor lands cleanly.
*
* Owner controls (Delete + Update background) are mounted per-card.
*/
import { useEffect, useRef, useState } from "react";
import { useAuth } from "@/components/auth/auth-provider";
import { PostScrollCard } from "@/components/social/post-scroll-card";
import { ConfirmModal } from "@/components/ui/confirm-modal";
import { posts, SocialError, type Post } from "@/lib/social";
export default function MyPostsFeedPage() {
const { user } = useAuth();
const [feed, setFeed] = useState<Post[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [pendingDelete, setPendingDelete] = useState<string | null>(null);
const scrolledToHashRef = useRef(false);
useEffect(() => {
if (!user) return;
setLoading(true);
posts
.mine()
.then((rows) => setFeed(rows ?? []))
.catch((err) =>
setError(
err instanceof SocialError ? err.message : "Could not load posts.",
),
)
.finally(() => setLoading(false));
}, [user]);
// Hash anchor: when the feed mounts, jump to the post identified in the
// URL hash. Defer one tick so the cards have laid out and `scroll-mt-*`
// can position the anchor below the sticky header.
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]);
async function performDelete() {
const id = pendingDelete;
if (!id) return;
const prev = feed;
setFeed((rows) => rows.filter((p) => p.id !== id));
try {
await posts.delete(id);
} catch (err) {
setFeed(prev);
const msg =
err instanceof SocialError ? err.message : "Could not delete.";
setError(msg);
// Re-throw so ConfirmModal surfaces the failure and stays open.
throw new Error(msg);
}
}
function onPostUpdated(updated: Post) {
setFeed((rows) => rows.map((p) => (p.id === updated.id ? updated : p)));
}
if (!user) return null;
return (
<div className="max-w-xl w-full mx-auto space-y-6">
{error ? (
<p className="text-sm text-destructive">{error}</p>
) : 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}
onDelete={(id) => setPendingDelete(id)}
onUpdated={onPostUpdated}
/>
))
)}
<ConfirmModal
open={!!pendingDelete}
onClose={() => setPendingDelete(null)}
title="Delete this post?"
message="The post will be removed permanently from your feed and from any collections it's in. This can't be undone."
confirmLabel="Delete post"
onConfirm={performDelete}
/>
</div>
);
}
+43
View File
@@ -0,0 +1,43 @@
"use client";
/**
* /u/me/settings — dedicated reading-preferences screen for auth users.
*
* Mirrors the Edit Profile pattern: a focused subview of /u/me that
* trades the tab strip for a back link + the settings form. We send
* users here instead of opening the popover because the popover, when
* triggered from ProfileHeader's centred action row, can spill off the
* left edge of narrow viewports. Anonymous users still get the popover
* in SiteHeader — that trigger sits at right-2 so it doesn't overflow.
*
* The /u/me layout's ConditionalTabs detects this path and hides the
* Posts/Collections/Bookmarks/Mentions strip while the user is editing
* settings.
*/
import Link from "next/link";
import { ChevronLeft } from "lucide-react";
import { ReadingSettings } from "@/components/reading-settings";
export default function ReadingSettingsPage() {
return (
<div className="space-y-6">
<Link
href="/u/me"
className="inline-flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground transition-colors"
>
<ChevronLeft className="size-4" />
Back to profile
</Link>
<div>
<h1 className="font-[family-name:var(--font-title)] text-2xl font-semibold text-foreground">
Reading settings
</h1>
<p className="text-sm text-muted-foreground mt-1">
Theme, palette, font, and size — synced across your devices.
</p>
</div>
<ReadingSettings variant="inline" />
</div>
);
}