Jake Vanderwerf
2026-01-01 58dccc86754deda247eb49310c266f6cba86d36a
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
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
// index.js - Main entry point for the Feed Block
import ErrorHandling from './services/ErrorHandlingService';
import StateManager from './services/StateManager';
import FeedService from './services/FeedService';
import FavouritesService from './services/FavouritesService';
import FilterService from './services/FilterService';
import FeedGrid from './components/FeedGrid';
import FilterPanel from './components/FilterPanel';
import GalleryModal from './components/GalleryModal';
import LoadingState from './components/LoadingState';
// import TaxonomySelector from './components/TaxonomySelector';
import cache from './utils/cache';
import { debounce } from './utils/formatters';
 
class FeedBlock {
    constructor(container) {
        // Store container reference
        this.container = container;
 
        // Initialize config
        this.initializeConfig();
 
        // Create services and components
        this.initializeServices();
        this.initializeComponents();
        this.initializeErrorHandling();
        this.initializeAccessibility();
 
        // Initialize state from URL
        this.loadStateFromURL();
        // Set up event delegation for efficiency
        this.setupEventDelegation();
        this.loadItems();
 
 
        // Check for highlighted item
        if (this.config.highlight && this.stateManager.getState().page === 1) {
            console.log(this.config.highlight);
            console.log('Opening Highlighted Item');
            this.openGallery();
        }
 
    }
 
    /**
     * Initialize error handling
     */
    initializeErrorHandling() {
        this.errorHandler = new ErrorHandling({
            apiUrl: this.config.apiUrl,
            logToServer: true,
            displayNotifications: true
        });
 
        // Pass error handler to services
        this.feedService.errorHandler = this.errorHandler;
        this.favouritesService.errorHandler = this.errorHandler;
    }
 
    /**
     * Initialize configuration from container data
     */
    initializeConfig() {
        // Get settings from container data attribute
        const settings = JSON.parse(this.container.dataset.settings || '{}');
 
        // Merge with globals
        this.config = {
            apiUrl: window.feedSettings?.apiUrl || '',
            nonce: window.feedSettings?.nonce || '',
            currentUser: window.feedSettings?.currentUser || null,
 
            content: settings.content || 'tattoo',
            contentTypes: settings.contentTypes || ['tattoo'],
            taxonomies: settings.taxonomies || [],
            defaultOrder: settings.defaultOrder || 'date',
            itemsPerPage: settings.itemsPerPage || 12,
 
            // Context information
            context: settings.context || null,
            name: settings.name || '',
            id: settings.id || '',
            inheritQuery: settings.inheritQuery || false,
 
            // Initial terms for taxonomies
            initialTerms: settings.initial_terms || {},
 
            // Source information for analytics
            source: this.container.dataset.source || '',
            sourceType: this.container.dataset.context || '',
 
            // Optional highlight
            highlight: null,
 
            // Gallery mode
            isGallery: settings.isGallery || false,
            showAuthor: true,
            showDate: false,
 
            // Feature flags
            loadMoreTax: settings.loadMoreTax ?? true,
 
            // User preferences
            viewMode: localStorage.getItem('feedViewMode') || 'grid',
        };
 
        // Get highlight from URL if present
        this.config.highlight = this.getHighlightFromURL();
 
        // Adjust config based on context
        if (this.config.context) {
            switch (this.config.context.type) {
                case 'author':
                    this.config.isGallery = true;
                    this.config.showAuthor = false;
                    this.config.showDate = true;
                    break;
            }
        }
    }
 
    /**
     * Initialize services
     */
    initializeServices() {
        // Create state manager
        this.stateManager = new StateManager({
            content: this.config.content,
            defaultOrder: this.config.defaultOrder,
        });
 
        // Create filter service
        this.filterService = new FilterService({
            taxonomyMap: window.taxonomy_for || {},
            contentTypeMap: window.feed_types || {},
            initialTerms: this.config.initialTerms,
        });
 
        // Create API service
        this.feedService = new FeedService(
            this.config.apiUrl,
            this.config.nonce
        );
 
        // Create favourites service
        this.favouritesService = new FavouritesService(
            this.config.apiUrl,
            this.config.nonce
        );
 
        // Initialize favourites
        this.favouritesService.init();
 
        // Make available globally for legacy code
        window.hasFavourited = (type, id) => this.favouritesService.isFavourited(type, id);
    }
 
