Files
Oxicloud/frontend/src/lib/composables/useSelection.svelte.ts
T

64 lines
1.4 KiB
TypeScript
Raw Normal View History

import { SvelteSet } from 'svelte/reactivity';
2026-06-17 22:30:56 -06:00
/**
* Reactive multi-select over string ids. Backs the repeated
* `let selected = $state(new Set()); function toggle(id) { … }` pattern used by
* the photos grid, music picker and other list views with one source of truth.
*
* Backed by a reactive {@link SvelteSet}, so in-place mutations (`add`/`delete`)
* drive `$derived`/template reads without copying the set.
2026-06-17 22:30:56 -06:00
*/
export class Selection {
#ids = new SvelteSet<string>();
2026-06-17 22:30:56 -06:00
/** The live selection set (read-only intent — mutate via the methods). */
get ids(): SvelteSet<string> {
2026-06-17 22:30:56 -06:00
return this.#ids;
}
get size(): number {
return this.#ids.size;
}
get isEmpty(): boolean {
return this.#ids.size === 0;
}
has(id: string): boolean {
return this.#ids.has(id);
}
/** Selected ids as an array (e.g. for batch API calls). */
values(): string[] {
return [...this.#ids];
}
toggle(id: string): void {
if (this.#ids.has(id)) this.#ids.delete(id);
else this.#ids.add(id);
2026-06-17 22:30:56 -06:00
}
add(id: string): void {
this.#ids.add(id);
2026-06-17 22:30:56 -06:00
}
delete(id: string): void {
this.#ids.delete(id);
2026-06-17 22:30:56 -06:00
}
/** Replace the whole selection. */
set(ids: Iterable<string>): void {
this.#ids.clear();
for (const id of ids) this.#ids.add(id);
2026-06-17 22:30:56 -06:00
}
clear(): void {
this.#ids.clear();
2026-06-17 22:30:56 -06:00
}
}
/** Create a reactive {@link Selection}. */
export function useSelection(): Selection {
return new Selection();
}