refactor(v2): one home for checkbox selection, and fix the a11y lint

The `ref<Set<number>>` plus clone-and-swap plus all/some computeds had
been written three times: the Files tab, the Firmware tab, and the Save
data tab this branch added. `useIdSelection` now owns it, and all three
call it.

It keeps the stale-id defence the Files tab had and the other two
lacked: the count comes from intersecting with the live list, so an id
left behind by a delete elsewhere cannot inflate it. The set is replaced
rather than mutated, since Vue does not track `Set` writes.

The toolbar's count moves onto RCheckbox's own `label`, which is what
associates the two. Wrapping the checkbox in a bare `<label>` failed
vuejs-accessibility/label-has-for in CI, because the rule cannot see
that the component renders an input. The Firmware tab already did it
this way.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016bZ7R3xC73MZu1vTNuatPK
This commit is contained in:
zurdi
2026-09-23 09:14:09 +02:00
parent 8e07bcbb90
commit effb33dbe9
25 changed files with 236 additions and 206 deletions

View File

@@ -413,7 +413,6 @@
"search-placeholder": "Търси по име, име на файл, хеш…",
"seek-progress": "{current} от {duration}",
"select-all": "Избери всички",
"select-all-assets": "Избери всички",
"select-all-disk": "Избери всички за диска",
"select-asset": "Избери {name}",
"select-cover-image": "Избери изображение за корица",

View File

@@ -413,7 +413,6 @@
"search-placeholder": "Hledat podle názvu, souboru, hashe…",
"seek-progress": "{current} z {duration}",
"select-all": "Vybrat vše",
"select-all-assets": "Vybrat vše",
"select-all-disk": "Vybrat vše pro disk",
"select-asset": "Vybrat {name}",
"select-cover-image": "Vybrat obrázek obalu",

View File

@@ -413,7 +413,6 @@
"search-placeholder": "Nach Name, Dateiname, Hash suchen…",
"seek-progress": "{current} von {duration}",
"select-all": "Alles auswählen",
"select-all-assets": "Alle auswählen",
"select-all-disk": "Alle für Datenträger auswählen",
"select-asset": "{name} auswählen",
"select-cover-image": "Wähle ein Coverbild",

View File

@@ -413,7 +413,6 @@
"search-placeholder": "Search by name, filename, hash…",
"seek-progress": "{current} of {duration}",
"select-all": "Select all",
"select-all-assets": "Select all",
"select-all-disk": "Select all for disk",
"select-asset": "Select {name}",
"select-cover-image": "Select a cover image",

View File

@@ -413,7 +413,6 @@
"search-placeholder": "Search by name, filename, hash…",
"seek-progress": "{current} of {duration}",
"select-all": "Select all",
"select-all-assets": "Select all",
"select-all-disk": "Select all for disk",
"select-asset": "Select {name}",
"select-cover-image": "Select a cover image",

View File

@@ -413,7 +413,6 @@
"search-placeholder": "Buscar por nombre, archivo, hash…",
"seek-progress": "Posición de reproducción",
"select-all": "Seleccionar todos",
"select-all-assets": "Seleccionar todo",
"select-all-disk": "Seleccionar todos para disco",
"select-asset": "Seleccionar {name}",
"select-cover-image": "Selecciona una carátula",

View File

@@ -413,7 +413,6 @@
"search-placeholder": "Rechercher par nom, nom de fichier, hachage…",
"seek-progress": "{current} sur {duration}",
"select-all": "Sélectionner tous",
"select-all-assets": "Tout sélectionner",
"select-all-disk": "Tout sélectionner pour le disque",
"select-asset": "Sélectionner {name}",
"select-cover-image": "Sélectionner une image de couverture",

View File

@@ -413,7 +413,6 @@
"search-placeholder": "Keresés név, fájlnév, hash szerint…",
"seek-progress": "{current} / {duration}",
"select-all": "Összes kijelölése",
"select-all-assets": "Összes kijelölése",
"select-all-disk": "Összes kijelölése a lemezhez",
"select-asset": "{name} kijelölése",
"select-cover-image": "Válassz borítóképet",

