SelectionState
A utility class that manages single or multiple external selection state with methods to query and update the current selection.
Usage
import { SelectionState } from 'svxui';
let value: string[] = $state();
// Initialize the selection state with the value to be managed
// Use accessors (getter and setter) for external updates
// The external value can be an array or a single value
// depending on the multiple option.
let selection = new SelectionState({
get value() {
return value;
},
set value(newValue) {
value = newValue;
},
multiple: true
});
// Manage selection
selection.select(item);
selection.deselect(item);
selection.toggle(item);
selection.has(item);
// Clear selection
selection.clear();
// Get selection count (reactive)
selection.count;
Type Definition
SelectionState
export declare class SelectionState<Value, Multiple extends boolean> {
/** Cleanup function to stop internal reactive effects. */
readonly destroy: () => void;
constructor(options: SelectionStateOptions<Value, Multiple>);
/**
* Current selection value. Reads from external value when controlled.
*/
get value(): SelectionStateValue<Value, Multiple>;
set value(val: SelectionStateValue<Value, Multiple>);
/**
* Whether multiple items can be selected simultaneously
*/
get multiple(): any;
/**
* Number of currently selected items.
*/
get count(): number;
/**
* Returns `true` if the given item is currently selected.
* @param item - The value to check.
*/
has(item: Value): boolean;
/**
* Selects the given item. In multiple mode, appends it if not already selected.
* @param item - The value to select.
*/
select(item: Value): void;
/**
* Deselects the given item. In single mode, clears the selection if it matches.
* @param item - The value to deselect.
*/
deselect(item: Value): void;
/**
* Toggles the selection state of the given item.
* @param item - The value to toggle.
*/
toggle(item: Value): void;
/**
* Resets the selection to empty (undefined in single mode, [] in multiple mode).
*/
clear(): void;
}SelectionStateOptions
/**
* Selection value type depending on single or multiple mode.
*/
export type SelectionStateValue<Value, Multiple extends boolean = true> =
| (Multiple extends true ? Value[] : Value)
| null
| undefined;
/**
* Selection state options including the value state to manage single or multiple selection
*/
export type SelectionStateOptions<Value, Multiple extends boolean> = {
/**
* Current controlled value
*/
value?: SelectionStateValue<Value, Multiple>;
/**
* Can select single or multiple value
*/
multiple?: Multiple;
/**
* Callback called on value change
* @param newValue
*/
onValueChange?: (newValue: SelectionStateValue<Value, Multiple>) => void;
/**
* Determines equality between two values. Defaults to `===`
*/
compare?: (a: Value, b: Value) => boolean;
};