web-player: TypeScript helpers (partial)

Add src/lib/actions/pressable.ts and clickOutside.ts (Svelte actions;
role/tabindex stay static in markup for SSR accessibility, the action
only adds click + Enter/Space) and src/lib/toggle.svelte.ts
(createToggle), used by playlists.svelte.ts and queuePanel.svelte.ts.

format.ts: adds plural(n, one, many); migrates the repo's 15 manual
pluralizations, unifying them to lowercase (visible diff in
Playlists, Home, liked, Explore).

player.svelte.ts: adds toQueueItem, isQueueCurrent, playAllOrToggle,
playShuffled; renames addToQueue -> playNextItem (the old name was
misleading: it inserts next, not at the end). Migrates the 5 places
that repeated the isCurrentQueue/playAll pattern (album, playlist,
liked, mix, Home). Simplifies liked.svelte.ts and recentlyPlayed.ts
with object spread instead of rebuilding every field by hand.

navigation.svelte.ts: adds searchHref (migrates the duplicated
buildHref from TopBar and Explore) and appNavLinks (added; its
adoption in Sidebar/TabsBar is left for a later pass, as noted
there).

menus.svelte.ts: createTrackMenu() replaces the manual context-menu
state (contextMenu + contextMenuStateFor + addToQueue) in Home,
Explore and Mix.

Deliberately left pending: removing tracks.ts's TrackTarget wrapper
and its 8 accessors is deferred — it's the riskiest change in the
plan, touches types across Home/Explore/Mix/menus, and couldn't be
visually verified without Docker this session.