View File

@@ -413,7 +413,6 @@
"search-placeholder": "Cerca per nome, nome file, hash…",
"seek-progress": "{current} di {duration}",
"select-all": "Seleziona tutto",
"select-all-assets": "Seleziona tutto",
"select-all-disk": "Seleziona tutto per il disco",
"select-asset": "Seleziona {name}",
"select-cover-image": "Seleziona un'immagine di copertina",

View File

@@ -413,7 +413,6 @@
"search-placeholder": "名前、ファイル名、ハッシュで検索…",
"seek-progress": "{duration}中{current}",
"select-all": "すべて選択",
"select-all-assets": "すべて選択",
"select-all-disk": "ディスク用にすべて選択",
"select-asset": "{name} を選択",
"select-cover-image": "カバー画像を選択",

View File

@@ -413,7 +413,6 @@
"search-placeholder": "이름, 파일 이름, 해시로 검색…",
"seek-progress": "{duration} 중 {current}",
"select-all": "모두 선택",
"select-all-assets": "전체 선택",
"select-all-disk": "디스크용 모두 선택",
"select-asset": "{name} 선택",
"select-cover-image": "커버 이미지 선택",

View File

@@ -413,7 +413,6 @@
"search-placeholder": "Szukaj po nazwie, pliku, hashu…",
"seek-progress": "{current} z {duration}",
"select-all": "Wybierz wszystkie",
"select-all-assets": "Zaznacz wszystko",
"select-all-disk": "Wybierz wszystkie z dysku",
"select-asset": "Zaznacz {name}",
"select-cover-image": "Wybierz obraz okładki",

View File

@@ -413,7 +413,6 @@
"search-placeholder": "Buscar por nome, arquivo, hash…",
"seek-progress": "{current} de {duration}",
"select-all": "Selecionar todos",
"select-all-assets": "Selecionar tudo",
"select-all-disk": "Selecionar todos para o disco",
"select-asset": "Selecionar {name}",
"select-cover-image": "Selecionar uma imagem de capa",

View File

@@ -413,7 +413,6 @@
"search-placeholder": "Caută după nume, nume fișier, hash…",
"seek-progress": "{current} din {duration}",
"select-all": "Selectează toate",
"select-all-assets": "Selectează tot",
"select-all-disk": "Selectează toate pentru disc",
"select-asset": "Selectează {name}",
"select-cover-image": "Selectează o imagine de copertă",

View File

@@ -413,7 +413,6 @@
"search-placeholder": "Поиск по названию, имени файла, хешу…",
"seek-progress": "{current} из {duration}",
"select-all": "Выбрать все",
"select-all-assets": "Выбрать все",
"select-all-disk": "Выбрать всё для диска",
"select-asset": "Выбрать {name}",
"select-cover-image": "Выбрать обложку",

View File

@@ -413,7 +413,6 @@
"search-placeholder": "Ad, dosya adı, hash ile ara…",
"seek-progress": "{duration} içinde {current}",
"select-all": "Tümünü seç",
"select-all-assets": "Tümünü seç",
"select-all-disk": "Disk için tümünü seç",
"select-asset": "{name} ögesini seç",
"select-cover-image": "Kapak görseli seç",

View File

@@ -413,7 +413,6 @@
"search-placeholder": "按名称、文件名、哈希值搜索…",
"seek-progress": "{current} / {duration}",
"select-all": "选择所有",
"select-all-assets": "全选",
"select-all-disk": "全选用于磁盘",
"select-asset": "选择 {name}",
"select-cover-image": "选择封面图片",

View File

@@ -413,7 +413,6 @@
"search-placeholder": "依名稱、檔案名、雜湊值搜尋…",
"seek-progress": "{current} / {duration}",
"select-all": "選擇所有",
"select-all-assets": "全選",
"select-all-disk": "選擇所有以從磁碟刪除",
"select-asset": "選擇 {name}",
"select-cover-image": "選擇封面圖片",

View File

