Comments on plays

- Anyone who can see a play can read its comments; the player and the people they follow can write.
  The author, the player and admins can delete; comments can be reported (admins see the text).
- Notifications: "commented on" for the player, "replied on" for earlier commenters, each with its
  own setting. Reaction and comment notifications now open the play.
- A 💬 chip with the count next to reactions on the feed and recent plays, opening the thread on
  the app (/play/[id]) and the website. Threads refresh every few seconds while open.
- Blocking removes comments between the two people. Plays with comments survive history trimming.
- Privacy page updated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011Y2iUsKEWDuRGjK5FPmcUP
This commit is contained in:
2026-10-15 13:32:14 -04:00
co-authored by Claude Opus 5.5
parent 31aed8dec4
commit 4402171f46
33 changed files with 2850 additions and 36 deletions
+16
View File
@@ -0,0 +1,16 @@
CREATE TABLE "comments" (
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
"listen_id" uuid NOT NULL,
"user_id" uuid NOT NULL,
"body" varchar(500) NOT NULL,
"created_at" timestamp with time zone DEFAULT now() NOT NULL
);
--> statement-breakpoint
ALTER TABLE "notifications" ADD COLUMN "comment_id" uuid;--> statement-breakpoint
ALTER TABLE "reports" ADD COLUMN "comment_id" uuid;--> statement-breakpoint
ALTER TABLE "reports" ADD COLUMN "comment_body" varchar(500);--> statement-breakpoint
ALTER TABLE "comments" ADD CONSTRAINT "comments_listen_id_listens_id_fk" FOREIGN KEY ("listen_id") REFERENCES "public"."listens"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "comments" ADD CONSTRAINT "comments_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
CREATE INDEX "comments_listen_created_idx" ON "comments" USING btree ("listen_id","created_at");--> statement-breakpoint
ALTER TABLE "notifications" ADD CONSTRAINT "notifications_comment_id_comments_id_fk" FOREIGN KEY ("comment_id") REFERENCES "public"."comments"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "reports" ADD CONSTRAINT "reports_comment_id_comments_id_fk" FOREIGN KEY ("comment_id") REFERENCES "public"."comments"("id") ON DELETE set null ON UPDATE no action;
File diff suppressed because it is too large Load Diff
+7
View File
@@ -120,6 +120,13 @@
"when": 1792028149643,
"tag": "0016_notifications",
"breakpoints": true
},
{
"idx": 17,
"version": "7",
"when": 1792084480262,
"tag": "0017_comments",
"breakpoints": true
}
]
}
+2
View File
@@ -12,6 +12,7 @@ import { HttpError } from './lib/http';
import { redis } from './lib/redis';
import { adminRoutes } from './routes/admin';
import { appUpdateRoutes } from './routes/appUpdates';
import { commentRoutes } from './routes/comments';
import { accountRoutes } from './routes/account';
import { authRoutes } from './routes/auth';
import { avatarRoutes } from './routes/avatars';
@@ -78,6 +79,7 @@ export async function buildApp({ logger = true, rateLimits = true }: { logger?:
await app.register(adminRoutes);
await app.register(trackRoutes);
await app.register(reactionRoutes);
await app.register(commentRoutes);
await app.register(notificationRoutes);
await app.register(connectionRoutes);
await app.register(deviceRoutes);
+25 -3
View File
@@ -105,6 +105,9 @@ export const reports = pgTable(
.references(() => users.id, { onDelete: 'cascade' }),
reason: text('reason').$type<ReportReason>().notNull(),
note: varchar('note', { length: 500 }),
/** When a comment was reported: which, and what it said then (kept if the comment is deleted). */
commentId: uuid('comment_id').references(() => comments.id, { onDelete: 'set null' }),
commentBody: varchar('comment_body', { length: 500 }),
status: text('status').$type<'open' | 'resolved'>().notNull().default('open'),
createdAt: createdAt(),
},
@@ -262,6 +265,23 @@ export const reactions = pgTable(
(t) => [primaryKey({ columns: [t.listenId, t.userId] })],
);
/** Comments on a play. They go with the play (plays with comments are kept when history is trimmed). */
export const comments = pgTable(
'comments',
{
id: uuid('id').primaryKey().defaultRandom(),
listenId: uuid('listen_id')
.notNull()
.references(() => listens.id, { onDelete: 'cascade' }),
userId: uuid('user_id')
.notNull()
.references(() => users.id, { onDelete: 'cascade' }),
body: varchar('body', { length: 500 }).notNull(),
createdAt: createdAt(),
},
(t) => [index('comments_listen_created_idx').on(t.listenId, t.createdAt)],
);
/** Email confirmation links (sign-up and email changes). Only a hash of the token is stored. */
export const emailVerifications = pgTable(
'email_verifications',
@@ -306,7 +326,7 @@ export const lyrics = pgTable('lyrics', {
fetchedAt: timestamp('fetched_at', { withTimezone: true }).notNull().defaultNow(),
});
/** Things that happened to a user: a reaction, a new follower, a song sent to them. */
/** Things that happened to a user: a reaction or comment, a new follower, a song sent to them. */
export const notifications = pgTable(
'notifications',
{
@@ -319,10 +339,12 @@ export const notifications = pgTable(
.notNull()
.references(() => users.id, { onDelete: 'cascade' }),
trackId: uuid('track_id').references(() => tracks.id, { onDelete: 'cascade' }),
/** The play a reaction was on (gone once the play is trimmed from history). */
/** The play a reaction or comment was on (gone once the play is trimmed from history). */
listenId: uuid('listen_id').references(() => listens.id, { onDelete: 'set null' }),
/** The comment (or reply); deleting the comment takes its notifications with it. */
commentId: uuid('comment_id').references(() => comments.id, { onDelete: 'cascade' }),
emoji: varchar('emoji', { length: 32 }),
/** A note sent with a song. */
/** A note sent with a song, or the start of a comment. */
message: varchar('message', { length: 280 }),
readAt: timestamp('read_at', { withTimezone: true }),
createdAt: createdAt(),
+1
View File
@@ -40,6 +40,7 @@ export async function adminRoutes(app: FastifyInstance) {
createdAt: report.createdAt.toISOString(),
reporter: by ? toUserSummary(by) : null,
reported: { ...toUserSummary(who), suspended: Boolean(who.suspendedAt) },
comment: report.commentBody ? { id: report.commentId, body: report.commentBody } : null,
}));
});
+163
View File
@@ -0,0 +1,163 @@
import { and, asc, eq, inArray, isNull, ne, or } from 'drizzle-orm';
import type { FastifyInstance } from 'fastify';
import { z } from 'zod';
import { commentSchema, reportSchema, type CommentDTO, type CommentThreadDTO } from '@musicshare/shared';
import { db, schema } from '../db';
import type { User } from '../db/schema';
import { requireUser } from '../lib/auth';
import { HttpError } from '../lib/http';
import { blockStatus, hiddenUserIds } from '../services/blocks';
import { notify } from '../services/notifications';
import { getReactions, publishNowPlaying, toUserSummary } from '../services/nowPlaying';
import { getTrackDTOs } from '../services/tracks';
const params = z.object({ id: z.uuid() });
/** Who may write on a play: the person who played it, and the people they follow. */
async function canCommentOn(viewerId: string, ownerId: string) {
if (viewerId === ownerId) return true;
const [row] = await db
.select({ one: schema.follows.followerId })
.from(schema.follows)
.where(and(eq(schema.follows.followerId, ownerId), eq(schema.follows.followeeId, viewerId)));
return Boolean(row);
}
/** The play and its owner, if the viewer may see it: the owner isn't suspended, and no block either way. */
async function visiblePlay(viewerId: string, listenId: string) {
const [row] = await db
.select({ listen: schema.listens, owner: schema.users })
.from(schema.listens)
.innerJoin(schema.users, eq(schema.users.id, schema.listens.userId))
.where(eq(schema.listens.id, listenId));
if (!row || row.owner.suspendedAt) throw new HttpError(404, 'That play is gone');
const { viewerBlocked, blockedByThem } = await blockStatus(viewerId, row.owner.id);
if (viewerBlocked || blockedByThem) throw new HttpError(404, 'That play is gone');
return row;
}
const toCommentDTO = (c: typeof schema.comments.$inferSelect, author: User, viewer: User, ownerId: string): CommentDTO => ({
id: c.id,
user: toUserSummary(author),
body: c.body,
createdAt: c.createdAt.toISOString(),
canDelete: c.userId === viewer.id || ownerId === viewer.id || viewer.role === 'admin',
});
export async function commentRoutes(app: FastifyInstance) {
app.get('/listens/:id/comments', async (req): Promise<CommentThreadDTO> => {
const viewer = requireUser(req);
const { id } = params.parse(req.params);
const { listen, owner } = await visiblePlay(viewer.id, id);
const hidden = await hiddenUserIds(viewer.id);
const rows = await db
.select({ comment: schema.comments, author: schema.users })
.from(schema.comments)
.innerJoin(schema.users, eq(schema.users.id, schema.comments.userId))
.where(and(eq(schema.comments.listenId, id), isNull(schema.users.suspendedAt)))
.orderBy(asc(schema.comments.createdAt));
const [tracks, reactions, canComment] = await Promise.all([
getTrackDTOs([listen.trackId]),
getReactions([id]),
canCommentOn(viewer.id, owner.id),
]);
return {
listenId: id,
owner: toUserSummary(owner),
track: tracks.get(listen.trackId)!,
playedAt: listen.startedAt.toISOString(),
reactions: reactions.get(id) ?? [],
comments: rows.filter((r) => !hidden.has(r.author.id)).map((r) => toCommentDTO(r.comment, r.author, viewer, owner.id)),
canComment,
};
});
app.post(
'/listens/:id/comments',
{ config: { rateLimit: { max: 20, timeWindow: '1 minute' } } },
async (req): Promise<CommentDTO> => {
const viewer = requireUser(req);
const { id } = params.parse(req.params);
const { body } = commentSchema.parse(req.body);
const { listen, owner } = await visiblePlay(viewer.id, id);
if (!(await canCommentOn(viewer.id, owner.id))) {
throw new HttpError(403, `Only people @${owner.username} follows can comment on their songs`);
}
const [comment] = await db.insert(schema.comments).values({ listenId: id, userId: viewer.id, body }).returning();
const excerpt = body.length > 280 ? `${body.slice(0, 279)}…` : body;
const about = { actorId: viewer.id, listenId: id, trackId: listen.trackId, commentId: comment!.id, message: excerpt };
await notify({ ...about, userId: owner.id, type: 'comment' });
// Everyone else who has commented here hears about replies (unless either side has blocked the other).
const others = await db
.selectDistinct({ userId: schema.comments.userId })
.from(schema.comments)
.where(and(eq(schema.comments.listenId, id), ne(schema.comments.userId, viewer.id), ne(schema.comments.userId, owner.id)));
const hidden = await hiddenUserIds(viewer.id);
for (const { userId } of others) {
if (!hidden.has(userId)) await notify({ ...about, userId, type: 'reply' });
}
await publishNowPlaying(owner.id); // the comment count on the feed
return toCommentDTO(comment!, viewer, viewer, owner.id);
},
);
async function findComment(commentId: string) {
const [row] = await db
.select({ comment: schema.comments, ownerId: schema.listens.userId })
.from(schema.comments)
.innerJoin(schema.listens, eq(schema.listens.id, schema.comments.listenId))
.where(eq(schema.comments.id, commentId));
if (!row) throw new HttpError(404, 'That comment is gone');
return row;
}
/** The author, the play's owner, or an admin. Its notifications go with it. */
app.delete('/comments/:id', async (req) => {
const viewer = requireUser(req);
const { id } = params.parse(req.params);
const { comment, ownerId } = await findComment(id);
if (comment.userId !== viewer.id && ownerId !== viewer.id && viewer.role !== 'admin') {
throw new HttpError(403, "You can't delete that comment");
}
await db.delete(schema.comments).where(eq(schema.comments.id, id));
await publishNowPlaying(ownerId);
return { ok: true };
});
app.post(
'/comments/:id/report',
{ config: { rateLimit: { max: 10, timeWindow: '1 hour' } } },
async (req) => {
const viewer = requireUser(req);
const { id } = params.parse(req.params);
const { comment } = await findComment(id);
await visiblePlay(viewer.id, comment.listenId);
if (comment.userId === viewer.id) throw new HttpError(400, "You can't report your own comment");
const input = reportSchema.parse(req.body);
await db.insert(schema.reports).values({
reporterId: viewer.id,
reportedId: comment.userId,
reason: input.reason,
note: input.note || null,
commentId: comment.id,
commentBody: comment.body,
});
return { ok: true };
},
);
}
/** When someone's blocked, their comments on each other's plays go too. */
export async function removeCommentsBetween(a: string, b: string) {
const playsOf = (userId: string) => db.select({ id: schema.listens.id }).from(schema.listens).where(eq(schema.listens.userId, userId));
await db
.delete(schema.comments)
.where(
or(
and(eq(schema.comments.userId, a), inArray(schema.comments.listenId, playsOf(b))),
and(eq(schema.comments.userId, b), inArray(schema.comments.listenId, playsOf(a))),
),
);
}
+2
View File
@@ -11,6 +11,7 @@ import { HttpError } from '../lib/http';
import { FOLLOWS_CHANGED_CHANNEL, redis } from '../lib/redis';
import { removeNotificationsBetween } from '../services/notifications';
import { toUserSummary } from '../services/nowPlaying';
import { removeCommentsBetween } from './comments';
import { removeReactionsBetween } from './reactions';
async function findUser(username: string) {
@@ -49,6 +50,7 @@ export async function safetyRoutes(app: FastifyInstance) {
);
});
await removeReactionsBetween(me.id, them.id);
await removeCommentsBetween(me.id, them.id);
await removeNotificationsBetween(me.id, them.id);
await followsChanged(me.id, them.id);
return { ok: true };
+2
View File
@@ -34,6 +34,7 @@ export async function notify(input: {
listenId?: string | null;
emoji?: string | null;
message?: string | null;
commentId?: string | null;
}): Promise<string | null> {
if (input.userId === input.actorId) return null;
const n = schema.notifications;
@@ -91,6 +92,7 @@ export async function toNotificationDTOs(rows: Row[]): Promise<NotificationDTO[]
type: r.type,
actor,
track: r.trackId ? (tracks.get(r.trackId) ?? null) : null,
listenId: r.listenId,
emoji: r.emoji,
message: r.message,
read: Boolean(r.readAt),
+28 -4
View File
@@ -1,4 +1,4 @@
import { and, desc, eq, inArray, isNull, lt } from 'drizzle-orm';
import { and, count, desc, eq, inArray, isNull, lt, notExists } from 'drizzle-orm';
import type { NowPlayingDTO, NowPlayingProvider, ReactionDTO, RecentPlayDTO, UserSummaryDTO } from '@musicshare/shared';
import { db, schema } from '../db';
import type { User } from '../db/schema';
@@ -40,6 +40,18 @@ export async function getReactions(listenIds: string[]): Promise<Map<string, Rea
return result;
}
/** How many comments each play has (from people who aren't suspended). */
export async function getCommentCounts(listenIds: string[]): Promise<Map<string, number>> {
if (listenIds.length === 0) return new Map();
const rows = await db
.select({ listenId: schema.comments.listenId, n: count() })
.from(schema.comments)
.innerJoin(schema.users, eq(schema.users.id, schema.comments.userId))
.where(and(inArray(schema.comments.listenId, listenIds), isNull(schema.users.suspendedAt)))
.groupBy(schema.comments.listenId);
return new Map(rows.map((r) => [r.listenId, r.n]));
}
/** Phones report changes and a heartbeat every few minutes; if they go quiet (app killed, no signal), stop showing "listening now". */
export const DEVICE_STALE_MS = 9 * 60_000;
const PUSH_SOURCES = new Set<NowPlayingProvider>(['android_media_session']);
@@ -63,7 +75,8 @@ export async function getNowPlaying(userIds: string[]): Promise<NowPlayingDTO[]>
const l = listenIds.get(np.userId);
return l && l.trackId === np.trackId ? l.id : null;
};
const reactions = await getReactions(rows.map((r) => listenFor(r.np)).filter((id): id is string => Boolean(id)));
const shownListens = rows.map((r) => listenFor(r.np)).filter((id): id is string => Boolean(id));
const [reactions, commentCounts] = await Promise.all([getReactions(shownListens), getCommentCounts(shownListens)]);
const now = Date.now();
return rows
.map(({ np, user }) => ({ np, user, track: tracks.get(np.trackId)! }))
@@ -78,6 +91,7 @@ export async function getNowPlaying(userIds: string[]): Promise<NowPlayingDTO[]>
updatedAt: np.updatedAt.toISOString(),
listenId: listenFor(np),
reactions: reactions.get(listenFor(np) ?? '') ?? [],
commentCount: commentCounts.get(listenFor(np) ?? '') ?? 0,
}))
.sort((a, b) => Number(b.isPlaying) - Number(a.isPlaying) || b.updatedAt.localeCompare(a.updatedAt));
}
@@ -108,7 +122,11 @@ async function recordListen(userId: string, trackId: string, source: NowPlayingP
.offset(LISTEN_HISTORY_LIMIT - 1)
.limit(1);
if (cutoff) {
await db.delete(schema.listens).where(and(eq(schema.listens.userId, userId), lt(schema.listens.startedAt, cutoff.startedAt)));
// Plays with comments stay, so conversations don't vanish as new songs come in.
const commented = db.select({ one: schema.comments.id }).from(schema.comments).where(eq(schema.comments.listenId, schema.listens.id));
await db
.delete(schema.listens)
.where(and(eq(schema.listens.userId, userId), lt(schema.listens.startedAt, cutoff.startedAt), notExists(commented)));
}
}
@@ -122,13 +140,19 @@ export async function getRecentPlays(userId: string, limit = 10): Promise<Recent
// Don't repeat the track that's playing right now.
const [current] = await db.select().from(schema.nowPlaying).where(eq(schema.nowPlaying.userId, userId));
const plays = current?.isPlaying && rows[0]?.trackId === current.trackId ? rows.slice(1) : rows.slice(0, limit);
const [tracks, reactions] = await Promise.all([getTrackDTOs(plays.map((p) => p.trackId)), getReactions(plays.map((p) => p.id))]);
const ids = plays.map((p) => p.id);
const [tracks, reactions, commentCounts] = await Promise.all([
getTrackDTOs(plays.map((p) => p.trackId)),
getReactions(ids),
getCommentCounts(ids),
]);
return plays.map((p) => ({
listenId: p.id,
track: tracks.get(p.trackId)!,
source: p.source,
playedAt: p.startedAt.toISOString(),
reactions: reactions.get(p.id) ?? [],
commentCount: commentCounts.get(p.id) ?? 0,
}));
}
+116
View File
@@ -0,0 +1,116 @@
import { describe, expect, it } from 'vitest';
import { applyPollResult, LISTEN_HISTORY_LIMIT } from '../src/services/nowPlaying';
import { bearer, createUser, follow, useTestApp } from './helpers';
const app = useTestApp();
const song = (title: string) => ({ track: { title, artist: 'Massive Attack' }, isPlaying: true, progressMs: null });
/** Alice plays a song. Bob follows her and she follows him back; Carol follows her, but she doesn't follow Carol. */
async function setup() {
const alice = await createUser(app(), 'alice');
const bob = await createUser(app(), 'bob');
const carol = await createUser(app(), 'carol');
await follow(app(), bob.token, 'alice');
await follow(app(), alice.token, 'bob');
await follow(app(), carol.token, 'alice');
await applyPollResult(alice.user.id, 'lastfm', song('Teardrop'));
const feed = (await app().inject({ url: '/feed', headers: bearer(bob.token) })).json();
return { alice, bob, carol, listenId: feed[0].listenId as string };
}
const comment = (token: string, listenId: string, body: string) =>
app().inject({ method: 'POST', url: `/listens/${listenId}/comments`, headers: bearer(token), payload: { body } });
const thread = (token: string, listenId: string) => app().inject({ url: `/listens/${listenId}/comments`, headers: bearer(token) });
/** Comment and reply notifications (setup's follows make some too). */
const notifications = async (token: string) =>
((await app().inject({ url: '/notifications', headers: bearer(token) })).json().notifications as { type: string; message: string }[]).filter(
(n) => n.type === 'comment' || n.type === 'reply',
);
describe('comments', () => {
it('lets the player and people they follow comment, oldest first, with a count on the feed', async () => {
const { alice, bob, carol, listenId } = await setup();
expect((await comment(bob.token, listenId, ' what a tune ')).json()).toMatchObject({ body: 'what a tune', canDelete: true });
await comment(alice.token, listenId, 'right?');
const res = await comment(carol.token, listenId, 'hi');
expect(res.statusCode).toBe(403);
expect(res.json().error).toBe('Only people @alice follows can comment on their songs');
const forCarol = (await thread(carol.token, listenId)).json();
expect(forCarol).toMatchObject({ canComment: false, owner: { username: 'alice' }, track: { title: 'Teardrop' } });
expect(forCarol.comments.map((c: { body: string; canDelete: boolean }) => [c.body, c.canDelete])).toEqual([
['what a tune', false],
['right?', false],
]);
expect((await thread(alice.token, listenId)).json().comments.every((c: { canDelete: boolean }) => c.canDelete)).toBe(true);
const feed = (await app().inject({ url: '/feed', headers: bearer(carol.token) })).json();
expect(feed[0].commentCount).toBe(2);
});
it('rejects empty and overlong comments', async () => {
const { bob, listenId } = await setup();
expect((await comment(bob.token, listenId, ' ')).statusCode).toBe(400);
expect((await comment(bob.token, listenId, 'x'.repeat(501))).statusCode).toBe(400);
});
it('notifies the player, and earlier commenters about replies', async () => {
const { alice, bob, listenId } = await setup();
const dave = await createUser(app(), 'dave');
await follow(app(), alice.token, 'dave');
await comment(bob.token, listenId, 'what a tune');
await comment(dave.token, listenId, 'agreed');
await comment(alice.token, listenId, 'thanks both');
expect((await notifications(alice.token)).map((n) => [n.type, n.message])).toEqual([
['comment', 'agreed'],
['comment', 'what a tune'],
]);
expect((await notifications(bob.token)).map((n) => [n.type, n.message])).toEqual([
['reply', 'thanks both'],
['reply', 'agreed'],
]);
const [latest] = (await app().inject({ url: '/notifications', headers: bearer(bob.token) })).json().notifications;
expect(latest).toMatchObject({ type: 'reply', listenId });
});
it('can be deleted by the author, the player or an admin (taking its notifications along), not anyone else', async () => {
const { alice, bob, carol, listenId } = await setup();
const { id } = (await comment(bob.token, listenId, 'first')).json();
const del = (token: string) => app().inject({ method: 'DELETE', url: `/comments/${id}`, headers: bearer(token) });
expect((await del(carol.token)).statusCode).toBe(403);
expect(await notifications(alice.token)).toHaveLength(1);
expect((await del(alice.token)).statusCode).toBe(200);
expect((await thread(bob.token, listenId)).json().comments).toEqual([]);
expect(await notifications(alice.token)).toEqual([]);
});
it('can be reported, keeping what it said for the admins', async () => {
const { bob, carol, listenId } = await setup();
const { id } = (await comment(bob.token, listenId, 'rude words')).json();
const report = (token: string) =>
app().inject({ method: 'POST', url: `/comments/${id}/report`, headers: bearer(token), payload: { reason: 'harassment' } });
expect((await report(bob.token)).statusCode).toBe(400);
expect((await report(carol.token)).statusCode).toBe(200);
});
it('goes away with a block, both ways', async () => {
const { alice, bob, listenId } = await setup();
await comment(bob.token, listenId, 'hello');
await app().inject({ method: 'POST', url: '/users/bob/block', headers: bearer(alice.token), payload: {} });
expect((await thread(bob.token, listenId)).statusCode).toBe(404);
expect((await thread(alice.token, listenId)).json().comments).toEqual([]);
});
it('keeps plays with comments when old history is trimmed', async () => {
const { alice, bob, listenId } = await setup();
await comment(bob.token, listenId, 'keep this');
for (let i = 0; i < LISTEN_HISTORY_LIMIT + 2; i++) {
await applyPollResult(alice.user.id, 'lastfm', song(`Song ${i}`));
}
const res = await thread(bob.token, listenId);
expect(res.statusCode).toBe(200);
expect(res.json().comments).toHaveLength(1);
});
});
+2 -2
View File
@@ -76,8 +76,8 @@ describe('notifications', () => {
it('saves notification settings', async () => {
const { alice } = await setup();
const me = (await app().inject({ method: 'PATCH', url: '/me', headers: bearer(alice.token), payload: { notifyPrefs: { follow: false } } })).json();
expect(me.notifyPrefs).toEqual({ reaction: true, follow: false, share: true });
const me = (await app().inject({ method: 'PATCH', url: '/me', headers: bearer(alice.token), payload: { notifyPrefs: { follow: false, reply: false } } })).json();
expect(me.notifyPrefs).toEqual({ reaction: true, comment: true, reply: false, follow: false, share: true });
});
});
+1
View File
@@ -109,6 +109,7 @@ function AppNavigator() {
<Stack.Screen name="scan" options={{ title: 'Scan a code', presentation: 'modal' }} />
<Stack.Screen name="notifications" options={{ title: 'Notifications' }} />
<Stack.Screen name="t/[id]" options={{ title: '' }} />
<Stack.Screen name="play/[id]" options={{ title: 'Comments' }} />
<Stack.Screen name="send/[trackId]" options={{ title: 'Send to friends', presentation: 'modal' }} />
</Stack.Protected>
<Stack.Protected guard={!signedIn}>
+195
View File
@@ -0,0 +1,195 @@
import { Stack, router, useLocalSearchParams } from 'expo-router';
import { useState } from 'react';
import { ActivityIndicator, Alert, FlatList, KeyboardAvoidingView, Platform, Pressable, StyleSheet, Text, TextInput, View } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import useSWR from 'swr';
import { COMMENT_MAX_LENGTH, timeAgo, type CommentDTO, type CommentThreadDTO } from '@musicshare/shared';
import { AmbientBackground } from '@/components/AmbientBackground';
import { Avatar } from '@/components/Avatar';
import { Reactions } from '@/components/Reactions';
import { TrackCard } from '@/components/TrackCard';
import { Body, Card } from '@/components/ui';
import { api } from '@/lib/api';
import { showError } from '@/lib/errors';
import { tapHaptic } from '@/lib/haptics';
import { useSession } from '@/lib/session';
import { colors, radius, space } from '@/lib/theme';
/** One play and its comments: where the 💬 chip and comment notifications lead. */
export default function PlayScreen() {
const { id } = useLocalSearchParams<{ id: string }>();
const { me } = useSession();
// Polled while open so other people's comments show up without refreshing.
const { data, error, mutate } = useSWR<CommentThreadDTO>(id ? `/listens/${id}/comments` : null, { refreshInterval: 5000 });
const [draft, setDraft] = useState('');
const [sending, setSending] = useState(false);
const send = async () => {
const body = draft.trim();
if (!body || !id) return;
setSending(true);
try {
const comment = await api.addComment(id, { body });
tapHaptic();
setDraft('');
await mutate((t) => (t ? { ...t, comments: [...t.comments, comment] } : t), { revalidate: false });
} catch (err) {
showError(err, "Couldn't post that");
}
setSending(false);
};
const remove = (c: CommentDTO) =>
Alert.alert('Delete this comment?', undefined, [
{ text: 'Cancel', style: 'cancel' },
{
text: 'Delete',
style: 'destructive',
onPress: async () => {
try {
await api.deleteComment(c.id);
await mutate((t) => (t ? { ...t, comments: t.comments.filter((x) => x.id !== c.id) } : t), { revalidate: false });
} catch (err) {
showError(err, "Couldn't delete it");
}
},
},
]);
const options = (c: CommentDTO) => {
const mine = c.user.id === me?.id;
Alert.alert(c.user.displayName ?? c.user.username, undefined, [
...(c.canDelete ? [{ text: 'Delete', style: 'destructive' as const, onPress: () => remove(c) }] : []),
...(!mine ? [{ text: 'Report', onPress: () => router.push(`/report/${c.user.username}?comment=${c.id}`) }] : []),
{ text: 'Cancel', style: 'cancel' as const },
]);
};
if (error) {
return (
<View style={styles.center}>
<Stack.Screen options={{ title: '' }} />
<Body muted>That play is gone.</Body>
</View>
);
}
if (!data) {
return (
<View style={styles.center}>
<ActivityIndicator color={colors.muted} />
</View>
);
}
const owner = data.owner.displayName ?? data.owner.username;
return (
<SafeAreaView style={styles.safe} edges={['bottom']}>
<Stack.Screen options={{ title: 'Comments' }} />
<AmbientBackground />
<KeyboardAvoidingView style={{ flex: 1 }} behavior={Platform.OS === 'ios' ? 'padding' : undefined} keyboardVerticalOffset={90}>
<FlatList
data={data.comments}
keyExtractor={(c) => c.id}
contentContainerStyle={styles.list}
keyboardShouldPersistTaps="handled"
ListHeaderComponent={
<View style={styles.header}>
<Pressable onPress={() => router.push(`/u/${data.owner.username}`)} style={styles.playedBy}>
<Avatar user={data.owner} size={28} />
<Text style={styles.muted}>
<Text style={styles.name}>{owner}</Text> played this · {timeAgo(data.playedAt)}
</Text>
</Pressable>
<TrackCard track={data.track} preferred={me?.preferredService} />
<Reactions listenId={data.listenId} reactions={data.reactions} ownerId={data.owner.id} style={{ marginTop: 0 }} />
</View>
}
ListEmptyComponent={<Body muted>{data.canComment ? 'No comments yet. Say something!' : 'No comments yet.'}</Body>}
renderItem={({ item }) => (
<Pressable onLongPress={() => options(item)} delayLongPress={300} style={styles.comment}>
<Pressable onPress={() => router.push(`/u/${item.user.username}`)} hitSlop={4}>
<Avatar user={item.user} size={34} />
</Pressable>
<View style={{ flex: 1, minWidth: 0, gap: 2 }}>
<Text style={styles.muted}>
<Text style={styles.name}>{item.user.displayName ?? item.user.username}</Text> · {timeAgo(item.createdAt)}
</Text>
<Text style={styles.body} selectable>
{item.body}
</Text>
</View>
<Pressable onPress={() => options(item)} hitSlop={10} accessibilityLabel="Comment options">
<Text style={styles.more}>⋯</Text>
</Pressable>
</Pressable>
)}
/>
{data.canComment ? (
<View style={styles.composer}>
<TextInput
value={draft}
onChangeText={setDraft}
placeholder={data.owner.id === me?.id ? 'Comment on your song' : `Comment on ${owner}'s song`}
placeholderTextColor={colors.muted}
multiline
maxLength={COMMENT_MAX_LENGTH}
style={styles.input}
/>
<Pressable
onPress={send}
disabled={!draft.trim() || sending}
accessibilityRole="button"
accessibilityLabel="Post comment"
style={[styles.send, (!draft.trim() || sending) && { opacity: 0.4 }]}>
{sending ? <ActivityIndicator color="#fff" size="small" /> : <Text style={styles.sendText}>Post</Text>}
</Pressable>
</View>
) : (
<Card style={styles.closed}>
<Body muted style={{ fontSize: 13 }}>
Only people {owner} follows can comment on their songs.
</Body>
</Card>
)}
</KeyboardAvoidingView>
</SafeAreaView>
);
}
const styles = StyleSheet.create({
safe: { flex: 1, backgroundColor: colors.bg },
center: { flex: 1, alignItems: 'center', justifyContent: 'center', backgroundColor: colors.bg },
list: { padding: space.lg, gap: space.md, paddingBottom: space.xl },
header: { gap: space.md, marginBottom: space.sm },
playedBy: { flexDirection: 'row', alignItems: 'center', gap: space.sm },
comment: { flexDirection: 'row', gap: space.md, alignItems: 'flex-start' },
name: { color: colors.text, fontWeight: '700' },
muted: { color: colors.muted, fontSize: 13 },
body: { color: colors.text, fontSize: 15, lineHeight: 21 },
more: { color: colors.muted, fontSize: 18, paddingHorizontal: space.xs },
composer: {
flexDirection: 'row',
alignItems: 'flex-end',
gap: space.sm,
paddingHorizontal: space.lg,
paddingVertical: space.sm,
borderTopWidth: StyleSheet.hairlineWidth,
borderTopColor: colors.border,
backgroundColor: colors.bg,
},
input: {
flex: 1,
maxHeight: 120,
color: colors.text,
fontSize: 15,
paddingHorizontal: space.md,
paddingVertical: space.sm,
borderRadius: radius.md,
backgroundColor: colors.surface,
borderWidth: 1,
borderColor: colors.border,
},
send: { paddingHorizontal: space.md, paddingVertical: space.sm + 2, borderRadius: radius.pill, backgroundColor: colors.accent },
sendText: { color: '#fff', fontWeight: '700' },
closed: { margin: space.lg, marginTop: 0 },
});
+5 -3
View File
@@ -8,7 +8,8 @@ import { api } from '@/lib/api';
import { showError } from '@/lib/errors';
export default function ReportScreen() {
const { username } = useLocalSearchParams<{ username: string }>();
// ?comment=<id> reports one comment of theirs rather than their account.
const { username, comment } = useLocalSearchParams<{ username: string; comment?: string }>();
const [reason, setReason] = useState<ReportReason | null>(null);
const [note, setNote] = useState('');
const [busy, setBusy] = useState(false);
@@ -18,7 +19,8 @@ export default function ReportScreen() {
if (!reason) return;
setBusy(true);
try {
await api.report(username, { reason, note: note.trim() || null });
const input = { reason, note: note.trim() || null };
await (comment ? api.reportComment(comment, input) : api.report(username, input));
setSent(true);
} catch (err) {
showError(err, "Couldn't send the report");
@@ -38,7 +40,7 @@ export default function ReportScreen() {
return (
<KeyboardAvoidingView style={{ flex: 1 }} behavior={Platform.OS === 'ios' ? 'padding' : undefined}>
<Screen>
<Body muted>What&apos;s wrong with @{username}&apos;s account?</Body>
<Body muted>{comment ? `What's wrong with @${username}'s comment?` : `What's wrong with @${username}'s account?`}</Body>
<Row>
{REPORT_REASONS.map((r) => (
<Chip key={r} label={REPORT_REASON_LABELS[r]} selected={reason === r} onPress={() => setReason(r)} />
@@ -101,7 +101,7 @@ export function NowPlayingCard({
<TrackRow track={np.track} preferred={preferred} expanded={expanded} onToggle={toggle} />
</Animated.View>
<ProgressBar np={np} compact={!expanded} />
<Reactions listenId={np.listenId} reactions={np.reactions} ownerId={np.user.id} />
<Reactions listenId={np.listenId} reactions={np.reactions} ownerId={np.user.id} commentCount={np.commentCount ?? 0} />
{expanded && (
<Animated.View entering={FadeIn.duration(200)} exiting={FadeOut.duration(120)} style={styles.details}>
<ServiceLinks track={np.track} preferred={preferred} />
+19 -3
View File
@@ -1,6 +1,7 @@
import { useState } from 'react';
import { FlatList, Modal, Pressable, StyleSheet, Text, TextInput, View, type ViewStyle } from 'react-native';
import Animated, { FadeIn, FadeOut, ZoomIn } from 'react-native-reanimated';
import { router } from 'expo-router';
import Animated, { FadeIn, FadeOut } from 'react-native-reanimated';
import { EMOJI_PICKER_GROUPS, QUICK_REACTIONS, searchEmoji, type ReactionDTO } from '@musicshare/shared';
import { api } from '@/lib/api';
import { showError } from '@/lib/errors';
@@ -11,16 +12,19 @@ import { colors, radius, space } from '@/lib/theme';
/**
* Emoji reactions on one play. Tap an emoji to add yours (or take it back); "☺+"
* opens the quick six, and "+" the full picker. One reaction per person.
* With `commentCount`, a 💬 chip opens the play's comments.
*/
export function Reactions({
listenId,
reactions,
ownerId,
commentCount,
style,
}: {
listenId: string | null;
reactions: ReactionDTO[];
ownerId: string;
commentCount?: number;
style?: ViewStyle;
}) {
const { me } = useSession();
@@ -31,7 +35,8 @@ export function Reactions({
const [pickerOpen, setPickerOpen] = useState(false);
const canReact = Boolean(me && listenId && me.id !== ownerId);
if (!listenId || (!canReact && shown.length === 0)) return null;
const showComments = commentCount !== undefined && Boolean(me);
if (!listenId || (!canReact && shown.length === 0 && !showComments)) return null;
const mine = me ? shown.find((r) => r.users.some((u) => u.id === me.id))?.emoji : undefined;
const choose = async (emoji: string) => {
@@ -50,7 +55,7 @@ export function Reactions({
<View style={[styles.wrap, style]}>
<View style={styles.row}>
{shown.map((r) => (
<Animated.View key={r.emoji} entering={ZoomIn.springify()}>
<Animated.View key={r.emoji} entering={FadeIn.duration(150)}>
<Pressable
disabled={!canReact}
onPress={() => choose(r.emoji)}
@@ -73,6 +78,17 @@ export function Reactions({
<Text style={[styles.count, { color: colors.muted }]}>+</Text>
</Pressable>
)}
{showComments && (
<Pressable
onPress={() => router.push(`/play/${listenId}`)}
accessibilityRole="button"
accessibilityLabel={commentCount ? `${commentCount} comment${commentCount === 1 ? '' : 's'}` : 'Comments'}
hitSlop={6}
style={({ pressed }) => [styles.chip, pressed && { transform: [{ scale: 0.9 }] }]}>
<Text style={styles.emoji}>💬</Text>
{commentCount ? <Text style={styles.count}>{commentCount}</Text> : null}
</Pressable>
)}
</View>
{quickOpen && (
<Animated.View entering={FadeIn.duration(150)} exiting={FadeOut.duration(120)} style={styles.quick}>
+1 -1
View File
@@ -47,7 +47,7 @@ export function RecentPlays({
</View>
<Text style={styles.time}>{timeAgo(p.playedAt)}</Text>
</Pressable>
<Reactions listenId={p.listenId} reactions={p.reactions} ownerId={ownerId} style={styles.reactions} />
<Reactions listenId={p.listenId} reactions={p.reactions} ownerId={ownerId} commentCount={p.commentCount ?? 0} style={styles.reactions} />
</View>
))}
{credits.map((s) => (
+5
View File
@@ -71,6 +71,11 @@ export default function AdminPage() {
<strong>{REPORT_REASON_LABELS[r.reason as ReportReason] ?? r.reason}</strong>
{r.reporter && <span className="muted"> · reported by @{r.reporter.username}</span>}
</p>
{r.comment && (
<p className="muted small">
Their comment{r.comment.id ? '' : ' (since deleted)'}: <q>{r.comment.body}</q>
</p>
)}
{r.note && <blockquote>{r.note}</blockquote>}
<div className="row">
{r.status === 'open' && (
+18
View File
@@ -130,6 +130,24 @@ input:focus, textarea:focus, select:focus {
.reaction-emoji { font-size: 1.05rem; line-height: 1.3; }
.reaction-count { font-size: 0.78rem; font-variant-numeric: tabular-nums; }
.reaction-add { color: var(--muted); font-size: 1rem; }
a.reaction { text-decoration: none; }
/* Comments on a play (/play/[id]) */
.played-by { display: flex; align-items: center; gap: 0.4rem; flex-wrap: wrap; }
.played-by-user { display: inline-flex; align-items: center; gap: 0.4rem; color: var(--text); }
.comments { display: flex; flex-direction: column; gap: 0.9rem; }
.comments h2 { margin: 0; }
.comment { display: flex; gap: 0.75rem; align-items: flex-start; }
.comment-main { flex: 1; min-width: 0; }
.comment-main a { color: var(--text); }
.comment-body { margin: 0.15rem 0 0; white-space: pre-wrap; overflow-wrap: anywhere; line-height: 1.45; }
.comment-actions { display: flex; gap: 0.6rem; opacity: 0.6; }
.comment:hover .comment-actions, .comment:focus-within .comment-actions { opacity: 1; }
.link-button { background: none; border: 0; padding: 0; font: inherit; font-size: 0.8rem; color: var(--muted); cursor: pointer; }
.link-button:hover { color: var(--text); text-decoration: underline; }
.comment-form { display: flex; gap: 0.6rem; align-items: flex-end; }
.comment-form textarea { flex: 1; resize: vertical; min-height: 2.6rem; }
@media (max-width: 520px) { .comment-actions { opacity: 1; } }
.reaction-add span { font-size: 0.75rem; margin-left: -0.15rem; }
.reaction-add-wrap { position: static; } /* the quick menu anchors to the row, so it never runs off the card */
.reaction-quick { position: absolute; bottom: calc(100% + 0.4rem); left: 0; z-index: 30; display: flex; align-items: center; gap: 0.15rem; padding: 0.3rem; border-radius: 999px; background: #1a1535; border: 1px solid rgba(255, 255, 255, 0.14); box-shadow: 0 14px 30px -10px rgba(0, 0, 0, 0.7); animation: pop 0.18s ease-out; white-space: nowrap; }
+1 -1
View File
@@ -8,7 +8,7 @@ import { notificationPath, notificationText, timeAgo, type NotificationListDTO }
import { Avatar } from '@/components/Avatar';
import { client, useMe } from '@/lib/api';
/** Reactions, new followers and songs sent to you, newest first. Opening it marks them read. */
/** Reactions, comments, new followers and songs sent to you, newest first. Opening it marks them read. */
export default function NotificationsPage() {
const { me, loggedOut } = useMe();
const { mutate } = useSWRConfig();
+145
View File
@@ -0,0 +1,145 @@
'use client';
import Link from 'next/link';
import { useParams } from 'next/navigation';
import { useState } from 'react';
import useSWR from 'swr';
import { COMMENT_MAX_LENGTH, timeAgo, type CommentDTO, type CommentThreadDTO } from '@musicshare/shared';
import { Avatar } from '@/components/Avatar';
import { ReportForm } from '@/components/ProfileMenu';
import { Reactions } from '@/components/Reactions';
import { TrackCard } from '@/components/TrackCard';
import { client, fetcher, useMe } from '@/lib/api';
/** One play and its comments: where the 💬 link and comment notifications lead. */
export default function PlayPage() {
const { id } = useParams<{ id: string }>();
const { me, loggedOut } = useMe();
// Polled while open so other people's comments show up without reloading.
const { data, error, mutate } = useSWR<CommentThreadDTO>(me ? `/listens/${id}/comments` : null, fetcher, { refreshInterval: 5000 });
const [draft, setDraft] = useState('');
const [sending, setSending] = useState(false);
const [problem, setProblem] = useState<string | null>(null);
const [reporting, setReporting] = useState<CommentDTO | null>(null);
if (loggedOut) {
return (
<p className="muted">
<Link href="/login">Log in</Link> to see the comments.
</p>
);
}
if (error) return <p className="muted">That play is gone.</p>;
if (!data) return null;
const owner = data.owner.displayName ?? data.owner.username;
const send = async (e: React.FormEvent) => {
e.preventDefault();
const body = draft.trim();
if (!body) return;
setSending(true);
setProblem(null);
try {
const comment = await client.addComment(id, { body });
setDraft('');
await mutate((t) => (t ? { ...t, comments: [...t.comments, comment] } : t), { revalidate: false });
} catch (err) {
setProblem((err as Error).message);
}
setSending(false);
};
const remove = async (c: CommentDTO) => {
if (!confirm('Delete this comment?')) return;
try {
await client.deleteComment(c.id);
await mutate((t) => (t ? { ...t, comments: t.comments.filter((x) => x.id !== c.id) } : t), { revalidate: false });
} catch (err) {
setProblem((err as Error).message);
}
};
return (
<div className="stack">
<p className="muted played-by">
<Link href={`/u/${data.owner.username}`} className="played-by-user">
<Avatar user={data.owner} size={28} />
<strong>{owner}</strong>
</Link>{' '}
played this · {timeAgo(data.playedAt)}
</p>
<section className="card">
<TrackCard track={data.track} preferred={me?.preferredService} />
<Reactions listenId={data.listenId} reactions={data.reactions} ownerId={data.owner.id} />
</section>
<section className="card comments">
<h2>Comments</h2>
{data.comments.length === 0 && <p className="muted">{data.canComment ? 'No comments yet. Say something!' : 'No comments yet.'}</p>}
{data.comments.map((c) => (
<div key={c.id} className="comment">
<Link href={`/u/${c.user.username}`}>
<Avatar user={c.user} size={34} />
</Link>
<div className="comment-main">
<div className="muted small">
<Link href={`/u/${c.user.username}`}>
<strong>{c.user.displayName ?? c.user.username}</strong>
</Link>{' '}
· {timeAgo(c.createdAt)}
</div>
<p className="comment-body">{c.body}</p>
</div>
<div className="comment-actions">
{c.canDelete && (
<button type="button" className="link-button" onClick={() => remove(c)}>
Delete
</button>
)}
{c.user.id !== me?.id && (
<button type="button" className="link-button" onClick={() => setReporting(c)}>
Report
</button>
)}
</div>
</div>
))}
{data.canComment ? (
<form className="comment-form" onSubmit={send}>
<textarea
value={draft}
onChange={(e) => setDraft(e.target.value)}
onKeyDown={(e) => {
// Enter posts; Shift+Enter is a new line.
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
e.currentTarget.form?.requestSubmit();
}
}}
placeholder={data.owner.id === me?.id ? 'Comment on your song' : `Comment on ${owner}'s song`}
maxLength={COMMENT_MAX_LENGTH}
rows={2}
/>
<button className="btn btn-primary" disabled={!draft.trim() || sending}>
Post
</button>
</form>
) : (
<p className="muted small">Only people {owner} follows can comment on their songs.</p>
)}
{problem && <p className="error">{problem}</p>}
</section>
{reporting && (
<ReportForm
username={reporting.user.username}
name={reporting.user.displayName ?? reporting.user.username}
commentId={reporting.id}
onClose={() => setReporting(null)}
/>
)}
</div>
);
}
+13 -4
View File
@@ -3,7 +3,7 @@ import Link from 'next/link';
export const metadata: Metadata = { title: 'Privacy policy · musicshare' };
const UPDATED = 'October 14, 2026';
const UPDATED = 'October 15, 2026';
const CONTACT = 'app@musicshare.binarygnome.com';
export default function PrivacyPage() {
@@ -40,11 +40,16 @@ export default function PrivacyPage() {
&ldquo;notification access&rdquo;, but the app only reads the song, artist and album from music apps you allow.
It doesn&apos;t read or store your notifications, messages or anything from other apps.
</li>
<li>
<strong>Comments and reactions</strong> you leave on plays. Comments stay until you or the person who played the
song deletes them, or one of your accounts is deleted. Plays with comments are kept in their history so the
conversation isn&apos;t lost.
</li>
<li>
<strong>People:</strong> who you follow, who you&apos;ve pinned, who you&apos;ve blocked, and reports you send.
</li>
<li>
<strong>Notifications:</strong> reactions, new followers and songs (with any note) sent to you, and your
<strong>Notifications:</strong> reactions, comments and replies, new followers and songs (with any note) sent to you, and your
notification settings. If you turn on push notifications, we store the push address your browser or
phone gives us and its encryption keys.
</li>
@@ -63,13 +68,17 @@ export default function PrivacyPage() {
people who aren&apos;t signed in.
</li>
<li>Your followers see what you play in their feed, live.</li>
<li>
Comments on a play can be read by signed-in people who can see that play. Only you and the people you follow can
write them, and you can delete any comment on your plays.
</li>
<li>
Your email address is never shown to other people. It&apos;s used to sign in, to send you confirmation and
password reset emails, and to contact you about your account.
</li>
<li>
People you block can&apos;t find you or see your profile, and you stop following each other. They aren&apos;t
told.
People you block can&apos;t find you or see your profile, and you stop following each other. Their comments on
your plays, and yours on theirs, are removed. They aren&apos;t told.
</li>
<li>
You can <strong>pause sharing</strong> at any time in Settings. While paused, nothing new you play is shared or
+1 -1
View File
@@ -89,7 +89,7 @@ export function NowPlayingCard({
>
<TrackRow track={np.track} preferred={preferred} expanded={expanded} onToggle={() => setExpanded((v) => !v)} />
<ProgressBar np={np} compact={!expanded} />
<Reactions listenId={np.listenId} reactions={np.reactions} ownerId={np.user.id} />
<Reactions listenId={np.listenId} reactions={np.reactions} ownerId={np.user.id} commentCount={np.commentCount ?? 0} />
<AnimatePresence initial={false}>
{expanded && (
<motion.div
+5 -3
View File
@@ -62,7 +62,8 @@ export function ProfileMenu({ profile, onChanged }: { profile: ProfileDTO; onCha
);
}
function ReportForm({ username, name, onClose }: { username: string; name: string; onClose: () => void }) {
/** Report someone's account, or one of their comments (`commentId`). */
export function ReportForm({ username, name, commentId, onClose }: { username: string; name: string; commentId?: string; onClose: () => void }) {
const [reason, setReason] = useState<ReportReason | null>(null);
const [note, setNote] = useState('');
const [sent, setSent] = useState(false);
@@ -72,7 +73,8 @@ function ReportForm({ username, name, onClose }: { username: string; name: strin
e.preventDefault();
if (!reason) return;
try {
await client.report(username, { reason, note: note.trim() || null });
const input = { reason, note: note.trim() || null };
await (commentId ? client.reportComment(commentId, input) : client.report(username, input));
setSent(true);
} catch (err) {
setError((err as Error).message);
@@ -90,7 +92,7 @@ function ReportForm({ username, name, onClose }: { username: string; name: strin
);
}
return (
<Modal onClose={onClose} title={`Report ${name}`}>
<Modal onClose={onClose} title={commentId ? `Report ${name}'s comment` : `Report ${name}`}>
<form className="form" onSubmit={submit}>
<fieldset className="choices">
<legend className="muted">What&apos;s wrong?</legend>
+25 -2
View File
@@ -1,5 +1,6 @@
'use client';
import Link from 'next/link';
import { useEffect, useRef, useState } from 'react';
import { EMOJI_PICKER_GROUPS, QUICK_REACTIONS, searchEmoji, type ReactionDTO } from '@musicshare/shared';
import { client, useMe } from '@/lib/api';
@@ -9,7 +10,18 @@ import { Modal } from './ProfileMenu';
* Emoji reactions on one play. Tap an emoji to add yours (or take it back); "☺+"
* offers the quick six, and "More" opens the full picker. One reaction per person.
*/
export function Reactions({ listenId, reactions, ownerId }: { listenId: string | null; reactions: ReactionDTO[]; ownerId: string }) {
export function Reactions({
listenId,
reactions,
ownerId,
commentCount,
}: {
listenId: string | null;
reactions: ReactionDTO[];
ownerId: string;
/** Shows a 💬 link to the play's comments. */
commentCount?: number;
}) {
const { me } = useMe();
// The server's answer to our last tap, until fresh props arrive (e.g. a realtime update).
const [local, setLocal] = useState<{ from: ReactionDTO[]; value: ReactionDTO[] } | null>(null);
@@ -27,7 +39,8 @@ export function Reactions({ listenId, reactions, ownerId }: { listenId: string |
}, [quickOpen]);
const canReact = Boolean(me && listenId && me.id !== ownerId);
if (!listenId || (!canReact && shown.length === 0)) return null;
const showComments = commentCount !== undefined && Boolean(me);
if (!listenId || (!canReact && shown.length === 0 && !showComments)) return null;
const mine = me ? shown.find((r) => r.users.some((u) => u.id === me.id))?.emoji : undefined;
const choose = async (emoji: string) => {
@@ -77,6 +90,16 @@ export function Reactions({ listenId, reactions, ownerId }: { listenId: string |
)}
</span>
)}
{showComments && (
<Link
href={`/play/${listenId}`}
className="reaction"
aria-label={commentCount ? `${commentCount} comment${commentCount === 1 ? '' : 's'}` : 'Comments'}
>
<span className="reaction-emoji">💬</span>
{commentCount ? <span className="reaction-count">{commentCount}</span> : null}
</Link>
)}
{error && <span className="error">{error}</span>}
{pickerOpen && <EmojiPicker onPick={choose} onClose={() => setPickerOpen(false)} />}
</div>
+1 -1
View File
@@ -48,7 +48,7 @@ export function RecentPlays({
) : (
<div className="recent-row">{row}</div>
)}
<Reactions listenId={p.listenId} reactions={p.reactions} ownerId={ownerId} />
<Reactions listenId={p.listenId} reactions={p.reactions} ownerId={ownerId} commentCount={p.commentCount ?? 0} />
</li>
);
})}