Verified with npm run check/build.
This commit is contained in:
2026-09-20 23:01:13 +02:00
parent aa20e70671
commit 1320b12699
25 changed files with 250 additions and 241 deletions
@@ -0,0 +1,17 @@
import type { Action } from 'svelte/action';
export const clickOutside: Action<HTMLElement, () => void> = (node, fn) => {
function onClick(event: MouseEvent) {
if (!node.contains(event.target as Node)) fn();
}
document.addEventListener('click', onClick, true);
return {
update(next) {
fn = next;
},
destroy() {
document.removeEventListener('click', onClick, true);
}
};
};
+25
View File
@@ -0,0 +1,25 @@
import type { Action } from 'svelte/action';
export const pressable: Action<HTMLElement, () => void> = (node, fn) => {
function onClick() {
fn();
}
function onKeydown(event: KeyboardEvent) {
if (event.key !== 'Enter' && event.key !== ' ') return;
event.preventDefault();
fn();
}
node.addEventListener('click', onClick);
node.addEventListener('keydown', onKeydown);
return {
update(next) {
fn = next;
},
destroy() {
node.removeEventListener('click', onClick);
node.removeEventListener('keydown', onKeydown);
}
};
};
+2 -5
View File
@@ -3,6 +3,7 @@
import { page } from '$app/state';
import type { SessionUser } from '$lib/types';
import { SEARCH_DEBOUNCE_MS, SEARCH_MIN_LENGTH } from '$lib/config';
import { searchHref } from '$lib/navigation.svelte';
import Search from '@lucide/svelte/icons/search';
import X from '@lucide/svelte/icons/x';
import ChevronLeft from '@lucide/svelte/icons/chevron-left';
@@ -24,13 +25,9 @@
let searchInput: HTMLInputElement | undefined = $state();
let searchTimeout: ReturnType<typeof setTimeout> | undefined;
function buildHref(term: string) {
return term ? `/explore?q=${encodeURIComponent(term)}` : '/explore';
}
function runSearch(term: string) {
if (term.length > 0 && term.length < SEARCH_MIN_LENGTH) return;
goto(buildHref(term), {
goto(searchHref(term), {
replaceState: page.url.pathname === '/explore',
keepFocus: true,
noScroll: true
@@ -4,6 +4,7 @@
import Artwork from '$lib/components/ui/Artwork.svelte';
import ArtistLink from '$lib/components/ui/ArtistLink.svelte';
import IconButton from '$lib/components/ui/IconButton.svelte';
import { pressable } from '$lib/actions/pressable';
import { fmtTime } from '$lib/format';
import X from '@lucide/svelte/icons/x';
import { fly } from 'svelte/transition';
@@ -71,12 +72,7 @@
<div
role="button"
tabindex="0"
onclick={() => player.playQueueIndex(index)}
onkeydown={(e) => {
if (e.key !== 'Enter' && e.key !== ' ') return;
e.preventDefault();
player.playQueueIndex(index);
}}
use:pressable={() => player.playQueueIndex(index)}
class="flex items-center gap-3 rounded-control p-2.25 text-left hover:bg-hover"
>
<Artwork trackIds={[track.id]} size="sm" alt={track.title} class="shrink-0 opacity-80" />
@@ -9,6 +9,7 @@
import MenuItem from './MenuItem.svelte';
import GlassMenu from './GlassMenu.svelte';
import { themeMode } from '$lib/theme/mode.svelte';
import { clickOutside } from '$lib/actions/clickOutside';
interface Props {
user: SessionUser;
@@ -27,7 +28,6 @@
}: Props = $props();
let open = $state(false);
let menuRef: HTMLDivElement | undefined = $state();
function toggle() {
open = !open;
@@ -36,13 +36,9 @@
function close() {
open = false;
}
function onDocumentClick(event: MouseEvent) {
if (menuRef && !menuRef.contains(event.target as Node)) open = false;
}
</script>
<div class="relative" bind:this={menuRef}>
<div class="relative" use:clickOutside={close}>
{@render trigger({ toggle, open })}
{#if open}
@@ -69,5 +65,3 @@
</GlassMenu>
{/if}
</div>
<svelte:window onclick={onDocumentClick} />
@@ -1,6 +1,7 @@
<script lang="ts">
import MediaCard from './MediaCard.svelte';
import Artwork from './Artwork.svelte';
import { plural } from '$lib/format';
interface Props {
id: string;
@@ -35,9 +36,7 @@
typeLabel,
subtitle,
releaseYear ? String(releaseYear) : undefined,
trackCount === undefined
? undefined
: `${trackCount} ${trackCount === 1 ? 'canción' : 'canciones'}`
trackCount === undefined ? undefined : plural(trackCount, 'canción', 'canciones')
]
.filter((part) => !!part)
.join(' · ')
@@ -1,6 +1,7 @@
<script lang="ts">
import MediaCard from './MediaCard.svelte';
import Artwork from './Artwork.svelte';
import { plural } from '$lib/format';
interface Props {
id: string;
@@ -13,7 +14,7 @@
let { id, name, trackCount, trackIds, updatedAt, index = 0 }: Props = $props();
const subtitle = $derived(`${trackCount} ${trackCount === 1 ? 'Canción' : 'Canciones'}`);
const subtitle = $derived(plural(trackCount, 'canción', 'canciones'));
</script>
<MediaCard href="/playlists/{id}" title={name} {subtitle} {index}>
@@ -3,6 +3,7 @@
import Artwork from './Artwork.svelte';
import ExplicitBadge from './ExplicitBadge.svelte';
import ArtistLink from './ArtistLink.svelte';
import { pressable } from '$lib/actions/pressable';
interface Props {
trackId: string | number;
@@ -33,24 +34,14 @@
overlay,
badge
}: Props = $props();
function onKeydown(event: KeyboardEvent) {
if (event.key !== 'Enter' && event.key !== ' ') return;
event.preventDefault();
onClick();
}
function onclick(event: MouseEvent) {
event.stopPropagation();
onClick();
}
</script>
<!-- svelte-ignore a11y_click_events_have_key_events -->
<div
role="button"
tabindex="0"
{onclick}
onkeydown={onKeydown}
use:pressable={onClick}
onclick={(event) => event.stopPropagation()}
class="flex min-w-0 items-center gap-3.5 text-left"
>
<Artwork trackIds={[trackId]} src={coverSrc} {size} alt={title} class="shrink-0">
+5 -1
View File
@@ -18,7 +18,11 @@ export function fmtDate(value: string | number | Date): string {
return dateFormatter.format(new Date(value));
}
export function plural(n: number, one: string, many: string): string {
return `${n} ${n === 1 ? one : many}`;
}
export function fmtPlays(count: number | string | undefined): string {
const value = Math.max(0, Math.floor(Number(count ?? 0)));
return `${value} ${value === 1 ? 'Reproducción' : 'Reproducciones'}`;
return plural(value, 'reproducción', 'reproducciones');
}
+27
View File
@@ -0,0 +1,27 @@
import {
contextMenuStateFor,
type ContextMenuState
} from '$lib/components/TrackContextMenu.svelte';
import { player } from './player/player.svelte';
import { queueItemForTarget, type TrackTarget } from './tracks';
export function createTrackMenu() {
let state = $state<ContextMenuState | null>(null);
return {
get state() {
return state;
},
open(event: MouseEvent, target: TrackTarget) {
state = contextMenuStateFor(event, target);
},
close() {
state = null;
},
playNext() {
if (!state) return;
player.playNextItem(queueItemForTarget(state));
state = null;
}
};
}
+45
View File
@@ -1,4 +1,13 @@
import { afterNavigate } from '$app/navigation';
import type { LucideIcon } from '@lucide/svelte';
import Home from '@lucide/svelte/icons/house';
import Compass from '@lucide/svelte/icons/compass';
import ListMusic from '@lucide/svelte/icons/list-music';
import Heart from '@lucide/svelte/icons/heart';
import Disc from '@lucide/svelte/icons/disc-2';
import Folder from '@lucide/svelte/icons/folder';
import Upload from '@lucide/svelte/icons/upload';
import type { SessionUser } from './types';
const HISTORY_INDEX = 'sveltekit:history';
@@ -54,3 +63,39 @@ export function isSectionActive(href: string, pathname: string, section?: string
if (section !== undefined) return section === href;
return href === '/' ? pathname === '/' : pathname.startsWith(href);
}
export function searchHref(query: string): string {
return query ? `/explore?q=${encodeURIComponent(query)}` : '/explore';
}
export interface AppNavLink {
href: string;
label: string;
icon: LucideIcon;
count?: number;
primary: boolean;
}
export interface AppNavCounts {
playlists?: number;
liked?: number;
}
export function appNavLinks(user: SessionUser | null, counts: AppNavCounts = {}): AppNavLink[] {
if (!user) return [{ href: '/explore', label: 'Descubrir', icon: Compass, primary: true }];
return [
{ href: '/', label: 'Inicio', icon: Home, primary: true },
{ href: '/explore', label: 'Descubrir', icon: Compass, primary: true },
{
href: '/playlists',
label: 'Playlists',
icon: ListMusic,
count: counts.playlists,
primary: true
},
{ href: '/liked', label: 'Me gusta', icon: Heart, count: counts.liked, primary: true },
{ href: '/albums', label: 'Mis álbumes', icon: Disc, primary: false },
{ href: '/library', label: 'Canciones subidas', icon: Folder, primary: false },
{ href: '/upload', label: 'Subir música', icon: Upload, primary: false }
];
}
+5 -18
View File
@@ -34,13 +34,10 @@ class LikedStore {
const items = toQueueItems(tracks);
const next: Record<string, LikedTrack> = {};
items.forEach((item, i) => {
next[String(item.id)] = {
id: String(item.id),
title: item.title,
artist: item.artist,
explicit: item.explicit,
ownerUserId: item.ownerUserId,
listensCount: item.listensCount,
const id = String(item.id);
next[id] = {
...item,
id,
duration: tracks[i].duration,
likedAt: new Date(tracks[i].createdAt).getTime()
};
@@ -58,17 +55,7 @@ class LikedStore {
const wasLiked = id in before;
const next = { ...before };
if (wasLiked) delete next[id];
else {
next[id] = {
id,
title: track.title,
artist: track.artist,
explicit: track.explicit,
ownerUserId: track.ownerUserId,
duration: track.duration,
likedAt: Date.now()
};
}
else next[id] = { ...track, id, likedAt: Date.now() };
this.entries = next;
try {
+21 -1
View File
@@ -1,6 +1,7 @@
import { browser } from '$app/environment';
import { DEFAULT_ACCENT } from '$lib/theme/color';
import { extractAccent, type Accent } from '$lib/theme/palette';
import { shuffle } from '$lib/collections';
export interface PlayerTrack {
id: string | number;
@@ -47,6 +48,25 @@ export function toQueueItems(tracks: ApiTrackLike[]): QueueItem[] {
}));
}
export function toQueueItem(track: ApiTrackLike): QueueItem {
return toQueueItems([track])[0];
}
export function isQueueCurrent(items: { id: string | number }[]): boolean {
return items.some((item) => item.id === player.current.id);
}
export function playAllOrToggle(items: QueueItem[]) {
if (items.length === 0) return;
if (isQueueCurrent(items)) player.toggle();
else player.playQueue(items, 0);
}
export function playShuffled(items: QueueItem[]) {
if (items.length === 0) return;
player.playQueue(shuffle(items), 0);
}
async function readErrorMessage(res: Response): Promise<string> {
try {
const body = (await res.json()) as { message?: string };
@@ -291,7 +311,7 @@ class PlayerState {
else this.playQueue(list, index);
}
addToQueue(item: QueueItem) {
playNextItem(item: QueueItem) {
this.playNext([item]);
}
+2 -15
View File
@@ -1,16 +1,3 @@
let open = $state(false);
import { createToggle } from '../toggle.svelte';
export const queuePanel = {
get open() {
return open;
},
toggle() {
open = !open;
},
close() {
open = false;
},
show() {
open = true;
}
};
export const queuePanel = createToggle();
+2 -12
View File
@@ -1,13 +1,3 @@
let open = $state(false);
import { createToggle } from './toggle.svelte';
export const createPlaylistModal = {
get open() {
return open;
},
show() {
open = true;
},
close() {
open = false;
}
};
export const createPlaylistModal = createToggle();
+2 -16
View File
@@ -12,28 +12,14 @@ export function mergeRecentlyPlayed(history: ApiTrackLike[], limit: number): Que
const id = String(t.id);
if (seen.has(id)) continue;
seen.add(id);
merged.push({
id,
title: t.title,
artist: t.artist,
explicit: t.explicit,
ownerUserId: t.ownerUserId,
listensCount: t.listensCount
});
merged.push({ ...t, id });
}
for (const item of toQueueItems(history)) {
const id = String(item.id);
if (seen.has(id)) continue;
seen.add(id);
merged.push({
id,
title: item.title,
artist: item.artist,
explicit: item.explicit,
ownerUserId: item.ownerUserId,
listensCount: item.listensCount
});
merged.push({ ...item, id });
}
return merged.slice(0, limit);
+18
View File
@@ -0,0 +1,18 @@
export function createToggle(initial = false) {
let open = $state(initial);
return {
get open() {
return open;
},
show() {
open = true;
},
close() {
open = false;
},
toggle() {
open = !open;
}
};
}