fix(player): apply the code-review findings

Correctness: the upload dialog seeds dropped files immediately (three of
its tests ran vacuously), dedupes them by name, submits on Enter and
rejects a blank slot name; slotted manual uploads are new versions even
when the bytes match; the core picker sees the nightly cores the player
offers; clearing a state hands the boot back to the save it displaced;
a slot or core group can be folded even while it holds the selection
and reopens when the selection moves into it; the entrance stagger
counts only rendered rows; the stream save picker keeps its flat list;
slot retention orders by id as a tiebreaker for same-second uploads.

Reuse: asset helpers shared by both lists move to v2/utils/assets.ts,
the write slot follows the picked save in one place, the upload payload
carries its type, and the endpoint's delete sequence is one helper.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
zurdi
2026-09-16 05:05:29 +02:00
parent e07eb69249
commit b536aced56
17 changed files with 316 additions and 195 deletions

View File

@@ -119,18 +119,26 @@ async def _remove_save_screenshot(save: Save) -> None:
)
async def _delete_save(save: Save) -> None:
"""Drop a save row with its file and screenshot; a missing file is only logged."""
db_save_handler.delete_save(save.id)
try:
await fs_asset_handler.remove_file(file_path=save.full_path)
except FileNotFoundError:
log.error(
f"Save file {hl(save.file_name)} not found for platform "
f"{hl(save.rom.platform_display_name, color=BLUE)}[{hl(save.rom.platform_slug)}]"
)
await _remove_save_screenshot(save)
async def _prune_slot(user_id: int, rom_id: int, slot: str, keep: int) -> None:
"""Drop every version of ``slot`` past the ``keep`` newest, files included."""
"""Drop every version of ``slot`` past the ``keep`` newest."""
slot_saves = db_save_handler.get_saves(
user_id=user_id, rom_ids=[rom_id], slot=slot, order_by="updated_at"
)
for old_save in slot_saves[keep:]:
db_save_handler.delete_save(old_save.id)
try:
await fs_asset_handler.remove_file(old_save.full_path)
except FileNotFoundError:
log.warning(f"Could not delete old save file: {old_save.full_path}")
await _remove_save_screenshot(old_save)
await _delete_save(old_save)
def _slot_retention(autocleanup: bool, autocleanup_limit: int) -> int | None:
@@ -138,7 +146,7 @@ def _slot_retention(autocleanup: bool, autocleanup_limit: int) -> int | None:
limits = [MAX_SAVES_PER_SLOT] if MAX_SAVES_PER_SLOT else []
if autocleanup:
limits.append(autocleanup_limit)
return min(limits) if limits else None
return min(limits, default=None)
def _apply_datetime_tag(filename: str) -> str:
@@ -775,19 +783,10 @@ async def delete_saves(
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=error)
affected_rom_ids.add(save.rom_id)
db_save_handler.delete_save(save_id)
log.info(
f"Deleting save {hl(save.file_name)} [{save.rom.platform_slug}] from filesystem"
)
try:
file_path = f"{save.file_path}/{save.file_name}"
await fs_asset_handler.remove_file(file_path=file_path)
except FileNotFoundError:
error = f"Save file {hl(save.file_name)} not found for platform {hl(save.rom.platform_display_name, color=BLUE)}[{hl(save.rom.platform_slug)}]"
log.error(error)
await _remove_save_screenshot(save)
await _delete_save(save)
refresh_affected_smart_collections(list(affected_rom_ids), membership_only=True)

View File

@@ -113,7 +113,8 @@ class DBSavesHandler(DBBaseHandler):
if order_by:
order_col = getattr(Save, order_by)
order_fn = asc if order_dir == "asc" else desc
query = query.order_by(order_fn(order_col))
# Timestamps tie at second resolution; the id keeps the order stable.
query = query.order_by(order_fn(order_col), order_fn(Save.id))
if only_fields:
query = query.options(load_only(*only_fields))

View File

