๐Ÿ“ฆ directus / website

๐Ÿ“„ useDirectory.ts ยท 176 lines
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176import { ref, computed, watch } from 'vue';
import Fuse from 'fuse.js';

interface DirectoryItem {
	[key: string]: any;
}

interface FacetOption {
	value: string;
	count: number;
}

interface FieldMapping {
	[key: string]: string | any;
}

interface UseDirectoryOptions {
	items: DirectoryItem[];
	searchFields: string[];
	facetFields: string[];
	fieldMapping?: FieldMapping | undefined;
	groupBy?: string;
}

export function useDirectory({ items, searchFields, facetFields, fieldMapping = {}, groupBy }: UseDirectoryOptions) {
	const route = useRoute();
	const router = useRouter();
	const searchQuery = ref('');
	const selectedFacets = ref<Record<string, string[]>>(Object.fromEntries(facetFields.map((field) => [field, []])));

	const fuse = new Fuse(items, {
		keys: searchFields,
		threshold: 0.3,
	});

	// Helpers for syncing state with URL
	const updateURL = () => {
		const query: Record<string, string> = {};

		if (searchQuery.value) {
			query.q = searchQuery.value;
		}

		Object.entries(selectedFacets.value).forEach(([field, values]) => {
			if (values.length > 0) {
				query[field] = values.join(',');
			}
		});

		router.replace({ query });
	};

	const readFromURL = () => {
		const { q, ...facetParams } = route.query;
		searchQuery.value = (q as string) || '';

		Object.keys(selectedFacets.value).forEach((field) => {
			const param = facetParams[field] as string | undefined;
			selectedFacets.value[field] = param ? param.split(',') : [];
		});
	};

	readFromURL();
	watch([searchQuery, selectedFacets], updateURL, { deep: true });

	const facets = computed(() => {
		return facetFields.map((field) => {
			const options = items.reduce(
				(acc, item) => {
					const values = Array.isArray(item[field]) ? item[field] : [item[field]];

					values.forEach((value: any) => {
						if (value) {
							if (!acc[value]) {
								acc[value] = { value, count: 0 };
							}

							acc[value].count++;
						}
					});

					return acc;
				},
				{} as Record<string, FacetOption>,
			);

			return {
				field,
				options: Object.values(options).sort((a, b) => b.count - a.count),
			};
		});
	});

	const filterItemsByFacets = (items: DirectoryItem[]) => {
		return items.filter((item) => {
			return Object.entries(selectedFacets.value).every(([field, values]) => {
				if (values.length === 0) return true;
				const itemValues = Array.isArray(item[field]) ? item[field] : [item[field]];
				return itemValues.some((v: any) => values.includes(v));
			});
		});
	};

	const applyFieldMapping = (item: DirectoryItem) => {
		return Object.entries(fieldMapping).reduce((mappedItem, [uiProp, sourceField]) => {
			if (typeof sourceField === 'function') {
				mappedItem[uiProp] = sourceField(item);
			} else {
				mappedItem[uiProp] = item[sourceField];
			}

			return mappedItem;
		}, {} as DirectoryItem);
	};

	const groupItems = (items: DirectoryItem[]) => {
		if (!groupBy) return items;

		return items.reduce(
			(acc, item) => {
				const groupValue = item[groupBy];

				if (!acc[groupValue]) {
					acc[groupValue] = [];
				}

				acc[groupValue].push(item);
				return acc;
			},
			{} as Record<string, DirectoryItem[]>,
		);
	};

	const filteredItems = computed(() => {
		let result = items;
		result = filterItemsByFacets(result);

		if (searchQuery.value) {
			result = fuse.search(searchQuery.value).map((res) => res.item);
		}

		const mappedResult = result.map(applyFieldMapping);
		return groupBy ? groupItems(mappedResult) : mappedResult;
	});

	const isFilterActive = computed(() => {
		return searchQuery.value || facetFields.some((field) => selectedFacets.value[field].length > 0);
	});

	const updateFacet = (field: string, value: string, isSelected: boolean) => {
		if (isSelected) {
			selectedFacets.value[field].push(value);
		} else {
			selectedFacets.value[field] = selectedFacets.value[field].filter((v) => v !== value);
		}
	};

	const clearFilters = () => {
		searchQuery.value = '';

		Object.keys(selectedFacets.value).forEach((field) => {
			selectedFacets.value[field] = [];
		});
	};

	return {
		searchQuery,
		selectedFacets,
		facets,
		filteredItems,
		updateFacet,
		clearFilters,
		isFilterActive,
	};
}