Locked-account profiles: private = stub + Pending follow flow

Replaces the earlier 404-for-private model with Mastodon-style locked
accounts. A private profile now returns 200 with a stub layout and
gates content behind follow approval. Default for new users flips from
'public' to 'private' to align with trails.cool's privacy-first
content defaults.

Schema:
- users.profile_visibility default flipped to 'private'. Existing rows
  remain 'public' (backfill on first migration handled them).

Follow API (follow.server.ts):
- followUser now creates Pending (accepted_at = NULL) against private
  targets and Accepted against public targets — no more refusal.
- New: countPendingFollowRequests, listPendingFollowRequests,
  approveFollowRequest, rejectFollowRequest. Approve/reject are
  owner-bound: only the followed user can act on their own incoming
  requests.
- countFollowers / countFollowing / listFollowers / listFollowing now
  filter to accepted-only relations.

Loader (users.$username.tsx):
- Drops the 404 paths. New canSeeContent flag = isOwn ||
  profile_visibility='public' || (followState.following === true).
- When canSeeContent=false, render a stub: header + 🔒 badge + body
  copy + Request-to-follow / sign-in CTA. Routes/activities sections
  are not rendered.

UI:
- FollowButton gains a "Request to follow" / "Requested" state for
  private targets via a new isPrivateTarget prop. Cancel-request reuses
  the unfollow endpoint.
- New /follows/requests page lists incoming Pending requests with
  Approve / Reject buttons.
- New API routes: POST /api/follows/:id/approve and /reject.
- Navbar shows a count badge linking to /follows/requests when
  pending > 0.

Privacy manifest already documents the follows relation; no changes
needed (the locked-account semantics don't add new data — same row,
different lifecycle).

Specs / design (social-feed change):
- public-profiles delta rewritten around the four-mode locked model
  (public, private+anon, private+pending, private+accepted) with
  scenarios for each.
- social-follows delta gains Pending lifecycle requirements (auto vs.
  manual accept, approve/reject endpoints, pending request management,
  Pending follows do not contribute to feed).
- design.md decision section reflects the new model and rationale for
  default-private; non-goal "locked-local-accounts as a follow-up" is
  removed since this change ships it.

Tests:
- follow.integration.test.ts: pending-against-private, approve flips
  to accepted, reject deletes, owner-bound enforcement.
- e2e/social.test.ts: full Request → Pending → Approve → full-view
  flow, plus stub-for-anonymous and /follows/requests auth gate.

Supersedes PR #309 (closed): the empty-public-profile 200 is now a
side-effect of the new render path.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
Ullrich Schäfer 2026-04-25 23:38:26 +02:00
parent ede68712a3
commit 5da7ffa037
17 changed files with 656 additions and 181 deletions

View file

