import type { IChipsItem, IModelFilter, IModelFilterOptions } from '../types'; import type { LocationQuery } from '#vue-router'; import { getMonth } from '../runtime'; import type { Ref } from 'vue'; export function useFilterChipsItems( filters: Ref, route: { query: LocationQuery }, t: (key: string) => string, locale: Ref ) { const chipsItems = computed(() => { const queryItems = Object.keys(route.query) .filter(item => item.startsWith('filter_')) .map(item => item .replace('filter_', '') .replace(/_/g, ' ') ); const groups = Object.values( queryItems.reduce((acc: Record, str: string) => { const parts = str.split(' '); const last = parts.at(-1); const key = last === 'from' || last === 'to' ? parts.slice(0, -1).join(' ') : str; acc[key] ??= []; if (last === 'from') acc[key].unshift(str); else acc[key].push(str); return acc; }, {}) ); const findFilter = (items: string[]) => { const key = items[0].replace(' from', '').replace(' to', ''); return filters.value.find(f => f.name.replace(/_/g, ' ') === key); }; const getValue = (item: string, index: number) => { const filter = filters.value.find(filter => filter.name === item .replace(/ /g, '_') .replace('_from', '') .replace('_to', '') ); const defaultValue = index === 0 ? filter?.options[0] : filter?.options.at(-1); const value = route.query[`filter_${item.replace(/ /g, '_')}`]; if (item.includes('month')) { return getMonth( locale.value, Number(value ?? defaultValue?.name) - 1 ); } if (!isNaN(Number(value))) { return value; } return ( filter?.options.find( (option: IModelFilterOptions) => option.name === value )?.title ?? defaultValue?.title ); }; const getValueText = (items: string[]) => [...new Set(items.map(getValue).filter(v => v !== undefined && v !== null && v !== ''))].join(' - '); const chipsTitle = (items: string[], filter: IModelFilter) => { const valueText = getValueText(items); const text = `${filter.title}: ${valueText}`; return text.length > 30 ? valueText : text; }; return groups .map(item => { const filter = findFilter(item); if (!filter) return null; const valueText = getValueText(item); if (!valueText) return null; return { title: chipsTitle(item, filter), value: item.map( sub => `filter_${sub.replace(/ /g, '_')}` ), }; }) .filter((c): c is IChipsItem => c !== null); }); return { chipsItems, }; }