-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseFilterState.ts
More file actions
402 lines (344 loc) · 12.9 KB
/
useFilterState.ts
File metadata and controls
402 lines (344 loc) · 12.9 KB
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
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
/**
* Hook for managing filter state and URL synchronization.
*
* Uses persistent state from Layout context to survive navigation.
*/
import { useState, useCallback, useEffect, useRef } from 'react';
import type { PlotImage, FilterCategory, ActiveFilters, FilterCounts } from '../types';
import { FILTER_CATEGORIES } from '../types';
import { API_URL, BATCH_SIZE } from '../constants';
import { useHomeState } from '../components/Layout';
/**
* Seeded random number generator (mulberry32).
*/
function seededRandom(seed: number): () => number {
return () => {
let t = (seed += 0x6d2b79f5);
t = Math.imul(t ^ (t >>> 15), t | 1);
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
/**
* Fisher-Yates shuffle algorithm with optional seed for deterministic results.
*/
function shuffleArray<T>(array: T[], seed?: number): T[] {
const shuffled = [...array];
const random = seed !== undefined ? seededRandom(seed) : Math.random;
for (let i = shuffled.length - 1; i > 0; i--) {
const j = Math.floor(random() * (i + 1));
[shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
}
return shuffled;
}
/**
* Generate a hash from filter state for deterministic shuffle.
*/
function hashFilters(filters: ActiveFilters): number {
const str = JSON.stringify(filters);
let hash = 0;
for (let i = 0; i < str.length; i++) {
const char = str.charCodeAt(i);
hash = (hash << 5) - hash + char;
hash = hash & hash;
}
return Math.abs(hash);
}
/**
* Parse URL params into ActiveFilters.
* URL format: ?lib=matplotlib&lib=seaborn (AND) or ?lib=matplotlib,seaborn (OR within group)
*/
function parseUrlFilters(): ActiveFilters {
const params = new URLSearchParams(window.location.search);
const filters: ActiveFilters = [];
FILTER_CATEGORIES.forEach((category) => {
const allValues = params.getAll(category);
allValues.forEach((value) => {
if (value) {
const values = value
.split(',')
.map((v) => v.trim())
.filter(Boolean);
if (values.length > 0) {
filters.push({ category, values });
}
}
});
});
return filters;
}
/**
* Build URL from ActiveFilters.
*/
function buildFilterUrl(filters: ActiveFilters): string {
const params = new URLSearchParams();
filters.forEach(({ category, values }) => {
if (values.length > 0) {
params.append(category, values.join(','));
}
});
const queryString = params.toString();
return queryString ? `?${queryString}` : '/';
}
/**
* Check if filters are empty.
*/
export function isFiltersEmpty(filters: ActiveFilters): boolean {
return filters.length === 0 || filters.every((f) => f.values.length === 0);
}
interface UseFilterStateOptions {
onTrackPageview: () => void;
onTrackEvent: (event: string, props?: Record<string, string>) => void;
}
interface UseFilterStateReturn {
// State
activeFilters: ActiveFilters;
filterCounts: FilterCounts | null;
globalCounts: FilterCounts | null;
orCounts: Record<string, number>[];
allImages: PlotImage[];
displayedImages: PlotImage[];
hasMore: boolean;
loading: boolean;
error: string;
// Setters for external state
setDisplayedImages: React.Dispatch<React.SetStateAction<PlotImage[]>>;
setHasMore: React.Dispatch<React.SetStateAction<boolean>>;
setError: React.Dispatch<React.SetStateAction<string>>;
// Callbacks
handleAddFilter: (category: FilterCategory, value: string) => void;
handleAddValueToGroup: (groupIndex: number, value: string) => void;
handleRemoveFilter: (groupIndex: number, value: string) => void;
handleRemoveGroup: (groupIndex: number) => void;
handleRandom: (method?: 'click' | 'space' | 'doubletap') => void;
// Animation state for random
randomAnimation: { index: number; phase: 'out' | 'in'; oldLabel?: string } | null;
}
export function useFilterState({
onTrackPageview,
onTrackEvent,
}: UseFilterStateOptions): UseFilterStateReturn {
const { homeStateRef, setHomeState } = useHomeState();
// Initialize from persistent state (ref) or URL params (all using lazy initializers)
const [activeFilters, setActiveFilters] = useState<ActiveFilters>(() =>
homeStateRef.current.initialized ? homeStateRef.current.activeFilters : parseUrlFilters()
);
const [filterCounts, setFilterCounts] = useState<FilterCounts | null>(() =>
homeStateRef.current.initialized ? homeStateRef.current.filterCounts : null
);
const [globalCounts, setGlobalCounts] = useState<FilterCounts | null>(() =>
homeStateRef.current.initialized ? homeStateRef.current.globalCounts : null
);
const [orCounts, setOrCounts] = useState<Record<string, number>[]>(() =>
homeStateRef.current.initialized ? homeStateRef.current.orCounts : []
);
// Image state - restore from persistent state if available
const [allImages, setAllImages] = useState<PlotImage[]>(() =>
homeStateRef.current.initialized ? homeStateRef.current.allImages : []
);
const [displayedImages, setDisplayedImages] = useState<PlotImage[]>(() =>
homeStateRef.current.initialized ? homeStateRef.current.displayedImages : []
);
const [hasMore, setHasMore] = useState(() =>
homeStateRef.current.initialized ? homeStateRef.current.hasMore : false
);
// UI state
const [loading, setLoading] = useState(() => !homeStateRef.current.initialized);
const [error, setError] = useState<string>('');
const [randomAnimation, setRandomAnimation] = useState<{
index: number;
phase: 'out' | 'in';
oldLabel?: string;
} | null>(null);
// Refs for stable callbacks
const activeFiltersRef = useRef(activeFilters);
activeFiltersRef.current = activeFilters;
// Sync state changes back to persistent context
useEffect(() => {
if (allImages.length > 0 || displayedImages.length > 0) {
setHomeState((prev) => ({
...prev,
allImages,
displayedImages,
activeFilters,
filterCounts,
globalCounts,
orCounts,
hasMore,
initialized: true,
}));
}
}, [allImages, displayedImages, activeFilters, filterCounts, globalCounts, orCounts, hasMore, setHomeState]);
// Add a new filter group (creates new chip - AND with other groups)
const handleAddFilter = useCallback((category: FilterCategory, value: string) => {
setActiveFilters((prev) => [...prev, { category, values: [value] }]);
}, []);
// Add value to existing group by index (OR within that group)
const handleAddValueToGroup = useCallback((groupIndex: number, value: string) => {
setActiveFilters((prev) => {
const newFilters = [...prev];
const group = newFilters[groupIndex];
if (group && !group.values.includes(value)) {
newFilters[groupIndex] = { ...group, values: [...group.values, value] };
}
return newFilters;
});
}, []);
// Remove a filter value from a specific group
const handleRemoveFilter = useCallback((groupIndex: number, value: string) => {
const group = activeFiltersRef.current[groupIndex];
if (group) {
onTrackEvent('filter_remove', { category: group.category, value });
}
setActiveFilters((prev) => {
const newFilters = [...prev];
const grp = newFilters[groupIndex];
if (!grp) return prev;
const updatedValues = grp.values.filter((v) => v !== value);
if (updatedValues.length === 0) {
return newFilters.filter((_, i) => i !== groupIndex);
}
newFilters[groupIndex] = { ...grp, values: updatedValues };
return newFilters;
});
}, [onTrackEvent]);
// Remove entire group by index
const handleRemoveGroup = useCallback((groupIndex: number) => {
const group = activeFiltersRef.current[groupIndex];
if (group) {
onTrackEvent('filter_remove', { category: group.category, value: group.values.join(',') });
}
setActiveFilters((prev) => prev.filter((_, i) => i !== groupIndex));
}, [onTrackEvent]);
// Random filter - replaces last filter slot (or adds first one)
const handleRandom = useCallback(
(method: 'click' | 'space' | 'doubletap' = 'click') => {
const currentFilters = activeFiltersRef.current;
// Use contextual counts if filters exist, otherwise global
const countsToUse = currentFilters.length > 0 ? filterCounts : globalCounts;
if (!countsToUse) return;
const availableCategories = FILTER_CATEGORIES.filter((cat) => {
const counts = countsToUse[cat];
return counts && Object.keys(counts).length > 0;
});
if (availableCategories.length === 0) return;
const randomCategory =
availableCategories[Math.floor(Math.random() * availableCategories.length)];
const values = Object.keys(countsToUse[randomCategory]);
if (values.length === 0) return;
const randomValue = values[Math.floor(Math.random() * values.length)];
const newFilter = { category: randomCategory, values: [randomValue] };
// Get old label before changing
const newIndex = currentFilters.length === 0 ? 0 : currentFilters.length - 1;
const oldGroup = currentFilters[newIndex];
const oldLabel = oldGroup ? `${oldGroup.category}:${oldGroup.values.join(',')}` : '';
// Start animation with old label, change filter immediately (so images load)
setRandomAnimation({ index: newIndex, phase: 'out', oldLabel });
setActiveFilters((prev) => {
if (prev.length === 0) {
return [newFilter];
}
return [...prev.slice(0, -1), newFilter];
});
// Switch to 'in' phase at halfway point
setTimeout(() => {
setRandomAnimation({ index: newIndex, phase: 'in' });
}, 500);
// Clear animation state
setTimeout(() => setRandomAnimation(null), 1000);
onTrackEvent('random', { category: randomCategory, value: randomValue, method });
},
[filterCounts, globalCounts, onTrackEvent]
);
// Update URL when filters change
useEffect(() => {
const newUrl = buildFilterUrl(activeFilters);
window.history.replaceState({}, '', newUrl);
// Update document title
const filterParts = activeFilters
.filter((f) => f.values.length > 0)
.map((f) => `${f.category}:${f.values.join(',')}`)
.join(' ');
document.title = filterParts ? `${filterParts} | pyplots.ai` : 'pyplots.ai';
onTrackPageview();
}, [activeFilters, onTrackPageview]);
// Track if we should skip initial fetch (restored from persistent state)
const initializedRef = useRef(homeStateRef.current.initialized);
const filtersMatchRef = useRef(
homeStateRef.current.initialized && JSON.stringify(homeStateRef.current.activeFilters) === JSON.stringify(activeFilters)
);
// Load filtered images when filters change
useEffect(() => {
// Skip fetch on first mount if restored from persistent state with same filters
if (initializedRef.current && filtersMatchRef.current) {
initializedRef.current = false;
filtersMatchRef.current = false;
return;
}
initializedRef.current = false;
filtersMatchRef.current = false;
const abortController = new AbortController();
const fetchFilteredImages = async () => {
setLoading(true);
try {
// Build query string from filters
const params = new URLSearchParams();
activeFilters.forEach(({ category, values }) => {
if (values.length > 0) {
params.append(category, values.join(','));
}
});
const queryString = params.toString();
const url = `${API_URL}/plots/filter${queryString ? `?${queryString}` : ''}`;
const response = await fetch(url, { signal: abortController.signal });
if (!response.ok) throw new Error('Failed to fetch filtered plots');
const data = await response.json();
if (abortController.signal.aborted) return;
// Update filter counts
setFilterCounts(data.counts);
setGlobalCounts(data.globalCounts || data.counts);
setOrCounts(data.orCounts || []);
// Shuffle with deterministic seed based on filters
const seed = hashFilters(activeFilters);
const shuffled = shuffleArray<PlotImage>(data.images || [], seed);
setAllImages(shuffled);
// Initial display count
setDisplayedImages(shuffled.slice(0, BATCH_SIZE));
setHasMore(shuffled.length > BATCH_SIZE);
} catch (err) {
if (abortController.signal.aborted) return;
setError(`Error loading images: ${err}`);
} finally {
if (!abortController.signal.aborted) {
setLoading(false);
}
}
};
fetchFilteredImages();
return () => abortController.abort();
}, [activeFilters]);
return {
// State
activeFilters,
filterCounts,
globalCounts,
orCounts,
allImages,
displayedImages,
hasMore,
loading,
error,
// Setters
setDisplayedImages,
setHasMore,
setError,
// Callbacks
handleAddFilter,
handleAddValueToGroup,
handleRemoveFilter,
handleRemoveGroup,
handleRandom,
// Animation
randomAnimation,
};
}