Slim song cards with an expand arrow, and lyrics
Feed and profile cards now show one slim line (small artwork, title, artist, Open button) with the progress bar and reactions. The arrow opens the rest: album, your other services, Share, and lyrics. Lyrics come from LRCLIB (open source; LRCLIB_URL can point at a self-hosted copy, or be empty to turn lyrics off). The server looks each song up once and caches it, including misses (retried after a week). Timed lyrics follow along with the song; otherwise the first lines show with "All lyrics". Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -19,6 +19,8 @@ LASTFM_API_KEY=
|
||||
LASTFM_SHARED_SECRET=
|
||||
# song.link API key (request at https://odesli.co). Enables YouTube Music/TIDAL links; without it those fall back to search.
|
||||
ODESLI_API_KEY=
|
||||
# Lyrics source: LRCLIB (open source; run your own and point this at it). Empty turns lyrics off.
|
||||
LRCLIB_URL=https://lrclib.net
|
||||
# Stable identifier for this app in Plex's auth flow
|
||||
PLEX_CLIENT_ID=musicshare-dev
|
||||
# Let users connect Jellyfin/Plex servers on private networks (LAN). Never enable in a hosted deployment.
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
CREATE TABLE "lyrics" (
|
||||
"track_id" uuid PRIMARY KEY NOT NULL,
|
||||
"synced" text,
|
||||
"plain" text,
|
||||
"instrumental" boolean DEFAULT false NOT NULL,
|
||||
"source_url" text,
|
||||
"fetched_at" timestamp with time zone DEFAULT now() NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
ALTER TABLE "lyrics" ADD CONSTRAINT "lyrics_track_id_tracks_id_fk" FOREIGN KEY ("track_id") REFERENCES "public"."tracks"("id") ON DELETE cascade ON UPDATE no action;
|
||||
File diff suppressed because it is too large
Load Diff
@@ -106,6 +106,13 @@
|
||||
"when": 1792025011207,
|
||||
"tag": "0014_user_services",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 15,
|
||||
"version": "7",
|
||||
"when": 1792025274882,
|
||||
"tag": "0015_lyrics",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -290,6 +290,20 @@ export const passwordResets = pgTable(
|
||||
(t) => [index('password_resets_user_idx').on(t.userId)],
|
||||
);
|
||||
|
||||
/** Lyrics looked up per track (misses too, so we don't keep asking). */
|
||||
export const lyrics = pgTable('lyrics', {
|
||||
trackId: uuid('track_id')
|
||||
.primaryKey()
|
||||
.references(() => tracks.id, { onDelete: 'cascade' }),
|
||||
/** LRC text with timestamps. */
|
||||
synced: text('synced'),
|
||||
plain: text('plain'),
|
||||
instrumental: boolean('instrumental').notNull().default(false),
|
||||
/** Where they came from (the LRCLIB record), null when none were found. */
|
||||
sourceUrl: text('source_url'),
|
||||
fetchedAt: timestamp('fetched_at', { withTimezone: true }).notNull().defaultNow(),
|
||||
});
|
||||
|
||||
const bytea = customType<{ data: Buffer }>({ dataType: () => 'bytea' });
|
||||
|
||||
/** Profile pictures, already resized and re-encoded (WebP, metadata stripped). */
|
||||
|
||||
@@ -26,6 +26,11 @@ const schema = z.object({
|
||||
/** Enables "Sign in with Last.fm" (web auth). Without it, users type their username. */
|
||||
LASTFM_SHARED_SECRET: optional,
|
||||
ODESLI_API_KEY: optional,
|
||||
/** Lyrics come from LRCLIB (open source, self-hostable). Point this at your own instance, or set it empty to turn lyrics off. */
|
||||
LRCLIB_URL: z
|
||||
.string()
|
||||
.default('https://lrclib.net')
|
||||
.transform((v) => v.replace(/\/+$/, '')),
|
||||
/** Apple Music (MusicKit): Team ID, MusicKit key ID, and the key's .p8 contents (newlines may be written as \n). */
|
||||
APPLE_TEAM_ID: optional,
|
||||
APPLE_MUSICKIT_KEY_ID: optional,
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
import { eq } from 'drizzle-orm';
|
||||
import type { FastifyInstance } from 'fastify';
|
||||
import { z } from 'zod';
|
||||
import { STREAMING_SERVICES, openUrl, type StreamingService, type TrackSearchResultDTO } from '@musicshare/shared';
|
||||
import { db, schema } from '../db';
|
||||
import { HttpError } from '../lib/http';
|
||||
import { deezerSearch } from '../providers/catalog';
|
||||
import { getLyrics } from '../services/lyrics';
|
||||
import { resolveTrackLinks } from '../services/resolver';
|
||||
import { getTrackDTOs } from '../services/tracks';
|
||||
|
||||
@@ -32,6 +34,22 @@ export async function trackRoutes(app: FastifyInstance) {
|
||||
return track;
|
||||
});
|
||||
|
||||
/** Lyrics (synced when available) or null. Looked up once per song, then cached. */
|
||||
app.get<{ Params: { id: string } }>(
|
||||
'/tracks/:id/lyrics',
|
||||
{ config: { rateLimit: { max: 60, timeWindow: '1 minute' } } },
|
||||
async (req, reply) => {
|
||||
if (!z.uuid().safeParse(req.params.id).success) throw new HttpError(404, 'Track not found');
|
||||
try {
|
||||
return reply.send(await getLyrics(req.params.id));
|
||||
} catch (err) {
|
||||
if (err instanceof HttpError && err.status === 404) throw err;
|
||||
req.log.warn(err, 'lyrics lookup failed');
|
||||
throw new HttpError(503, "Couldn't get lyrics right now");
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
/** Shareable redirect: /tracks/:id/open?service=spotify (defaults to the viewer's preferred service). */
|
||||
app.get<{ Params: { id: string }; Querystring: { service?: string } }>('/tracks/:id/open', async (req, reply) => {
|
||||
const service = (req.query.service ?? req.user?.preferredService ?? 'spotify') as StreamingService;
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
import { eq } from 'drizzle-orm';
|
||||
import { parseLrc, type LyricsDTO } from '@musicshare/shared';
|
||||
import { db, schema } from '../db';
|
||||
import { env } from '../env';
|
||||
import { HttpError, fetchJson, normalize, primaryArtist } from '../lib/http';
|
||||
|
||||
/** Look again for songs that had none after this long; lyrics get added to LRCLIB all the time. */
|
||||
const RETRY_MISS_MS = 7 * 86_400_000;
|
||||
/** A search result has to be this close in length to count as the same recording. */
|
||||
const DURATION_SLACK_S = 4;
|
||||
|
||||
interface LrclibRecord {
|
||||
id: number;
|
||||
trackName: string;
|
||||
artistName: string;
|
||||
duration: number | null;
|
||||
instrumental: boolean;
|
||||
plainLyrics: string | null;
|
||||
syncedLyrics: string | null;
|
||||
}
|
||||
|
||||
type Row = typeof schema.lyrics.$inferSelect;
|
||||
|
||||
/** The track's lyrics, from our cache or LRCLIB. Null when there are none (or lyrics are turned off). */
|
||||
export async function getLyrics(trackId: string): Promise<LyricsDTO | null> {
|
||||
if (!env.LRCLIB_URL) return null;
|
||||
const [track] = await db.select().from(schema.tracks).where(eq(schema.tracks.id, trackId));
|
||||
if (!track) throw new HttpError(404, 'Track not found');
|
||||
|
||||
let [row] = await db.select().from(schema.lyrics).where(eq(schema.lyrics.trackId, trackId));
|
||||
const stale = row && !row.sourceUrl && Date.now() - row.fetchedAt.getTime() > RETRY_MISS_MS;
|
||||
if (!row || stale) {
|
||||
const found = await lookup(track);
|
||||
const values = {
|
||||
synced: found?.syncedLyrics || null,
|
||||
plain: found?.plainLyrics || null,
|
||||
instrumental: found?.instrumental ?? false,
|
||||
sourceUrl: found ? `${env.LRCLIB_URL}/api/get/${found.id}` : null,
|
||||
fetchedAt: new Date(),
|
||||
};
|
||||
[row] = await db
|
||||
.insert(schema.lyrics)
|
||||
.values({ trackId, ...values })
|
||||
.onConflictDoUpdate({ target: schema.lyrics.trackId, set: values })
|
||||
.returning();
|
||||
}
|
||||
return toDTO(row!);
|
||||
}
|
||||
|
||||
function toDTO(row: Row): LyricsDTO | null {
|
||||
if (!row.sourceUrl || (!row.synced && !row.plain && !row.instrumental)) return null;
|
||||
const synced = row.synced ? parseLrc(row.synced) : null;
|
||||
return {
|
||||
synced: synced?.length ? synced : null,
|
||||
plain: row.plain,
|
||||
instrumental: row.instrumental,
|
||||
source: { name: 'LRCLIB', url: 'https://lrclib.net' },
|
||||
};
|
||||
}
|
||||
|
||||
async function lookup(track: { title: string; artist: string; album: string | null; durationMs: number | null }) {
|
||||
const artist = primaryArtist(track.artist);
|
||||
const headers = { 'user-agent': 'musicshare (https://musicshare.binarygnome.com)' };
|
||||
// Exact lookup needs the length; LRCLIB matches it within a couple of seconds.
|
||||
if (track.durationMs) {
|
||||
const params = new URLSearchParams({ track_name: track.title, artist_name: artist, duration: String(Math.round(track.durationMs / 1000)) });
|
||||
if (track.album) params.set('album_name', track.album);
|
||||
const exact = await fetchJson<LrclibRecord>(`${env.LRCLIB_URL}/api/get?${params}`, { headers }).catch((e: unknown) => {
|
||||
if (e instanceof HttpError && e.status === 404) return null;
|
||||
throw e;
|
||||
});
|
||||
if (exact) return exact;
|
||||
}
|
||||
const params = new URLSearchParams({ track_name: track.title, artist_name: artist });
|
||||
const results = (await fetchJson<LrclibRecord[]>(`${env.LRCLIB_URL}/api/search?${params}`, { headers })) ?? [];
|
||||
const title = normalize(track.title);
|
||||
const matches = results.filter(
|
||||
(r) =>
|
||||
normalize(r.trackName) === title &&
|
||||
normalize(r.artistName).includes(normalize(artist)) &&
|
||||
(!track.durationMs || !r.duration || Math.abs(r.duration - track.durationMs / 1000) <= DURATION_SLACK_S),
|
||||
);
|
||||
// Prefer synced lyrics, then anything with words.
|
||||
return matches.find((r) => r.syncedLyrics) ?? matches.find((r) => r.plainLyrics || r.instrumental) ?? null;
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import { upsertTrack } from '../src/services/tracks';
|
||||
import { json, routeFetch, useTestApp } from './helpers';
|
||||
|
||||
const app = useTestApp();
|
||||
afterEach(() => vi.unstubAllGlobals());
|
||||
|
||||
const record = (over: object = {}) => ({
|
||||
id: 70627,
|
||||
trackName: 'Midnight City',
|
||||
artistName: 'M83',
|
||||
duration: 241,
|
||||
instrumental: false,
|
||||
plainLyrics: 'Waiting in a car\nWaiting for a ride in the dark',
|
||||
syncedLyrics: '[00:01.00] Waiting in a car\n[00:04.50] Waiting for a ride in the dark',
|
||||
...over,
|
||||
});
|
||||
const lyrics = (id: string) => app().inject({ url: `/tracks/${id}/lyrics` });
|
||||
|
||||
describe('lyrics', () => {
|
||||
it('looks up synced lyrics once and serves them from the cache after', async () => {
|
||||
const { id } = await upsertTrack({ title: 'Midnight City', artist: 'M83', durationMs: 241_000 });
|
||||
const calls: string[] = [];
|
||||
vi.stubGlobal('fetch', routeFetch([[/lrclib\.net\/api\/get\?/, (url) => (calls.push(url), json(record()))]]));
|
||||
|
||||
const first = (await lyrics(id)).json();
|
||||
expect(first.synced).toEqual([
|
||||
{ timeMs: 1000, text: 'Waiting in a car' },
|
||||
{ timeMs: 4500, text: 'Waiting for a ride in the dark' },
|
||||
]);
|
||||
expect(first.source.name).toBe('LRCLIB');
|
||||
expect(new URL(calls[0]!).searchParams.get('duration')).toBe('241');
|
||||
expect((await lyrics(id)).json()).toEqual(first);
|
||||
expect(calls).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('falls back to a search, skipping recordings of a different length', async () => {
|
||||
const { id } = await upsertTrack({ title: 'Song', artist: 'Band', durationMs: 200_000 });
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
routeFetch([
|
||||
[/\/api\/get\?/, () => json({ code: 404 }, 404)],
|
||||
[
|
||||
/\/api\/search\?/,
|
||||
() =>
|
||||
json([
|
||||
record({ id: 1, trackName: 'Song', artistName: 'Band', duration: 320, plainLyrics: 'extended mix' }),
|
||||
record({ id: 2, trackName: 'Song', artistName: 'Band', duration: 201, syncedLyrics: null, plainLyrics: 'the one' }),
|
||||
]),
|
||||
],
|
||||
]),
|
||||
);
|
||||
const body = (await lyrics(id)).json();
|
||||
expect(body.synced).toBeNull();
|
||||
expect(body.plain).toBe('the one');
|
||||
});
|
||||
|
||||
it('returns null when nothing matches, and 503 when LRCLIB is down', async () => {
|
||||
const { id } = await upsertTrack({ title: 'Unknown', artist: 'Nobody', durationMs: 100_000 });
|
||||
vi.stubGlobal('fetch', routeFetch([[/lrclib/, () => json({ message: 'down' }, 500)]]));
|
||||
expect((await lyrics(id)).statusCode).toBe(503);
|
||||
vi.stubGlobal('fetch', routeFetch([[/\/api\/get\?/, () => json({}, 404)], [/\/api\/search\?/, () => json([])]]));
|
||||
const res = await lyrics(id);
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.json()).toBeNull();
|
||||
expect((await lyrics('not-a-uuid')).statusCode).toBe(404);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,97 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { Linking, Pressable, StyleSheet, Text, View } from 'react-native';
|
||||
import Animated, { LinearTransition } from 'react-native-reanimated';
|
||||
import useSWR from 'swr';
|
||||
import { currentLyricIndex, playbackPosition, type LyricLine, type LyricsDTO, type NowPlayingDTO, type TrackDTO } from '@musicshare/shared';
|
||||
import { colors, fonts, space } from '@/lib/theme';
|
||||
|
||||
/** Lines shown around the current one while following along. */
|
||||
const BEFORE = 1;
|
||||
const AFTER = 3;
|
||||
/** Lines shown before "All lyrics" when there's nothing to follow. */
|
||||
const PREVIEW = 8;
|
||||
|
||||
/**
|
||||
* A song's lyrics. With timed lyrics and a live position (`np`), shows a few
|
||||
* lines around the one being sung and follows along; "All lyrics" shows the rest.
|
||||
*/
|
||||
export function Lyrics({ track, np }: { track: TrackDTO; np?: NowPlayingDTO }) {
|
||||
const { data, error, isLoading } = useSWR<LyricsDTO | null>(`/tracks/${track.id}/lyrics`);
|
||||
const [full, setFull] = useState(false);
|
||||
|
||||
if (isLoading) return <Text style={styles.note}>Finding lyrics…</Text>;
|
||||
if (error) return <Text style={styles.note}>Couldn't load lyrics right now.</Text>;
|
||||
if (!data) return <Text style={styles.note}>No lyrics found for this song.</Text>;
|
||||
if (data.instrumental && !data.synced && !data.plain) return <Text style={styles.note}>♪ Instrumental</Text>;
|
||||
|
||||
const synced = data.synced;
|
||||
const live = Boolean(np?.isPlaying && playbackPosition(np, 0));
|
||||
const following = Boolean(synced && live && !full);
|
||||
const text = synced ? synced.map((l) => l.text).join('\n') : (data.plain ?? '');
|
||||
const all = text.split('\n');
|
||||
const clipped = !following && !full && all.length > PREVIEW;
|
||||
const canToggle = (synced && live) || clipped || full;
|
||||
|
||||
return (
|
||||
<View style={styles.wrap}>
|
||||
<Pressable onPress={() => setFull((v) => !v)} disabled={!canToggle} accessibilityRole="button" accessibilityLabel={full ? 'Show fewer lyrics' : 'Show all lyrics'}>
|
||||
{following && synced && np ? (
|
||||
// Each fresh position from the server restarts the clock.
|
||||
<FollowAlong key={`${np.track.id}|${np.progressMs}|${np.updatedAt}`} lines={synced} np={np} />
|
||||
) : (
|
||||
(clipped ? all.slice(0, PREVIEW) : all).map((t, i) => (
|
||||
<Text key={i} style={[styles.line, styles.plain]}>
|
||||
{t}
|
||||
</Text>
|
||||
))
|
||||
)}
|
||||
</Pressable>
|
||||
<View style={styles.footer}>
|
||||
{canToggle && (
|
||||
<Text style={styles.toggle} onPress={() => setFull((v) => !v)}>
|
||||
{!full ? 'All lyrics' : synced && live ? 'Follow along' : 'Less'}
|
||||
</Text>
|
||||
)}
|
||||
<Text style={styles.source} onPress={() => Linking.openURL(data.source.url)}>
|
||||
Lyrics from {data.source.name}
|
||||
</Text>
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
/** The line being sung, one before it and a few after, moving with the song. */
|
||||
function FollowAlong({ lines, np }: { lines: LyricLine[]; np: NowPlayingDTO }) {
|
||||
const [receivedAt] = useState(() => Date.now());
|
||||
const [now, setNow] = useState(receivedAt);
|
||||
useEffect(() => {
|
||||
const id = setInterval(() => setNow(Date.now()), 500);
|
||||
return () => clearInterval(id);
|
||||
}, []);
|
||||
|
||||
const position = playbackPosition(np, now - receivedAt)?.positionMs ?? 0;
|
||||
const current = currentLyricIndex(lines, position);
|
||||
const from = Math.max(0, current - BEFORE);
|
||||
return lines.slice(from, Math.max(current, 0) + AFTER + 1).map((l, i) => {
|
||||
const index = from + i;
|
||||
const state = index < current ? styles.past : index === current ? styles.now : styles.next;
|
||||
return (
|
||||
<Animated.Text key={`${l.timeMs}-${index}`} layout={LinearTransition.duration(300)} style={[styles.line, state]}>
|
||||
{l.text || '♪'}
|
||||
</Animated.Text>
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
wrap: { gap: space.sm },
|
||||
note: { color: colors.muted, fontSize: 13 },
|
||||
line: { color: colors.text, fontSize: 15, lineHeight: 22 },
|
||||
plain: { opacity: 0.9 },
|
||||
past: { opacity: 0.4 },
|
||||
now: { fontFamily: fonts.display, fontSize: 17, lineHeight: 24 },
|
||||
next: { opacity: 0.65 },
|
||||
footer: { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center' },
|
||||
toggle: { color: colors.accent2, fontSize: 13, fontWeight: '600' },
|
||||
source: { color: colors.muted, fontSize: 11, marginLeft: 'auto' },
|
||||
});
|
||||
@@ -1,7 +1,7 @@
|
||||
import { Image } from 'expo-image';
|
||||
import { LinearGradient } from 'expo-linear-gradient';
|
||||
import { router } from 'expo-router';
|
||||
import { useEffect, useRef } from 'react';
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { Linking, Pressable, StyleSheet, Text, View } from 'react-native';
|
||||
import Animated, {
|
||||
FadeIn,
|
||||
@@ -17,9 +17,10 @@ import { successHaptic, tapHaptic } from '@/lib/haptics';
|
||||
import { colors, radius, space } from '@/lib/theme';
|
||||
import { Avatar } from './Avatar';
|
||||
import { Equalizer } from './Equalizer';
|
||||
import { Lyrics } from './Lyrics';
|
||||
import { ProgressBar } from './ProgressBar';
|
||||
import { Reactions } from './Reactions';
|
||||
import { TrackCard } from './TrackCard';
|
||||
import { ServiceLinks, TrackRow } from './TrackCard';
|
||||
|
||||
export function NowPlayingCard({
|
||||
np,
|
||||
@@ -42,6 +43,11 @@ export function NowPlayingCard({
|
||||
wasPinned.current = pinned;
|
||||
}, [pinned, star]);
|
||||
const starStyle = useAnimatedStyle(() => ({ transform: [{ scale: star.value }] }));
|
||||
const [expanded, setExpanded] = useState(false);
|
||||
const toggle = () => {
|
||||
tapHaptic();
|
||||
setExpanded((v) => !v);
|
||||
};
|
||||
|
||||
const togglePin = () => {
|
||||
if (pinned) tapHaptic();
|
||||
@@ -62,7 +68,7 @@ export function NowPlayingCard({
|
||||
<View style={styles.header}>
|
||||
{showUser && (
|
||||
<Pressable style={styles.user} onPress={() => router.push(`/u/${np.user.username}`)} accessibilityRole="link">
|
||||
<Avatar user={np.user} size={30} live={np.isPlaying} />
|
||||
<Avatar user={np.user} size={26} live={np.isPlaying} />
|
||||
<Text style={styles.name} numberOfLines={1}>
|
||||
{np.user.displayName ?? np.user.username}
|
||||
</Text>
|
||||
@@ -93,10 +99,16 @@ export function NowPlayingCard({
|
||||
</View>
|
||||
|
||||
<Animated.View key={np.track.id} entering={FadeInDown.duration(380).springify()} exiting={FadeOut.duration(200)}>
|
||||
<TrackCard track={np.track} preferred={preferred} />
|
||||
<TrackRow track={np.track} preferred={preferred} expanded={expanded} onToggle={toggle} />
|
||||
</Animated.View>
|
||||
<ProgressBar np={np} />
|
||||
<ProgressBar np={np} compact={!expanded} />
|
||||
<Reactions listenId={np.listenId} reactions={np.reactions} ownerId={np.user.id} />
|
||||
{expanded && (
|
||||
<Animated.View entering={FadeIn.duration(200)} exiting={FadeOut.duration(120)} style={styles.details}>
|
||||
<ServiceLinks track={np.track} preferred={preferred} />
|
||||
<Lyrics track={np.track} np={np} />
|
||||
</Animated.View>
|
||||
)}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
@@ -104,13 +116,14 @@ export function NowPlayingCard({
|
||||
const styles = StyleSheet.create({
|
||||
card: {
|
||||
borderRadius: radius.lg,
|
||||
padding: space.lg,
|
||||
gap: space.md,
|
||||
padding: space.md + 2,
|
||||
gap: space.sm + 2,
|
||||
overflow: 'hidden',
|
||||
backgroundColor: colors.surface,
|
||||
borderWidth: 1,
|
||||
borderColor: colors.border,
|
||||
},
|
||||
details: { gap: space.md },
|
||||
pinned: { borderColor: 'rgba(251,191,36,0.55)' },
|
||||
backdrop: { position: 'absolute', top: '-40%', left: '-40%', width: '180%', height: '180%', opacity: 0.55 },
|
||||
header: { flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', gap: space.sm },
|
||||
|
||||
@@ -6,13 +6,13 @@ import { formatDuration, playbackPosition, type NowPlayingDTO } from '@musicshar
|
||||
import { colors } from '@/lib/theme';
|
||||
|
||||
/** Where they are in the song. Renders nothing when the source doesn't report a position. */
|
||||
export function ProgressBar({ np }: { np: NowPlayingDTO }) {
|
||||
export function ProgressBar({ np, compact }: { np: NowPlayingDTO; /** Just the bar, no times. */ compact?: boolean }) {
|
||||
if (!np.isPlaying || playbackPosition(np, 0) === null) return null;
|
||||
// Each fresh position from the server restarts the clock, realigning the bar.
|
||||
return <Bar key={`${np.track.id}|${np.progressMs}|${np.updatedAt}`} np={np} />;
|
||||
return <Bar key={`${np.track.id}|${np.progressMs}|${np.updatedAt}`} np={np} compact={compact} />;
|
||||
}
|
||||
|
||||
function Bar({ np }: { np: NowPlayingDTO }) {
|
||||
function Bar({ np, compact }: { np: NowPlayingDTO; compact?: boolean }) {
|
||||
const [receivedAt] = useState(() => Date.now());
|
||||
const [now, setNow] = useState(receivedAt);
|
||||
useEffect(() => {
|
||||
@@ -36,16 +36,18 @@ function Bar({ np }: { np: NowPlayingDTO }) {
|
||||
<LinearGradient colors={['#7b2ff7', '#2f8cff']} start={{ x: 0, y: 0 }} end={{ x: 1, y: 0 }} style={StyleSheet.absoluteFill} />
|
||||
</Animated.View>
|
||||
</View>
|
||||
<View style={styles.times}>
|
||||
<Text style={styles.time}>{formatDuration(pos.positionMs)}</Text>
|
||||
<Text style={styles.time}>{formatDuration(pos.durationMs)}</Text>
|
||||
</View>
|
||||
{!compact && (
|
||||
<View style={styles.times}>
|
||||
<Text style={styles.time}>{formatDuration(pos.positionMs)}</Text>
|
||||
<Text style={styles.time}>{formatDuration(pos.durationMs)}</Text>
|
||||
</View>
|
||||
)}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
wrap: { marginTop: 12 },
|
||||
wrap: { marginTop: 2 },
|
||||
track: { height: 4, borderRadius: 2, backgroundColor: 'rgba(255,255,255,0.14)', overflow: 'hidden' },
|
||||
fill: { height: '100%', borderRadius: 2, overflow: 'hidden' },
|
||||
times: { flexDirection: 'row', justifyContent: 'space-between', marginTop: 4 },
|
||||
|
||||
@@ -20,50 +20,114 @@ function shareTrack(track: TrackDTO, from: string | undefined) {
|
||||
Share.share({ message: `${shareText(track)} ${url}`, url, title: shareText(track) }).catch((e) => showError(e, "Couldn't share"));
|
||||
}
|
||||
|
||||
export function TrackCard({ track, preferred }: { track: TrackDTO; preferred: StreamingService | null | undefined }) {
|
||||
const { me } = useSession();
|
||||
const primary = preferred ? openUrl(track, preferred) : null;
|
||||
const others = viewerServices(me).filter((s) => s !== preferred);
|
||||
function Artwork({ track, size }: { track: TrackDTO; size: number }) {
|
||||
const box = { width: size, height: size, borderRadius: size > 64 ? 14 : 10 };
|
||||
return track.artworkUrl ? (
|
||||
<Image source={track.artworkUrl} style={[styles.artwork, box]} contentFit="cover" transition={150} />
|
||||
) : (
|
||||
<View style={[styles.artwork, styles.artworkEmpty, box]}>
|
||||
<Text style={[styles.note, { fontSize: size / 3 }]}>♪</Text>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
/** The big "Open in Spotify" button for your main service ("Search in" when we have no direct link). */
|
||||
function PrimaryButton({ track, preferred, label }: { track: TrackDTO; preferred: StreamingService; label?: 'short' }) {
|
||||
const { url, exact } = openUrl(track, preferred);
|
||||
const name = SERVICE_LABELS[preferred];
|
||||
return (
|
||||
<Button
|
||||
small
|
||||
variant="primary"
|
||||
title={label === 'short' ? (exact ? 'Open ▶' : 'Search') : `${exact ? 'Open' : 'Search'} in ${name}`}
|
||||
accessibilityLabel={`${exact ? 'Open' : 'Search'} in ${name}`}
|
||||
onPress={() => open(url)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
/** Quieter links for your other services, and Share. */
|
||||
export function ServiceLinks({ track, preferred }: { track: TrackDTO; preferred: StreamingService | null | undefined }) {
|
||||
const { me } = useSession();
|
||||
const others = viewerServices(me).filter((s) => s !== preferred);
|
||||
return (
|
||||
<View style={styles.services}>
|
||||
{others.map((s) => {
|
||||
const { url, exact } = openUrl(track, s);
|
||||
return (
|
||||
<Pressable key={s} onPress={() => open(url)} hitSlop={6} accessibilityRole="link">
|
||||
<Text style={[styles.service, !exact && { opacity: 0.55 }]}>{SERVICE_LABELS[s]}</Text>
|
||||
</Pressable>
|
||||
);
|
||||
})}
|
||||
<Pressable onPress={() => shareTrack(track, me?.username)} hitSlop={6} accessibilityRole="button" accessibilityLabel="Share this song">
|
||||
<Text style={[styles.service, styles.share]}>Share ↗</Text>
|
||||
</Pressable>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* One slim line: small artwork, title and artist, the open button, and an
|
||||
* arrow that shows the rest (`expanded` / `onToggle`).
|
||||
*/
|
||||
export function TrackRow({
|
||||
track,
|
||||
preferred,
|
||||
expanded,
|
||||
onToggle,
|
||||
}: {
|
||||
track: TrackDTO;
|
||||
preferred: StreamingService | null | undefined;
|
||||
expanded: boolean;
|
||||
onToggle: () => void;
|
||||
}) {
|
||||
return (
|
||||
<View style={styles.row}>
|
||||
<Pressable style={styles.rowMain} onPress={onToggle} accessibilityRole="button" accessibilityState={{ expanded }}>
|
||||
<Artwork track={track} size={52} />
|
||||
<View style={styles.body}>
|
||||
<Text style={styles.title} numberOfLines={1}>
|
||||
{track.title}
|
||||
</Text>
|
||||
<Text style={styles.artist} numberOfLines={1}>
|
||||
{track.artist}
|
||||
{expanded && track.album ? <Text style={styles.muted}> · {track.album}</Text> : null}
|
||||
</Text>
|
||||
</View>
|
||||
</Pressable>
|
||||
{preferred && <PrimaryButton track={track} preferred={preferred} label="short" />}
|
||||
<Pressable
|
||||
onPress={onToggle}
|
||||
hitSlop={10}
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={expanded ? 'Show less' : 'Show more'}
|
||||
style={styles.chevron}>
|
||||
<Text style={[styles.chevronText, expanded && { transform: [{ rotate: '180deg' }] }]}>⌄</Text>
|
||||
</Pressable>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
/** A song with big artwork and every link showing (e.g. a profile's featured song). */
|
||||
export function TrackCard({ track, preferred }: { track: TrackDTO; preferred: StreamingService | null | undefined }) {
|
||||
return (
|
||||
<View style={styles.track}>
|
||||
{track.artworkUrl ? (
|
||||
<Image source={track.artworkUrl} style={styles.artwork} contentFit="cover" transition={150} />
|
||||
) : (
|
||||
<View style={[styles.artwork, styles.artworkEmpty]}>
|
||||
<Text style={styles.note}>♪</Text>
|
||||
</View>
|
||||
)}
|
||||
<Artwork track={track} size={96} />
|
||||
<View style={styles.body}>
|
||||
<Text style={styles.title} numberOfLines={1}>
|
||||
<Text style={[styles.title, styles.titleBig]} numberOfLines={1}>
|
||||
{track.title}
|
||||
</Text>
|
||||
<Text style={styles.artist} numberOfLines={1}>
|
||||
{track.artist}
|
||||
{track.album ? <Text style={styles.muted}> · {track.album}</Text> : null}
|
||||
</Text>
|
||||
{preferred && primary && (
|
||||
<Button
|
||||
small
|
||||
variant="primary"
|
||||
title={`${primary.exact ? 'Open' : 'Search'} in ${SERVICE_LABELS[preferred]}`}
|
||||
onPress={() => open(primary.url)}
|
||||
style={styles.primary}
|
||||
/>
|
||||
{preferred && (
|
||||
<View style={styles.primary}>
|
||||
<PrimaryButton track={track} preferred={preferred} />
|
||||
</View>
|
||||
)}
|
||||
<View style={styles.services}>
|
||||
{others.map((s) => {
|
||||
const { url, exact } = openUrl(track, s);
|
||||
return (
|
||||
<Pressable key={s} onPress={() => open(url)} hitSlop={6} accessibilityRole="link">
|
||||
<Text style={[styles.service, !exact && { opacity: 0.55 }]}>{SERVICE_LABELS[s]}</Text>
|
||||
</Pressable>
|
||||
);
|
||||
})}
|
||||
<Pressable onPress={() => shareTrack(track, me?.username)} hitSlop={6} accessibilityRole="button" accessibilityLabel="Share this song">
|
||||
<Text style={[styles.service, styles.share]}>Share ↗</Text>
|
||||
</Pressable>
|
||||
</View>
|
||||
<ServiceLinks track={track} preferred={preferred} />
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
@@ -71,20 +135,22 @@ export function TrackCard({ track, preferred }: { track: TrackDTO; preferred: St
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
track: { flexDirection: 'row', gap: space.md + 2, alignItems: 'flex-start' },
|
||||
row: { flexDirection: 'row', alignItems: 'center', gap: space.sm },
|
||||
rowMain: { flex: 1, minWidth: 0, flexDirection: 'row', alignItems: 'center', gap: space.md },
|
||||
artwork: {
|
||||
width: 96,
|
||||
height: 96,
|
||||
borderRadius: 14,
|
||||
backgroundColor: colors.surface2,
|
||||
borderWidth: StyleSheet.hairlineWidth,
|
||||
borderColor: 'rgba(255,255,255,0.12)',
|
||||
},
|
||||
artworkEmpty: { alignItems: 'center', justifyContent: 'center', backgroundColor: '#3a1a6e' },
|
||||
note: { color: 'rgba(255,255,255,0.85)', fontSize: 30 },
|
||||
note: { color: 'rgba(255,255,255,0.85)' },
|
||||
body: { flex: 1, minWidth: 0, gap: 2 },
|
||||
title: { color: colors.text, fontFamily: fonts.display, fontSize: 18, letterSpacing: -0.2 },
|
||||
title: { color: colors.text, fontFamily: fonts.display, fontSize: 16, letterSpacing: -0.2 },
|
||||
titleBig: { fontSize: 18 },
|
||||
artist: { color: colors.text, opacity: 0.85, fontSize: 14 },
|
||||
muted: { color: colors.muted },
|
||||
chevron: { paddingHorizontal: space.xs, alignSelf: 'stretch', justifyContent: 'center' },
|
||||
chevronText: { color: colors.muted, fontSize: 22, lineHeight: 24 },
|
||||
share: { backgroundColor: 'rgba(123,47,247,0.28)', borderColor: 'rgba(123,47,247,0.5)' },
|
||||
primary: { alignSelf: 'flex-start', marginTop: space.sm },
|
||||
services: { flexDirection: 'row', flexWrap: 'wrap', gap: space.xs + 2, marginTop: space.sm + 2 },
|
||||
|
||||
@@ -227,7 +227,9 @@ input:focus, textarea:focus, select:focus {
|
||||
.form label.checkbox { flex-direction: row; align-items: center; gap: 0.5rem; font-weight: 500; }
|
||||
|
||||
/* Now-playing cards take their colour from the album art. */
|
||||
.np-card { border-color: rgba(255, 255, 255, 0.11); }
|
||||
.np-card { border-color: rgba(255, 255, 255, 0.11); padding: 0.9rem 1rem; }
|
||||
.np-card .card-header { margin-bottom: 0.65rem; }
|
||||
.np-card .reactions { margin-top: 0.55rem; }
|
||||
.np-card.pinned { border-color: rgba(251, 191, 36, 0.45); box-shadow: 0 0 0 1px rgba(251, 191, 36, 0.15), 0 18px 40px -20px rgba(251, 191, 36, 0.35); }
|
||||
.np-backdrop {
|
||||
position: absolute; inset: -40%; z-index: 0; background-size: cover; background-position: center;
|
||||
@@ -286,6 +288,33 @@ input:focus, textarea:focus, select:focus {
|
||||
.track-title { font-family: var(--font-display); font-weight: 700; font-size: 1.15rem; letter-spacing: -0.01em; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.track-artist { color: var(--text); opacity: 0.82; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.progress { margin-top: 0.85rem; }
|
||||
.track-row { display: flex; align-items: center; gap: 0.6rem; }
|
||||
.track-row-main {
|
||||
flex: 1; min-width: 0; display: flex; align-items: center; gap: 0.8rem; padding: 0; border: 0; background: none;
|
||||
color: inherit; font: inherit; text-align: left; cursor: pointer;
|
||||
}
|
||||
.track-row-main .track-body { display: flex; flex-direction: column; }
|
||||
.track-row-main .track-title { font-size: 1.02rem; }
|
||||
.artwork.artwork-row { width: 56px; height: 56px; border-radius: 10px; font-size: 1.3rem; }
|
||||
.track-row:hover .artwork { transform: scale(1.04) rotate(-1deg); }
|
||||
.chevron {
|
||||
display: grid; place-items: center; width: 32px; height: 32px; flex-shrink: 0; border-radius: 999px; border: 0; cursor: pointer;
|
||||
background: rgba(255, 255, 255, 0.06); color: var(--muted); transition: transform 0.3s var(--spring), color 0.2s, background 0.2s;
|
||||
}
|
||||
.chevron:hover { color: var(--text); background: rgba(255, 255, 255, 0.12); }
|
||||
.chevron.open { transform: rotate(180deg); }
|
||||
.np-card .progress { margin-top: 0.65rem; }
|
||||
.np-details { overflow: hidden; }
|
||||
.np-details > .track-actions { margin-top: 0.75rem; }
|
||||
.lyrics { margin-top: 0.9rem; }
|
||||
.lyrics-lines { display: flex; flex-direction: column; gap: 0.15rem; }
|
||||
.lyric { margin: 0; line-height: 1.45; transition: opacity 0.3s, font-size 0.3s; }
|
||||
.lyric-past { opacity: 0.4; }
|
||||
.lyric-next { opacity: 0.65; }
|
||||
.lyric-now { font-family: var(--font-display); font-weight: 700; font-size: 1.08rem; }
|
||||
.lyrics-note { margin: 0.9rem 0 0; font-size: 0.85rem; }
|
||||
.lyrics-footer { display: flex; align-items: center; justify-content: space-between; margin-top: 0.5rem; font-size: 0.82rem; }
|
||||
.lyrics-source { margin-left: auto; font-size: 0.72rem; }
|
||||
.progress-track { height: 4px; border-radius: 999px; background: rgba(255, 255, 255, 0.14); overflow: hidden; }
|
||||
.progress-fill { height: 100%; border-radius: inherit; background: var(--grad); transition: width 1s linear; }
|
||||
.progress-times { display: flex; justify-content: space-between; margin-top: 0.3rem; font-size: 0.75rem; color: var(--muted); font-variant-numeric: tabular-nums; }
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect, useState } from 'react';
|
||||
import useSWR from 'swr';
|
||||
import { currentLyricIndex, playbackPosition, type LyricLine, type LyricsDTO, type NowPlayingDTO, type TrackDTO } from '@musicshare/shared';
|
||||
import { fetcher } from '@/lib/api';
|
||||
|
||||
/** Lines shown around the current one while following along. */
|
||||
const BEFORE = 1;
|
||||
const AFTER = 3;
|
||||
/** Lines shown before "All lyrics" when there's nothing to follow. */
|
||||
const PREVIEW = 8;
|
||||
|
||||
/**
|
||||
* A song's lyrics. With timed lyrics and a live position (`np`), shows a few
|
||||
* lines around the one being sung and follows along; "All lyrics" shows the rest.
|
||||
*/
|
||||
export function Lyrics({ track, np }: { track: TrackDTO; np?: NowPlayingDTO }) {
|
||||
const { data, error, isLoading } = useSWR<LyricsDTO | null>(`/tracks/${track.id}/lyrics`, fetcher);
|
||||
const [full, setFull] = useState(false);
|
||||
|
||||
if (isLoading) return <p className="muted lyrics-note">Finding lyrics…</p>;
|
||||
if (error) return <p className="muted lyrics-note">Couldn't load lyrics right now.</p>;
|
||||
if (!data) return <p className="muted lyrics-note">No lyrics found for this song.</p>;
|
||||
if (data.instrumental && !data.synced && !data.plain) return <p className="muted lyrics-note">♪ Instrumental</p>;
|
||||
|
||||
const synced = data.synced;
|
||||
const live = Boolean(np?.isPlaying && playbackPosition(np, 0));
|
||||
const following = Boolean(synced && live && !full);
|
||||
const text = synced ? synced.map((l) => l.text).join('\n') : (data.plain ?? '');
|
||||
const all = text.split('\n');
|
||||
const clipped = !following && !full && all.length > PREVIEW;
|
||||
const canToggle = (synced && live) || clipped || full;
|
||||
|
||||
return (
|
||||
<div className="lyrics">
|
||||
<div className="lyrics-lines" aria-live={following ? 'polite' : undefined}>
|
||||
{following && synced && np ? (
|
||||
// Each fresh position from the server restarts the clock.
|
||||
<FollowAlong key={`${np.track.id}|${np.progressMs}|${np.updatedAt}`} lines={synced} np={np} />
|
||||
) : (
|
||||
(clipped ? all.slice(0, PREVIEW) : all).map((t, i) => (
|
||||
<p key={i} className="lyric lyric-plain">
|
||||
{t || ' '}
|
||||
</p>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
<div className="lyrics-footer">
|
||||
{canToggle && (
|
||||
<button type="button" className="link-button" onClick={() => setFull((v) => !v)}>
|
||||
{!full ? 'All lyrics' : synced && live ? 'Follow along' : 'Less'}
|
||||
</button>
|
||||
)}
|
||||
<a className="muted lyrics-source" href={data.source.url} target="_blank" rel="noreferrer">
|
||||
Lyrics from {data.source.name}
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** The line being sung, one before it and a few after, moving with the song. */
|
||||
function FollowAlong({ lines, np }: { lines: LyricLine[]; np: NowPlayingDTO }) {
|
||||
const [receivedAt] = useState(() => Date.now());
|
||||
const [now, setNow] = useState(receivedAt);
|
||||
useEffect(() => {
|
||||
const id = setInterval(() => setNow(Date.now()), 500);
|
||||
return () => clearInterval(id);
|
||||
}, []);
|
||||
|
||||
const position = playbackPosition(np, now - receivedAt)?.positionMs ?? 0;
|
||||
const current = currentLyricIndex(lines, position);
|
||||
const from = Math.max(0, current - BEFORE);
|
||||
return lines.slice(from, Math.max(current, 0) + AFTER + 1).map((l, i) => {
|
||||
const index = from + i;
|
||||
const state = index < current ? 'past' : index === current ? 'now' : 'next';
|
||||
return (
|
||||
<p key={`${l.timeMs}-${index}`} className={`lyric lyric-${state}`}>
|
||||
{l.text || '♪'}
|
||||
</p>
|
||||
);
|
||||
});
|
||||
}
|
||||
@@ -1,13 +1,15 @@
|
||||
'use client';
|
||||
|
||||
import { AnimatePresence, motion } from 'motion/react';
|
||||
import { useState } from 'react';
|
||||
import Link from 'next/link';
|
||||
import { SERVICE_LABELS, timeAgo, type NowPlayingDTO, type StreamingService } from '@musicshare/shared';
|
||||
import { Avatar } from './Avatar';
|
||||
import { Equalizer } from './Equalizer';
|
||||
import { Lyrics } from './Lyrics';
|
||||
import { ProgressBar } from './ProgressBar';
|
||||
import { Reactions } from './Reactions';
|
||||
import { TrackCard } from './TrackCard';
|
||||
import { ServiceLinks, TrackRow } from './TrackCard';
|
||||
|
||||
export function NowPlayingCard({
|
||||
np,
|
||||
@@ -23,6 +25,7 @@ export function NowPlayingCard({
|
||||
onTogglePin?: () => void;
|
||||
}) {
|
||||
const sourceLabel = np.sourceApp ?? SERVICE_LABELS[np.source];
|
||||
const [expanded, setExpanded] = useState(false);
|
||||
return (
|
||||
<article className={`card np-card ${pinned ? 'pinned' : ''} ${np.isPlaying ? 'playing' : ''}`}>
|
||||
{/* The card glows with its album art; crossfades when the song changes. */}
|
||||
@@ -42,7 +45,7 @@ export function NowPlayingCard({
|
||||
<header className="card-header">
|
||||
{showUser && (
|
||||
<Link href={`/u/${np.user.username}`} className="user-chip">
|
||||
<Avatar user={np.user} size={30} live={np.isPlaying} />
|
||||
<Avatar user={np.user} size={26} live={np.isPlaying} />
|
||||
<span className="user-name">{np.user.displayName ?? np.user.username}</span>
|
||||
</Link>
|
||||
)}
|
||||
@@ -84,9 +87,25 @@ export function NowPlayingCard({
|
||||
exit={{ opacity: 0, y: -12, filter: 'blur(6px)' }}
|
||||
transition={{ duration: 0.35, ease: [0.22, 1, 0.36, 1] }}
|
||||
>
|
||||
<TrackCard track={np.track} preferred={preferred} />
|
||||
<ProgressBar np={np} />
|
||||
<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} />
|
||||
<AnimatePresence initial={false}>
|
||||
{expanded && (
|
||||
<motion.div
|
||||
className="np-details"
|
||||
initial={{ opacity: 0, height: 0 }}
|
||||
animate={{ opacity: 1, height: 'auto' }}
|
||||
exit={{ opacity: 0, height: 0 }}
|
||||
transition={{ duration: 0.25, ease: [0.22, 1, 0.36, 1] }}
|
||||
>
|
||||
<div className="track-actions">
|
||||
<ServiceLinks track={np.track} preferred={preferred} />
|
||||
</div>
|
||||
<Lyrics track={np.track} np={np} />
|
||||
</motion.div>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
</motion.div>
|
||||
</AnimatePresence>
|
||||
</article>
|
||||
|
||||
@@ -4,13 +4,13 @@ import { useEffect, useState } from 'react';
|
||||
import { formatDuration, playbackPosition, type NowPlayingDTO } from '@musicshare/shared';
|
||||
|
||||
/** Where they are in the song. Renders nothing when the source doesn't report a position. */
|
||||
export function ProgressBar({ np }: { np: NowPlayingDTO }) {
|
||||
export function ProgressBar({ np, compact }: { np: NowPlayingDTO; /** Just the bar, no times. */ compact?: boolean }) {
|
||||
if (!np.isPlaying || playbackPosition(np, 0) === null) return null;
|
||||
// Each fresh position from the server restarts the clock, realigning the bar.
|
||||
return <Bar key={`${np.track.id}|${np.progressMs}|${np.updatedAt}`} np={np} />;
|
||||
return <Bar key={`${np.track.id}|${np.progressMs}|${np.updatedAt}`} np={np} compact={compact} />;
|
||||
}
|
||||
|
||||
function Bar({ np }: { np: NowPlayingDTO }) {
|
||||
function Bar({ np, compact }: { np: NowPlayingDTO; compact?: boolean }) {
|
||||
const [receivedAt] = useState(() => Date.now());
|
||||
const [now, setNow] = useState(receivedAt);
|
||||
useEffect(() => {
|
||||
@@ -25,10 +25,12 @@ function Bar({ np }: { np: NowPlayingDTO }) {
|
||||
<div className="progress-track">
|
||||
<div className="progress-fill" style={{ width: `${(pos.positionMs / pos.durationMs) * 100}%` }} />
|
||||
</div>
|
||||
<div className="progress-times" aria-hidden>
|
||||
<span>{formatDuration(pos.positionMs)}</span>
|
||||
<span>{formatDuration(pos.durationMs)}</span>
|
||||
</div>
|
||||
{!compact && (
|
||||
<div className="progress-times" aria-hidden>
|
||||
<span>{formatDuration(pos.positionMs)}</span>
|
||||
<span>{formatDuration(pos.durationMs)}</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -4,6 +4,85 @@ import { SERVICE_LABELS, openUrl, viewerServices, type StreamingService, type Tr
|
||||
import { useMe } from '@/lib/api';
|
||||
import { ShareButton } from './ShareButton';
|
||||
|
||||
function Artwork({ track, small }: { track: TrackDTO; small?: boolean }) {
|
||||
const cls = small ? 'artwork artwork-row' : 'artwork';
|
||||
return track.artworkUrl ? <img className={cls} src={track.artworkUrl} alt="" /> : <div className={`${cls} artwork-empty`}>♪</div>;
|
||||
}
|
||||
|
||||
/** The big "Open in Spotify" button for your main service ("Search in" when we have no direct link). */
|
||||
function PrimaryLink({ track, preferred, short }: { track: TrackDTO; preferred: StreamingService; short?: boolean }) {
|
||||
const { url, exact } = openUrl(track, preferred);
|
||||
const full = `${exact ? 'Open' : 'Search'} in ${SERVICE_LABELS[preferred]}`;
|
||||
return (
|
||||
<a className={`btn btn-primary ${short ? 'btn-small' : ''}`} href={url} target="_blank" rel="noreferrer" title={full}>
|
||||
{short ? (exact ? 'Open ▶' : 'Search') : full}
|
||||
</a>
|
||||
);
|
||||
}
|
||||
|
||||
/** Quieter links for your other services, and Share. */
|
||||
export function ServiceLinks({ track, preferred }: { track: TrackDTO; preferred: StreamingService | null | undefined }) {
|
||||
const { me } = useMe();
|
||||
const others = viewerServices(me).filter((s) => s !== preferred);
|
||||
return (
|
||||
<>
|
||||
{others.map((s) => {
|
||||
const { url, exact } = openUrl(track, s);
|
||||
return (
|
||||
<a
|
||||
key={s}
|
||||
className={`service-link ${exact ? '' : 'inexact'}`}
|
||||
href={url}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
title={exact ? `Open in ${SERVICE_LABELS[s]}` : `Search ${SERVICE_LABELS[s]}`}
|
||||
>
|
||||
{SERVICE_LABELS[s]}
|
||||
</a>
|
||||
);
|
||||
})}
|
||||
<ShareButton track={track} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* One slim line: small artwork, title and artist, the open button, and an
|
||||
* arrow that shows the rest (`expanded` / `onToggle`).
|
||||
*/
|
||||
export function TrackRow({
|
||||
track,
|
||||
preferred,
|
||||
expanded,
|
||||
onToggle,
|
||||
}: {
|
||||
track: TrackDTO;
|
||||
preferred: StreamingService | null | undefined;
|
||||
expanded: boolean;
|
||||
onToggle: () => void;
|
||||
}) {
|
||||
return (
|
||||
<div className="track-row">
|
||||
<button type="button" className="track-row-main" onClick={onToggle} aria-expanded={expanded}>
|
||||
<Artwork track={track} small />
|
||||
<span className="track-body">
|
||||
<span className="track-title">{track.title}</span>
|
||||
<span className="track-artist">
|
||||
{track.artist}
|
||||
{expanded && track.album && <span className="muted"> · {track.album}</span>}
|
||||
</span>
|
||||
</span>
|
||||
</button>
|
||||
{preferred && <PrimaryLink track={track} preferred={preferred} short />}
|
||||
<button type="button" className={`chevron ${expanded ? 'open' : ''}`} onClick={onToggle} aria-expanded={expanded} title={expanded ? 'Show less' : 'Show more'}>
|
||||
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round" aria-hidden>
|
||||
<path d="m6 9 6 6 6-6" />
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Artwork + title, with a primary button for the viewer's preferred service
|
||||
* and quieter links for the rest. Links are https universal links, so on
|
||||
@@ -21,17 +100,9 @@ export function TrackCard({
|
||||
/** When the page already shows the artwork big. */
|
||||
hideArtwork?: boolean;
|
||||
}) {
|
||||
const { me } = useMe();
|
||||
const others = viewerServices(me).filter((s) => s !== preferred);
|
||||
const primary = preferred ? openUrl(track, preferred) : null;
|
||||
|
||||
return (
|
||||
<div className={`track ${compact ? 'track-compact' : ''}`}>
|
||||
{hideArtwork ? null : track.artworkUrl ? (
|
||||
<img className="artwork" src={track.artworkUrl} alt="" />
|
||||
) : (
|
||||
<div className="artwork artwork-empty">♪</div>
|
||||
)}
|
||||
{!hideArtwork && <Artwork track={track} />}
|
||||
<div className="track-body">
|
||||
<div className="track-title">{track.title}</div>
|
||||
<div className="track-artist">
|
||||
@@ -39,27 +110,8 @@ export function TrackCard({
|
||||
{track.album && <span className="muted"> · {track.album}</span>}
|
||||
</div>
|
||||
<div className="track-actions">
|
||||
{preferred && primary && (
|
||||
<a className="btn btn-primary" href={primary.url} target="_blank" rel="noreferrer">
|
||||
{primary.exact ? 'Open' : 'Search'} in {SERVICE_LABELS[preferred]}
|
||||
</a>
|
||||
)}
|
||||
{others.map((s) => {
|
||||
const { url, exact } = openUrl(track, s);
|
||||
return (
|
||||
<a
|
||||
key={s}
|
||||
className={`service-link ${exact ? '' : 'inexact'}`}
|
||||
href={url}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
title={exact ? `Open in ${SERVICE_LABELS[s]}` : `Search ${SERVICE_LABELS[s]}`}
|
||||
>
|
||||
{SERVICE_LABELS[s]}
|
||||
</a>
|
||||
);
|
||||
})}
|
||||
<ShareButton track={track} />
|
||||
{preferred && <PrimaryLink track={track} preferred={preferred} />}
|
||||
<ServiceLinks track={track} preferred={preferred} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -11,6 +11,7 @@ import type {
|
||||
UserSummaryDTO,
|
||||
} from './dto';
|
||||
import type { DeviceDTO } from './devices';
|
||||
import type { LyricsDTO } from './lyrics';
|
||||
import type {
|
||||
ChangeEmailInput,
|
||||
ChangePasswordInput,
|
||||
@@ -132,6 +133,8 @@ export function createApiClient({ baseUrl, getToken, credentials }: ApiClientOpt
|
||||
unreact: (listenId: string) => request<ReactionDTO[]>(`/listens/${q(listenId)}/reaction`, { method: 'DELETE' }),
|
||||
|
||||
searchTracks: (query: string) => request<TrackSearchResultDTO[]>(`/tracks/search?q=${q(query)}`),
|
||||
/** Null when no lyrics were found for the song. */
|
||||
lyrics: (trackId: string) => request<LyricsDTO | null>(`/tracks/${q(trackId)}/lyrics`),
|
||||
|
||||
connections: () => request<ConnectionDTO[]>('/connections'),
|
||||
authorizeUrl: (provider: 'plex' | 'lastfm', body: { client: 'web' | 'mobile'; returnTo?: string }) =>
|
||||
|
||||
@@ -9,3 +9,4 @@ export * from './links';
|
||||
export * from './qr';
|
||||
export * from './progress';
|
||||
export * from './reactions';
|
||||
export * from './lyrics';
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { currentLyricIndex, parseLrc } from './lyrics';
|
||||
|
||||
describe('parseLrc', () => {
|
||||
it('reads timestamps, skips tags, and sorts lines repeated by several tags', () => {
|
||||
const lines = parseLrc('[ar:M83]\n[00:12.50] Waiting in a car\n[00:05.00][01:00.1]Chorus\n[00:20.00]\n\nnot a lyric');
|
||||
expect(lines).toEqual([
|
||||
{ timeMs: 5000, text: 'Chorus' },
|
||||
{ timeMs: 12500, text: 'Waiting in a car' },
|
||||
{ timeMs: 20000, text: '' },
|
||||
{ timeMs: 60100, text: 'Chorus' },
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('currentLyricIndex', () => {
|
||||
const lines = parseLrc('[00:05.00]a\n[00:10.00]b\n[00:15.00]c');
|
||||
it('finds the line being sung', () => {
|
||||
expect(currentLyricIndex(lines, 0)).toBe(-1);
|
||||
expect(currentLyricIndex(lines, 5000)).toBe(0);
|
||||
expect(currentLyricIndex(lines, 14_999)).toBe(1);
|
||||
expect(currentLyricIndex(lines, 99_000)).toBe(2);
|
||||
expect(currentLyricIndex([], 1000)).toBe(-1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,47 @@
|
||||
/** One line of time-synced lyrics; empty text is an instrumental gap. */
|
||||
export interface LyricLine {
|
||||
timeMs: number;
|
||||
text: string;
|
||||
}
|
||||
|
||||
export interface LyricsDTO {
|
||||
/** Lines with timestamps, when the song has synced lyrics. */
|
||||
synced: LyricLine[] | null;
|
||||
/** Plain text, when there are no synced lyrics (or as a fallback). */
|
||||
plain: string | null;
|
||||
instrumental: boolean;
|
||||
/** Where they came from, for attribution. */
|
||||
source: { name: string; url: string };
|
||||
}
|
||||
|
||||
const TIME_TAG = /\[(\d{1,3}):(\d{1,2}(?:\.\d{1,3})?)\]/g;
|
||||
|
||||
/**
|
||||
* Parse LRC ("[01:23.45] words"). A line may carry several time tags; tags
|
||||
* that aren't times (like [ar:Artist]) are skipped. Sorted by time.
|
||||
*/
|
||||
export function parseLrc(lrc: string): LyricLine[] {
|
||||
const lines: LyricLine[] = [];
|
||||
for (const raw of lrc.split(/\r?\n/)) {
|
||||
const times = [...raw.matchAll(TIME_TAG)];
|
||||
if (times.length === 0) continue;
|
||||
const text = raw.replace(TIME_TAG, '').trim();
|
||||
for (const [, min, sec] of times) lines.push({ timeMs: Math.round((Number(min) * 60 + Number(sec)) * 1000), text });
|
||||
}
|
||||
return lines.sort((a, b) => a.timeMs - b.timeMs);
|
||||
}
|
||||
|
||||
/** Index of the line being sung at `positionMs`, or -1 before the first one. */
|
||||
export function currentLyricIndex(lines: LyricLine[], positionMs: number): number {
|
||||
let lo = 0;
|
||||
let hi = lines.length - 1;
|
||||
let found = -1;
|
||||
while (lo <= hi) {
|
||||
const mid = (lo + hi) >> 1;
|
||||
if (lines[mid]!.timeMs <= positionMs) {
|
||||
found = mid;
|
||||
lo = mid + 1;
|
||||
} else hi = mid - 1;
|
||||
}
|
||||
return found;
|
||||
}
|
||||
Reference in New Issue
Block a user