-
Notifications
You must be signed in to change notification settings - Fork 256
Expand file tree
/
Copy pathFilterableCollection.tsx
More file actions
988 lines (869 loc) · 36.7 KB
/
Copy pathFilterableCollection.tsx
File metadata and controls
988 lines (869 loc) · 36.7 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
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
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
'use client';
import React, { useEffect, useLayoutEffect, useRef, useCallback, useState } from 'react';
import { useFilterStore } from '@/stores/useFilterStore';
import { LOAD_MORE_APPENDED_ATTR } from '@/components/LoadMoreCollection';
import { hasDynamicDateRule } from '@/lib/collection-field-utils';
import { resolvePaginationString } from '@/lib/pagination-text-utils';
import type { ConditionalVisibility, Layer } from '@/types';
interface FilterableCollectionProps {
children: React.ReactNode;
collectionId: string;
collectionLayerId: string;
filters: ConditionalVisibility;
sortBy?: string;
sortOrder?: 'asc' | 'desc';
sortByInputLayerId?: string;
sortOrderInputLayerId?: string;
limit?: number;
/** Hard cap on the total — clamps the displayed count and `hasMore` so a
* client-side reconcile matches the SSR-capped "Showing X of Y". */
maxTotal?: number;
/** Leading records skipped by the collection's `offset` before pagination.
* Forwarded to the filter API so filtered paging composes offset the same
* way SSR does. */
baseOffset?: number;
paginationMode?: 'pages' | 'load_more';
layerTemplate: Layer[];
collectionLayerClasses?: string[];
collectionLayerTag?: string;
isPublished?: boolean;
/** Preview mode forces server-rendered links to use the `/ycode/preview` prefix. */
isPreview?: boolean;
/** Item ID of the dynamic-page collection being rendered (for `current-page` link keywords). */
pageCollectionItemId?: string;
/** Ordered ids of the dynamic page's collection — powers `next-item` / `previous-item` link keywords. */
pageCollectionSortedItemIds?: string[];
/** Full collection layer (sans children) — lets the server rebuild proper item wrappers (link/action/attributes). */
collectionLayer?: Omit<Layer, 'children'>;
}
const FC_FILTERED_ATTR = 'data-fc-filtered';
const FC_SKELETON_ATTR = 'data-fc-skeleton';
const FC_RUNTIME_SKELETON_ATTR = 'data-fc-runtime-skeleton';
const FC_SKELETON_STYLE_ID = 'fc-skeleton-style';
const FC_PRERENDER_HIDE_ATTR = 'data-fc-prerender-hide';
/**
* Inject the skeleton pulse keyframes once. Published sites ship their own
* compiled CSS (no guaranteed Tailwind utilities), so the loading placeholder
* relies on inline styles plus this self-contained animation rather than
* framework classes.
*/
function ensureSkeletonStyles() {
if (typeof document === 'undefined') return;
if (document.getElementById(FC_SKELETON_STYLE_ID)) return;
const style = document.createElement('style');
style.id = FC_SKELETON_STYLE_ID;
style.textContent = getSkeletonStyles();
document.head.appendChild(style);
}
function getSkeletonStyles() {
return (
`@keyframes fc-skeleton-pulse{0%,100%{opacity:1}50%{opacity:.45}}` +
`[${FC_SKELETON_ATTR}]{` +
`min-height:7rem;border-radius:.5rem;` +
`background:currentColor;color:rgba(120,120,120,.18);` +
`animation:fc-skeleton-pulse 1.2s ease-in-out infinite;}`
);
}
function getPrerenderHideStyles() {
return getSkeletonStyles() +
`[${FC_PRERENDER_HIDE_ATTR}]~:not([${FC_SKELETON_ATTR}]){display:none!important;}`;
}
/**
* Browser custom event dispatched after collection HTML is appended/replaced
* client-side. AnimationInitializer / SliderInitializer listen for it so they
* can bind animations and sliders to the freshly injected DOM nodes.
*/
export interface ItemsInjectedDetail {
collectionLayerId: string;
layerTemplate: Layer[];
itemIds: string[];
append: boolean;
/** Full collection layer (sans children) — when present, initializers
* rebuild the full layer tree per item (so animations on the wrapper
* itself are bound), matching SSR. */
collectionLayer?: Omit<Layer, 'children'>;
}
export const ITEMS_INJECTED_EVENT = 'ycode:items-injected';
export default function FilterableCollection({
children,
collectionId,
collectionLayerId,
filters,
sortBy,
sortOrder,
sortByInputLayerId,
sortOrderInputLayerId,
limit,
maxTotal,
baseOffset,
paginationMode,
layerTemplate,
collectionLayerClasses,
collectionLayerTag,
isPublished = true,
isPreview = false,
pageCollectionItemId,
pageCollectionSortedItemIds,
collectionLayer,
}: FilterableCollectionProps) {
const markerRef = useRef<HTMLSpanElement>(null);
const ssrChildrenRef = useRef<Element[]>([]);
const [isFiltering, setIsFiltering] = useState(false);
const [hasActiveFilters, setHasActiveFilters] = useState(false);
const prevFilterKeyRef = useRef<string>('');
const abortRef = useRef<AbortController | null>(null);
const inFlightRequestKeyRef = useRef<string | null>(null);
const hasInputLinkedFilters = filters.groups.some(g =>
g.conditions.some(c => c.inputLayerId || c.inputLayerId2)
);
// Relative date presets (e.g. `$today`) are resolved at render time and baked
// into the indefinitely-cached SSR HTML, so they go stale as the calendar
// advances. Treat their presence like a runtime control: reconcile against the
// live server on mount so the list always reflects the real "today" (and stays
// consistent with the server-side search/filter, which re-resolves it fresh).
const hasDynamicDateFilter = hasDynamicDateRule(filters);
const [renderInitialSkeleton, setRenderInitialSkeleton] = useState(hasDynamicDateFilter);
// Input-linked filters (e.g. a URL-driven search) hide the SSR list up front so
// we don't flash the full list before narrowing it. A date-only reconcile keeps
// the SSR list visible and relies on the loading dim (`isFiltering` opacity)
// instead — showing the current list while it updates avoids a blank flash
// before the reconciled list arrives.
const pendingFirstEvalRef = useRef(hasInputLinkedFilters);
const [filteredPage, setFilteredPage] = useState(1);
const [filteredTotalPages, setFilteredTotalPages] = useState(1);
const [filteredHasMore, setFilteredHasMore] = useState(false);
const [filteredTotal, setFilteredTotal] = useState(0);
const [filteredLoaded, setFilteredLoaded] = useState(0);
const loadMoreOffsetRef = useRef(0);
const ssrPaginationTextRef = useRef<string | null>(null);
const ssrPrevClassRef = useRef<string | null>(null);
const ssrNextClassRef = useRef<string | null>(null);
const ssrCountTextRef = useRef<string | null>(null);
const ssrLoadMoreBtnDisplayRef = useRef<string | null>(null);
const ssrWrapperHadHiddenRef = useRef<boolean | null>(null);
const strippedPaginationParamRef = useRef(false);
const strippedId = collectionLayerId.startsWith('lyr-')
? collectionLayerId.slice(4)
: collectionLayerId;
const pKey = `p_${strippedId}`;
const fpKey = `fp_${strippedId}`;
// --- DOM helpers: find parent collection layer, hide/show SSR children ---
const getParent = useCallback(() => {
return markerRef.current?.parentElement as HTMLElement | null;
}, []);
const setSsrItemsDisplay = useCallback((display: '' | 'none') => {
ssrChildrenRef.current.forEach(el => {
(el as HTMLElement).style.display = display;
});
// Items previously appended by LoadMoreCollection live alongside the SSR
// children but aren't captured by `ssrChildrenRef` (they're added after
// mount). Toggle them in tandem so a runtime filter doesn't leave stale
// load-more rows visible underneath the filtered results.
const parent = getParent();
if (!parent) return;
parent.querySelectorAll(`[${LOAD_MORE_APPENDED_ATTR}]`).forEach(el => {
(el as HTMLElement).style.display = display;
});
}, [getParent]);
const hideSSR = useCallback(() => setSsrItemsDisplay('none'), [setSsrItemsDisplay]);
const showSSR = useCallback(() => setSsrItemsDisplay(''), [setSsrItemsDisplay]);
const clearFilteredDOM = useCallback(() => {
const parent = getParent();
if (!parent) return;
parent.querySelectorAll(`[${FC_FILTERED_ATTR}]`).forEach(el => el.remove());
}, [getParent]);
const removeLoadingSkeleton = useCallback(() => {
setRenderInitialSkeleton(false);
const parent = getParent();
if (!parent) return;
parent.querySelectorAll(`[${FC_RUNTIME_SKELETON_ATTR}]`).forEach(el => el.remove());
}, [getParent]);
// Show placeholder cards while a fresh list is fetched, but only when there's
// nothing already on screen to dim. This targets the relative-date reconcile
// (and any filter that starts from an empty list), where the SSR HTML can be
// empty — without it the list looks broken/empty for the 1-3s round-trip.
const showLoadingSkeleton = useCallback(() => {
const parent = getParent();
if (!parent) return;
if (parent.querySelector(`[${FC_SKELETON_ATTR}]`)) return;
const hasVisibleSsr = ssrChildrenRef.current.some(
el => (el as HTMLElement).style.display !== 'none'
);
const hasVisibleFiltered = parent.querySelector(`[${FC_FILTERED_ATTR}]`) !== null;
if (hasVisibleSsr || hasVisibleFiltered) return;
ensureSkeletonStyles();
const count = Math.min(Math.max(limit && limit > 0 ? limit : 6, 1), 8);
// Clone a real item when one exists (best layout fidelity); otherwise fall
// back to a generic block that flows in whatever grid/flex the parent uses.
const template = ssrChildrenRef.current[0] as HTMLElement | undefined;
for (let i = 0; i < count; i++) {
let node: HTMLElement;
if (template) {
node = template.cloneNode(true) as HTMLElement;
node.style.color = 'rgba(120,120,120,.18)';
node.style.background = 'currentColor';
node.style.borderRadius = '0.5rem';
node.style.animation = 'fc-skeleton-pulse 1.2s ease-in-out infinite';
node.querySelectorAll('*').forEach(child => {
(child as HTMLElement).style.visibility = 'hidden';
});
} else {
node = document.createElement('div');
}
node.style.display = '';
node.setAttribute(FC_SKELETON_ATTR, '');
node.setAttribute(FC_RUNTIME_SKELETON_ATTR, '');
parent.appendChild(node);
}
}, [getParent, limit]);
const injectFilteredHTML = useCallback((html: string, append: boolean, itemIds: string[]) => {
const parent = getParent();
if (!parent) return;
if (!append) {
removeLoadingSkeleton();
hideSSR();
clearFilteredDOM();
}
const temp = document.createElement('div');
temp.innerHTML = html;
while (temp.firstChild) {
const child = temp.firstChild;
if (child instanceof Element) child.setAttribute(FC_FILTERED_ATTR, '');
parent.appendChild(child);
}
const detail: ItemsInjectedDetail = { collectionLayerId, layerTemplate, itemIds, append, collectionLayer };
window.dispatchEvent(new CustomEvent<ItemsInjectedDetail>(ITEMS_INJECTED_EVENT, { detail }));
}, [getParent, hideSSR, clearFilteredDOM, removeLoadingSkeleton, collectionLayerId, layerTemplate, collectionLayer]);
// Capture SSR children on mount (before paint) and hide stale SSR output when
// the initial runtime reconcile will replace it. Without this, cached rows can
// flash briefly before the skeleton/fresh fetch starts.
useLayoutEffect(() => {
if (!markerRef.current) return;
const parent = markerRef.current.parentElement;
if (!parent) return;
ssrChildrenRef.current = Array.from(parent.children).filter(
el =>
el !== markerRef.current &&
el.tagName.toLowerCase() !== 'style' &&
!(el as HTMLElement).hasAttribute('data-collection-marker') &&
!(el as HTMLElement).hasAttribute(FC_SKELETON_ATTR)
);
if (pendingFirstEvalRef.current) {
hideSSR();
} else if (hasDynamicDateFilter) {
hideSSR();
showLoadingSkeleton();
}
markerRef.current.removeAttribute(FC_PRERENDER_HIDE_ATTR);
}, []); // eslint-disable-line react-hooks/exhaustive-deps
const filterValues = useFilterStore((state) => state.values);
const findLinkedInputValue = useCallback((inputLayerId?: string): string => {
if (!inputLayerId) return '';
for (const layerValues of Object.values(filterValues)) {
if (inputLayerId in layerValues) {
return layerValues[inputLayerId] || '';
}
}
return '';
}, [filterValues]);
const linkedSortByValue = findLinkedInputValue(sortByInputLayerId).trim();
const linkedSortOrderValue = findLinkedInputValue(sortOrderInputLayerId).trim().toLowerCase();
const isLinkedSortByValid = linkedSortByValue.length > 0 && linkedSortByValue !== 'none';
const isLinkedSortOrderValid = linkedSortOrderValue === 'asc' || linkedSortOrderValue === 'desc';
const effectiveSortBy = isLinkedSortByValid ? linkedSortByValue : sortBy;
const effectiveSortOrder = (isLinkedSortOrderValid ? linkedSortOrderValue : sortOrder) as 'asc' | 'desc' | undefined;
const hasRuntimeSortOverride = Boolean(
(sortByInputLayerId && isLinkedSortByValid) ||
(sortOrderInputLayerId && isLinkedSortOrderValid)
);
const buildApiFilters = useCallback(() => {
type FilterItem = {
fieldId: string;
operator: string;
value: string;
value2?: string;
fieldType?: string;
source?: 'collection_field' | 'self';
includesCurrentPageItem?: boolean;
valueMode?: 'static' | 'current_page';
currentPageFieldId?: string;
};
const operatorsWithoutValue = new Set([
'is_present',
'is_empty',
'is_not_empty',
'has_items',
'has_no_items',
'exists',
'does_not_exist',
]);
const activeByGroup: FilterItem[][] = [];
for (const group of filters.groups) {
const activeInGroup: FilterItem[] = [];
for (const condition of group.conditions) {
// Self conditions compare against the item's own ID — no fieldId needed,
// and they're forwarded verbatim so the server resolves the current page item.
if (condition.source === 'self') {
const hasStaticIds = !!condition.value && condition.value !== '[]';
if (!hasStaticIds && !condition.includesCurrentPageItem) continue;
activeInGroup.push({
fieldId: '',
operator: condition.operator,
value: condition.value || '[]',
source: 'self',
includesCurrentPageItem: condition.includesCurrentPageItem,
});
continue;
}
if (!condition.fieldId) continue;
// Current-page conditions are forwarded verbatim; the server resolves the
// compare value from the current dynamic page item (its own ID for
// reference fields, or `currentPageFieldId`'s value for scalar fields).
if (condition.valueMode === 'current_page') {
activeInGroup.push({
fieldId: condition.fieldId,
operator: condition.operator,
value: condition.value || '',
fieldType: condition.fieldType,
valueMode: 'current_page',
currentPageFieldId: condition.currentPageFieldId,
});
continue;
}
let value = condition.inputLayerId ? '' : (condition.value || '');
let value2 = condition.inputLayerId2 ? '' : condition.value2;
if (condition.inputLayerId) {
let inputValue = '';
for (const layerValues of Object.values(filterValues)) {
if (condition.inputLayerId in layerValues) {
inputValue = layerValues[condition.inputLayerId];
break;
}
}
if (!inputValue && condition.operator !== 'is_between') continue;
if (condition.fieldType === 'boolean' && inputValue === 'false') continue;
if (inputValue && inputValue.includes(',')) {
const checkedValues = inputValue.split(',').filter(Boolean);
if (checkedValues.length > 0) {
const arrayOperators = ['is_one_of', 'is_not_one_of', 'contains_all_of', 'contains_exactly'];
activeInGroup.push({
fieldId: condition.fieldId,
operator: arrayOperators.includes(condition.operator) ? condition.operator : 'is_one_of',
value: JSON.stringify(checkedValues),
fieldType: condition.fieldType,
});
}
continue;
}
if (inputValue) value = inputValue;
}
if (condition.inputLayerId2) {
let inputValue2 = '';
for (const layerValues of Object.values(filterValues)) {
if (condition.inputLayerId2 in layerValues) {
inputValue2 = layerValues[condition.inputLayerId2];
break;
}
}
if (!inputValue2 && condition.operator !== 'is_between') continue;
if (inputValue2) value2 = inputValue2;
}
const requiresValue = !operatorsWithoutValue.has(condition.operator);
if (condition.operator === 'is_between') {
if (!value && !value2) continue;
} else if (requiresValue && !value) {
continue;
}
if (
(condition.fieldType === 'reference' || condition.fieldType === 'multi_reference') &&
['is_one_of', 'is_not_one_of', 'contains_all_of', 'contains_exactly'].includes(condition.operator) &&
condition.inputLayerId
) {
value = JSON.stringify([value]);
}
// Date presets (e.g. `$today`) are forwarded verbatim — the filter API
// resolves them against the project timezone, so "today" matches the
// site's configured timezone rather than the visitor's browser.
activeInGroup.push({
fieldId: condition.fieldId,
operator: condition.operator,
value,
value2,
fieldType: condition.fieldType,
});
}
if (activeInGroup.length > 0) {
activeByGroup.push(activeInGroup);
}
}
if (activeByGroup.length === 0) return [];
const MAX_FILTER_GROUPS = 50;
let result: FilterItem[][] = [[]];
for (const groupConditions of activeByGroup) {
const expanded: FilterItem[][] = [];
for (const existing of result) {
for (const cond of groupConditions) {
expanded.push([...existing, cond]);
if (expanded.length >= MAX_FILTER_GROUPS) break;
}
if (expanded.length >= MAX_FILTER_GROUPS) break;
}
result = expanded;
if (result.length >= MAX_FILTER_GROUPS) break;
}
return result;
}, [filters, filterValues]);
const updateEmptyStateElements = useCallback((filteredCount: number) => {
const emptyEls = document.querySelectorAll(
`[data-collection-empty-state="${collectionLayerId}"]`
);
const hasItemsEls = document.querySelectorAll(
`[data-collection-has-items="${collectionLayerId}"]`
);
const itemCountEls = document.querySelectorAll(
`[data-collection-item-count="${collectionLayerId}"]`
);
const evaluateItemCount = (count: number, op: string, value: number): boolean => {
if (op === 'lt') return count < value;
if (op === 'lte') return count <= value;
if (op === 'gt') return count > value;
if (op === 'gte') return count >= value;
return count === value;
};
if (filteredCount < 0) {
emptyEls.forEach(el => { (el as HTMLElement).style.display = 'none'; });
hasItemsEls.forEach(el => { (el as HTMLElement).style.display = 'none'; });
itemCountEls.forEach(el => { (el as HTMLElement).style.display = 'none'; });
} else {
emptyEls.forEach(el => {
(el as HTMLElement).style.display = filteredCount === 0 ? '' : 'none';
});
hasItemsEls.forEach(el => {
(el as HTMLElement).style.display = filteredCount > 0 ? '' : 'none';
});
itemCountEls.forEach(el => {
const node = el as HTMLElement;
const op = node.getAttribute('data-collection-item-count-op') || 'eq';
const rawValue = node.getAttribute('data-collection-item-count-value') || '0';
const value = Number.parseInt(rawValue, 10);
const shouldShow = evaluateItemCount(filteredCount, op, Number.isNaN(value) ? 0 : value);
node.style.display = shouldShow ? '' : 'none';
});
}
}, [collectionLayerId]);
// --- SSR pagination DOM helpers ---
const getSsrPaginationWrapper = useCallback(() => {
return document.querySelector(
`[data-pagination-for="${collectionLayerId}"]`
) as HTMLElement | null;
}, [collectionLayerId]);
const toggleSsrWrapperHidden = useCallback((wrapper: HTMLElement, hide: boolean) => {
if (ssrWrapperHadHiddenRef.current === null) {
ssrWrapperHadHiddenRef.current = wrapper.classList.contains('hidden');
}
wrapper.classList.toggle('hidden', hide);
}, []);
const updateSsrPaginationDisplay = useCallback((page: number, totalPages: number) => {
const wrapper = getSsrPaginationWrapper();
if (!wrapper) return;
toggleSsrWrapperHidden(wrapper, totalPages <= 0);
const infoEl = wrapper.querySelector(`[data-layer-id$="-pagination-info"]`) as HTMLElement | null;
if (infoEl) {
if (ssrPaginationTextRef.current === null) {
ssrPaginationTextRef.current = infoEl.textContent || '';
}
const template = infoEl.getAttribute('data-pagination-template');
infoEl.textContent = template
? resolvePaginationString(template, { shown: 0, total: 0, current: page, pages: totalPages })
: `Page ${page} of ${totalPages}`;
}
const prevBtn = wrapper.querySelector(`[data-pagination-action="prev"]`) as HTMLElement | null;
if (prevBtn) {
if (ssrPrevClassRef.current === null) {
ssrPrevClassRef.current = prevBtn.className;
}
const isFirst = page <= 1;
if (isFirst) {
prevBtn.classList.add('opacity-50', 'cursor-not-allowed');
prevBtn.classList.remove('cursor-pointer');
} else {
prevBtn.classList.remove('opacity-50', 'cursor-not-allowed');
prevBtn.classList.add('cursor-pointer');
}
}
const nextBtn = wrapper.querySelector(`[data-pagination-action="next"]`) as HTMLElement | null;
if (nextBtn) {
if (ssrNextClassRef.current === null) {
ssrNextClassRef.current = nextBtn.className;
}
const isLast = page >= totalPages;
if (isLast) {
nextBtn.classList.add('opacity-50', 'cursor-not-allowed');
nextBtn.classList.remove('cursor-pointer');
} else {
nextBtn.classList.remove('opacity-50', 'cursor-not-allowed');
nextBtn.classList.add('cursor-pointer');
}
}
}, [getSsrPaginationWrapper, toggleSsrWrapperHidden]);
const updateSsrLoadMoreDisplay = useCallback((loaded: number, total: number, hasMore: boolean) => {
const wrapper = getSsrPaginationWrapper();
if (!wrapper) return;
toggleSsrWrapperHidden(wrapper, total <= 0);
const countEl = wrapper.querySelector(`[data-layer-id$="-pagination-count"]`) as HTMLElement | null;
if (countEl) {
if (ssrCountTextRef.current === null) {
ssrCountTextRef.current = countEl.textContent || '';
}
const template = countEl.getAttribute('data-pagination-template');
const shown = Math.min(loaded, total);
countEl.textContent = template
? resolvePaginationString(template, { shown, total, current: 1, pages: 1 })
: `Showing ${shown} of ${total}`;
}
const loadMoreBtn = wrapper.querySelector(`[data-pagination-action="load_more"]`) as HTMLElement | null;
if (loadMoreBtn) {
if (ssrLoadMoreBtnDisplayRef.current === null) {
ssrLoadMoreBtnDisplayRef.current = loadMoreBtn.style.display;
}
loadMoreBtn.style.display = hasMore ? '' : 'none';
}
}, [getSsrPaginationWrapper]);
const restoreSsrPagination = useCallback(() => {
const wrapper = getSsrPaginationWrapper();
if (!wrapper) return;
if (ssrPaginationTextRef.current !== null) {
const infoEl = wrapper.querySelector(`[data-layer-id$="-pagination-info"]`) as HTMLElement | null;
if (infoEl) {
infoEl.textContent = ssrPaginationTextRef.current;
}
ssrPaginationTextRef.current = null;
}
if (ssrPrevClassRef.current !== null) {
const prevBtn = wrapper.querySelector(`[data-pagination-action="prev"]`) as HTMLElement | null;
if (prevBtn) prevBtn.className = ssrPrevClassRef.current;
ssrPrevClassRef.current = null;
}
if (ssrNextClassRef.current !== null) {
const nextBtn = wrapper.querySelector(`[data-pagination-action="next"]`) as HTMLElement | null;
if (nextBtn) nextBtn.className = ssrNextClassRef.current;
ssrNextClassRef.current = null;
}
if (ssrCountTextRef.current !== null) {
const countEl = wrapper.querySelector(`[data-layer-id$="-pagination-count"]`) as HTMLElement | null;
if (countEl) countEl.textContent = ssrCountTextRef.current;
ssrCountTextRef.current = null;
}
if (ssrLoadMoreBtnDisplayRef.current !== null) {
const loadMoreBtn = wrapper.querySelector(`[data-pagination-action="load_more"]`) as HTMLElement | null;
if (loadMoreBtn) loadMoreBtn.style.display = ssrLoadMoreBtnDisplayRef.current;
ssrLoadMoreBtnDisplayRef.current = null;
}
if (ssrWrapperHadHiddenRef.current !== null) {
wrapper.classList.toggle('hidden', ssrWrapperHadHiddenRef.current);
ssrWrapperHadHiddenRef.current = null;
}
}, [getSsrPaginationWrapper]);
// --- Click intercepts ---
const paginationInterceptRef = useRef<((e: Event) => void) | null>(null);
const goToFilteredPageRef = useRef<(page: number) => void>(() => {});
const handleLoadMoreRef = useRef<() => void>(() => {});
const syncFilteredPageToUrl = useCallback((page: number) => {
const url = new URL(window.location.href);
if (page <= 1) {
url.searchParams.delete(fpKey);
} else {
url.searchParams.set(fpKey, String(page));
}
window.history.replaceState({}, '', url.toString());
}, [fpKey]);
const goToFilteredPage = useCallback((page: number) => {
if (page < 1 || page > filteredTotalPages || isFiltering) return;
const groups = buildApiFilters();
const offset = (page - 1) * (limit || 10);
setFilteredPage(page);
syncFilteredPageToUrl(page);
fetchFilteredRef.current(groups, offset, false);
}, [filteredTotalPages, isFiltering, buildApiFilters, limit, syncFilteredPageToUrl]);
useEffect(() => {
goToFilteredPageRef.current = goToFilteredPage;
}, [goToFilteredPage]);
const handleLoadMore = useCallback(() => {
if (isFiltering || !filteredHasMore) return;
const groups = buildApiFilters();
fetchFilteredRef.current(groups, loadMoreOffsetRef.current, true);
}, [isFiltering, filteredHasMore, buildApiFilters]);
useEffect(() => {
handleLoadMoreRef.current = handleLoadMore;
}, [handleLoadMore]);
const attachPaginationIntercept = useCallback(() => {
const wrapper = getSsrPaginationWrapper();
if (!wrapper || paginationInterceptRef.current) return;
const handler = (e: Event) => {
const target = e.target as HTMLElement;
const button = target.closest('[data-pagination-action]') as HTMLElement | null;
if (!button) return;
e.stopPropagation();
e.preventDefault();
const action = button.getAttribute('data-pagination-action');
if (action === 'prev') {
goToFilteredPageRef.current(filteredPageRef.current - 1);
} else if (action === 'next') {
goToFilteredPageRef.current(filteredPageRef.current + 1);
} else if (action === 'load_more') {
handleLoadMoreRef.current();
}
};
wrapper.addEventListener('click', handler, true);
paginationInterceptRef.current = handler;
}, [getSsrPaginationWrapper]);
const detachPaginationIntercept = useCallback(() => {
const wrapper = getSsrPaginationWrapper();
if (!wrapper || !paginationInterceptRef.current) return;
wrapper.removeEventListener('click', paginationInterceptRef.current, true);
paginationInterceptRef.current = null;
}, [getSsrPaginationWrapper]);
const filteredPageRef = useRef(filteredPage);
useEffect(() => { filteredPageRef.current = filteredPage; }, [filteredPage]);
// --- Fetch logic ---
const fetchFiltered = useCallback((
filterGroups: Array<Array<{
fieldId: string;
operator: string;
value: string;
value2?: string;
fieldType?: string;
source?: 'collection_field' | 'self';
includesCurrentPageItem?: boolean;
valueMode?: 'static' | 'current_page';
currentPageFieldId?: string;
}>>,
offset: number,
append: boolean,
) => {
const requestKey = JSON.stringify({
filterGroups,
offset,
append,
sortBy: effectiveSortBy,
sortOrder: effectiveSortOrder,
limit,
});
if (inFlightRequestKeyRef.current === requestKey) return;
setIsFiltering(true);
if (!append) showLoadingSkeleton();
abortRef.current?.abort();
const controller = new AbortController();
abortRef.current = controller;
inFlightRequestKeyRef.current = requestKey;
fetch(`/ycode/api/collections/${collectionId}/items/filter`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
layerTemplate,
collectionLayerId,
filterGroups,
sortBy: effectiveSortBy,
sortOrder: effectiveSortOrder,
limit,
offset,
maxTotal,
baseOffset,
published: isPublished,
collectionLayerClasses,
collectionLayerTag,
isPreview,
pageCollectionItemId,
pageCollectionSortedItemIds,
collectionLayer,
}),
signal: controller.signal,
})
.then(res => {
if (!res.ok) throw new Error(`Filter API returned ${res.status}`);
return res.json();
})
.then(result => {
if (result.error) {
console.error('Filter API error:', result.error);
removeLoadingSkeleton();
setIsFiltering(false);
return;
}
const data = result.data;
if (!data) {
removeLoadingSkeleton();
setIsFiltering(false);
return;
}
const responseItemIds: string[] = Array.isArray(data.itemIds) ? data.itemIds : [];
injectFilteredHTML(data.html ?? '', append, responseItemIds);
const total = data.total ?? 0;
const count = data.count ?? 0;
const hasMore = data.hasMore ?? false;
const newOffset = (data.offset ?? 0) + count;
loadMoreOffsetRef.current = newOffset;
setFilteredHasMore(hasMore);
setFilteredTotal(total);
setFilteredLoaded(newOffset);
setIsFiltering(false);
updateEmptyStateElements(total);
if (paginationMode === 'pages' && limit && limit > 0) {
setFilteredTotalPages(Math.max(1, Math.ceil(total / limit)));
}
})
.catch(err => {
if (err.name !== 'AbortError') {
console.error('Filter fetch failed:', err);
removeLoadingSkeleton();
setIsFiltering(false);
}
})
.finally(() => {
if (inFlightRequestKeyRef.current === requestKey) {
inFlightRequestKeyRef.current = null;
abortRef.current = null;
}
});
}, [collectionId, collectionLayerId, layerTemplate, effectiveSortBy, effectiveSortOrder, limit, maxTotal, baseOffset, paginationMode, updateEmptyStateElements, injectFilteredHTML, showLoadingSkeleton, removeLoadingSkeleton, collectionLayerClasses, collectionLayerTag, isPublished, isPreview, pageCollectionItemId, pageCollectionSortedItemIds, collectionLayer]);
const fetchFilteredRef = useRef(fetchFiltered);
useEffect(() => { fetchFilteredRef.current = fetchFiltered; }, [fetchFiltered]);
// --- React to filter value changes ---
useEffect(() => {
const filterGroups = buildApiFilters();
const hasActiveInputValues = filters.groups.some(g =>
g.conditions.some(c => {
if (!c.inputLayerId) return false;
for (const layerValues of Object.values(filterValues)) {
if (c.inputLayerId in layerValues && layerValues[c.inputLayerId]) return true;
}
return false;
})
);
const hasRuntimeControls = hasActiveInputValues || hasRuntimeSortOverride || hasDynamicDateFilter;
const filterKey = JSON.stringify({
filterGroups,
sortBy: effectiveSortBy,
sortOrder: effectiveSortOrder,
hasRuntimeControls,
});
if (filterKey === prevFilterKeyRef.current) {
if (pendingFirstEvalRef.current) {
pendingFirstEvalRef.current = false;
showSSR();
}
return;
}
const wasEmpty = prevFilterKeyRef.current === '' || prevFilterKeyRef.current === '[]';
prevFilterKeyRef.current = filterKey;
pendingFirstEvalRef.current = false;
if (!hasRuntimeControls) {
abortRef.current?.abort();
abortRef.current = null;
const cleanUrl = new URL(window.location.href);
if (cleanUrl.searchParams.has(fpKey)) {
cleanUrl.searchParams.delete(fpKey);
window.history.replaceState({}, '', cleanUrl.toString());
}
strippedPaginationParamRef.current = false;
useFilterStore.getState().syncToUrl();
setHasActiveFilters(false);
setIsFiltering(false);
setFilteredHasMore(false);
setFilteredPage(1);
setFilteredTotalPages(1);
setFilteredTotal(0);
setFilteredLoaded(0);
loadMoreOffsetRef.current = 0;
removeLoadingSkeleton();
clearFilteredDOM();
showSSR();
detachPaginationIntercept();
restoreSsrPagination();
const wrapper = getSsrPaginationWrapper();
if (wrapper) wrapper.style.display = '';
updateEmptyStateElements(-1);
// Notify initializers (animations, sliders) that injected items are
// gone so they can drop any extras for this collection.
const clearDetail: ItemsInjectedDetail = {
collectionLayerId,
layerTemplate,
itemIds: [],
append: false,
collectionLayer,
};
window.dispatchEvent(new CustomEvent<ItemsInjectedDetail>(ITEMS_INJECTED_EVENT, { detail: clearDetail }));
return;
}
setHasActiveFilters(true);
const currentUrl = new URL(window.location.href);
const fpValue = currentUrl.searchParams.get(fpKey);
const restoredPage = fpValue ? Math.max(1, parseInt(fpValue, 10) || 1) : 1;
const startPage = wasEmpty ? restoredPage : 1;
setFilteredPage(startPage);
loadMoreOffsetRef.current = 0;
if (startPage <= 1 && currentUrl.searchParams.has(fpKey)) {
currentUrl.searchParams.delete(fpKey);
window.history.replaceState({}, '', currentUrl.toString());
}
if (currentUrl.searchParams.has(pKey)) {
currentUrl.searchParams.delete(pKey);
window.history.replaceState({}, '', currentUrl.toString());
strippedPaginationParamRef.current = true;
}
if (paginationMode === 'pages' || paginationMode === 'load_more') {
attachPaginationIntercept();
}
const startOffset = (startPage - 1) * (limit || 10);
fetchFiltered(filterGroups, startOffset, false);
}, [filterValues, buildApiFilters, fetchFiltered, paginationMode, attachPaginationIntercept, detachPaginationIntercept, restoreSsrPagination, getSsrPaginationWrapper, updateEmptyStateElements, fpKey, pKey, limit, hasRuntimeSortOverride, hasDynamicDateFilter, effectiveSortBy, effectiveSortOrder, showSSR, clearFilteredDOM, removeLoadingSkeleton]);
useEffect(() => {
if (!hasActiveFilters || paginationMode !== 'pages') return;
updateSsrPaginationDisplay(filteredPage, filteredTotalPages);
}, [hasActiveFilters, paginationMode, filteredPage, filteredTotalPages, updateSsrPaginationDisplay]);
useEffect(() => {
if (!hasActiveFilters || paginationMode !== 'load_more') return;
updateSsrLoadMoreDisplay(filteredLoaded, filteredTotal, filteredHasMore);
}, [hasActiveFilters, paginationMode, filteredLoaded, filteredTotal, filteredHasMore, updateSsrLoadMoreDisplay]);
useEffect(() => {
return () => detachPaginationIntercept();
}, [detachPaginationIntercept]);
// Abort any in-flight fetch on unmount
useEffect(() => {
return () => abortRef.current?.abort();
}, []);
// Loading state: apply opacity to the parent collection layer element
useEffect(() => {
const el = getParent();
if (!el) return;
if (isFiltering) {
el.style.opacity = '0.5';
el.style.pointerEvents = 'none';
} else {
el.style.opacity = '';
el.style.pointerEvents = '';
}
}, [isFiltering, getParent]);
const initialSkeletonCount = hasDynamicDateFilter
? Math.min(Math.max(limit && limit > 0 ? limit : 6, 1), 8)
: 0;
// Zero DOM footprint for normal lists; dynamic-date lists include first-paint
// skeletons so stale cached SSR rows never flash before hydration.
return (
<>
{renderInitialSkeleton && (
<style dangerouslySetInnerHTML={{ __html: getPrerenderHideStyles() }} />
)}
<span
ref={markerRef}
data-collection-marker=""
{...(renderInitialSkeleton ? { [FC_PRERENDER_HIDE_ATTR]: '' } : {})}
style={{ display: 'none' }}
/>
{renderInitialSkeleton && Array.from({ length: initialSkeletonCount }).map((_, index) => (
<div key={`fc-skeleton-${index}`} {...{ [FC_SKELETON_ATTR]: '' }} />
))}
{children}
</>
);
}