    /**
     * Initialize components
     */
    initializeComponents() {
        // Create filter panel with centralized onChange handler
        this.filterPanel = new FilterPanel(
            this.container.querySelector('.feed-filters'),
            {
                taxonomies: this.config.taxonomies,
                contentTypes: this.config.contentTypes,
                taxonomyFor: window.taxonomy_for || {},
                defaultContent: this.config.content,
                // Pass a reference to the handler instead of binding to avoid duplication
                onChange: this.handleFilterChange.bind(this)
            }
        );
 
        // IMPORTANT: Initialize taxonomy filters with current content type
        this.filterPanel.updateTaxonomyFilters(this.config.content);
        this.filterPanel.updateOrderFilters(this.config.content);
 
        // Create feed grid
        this.feedGrid = new FeedGrid(
            this.container.querySelector('.feed-grid'),
            {
                isGallery: this.config.isGallery,
                showAuthor: this.config.showAuthor,
                showDate: this.config.showDate,
            }
        );
 
        // Create loading state
        this.loadingState = new LoadingState(
            this.container.querySelector('.feed-overlay'),
            {
                contentTypes: this.config.contentTypes,
                taxonomies: this.config.taxonomies,
            }
        );
 
        // Set up gallery if needed
        if (this.config.isGallery) {
            this.feedGrid.setGalleryOpenHandler(this.openGallery.bind(this));
        }
    }
 
    /**
     * Use event delegation for improved performance
     */
    setupEventDelegation() {
        // State change listener
        this.stateManager.subscribe(this.handleStateChange.bind(this));
 
        // Single container event listener for load more
        this.container.addEventListener('click', (e) => {
            // Handle load more button
            if (e.target.closest('.load-more')) {
                this.handleLoadMore();
                e.preventDefault();
            }
        });
 
        // Global events that should only have one listener
        window.addEventListener('popstate', this.handlePopState.bind(this));
        document.addEventListener('galleryClose', () => this.gallery = null);
        document.addEventListener('favourites-updated', this.handleFavouritesUpdate.bind(this));
    }
 
    /**
    * Handle browser history navigation
    */
    handlePopState(e) {
        if (e.state && e.state.filters) {
            // Update state manager with filters from URL
            this.stateManager.updateFilters(e.state.filters);
 
            // Update UI
            this.filterPanel.loadFromURL();
 
            // Update taxonomy and order filters for current content type
            const contentType = e.state.filters.content || this.config.content;
            this.filterPanel.updateTaxonomyFilters(contentType);
            this.filterPanel.updateOrderFilters(contentType);
 
            // Load items with updated filters
            this.loadItems();
 
 
 
            // Announce to screen readers
            this.announceToScreenReader('Updated filters from browser history');
        }
    }
 
    /**
     * Handle state changes
     */
    handleStateChange(state) {
        // Update loading UI
        this.updateLoadingUI(state.loading);
 
        // Update load more button visibility
        this.updateLoadMoreButton(state.hasMore);
    }
 
    /**
     * Update loading UI
     */
    updateLoadingUI(loading) {
        if (loading) {
            this.loadingState.show();
        } else {
            this.loadingState.hide();
        }
 
        // Update loading spinner
        const spinner = this.container.querySelector('.loading-spinner');
        if (spinner) {
            spinner.hidden = !loading;
        }
 
        // Update load more button
        const loadMoreBtn = this.container.querySelector('.load-more');
        if (loadMoreBtn) {
            loadMoreBtn.disabled = loading;
        }
    }
 
    /**
     * Update load more button visibility
     */
    updateLoadMoreButton(hasMore) {
        const loadMoreBtn = this.container.querySelector('.load-more');
        if (loadMoreBtn) {
            loadMoreBtn.hidden = !hasMore;
        }
    }
 
    /**
     * Handle filter changes
     */
    handleFilterChange(filters) {
        // Check if content type has changed
        const prevContentType = this.stateManager.getState().filters;
        const contentTypeChanged = prevContentType !== filters;
 
        // Update state
        this.stateManager.updateFilters(filters);
 
        // Reset pagination
        this.stateManager.resetPagination();
 
        // Reload items (with cache reset if content type changed)
        this.loadItems(contentTypeChanged);
    }
 
    /**
     * Handle favourites updates
     */
    handleFavouritesUpdate(event) {
        const { type, id, isFavourited } = event.detail;
 
        // Update UI
        this.feedGrid.updateFavouriteStatus(type, id, isFavourited);
 
        // Show notification
        this.showNotification(
            isFavourited ? 'Added to favourites' : 'Removed from favourites',
            'success'
        );
    }
 