@@ -30,15 +30,17 @@ import type {
import saveApi from "@/services/api/save";
import stateApi from "@/services/api/state";
import storeAuth from "@/stores/auth";
import storeConfig from "@/stores/config";
import { getSupportedEJSCores } from "@/utils";
import UploadAssetDialog, {
type UploadAssetType,
type UploadAssetPayload,
} from "@/v2/components/GameDetails/UploadAssetDialog.vue";
import AssetList from "@/v2/components/shared/AssetList.vue";
import AssetStrip from "@/v2/components/shared/AssetStrip.vue";
import { useConfirm } from "@/v2/composables/useConfirm";
import { useRomSync } from "@/v2/composables/useRomSync";
import { useSnackbar } from "@/v2/composables/useSnackbar";
import type { AssetType } from "@/v2/utils/assets";
import { errorMessage } from "@/v2/utils/errorMessage";
// Slot payload from AssetList/AssetStrip is the full save|state union; these
@@ -95,6 +97,7 @@ watch(
);
const authStore = storeAuth();
const configStore = storeConfig();
const { user } = storeToRefs(authStore);
const myId = computed(() => user.value?.id ?? null);
@@ -132,31 +135,32 @@ const subtabDefs = computed<SubtabDef[]>(() => [
// ---------- Upload / refresh plumbing ----------
// Every upload goes through the dialog, which asks saves for a slot and
// states for a core; dropped files land in it pre-picked.
const uploadDialog = ref<{ type: UploadAssetType; files: File[] } | null>(null);
function openUpload(type: UploadAssetType, files: File[] = []) {
const uploadDialog = ref<{ type: AssetType; files: File[] } | null>(null);
function openUpload(type: AssetType, files: File[] = []) {
uploadDialog.value = { type, files };
}
// The platform's cores plus whatever the existing states were tagged with.
// The cores the player offers plus whatever the existing states carry.
const uploadCores = computed(() => {
const cores = new Set(getSupportedEJSCores(props.rom.platform_slug));
const cores = new Set(
getSupportedEJSCores(
props.rom.platform_slug,
configStore.config.EJS_NETPLAY_ENABLED,
),
);
for (const state of myStates.value) {
if (state.emulator) cores.add(state.emulator);
}
return [...cores];
});
async function onUploadSubmit({
type,
files,
slot,
emulator,
}: {
files: File[];
slot: string | null;
emulator: string | null;
}) {
const type = uploadDialog.value?.type;
}: UploadAssetPayload) {
uploadDialog.value = null;
if (type === "save") await onSaveUpload(files, slot);
else if (type === "state") await onStateUpload(files, emulator);
else await onStateUpload(files, emulator);
}
const uploadingSaves = ref(false);
const uploadingStates = ref(false);
@@ -174,10 +178,12 @@ async function onSaveUpload(files: File[], slot: string | null) {
uploadingSaves.value = true;
try {
// A manual upload into a slot is a new version even if the bytes match.
const results = await saveApi.uploadSaves({
rom: props.rom,
savesToUpload: files.map((saveFile) => ({ saveFile })),
slot: slot ?? undefined,
overwrite: slot !== null,
});
const successful = results.filter((r) => r.status === "fulfilled").length;
const failed = results.length - successful;

View File

@@ -1,7 +1,9 @@
import { mount } from "@vue/test-utils";
import { describe, expect, it, vi } from "vitest";
import { nextTick } from "vue";
import UploadAssetDialog from "./UploadAssetDialog.vue";
import { afterEach, describe, expect, it, vi } from "vitest";
import { defineComponent, nextTick, type PropType } from "vue";
import UploadAssetDialog, {
type UploadAssetPayload,
} from "./UploadAssetDialog.vue";
vi.mock("vue-i18n", () => ({
useI18n: () => ({ t: (key: string) => key }),
@@ -23,22 +25,23 @@ const RForm = {
template: `<form><slot /></form>`,
};
// Emits the raw item in object mode and its value otherwise, like RSelect.
const RSelect = {
const RSelect = defineComponent({
props: {
modelValue: { type: null, default: undefined },
items: { type: Array, default: () => [] },
itemTitle: { type: [String, Function], default: "title" },
modelValue: {
type: null as unknown as PropType<unknown>,
default: undefined,
},
items: { type: Array as PropType<unknown[]>, default: () => [] },
itemTitle: {
type: [String, Function] as PropType<
string | ((item: unknown) => string)
>,
default: "title",
},
returnObject: { type: Boolean, default: false },
},
emits: ["update:modelValue"],
setup(
props: {
items: unknown[];
itemTitle: string | ((item: unknown) => string);
returnObject: boolean;
},
{ emit }: { emit: (event: "update:modelValue", value: unknown) => void },
) {
setup(props, { emit }) {
const titleOf = (item: unknown) =>
typeof props.itemTitle === "function"
? props.itemTitle(item)
@@ -51,7 +54,7 @@ const RSelect = {
return { titleOf, pick };
},
template: `<select @change="pick"><option v-for="(i, n) in items" :key="n">{{ titleOf(i) }}</option></select>`,
};
});
const RTextField = {
props: { modelValue: { type: String, default: "" } },
emits: ["update:modelValue"],
@@ -73,8 +76,6 @@ const RBtn = {
template: `<button class="btn" :disabled="disabled" @click="$emit('click')"><slot /></button>`,
};
type Payload = { files: File[]; slot: string | null; emulator: string | null };
function mountDialog(
type: "save" | "state",
initialFiles: File[] = [],
@@ -120,10 +121,16 @@ async function choose(
async function submitted(wrapper: ReturnType<typeof mountDialog>) {
await uploadButton(wrapper).trigger("click");
await nextTick();
return (wrapper.emitted("submit")?.[0] as [Payload] | undefined)?.[0];
return (
wrapper.emitted("submit")?.[0] as [UploadAssetPayload] | undefined
)?.[0];
}
describe("UploadAssetDialog", () => {
afterEach(() => {
formValid.value = true;
});
it("keeps Upload disabled until a file is picked, then uploads as an archive", async () => {
const wrapper = mountDialog("save");
expect(uploadButton(wrapper).attributes("disabled")).toBeDefined();
@@ -132,7 +139,7 @@ describe("UploadAssetDialog", () => {
expect(uploadButton(wrapper).attributes("disabled")).toBeUndefined();
const payload = await submitted(wrapper);
expect(payload).toMatchObject({ slot: null, emulator: null });
expect(payload).toMatchObject({ type: "save", slot: null, emulator: null });
expect(payload!.files.map((f) => f.name)).toEqual(["game.srm"]);
});
@@ -169,7 +176,6 @@ describe("UploadAssetDialog", () => {
await choose(wrapper, 0, 3);
expect(await submitted(wrapper)).toBeUndefined();
formValid.value = true;
});
it("asks states only for the core", async () => {

View File

@@ -1,7 +1,6 @@
<script setup lang="ts">
// UploadAssetDialog: pick the slot for saves, or the core states were made
// with, then the files to send. The Save data tab owns the upload, and
// closes the dialog first.
// UploadAssetDialog: the slot for saves, or the core for states, plus the
// files to send. The Save data tab owns the upload.
import {
RBtn,
RChip,
@@ -17,6 +16,7 @@ import { useI18n } from "vue-i18n";
import type { SaveSchema } from "@/__generated__";
import { SAVE_SLOT_MAX_LENGTH } from "@/services/api/save";
import { formatBytes } from "@/utils";
import type { AssetType } from "@/v2/utils/assets";
import {
chosenSlot,
isSlotChoice,
@@ -24,9 +24,14 @@ import {
slotChoices,
type SlotChoice,
} from "@/v2/utils/saveSlots";
import { required } from "@/v2/utils/validation";
import { notBlank } from "@/v2/utils/validation";
export type UploadAssetType = "save" | "state";
export interface UploadAssetPayload {
type: AssetType;
files: File[];
slot: string | null;
emulator: string | null;
}
// A manual upload may also stay out of every slot, as an archive.
type UploadSlot = SlotChoice | { kind: "none" };
@@ -34,7 +39,7 @@ const NO_SLOT: UploadSlot = { kind: "none" };
const props = defineProps<{
modelValue: boolean;
type: UploadAssetType;
type: AssetType;
/** Own saves, whose slots the picker offers. */
saves: Pick<SaveSchema, "slot">[];
/** Cores the states may have been made with. */
@@ -45,9 +50,7 @@ const props = defineProps<{
const emit = defineEmits<{
"update:modelValue": [value: boolean];
submit: [
payload: { files: File[]; slot: string | null; emulator: string | null },
];
submit: [payload: UploadAssetPayload];
}>();
const { t } = useI18n();
@@ -86,8 +89,10 @@ watch(
slot.value = NO_SLOT;
newSlotName.value = "";
core.value = "";
files.value = [...props.initialFiles];
files.value = [];
addFiles(props.initialFiles);
},
{ immediate: true },
);
function addFiles(picked: File[]) {
@@ -109,6 +114,7 @@ async function submit() {
if (result && !result.valid) return;
const picked = slot.value;
emit("submit", {
type: props.type,
files: files.value,
slot:
props.type === "save" && picked.kind !== "none"
@@ -125,7 +131,6 @@ async function submit() {
icon="mdi-cloud-upload-outline"
width="520"
@update:model-value="emit('update:modelValue', $event)"
@close="close"
>
<template #header>
<span>{{
@@ -133,7 +138,7 @@ async function submit() {
}}</span>
</template>
<template #content>
<RForm ref="formRef" class="r-v2-upload-asset">
<RForm ref="formRef" class="r-v2-upload-asset" @submit="submit">
<RSelect
v-if="type === 'save'"
:model-value="slot"
@@ -154,7 +159,7 @@ async function submit() {
v-if="type === 'save' && slot.kind === 'new'"
v-model="newSlotName"
:label="t('play.slot-name')"
:rules="[required()]"
:rules="[notBlank()]"
:maxlength="SAVE_SLOT_MAX_LENGTH"
autocomplete="off"
/>

View File

@@ -150,7 +150,7 @@ export const ArchiveOnly: Story = {
},
};
// One slot, one version — the most common case for new players.
// One slot, one version, the most common case for new players.
export const SingleSave: Story = {
name: "Single save",
render: () => {

View File

@@ -3,10 +3,8 @@
// states). Shared between the EmulatorJS and Stream launch screens
// (selection) and the GameDetails "Save data" subtab (management).
//
// Saves follow the sync clients' slot model: rows group by slot, newest
// version first, with older versions folded behind a toggle. Slot-less saves
// are manual archives and sit in their own group. A save written by the
// browser player carries a screenshot, shown as the row thumbnail.
// Saves group by slot (archives last), newest version first with the older
// ones folded; a save's screenshot, when it has one, is the row thumbnail.
//
// Two modes, driven by `selectable`:
// * selectable (default) — Play view. Each row is a button; clicking
@@ -15,30 +13,29 @@
// trailing area renders the `#actions` slot (download/delete/toggle),
// and `showOwner` adds an author chip for community items.
import { RAvatar, RBtn, RIcon, RTag, RTooltip } from "@v2/lib";
import { computed, ref } from "vue";
import { computed, ref, watch } from "vue";
import { useI18n } from "vue-i18n";
import type {
SaveSchema,
StateSchema,
UserSaveSchema,
UserStateSchema,
} from "@/__generated__";
import { AUTOSAVE_SLOT } from "@/services/api/save";
import { formatBytes, formatRelativeDate, formatTimestamp } from "@/utils";
import {
byUpdatedDesc,
ownerOf,
screenshotOf,
staggerIndex,
type Asset,
type AssetOwner,
type AssetType,
} from "@/v2/utils/assets";
import { toCssUrl } from "@/v2/utils/css";
import { userAvatarUrl } from "@/v2/utils/userAvatar";
defineOptions({ inheritAttrs: false });
export type AssetType = "save" | "state";
type Asset = SaveSchema | StateSchema | UserSaveSchema | UserStateSchema;
type Owner = UserSaveSchema | UserStateSchema;
interface SlotGroup {
key: string;
/** Null for the archive of slot-less saves and for ungrouped states. */
slot: string | null;
owner: Owner | null;
owner: AssetOwner | null;
/** Newest first. */
versions: Asset[];
}
@@ -55,12 +52,15 @@ const props = withDefaults(
showOwner?: boolean;
/** Internal max-height + scroll. Off when the parent owns scrolling. */
scrollable?: boolean;
/** Off for lists whose saves are not slot versions (stream archives). */
groupBySlot?: boolean;
}>(),
{
selectable: true,
selectedId: null,
showOwner: false,
scrollable: true,
groupBySlot: true,
},
);
@@ -80,23 +80,12 @@ const emptyLabel = computed(() =>
: t("play.no-states-available"),
);
function ownerOf(asset: Asset): Owner | null {
return "username" in asset && asset.username ? asset : null;
}
function screenshotOf(asset: Asset): string | null {
return asset.screenshot?.download_path ?? null;
}
function slotOf(asset: Asset): string | null {
return "slot" in asset && asset.slot ? asset.slot : null;
}
// Only saves have slots; states render as one flat, headerless group.
const grouped = computed(() => props.type === "save");
const byUpdatedDesc = (a: Asset, b: Asset) =>
b.updated_at.localeCompare(a.updated_at);
const grouped = computed(() => props.type === "save" && props.groupBySlot);
// Autosave leads, named slots follow by recency, and the archive closes the
// list. Community lists key by owner too so two users' slots never merge.
@@ -124,33 +113,37 @@ const groups = computed<SlotGroup[]>(() => {
);
});
// Keeps the entrance stagger continuous across groups.
const fadeIndex = computed(() => {
const order = new Map<number, number>();
for (const group of groups.value) {
for (const asset of group.versions) order.set(asset.id, order.size);
}
return order;
});
// Older versions stay folded unless the user opens them or one is selected.
const expandedKeys = ref(new Set<string>());
function isExpanded(group: SlotGroup): boolean {
if (!grouped.value || expandedKeys.value.has(group.key)) return true;
// Older versions stay folded until opened, or until one of them is selected;
// an explicit toggle wins until the selection moves into the group again.
const openGroups = ref(new Map<string, boolean>());
function holdsOlderSelection(group: SlotGroup): boolean {
return (
props.selectable &&
group.versions.slice(1).some((asset) => asset.id === props.selectedId)
);
}
function toggleExpanded(group: SlotGroup) {
const next = new Set(expandedKeys.value);
if (isExpanded(group)) next.delete(group.key);
else next.add(group.key);
expandedKeys.value = next;
function isExpanded(group: SlotGroup): boolean {
if (!grouped.value) return true;
return openGroups.value.get(group.key) ?? holdsOlderSelection(group);
}
function toggleExpanded(group: SlotGroup) {
openGroups.value.set(group.key, !isExpanded(group));
}
watch(
() => props.selectedId,
() => {
for (const group of groups.value) {
if (holdsOlderSelection(group)) openGroups.value.delete(group.key);
}
},
);
function visibleVersions(group: SlotGroup): Asset[] {
return isExpanded(group) ? group.versions : group.versions.slice(0, 1);
}
const fadeIndex = computed(() =>
staggerIndex(groups.value.map(visibleVersions)),
);
</script>
<template>

View File

@@ -27,23 +27,23 @@
// `groupBy="emulator"` folds the tiles into one collapsible group per core,
// loadable cores first; a group whose tiles are all disabled starts closed.
import { RAvatar, RExpandTransition, RIcon, RTag, RTooltip } from "@v2/lib";
import { computed, ref } from "vue";
import { computed, ref, watch } from "vue";
import { useI18n } from "vue-i18n";
import type {
SaveSchema,
StateSchema,
UserSaveSchema,
UserStateSchema,
} from "@/__generated__";
import { formatBytes, formatRelativeDate, formatTimestamp } from "@/utils";
import {
newestUpdatedAt,
ownerOf,
screenshotOf,
staggerIndex,
type Asset,
type AssetType,
} from "@/v2/utils/assets";
import { toCssUrl } from "@/v2/utils/css";
import { userAvatarUrl } from "@/v2/utils/userAvatar";
defineOptions({ inheritAttrs: false });
export type AssetType = "save" | "state";
export type AssetLayout = "strip" | "flow" | "grid" | "list";
type Asset = SaveSchema | StateSchema | UserSaveSchema | UserStateSchema;
const props = withDefaults(
defineProps<{
@@ -83,17 +83,6 @@ const emptyLabel = computed(() =>
: t("play.no-states-available"),
);
function screenshotOf(asset: Asset): string | null {
if ("screenshot" in asset && asset.screenshot?.download_path) {
return asset.screenshot.download_path;
}
return null;
}
function ownerOf(asset: Asset): UserSaveSchema | UserStateSchema | null {
return "username" in asset && asset.username ? asset : null;
}
function reasonOf(asset: Asset): string | null {
return props.selectable ? (props.disabledReason?.(asset) ?? null) : null;
}
@@ -107,9 +96,6 @@ interface AssetGroup {
disabled: boolean;
}
const newestOf = (assets: Asset[]) =>
assets.reduce((best, a) => (a.updated_at > best ? a.updated_at : best), "");
const groups = computed<AssetGroup[]>(() => {
if (!props.groupBy) {
return [{ key: "all", label: "", assets: props.assets, disabled: false }];
@@ -130,39 +116,52 @@ const groups = computed<AssetGroup[]>(() => {
group.assets.push(asset);
if (!reasonOf(asset)) group.disabled = false;
}
const newest = new Map(
[...byKey.values()].map((group) => [
group.key,
newestUpdatedAt(group.assets),
]),
);
return [...byKey.values()].sort(
(a, b) =>
Number(a.disabled) - Number(b.disabled) ||
newestOf(b.assets).localeCompare(newestOf(a.assets)),
newest.get(b.key)!.localeCompare(newest.get(a.key)!),
);
});
// Keeps the entrance stagger continuous across groups.
const fadeIndex = computed(() => {
const order = new Map<number, number>();
for (const group of groups.value) {
for (const asset of group.assets) order.set(asset.id, order.size);
}
return order;
});
// A group opens on its own while it holds the selection.
// Loadable groups start open and a group opens when it takes the selection;
// an explicit toggle wins until the selection moves into the group again.
const openGroups = ref(new Map<string, boolean>());
function isOpen(group: AssetGroup): boolean {
if (!props.groupBy) return true;
if (
function holdsSelection(group: AssetGroup): boolean {
return (
props.selectable &&
group.assets.some((asset) => asset.id === props.selectedId)
) {
return true;
}
return openGroups.value.get(group.key) ?? !group.disabled;
);
}
function isOpen(group: AssetGroup): boolean {
if (!props.groupBy) return true;
return (
openGroups.value.get(group.key) ??
(holdsSelection(group) || !group.disabled)
);
}
function toggleGroup(group: AssetGroup) {
const next = new Map(openGroups.value);
next.set(group.key, !isOpen(group));
openGroups.value = next;
openGroups.value.set(group.key, !isOpen(group));
}
watch(
() => props.selectedId,
() => {
for (const group of groups.value) {
if (holdsSelection(group)) openGroups.value.delete(group.key);
}
},
);
const fadeIndex = computed(() =>
staggerIndex(
groups.value.map((group) => (isOpen(group) ? group.assets : [])),
),
);
</script>
<template>

View File

@@ -16,7 +16,7 @@
// • title — header (alternatively `title` prop)
// • prepend — replaces the auto-picked icon
// • append — extra content on the trailing edge
// • actions — a row of controls under the body text
// • actions: a row of controls under the body text
//
// v-model controls visibility. When `closable` is set, clicking the
// X emits `click:close` and flips `modelValue` to false; the leave

View File

@@ -0,0 +1,41 @@
import type {
SaveSchema,
StateSchema,
UserSaveSchema,
UserStateSchema,
} from "@/__generated__";
export type AssetType = "save" | "state";
export type Asset = SaveSchema | StateSchema | UserSaveSchema | UserStateSchema;
export type AssetOwner = UserSaveSchema | UserStateSchema;
export function ownerOf(asset: Asset): AssetOwner | null {
return "username" in asset && asset.username ? asset : null;
}
export function screenshotOf(asset: Asset): string | null {
return asset.screenshot?.download_path ?? null;
}
/** ISO timestamps sort lexically. */
export function byUpdatedDesc(a: Asset, b: Asset): number {
return b.updated_at.localeCompare(a.updated_at);
}
export function newestUpdatedAt(assets: readonly Asset[]): string {
return assets.reduce(
(best, asset) => (asset.updated_at > best ? asset.updated_at : best),
"",
);
}
/** Entrance-stagger index per rendered asset, continuous across groups. */
export function staggerIndex(
visibleGroups: readonly (readonly Asset[])[],
): Map<number, number> {
const order = new Map<number, number>();
for (const assets of visibleGroups) {
for (const asset of assets) order.set(asset.id, order.size);
}
return order;
}

View File

@@ -7,6 +7,7 @@ import {
preferredSlot,
slotChoiceKey,
slotChoices,
slotForSave,
} from "./saveSlots";
const save = (id: number, slot: string | null = null) => ({ id, slot });
@@ -88,3 +89,12 @@ describe("isSlotChoice", () => {
expect(isSlotChoice(null)).toBe(false);
});
});
describe("slotForSave", () => {
it("follows a slotted save and keeps the choice for an archive", () => {
expect(slotForSave(save(1, "main"), existingSlot("autosave"))).toEqual(
existingSlot("main"),
);
expect(slotForSave(save(2), NEW_SLOT_CHOICE)).toBe(NEW_SLOT_CHOICE);
});
});

View File

@@ -50,3 +50,11 @@ export function chosenSlot(choice: SlotChoice, newSlotName: string): string {
if (choice.kind === "existing") return choice.slot;
return newSlotName.trim() || AUTOSAVE_SLOT;
}
/** A slotted save fixes the write slot; an archive leaves the choice as is. */
export function slotForSave(
save: Pick<SaveSchema, "slot">,
current: SlotChoice,
): SlotChoice {
return save.slot ? existingSlot(save.slot) : current;
}

View File

@@ -25,6 +25,13 @@ export function required(msg?: string): Rule {
return (v) => !isEmpty(v) || (msg ?? t("common.required"));
}
/** `required` that also rejects whitespace-only text. */
export function notBlank(msg?: string): Rule {
return (v) =>
(typeof v === "string" ? v.trim().length > 0 : !isEmpty(v)) ||
(msg ?? t("common.required"));
}
export const email: Rule = (v) =>
typeof v === "string" && /.+@.+\..+/.test(v)
? true

View File

@@ -92,11 +92,13 @@ import {
preferredSlot,
slotChoiceKey,
slotChoices,
slotForSave,
type SlotChoice,
} from "@/v2/utils/saveSlots";
import { isJsResource, loadScript } from "@/v2/utils/scriptLoader";
import { rememberCore, resolveRememberedCore } from "./coreStorage";
import {
clearState,
defaultResumeSelection,
newerThanPick,
pickSave,
@@ -173,6 +175,9 @@ const compatibleStates = computed(
() => rom.value?.user_states.filter(isCoreCompatible) ?? [],
);
const stateCount = computed(() => rom.value?.user_states.length ?? 0);
const allStatesCompatible = computed(
() => compatibleStates.value.length === stateCount.value,
);
// Other emulators' states stay listed, disabled, so the count adds up.
function stateDisabledReason(asset: { emulator?: string | null }) {
if (isCoreCompatible(asset)) return null;
@@ -287,8 +292,11 @@ async function onPlay() {
}
}
// A slotted save fixes the write slot, and it stays put for the session
// even when a state later displaces the save.
function selectSave(save: SaveSchema) {
resume.value = pickSave(save);
slotChoice.value = slotForSave(save, slotChoice.value);
isSavesTabSelected.value = true;
}
@@ -296,16 +304,13 @@ function unselectSave() {
resume.value = { ...resume.value, save: null };
}
// The picked save's slot carries over as the write target for the session.
function selectState(state: StateSchema) {
const previousSlot = resume.value.save?.slot;
resume.value = pickState(state);
if (previousSlot) slotChoice.value = existingSlot(previousSlot);
resume.value = pickState(resume.value, state);
isSavesTabSelected.value = false;
}
function unselectState() {
resume.value = { ...resume.value, state: null };
resume.value = clearState(resume.value);
}
watch(selectedCore, (newSelectedCore) => {
@@ -460,10 +465,9 @@ const assetTabs = computed<SliderBtnGroupItem<AssetTab>[]>(() => [
{
id: "state",
label: t("common.states"),
badge:
compatibleStates.value.length === stateCount.value
? stateCount.value
: `${compatibleStates.value.length}/${stateCount.value}`,
badge: allStatesCompatible.value
? stateCount.value
: `${compatibleStates.value.length}/${stateCount.value}`,
icon: "mdi-file",
},
]);
@@ -482,21 +486,17 @@ function clearSelectedAsset() {
else unselectState();
}
// Loadable states lead; the rest trail, disabled, in their own order.
const activeAssets = computed<(SaveSchema | StateSchema)[]>(() => {
if (isSavesTabSelected.value) return rom.value?.user_saves ?? [];
const states = rom.value?.user_states ?? [];
return [
...compatibleStates.value,
...states.filter((s) => !isCoreCompatible(s)),
];
});
const activeAssets = computed<(SaveSchema | StateSchema)[]>(() =>
isSavesTabSelected.value
? (rom.value?.user_saves ?? [])
: (rom.value?.user_states ?? []),
);
const stripCount = computed(() => {
if (isSavesTabSelected.value) return String(activeAssets.value.length);
const compatible = compatibleStates.value.length;
if (compatible === stateCount.value) return String(stateCount.value);
if (isSavesTabSelected.value || allStatesCompatible.value) {
return String(activeAssets.value.length);
}
return t("play.compatible-of-total", {
compatible,
compatible: compatibleStates.value.length,
total: stateCount.value,
});
});
@@ -650,9 +650,7 @@ const saveSlot = computed(() => chosenSlot(slotChoice.value, customSlot.value));
<div class="r-v2-ejs__slot-row">
<RSelect
class="r-v2-ejs__slot-select"
:model-value="
boundSlot ? existingSlot(boundSlot) : slotChoice
"
:model-value="slotChoice"
:disabled="!!boundSlot"
variant="outlined"
density="compact"
@@ -708,9 +706,8 @@ const saveSlot = computed(() => chosenSlot(slotChoice.value, customSlot.value));
<span class="r-v2-ejs__strip-count">{{ stripCount }}</span>
</div>
<!-- Saves render as a vertical list (no screenshot ⇒ density);
states keep the horizontal tile strip (screenshot is the
point). The wrapper owns the only scroll on the screen. -->
<!-- Saves as slot rows, states as a grid grouped by core. The
wrapper owns the only scroll on the screen. -->
<div class="r-v2-ejs__assets">
<AssetList
v-if="activeAssetTab === 'save'"
@@ -990,9 +987,8 @@ const saveSlot = computed(() => chosenSlot(slotChoice.value, customSlot.value));
.r-v2-ejs__resume-main {
flex: 1;
}
/* States on a wide screen: the tile grid takes the panel's width and the
preview, warning and slot picker sit in a fixed side column so the grid
never shrinks. Saves keep the stacked column, their rows are wide. */
/* States on a wide screen: the grid keeps the panel's width and the preview
column stays fixed. Saves keep the stacked column, their rows are wide. */
html[data-bp~="md-and-up"] .r-v2-ejs__resume-body--split {
display: grid;
grid-template-columns: minmax(0, 1fr) minmax(220px, 280px);

View File

@@ -1422,6 +1422,7 @@ onBeforeUnmount(() => {
:assets="restorableSaves"
type="save"
:selected-id="selectedSave?.id ?? null"
:group-by-slot="false"
@select="savePickId = ($event as SaveSchema).id"
/>
</template>

View File

@@ -1,6 +1,7 @@
import { describe, expect, it } from "vitest";
import type { SaveSchema, StateSchema } from "@/__generated__";
import {
clearState,
defaultResumeSelection,
newerThanPick,
pickSave,
@@ -40,8 +41,34 @@ describe("pickSave", () => {
});
describe("pickState", () => {
it("boots from the state and drops any picked save", () => {
expect(pickState(state(9))).toEqual({ save: null, state: state(9) });
it("boots from the state and sets the picked save aside", () => {
expect(pickState(pickSave(save(2)), state(9))).toEqual({
save: null,
state: state(9),
aside: save(2),
});
});
it("keeps the aside save across a second state pick", () => {
const first = pickState(pickSave(save(2)), state(9));
expect(pickState(first, state(8)).aside).toEqual(save(2));
});
});
describe("clearState", () => {
it("restores the save the state displaced", () => {
expect(clearState(pickState(pickSave(save(2)), state(9)))).toEqual({
save: save(2),
state: null,
});
});
it("leaves nothing picked when the state was the default", () => {
expect(clearState(defaultResumeSelection([save(1)], [state(9)]))).toEqual({
save: null,
state: null,
});
});
});
@@ -58,11 +85,23 @@ describe("newerThanPick", () => {
stateAt(8, "2026-09-05T10:00:00Z"),
];
expect(newerThanPick(saves, states, pickState(states[0]))).toEqual({
expect(
newerThanPick(
saves,
states,
pickState({ save: null, state: null }, states[0]),
),
).toEqual({
kind: "state",
asset: states[1],
});
expect(newerThanPick(saves, [states[0]], pickState(states[0]))).toEqual({
expect(
newerThanPick(
saves,
[states[0]],
pickState({ save: null, state: null }, states[0]),
),
).toEqual({
kind: "save",
asset: saves[0],
});

View File

@@ -5,6 +5,8 @@ import type { SaveSchema, StateSchema } from "@/__generated__";
export interface ResumeSelection {
save: SaveSchema | null;
state: StateSchema | null;
/** The save a picked state displaced, restored when the state is cleared. */
aside?: SaveSchema | null;
}
/** The newest compatible state, else the newest save; never both. */
@@ -21,9 +23,17 @@ export function pickSave(save: SaveSchema): ResumeSelection {
return { save, state: null };
}
/** A picked state carries its own SRAM, so no save stays bound. */
export function pickState(state: StateSchema): ResumeSelection {
return { save: null, state };
/** A picked state carries its own SRAM, so the picked save steps aside. */
export function pickState(
selection: ResumeSelection,
state: StateSchema,
): ResumeSelection {
return { save: null, state, aside: selection.save ?? selection.aside };
}
/** Clearing the state hands the boot back to the save it displaced. */
export function clearState(selection: ResumeSelection): ResumeSelection {
return { save: selection.aside ?? null, state: null };
}
export type NewerAsset =