refactor: simplify pass (pr-ready step 3)

- Validate each exclude list where it is read, so a new path cannot skip
  validation and the rule has one home.
- Move useEscapable to composables/ and use it in RMenu and
  MatchRomBodyGrid, which hand-rolled the same stack wiring.
- Drop the Escape branches in RSelect and RDateField that the escape
  stack's capture listener now preempts.
- Debounce the gallery search with lodash like the rest of v2.
- Drop a cached-client assertion that held by construction.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Georges-Antoine Assi
2026-10-01 15:10:39 -04:00
parent c92d665c6c
commit b2b7904b51
10 changed files with 48 additions and 109 deletions

View File

@@ -303,14 +303,6 @@ PLATFORM_MEDIA_DIRS: Final = {
DEFAULT_EXCLUDED_MULTI_FILE_DIRS: Final = sorted(
{*DEFAULT_EXCLUDED_PLATFORM_DIRS, *PLATFORM_MEDIA_DIRS.values()}
)
EXCLUDE_LIST_PATHS: Final = (
"exclude.platforms",
"exclude.roms.single_file.extensions",
"exclude.roms.single_file.names",
"exclude.roms.multi_file.names",
"exclude.roms.multi_file.parts.extensions",
"exclude.roms.multi_file.parts.names",
)
class ExclusionType(enum.StrEnum):
@@ -688,11 +680,21 @@ class ConfigManager:
)
def _raw_exclude_list(self, path: str) -> list[str]:
"""Read a user exclude list; `_validate_config` rejects non-strings."""
"""Read a user exclude list, exiting on anything but a list of strings."""
value = pydash.get(self._raw_config, path)
if not isinstance(value, list):
if value is None:
return []
return [item for item in value if isinstance(item, str)]
if not isinstance(value, list):
log.critical(f"Invalid config.yml: {path} must be a list")
sys.exit(3)
# YAML reads an unquoted 001 or 1942 as a number.
if not all(isinstance(item, str) for item in value):
log.critical(
f"Invalid config.yml: {path} must only hold strings, "
"quote numeric entries such as '001'"
)
sys.exit(3)
return value
def _parse_config(self) -> None:
"""Parses each entry in the config.yml"""
@@ -1003,21 +1005,6 @@ class ConfigManager:
"""Validates the config.yml file"""
self._check_retired_filesystem_keys()
for path in EXCLUDE_LIST_PATHS:
value = pydash.get(self._raw_config, path)
if value is None:
continue
if not isinstance(value, list):
log.critical(f"Invalid config.yml: {path} must be a list")
sys.exit(3)
# YAML reads an unquoted 001 or 1942 as a number.
if not all(isinstance(item, str) for item in value):
log.critical(
f"Invalid config.yml: {path} must only hold strings, "
"quote numeric entries such as '001'"
)
sys.exit(3)
if not isinstance(self.config.GAMELIST_AUTO_EXPORT_ON_SCAN, bool):
log.critical("Invalid config.yml: scan.gamelist.export must be a boolean")
sys.exit(3)

View File