@@ -34,6 +34,7 @@ import { formatBytes } from "@/utils";
import DeleteFirmwareDialog from "@/v2/components/Gallery/DeleteFirmwareDialog.vue";
import HashChip from "@/v2/components/shared/HashChip.vue";
import { useCan } from "@/v2/composables/useCan";
import { useIdSelection } from "@/v2/composables/useIdSelection";
import { useSnackbar } from "@/v2/composables/useSnackbar";
import storeGalleryRoms from "@/v2/stores/galleryRoms";
@@ -49,41 +50,19 @@ const platformsStore = storePlatforms();
const galleryRoms = storeGalleryRoms();
const canWrite = useCan("platform.edit");
const selectedIds = ref<Set<number>>(new Set());
const firmwareList = computed<FirmwareSchema[]>(
() => props.platform.firmware ?? [],
);
const selectedFirmware = computed<FirmwareSchema[]>(() =>
firmwareList.value.filter((f) => selectedIds.value.has(f.id)),
);
const allSelected = computed(
() =>
firmwareList.value.length > 0 &&
selectedIds.value.size === firmwareList.value.length,
);
const someSelected = computed(
() =>
selectedIds.value.size > 0 &&
selectedIds.value.size < firmwareList.value.length,
);
function toggleAll() {
if (allSelected.value) {
selectedIds.value = new Set();
} else {
selectedIds.value = new Set(firmwareList.value.map((f) => f.id));
}
}
function toggleOne(id: number) {
const next = new Set(selectedIds.value);
if (next.has(id)) next.delete(id);
else next.add(id);
selectedIds.value = next;
}
// Destructured so the template sees plain refs; a nested one is not unwrapped.
const {
selectedIds,
selected: selectedFirmware,
allSelected,
someSelected,
toggle: toggleOne,
toggleAll,
} = useIdSelection(() => firmwareList.value);
// ── Inline upload (no dialog — the dropzone lives in the tab) ──────
const firmwareDz = ref<InstanceType<typeof RDropzone> | null>(null);

View File