    /**
     * Handle load more button click
     */
    handleLoadMore() {
        const state = this.stateManager.getState();
 
            if (state.loading || !state.hasMore) {
                return;
            }
 
        // Increment page
        this.stateManager.nextPage();
 
        // Load more items
        this.loadItems();
    }
 
    /**
     * Load items from API with optional cache busting
     */
    async loadItems(resetCache = false) {
        const state = this.stateManager.getState();
 
        // Skip if already loading
        if (state.loading) {
            return;
        }
 
        // Update loading state
        this.stateManager.setLoading(true);
        console.log(this.config);
        try {
            // Get query parameters - explicitly include content type
            const params = {
                filters: {
                    ...state.filters,
                    // Ensure content type is explicitly set
                    content: state.filters.content || this.config.content
                },
                page: state.page,
                highlight: this.config.highlight,
                source: this.config.source,
                sourceType: this.config.sourceType
            };
 
 
            // Fetch data with cache busting if specified
            const data = await this.feedService.fetchFeed(params, resetCache);
 
            // Clear grid on first page
            if (state.page === 1) {
                this.feedGrid.clear();
            }
            // Handle empty results
            if (!data || !data.items || data.items.length === 0) {
                if (state.page === 1) {
                    this.feedGrid.showEmptyState(!!state.filters.favouritesOnly);
                }
                this.stateManager.setState({ hasMore: false });
            } else {
                // Render items
                this.feedGrid.renderItems(data.items, state.page > 1);
 
                // Update has more
                this.stateManager.setState({ hasMore: data.hasMore });
 
 
            }
        } catch (error) {
            this.handleError(error);
        } finally {
            // Update loading state
            this.stateManager.setLoading(false);
        }
    }
 
    /**
     * Handle errors
     */
    handleError(error) {
        if (this.errorHandler) {
            return this.errorHandler.handleApiError(
                error,
                {
                    component: 'FeedBlock',
                    action: 'loadItems'
                },
                () => this.loadItems()
            );
        }
 
        // Fallback to basic error handling if errorHandler not available
        this.showNotification(
            'Failed to load content. Please try again.',
            'error',
            [{
                label: 'Refresh',
                icon: 'refresh',
                action: () => {
                    window.location.reload();
                }
            }]
        );
    }
 
    /**
     * Show notification
     */
    showNotification(message, type = 'info', actions = []) {
        if (window.jvbNotifications) {
            window.jvbNotifications.queuePopupNotification({
                type: type,
                message: message,
                icon: type === 'error' ? 'alert' : (type === 'success' ? 'heart' : 'info'),
                priority: type === 'error' ? 'high' : 'medium',
                displayDuration: 3000,
                actions: actions
            });
        }
 
        // Update live region for accessibility
        const liveRegion = this.container.querySelector('.live-region');
        if (liveRegion) {
            liveRegion.textContent = message;
        }
    }
 
    /**
     * Load state from URL parameters
     */
    loadStateFromURL() {
        // Get filters from URL via the filter service
        const urlFilters = this.filterService.parseFiltersFromURL();
        if (Object.keys(urlFilters).length === 0) {
            return;
        }
 
        // Determine content type - from URL or default config
        const contentType = urlFilters['f_content'] || this.config.content;
 
        // Update state manager with URL filters
        if (Object.keys(urlFilters).length > 0) {
            this.stateManager.updateFilters(urlFilters);
        }
 
        // Update UI to match current state (handled by FilterPanel)
        this.filterPanel.loadFromURL();
 
        // IMPORTANT: Make sure taxonomy filters visibility is correct
        // for the current content type
        this.filterPanel.updateTaxonomyFilters(contentType);
        this.filterPanel.updateOrderFilters(contentType);
 
    }
 
    /**
     * Get highlighted item from URL
     */
    getHighlightFromURL() {
        const searchParams = new URLSearchParams(window.location.search);
 
        // Check for content type parameters
        const contentTypes = ['tattoo', 'piercing', 'artwork'];
 
        for (const type of contentTypes) {
            if (searchParams.has(type)) {
                return { [type]: searchParams.get(type) };
            }
        }
 
        return null;
    }
 
    /**
     * Scroll to highlighted item
     */
    scrollToHighlightedItem() {
        if (!this.config.highlight) return;
 
        // Get highlight type and ID
        const type = Object.keys(this.config.highlight)[0];
        const id = this.config.highlight[type];
 
        if (!type || !id) return;
 
        // Find the item
        const item = this.container.querySelector(`#${type}-${id}`);
 
        if (item) {
            // Scroll to item
            item.scrollIntoView({ behavior: 'smooth', block: 'center' });
 
            // Highlight the item
            item.classList.add('highlighted');
 
            // Open gallery if in gallery mode
            if (this.config.isGallery) {
                console.log('It is a gallery item!');
                const items = Array.from(this.container.querySelectorAll('.feed-item'));
                const index = items.indexOf(item);
 
                if (index !== -1) {
                    this.openGallery(index);
                }
            }
 
            // Clean up URL
            window.history.replaceState('', '', window.location.origin + window.location.pathname);
        }
    }
 