@@ -10,7 +10,6 @@ from config.config_manager import (
DEFAULT_EXCLUDED_FILES,
DEFAULT_EXCLUDED_MULTI_FILE_DIRS,
DEFAULT_EXCLUDED_PLATFORM_DIRS,
EXCLUDE_LIST_PATHS,
ConfigManager,
parse_firmware_template,
parse_platform_templates,
@@ -705,6 +704,16 @@ def critical(mocker):
return lambda: str(spy.call_args[0][0])
EXCLUDE_LIST_PATHS = (
"exclude.platforms",
"exclude.roms.single_file.extensions",
"exclude.roms.single_file.names",
"exclude.roms.multi_file.names",
"exclude.roms.multi_file.parts.extensions",
"exclude.roms.multi_file.parts.names",
)
def _write_exclude_config(tmp_path: Path, path: str, value: str) -> ConfigManager:
"""Write `value` at the dotted `path`, nesting one YAML level per segment."""
lines = [f"{' ' * depth}{key}:" for depth, key in enumerate(path.split("."))]

View File

@@ -1,7 +1,6 @@
import type { AxiosRequestConfig, AxiosResponse } from "axios";
import { beforeEach, describe, expect, it, vi } from "vitest";
import {
buildGetRomsQuery,
RECENT_PLAYED_ROMS_LIMIT,
RECENT_ROMS_LIMIT,
} from "@/services/api/rom";
@@ -83,7 +82,7 @@ describe("home row cache invalidation", () => {
});
describe("gallery request", () => {
it("sends the same query as the uncached client", async () => {
it("sends every gallery filter the uncached client maps", async () => {
const params = {
platformIds: [1],
selectedPublishers: ["Nintendo"],
@@ -98,7 +97,6 @@ describe("gallery request", () => {
await cachedApiService.getRoms(params, noop);
expect(requestParams()).toEqual(buildGetRomsQuery(params));
expect(requestParams()).toMatchObject({
publishers: ["Nintendo"],
has_soundtrack: true,

View File

@@ -6,7 +6,7 @@
// over the body with cover-source picker + rename + confirm. Click
// the backdrop or press Esc to close.
import { RBtn, REmptyState, RIcon, RProgressCircular } from "@v2/lib";
import { computed, onBeforeUnmount, ref, watch } from "vue";
import { computed, ref, watch } from "vue";
import { useI18n } from "vue-i18n";
import type { SearchRom, SimpleRom } from "@/stores/roms";
import GameCard from "@/v2/components/GameCard/GameCard.vue";
@@ -18,11 +18,7 @@ import {
matchKey,
type MatchedSource,
} from "@/v2/components/MatchRom/types";
import {
type EscapableEntry,
popEscapable,
pushEscapable,
} from "@/v2/lib/overlays/RDialog/escapeStack";
import { useEscapable } from "@/v2/composables/useEscapable";
defineOptions({ inheritAttrs: false });
@@ -88,15 +84,10 @@ function confirm() {
// RDialog open (the user can press Esc again to close that). Without
// the stack, the dialog's own global Esc listener would fire first
// and close everything at once.
const overlayEscEntry: EscapableEntry = {
close: () => close(),
persistent: false,
};
watch(activeKey, (value) => {
if (value !== null) pushEscapable(overlayEscEntry);
else popEscapable(overlayEscEntry);
});
onBeforeUnmount(() => popEscapable(overlayEscEntry));
useEscapable(
computed(() => activeKey.value !== null),
() => close(),
);
watch(
() => props.results,

View File

@@ -1,34 +1,29 @@
import { debounce } from "lodash";
import { onScopeDispose, type Ref, ref, watch } from "vue";
/** A search box bound to a store term, debounced one way and immediate the
* other, so a term set by navigation shows up in the box. */
export function useDebouncedSearch(term: Ref<string | null>, delayMs = 300) {
const input = ref(term.value ?? "");
let pending: ReturnType<typeof setTimeout> | null = null;
function cancel() {
if (pending) clearTimeout(pending);
pending = null;
}
const commit = debounce((value: string) => {
const normalized = value.trim();
if (normalized !== (term.value ?? "")) term.value = normalized || null;
}, delayMs);
function setSearch(value: string) {
input.value = value;
cancel();
pending = setTimeout(() => {
pending = null;
const normalized = value.trim();
if (normalized !== (term.value ?? "")) term.value = normalized || null;
}, delayMs);
commit(value);
}
watch(term, (value) => {
if (input.value.trim() === (value ?? "")) return;
// A keystroke still waiting would overwrite the term just navigated to.
cancel();
commit.cancel();
input.value = value ?? "";
});
onScopeDispose(cancel);
onScopeDispose(commit.cancel);
return { input, setSearch };
}

View File

@@ -3,7 +3,7 @@ import {
type EscapableEntry,
popEscapable,
pushEscapable,
} from "./escapeStack";
} from "@/v2/lib/overlays/RDialog/escapeStack";
/** Keep a popover on the escape stack while `isOpen`, so Escape and pad B
* close it before any overlay it sits in. Returns the stack entry. */

View File

@@ -37,8 +37,8 @@ import {
useSlots,
watch,
} from "vue";
import { useEscapable } from "@/v2/composables/useEscapable";
import { useChromeLabels } from "@/v2/lib/a11y/chromeLabels";
import { useEscapable } from "@/v2/lib/overlays/RDialog/useEscapable";
import RIcon from "@/v2/lib/primitives/RIcon/RIcon.vue";
import RTag from "@/v2/lib/primitives/RTag/RTag.vue";
import { useRFormRegistration } from "../RForm/context";

View File

@@ -32,8 +32,8 @@ import {
useId,
watch,
} from "vue";
import { useEscapable } from "@/v2/composables/useEscapable";
import { useChromeLabels } from "@/v2/lib/a11y/chromeLabels";
import { useEscapable } from "@/v2/lib/overlays/RDialog/useEscapable";
import RBtn from "../../primitives/RBtn/RBtn.vue";
import RIcon from "../../primitives/RIcon/RIcon.vue";
import RTextField from "../RTextField/RTextField.vue";
@@ -364,11 +364,6 @@ function onPanelKeydown(evt: KeyboardEvent) {
evt.preventDefault();
selectDay(new Date(focusedDay.value));
break;
case "Escape":
evt.preventDefault();
evt.stopPropagation();
dismiss();
break;
default:
break;
}
@@ -414,9 +409,8 @@ function focusDayCell() {
// ── Field-level keyboard wiring ────────────────────────────────
// On the closed field: Space / Enter / ArrowDown opens the popup. Tab
// behaves natively (moves to next focusable). When open, Escape closes
// (handled inside the panel: the field doesn't see keydown when focus
// has moved into the calendar).
// behaves natively (moves to next focusable). When open, the escape stack
// owns Escape.
function onFieldKeydown(evt: KeyboardEvent) {
if (props.disabled) return;
if (isOpen.value) return;
@@ -456,7 +450,7 @@ useEscapable(isOpen, dismiss, () => panelRef.value);
</script>
<template>
<!-- Keydown sits here so Escape and the arrows work wherever focus is
<!-- Keydown sits here so the opening keys work wherever focus is
inside the field; the combobox role goes on the input via `popup`. -->
<!-- eslint-disable-next-line vuejs-accessibility/no-static-element-interactions -->
<div ref="referenceEl" class="r-date-field" @keydown="onFieldKeydown">

View File

@@ -36,9 +36,9 @@ import {
useSlots,
watch,
} from "vue";
import { useEscapable } from "@/v2/composables/useEscapable";
import { useInputModality } from "@/v2/composables/useInputModality";
import { useChromeLabels } from "@/v2/lib/a11y/chromeLabels";
import { useEscapable } from "@/v2/lib/overlays/RDialog/useEscapable";
import { shouldAutofocusSearch } from "@/v2/utils/autofocus";
import RDivider from "../../primitives/RDivider/RDivider.vue";
import RIcon from "../../primitives/RIcon/RIcon.vue";
@@ -813,12 +813,6 @@ function onActivatorKey(evt: KeyboardEvent) {
if (item) selectItem(item);
}
break;
case "Escape":
if (isOpen.value) {
evt.preventDefault();
closeMenu();
}
break;
case "Tab":
if (isOpen.value) closeMenu();
break;
@@ -841,11 +835,6 @@ function onSearchKey(evt: KeyboardEvent) {
if (item) selectItem(item);
break;
}
case "Escape":
evt.preventDefault();
closeMenu();
activatorRef.value?.focus();
break;
}
}

View File

@@ -44,15 +44,11 @@ import {
watch,
} from "vue";
import { useBreakpoint } from "@/v2/composables/useBreakpoint";
import { useEscapable } from "@/v2/composables/useEscapable";
import { useInputModality } from "@/v2/composables/useInputModality";
import { opensInNewContext } from "@/v2/utils/mouseGestures";
import RTextField from "../../forms/RTextField/RTextField.vue";
import {
type EscapableEntry,
isInsideEscapableAbove,
popEscapable,
pushEscapable,
} from "../../overlays/RDialog/escapeStack.js";
import { isInsideEscapableAbove } from "../../overlays/RDialog/escapeStack.js";
import RIcon from "../../primitives/RIcon/RIcon.vue";
import { RMenuCloseKey } from "./context";
@@ -333,23 +329,7 @@ watch(
},
);
const escEntry: EscapableEntry = {
close: () => close(),
persistent: false,
panel: () => panelRef.value,
};
watch(
() => isOpen.value,
(open) => {
if (open) pushEscapable(escEntry);
else popEscapable(escEntry);
},
// `immediate: true` so a menu that mounts already open registers too, the
// same reason RDialog does it: otherwise the watch never sees the initial
// `true` and Esc, gamepad-back and tooltip suppression all miss the panel.
{ immediate: true },
);
const escEntry = useEscapable(isOpen, close, () => panelRef.value);
onMounted(() => {
reference.value = activatorWrapper.value?.firstElementChild ?? null;
@@ -357,10 +337,6 @@ onMounted(() => {
});
onBeforeUnmount(() => {
document.removeEventListener("pointerdown", onDocPointerDown, true);
// Safety: if we unmount while open (route change while the menu is
// visible) drop our entry so the stack doesn't dereference a dead
// close function.
popEscapable(escEntry);
});
// Re-read the reference if the slot content changes (e.g., v-if flips).