@ -8,21 +8,36 @@ interface FollowState {
interface Props {
username: string;
// Whether the followed profile is private/locked. Drives the "Request to
// follow" label vs. plain "Follow" before any click happens.
isPrivateTarget: boolean;
initialState: FollowState | null;
}
export function FollowButton({ username, initialState }: Props) {
type Display = "follow" | "request" | "pending" | "unfollow";
function displayFor(state: FollowState | null, isPrivateTarget: boolean): Display {
if (state?.following) return "unfollow";
if (state?.pending) return "pending";
return isPrivateTarget ? "request" : "follow";
}
export function FollowButton({ username, isPrivateTarget, initialState }: Props) {
const { t } = useTranslation("journal");
const [state, setState] = useState<FollowState>(
initialState ?? { following: false, pending: false },
);
const [isPending, startTransition] = useTransition();
const [isInFlight, startTransition] = useTransition();
const [error, setError] = useState<string | null>(null);
const display = displayFor(state, isPrivateTarget);
const onClick = () => {
setError(null);
startTransition(async () => {
const path = state.following
// For "pending" we treat the click as cancel-request: same /unfollow
// endpoint deletes the row whether it's accepted or pending.
const path = state.following || state.pending
? `/api/users/${username}/unfollow`
: `/api/users/${username}/follow`;
try {
@ -40,21 +55,33 @@ export function FollowButton({ username, initialState }: Props) {
});
};
const label = state.following ? t("social.unfollow") : t("social.follow");
const label = (() => {
switch (display) {
case "unfollow":
return t("social.unfollow");
case "pending":
return t("social.pendingCancel");
case "request":
return t("social.requestToFollow");
case "follow":
default:
return t("social.follow");
}
})();
const baseClass = display === "follow" || display === "request"
? "rounded-md bg-blue-600 px-4 py-2 text-sm font-medium text-white hover:bg-blue-700 disabled:opacity-50"
: "rounded-md border border-gray-300 bg-white px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50 disabled:opacity-50";
return (
<div className="flex flex-col items-end gap-1">
<button
type="button"
onClick={onClick}
disabled={isPending}
className={
state.following
? "rounded-md border border-gray-300 bg-white px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50 disabled:opacity-50"
: "rounded-md bg-blue-600 px-4 py-2 text-sm font-medium text-white hover:bg-blue-700 disabled:opacity-50"
}
disabled={isInFlight}
className={baseClass}
>
{isPending ? "…" : label}
{isInFlight ? "…" : label}
</button>
{error && <p className="text-xs text-red-600">{error}</p>}
</div>

View file

@ -9,7 +9,10 @@ import {
getFollowState,
countFollowers,
countFollowing,
FollowError,
countPendingFollowRequests,
listPendingFollowRequests,
approveFollowRequest,
rejectFollowRequest,
} from "./follow.server.ts";
// Opt-in: these talk to real Postgres. Gated by an env flag so laptop
@ -74,12 +77,14 @@ describe.skipIf(!runIntegration)("follow.server integration", () => {
expect(aRow.username.startsWith("f_a_")).toBe(true);
});
it("refuses to follow a private profile", async () => {
it("creates a Pending follow against a private profile (not a refusal)", async () => {
const a = await makeUser({ username: `f_pa_${Date.now()}` });
const b = await makeUser({ username: `f_pb_${Date.now()}`, profileVisibility: "private" });
const bRow = (await getDb().select().from(users).where(eq(users.id, b)))[0]!;
await expect(followUser(a, bRow.username)).rejects.toBeInstanceOf(FollowError);
await expect(followUser(a, bRow.username)).rejects.toMatchObject({ code: "private_profile" });
const s = await followUser(a, bRow.username);
expect(s).toEqual({ following: false, pending: true });
// Pending is excluded from accepted-only counts.
expect(await countFollowers(b)).toBe(0);
expect(await countFollowing(a)).toBe(0);
});
@ -89,6 +94,48 @@ describe.skipIf(!runIntegration)("follow.server integration", () => {
await expect(followUser(a, aRow.username)).rejects.toMatchObject({ code: "self_follow" });
});
it("approve flips Pending → Accepted; reject deletes the request", async () => {
const a = await makeUser({ username: `f_apr_${Date.now()}` });
const b = await makeUser({ username: `f_apb_${Date.now()}`, profileVisibility: "private" });
const bRow = (await getDb().select().from(users).where(eq(users.id, b)))[0]!;
await followUser(a, bRow.username);
expect(await countPendingFollowRequests(b)).toBe(1);
const reqs = await listPendingFollowRequests(b);
expect(reqs.length).toBe(1);
const reqId = reqs[0]!.id;
const approved = await approveFollowRequest(b, reqId);
expect(approved).toBe(true);
expect(await countPendingFollowRequests(b)).toBe(0);
expect(await countFollowers(b)).toBe(1);
expect(await getFollowState(a, bRow.username)).toEqual({ following: true, pending: false });
// Idempotent: approving again is a no-op.
expect(await approveFollowRequest(b, reqId)).toBe(false);
// Reject path: a fresh request from a 3rd user, B rejects.
const c = await makeUser({ username: `f_apc_${Date.now()}` });
await followUser(c, bRow.username);
const reqs2 = await listPendingFollowRequests(b);
expect(reqs2.length).toBe(1);
expect(await rejectFollowRequest(b, reqs2[0]!.id)).toBe(true);
expect(await countPendingFollowRequests(b)).toBe(0);
expect(await getFollowState(c, bRow.username)).toBeNull();
});
it("approve/reject is owner-bound (other users can't approve someone else's request)", async () => {
const a = await makeUser({ username: `f_obA_${Date.now()}` });
const b = await makeUser({ username: `f_obB_${Date.now()}`, profileVisibility: "private" });
const bRow = (await getDb().select().from(users).where(eq(users.id, b)))[0]!;
const c = await makeUser({ username: `f_obC_${Date.now()}` });
await followUser(a, bRow.username);
const reqs = await listPendingFollowRequests(b);
// C tries to approve B's incoming request — should be a no-op.
expect(await approveFollowRequest(c, reqs[0]!.id)).toBe(false);
expect(await countPendingFollowRequests(b)).toBe(1);
});
it("404s on unknown username", async () => {
const a = await makeUser({ username: `f_404_${Date.now()}` });
await expect(followUser(a, "no_such_user_xyz")).rejects.toMatchObject({ code: "user_not_found" });

View file

@ -1,11 +1,11 @@
import { randomUUID } from "node:crypto";
import { eq, and, count, desc } from "drizzle-orm";
import { eq, and, count, desc, isNull, isNotNull } from "drizzle-orm";
import { getDb } from "./db.ts";
import { users, follows } from "@trails-cool/db/schema/journal";
import { localActorIri } from "./actor-iri.ts";
export class FollowError extends Error {
readonly code: "self_follow" | "private_profile" | "user_not_found" | "not_found";
readonly code: "self_follow" | "user_not_found" | "not_found" | "forbidden";
constructor(code: FollowError["code"], message: string) {
super(message);
this.name = "FollowError";
@ -34,18 +34,16 @@ async function loadFollowableTarget(targetUsername: string) {
/**
* Create a follow row from `followerId` to the local user with username
* `targetUsername`. Auto-accepted because the target is local + public.
* Idempotent: re-following an already-followed user returns the same state
* without creating a duplicate row.
* `targetUsername`. Public targets auto-accept (`accepted_at = now()`),
* private (locked) targets land Pending (`accepted_at = NULL`) and
* appear in the target's /follows/requests list for manual approval.
* Idempotent: re-following keeps the existing row's state.
*/
export async function followUser(followerId: string, targetUsername: string): Promise<FollowState> {
const target = await loadFollowableTarget(targetUsername);
if (target.id === followerId) {
throw new FollowError("self_follow", "Users cannot follow themselves");
}
if (target.profileVisibility !== "public") {
throw new FollowError("private_profile", "This profile is not followable");
}
const db = getDb();
const followedActorIri = localActorIri(target.username);
@ -57,15 +55,19 @@ export async function followUser(followerId: string, targetUsername: string): Pr
return { following: existing.acceptedAt !== null, pending: existing.acceptedAt === null };
}
const acceptedAt = target.profileVisibility === "public" ? new Date() : null;
await db.insert(follows).values({
id: randomUUID(),
followerId,
followedActorIri,
followedUserId: target.id,
acceptedAt: new Date(),
acceptedAt,
});
return { following: true, pending: false };
return {
following: acceptedAt !== null,
pending: acceptedAt === null,
};
}
/**
@ -101,12 +103,16 @@ export async function getFollowState(
return { following: row.acceptedAt !== null, pending: row.acceptedAt === null };
}
// Counts include only accepted relations — Pending requests don't count
// toward the public follower/following tallies (a request not yet
// approved isn't a real follow).
export async function countFollowers(userId: string): Promise<number> {
const db = getDb();
const [row] = await db
.select({ n: count() })
.from(follows)
.where(eq(follows.followedUserId, userId));
.where(and(eq(follows.followedUserId, userId), isNotNull(follows.acceptedAt)));
return row?.n ?? 0;
}
@ -115,10 +121,91 @@ export async function countFollowing(userId: string): Promise<number> {
const [row] = await db
.select({ n: count() })
.from(follows)
.where(eq(follows.followerId, userId));
.where(and(eq(follows.followerId, userId), isNotNull(follows.acceptedAt)));
return row?.n ?? 0;
}
/**
* Count of incoming Pending follow requests for `userId`. Drives the
* navbar badge. Distinct from countFollowers (which is accepted-only).
*/
export async function countPendingFollowRequests(userId: string): Promise<number> {
const db = getDb();
const [row] = await db
.select({ n: count() })
.from(follows)
.where(and(eq(follows.followedUserId, userId), isNull(follows.acceptedAt)));
return row?.n ?? 0;
}
export interface FollowRequest {
id: string;
followerUsername: string;
followerDisplayName: string | null;
followerDomain: string;
createdAt: Date;
}
/**
* Pending incoming follow requests for `userId`. Used by /follows/requests.
* Reverse-chronological by request creation time.
*/
export async function listPendingFollowRequests(userId: string): Promise<FollowRequest[]> {
const db = getDb();
const rows = await db
.select({
id: follows.id,
followerUsername: users.username,
followerDisplayName: users.displayName,
followerDomain: users.domain,
createdAt: follows.createdAt,
})
.from(follows)
.innerJoin(users, eq(follows.followerId, users.id))
.where(and(eq(follows.followedUserId, userId), isNull(follows.acceptedAt)))
.orderBy(desc(follows.createdAt));
return rows;
}
/**
* Approve a Pending follow request. Owner-bound: `ownerId` must equal
* `follows.followedUserId` for the row, otherwise the call is a no-op.
*/
export async function approveFollowRequest(ownerId: string, followId: string): Promise<boolean> {
const db = getDb();
const result = await db
.update(follows)
.set({ acceptedAt: new Date() })
.where(
and(
eq(follows.id, followId),
eq(follows.followedUserId, ownerId),
isNull(follows.acceptedAt),
),
)
.returning({ id: follows.id });
return result.length > 0;
}
/**
* Reject a Pending follow request. Deletes the row entirely so the
* follower can re-request later if they want.
*/
export async function rejectFollowRequest(ownerId: string, followId: string): Promise<boolean> {
const db = getDb();
const result = await db
.delete(follows)
.where(
and(
eq(follows.id, followId),
eq(follows.followedUserId, ownerId),
isNull(follows.acceptedAt),
),
)
.returning({ id: follows.id });
return result.length > 0;
}
export interface CollectionEntry {
username: string;
displayName: string | null;
@ -128,7 +215,8 @@ export interface CollectionEntry {
const COLLECTION_PAGE_SIZE = 50;
/**
* Paginated list of users who follow `userId`. Newest acceptance first.
* Paginated list of accepted followers of `userId`. Newest acceptance first.
* Pending requests are excluded they live in /follows/requests.
*/
export async function listFollowers(userId: string, page: number = 1): Promise<CollectionEntry[]> {
const db = getDb();
@ -141,7 +229,7 @@ export async function listFollowers(userId: string, page: number = 1): Promise<C
})
.from(follows)
.innerJoin(users, eq(follows.followerId, users.id))
.where(eq(follows.followedUserId, userId))
.where(and(eq(follows.followedUserId, userId), isNotNull(follows.acceptedAt)))
.orderBy(desc(follows.acceptedAt))
.limit(COLLECTION_PAGE_SIZE)
.offset(offset);
@ -149,9 +237,8 @@ export async function listFollowers(userId: string, page: number = 1): Promise<C
}
/**
* Paginated list of users that `userId` follows. Newest acceptance first.
* Limited to local follows in this change (`followedUserId IS NOT NULL`);
* federation will surface remote actors here too.
* Paginated list of accepted follows from `userId`. Newest acceptance first.
* Pending outgoing follows (against private/locked targets) are excluded.
*/
export async function listFollowing(userId: string, page: number = 1): Promise<CollectionEntry[]> {
const db = getDb();
@ -164,7 +251,7 @@ export async function listFollowing(userId: string, page: number = 1): Promise<C
})
.from(follows)
.innerJoin(users, eq(follows.followedUserId, users.id))
.where(eq(follows.followerId, userId))
.where(and(eq(follows.followerId, userId), isNotNull(follows.acceptedAt)))
.orderBy(desc(follows.acceptedAt))
.limit(COLLECTION_PAGE_SIZE)
.offset(offset);

View file

@ -62,10 +62,30 @@ export async function loader({ request }: Route.LoaderArgs) {
}
}
return { user: user ? { id: user.id, username: user.username } : null, locale };
// Pending follow-request count for the navbar badge. Cheap (a single
// `count(*) WHERE accepted_at IS NULL`); only computed for signed-in
// users. Hidden behind a dynamic import so the root layout doesn't
// pull in the follow module on anonymous renders.
let pendingFollowRequests = 0;
if (user) {
const { countPendingFollowRequests } = await import("./lib/follow.server.ts");
pendingFollowRequests = await countPendingFollowRequests(user.id);
}
return {
user: user ? { id: user.id, username: user.username } : null,
locale,
pendingFollowRequests,
};
}
function NavBar({ user }: { user: { id: string; username: string } | null }) {
function NavBar({
user,
pendingFollowRequests,
}: {
user: { id: string; username: string } | null;
pendingFollowRequests: number;
}) {
const { t } = useTranslation("journal");
const location = useLocation();
@ -103,6 +123,18 @@ function NavBar({ user }: { user: { id: string; username: string } | null }) {
<div className="flex items-center gap-4">
{user ? (
<>
<Link
to="/follows/requests"
className={`relative ${linkClass("/follows/requests")}`}
title={t("social.requests.title")}
>
{t("social.requests.title")}
{pendingFollowRequests > 0 && (
<span className="ml-1 inline-flex h-5 min-w-[1.25rem] items-center justify-center rounded-full bg-red-500 px-1.5 text-xs font-semibold text-white">
{pendingFollowRequests}
</span>
)}
</Link>
<Link
to={`/users/${user.username}`}
className={linkClass(`/users/${user.username}`)}
@ -143,6 +175,7 @@ function NavBar({ user }: { user: { id: string; username: string } | null }) {
export default function App({ loaderData }: Route.ComponentProps) {
const user = loaderData?.user;
const locale = loaderData?.locale ?? "en";
const pendingFollowRequests = loaderData?.pendingFollowRequests ?? 0;
useEffect(() => {
if (user) {
initSentryClient();
@ -156,7 +189,7 @@ export default function App({ loaderData }: Route.ComponentProps) {
return (
<LocaleProvider locale={locale}>
<AlphaBanner />
<NavBar user={user ?? null} />
<NavBar user={user ?? null} pendingFollowRequests={pendingFollowRequests} />
<Outlet />
<Footer />
</LocaleProvider>

View file

@ -27,6 +27,9 @@ export default [
route("users/:username/following", "routes/users.$username.following.tsx"),
route("api/users/:username/follow", "routes/api.users.$username.follow.ts"),
route("api/users/:username/unfollow", "routes/api.users.$username.unfollow.ts"),
route("follows/requests", "routes/follows.requests.tsx"),
route("api/follows/:id/approve", "routes/api.follows.$id.approve.ts"),
route("api/follows/:id/reject", "routes/api.follows.$id.reject.ts"),
route("feed", "routes/feed.tsx"),
route("settings", "routes/settings.tsx"),
route("api/settings/profile", "routes/api.settings.profile.ts"),

View file

@ -0,0 +1,19 @@
import { data } from "react-router";
import type { Route } from "./+types/api.follows.$id.approve";
import { getSessionUser } from "~/lib/auth.server";
import { approveFollowRequest } from "~/lib/follow.server";
export async function action({ request, params }: Route.ActionArgs) {
if (request.method !== "POST") {
return data({ error: "Method not allowed" }, { status: 405 });
}
const user = await getSessionUser(request);
if (!user) return data({ error: "Unauthorized" }, { status: 401 });
const id = params.id;
if (!id) return data({ error: "id required" }, { status: 400 });
const ok = await approveFollowRequest(user.id, id);
if (!ok) return data({ error: "Not found" }, { status: 404 });
return data({ ok: true });
}

View file

@ -0,0 +1,19 @@
import { data } from "react-router";
import type { Route } from "./+types/api.follows.$id.reject";
import { getSessionUser } from "~/lib/auth.server";
import { rejectFollowRequest } from "~/lib/follow.server";
export async function action({ request, params }: Route.ActionArgs) {
if (request.method !== "POST") {
return data({ error: "Method not allowed" }, { status: 405 });
}
const user = await getSessionUser(request);
if (!user) return data({ error: "Unauthorized" }, { status: 401 });
const id = params.id;
if (!id) return data({ error: "id required" }, { status: 400 });
const ok = await rejectFollowRequest(user.id, id);
if (!ok) return data({ error: "Not found" }, { status: 404 });
return data({ ok: true });
}

View file

@ -0,0 +1,99 @@
import { data, redirect, useFetcher } from "react-router";
import { useTranslation } from "react-i18next";
import type { Route } from "./+types/follows.requests";
import { getSessionUser } from "~/lib/auth.server";
import { listPendingFollowRequests } from "~/lib/follow.server";
import { ClientDate } from "~/components/ClientDate";
export async function loader({ request }: Route.LoaderArgs) {
const user = await getSessionUser(request);
if (!user) throw redirect("/auth/login");
const requests = await listPendingFollowRequests(user.id);
return data({
requests: requests.map((r) => ({
id: r.id,
followerUsername: r.followerUsername,
followerDisplayName: r.followerDisplayName,
followerDomain: r.followerDomain,
createdAt: r.createdAt.toISOString(),
})),
});
}
export function meta(_args: Route.MetaArgs) {
return [{ title: "Follow requests — trails.cool" }];
}
interface RequestRow {
id: string;
followerUsername: string;
followerDisplayName: string | null;
followerDomain: string;
createdAt: string;
}
function RequestItem({ row }: { row: RequestRow }) {
const { t } = useTranslation("journal");
const approve = useFetcher();
const reject = useFetcher();
const inFlight = approve.state !== "idle" || reject.state !== "idle";
return (
<li className="flex items-center justify-between px-4 py-3">
<div>
<a
href={`/users/${row.followerUsername}`}
className="text-sm font-medium text-gray-900 hover:underline"
>
{row.followerDisplayName ?? row.followerUsername}
</a>
<p className="text-xs text-gray-500">
@{row.followerUsername}@{row.followerDomain} ·{" "}
<ClientDate iso={row.createdAt} />
</p>
</div>
<div className="flex gap-2">
<reject.Form method="post" action={`/api/follows/${row.id}/reject`}>
<button
type="submit"
disabled={inFlight}
className="rounded-md border border-gray-300 bg-white px-3 py-1.5 text-sm font-medium text-gray-700 hover:bg-gray-50 disabled:opacity-50"
>
{t("social.requests.reject")}
</button>
</reject.Form>
<approve.Form method="post" action={`/api/follows/${row.id}/approve`}>
<button
type="submit"
disabled={inFlight}
className="rounded-md bg-blue-600 px-3 py-1.5 text-sm font-medium text-white hover:bg-blue-700 disabled:opacity-50"
>
{t("social.requests.approve")}
</button>
</approve.Form>
</div>
</li>
);
}
export default function FollowRequests({ loaderData }: Route.ComponentProps) {
const { requests } = loaderData;
const { t } = useTranslation("journal");
return (
<div className="mx-auto max-w-2xl px-4 py-8">
<h1 className="text-2xl font-bold text-gray-900">{t("social.requests.title")}</h1>
{requests.length === 0 ? (
<p className="mt-8 text-center text-gray-500">{t("social.requests.empty")}</p>
) : (
<ul className="mt-6 divide-y divide-gray-200 rounded-lg border border-gray-200 bg-white">
{requests.map((r) => (
<RequestItem key={r.id} row={r} />
))}
</ul>
)}
</div>
);
}

View file

@ -20,33 +20,36 @@ export async function loader({ params, request }: Route.LoaderArgs) {
throw data({ error: "User not found" }, { status: 404 });
}
const [publicRoutes, publicActivities, currentUser, followers, following] = await Promise.all([
listPublicRoutesForOwner(user.id),
listPublicActivitiesForOwner(user.id),
getSessionUser(request),
countFollowers(user.id),
countFollowing(user.id),
]);
const currentUser = await getSessionUser(request);
const isOwn = currentUser?.id === user.id;
// Profile-visibility gate: a `private` profile 404s for everyone but
// the owner, regardless of how much public content they have.
if (!isOwn && user.profileVisibility !== "public") {
throw data({ error: "User not found" }, { status: 404 });
}
// 404 for public-but-empty profiles to prevent account enumeration.
// Owners still see their own profile even when empty.
if (!isOwn && publicRoutes.length === 0 && publicActivities.length === 0) {
throw data({ error: "User not found" }, { status: 404 });
}
// Follow state for non-owner viewers (null when anonymous).
// Follow state: null when anonymous or owner; { following, pending }
// otherwise.
const followState = !isOwn && currentUser
? await getFollowState(currentUser.id, user.username)
: null;
// Locked-account model: a private profile renders a stub for
// non-followers (anonymous OR signed-in but not an accepted follower).
// Owners always see their own profile in full.
const canSeeContent =
isOwn ||
user.profileVisibility === "public" ||
(followState !== null && followState.following === true);
// For private-stub viewers we still want counts (cheap) but skip the
// expensive content fetches.
const [followers, following] = await Promise.all([
countFollowers(user.id),
countFollowing(user.id),
]);
const [publicRoutes, publicActivities] = canSeeContent
? await Promise.all([
listPublicRoutesForOwner(user.id),
listPublicActivitiesForOwner(user.id),
])
: [[], []];
// Demo-account badge: true when this profile matches the instance's
// configured demo persona username. Computed server-side so we don't
// ship the persona config through client HTML.
@ -84,6 +87,7 @@ export async function loader({ params, request }: Route.LoaderArgs) {
followState,
isLoggedIn: currentUser !== null,
profileVisibility: user.profileVisibility,
canSeeContent,
});
}
@ -109,7 +113,7 @@ export function meta({ data: loaderData }: Route.MetaArgs) {
}
export default function UserProfilePage({ loaderData }: Route.ComponentProps) {
const { user, routes, activities, isOwn, isDemoUser, followers, following, followState, isLoggedIn } = loaderData;
const { user, routes, activities, isOwn, isDemoUser, followers, following, followState, isLoggedIn, canSeeContent } = loaderData;
const { t } = useTranslation("journal");
return (
@ -123,6 +127,14 @@ export default function UserProfilePage({ loaderData }: Route.ComponentProps) {
<h1 className="text-2xl font-bold text-gray-900">
{user.displayName ?? user.username}
</h1>
{loaderData.profileVisibility === "private" && !isOwn && (
<span
className="rounded-full bg-gray-200 px-2 py-0.5 text-xs font-medium text-gray-700"
title={t("profile.lockedTitle")}
>
🔒 {t("profile.lockedBadge")}
</span>
)}
{isDemoUser && (
<span className="rounded-full bg-amber-100 px-2 py-0.5 text-xs font-medium text-amber-800">
{t("demo.badge")}
@ -153,11 +165,34 @@ export default function UserProfilePage({ loaderData }: Route.ComponentProps) {
{!isOwn && isLoggedIn && (
<FollowButton
username={user.username}
isPrivateTarget={loaderData.profileVisibility === "private"}
initialState={followState}
/>
)}
</div>
{!canSeeContent && (
<div className="mt-8 rounded-lg border border-gray-200 bg-gray-50 p-6 text-center">
<p className="text-2xl" aria-hidden="true">🔒</p>
<p className="mt-2 text-sm font-medium text-gray-900">
{t("profile.privateStub.heading")}
</p>
<p className="mt-1 text-sm text-gray-500">
{isLoggedIn
? t("profile.privateStub.bodyAuth")
: t("profile.privateStub.bodyAnon")}
</p>
{!isLoggedIn && (
<a
href="/auth/login"
className="mt-4 inline-block rounded-md border border-gray-300 bg-white px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50"
>
{t("auth.login")}
</a>
)}
</div>
)}
{isOwn && loaderData.profileVisibility === "private" && (
<div className="mt-6 rounded-md border border-amber-200 bg-amber-50 p-3 text-sm text-amber-800">
{t("profile.privateNote")}{" "}
@ -175,6 +210,8 @@ export default function UserProfilePage({ loaderData }: Route.ComponentProps) {
</div>
)}
{canSeeContent && (
<>
<section className="mt-8">
<h2 className="text-lg font-semibold text-gray-900">
{t("routes.title")} ({routes.length})
@ -238,6 +275,8 @@ export default function UserProfilePage({ loaderData }: Route.ComponentProps) {
</ul>
)}
</section>
</>
)}
</div>
);
}