File size: 10,961 Bytes
f0743f4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import React, { useMemo, useEffect, useCallback, useRef } from 'react';
import { AutoSizer, List as VirtualList, WindowScroller } from 'react-virtualized';
import { throttle } from 'lodash';
import { Spinner } from '@librechat/client';
import { PermissionBits } from 'librechat-data-provider';
import type t from 'librechat-data-provider';
import { useMarketplaceAgentsInfiniteQuery } from '~/data-provider/Agents';
import { useAgentCategories, useLocalize } from '~/hooks';
import { useHasData } from './SmartLoader';
import ErrorDisplay from './ErrorDisplay';
import AgentCard from './AgentCard';
import { cn } from '~/utils';

interface VirtualizedAgentGridProps {
  category: string;
  searchQuery: string;
  onSelectAgent: (agent: t.Agent) => void;
  scrollElement?: HTMLElement | null;
}

// Constants for layout calculations
const CARD_HEIGHT = 160; // h-40 in pixels
const GAP_SIZE = 24; // gap-6 in pixels
const ROW_HEIGHT = CARD_HEIGHT + GAP_SIZE;
const CARDS_PER_ROW_MOBILE = 1;
const CARDS_PER_ROW_DESKTOP = 2;
const OVERSCAN_ROW_COUNT = 3;

/**
 * Virtualized grid component for displaying agent cards with high performance
 */
