Let users browse followers and following lists

Following lists are public; followers are visible to the user and to mutual followers.
Adds GET /users/{id}/followers and /following, exposes isFollowing and canViewFollowers
on the profile, and returns isFollowedByViewer from user search so the web player no
longer calls /is-following per user.
This commit is contained in:
2026-09-23 22:55:14 +02:00
parent b9a40186b1
commit cb046bba9e
26 changed files with 768 additions and 64 deletions
+118 -3
View File
@@ -607,6 +607,40 @@ export interface paths {
patch?: never;
trace?: never;
};
"/users/{id}/followers": {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
/** Get The Users Following A User. Visible To The User And To Mutual Followers. */
get: operations["GetUserFollowers"];
put?: never;
post?: never;
delete?: never;
options?: never;
head?: never;
patch?: never;
trace?: never;
};
"/users/{id}/following": {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
/** Get The Users A User Follows. */
get: operations["GetUserFollowing"];
put?: never;
post?: never;
delete?: never;
options?: never;
head?: never;
patch?: never;
trace?: never;
};
"/users/{id}/is-following": {
parameters: {
query?: never;
@@ -807,8 +841,8 @@ export interface components {
hasNextPage: boolean;
hasPreviousPage: boolean;
};
PaginatedResponseOfUserApplicationResponse: {
items: components["schemas"]["UserApplicationResponse"][];
PaginatedResponseOfUserSummaryResponse: {
items: components["schemas"]["UserSummaryResponse"][];
/** Format: int32 */
pageNumber: number | string;
/** Format: int32 */
@@ -976,6 +1010,16 @@ export interface components {
followersCount: number | string;
/** Format: int32 */
followingCount: number | string;
isFollowing: boolean;
canViewFollowers: boolean;
};
UserSummaryResponse: {
id: string;
name: string;
firstName: null | string;
secondName: null | string;
profilePictureUrl: null | string;
isFollowedByViewer: boolean;
};
};
responses: never;
@@ -2277,7 +2321,7 @@ export interface operations {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["PaginatedResponseOfUserApplicationResponse"];
"application/json": components["schemas"]["PaginatedResponseOfUserSummaryResponse"];
};
};
};
@@ -2460,6 +2504,77 @@ export interface operations {
};
};
};
GetUserFollowers: {
parameters: {
query?: {
pageNumber?: number | string;
pageSize?: number | string;
};
header?: never;
path: {
id: number | string;
};
cookie?: never;
};
requestBody?: never;
responses: {
/** @description OK */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["PaginatedResponseOfUserSummaryResponse"];
};
};
/** @description Forbidden */
403: {
headers: {
[name: string]: unknown;
};
content?: never;
};
/** @description Not Found */
404: {
headers: {
[name: string]: unknown;
};
content?: never;
};
};
};
GetUserFollowing: {
parameters: {
query?: {
pageNumber?: number | string;
pageSize?: number | string;
};
header?: never;
path: {
id: number | string;
};
cookie?: never;
};
requestBody?: never;
responses: {
/** @description OK */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["PaginatedResponseOfUserSummaryResponse"];
};
};
/** @description Not Found */
404: {
headers: {
[name: string]: unknown;
};
content?: never;
};
};
};
IsFollowingUser: {
parameters: {
query?: never;
@@ -5,7 +5,7 @@
title: string;
eyebrow?: string;
description?: string;
meta?: string;
meta?: string | Snippet;
cover?: Snippet;
actions?: Snippet;
align?: 'center' | 'end';
@@ -45,8 +45,10 @@
{#if description}
<p class="mt-3 max-w-2xl text-body text-fg-2">{description}</p>
{/if}
{#if meta}
{#if typeof meta === 'string'}
<p class="mt-3 text-sm text-fg-2">{meta}</p>
{:else if meta}
<p class="mt-3 text-sm text-fg-2">{@render meta()}</p>
{/if}
</div>
{#if actions && !cover}
@@ -0,0 +1,28 @@
<script lang="ts">
import ListRow from './ListRow.svelte';
import Avatar from './Avatar.svelte';
import FollowButton from './FollowButton.svelte';
interface Props {
user: {
id: string;
name: string;
profilePictureUrl: string | null;
isFollowedByViewer: boolean;
};
canFollow?: boolean;
}
let { user, canFollow = false }: Props = $props();
</script>
<div class="flex items-center gap-3">
<ListRow title={user.name} href="/user/{user.id}" size="lg" class="min-w-0 flex-1">
{#snippet art()}
<Avatar name={user.name} src={user.profilePictureUrl} size="md" />
{/snippet}
</ListRow>
{#if canFollow}
<FollowButton following={user.isFollowedByViewer} userId={user.id} class="shrink-0" />
{/if}
</div>
+1
View File
@@ -17,5 +17,6 @@ export const HOME_POPULAR_MAX = 8;
export const PLAYLIST_PICKER_PAGE_SIZE = 50;
export const LIKED_TRACKS_PAGE_SIZE = 500;
export const EXPLORE_USERS_LIMIT = 12;
export const FOLLOW_LIST_PAGE_SIZE = 30;
export const MENU_WIDTH = 240;
export const SUBMENU_WIDTH = 256;
+17
View File
@@ -0,0 +1,17 @@
import type { createApiClient } from '$lib/server/api';
import type { FollowList } from '$lib/types';
type ApiClient = ReturnType<typeof createApiClient>;
export function fetchFollowList(
api: ApiClient,
list: FollowList,
id: string,
pageNumber: number,
pageSize: number
) {
const options = { params: { path: { id }, query: { pageNumber, pageSize } } };
return list === 'followers'
? api.GET('/users/{id}/followers', options)
: api.GET('/users/{id}/following', options);
}
+2
View File
@@ -4,3 +4,5 @@ export interface SessionUser {
email: string;
picture: string;
}
export type FollowList = 'followers' | 'following';
+5
View File
@@ -0,0 +1,5 @@
import type { ParamMatcher } from '@sveltejs/kit';
import type { FollowList } from '$lib/types';
export const match = ((param: string): param is FollowList =>
param === 'followers' || param === 'following') satisfies ParamMatcher;
@@ -46,31 +46,12 @@ export const load: PageServerLoad = async ({ url, locals, fetch }) => {
const tracks = unwrapOrError(tracksRes, 'No se pudieron cargar las canciones.');
const userItems = usersRes?.data?.items ?? [];
const followedIds = user
? await Promise.all(
userItems
.filter((u) => u.id !== user.sub)
.map((u) =>
api
.GET('/users/{id}/is-following', { params: { path: { id: u.id } } })
.then((res) => (res.data ? u.id : null))
.catch(() => null)
)
)
: [];
const followed = new Set(followedIds);
return {
query,
tracks,
albums: (albumsRes?.data?.items ?? []).map((item) => item.album),
users: userItems.map((u) => ({
...u,
isSelf: user?.sub === u.id,
isFollowing: followed.has(u.id)
})),
canFollow: !!user,
users: usersRes?.data?.items ?? [],
viewerId: user?.sub ?? null,
playlists: playlistsRes?.data?.items ?? []
};
};
@@ -10,7 +10,7 @@
import InfiniteScroll from '$lib/components/ui/primitives/InfiniteScroll.svelte';
import Artwork from '$lib/components/ui/media/Artwork.svelte';
import Avatar from '$lib/components/ui/media/Avatar.svelte';
import FollowButton from '$lib/components/ui/media/FollowButton.svelte';
import UserRow from '$lib/components/ui/media/UserRow.svelte';
import PlayButton from '$lib/components/ui/media/PlayButton.svelte';
import EqBars from '$lib/components/ui/media/EqBars.svelte';
import ListRow from '$lib/components/ui/media/ListRow.svelte';
@@ -402,15 +402,8 @@
<SectionHeading title="Usuarios" count={counts.Usuarios} />
<ul class="flex flex-col gap-1">
{#each capped(sfilter, users) as u (u.id)}
<li class="flex items-center gap-3">
<ListRow title={u.name} href="/user/{u.id}" size="lg" class="min-w-0 flex-1">
{#snippet art()}
<Avatar name={u.name} src={u.profilePictureUrl} size="md" />
{/snippet}
</ListRow>
{#if data.canFollow && !u.isSelf}
<FollowButton following={u.isFollowing} userId={u.id} class="shrink-0" />
{/if}
<li>
<UserRow user={u} canFollow={data.viewerId !== null && data.viewerId !== u.id} />
</li>
{/each}
</ul>
@@ -39,15 +39,7 @@ export const load: PageServerLoad = async ({ params, locals, url, fetch, parent
const isOwnProfile = viewer !== null && viewer.sub === params.id;
const isFollowing =
viewer && !isOwnProfile
? await api
.GET('/users/{id}/is-following', { params: { path: { id: params.id } } })
.then((res) => res.data ?? false)
.catch(() => false)
: false;
return { profile, playlists, isOwnProfile, isFollowing, isAnonymous: viewer === null };
return { profile, playlists, isOwnProfile, isAnonymous: viewer === null };
};
export const actions: Actions = {
@@ -22,18 +22,27 @@
</svelte:head>
{#snippet followAction()}
<FollowButton following={data.isFollowing} invalidateAll />
<FollowButton following={profile.isFollowing} invalidateAll />
{/snippet}
{#snippet followStats()}
{@const followers = plural(Number(profile.followersCount), 'seguidor', 'seguidores')}
{#if data.isOwnProfile || profile.canViewFollowers}
<a href="/user/{profile.id}/followers" class="transition-colors hover:text-fg">{followers}</a>
{:else}
<span>{followers}</span>
{/if}
·
<a href="/user/{profile.id}/following" class="transition-colors hover:text-fg">
{profile.followingCount} siguiendo
</a>
{/snippet}
<Page>
<PageHeader
eyebrow="Perfil"
title={profile.name}
meta="{plural(
Number(profile.followersCount),
'seguidor',
'seguidores'
)} · {profile.followingCount} siguiendo"
meta={followStats}
align="center"
actions={canFollow ? followAction : undefined}
>
@@ -0,0 +1,32 @@
import type { PageServerLoad, Actions } from './$types';
import { createApiClient, optionalUser, unwrapOrError } from '$lib/server/api';
import { fetchFollowList } from '$lib/server/follows';
import { followUserAction, unfollowUserAction } from '$lib/server/followActions';
import { FOLLOW_LIST_PAGE_SIZE } from '$lib/config';
export const load: PageServerLoad = async ({ params, locals, url, fetch, parent }) => {
const { allowAnonymousListening } = await parent();
const viewer = optionalUser(locals, url, allowAnonymousListening);
const api = createApiClient({ fetch, accessToken: locals.accessToken ?? undefined });
const [profileRes, listRes] = await Promise.all([
api.GET('/users/{id}/profile', { params: { path: { id: params.id } } }),
fetchFollowList(api, params.list, params.id, 1, FOLLOW_LIST_PAGE_SIZE)
]);
const profile = unwrapOrError(profileRes, 'Usuario no encontrado.', 404);
const forbidden = listRes.response?.status === 403;
return {
list: params.list,
profile,
users: forbidden ? null : unwrapOrError(listRes, 'No se pudo cargar la lista.'),
forbidden,
viewerId: viewer?.sub ?? null
};
};
export const actions: Actions = {
follow: followUserAction,
unfollow: unfollowUserAction
};
@@ -0,0 +1,93 @@
<script lang="ts">
import Users from '@lucide/svelte/icons/users';
import Lock from '@lucide/svelte/icons/lock';
import Page from '$lib/components/ui/layout/Page.svelte';
import PageHeader from '$lib/components/ui/layout/PageHeader.svelte';
import EmptyState from '$lib/components/ui/primitives/EmptyState.svelte';
import InfiniteScroll from '$lib/components/ui/primitives/InfiniteScroll.svelte';
import Alert from '$lib/components/ui/primitives/Alert.svelte';
import UserRow from '$lib/components/ui/media/UserRow.svelte';
import { appendUnique } from '$lib/data/collections';
import { plural } from '$lib/utils/format';
let { data, form } = $props();
type ListUser = NonNullable<typeof data.users>['items'][number];
let items = $state<ListUser[]>([]);
let page = $state(1);
let hasMore = $state(false);
let loadingMore = $state(false);
$effect(() => {
items = data.users?.items ?? [];
page = Number(data.users?.pageNumber ?? 1);
hasMore = data.users?.hasNextPage ?? false;
});
const isFollowers = $derived(data.list === 'followers');
const title = $derived(isFollowers ? 'Seguidores' : 'Siguiendo');
const total = $derived(Number(data.users?.totalItemCount ?? 0));
async function loadMore() {
if (loadingMore) return;
loadingMore = true;
try {
const res = await fetch(`/api/users/${data.profile.id}/${data.list}?pageNumber=${page + 1}`);
if (!res.ok) throw new Error(String(res.status));
const next = (await res.json()) as NonNullable<typeof data.users>;
items = appendUnique(items, next.items, (u) => u.id);
page = Number(next.pageNumber);
hasMore = next.hasNextPage;
} catch {
hasMore = false;
} finally {
loadingMore = false;
}
}
</script>
<svelte:head>
<title>{title} · {data.profile.name}</title>
</svelte:head>
<Page>
<PageHeader
eyebrow={data.profile.name}
{title}
meta={data.forbidden
? undefined
: isFollowers
? plural(total, 'seguidor', 'seguidores')
: plural(total, 'usuario', 'usuarios')}
/>
{#if form?.message}
<Alert class="mb-4">{form.message}</Alert>
{/if}
{#if data.forbidden}
<EmptyState
icon={Lock}
title="Seguidores privados"
description="Solo puedes ver los seguidores de {data.profile.name} si os seguís mutuamente."
/>
{:else if items.length === 0}
<EmptyState
icon={Users}
title={isFollowers ? 'Sin seguidores' : 'No sigue a nadie'}
description={isFollowers
? `Todavía nadie sigue a ${data.profile.name}.`
: `${data.profile.name} todavía no sigue a nadie.`}
/>
{:else}
<ul class="flex flex-col gap-1">
{#each items as user (user.id)}
<li>
<UserRow {user} canFollow={data.viewerId !== null && data.viewerId !== user.id} />
</li>
{/each}
</ul>
<InfiniteScroll onLoadMore={loadMore} {hasMore} loading={loadingMore} />
{/if}
</Page>
@@ -0,0 +1,19 @@
import type { RequestHandler } from './$types';
import { json } from '@sveltejs/kit';
import { createApiClient, unwrapOrError } from '$lib/server/api';
import { fetchFollowList } from '$lib/server/follows';
import { FOLLOW_LIST_PAGE_SIZE } from '$lib/config';
export const GET: RequestHandler = async ({ params, url, locals, fetch }) => {
const pageNumber = Math.max(1, Number(url.searchParams.get('pageNumber')) || 1);
const api = createApiClient({ fetch, accessToken: locals.accessToken ?? undefined });
const result = await fetchFollowList(
api,
params.list,
params.id,
pageNumber,
FOLLOW_LIST_PAGE_SIZE
);
return json(unwrapOrError(result, 'No se pudo cargar la lista.', result.response?.status));
};