refactor(createFilter): createFilterStore rewrote to runes
This commit is contained in:
111
src/shared/lib/helpers/createFilter/createFilter.svelte.ts
Normal file
111
src/shared/lib/helpers/createFilter/createFilter.svelte.ts
Normal file
@@ -0,0 +1,111 @@
|
||||
export interface Property {
|
||||
/**
|
||||
* Property identifier
|
||||
*/
|
||||
id: string;
|
||||
/**
|
||||
* Property name
|
||||
*/
|
||||
name: string;
|
||||
/**
|
||||
* Property selected state
|
||||
*/
|
||||
selected?: boolean;
|
||||
}
|
||||
|
||||
export interface FilterModel {
|
||||
/**
|
||||
* Search query
|
||||
*/
|
||||
searchQuery?: string;
|
||||
/**
|
||||
* Properties
|
||||
*/
|
||||
properties: Property[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a filter store.
|
||||
* @param initialState - Initial state of the filter store
|
||||
*/
|
||||
export function createFilter<T extends FilterModel>(
|
||||
initialState: T,
|
||||
) {
|
||||
let 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;
|
||||
},
|
||||
/**
|
||||
* Get selected count.
|
||||
*/
|
||||
get selectedCount() {
|
||||
return selectedCount;
|
||||
},
|
||||
/**
|
||||
* Toggle property selection.
|
||||
*/
|
||||
toggleProperty: (id: string) => {
|
||||
properties = properties.map(p => ({
|
||||
...p,
|
||||
selected: p.id === id ? !p.selected : p.selected,
|
||||
}));
|
||||
},
|
||||
/**
|
||||
* Select property.
|
||||
*/
|
||||
selectProperty(id: string) {
|
||||
properties = properties.map(p => ({
|
||||
...p,
|
||||
selected: p.id === id ? true : p.selected,
|
||||
}));
|
||||
},
|
||||
/**
|
||||
* Deselect property.
|
||||
*/
|
||||
deselectProperty(id: string) {
|
||||
properties = properties.map(p => ({
|
||||
...p,
|
||||
selected: p.id === id ? false : p.selected,
|
||||
}));
|
||||
},
|
||||
/**
|
||||
* Select all properties.
|
||||
*/
|
||||
selectAll: () => {
|
||||
properties = properties.map(p => ({
|
||||
...p,
|
||||
selected: true,
|
||||
}));
|
||||
},
|
||||
/**
|
||||
* Deselect all properties.
|
||||
*/
|
||||
deselectAll: () => {
|
||||
properties = properties.map(p => ({
|
||||
...p,
|
||||
selected: false,
|
||||
}));
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export type Filter = ReturnType<typeof createFilter>;
|
||||
Reference in New Issue
Block a user