diff --git a/src/shared/lib/helpers/createFilter/createFilter.svelte.ts b/src/shared/lib/helpers/createFilter/createFilter.svelte.ts index b48521d..193a58f 100644 --- a/src/shared/lib/helpers/createFilter/createFilter.svelte.ts +++ b/src/shared/lib/helpers/createFilter/createFilter.svelte.ts @@ -26,84 +26,52 @@ export interface FilterModel { /** * Create a filter store. - * @param initialState - Initial state of the filter store + * @param initialState - Initial state of filter store */ -export function createFilter( - initialState: FilterModel, -) { - let properties = $state( +export function createFilter(initialState: FilterModel) { + // We map the initial properties into a reactive state array + const properties = $state( initialState.properties.map(p => ({ ...p, selected: p.selected ?? false, })), ); - const selectedProperties = $derived(properties.filter(p => p.selected)); - const selectedCount = $derived(selectedProperties.length); - return { - /** - * Get all properties. - */ get properties() { return properties; }, - /** - * Get selected properties. - */ + get selectedProperties() { - return selectedProperties; + return properties.filter(p => p.selected); }, - /** - * Get selected count. - */ + get selectedCount() { - return selectedCount; + return this.selectedProperties.length; }, - /** - * Toggle property selection. - */ - toggleProperty: (id: string) => { - properties = properties.map(p => ({ - ...p, - selected: p.id === id ? !p.selected : p.selected, - })); + + // 3. Methods mutate the reactive state directly + toggleProperty(id: string) { + const prop = properties.find(p => p.id === id); + if (prop) prop.selected = !prop.selected; }, - /** - * Select property. - */ + selectProperty(id: string) { - properties = properties.map(p => ({ - ...p, - selected: p.id === id ? true : p.selected, - })); + const prop = properties.find(p => p.id === id); + if (prop) prop.selected = true; }, - /** - * Deselect property. - */ + deselectProperty(id: string) { - properties = properties.map(p => ({ - ...p, - selected: p.id === id ? false : p.selected, - })); + const prop = properties.find(p => p.id === id); + if (prop) prop.selected = false; }, - /** - * Select all properties. - */ - selectAll: () => { - properties = properties.map(p => ({ - ...p, - selected: true, - })); + + selectAll() { + properties.forEach(p => p.selected = true); }, - /** - * Deselect all properties. - */ - deselectAll: () => { - properties = properties.map(p => ({ - ...p, - selected: false, - })); + + deselectAll() { + properties.forEach(p => p.selected = false); }, }; }