feat: user profiles, subscriptions, and subscription feed
Some checks failed
CI / Scraper / Lint (push) Failing after 8s
CI / Scraper / Test (push) Successful in 11s
CI / Scraper / Lint (pull_request) Failing after 7s
CI / Scraper / Test (pull_request) Successful in 9s
CI / Scraper / Docker Push (push) Has been skipped
CI / Scraper / Docker Push (pull_request) Has been skipped
CI / UI / Build (push) Successful in 23s
CI / UI / Build (pull_request) Successful in 22s
CI / UI / Docker Push (pull_request) Has been skipped
CI / UI / Docker Push (push) Successful in 32s
iOS CI / Build (pull_request) Successful in 1m52s
iOS CI / Test (pull_request) Successful in 3m50s
Some checks failed
CI / Scraper / Lint (push) Failing after 8s
CI / Scraper / Test (push) Successful in 11s
CI / Scraper / Lint (pull_request) Failing after 7s
CI / Scraper / Test (pull_request) Successful in 9s
CI / Scraper / Docker Push (push) Has been skipped
CI / Scraper / Docker Push (pull_request) Has been skipped
CI / UI / Build (push) Successful in 23s
CI / UI / Build (pull_request) Successful in 22s
CI / UI / Docker Push (pull_request) Has been skipped
CI / UI / Docker Push (push) Successful in 32s
iOS CI / Build (pull_request) Successful in 1m52s
iOS CI / Test (pull_request) Successful in 3m50s
- PocketBase: new user_subscriptions collection (follower_id, followee_id) - pocketbase.ts: subscribe/unsubscribe/getFollowingIds/getPublicProfile/ getUserPublicLibrary/getUserCurrentlyReading/getSubscriptionFeed helpers - GET /api/users/[username] — public profile with subscription state - POST/DELETE /api/users/[username]/subscribe — follow/unfollow - /users/[username] — public profile page: avatar, stats, follow button, currently reading grid, full library grid - CommentsSection: usernames are now links to /users/[username] - Home page: 'From People You Follow' section powered by subscription feed
This commit is contained in:
@@ -449,6 +449,16 @@ func (s *PocketBaseStore) EnsureCollections(ctx context.Context) error {
|
||||
{"name": "vote", "type": "text", "required": true}, // "up" | "down"
|
||||
},
|
||||
},
|
||||
{
|
||||
// follower_id follows followee_id
|
||||
"name": "user_subscriptions",
|
||||
"type": "base",
|
||||
"fields": []map[string]interface{}{
|
||||
{"name": "follower_id", "type": "text", "required": true},
|
||||
{"name": "followee_id", "type": "text", "required": true},
|
||||
{"name": "created", "type": "date"},
|
||||
},
|
||||
},
|
||||
}
|
||||
for _, col := range collections {
|
||||
name, _ := col["name"].(string)
|
||||
|
||||
@@ -354,7 +354,11 @@
|
||||
<span class="text-[9px] font-semibold text-zinc-300 leading-none">{initials(comment.username)}</span>
|
||||
</div>
|
||||
{/if}
|
||||
<span class="text-sm font-medium text-zinc-200">{comment.username || 'Anonymous'}</span>
|
||||
{#if comment.username}
|
||||
<a href="/users/{comment.username}" class="text-sm font-medium text-zinc-200 hover:text-amber-400 transition-colors">{comment.username}</a>
|
||||
{:else}
|
||||
<span class="text-sm font-medium text-zinc-400">Anonymous</span>
|
||||
{/if}
|
||||
<span class="text-zinc-600 text-xs">·</span>
|
||||
<span class="text-xs text-zinc-500">{formatDate(comment.created)}</span>
|
||||
</div>
|
||||
@@ -491,7 +495,11 @@
|
||||
<span class="text-[8px] font-semibold text-zinc-300 leading-none">{initials(reply.username)}</span>
|
||||
</div>
|
||||
{/if}
|
||||
<span class="text-xs font-medium text-zinc-300">{reply.username || 'Anonymous'}</span>
|
||||
{#if reply.username}
|
||||
<a href="/users/{reply.username}" class="text-xs font-medium text-zinc-300 hover:text-amber-400 transition-colors">{reply.username}</a>
|
||||
{:else}
|
||||
<span class="text-xs font-medium text-zinc-400">Anonymous</span>
|
||||
{/if}
|
||||
<span class="text-zinc-600 text-xs">·</span>
|
||||
<span class="text-xs text-zinc-500">{formatDate(reply.created)}</span>
|
||||
</div>
|
||||
|
||||
@@ -1079,3 +1079,231 @@ export async function getMyVotes(
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
// ─── User subscriptions ───────────────────────────────────────────────────────
|
||||
|
||||
export interface UserSubscription {
|
||||
id: string;
|
||||
follower_id: string;
|
||||
followee_id: string;
|
||||
created: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the subscription record if follower_id follows followee_id, else null.
|
||||
*/
|
||||
export async function getSubscription(
|
||||
followerId: string,
|
||||
followeeId: string
|
||||
): Promise<UserSubscription | null> {
|
||||
const filter = encodeURIComponent(`follower_id="${followerId}"&&followee_id="${followeeId}"`);
|
||||
const res = await pbGet<{ items: UserSubscription[]; totalItems: number }>(
|
||||
`/api/collections/user_subscriptions/records?filter=${filter}&perPage=1`
|
||||
).catch(() => null);
|
||||
return res?.items?.[0] ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Subscribe follower_id to followee_id. No-ops if already subscribed.
|
||||
* Returns the subscription record.
|
||||
*/
|
||||
export async function subscribe(followerId: string, followeeId: string): Promise<void> {
|
||||
const existing = await getSubscription(followerId, followeeId);
|
||||
if (existing) return;
|
||||
const res = await pbPost('/api/collections/user_subscriptions/records', {
|
||||
follower_id: followerId,
|
||||
followee_id: followeeId,
|
||||
created: new Date().toISOString()
|
||||
});
|
||||
if (!res.ok) {
|
||||
const body = await res.text().catch(() => '');
|
||||
throw new Error(`Failed to subscribe: ${res.status} — ${body}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Unsubscribe follower_id from followee_id. No-ops if not subscribed.
|
||||
*/
|
||||
export async function unsubscribe(followerId: string, followeeId: string): Promise<void> {
|
||||
const existing = await getSubscription(followerId, followeeId);
|
||||
if (!existing) return;
|
||||
const token = await getToken();
|
||||
await fetch(`${PB_URL}/api/collections/user_subscriptions/records/${existing.id}`, {
|
||||
method: 'DELETE',
|
||||
headers: { Authorization: `Bearer ${token}` }
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the list of user IDs that followerId is subscribed to.
|
||||
*/
|
||||
export async function getFollowingIds(followerId: string): Promise<string[]> {
|
||||
const items = await listAll<UserSubscription>(
|
||||
'user_subscriptions',
|
||||
`follower_id="${followerId}"`,
|
||||
'-created'
|
||||
).catch(() => [] as UserSubscription[]);
|
||||
return items.map((s) => s.followee_id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the count of subscribers (followers) for a given user.
|
||||
*/
|
||||
export async function getFollowerCount(followeeId: string): Promise<number> {
|
||||
return countCollection('user_subscriptions', `followee_id="${followeeId}"`).catch(() => 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the count of accounts a user is following.
|
||||
*/
|
||||
export async function getFollowingCount(followerId: string): Promise<number> {
|
||||
return countCollection('user_subscriptions', `follower_id="${followerId}"`).catch(() => 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Public profile data for a user.
|
||||
*/
|
||||
export interface PublicProfile {
|
||||
id: string;
|
||||
username: string;
|
||||
avatar_url?: string;
|
||||
created: string;
|
||||
followerCount: number;
|
||||
followingCount: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a user's public profile (no sensitive fields) by username.
|
||||
*/
|
||||
export async function getPublicProfile(username: string): Promise<PublicProfile | null> {
|
||||
const user = await getUserByUsername(username);
|
||||
if (!user) return null;
|
||||
const [followerCount, followingCount] = await Promise.all([
|
||||
getFollowerCount(user.id),
|
||||
getFollowingCount(user.id)
|
||||
]);
|
||||
return {
|
||||
id: user.id,
|
||||
username: user.username,
|
||||
avatar_url: user.avatar_url,
|
||||
created: user.created,
|
||||
followerCount,
|
||||
followingCount
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a user's public library: books they have saved or are reading.
|
||||
* Only includes books with progress or explicit saves (user_library).
|
||||
*/
|
||||
export async function getUserPublicLibrary(
|
||||
userId: string
|
||||
): Promise<Array<{ book: Book; chapter: number | null; saved: boolean }>> {
|
||||
const [allBooks, progressList, savedEntries] = await Promise.all([
|
||||
listBooks(),
|
||||
listAll<Progress>('progress', `user_id="${userId}"`, '-updated').catch(() => [] as Progress[]),
|
||||
listAll<{ id: string; slug: string; saved_at: string }>(
|
||||
'user_library',
|
||||
`user_id="${userId}"`,
|
||||
'-saved_at'
|
||||
).catch(() => [] as { id: string; slug: string; saved_at: string }[])
|
||||
]);
|
||||
|
||||
const bookMap = new Map<string, Book>(allBooks.map((b) => [b.slug, b]));
|
||||
const result: Array<{ book: Book; chapter: number | null; saved: boolean }> = [];
|
||||
const seen = new Set<string>();
|
||||
|
||||
// Books with progress first (most recently read)
|
||||
for (const p of progressList) {
|
||||
const book = bookMap.get(p.slug);
|
||||
if (!book || seen.has(p.slug)) continue;
|
||||
seen.add(p.slug);
|
||||
result.push({ book, chapter: p.chapter, saved: false });
|
||||
}
|
||||
|
||||
// Saved-only books next
|
||||
for (const e of savedEntries) {
|
||||
const book = bookMap.get(e.slug);
|
||||
if (!book || seen.has(e.slug)) continue;
|
||||
seen.add(e.slug);
|
||||
result.push({ book, chapter: null, saved: true });
|
||||
}
|
||||
|
||||
// Mark saved flag for books that are both in progress AND saved
|
||||
const savedSlugs = new Set(savedEntries.map((e) => e.slug));
|
||||
return result.map((r) => ({ ...r, saved: savedSlugs.has(r.book.slug) }));
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the currently-reading books (books with progress, not completed)
|
||||
* for a given user ID.
|
||||
*/
|
||||
export async function getUserCurrentlyReading(
|
||||
userId: string
|
||||
): Promise<Array<{ book: Book; chapter: number }>> {
|
||||
const [allBooks, progressList] = await Promise.all([
|
||||
listBooks(),
|
||||
listAll<Progress>('progress', `user_id="${userId}"`, '-updated').catch(() => [] as Progress[])
|
||||
]);
|
||||
const bookMap = new Map<string, Book>(allBooks.map((b) => [b.slug, b]));
|
||||
return progressList
|
||||
.filter((p) => {
|
||||
const book = bookMap.get(p.slug);
|
||||
return book && p.chapter > 0 && p.chapter < book.total_chapters;
|
||||
})
|
||||
.slice(0, 10)
|
||||
.map((p) => ({ book: bookMap.get(p.slug)!, chapter: p.chapter }));
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns recently-updated books from ALL users that followerId is subscribed to.
|
||||
* Deduplicates across followed users; sorts by most recently updated.
|
||||
*/
|
||||
export async function getSubscriptionFeed(
|
||||
followerId: string,
|
||||
limit = 12
|
||||
): Promise<Array<{ book: Book; readerUsername: string }>> {
|
||||
const followingIds = await getFollowingIds(followerId);
|
||||
if (followingIds.length === 0) return [];
|
||||
|
||||
// Fetch all users we follow (for display names)
|
||||
const token = await getToken();
|
||||
const userFetches = followingIds.map((id) =>
|
||||
fetch(`${PB_URL}/api/collections/app_users/records/${id}`, {
|
||||
headers: { Authorization: `Bearer ${token}` }
|
||||
})
|
||||
.then((r) => (r.ok ? (r.json() as Promise<User>) : null))
|
||||
.catch(() => null)
|
||||
);
|
||||
const users = (await Promise.all(userFetches)).filter(Boolean) as User[];
|
||||
const userMap = new Map<string, User>(users.map((u) => [u.id, u]));
|
||||
|
||||
// Fetch progress for each followed user
|
||||
const progressFetches = followingIds.map((id) =>
|
||||
listAll<Progress>('progress', `user_id="${id}"`, '-updated').catch(() => [] as Progress[])
|
||||
);
|
||||
const allProgressArrays = await Promise.all(progressFetches);
|
||||
|
||||
const allBooks = await listBooks();
|
||||
const bookMap = new Map<string, Book>(allBooks.map((b) => [b.slug, b]));
|
||||
|
||||
// Merge: per slug take the most-recent progress entry
|
||||
const seen = new Set<string>();
|
||||
const feed: Array<{ book: Book; readerUsername: string; updated: string }> = [];
|
||||
|
||||
for (let i = 0; i < followingIds.length; i++) {
|
||||
const uid = followingIds[i];
|
||||
const username = userMap.get(uid)?.username ?? 'unknown';
|
||||
for (const p of allProgressArrays[i]) {
|
||||
if (seen.has(p.slug)) continue;
|
||||
const book = bookMap.get(p.slug);
|
||||
if (!book) continue;
|
||||
seen.add(p.slug);
|
||||
feed.push({ book, readerUsername: username, updated: p.updated });
|
||||
}
|
||||
}
|
||||
|
||||
// Sort by most recently read across all followed users
|
||||
feed.sort((a, b) => b.updated.localeCompare(a.updated));
|
||||
return feed.slice(0, limit).map(({ book, readerUsername }) => ({ book, readerUsername }));
|
||||
}
|
||||
|
||||
@@ -3,7 +3,8 @@ import {
|
||||
listBooks,
|
||||
recentlyAddedBooks,
|
||||
allProgress,
|
||||
getHomeStats
|
||||
getHomeStats,
|
||||
getSubscriptionFeed
|
||||
} from '$lib/server/pocketbase';
|
||||
import { log } from '$lib/server/logger';
|
||||
import type { Book, Progress } from '$lib/server/pocketbase';
|
||||
@@ -38,9 +39,18 @@ export const load: PageServerLoad = async ({ locals }) => {
|
||||
const inProgressSlugs = new Set(continueReading.map((c) => c.book.slug));
|
||||
const recentlyUpdated = recentBooks.filter((b) => !inProgressSlugs.has(b.slug)).slice(0, 6);
|
||||
|
||||
// Subscription feed — only when logged in
|
||||
const subscriptionFeed = locals.user
|
||||
? await getSubscriptionFeed(locals.user.id, 12).catch((e) => {
|
||||
log.error('home', 'failed to load subscription feed', { err: String(e) });
|
||||
return [] as Awaited<ReturnType<typeof getSubscriptionFeed>>;
|
||||
})
|
||||
: [];
|
||||
|
||||
return {
|
||||
continueReading,
|
||||
recentlyUpdated,
|
||||
subscriptionFeed,
|
||||
stats: {
|
||||
...stats,
|
||||
booksInProgress: continueReading.length
|
||||
|
||||
@@ -147,3 +147,56 @@
|
||||
</a>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<!-- From Subscriptions -->
|
||||
{#if data.subscriptionFeed.length > 0}
|
||||
<section class="mb-10">
|
||||
<div class="flex items-baseline justify-between mb-3">
|
||||
<h2 class="text-lg font-bold text-zinc-100">From People You Follow</h2>
|
||||
</div>
|
||||
<div class="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-6 gap-4">
|
||||
{#each data.subscriptionFeed as { book, readerUsername }}
|
||||
{@const genres = parseGenres(book.genres)}
|
||||
<a
|
||||
href="/books/{book.slug}"
|
||||
class="group flex flex-col rounded-lg overflow-hidden bg-zinc-800 hover:bg-zinc-700 transition-colors border border-zinc-700 hover:border-zinc-500"
|
||||
>
|
||||
<div class="aspect-[2/3] bg-zinc-900 overflow-hidden">
|
||||
{#if book.cover}
|
||||
<img
|
||||
src={book.cover}
|
||||
alt={book.title}
|
||||
class="w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"
|
||||
loading="lazy"
|
||||
/>
|
||||
{:else}
|
||||
<div class="w-full h-full flex items-center justify-center text-zinc-600">
|
||||
<svg class="w-10 h-10" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5"
|
||||
d="M12 6.253v13m0-13C10.832 5.477 9.246 5 7.5 5S4.168 5.477 3 6.253v13C4.168 18.477 5.754 18 7.5 18s3.332.477 4.5 1.253m0-13C13.168 5.477 14.754 5 16.5 5c1.747 0 3.332.477 4.5 1.253v13C19.832 18.477 18.247 18 16.5 18c-1.746 0-3.332.477-4.5 1.253" />
|
||||
</svg>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
<div class="p-2 flex flex-col gap-1">
|
||||
<h3 class="text-xs font-semibold text-zinc-100 line-clamp-2 leading-snug">{book.title ?? ''}</h3>
|
||||
{#if book.author}
|
||||
<p class="text-xs text-zinc-400 truncate">{book.author}</p>
|
||||
{/if}
|
||||
<!-- Reader attribution -->
|
||||
<p class="text-xs text-zinc-600 truncate mt-0.5">
|
||||
via <span class="text-amber-500/70">{readerUsername}</span>
|
||||
</p>
|
||||
{#if genres.length > 0}
|
||||
<div class="flex flex-wrap gap-1 mt-auto pt-1">
|
||||
{#each genres.slice(0, 1) as genre}
|
||||
<span class="text-xs px-1 py-0.5 rounded bg-zinc-900 text-zinc-500">{genre}</span>
|
||||
{/each}
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
</a>
|
||||
{/each}
|
||||
</div>
|
||||
</section>
|
||||
{/if}
|
||||
|
||||
46
ui/src/routes/api/users/[username]/+server.ts
Normal file
46
ui/src/routes/api/users/[username]/+server.ts
Normal file
@@ -0,0 +1,46 @@
|
||||
import { json, error } from '@sveltejs/kit';
|
||||
import type { RequestHandler } from './$types';
|
||||
import { getPublicProfile, getSubscription } from '$lib/server/pocketbase';
|
||||
import { presignAvatarUrl } from '$lib/server/minio';
|
||||
import { log } from '$lib/server/logger';
|
||||
|
||||
/**
|
||||
* GET /api/users/[username]
|
||||
* Returns public profile info + whether the current user is subscribed.
|
||||
*/
|
||||
export const GET: RequestHandler = async ({ params, locals }) => {
|
||||
const { username } = params;
|
||||
|
||||
try {
|
||||
const profile = await getPublicProfile(username);
|
||||
if (!profile) error(404, `User "${username}" not found`);
|
||||
|
||||
// Resolve avatar presigned URL if set
|
||||
let avatarUrl: string | null = null;
|
||||
if (profile.avatar_url) {
|
||||
avatarUrl = await presignAvatarUrl(profile.id).catch(() => null);
|
||||
}
|
||||
|
||||
// Is the current logged-in user subscribed?
|
||||
let isSubscribed = false;
|
||||
if (locals.user && locals.user.id !== profile.id) {
|
||||
const sub = await getSubscription(locals.user.id, profile.id).catch(() => null);
|
||||
isSubscribed = !!sub;
|
||||
}
|
||||
|
||||
return json({
|
||||
id: profile.id,
|
||||
username: profile.username,
|
||||
avatarUrl,
|
||||
created: profile.created,
|
||||
followerCount: profile.followerCount,
|
||||
followingCount: profile.followingCount,
|
||||
isSubscribed,
|
||||
isSelf: locals.user?.id === profile.id
|
||||
});
|
||||
} catch (e) {
|
||||
if ((e as { status?: number }).status === 404) throw e;
|
||||
log.error('api/users', 'failed to load profile', { username, err: String(e) });
|
||||
error(500, 'Failed to load profile');
|
||||
}
|
||||
};
|
||||
48
ui/src/routes/api/users/[username]/subscribe/+server.ts
Normal file
48
ui/src/routes/api/users/[username]/subscribe/+server.ts
Normal file
@@ -0,0 +1,48 @@
|
||||
import { json, error } from '@sveltejs/kit';
|
||||
import type { RequestHandler } from './$types';
|
||||
import {
|
||||
getUserByUsername,
|
||||
subscribe,
|
||||
unsubscribe,
|
||||
getSubscription
|
||||
} from '$lib/server/pocketbase';
|
||||
import { log } from '$lib/server/logger';
|
||||
|
||||
/**
|
||||
* POST /api/users/[username]/subscribe — subscribe to a user
|
||||
* DELETE /api/users/[username]/subscribe — unsubscribe
|
||||
* Requires authentication.
|
||||
*/
|
||||
export const POST: RequestHandler = async ({ params, locals }) => {
|
||||
if (!locals.user) error(401, 'Login required');
|
||||
|
||||
const { username } = params;
|
||||
const target = await getUserByUsername(username).catch(() => null);
|
||||
if (!target) error(404, `User "${username}" not found`);
|
||||
if (locals.user.id === target.id) error(400, 'Cannot subscribe to yourself');
|
||||
|
||||
try {
|
||||
await subscribe(locals.user.id, target.id);
|
||||
const sub = await getSubscription(locals.user.id, target.id);
|
||||
return json({ subscribed: true, subId: sub?.id ?? null });
|
||||
} catch (e) {
|
||||
log.error('api/users/subscribe', 'subscribe failed', { username, err: String(e) });
|
||||
error(500, 'Failed to subscribe');
|
||||
}
|
||||
};
|
||||
|
||||
export const DELETE: RequestHandler = async ({ params, locals }) => {
|
||||
if (!locals.user) error(401, 'Login required');
|
||||
|
||||
const { username } = params;
|
||||
const target = await getUserByUsername(username).catch(() => null);
|
||||
if (!target) error(404, `User "${username}" not found`);
|
||||
|
||||
try {
|
||||
await unsubscribe(locals.user.id, target.id);
|
||||
return json({ subscribed: false });
|
||||
} catch (e) {
|
||||
log.error('api/users/subscribe', 'unsubscribe failed', { username, err: String(e) });
|
||||
error(500, 'Failed to unsubscribe');
|
||||
}
|
||||
};
|
||||
59
ui/src/routes/users/[username]/+page.server.ts
Normal file
59
ui/src/routes/users/[username]/+page.server.ts
Normal file
@@ -0,0 +1,59 @@
|
||||
import { error } from '@sveltejs/kit';
|
||||
import type { PageServerLoad } from './$types';
|
||||
import {
|
||||
getPublicProfile,
|
||||
getSubscription,
|
||||
getUserPublicLibrary,
|
||||
getUserCurrentlyReading
|
||||
} from '$lib/server/pocketbase';
|
||||
import { presignAvatarUrl } from '$lib/server/minio';
|
||||
import { log } from '$lib/server/logger';
|
||||
|
||||
export const load: PageServerLoad = async ({ params, locals }) => {
|
||||
const { username } = params;
|
||||
|
||||
const profile = await getPublicProfile(username).catch(() => null);
|
||||
if (!profile) error(404, `User "${username}" not found`);
|
||||
|
||||
// Resolve avatar
|
||||
let avatarUrl: string | null = null;
|
||||
if (profile.avatar_url) {
|
||||
avatarUrl = await presignAvatarUrl(profile.id).catch(() => null);
|
||||
}
|
||||
|
||||
// Subscription state for the logged-in visitor
|
||||
let isSubscribed = false;
|
||||
const isSelf = locals.user?.id === profile.id;
|
||||
if (locals.user && !isSelf) {
|
||||
const sub = await getSubscription(locals.user.id, profile.id).catch(() => null);
|
||||
isSubscribed = !!sub;
|
||||
}
|
||||
|
||||
// Load public library + currently reading in parallel
|
||||
const [library, currentlyReading] = await Promise.all([
|
||||
getUserPublicLibrary(profile.id).catch((e) => {
|
||||
log.error('users/profile', 'getUserPublicLibrary failed', { username, err: String(e) });
|
||||
return [] as Awaited<ReturnType<typeof getUserPublicLibrary>>;
|
||||
}),
|
||||
getUserCurrentlyReading(profile.id).catch((e) => {
|
||||
log.error('users/profile', 'getUserCurrentlyReading failed', { username, err: String(e) });
|
||||
return [] as Awaited<ReturnType<typeof getUserCurrentlyReading>>;
|
||||
})
|
||||
]);
|
||||
|
||||
return {
|
||||
profile: {
|
||||
id: profile.id,
|
||||
username: profile.username,
|
||||
created: profile.created,
|
||||
followerCount: profile.followerCount,
|
||||
followingCount: profile.followingCount
|
||||
},
|
||||
avatarUrl,
|
||||
isSubscribed,
|
||||
isSelf,
|
||||
isLoggedIn: !!locals.user,
|
||||
library,
|
||||
currentlyReading
|
||||
};
|
||||
};
|
||||
224
ui/src/routes/users/[username]/+page.svelte
Normal file
224
ui/src/routes/users/[username]/+page.svelte
Normal file
@@ -0,0 +1,224 @@
|
||||
<script lang="ts">
|
||||
import type { PageData } from './$types';
|
||||
|
||||
let { data }: { data: PageData } = $props();
|
||||
|
||||
// ── Subscribe / unsubscribe ──────────────────────────────────────────────────
|
||||
let subscribed = $state(data.isSubscribed);
|
||||
let followerCount = $state(data.profile.followerCount);
|
||||
let subLoading = $state(false);
|
||||
|
||||
async function toggleSubscribe() {
|
||||
if (subLoading) return;
|
||||
subLoading = true;
|
||||
try {
|
||||
const method = subscribed ? 'DELETE' : 'POST';
|
||||
const res = await fetch(`/api/users/${data.profile.username}/subscribe`, { method });
|
||||
if (res.ok) {
|
||||
subscribed = !subscribed;
|
||||
followerCount += subscribed ? 1 : -1;
|
||||
}
|
||||
} finally {
|
||||
subLoading = false;
|
||||
}
|
||||
}
|
||||
|
||||
// ── Helpers ──────────────────────────────────────────────────────────────────
|
||||
function initials(username: string): string {
|
||||
return username.slice(0, 2).toUpperCase();
|
||||
}
|
||||
|
||||
function joinDate(iso: string): string {
|
||||
try {
|
||||
return new Date(iso).toLocaleDateString(undefined, { year: 'numeric', month: 'long' });
|
||||
} catch {
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
function parseGenres(genres: string[] | string | null | undefined): string[] {
|
||||
if (!genres) return [];
|
||||
if (Array.isArray(genres)) return genres;
|
||||
try {
|
||||
const parsed = JSON.parse(genres);
|
||||
return Array.isArray(parsed) ? parsed : [];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<svelte:head>
|
||||
<title>{data.profile.username} — libnovel</title>
|
||||
</svelte:head>
|
||||
|
||||
<!-- ── Header ────────────────────────────────────────────────────────────── -->
|
||||
<div class="flex items-start gap-5 mb-8">
|
||||
<!-- Avatar -->
|
||||
<div class="flex-shrink-0">
|
||||
{#if data.avatarUrl}
|
||||
<img
|
||||
src={data.avatarUrl}
|
||||
alt={data.profile.username}
|
||||
class="w-20 h-20 rounded-full object-cover ring-2 ring-zinc-700"
|
||||
/>
|
||||
{:else}
|
||||
<div class="w-20 h-20 rounded-full bg-zinc-700 flex items-center justify-center text-2xl font-bold text-zinc-300 ring-2 ring-zinc-600">
|
||||
{initials(data.profile.username)}
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<!-- Info -->
|
||||
<div class="flex-1 min-w-0">
|
||||
<h1 class="text-xl font-bold text-zinc-100 mb-0.5">{data.profile.username}</h1>
|
||||
<p class="text-xs text-zinc-500 mb-3">Joined {joinDate(data.profile.created)}</p>
|
||||
|
||||
<!-- Stats row -->
|
||||
<div class="flex gap-5 text-sm mb-4">
|
||||
<span>
|
||||
<span class="font-semibold text-zinc-100">{followerCount}</span>
|
||||
<span class="text-zinc-500 ml-1">followers</span>
|
||||
</span>
|
||||
<span>
|
||||
<span class="font-semibold text-zinc-100">{data.profile.followingCount}</span>
|
||||
<span class="text-zinc-500 ml-1">following</span>
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<!-- Subscribe button — only shown to logged-in visitors viewing someone else's profile -->
|
||||
{#if data.isLoggedIn && !data.isSelf}
|
||||
<button
|
||||
onclick={toggleSubscribe}
|
||||
disabled={subLoading}
|
||||
class="px-4 py-1.5 rounded-lg text-sm font-medium transition-colors disabled:opacity-50
|
||||
{subscribed
|
||||
? 'bg-zinc-700 text-zinc-300 hover:bg-zinc-600 border border-zinc-600'
|
||||
: 'bg-amber-400 text-zinc-900 hover:bg-amber-300'}"
|
||||
>
|
||||
{#if subLoading}
|
||||
…
|
||||
{:else if subscribed}
|
||||
Following
|
||||
{:else}
|
||||
Follow
|
||||
{/if}
|
||||
</button>
|
||||
{:else if !data.isLoggedIn}
|
||||
<a
|
||||
href="/login"
|
||||
class="inline-block px-4 py-1.5 rounded-lg text-sm font-medium bg-amber-400 text-zinc-900 hover:bg-amber-300 transition-colors"
|
||||
>
|
||||
Follow
|
||||
</a>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ── Currently Reading ─────────────────────────────────────────────────── -->
|
||||
{#if data.currentlyReading.length > 0}
|
||||
<section class="mb-10">
|
||||
<h2 class="text-base font-semibold text-zinc-200 mb-3">Currently Reading</h2>
|
||||
<div class="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-6 gap-4">
|
||||
{#each data.currentlyReading as { book, chapter }}
|
||||
<a
|
||||
href="/books/{book.slug}"
|
||||
class="group flex flex-col rounded-lg overflow-hidden bg-zinc-800 hover:bg-zinc-700 transition-colors border border-zinc-700 hover:border-zinc-500"
|
||||
>
|
||||
<div class="aspect-[2/3] bg-zinc-900 overflow-hidden relative">
|
||||
{#if book.cover}
|
||||
<img
|
||||
src={book.cover}
|
||||
alt={book.title}
|
||||
class="w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"
|
||||
loading="lazy"
|
||||
/>
|
||||
{:else}
|
||||
<div class="w-full h-full flex items-center justify-center text-zinc-600">
|
||||
<svg class="w-8 h-8" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M12 6.253v13m0-13C10.832 5.477 9.246 5 7.5 5S4.168 5.477 3 6.253v13C4.168 18.477 5.754 18 7.5 18s3.332.477 4.5 1.253m0-13C13.168 5.477 14.754 5 16.5 5c1.747 0 3.332.477 4.5 1.253v13C19.832 18.477 18.247 18 16.5 18c-1.746 0-3.332.477-4.5 1.253" />
|
||||
</svg>
|
||||
</div>
|
||||
{/if}
|
||||
<span class="absolute bottom-1.5 right-1.5 text-xs bg-amber-400 text-zinc-900 font-bold px-1.5 py-0.5 rounded">
|
||||
ch.{chapter}
|
||||
</span>
|
||||
</div>
|
||||
<div class="p-2">
|
||||
<h3 class="text-xs font-semibold text-zinc-100 line-clamp-2 leading-snug">{book.title}</h3>
|
||||
{#if book.author}
|
||||
<p class="text-xs text-zinc-500 truncate mt-0.5">{book.author}</p>
|
||||
{/if}
|
||||
</div>
|
||||
</a>
|
||||
{/each}
|
||||
</div>
|
||||
</section>
|
||||
{/if}
|
||||
|
||||
<!-- ── Library ───────────────────────────────────────────────────────────── -->
|
||||
{#if data.library.length > 0}
|
||||
<section class="mb-10">
|
||||
<h2 class="text-base font-semibold text-zinc-200 mb-3">
|
||||
Library
|
||||
<span class="text-zinc-500 font-normal text-sm ml-1">({data.library.length})</span>
|
||||
</h2>
|
||||
<div class="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-6 gap-4">
|
||||
{#each data.library as { book, chapter, saved }}
|
||||
{@const genres = parseGenres(book.genres)}
|
||||
<a
|
||||
href="/books/{book.slug}"
|
||||
class="group flex flex-col rounded-lg overflow-hidden bg-zinc-800 hover:bg-zinc-700 transition-colors border border-zinc-700 hover:border-zinc-500"
|
||||
>
|
||||
<div class="aspect-[2/3] bg-zinc-900 overflow-hidden relative">
|
||||
{#if book.cover}
|
||||
<img
|
||||
src={book.cover}
|
||||
alt={book.title}
|
||||
class="w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"
|
||||
loading="lazy"
|
||||
/>
|
||||
{:else}
|
||||
<div class="w-full h-full flex items-center justify-center text-zinc-600">
|
||||
<svg class="w-8 h-8" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M12 6.253v13m0-13C10.832 5.477 9.246 5 7.5 5S4.168 5.477 3 6.253v13C4.168 18.477 5.754 18 7.5 18s3.332.477 4.5 1.253m0-13C13.168 5.477 14.754 5 16.5 5c1.747 0 3.332.477 4.5 1.253v13C19.832 18.477 18.247 18 16.5 18c-1.746 0-3.332.477-4.5 1.253" />
|
||||
</svg>
|
||||
</div>
|
||||
{/if}
|
||||
{#if chapter}
|
||||
<span class="absolute bottom-1.5 right-1.5 text-xs bg-zinc-900/80 text-zinc-300 font-medium px-1.5 py-0.5 rounded">
|
||||
ch.{chapter}
|
||||
</span>
|
||||
{/if}
|
||||
{#if saved && !chapter}
|
||||
<span class="absolute top-1.5 right-1.5">
|
||||
<svg class="w-3.5 h-3.5 text-amber-400" fill="currentColor" viewBox="0 0 24 24">
|
||||
<path d="M5 3a2 2 0 00-2 2v16l9-4 9 4V5a2 2 0 00-2-2H5z"/>
|
||||
</svg>
|
||||
</span>
|
||||
{/if}
|
||||
</div>
|
||||
<div class="p-2">
|
||||
<h3 class="text-xs font-semibold text-zinc-100 line-clamp-2 leading-snug">{book.title}</h3>
|
||||
{#if book.author}
|
||||
<p class="text-xs text-zinc-500 truncate mt-0.5">{book.author}</p>
|
||||
{/if}
|
||||
{#if genres.length > 0}
|
||||
<p class="text-xs text-zinc-600 truncate mt-0.5">{genres[0]}</p>
|
||||
{/if}
|
||||
</div>
|
||||
</a>
|
||||
{/each}
|
||||
</div>
|
||||
</section>
|
||||
{/if}
|
||||
|
||||
<!-- ── Empty state ───────────────────────────────────────────────────────── -->
|
||||
{#if data.library.length === 0 && data.currentlyReading.length === 0}
|
||||
<div class="py-16 text-center text-zinc-500">
|
||||
<svg class="w-10 h-10 mx-auto mb-3 text-zinc-700" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M12 6.253v13m0-13C10.832 5.477 9.246 5 7.5 5S4.168 5.477 3 6.253v13C4.168 18.477 5.754 18 7.5 18s3.332.477 4.5 1.253m0-13C13.168 5.477 14.754 5 16.5 5c1.747 0 3.332.477 4.5 1.253v13C19.832 18.477 18.247 18 16.5 18c-1.746 0-3.332.477-4.5 1.253" />
|
||||
</svg>
|
||||
<p class="text-sm">No books in library yet.</p>
|
||||
</div>
|
||||
{/if}
|
||||
Reference in New Issue
Block a user