const VirtualizedAgentGrid: React.FC<VirtualizedAgentGridProps> = ({
  category,
  searchQuery,
  onSelectAgent,
  scrollElement,
}) => {
  const localize = useLocalize();
  const listRef = useRef<VirtualList>(null);
  const { categories } = useAgentCategories();

  // Build query parameters
  const queryParams = useMemo(() => {
    const params: {
      requiredPermission: number;
      category?: string;
      search?: string;
      limit: number;
      promoted?: 0 | 1;
    } = {
      requiredPermission: PermissionBits.VIEW,
      // Align with AgentGrid to eliminate API mismatch as a factor
      limit: 6,
    };

    if (searchQuery) {
      params.search = searchQuery;
      if (category !== 'all' && category !== 'promoted') {
        params.category = category;
      }
    } else {
      if (category === 'promoted') {
        params.promoted = 1;
      } else if (category !== 'all') {
        params.category = category;
      }
    }

    return params;
  }, [category, searchQuery]);

  // Use infinite query
  const {
    data,
    isLoading,
    error,
    isFetching,
    fetchNextPage,
    hasNextPage,
    refetch,
    isFetchingNextPage,
  } = useMarketplaceAgentsInfiniteQuery(queryParams);

  // Flatten pages into single array
  const currentAgents = useMemo(() => {
    if (!data?.pages) return [];
    return data.pages.flatMap((page) => page.data || []);
  }, [data?.pages]);

  const hasData = useHasData(data?.pages?.[0]);

  // Direct scroll handling for virtualized component to avoid hook conflicts
  useEffect(() => {
    if (!scrollElement) return;

    const throttledScrollHandler = throttle(() => {
      const { scrollTop, scrollHeight, clientHeight } = scrollElement;
      const scrollPosition = (scrollTop + clientHeight) / scrollHeight;

      if (scrollPosition >= 0.8 && hasNextPage && !isFetchingNextPage && !isFetching) {
        fetchNextPage();
      }
    }, 200);

    scrollElement.addEventListener('scroll', throttledScrollHandler, { passive: true });

    return () => {
      scrollElement.removeEventListener('scroll', throttledScrollHandler);
      throttledScrollHandler.cancel?.();
    };
  }, [scrollElement, hasNextPage, isFetchingNextPage, isFetching, fetchNextPage, category]);

  // Separate effect for list re-rendering on data changes
  useEffect(() => {
    if (listRef.current) {
      listRef.current.forceUpdateGrid();
    }
  }, [currentAgents]);

  // Helper functions for grid calculations
  const getCardsPerRow = useCallback((width: number) => {
    return width >= 768 ? CARDS_PER_ROW_DESKTOP : CARDS_PER_ROW_MOBILE;
  }, []);

  const getRowCount = useCallback((agentCount: number, cardsPerRow: number) => {
    return Math.ceil(agentCount / cardsPerRow);
  }, []);

  const getRowItems = useCallback(
    (rowIndex: number, cardsPerRow: number) => {
      const startIndex = rowIndex * cardsPerRow;
      const endIndex = Math.min(startIndex + cardsPerRow, currentAgents.length);
      return currentAgents.slice(startIndex, endIndex);
    },
    [currentAgents],
  );

  const getCategoryDisplayName = (categoryValue: string) => {
    const categoryData = categories.find((cat) => cat.value === categoryValue);
    if (categoryData) {
      return categoryData.label;
    }

    if (categoryValue === 'promoted') {
      return localize('com_agents_top_picks');
    }
    if (categoryValue === 'all') {
      return 'All';
    }

    return categoryValue.charAt(0).toUpperCase() + categoryValue.slice(1);
  };

  // Row renderer for virtual list
  const rowRenderer = useCallback(
    ({ index, key, style, parent }: any) => {
      const containerWidth = parent?.props?.width || 800;
      const cardsPerRow = getCardsPerRow(containerWidth);
      const rowAgents = getRowItems(index, cardsPerRow);
      const totalRows = getRowCount(currentAgents.length, cardsPerRow);
      const isLastRow = index === totalRows - 1;
      const showLoading = isFetchingNextPage && isLastRow;

      return (
        <div key={key} style={style}>
          <div
            className={cn(
              'grid gap-6 px-0',
              cardsPerRow === 1 ? 'grid-cols-1' : 'grid-cols-1 md:grid-cols-2',
            )}
            role="row"
            aria-rowindex={index + 1}
          >
            {rowAgents.map((agent: t.Agent, cardIndex: number) => {
              const globalIndex = index * cardsPerRow + cardIndex;
              return (
                <div key={`${agent.id}-${globalIndex}`} role="gridcell">
                  <AgentCard agent={agent} onClick={() => onSelectAgent(agent)} />
                </div>
              );
            })}
          </div>

          {showLoading && (
            <div
              className="flex justify-center py-4"
              role="status"
              aria-live="polite"
              aria-label={localize('com_agents_loading')}
            >
              <Spinner className="h-6 w-6 text-primary" />
              <span className="sr-only">{localize('com_agents_loading')}</span>
            </div>
          )}
        </div>
      );
    },
    [
      currentAgents,
      getCardsPerRow,
      getRowItems,
      getRowCount,
      isFetchingNextPage,
      localize,
      onSelectAgent,
    ],
  );

  // Simple loading spinner
  const loadingSpinner = (
    <div className="flex justify-center py-12">
      <Spinner className="h-8 w-8 text-primary" />
    </div>
  );

  // Handle error state
  if (error) {
    return (
      <ErrorDisplay
        error={error || 'Unknown error occurred'}
        onRetry={() => refetch()}
        context={{ searchQuery, category }}
      />
    );
  }

  // Handle loading state
  if (isLoading || (isFetching && !isFetchingNextPage)) {
    return loadingSpinner;
  }

  // Handle empty results
  if ((!currentAgents || currentAgents.length === 0) && !isLoading && !isFetching) {
    return (
      <div
        className="py-12 text-center text-text-secondary"
        role="status"
        aria-live="polite"
        aria-label={
          searchQuery
            ? localize('com_agents_search_empty_heading')
            : localize('com_agents_empty_state_heading')
        }
      >
        <h3 className="mb-2 text-lg font-medium">{localize('com_agents_empty_state_heading')}</h3>
      </div>
    );
  }

  // Main virtualized content
  return (
    <div
      className="space-y-6"
      role="tabpanel"
      id={`category-panel-${category}`}
      aria-labelledby={`category-tab-${category}`}
      aria-live="polite"
      aria-busy={isLoading && !hasData}
    >
      {/* Screen reader announcement */}
      <div id="search-results-count" className="sr-only" aria-live="polite" aria-atomic="true">
        {localize('com_agents_grid_announcement', {
          count: currentAgents?.length || 0,
          category: getCategoryDisplayName(category),
        })}
      </div>

      {/* Virtualized grid with external scroll integration */}
      <div
        role="grid"
        aria-label={localize('com_agents_grid_announcement', {
          count: currentAgents.length,
          category: getCategoryDisplayName(category),
        })}
      >
        {scrollElement ? (
          <WindowScroller scrollElement={scrollElement}>
            {({ height, isScrolling, registerChild, onChildScroll, scrollTop }) => (
              <AutoSizer disableHeight>
                {({ width }) => {
                  const cardsPerRow = getCardsPerRow(width);
                  const rowCount = getRowCount(currentAgents.length, cardsPerRow);

                  return (
                    <div ref={registerChild}>
                      <VirtualList
                        ref={listRef}
                        autoHeight
                        height={height}
                        isScrolling={isScrolling}
                        onScroll={onChildScroll}
                        overscanRowCount={OVERSCAN_ROW_COUNT}
                        rowCount={rowCount}
                        rowHeight={ROW_HEIGHT}
                        rowRenderer={rowRenderer}
                        scrollTop={scrollTop}
                        width={width}
                        style={{ outline: 'none' }}
                        aria-rowcount={rowCount}
                        data-testid="virtual-list"
                        data-total-rows={rowCount}
                      />
                    </div>
                  );
                }}
              </AutoSizer>
            )}
          </WindowScroller>
        ) : (
          // Fallback for when no external scroll element is provided
          <div style={{ height: 600 }}>
            <AutoSizer>
              {({ width, height }) => {
                const cardsPerRow = getCardsPerRow(width);
                const rowCount = getRowCount(currentAgents.length, cardsPerRow);

                return (
                  <VirtualList
                    ref={listRef}
                    height={height}
                    overscanRowCount={OVERSCAN_ROW_COUNT}
                    rowCount={rowCount}
                    rowHeight={ROW_HEIGHT}
                    rowRenderer={rowRenderer}
                    width={width}
                    style={{ outline: 'none' }}
                    aria-rowcount={rowCount}
                    data-testid="virtual-list"
                    data-total-rows={rowCount}
                  />
                );
              }}
            </AutoSizer>
          </div>
        )}
      </div>

      {/* End of results indicator */}
      {!hasNextPage && currentAgents && currentAgents.length > 0 && (
        <div className="mt-8 text-center">
          <p className="text-sm text-text-secondary">{localize('com_agents_no_more_results')}</p>
        </div>
      )}
    </div>
  );
};

export default VirtualizedAgentGrid;