refactor(music): review cleanup across the jukebox branch

Consolidates the three copies of the track-time formatter into a shared
formatTrackTime util (Intl.DurationFormat can't match the "2:37" format,
its digital style always pads minutes), points the six private copies of
the axios errorMessage helper at the shared util (MediaTab's was dead
code and is just removed), drops the legacy ?mode= redirect since the
jukebox never shipped with query-based modes, shrinks the free-radio
sample from 1000 tracks to the 200 that comfortably fill an hour, and
prunes redundant comments.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
Georges-Antoine Assi
2026-08-30 15:05:21 -04:00
parent ad44d970dd
commit 8029ffed2c
18 changed files with 58 additions and 127 deletions

View File

@@ -2290,8 +2290,6 @@ class DBRomsHandler(DBBaseHandler):
if platform_ids:
clauses.append(Rom.platform_id.in_(platform_ids))
if game_genre and exclude_field != "game_genre":
# RomMetadata.genres is a JSON array; reuse the dialect-aware
# containment helper the ROM filters already go through.
clauses.append(
json_array_contains_value(
RomMetadata.genres, game_genre, session=session

View File

@@ -13,8 +13,6 @@ VIEWER_ACTIONS = {
"collection.create",
"collection.edit",
"collection.delete",
# Viewers have owned-playlist write (LEGACY_VIEWER_GRANTS), which covers
# favoriting soundtrack tracks.
"playlist.edit",
}

View File

@@ -188,8 +188,6 @@ const routes = [
},
},
{
// The browse mode is a path segment so every jukebox subgroup is
// its own history entry and browser back/forward walks between them.
path: "music/:mode?",
name: ROUTES.MUSIC,
meta: { title: i18n.global.t("common.jukebox") },

View File

@@ -2,12 +2,6 @@ import { defineStore } from "pinia";
import { computed, ref } from "vue";
import musicApi from "@/services/api/music";
// One source of truth for "is this track a favorite".
//
// Favorites show up on several surfaces at once (the game's soundtrack tab,
// every jukebox mode, the favorites playlist itself). Before this store each
// surface kept its own copy and the writer had to fan changes out by hand,
// so a toggle in one place left the others stale.
const useMusicFavorites = defineStore("musicFavorites", () => {
const favoriteIds = ref<Set<number>>(new Set());
const pendingIds = ref<Set<number>>(new Set());

View File

@@ -3,7 +3,6 @@
// a single manual file (multi-manual ROMs). The emitter payload picks the
// scope.
import { RBtn, RDialog, RIcon } from "@v2/lib";
import axios from "axios";
import type { Emitter } from "mitt";
import { inject, onBeforeUnmount, ref } from "vue";
import { useI18n } from "vue-i18n";
@@ -11,6 +10,7 @@ import romApi from "@/services/api/rom";
import storeRoms, { type DetailedRom } from "@/stores/roms";
import type { Events } from "@/types/emitter";
import { useSnackbar } from "@/v2/composables/useSnackbar";
import { errorMessage } from "@/v2/utils/errorMessage";
defineOptions({ inheritAttrs: false });
@@ -25,15 +25,6 @@ const isPrimary = ref(false);
const fileId = ref<number | undefined>(undefined);
const deleting = ref(false);
function errorMessage(err: unknown): string {
if (axios.isAxiosError(err)) {
const detail = err.response?.data?.detail;
if (typeof detail === "string" && detail) return detail;
return err.message;
}
return err instanceof Error ? err.message : String(err);
}
const handleShow = (payload: Events["showDeleteManualDialog"]) => {
rom.value = payload.rom;
isPrimary.value = payload.isPrimary;

View File

@@ -39,7 +39,6 @@
// `rom.delete` permission. Each file is removed from disk and the DB
// row is dropped via `DELETE /roms/{rom_id}/files/{file_id}`.
import { RBtn, RCheckbox, REmptyState, RIcon, RTooltip } from "@v2/lib";
import axios from "axios";
import { computed, ref, watch } from "vue";
import { useI18n } from "vue-i18n";
import { useRoute, useRouter } from "vue-router";
@@ -54,6 +53,7 @@ import { getDownloadLink } from "@/utils";
import { useCan } from "@/v2/composables/useCan";
import { useConfirm } from "@/v2/composables/useConfirm";
import { useSnackbar } from "@/v2/composables/useSnackbar";
import { errorMessage } from "@/v2/utils/errorMessage";
import FileRow from "./FileRow.vue";
import FilesSummary from "./FilesSummary.vue";
@@ -73,15 +73,6 @@ const hasDeleteGrant = useCan("rom.delete");
// `DELETE /roms/{id}/files/{file_id}` gates on ROMS_WRITE
const canDelete = computed(() => hasDeleteGrant.value && canUpload.value);
function errorMessage(err: unknown): string {
if (axios.isAxiosError(err)) {
const detail = err.response?.data?.detail;
if (typeof detail === "string" && detail) return detail;
return err.message;
}
return String(err);
}
// ---------- Category metadata ----------
// Drives per-file category chips (one per `RomFileCategory` enum
// value). Folder→icon resolution lives in `FOLDER_META` below — it

View File

@@ -8,7 +8,6 @@
// tab's content height) so the viewer keeps its internal scroll and switching
// subtabs never forces an outer scrollbar.
import { RBtn, RDropzone, REmptyState, RSelect } from "@v2/lib";
import axios from "axios";
import type { Emitter } from "mitt";
import { computed, defineAsyncComponent, inject, ref, watch } from "vue";
import { useI18n } from "vue-i18n";
@@ -19,6 +18,7 @@ import { FRONTEND_RESOURCES_PATH } from "@/utils";
import { useCan } from "@/v2/composables/useCan";
import { useConfirm } from "@/v2/composables/useConfirm";
import { useSnackbar } from "@/v2/composables/useSnackbar";
import { errorMessage } from "@/v2/utils/errorMessage";
const PdfViewer = defineAsyncComponent(
() => import("@/v2/components/GameDetails/PdfViewer.vue"),
@@ -27,15 +27,6 @@ const MarkdownViewer = defineAsyncComponent(
() => import("@/v2/components/GameDetails/MarkdownViewer.vue"),
);
function errorMessage(err: unknown): string {
if (axios.isAxiosError(err)) {
const detail = err.response?.data?.detail;
if (typeof detail === "string" && detail) return detail;
return err.message;
}
return err instanceof Error ? err.message : String(err);
}
const props = defineProps<{ rom: DetailedRom }>();
const emitter = inject<Emitter<Events>>("emitter");
const snackbar = useSnackbar();

View File

@@ -12,7 +12,6 @@
//
// The soundtrack player is reused from v1 for now.
import { RBtn, RDropzone, REmptyState, RIcon } from "@v2/lib";
import axios from "axios";
import { computed, defineAsyncComponent, ref, watch } from "vue";
import { useI18n } from "vue-i18n";
import { useRoute, useRouter } from "vue-router";
@@ -38,15 +37,6 @@ const ArtworkSubtab = defineAsyncComponent(
() => import("@/v2/components/GameDetails/ArtworkSubtab.vue"),
);
function errorMessage(err: unknown): string {
if (axios.isAxiosError(err)) {
const detail = err.response?.data?.detail;
if (typeof detail === "string" && detail) return detail;
return err.message;
}
return err instanceof Error ? err.message : String(err);
}
const props = defineProps<{ rom: DetailedRom }>();
const snackbar = useSnackbar();
const confirm = useConfirm();

View File

@@ -16,7 +16,6 @@
// into a specific list works and stale state doesn't leak when the
// user navigates to a sibling tab.
import { RBtn, RDropzone, RIcon } from "@v2/lib";
import axios from "axios";
import { storeToRefs } from "pinia";
import { computed, ref, watch } from "vue";
import { useI18n } from "vue-i18n";
@@ -37,6 +36,7 @@ import AssetList from "@/v2/components/shared/AssetList.vue";
import AssetStrip from "@/v2/components/shared/AssetStrip.vue";
import { useConfirm } from "@/v2/composables/useConfirm";
import { useSnackbar } from "@/v2/composables/useSnackbar";
import { errorMessage } from "@/v2/utils/errorMessage";
// Slot payload from AssetList/AssetStrip is the full save|state union; these
// narrow it back to the concrete schema the section's handlers expect.
@@ -139,15 +139,6 @@ const snackbar = useSnackbar();
const confirm = useConfirm();
const romsStore = storeRoms();
function errorMessage(err: unknown): string {
if (axios.isAxiosError(err)) {
const detail = err.response?.data?.detail;
if (typeof detail === "string" && detail) return detail;
return err.message;
}
return err instanceof Error ? err.message : String(err);
}
async function refreshRom() {
try {
const { data } = await romApi.getRom({ romId: props.rom.id });

View File

@@ -13,7 +13,6 @@
// Both uploadable sections use RDropzone (CTA when empty, overlay over the
// grid when filled).
import { RBtn, RDropzone } from "@v2/lib";
import axios from "axios";
import { storeToRefs } from "pinia";
import { computed, defineAsyncComponent, ref } from "vue";
import { useI18n } from "vue-i18n";
@@ -26,6 +25,7 @@ import type { ScreenshotItem } from "@/v2/components/GameDetails/ScreenshotsTab.
import { useCan } from "@/v2/composables/useCan";
import { useConfirm } from "@/v2/composables/useConfirm";
import { useSnackbar } from "@/v2/composables/useSnackbar";
import { errorMessage } from "@/v2/utils/errorMessage";
const ScreenshotsTab = defineAsyncComponent(
() => import("@/v2/components/GameDetails/ScreenshotsTab.vue"),
@@ -43,15 +43,6 @@ const IMAGE_EXTENSIONS = new Set([
"avif",
]);
function errorMessage(err: unknown): string {
if (axios.isAxiosError(err)) {
const detail = err.response?.data?.detail;
if (typeof detail === "string" && detail) return detail;
return err.message;
}
return err instanceof Error ? err.message : String(err);
}
const props = defineProps<{ rom: DetailedRom }>();
const { t } = useI18n();

View File

@@ -23,6 +23,7 @@ import useSoundtrackPlayer from "@/stores/soundtrackPlayer";
import type { Events } from "@/types/emitter";
import VolumeControl from "@/v2/components/Soundtrack/VolumeControl.vue";
import { isJukeboxPlayerMode } from "@/v2/utils/jukebox";
import { formatTrackTime } from "@/v2/utils/time";
defineOptions({ inheritAttrs: false });
@@ -146,19 +147,10 @@ function onError() {
});
}
function fmt(s: number) {
if (!Number.isFinite(s) || s < 0) return "0:00";
const m = Math.floor(s / 60);
const sec = Math.floor(s % 60)
.toString()
.padStart(2, "0");
return `${m}:${sec}`;
}
function seekValueText(v: number): string {
return t("rom.seek-progress", {
current: fmt(v),
duration: fmt(duration.value),
current: formatTrackTime(v),
duration: formatTrackTime(duration.value),
});
}
@@ -292,7 +284,7 @@ function openRom() {
<!-- Seek row -->
<div class="r-v2-mp__seek">
<span class="r-v2-mp__time">{{ fmt(currentTime) }}</span>
<span class="r-v2-mp__time">{{ formatTrackTime(currentTime) }}</span>
<RSlider
:model-value="currentTime"
:max="duration || 0"
@@ -304,7 +296,7 @@ function openRom() {
@update:model-value="(v: number) => store.seek(v)"
/>
<span class="r-v2-mp__time r-v2-mp__time--right">
{{ fmt(duration) }}
{{ formatTrackTime(duration) }}
</span>
</div>
</div>

View File

@@ -37,6 +37,7 @@ import EmptyState from "@/v2/components/shared/EmptyState.vue";
import { useCan } from "@/v2/composables/useCan";
import { useSnackbar } from "@/v2/composables/useSnackbar";
import type { PanelTrack } from "@/v2/utils/soundtrackTracks";
import { formatTrackTime } from "@/v2/utils/time";
import TrackRow from "./TrackRow.vue";
// Row height must match `.r-v2-stp__row` in TrackRow's stylesheet.
@@ -242,7 +243,7 @@ const queueSummary = computed(() => {
if (isFullyLoaded.value && totalDurationSeconds.value > 0)
return t("rom.tracks-summary", {
count: trackCount.value.toLocaleString(),
duration: fmt(totalDurationSeconds.value),
duration: formatTrackTime(totalDurationSeconds.value),
});
return t("rom.tracks-n", trackCount.value, {
named: { n: trackCount.value.toLocaleString() },
@@ -328,19 +329,10 @@ function downloadTrack(track: PanelTrack) {
a.remove();
}
function fmt(s: number | undefined | null) {
if (s == null || !Number.isFinite(s) || s < 0) return "0:00";
const m = Math.floor(s / 60);
const sec = Math.floor(s % 60)
.toString()
.padStart(2, "0");
return `${m}:${sec}`;
}
function seekValueText(v: number): string {
return t("rom.seek-progress", {
current: fmt(v),
duration: fmt(duration.value),
current: formatTrackTime(v),
duration: formatTrackTime(duration.value),
});
}
</script>
@@ -484,7 +476,9 @@ function seekValueText(v: number): string {
<VolumeControl size="small" />
</div>
<div class="r-v2-stp__timeline">
<span class="r-v2-stp__time">{{ fmt(currentTime) }}</span>
<span class="r-v2-stp__time">{{
formatTrackTime(currentTime)
}}</span>
<RSlider
:model-value="currentTime"
:max="duration || 0"
@@ -497,7 +491,7 @@ function seekValueText(v: number): string {
@update:model-value="(v: number) => player.seek(v)"
/>
<span class="r-v2-stp__time r-v2-stp__time--right">
{{ fmt(duration) }}
{{ formatTrackTime(duration) }}
</span>
</div>
</div>

View File

@@ -14,6 +14,7 @@ import { useI18n } from "vue-i18n";
import useMusicFavorites from "@/stores/musicFavorites";
import { formatBytes } from "@/utils";
import type { PanelTrack } from "@/v2/utils/soundtrackTracks";
import { formatTrackTime } from "@/v2/utils/time";
const props = defineProps<{
track: PanelTrack;
@@ -37,15 +38,6 @@ const favorites = useMusicFavorites();
const isFavorite = computed(() => favorites.isFavorite(props.track.id));
const isPending = computed(() => favorites.isPending(props.track.id));
function fmt(s: number | undefined | null) {
if (s == null || !Number.isFinite(s) || s < 0) return "0:00";
const m = Math.floor(s / 60);
const sec = Math.floor(s % 60)
.toString()
.padStart(2, "0");
return `${m}:${sec}`;
}
</script>
<template>
@@ -85,7 +77,7 @@ function fmt(s: number | undefined | null) {
<div class="r-v2-stp__row-right">
<span v-if="track.durationSeconds" class="r-v2-stp__row-duration">
{{ fmt(track.durationSeconds) }}
{{ formatTrackTime(track.durationSeconds) }}
</span>
<span v-if="track.fileSizeBytes != null" class="r-v2-stp__row-size">
{{ formatBytes(track.fileSizeBytes) }}

View File

@@ -22,12 +22,7 @@ export function useJukeboxUrlState() {
const route = useRoute();
const router = useRouter();
// Old links carried the mode as `?mode=`; honor them on entry (the
// redirect below rewrites the URL to the subpath form).
const entryMode = parseJukeboxMode(route.params.mode);
const mode = ref<JukeboxMode>(
entryMode === "home" ? parseJukeboxMode(route.query.mode) : entryMode,
);
const mode = ref<JukeboxMode>(parseJukeboxMode(route.params.mode));
/** A ref mirrored into `?key=`; writes are merged by `patchQuery`. */
function queryRef(key: string): Ref<string> {
@@ -85,14 +80,6 @@ export function useJukeboxUrlState() {
void router.push(locationFor(value));
});
// Rewrite legacy `?mode=` links to the subpath form.
if (
parseJukeboxMode(route.query.mode) !== "home" &&
parseJukeboxMode(route.params.mode) === "home"
) {
void router.replace(locationFor(mode.value));
}
const selectedPlatformId = computed(() => Number(platform.value) || 0);
const selectedDecade = computed(() => Number(decade.value) || 0);
const selectedRomId = computed(() => Number(game.value) || 0);

View File

@@ -0,0 +1,21 @@
import { describe, expect, it } from "vitest";
import { formatTrackTime } from "./time";
describe("formatTrackTime", () => {
it("formats seconds as a digital track position", () => {
expect(formatTrackTime(157)).toBe("2:37");
expect(formatTrackTime(5)).toBe("0:05");
expect(formatTrackTime(0)).toBe("0:00");
expect(formatTrackTime(5412)).toBe("90:12");
});
it("treats missing or unusable values as zero", () => {
for (const value of [undefined, null, -3, Number.NaN, Infinity]) {
expect(formatTrackTime(value)).toBe("0:00");
}
});
it("truncates fractional seconds", () => {
expect(formatTrackTime(61.9)).toBe("1:01");
});
});

View File

@@ -0,0 +1,13 @@
// Track-position formatting shared by every soundtrack surface (panel,
// track rows, mini player).
//
// Not Intl.DurationFormat: its digital style always pads minutes to two
// digits ("02:37"), and player timestamps read as "2:37".
/** Seconds as a digital track position: "2:37", "0:05", "90:12". */
export function formatTrackTime(s: number | undefined | null): string {
if (s == null || !Number.isFinite(s) || s < 0) return "0:00";
const minutes = Math.floor(s / 60);
const seconds = Math.floor(s % 60);
return `${minutes}:${String(seconds).padStart(2, "0")}`;
}

View File

@@ -1,6 +1,4 @@
<script setup lang="ts">
// One "pick something on the left, play it on the right" jukebox screen.
//
// Artist / game-genre / platform / decade / album all have this exact shape,
// so they share one component and differ only by the facet they load and the
// filter they hand to the track query. Adding a browse dimension is a new

View File

@@ -18,8 +18,9 @@ import { panelTracksFromCatalog } from "@/v2/utils/soundtrackTracks";
const RECENTLY_ADDED_LIMIT = 25;
// Comfortably more than an hour of music, without paging a whole library.
const STATION_SAMPLE_SIZE = 1_000;
// Enough to fill the hour-long station even when tracks are short and many
// lack the duration metadata the session builder needs.
const STATION_SAMPLE_SIZE = 200;
const props = defineProps<{
mode: Extract<