    /**
     * Open gallery view
     */
    openGallery(index) {
        if (!this.config.isGallery || this.gallery) return;
 
        // Get gallery items from grid
        const items = this.feedGrid.getGalleryItems();
        console.log(items);
 
        // Create gallery with unified callbacks object
        this.gallery = new GalleryModal(items, index);
 
        // Set callbacks
        this.gallery.setCallbacks({
            onClose: () => this.gallery = null,
            onLoadMore: this.handleGalleryLoadMore.bind(this),
            onNavigate: (newIndex) => {
                if (newIndex >= items.length - 3 && this.stateManager.getState().hasMore) {
                    this.handleGalleryLoadMore();
                }
            }
        });
 
        this.gallery.show();
    }
 
    /**
     * Handle load more request from gallery
     */
    async handleGalleryLoadMore() {
        const state = this.stateManager.getState();
 
        if (!state.hasMore || state.loading) {
            return false;
        }
 
        // Increment page
        this.stateManager.nextPage();
 
        // Load more items
        await this.loadItems();
 
        // Update gallery items
        if (this.gallery) {
            this.gallery.updateItems(this.feedGrid.getGalleryItems());
        }
 
        return true;
    }
 
    /**
     * Initialize accessibility features
     */
    initializeAccessibility() {
        // Create live region for screen reader announcements
        this.liveRegion = document.createElement('div');
        this.liveRegion.setAttribute('aria-live', 'polite');
        this.liveRegion.setAttribute('role', 'status');
        this.liveRegion.className = 'screen-reader-text live-region';
        this.container.appendChild(this.liveRegion);
 
        // Add keyboard shortcut support
        this.bindKeyboardShortcuts();
    }
 
    /**
     * Set up focus traps for modals
     */
    setupFocusTraps() {
        // Add focus trap to filter dropdowns
        this.filterDropdowns = this.container.querySelectorAll('.filter-dropdown');
        this.filterDropdowns.forEach(dialog => {
            dialog.addEventListener('show', () => {
                // Store current focus
                this._previouslyFocused = document.activeElement;
 
                // Focus first focusable element
                const focusable = dialog.querySelectorAll(
                    'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])'
                );
                if (focusable.length) {
                    focusable[0].focus();
                }
            });
 
            dialog.addEventListener('close', () => {
                // Restore focus
                if (this._previouslyFocused) {
                    this._previouslyFocused.focus();
                }
            });
        });
    }
 
    /**
     * Bind keyboard shortcuts
     */
    bindKeyboardShortcuts() {
        // Use a single event listener for keyboard shortcuts
        document.addEventListener('keydown', (e) => {
            // Only handle when feed is visible (check if in viewport)
            if (!this.isElementInViewport(this.container)) return;
 
            // Escape key closes any open dialogs
            if (e.key === 'Escape') {
                const openDialogs = this.container.querySelectorAll('dialog[open]');
                if (openDialogs.length) {
                    openDialogs[0].close();
                    e.preventDefault();
                }
            }
 
            // Alt+F opens filters (common accessibility pattern)
            if (e.key === 'f' && e.altKey) {
                const filterToggle = this.container.querySelector('.filter-toggle');
                if (filterToggle) {
                    filterToggle.click();
                    e.preventDefault();
                }
            }
 
            // Space or Enter on focused items activates them
            if ((e.key === ' ' || e.key === 'Enter') && document.activeElement.classList.contains('feed-item')) {
                const link = document.activeElement.querySelector('a');
                if (link) {
                    link.click();
                    e.preventDefault();
                }
            }
        });
    }
 
 
    /**
     * Check if element is in viewport
     */
    isElementInViewport(el) {
        const rect = el.getBoundingClientRect();
        return (
            rect.top >= 0 &&
            rect.left >= 0 &&
            rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
            rect.right <= (window.innerWidth || document.documentElement.clientWidth)
        );
    }
 
    /**
     * Announce message to screen readers
     */
    announceToScreenReader(message) {
        if (!this.liveRegion) return;
 
        this.liveRegion.textContent = message;
    }
}
 
export default FeedBlock;