@@ -14,9 +14,10 @@ const RCheckbox = {
props: {
modelValue: { type: Boolean, default: false },
indeterminate: { type: Boolean, default: false },
label: { type: String, default: "" },
},
emits: ["update:modelValue"],
template: `<input type="checkbox" class="all" :checked="modelValue" :data-indeterminate="indeterminate" @change="$emit('update:modelValue', !modelValue)" />`,
template: `<label class="all" :data-indeterminate="indeterminate"><input type="checkbox" :checked="modelValue" @change="$emit('update:modelValue', !modelValue)" />{{ label }}</label>`,
};
const RBtn = {
props: { ariaLabel: { type: String, default: "" } },
@@ -42,16 +43,12 @@ function toolbar(
describe("AssetSelectionToolbar", () => {
it("counts the list until something is checked, then the selection", () => {
expect(toolbar().get(".r-v2-asset-select__status").text()).toBe(
"rom.assets-count-n:3",
);
expect(toolbar().get(".all").text()).toBe("rom.assets-count-n:3");
expect(toolbar().findAll(".btn")).toHaveLength(0);
const some = toolbar({ count: 2, someChecked: true });
expect(some.get(".r-v2-asset-select__status").text()).toBe(
"rom.assets-selected-of",
);
expect(some.get(".all").text()).toBe("rom.assets-selected-of");
expect(some.findAll(".btn").map((b) => b.attributes("aria-label"))).toEqual(
[
"rom.add-to-favorites",
@@ -87,7 +84,7 @@ describe("AssetSelectionToolbar", () => {
const wrapper = toolbar({ count: 1, someChecked: true });
const buttons = wrapper.findAll(".btn");
await wrapper.get(".all").trigger("change");
await wrapper.get(".all input").trigger("change");
await buttons[0].trigger("click");
await buttons[1].trigger("click");
await buttons[2].trigger("click");

View File

@@ -28,24 +28,19 @@ const { t } = useI18n();
<template>
<div class="r-v2-asset-select" v-bind="$attrs">
<label class="r-v2-asset-select__all">
<RCheckbox
:model-value="allChecked"
:indeterminate="someChecked"
size="sm"
hide-details
:aria-label="t('rom.select-all-assets')"
@update:model-value="emit('toggleAll')"
/>
<span class="r-v2-asset-select__status">
<template v-if="count > 0">
{{ t("rom.assets-selected-of", { selected: count, total }) }}
</template>
<template v-else>
{{ t("rom.assets-count-n", total, { named: { n: total } }) }}
</template>
</span>
</label>
<RCheckbox
class="r-v2-asset-select__all"
:model-value="allChecked"
:indeterminate="someChecked"
size="sm"
hide-details
:label="
count > 0
? t('rom.assets-selected-of', { selected: count, total })
: t('rom.assets-count-n', total, { named: { n: total } })
"
@update:model-value="emit('toggleAll')"
/>
<div v-if="count > 0" class="r-v2-asset-select__actions">
<RBtn
@@ -105,16 +100,8 @@ const { t } = useI18n();
min-height: 36px;
}
.r-v2-asset-select__all {
display: flex;
align-items: center;
gap: 8px;
font-size: 12px;
color: var(--r-color-fg-muted);
cursor: pointer;
user-select: none;
}
.r-v2-asset-select__status {
font-weight: var(--r-font-weight-medium);
}
.r-v2-asset-select__actions {
display: flex;

View File

@@ -55,6 +55,7 @@ import SubtabNav, {
import { useBreakpoint } from "@/v2/composables/useBreakpoint";
import { useCan } from "@/v2/composables/useCan";
import { useConfirm } from "@/v2/composables/useConfirm";
import { useIdSelection } from "@/v2/composables/useIdSelection";
import { useIsAlive } from "@/v2/composables/useIsAlive";
import { useRomFileUpload } from "@/v2/composables/useRomFileUpload";
import { useRomSync } from "@/v2/composables/useRomSync";
@@ -338,64 +339,26 @@ const filteredFiles = computed<RomFileSchema[]>(() => {
});
// ---------- Selection ----------
const selectedIds = ref<Set<number>>(new Set());
// Destructured so the template sees plain refs; a nested one is not unwrapped.
const {
selected: selectedFiles,
count: selectedCount,
allSelected: visibleAllSelected,
someSelected: visibleSomeSelected,
isSelected,
toggle: toggleFile,
toggleAll: toggleVisible,
clear: clearSelection,
} = useIdSelection(() => filteredFiles.value);
// Reset selection whenever the active subtab or the rom changes —
// keeping selections across categories would let the user "Download
// selected" with files invisible to them, which is surprising.
watch([subTab, () => props.rom.id], () => {
selectedIds.value = new Set();
});
const selectedCount = computed(() => {
// Only count selections that are still in the filtered view —
// protects against stale ids if the underlying rom file list
// changes mid-selection (uploads, deletions in other tabs).
let n = 0;
for (const f of filteredFiles.value) if (selectedIds.value.has(f.id)) n++;
return n;
});
watch([subTab, () => props.rom.id], clearSelection);
const filteredCount = computed(() => filteredFiles.value.length);
const showUpload = computed(() => filteredCount.value > 0 && canUpload.value);
const visibleAllSelected = computed(
() => filteredCount.value > 0 && selectedCount.value === filteredCount.value,
);
const visibleSomeSelected = computed(
() => selectedCount.value > 0 && !visibleAllSelected.value,
);
function isSelected(file: RomFileSchema): boolean {
return selectedIds.value.has(file.id);
}
function toggleFile(file: RomFileSchema) {
const next = new Set(selectedIds.value);
if (next.has(file.id)) next.delete(file.id);
else next.add(file.id);
selectedIds.value = next;
}
function toggleVisible() {
const next = new Set(selectedIds.value);
if (visibleAllSelected.value) {
for (const f of filteredFiles.value) next.delete(f.id);
} else {
for (const f of filteredFiles.value) next.add(f.id);
}
selectedIds.value = next;
}
function clearSelection() {
selectedIds.value = new Set();
}
const selectedFiles = computed<RomFileSchema[]>(() =>
filteredFiles.value.filter((f) => selectedIds.value.has(f.id)),
);
// ---------- Clipboard helper ----------
// Used by the per-subtab + per-selection copy-link buttons; per-file
// hash copying lives in HashChip itself.
@@ -709,12 +672,12 @@ async function refreshRom() {
:file="file"
:display-path="displayPath(file)"
:relative-path="relativePath(file)"
:selected="isSelected(file)"
:selected="isSelected(file.id)"
:show-row-icon="subTab === 'all'"
:show-category-badge="subTab === 'all'"
:can-delete="canDelete"
:missing="rom.missing_from_fs"
@toggle="toggleFile(file)"
@toggle="toggleFile(file.id)"
@download="downloadFile(file)"
@copy-link="copyFileLink(file)"
@delete="deleteFiles([file])"

View File

@@ -40,6 +40,7 @@ import AssetList from "@/v2/components/shared/AssetList.vue";
import AssetStrip from "@/v2/components/shared/AssetStrip.vue";
import { useBreakpoint } from "@/v2/composables/useBreakpoint";
import { useConfirm } from "@/v2/composables/useConfirm";
import { useIdSelection } from "@/v2/composables/useIdSelection";
import { useRomSync } from "@/v2/composables/useRomSync";
import { useSnackbar } from "@/v2/composables/useSnackbar";
import { useSubtabQuery } from "@/v2/composables/useSubtabQuery";
@@ -331,53 +332,22 @@ async function toggleStateVisibility(state: StateSchema) {
// ---------- Bulk selection (own items only) ----------
// A save and a state can share an id and both panels stay mounted, so each
// kind keeps its own set rather than one keyed by id alone.
const checkedSaves = ref<Set<number>>(new Set());
const checkedStates = ref<Set<number>>(new Set());
// kind gets its own selection rather than one keyed by id alone.
const saveSelection = useIdSelection(() => mySaves.value);
const stateSelection = useIdSelection(() => myStates.value);
function checkedSetFor(type: AssetType) {
return type === "save" ? checkedSaves : checkedStates;
}
// Only count what is still on screen, so an upload or a delete elsewhere
// cannot leave a stale id inflating the total.
const checkedSaveList = computed(() =>
mySaves.value.filter((s) => checkedSaves.value.has(s.id)),
);
const checkedStateList = computed(() =>
myStates.value.filter((s) => checkedStates.value.has(s.id)),
);
function toggleChecked(type: AssetType, asset: AssetSlot) {
const set = checkedSetFor(type);
const next = new Set(set.value);
if (next.has(asset.id)) next.delete(asset.id);
else next.add(asset.id);
set.value = next;
}
function toggleAllChecked(type: AssetType) {
const set = checkedSetFor(type);
const all = type === "save" ? mySaves.value : myStates.value;
const checked =
type === "save" ? checkedSaveList.value : checkedStateList.value;
set.value =
checked.length === all.length ? new Set() : new Set(all.map((a) => a.id));
}
function clearChecked(type: AssetType) {
checkedSetFor(type).value = new Set();
function selectionFor(type: AssetType) {
return type === "save" ? saveSelection : stateSelection;
}
// A selection only makes sense against the list it was made on.
watch([subTab, () => props.rom.id], () => {
checkedSaves.value = new Set();
checkedStates.value = new Set();
saveSelection.clear();
stateSelection.clear();
});
const allCheckedFavorite = (type: AssetType) => {
const assets =
type === "save" ? checkedSaveList.value : checkedStateList.value;
const assets = selectionFor(type).selected.value;
return assets.length > 0 && assets.every((a) => a.is_favorite);
};
@@ -404,8 +374,7 @@ async function reportBulk(
}
async function toggleCheckedFavorite(type: AssetType) {
const assets =
type === "save" ? checkedSaveList.value : checkedStateList.value;
const assets = selectionFor(type).selected.value;
if (assets.length === 0) return;
const isFavorite = !allCheckedFavorite(type);
@@ -424,8 +393,7 @@ async function toggleCheckedFavorite(type: AssetType) {
}
async function deleteChecked(type: AssetType) {
const assets =
type === "save" ? checkedSaveList.value : checkedStateList.value;
const assets = selectionFor(type).selected.value;
if (assets.length === 0) return;
const ok = await confirm({
@@ -440,7 +408,7 @@ async function deleteChecked(type: AssetType) {
});
if (!ok) return;
clearChecked(type);
selectionFor(type).clear();
try {
if (type === "save") {
await saveApi.deleteSaves({ saves: assets as SaveSchema[] });
@@ -518,8 +486,7 @@ async function submitLabels(labels: string[]) {
await refreshRom();
snackbar.success(t("rom.labels-updated"), { icon: "mdi-check-bold" });
} else {
const assets =
target.type === "save" ? checkedSaveList.value : checkedStateList.value;
const assets = selectionFor(target.type).selected.value;
const results = await Promise.allSettled(
assets.map((asset) =>
writeLabels(target.type, asset.id, [
@@ -632,21 +599,16 @@ const labelSuggestions = computed(() =>
>
<AssetSelectionToolbar
v-if="mySaves.length > 0"
:count="checkedSaveList.length"
:count="saveSelection.count.value"
:total="mySaves.length"
:all-checked="
mySaves.length > 0 && checkedSaveList.length === mySaves.length
"
:some-checked="
checkedSaveList.length > 0 &&
checkedSaveList.length < mySaves.length
"
:all-checked="saveSelection.allSelected.value"
:some-checked="saveSelection.someSelected.value"
:all-favorite="allCheckedFavorite('save')"
@toggle-all="toggleAllChecked('save')"
@toggle-all="saveSelection.toggleAll()"
@toggle-favorite="toggleCheckedFavorite('save')"
@edit-labels="labelTarget = { kind: 'many', type: 'save' }"
@delete="deleteChecked('save')"
@clear="clearChecked('save')"
@clear="saveSelection.clear()"
/>
<AssetList
:assets="mySaves"
@@ -654,8 +616,8 @@ const labelSuggestions = computed(() =>
:selectable="false"
:scrollable="false"
checkable
:checked-ids="checkedSaves"
@toggle="toggleChecked('save', $event)"
:checked-ids="saveSelection.selectedIds.value"
@toggle="saveSelection.toggle($event.id)"
>
<template #actions="{ asset }">
<AssetActions
@@ -749,32 +711,26 @@ const labelSuggestions = computed(() =>
>
<AssetSelectionToolbar
v-if="myStates.length > 0"
:count="checkedStateList.length"
:count="stateSelection.count.value"
:total="myStates.length"
:all-checked="
myStates.length > 0 &&
checkedStateList.length === myStates.length
"
:some-checked="
checkedStateList.length > 0 &&
checkedStateList.length < myStates.length
"
:all-checked="stateSelection.allSelected.value"
:some-checked="stateSelection.someSelected.value"
:all-favorite="allCheckedFavorite('state')"
@toggle-all="toggleAllChecked('state')"
@toggle-all="stateSelection.toggleAll()"
@toggle-favorite="toggleCheckedFavorite('state')"
@edit-labels="labelTarget = { kind: 'many', type: 'state' }"
@delete="deleteChecked('state')"
@clear="clearChecked('state')"
@clear="stateSelection.clear()"
/>
<AssetStrip
:assets="myStates"
type="state"
:selectable="false"
checkable
:checked-ids="checkedStates"
:checked-ids="stateSelection.selectedIds.value"
layout="flow"
group-by="emulator"
@toggle="toggleChecked('state', $event)"
@toggle="stateSelection.toggle($event.id)"
>
<template #actions="{ asset }">
<AssetActions

View File

@@ -0,0 +1,91 @@
import { describe, expect, it } from "vitest";
import { ref } from "vue";
import { useIdSelection } from "./index";
interface Row {
id: number;
}
const rows = (...ids: number[]): Row[] => ids.map((id) => ({ id }));
describe("useIdSelection", () => {
it("toggles one id at a time", () => {
const s = useIdSelection(() => rows(1, 2, 3));
s.toggle(2);
expect(s.isSelected(2)).toBe(true);
expect(s.selected.value).toEqual([{ id: 2 }]);
expect(s.count.value).toBe(1);
s.toggle(2);
expect(s.isSelected(2)).toBe(false);
expect(s.count.value).toBe(0);
});
it("replaces the set rather than mutating it, so watchers fire", () => {
const s = useIdSelection(() => rows(1, 2));
const before = s.selectedIds.value;
s.toggle(1);
expect(s.selectedIds.value).not.toBe(before);
expect(before.has(1)).toBe(false);
});
it("reports all and some against the live list", () => {
const s = useIdSelection(() => rows(1, 2));
expect(s.allSelected.value).toBe(false);
expect(s.someSelected.value).toBe(false);
s.toggle(1);
expect(s.someSelected.value).toBe(true);
expect(s.allSelected.value).toBe(false);
s.toggle(2);
expect(s.allSelected.value).toBe(true);
expect(s.someSelected.value).toBe(false);
});
it("treats an empty list as nothing selected", () => {
const s = useIdSelection(() => [] as Row[]);
expect(s.allSelected.value).toBe(false);
expect(s.someSelected.value).toBe(false);
});
it("selects everything, then clears when everything already is", () => {
const s = useIdSelection(() => rows(1, 2, 3));
s.toggleAll();
expect(s.count.value).toBe(3);
s.toggleAll();
expect(s.count.value).toBe(0);
});
it("ignores ids that have left the list", () => {
const items = ref<Row[]>(rows(1, 2));
const s = useIdSelection(() => items.value);
s.toggleAll();
expect(s.count.value).toBe(2);
// The row is deleted elsewhere; its stale id must not inflate the count.
items.value = rows(1);
expect(s.count.value).toBe(1);
expect(s.allSelected.value).toBe(true);
expect(s.selected.value).toEqual([{ id: 1 }]);
});
it("takes a custom id accessor", () => {
const s = useIdSelection(
() => [{ fileId: 7 }, { fileId: 9 }],
(item) => item.fileId,
);
s.toggleAll();
expect(s.selected.value).toEqual([{ fileId: 7 }, { fileId: 9 }]);
});
});

View File

@@ -0,0 +1,75 @@
import { computed, ref, type ComputedRef, type Ref } from "vue";
/**
* Checkbox selection over a list of items identified by a numeric id.
*
* The set is cloned on every write: Vue does not track `Set` mutation, so a
* handler that added in place would leave the checkboxes stale.
*/
export interface IdSelection<T> {
/** The raw ids, for passing to a list component. */
selectedIds: Ref<ReadonlySet<number>>;
/** The selected items still present in `items`. */
selected: ComputedRef<T[]>;
count: ComputedRef<number>;
allSelected: ComputedRef<boolean>;
someSelected: ComputedRef<boolean>;
isSelected: (id: number) => boolean;
toggle: (id: number) => void;
/** Checks everything, or clears it when everything already is. */
toggleAll: () => void;
clear: () => void;
}
export function useIdSelection<T>(
items: () => readonly T[],
idOf: (item: T) => number = (item) => (item as { id: number }).id,
): IdSelection<T> {
const selectedIds = ref<ReadonlySet<number>>(new Set<number>());
// Derived from the live list rather than the set's own size, so an id left
// behind by a delete or a refresh elsewhere cannot inflate the count.
const selected = computed(() =>
items().filter((item) => selectedIds.value.has(idOf(item))),
);
const count = computed(() => selected.value.length);
const allSelected = computed(
() => items().length > 0 && count.value === items().length,
);
const someSelected = computed(
() => count.value > 0 && count.value < items().length,
);
function isSelected(id: number): boolean {
return selectedIds.value.has(id);
}
function toggle(id: number): void {
const next = new Set(selectedIds.value);
if (next.has(id)) next.delete(id);
else next.add(id);
selectedIds.value = next;
}
function toggleAll(): void {
selectedIds.value = allSelected.value
? new Set<number>()
: new Set(items().map(idOf));
}
function clear(): void {
selectedIds.value = new Set<number>();
}
return {
selectedIds,
selected,
count,
allSelected,
someSelected,
isSelected,
toggle,
toggleAll,
clear,
};
}