2026-06-21 19:03:07 +02:00
|
|
|
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.
|
|
|
|
|
*
|
2026-06-21 19:03:07 +02:00
|
|
|
* 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 {
|
2026-06-21 19:03:07 +02:00
|
|
|
#ids = new SvelteSet<string>();
|
2026-06-17 22:30:56 -06:00
|
|
|
|
|
|
|
|
/** The live selection set (read-only intent — mutate via the methods). */
|
2026-06-21 19:03:07 +02:00
|
|
|
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 {
|
2026-06-21 19:03:07 +02:00
|
|
|
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 {
|
2026-06-21 19:03:07 +02:00
|
|
|
this.#ids.add(id);
|
2026-06-17 22:30:56 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
delete(id: string): void {
|
2026-06-21 19:03:07 +02:00
|
|
|
this.#ids.delete(id);
|
2026-06-17 22:30:56 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/** Replace the whole selection. */
|
|
|
|
|
set(ids: Iterable<string>): void {
|
2026-06-21 19:03:07 +02:00
|
|
|
this.#ids.clear();
|
|
|
|
|
for (const id of ids) this.#ids.add(id);
|
2026-06-17 22:30:56 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
clear(): void {
|
2026-06-21 19:03:07 +02:00
|
|
|
this.#ids.clear();
|
2026-06-17 22:30:56 -06:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/** Create a reactive {@link Selection}. */
|
|
|
|
|
export function useSelection(): Selection {
|
|
|
|
|
return new Selection();
|
|
|
|
|
}
|