Bin
2025-12-17 2b99d77d73ba568beff0a549534017caaad8a6de
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
import { observer } from "mobx-react";
import { useCallback, useContext, useMemo, useEffect, useRef } from "react";
import AutoSizer from "react-virtualized-auto-sizer";
import { FixedSizeGrid } from "react-window";
import InfiniteLoader from "react-window-infinite-loader";
import { cn } from "../../../utils/bem";
import { Checkbox, cnm } from "@humansignal/ui";
import { Space } from "../../Common/Space/Space";
import { getProperty, prepareColumns } from "../../Common/Table/utils";
import * as DataGroups from "../../DataGroups";
import { FF_GRID_PREVIEW, FF_LOPS_E_3, isFF } from "../../../utils/feature-flags";
import { SkeletonLoader } from "../../Common/SkeletonLoader";
import { GridViewContext, GridViewProvider } from "./GridPreview";
import "./GridView.scss";
import { groupBy } from "../../../utils/utils";
import { IMAGE_SIZE_COEFFICIENT } from "../../DataGroups/ImageDataGroup";
 
const NO_IMAGE_CELL_HEIGHT = 250;
const CELL_HEADER_HEIGHT = 32;
 
export const GridHeader = observer(({ row, selected, onSelect }) => {
  const isSelected = selected.isSelected(row.id);
  return (
    <div className={cn("grid-view").elem("cell-header").toClassName()}>
      <Space>
        <Checkbox
          checked={isSelected}
          ariaLabel={`${isSelected ? "取消选择" : "选择"} 任务 ${row.id}`}
          onChange={() => onSelect?.(row.id)}
        />
        <span>{row.id}</span>
      </Space>
    </div>
  );
});
 
export const GridBody = observer(({ row, fields, columnCount }) => {
  const { hasImage } = useContext(GridViewContext);
  const dataFields = fields.filter((f) => f.parent?.alias === "data");
  const group = groupBy(dataFields, (f) => f.currentType);
 
  return Object.entries(group).map(([type, fields]) => {
    return (
      <div
        key={type}
        className={cnm("h-full w-full", {
          "overflow-x-auto scrollbar-thin scrollbar-thumb-neutral-border scrollbar-track-transparent":
            type !== "Image" || type === "Unknown",
          "h-auto": !hasImage || hasImage,
        })}
      >
        {fields.map((field, index) => {
          const valuePath = field.id.split(":")[1] ?? field.id;
          const field_type = field.currentType;
          let value = getProperty(row, valuePath);
 
          /**
           * The value is an array...
           * In this case, we take the first element of the array
           */
          if (Array.isArray(value)) {
            value = value[0];
          }
 
          return (
            <GridDataGroup
              key={`${row.id}-${index}`}
              type={field_type}
              value={value}
              hasImage={hasImage}
              field={field}
              row={row}
              columnCount={columnCount}
            />
          );
        })}
      </div>
    );
  });
});
 
export const GridDataGroup = observer(({ type, value, field, row, columnCount, hasImage }) => {
  const DataTypeComponent = DataGroups[type];
 
  return isFF(FF_LOPS_E_3) && row.loading === field.alias ? (
    <SkeletonLoader />
  ) : DataTypeComponent ? (
    <DataTypeComponent value={value} field={field} original={row} columnCount={columnCount} hasImage={hasImage} />
  ) : (
    <DataGroups.TextDataGroup value={value} field={field} original={row} hasImage={hasImage} />
  );
});
 
export const GridCell = observer(({ view, selected, row, fields, onClick, columnCount, ...props }) => {
  const { setCurrentTaskId, imageField, hasImage } = useContext(GridViewContext);
 
  const handleBodyClick = useCallback(
    (e) => {
      if (!isFF(FF_GRID_PREVIEW) || !imageField) return;
      e.stopPropagation();
      setCurrentTaskId(row.id);
    },
    [imageField, row.id],
  );
 
  return (
    <div
      {...props}
      className={cn("grid-view")
        .elem("cell")
        .mod({ selected: selected.isSelected(row.id) })
        .toClassName()}
      onClick={onClick}
    >
      <div className={cn("grid-view").elem("cell-content").toClassName()}>
        <GridHeader
          view={view}
          row={row}
          fields={fields}
          selected={view.selected}
          onSelect={view.selected.toggleSelected}
        />
        <div
          className={`${cn("grid-view").elem("cell-body").mod({ responsive: !view.gridFitImagesToWidth }).toClassName()} ${cnm({ "overflow-auto": !hasImage })}`}
          onClick={handleBodyClick}
        >
          <GridBody view={view} row={row} fields={fields} columnCount={columnCount} />
        </div>
      </div>
    </div>
  );
});
 
export const GridView = observer(({ data, view, loadMore, fields, onChange, hiddenFields }) => {
  const columnCount = view.gridWidth ?? 4;
  const prevColumnCountRef = useRef(columnCount);
 
  const getCellIndex = useCallback((row, column) => columnCount * row + column, [columnCount]);
 
  const fieldsData = useMemo(() => {
    return prepareColumns(fields, hiddenFields);
  }, [fields, hiddenFields]);
  const hasImage = fieldsData.some((f) => f.currentType === "Image");
 
  const rowHeight = hasImage
    ? fieldsData
      .filter((f) => f.parent?.alias === "data")
      .reduce((res, f) => {
        const height = (DataGroups[f.currentType] ?? DataGroups.TextDataGroup).height;
 
        return res + height;
      }, 16)
    : NO_IMAGE_CELL_HEIGHT;
  const finalRowHeight =
    CELL_HEADER_HEIGHT + rowHeight * (hasImage ? Math.max(1, (IMAGE_SIZE_COEFFICIENT - columnCount) * 0.5) : 1);
 
  // Calculate the total number of rows needed to display all items
  const itemCount = view.dataStore.total || data.length;
  // Use only loaded data for grid dimensions to avoid long scrollbar
  const loadedRows = Math.ceil(data.length / columnCount);
 
  const renderItem = useCallback(
    ({ style, rowIndex, columnIndex }) => {
      const index = getCellIndex(rowIndex, columnIndex);
      const row = data[index];
      if (!row) return null;
 
      const props = {
        style: {
          ...style,
          marginLeft: "1em",
        },
      };
 
      return (
        <GridCell
          {...props}
          view={view}
          row={row}
          fields={fieldsData}
          columnCount={columnCount}
          selected={view.selected}
          onClick={() => onChange?.(row.id)}
        />
      );
    },
    [data, columnCount, fieldsData, view, onChange, getCellIndex],
  );
 
  const onItemsRenderedWrap = useCallback(
    (cb) =>
      ({ visibleRowStartIndex, visibleRowStopIndex, overscanRowStopIndex, overscanRowStartIndex }) => {
        // Check if we're near the end and need to load more
        const visibleItemStopIndex = getCellIndex(visibleRowStopIndex, columnCount - 1);
 
        // Calculate how many items are visible in the current view
        const visibleItemsCount = (visibleRowStopIndex - visibleRowStartIndex + 1) * columnCount;
 
        // If we're showing items near the end of our loaded data, trigger loading
        // Use a threshold of 2 rows worth of items to trigger loading
        const threshold = Math.max(columnCount * 2, 8); // At least 8 items or 2 rows
 
        // Check if we need to load more items
        const shouldLoadMore = visibleItemStopIndex >= data.length - threshold && view.dataStore.hasNextPage;
 
        // Also check if we don't have enough items to fill the visible area
        const hasEnoughItemsForVisibleArea = visibleItemStopIndex < data.length;
        const needsMoreItemsForDisplay = !hasEnoughItemsForVisibleArea && view.dataStore.hasNextPage;
 
        // More aggressive check: if we have fewer items than columns, always load more
        const hasInsufficientItems = data.length < columnCount && view.dataStore.hasNextPage;
 
        // Special case: if we have very few items compared to columns, be extra aggressive
        const hasVeryFewItems = data.length < columnCount * 0.5 && view.dataStore.hasNextPage;
 
        if (shouldLoadMore || needsMoreItemsForDisplay || hasInsufficientItems || hasVeryFewItems) {
          loadMore?.();
        }
 
        cb({
          overscanStartIndex: overscanRowStartIndex,
          overscanStopIndex: overscanRowStopIndex,
          visibleStartIndex: visibleRowStartIndex,
          visibleStopIndex: visibleRowStopIndex,
        });
      },
    [data.length, columnCount, view.dataStore.hasNextPage, view.dataStore.loading, loadMore, getCellIndex],
  );
 
  // Check if a specific item index is loaded
  const isItemLoaded = useCallback(
    (index) => {
      const rowExists = index < data.length && !!data[index];
      const hasNextPage = view.dataStore.hasNextPage;
      return !hasNextPage || rowExists;
    },
    [data.length, view.dataStore.hasNextPage],
  );
 
  // Handle column count changes
  useEffect(() => {
    const prevColumnCount = prevColumnCountRef.current;
    const currentColumnCount = columnCount;
 
    // If column count changed and we have more columns now (showing fewer rows)
    if (prevColumnCount !== currentColumnCount) {
      prevColumnCountRef.current = currentColumnCount;
 
      // Calculate how many items we can display with the new column count
      const estimatedVisibleRows = Math.ceil(window.innerHeight / finalRowHeight);
      const estimatedVisibleItems = estimatedVisibleRows * currentColumnCount;
 
      // If we don't have enough items to fill the visible area, load more
      // Note: We don't check !view.dataStore.loading here because we want to trigger loading
      // even if something is already loading, to ensure we get enough items
      if (data.length < estimatedVisibleItems && view.dataStore.hasNextPage) {
        loadMore?.();
      }
 
      // Fallback: if we have significantly fewer items than columns, always load more
      if (data.length < currentColumnCount * 2 && view.dataStore.hasNextPage) {
        loadMore?.();
      }
 
      // Special case: if we have fewer items than the column count itself, definitely load more
      // This handles the case where there aren't enough items to even fill one row
      if (data.length < currentColumnCount && view.dataStore.hasNextPage) {
        loadMore?.();
      }
    }
  }, [columnCount, data.length, view.dataStore.hasNextPage, view.dataStore.loading, loadMore, finalRowHeight]);
 
  // Additional effect to handle cases where we have a gap between content and screen bottom
  useEffect(() => {
    // Calculate if we have enough content to fill the screen
    const estimatedVisibleRows = Math.ceil(window.innerHeight / finalRowHeight);
    const estimatedVisibleItems = estimatedVisibleRows * columnCount;
 
    // If we have significantly fewer items than needed to fill the screen, load more
    // This handles the case where there's a gap and no scroll events are firing
    if (data.length < estimatedVisibleItems * 0.8 && view.dataStore.hasNextPage) {
      loadMore?.();
    }
  }, [data.length, columnCount, view.dataStore.hasNextPage, loadMore, finalRowHeight]);
 
  // Custom loadMore function that bypasses InfiniteLoader when needed
  const customLoadMore = useCallback(() => {
    if (view.dataStore.hasNextPage && !view.dataStore.loading) {
      loadMore?.();
    }
  }, [view.dataStore.hasNextPage, view.dataStore.loading, loadMore]);
 
  // Aggressive initial loading - trigger loading immediately when we don't have enough content
  useEffect(() => {
    const estimatedVisibleRows = Math.ceil(window.innerHeight / finalRowHeight);
    const estimatedVisibleItems = estimatedVisibleRows * columnCount;
 
    // If we don't have enough items to fill the screen, start loading immediately
    if (data.length < estimatedVisibleItems && view.dataStore.hasNextPage && !view.dataStore.loading) {
      loadMore?.();
    }
  }, [data.length, columnCount, view.dataStore.hasNextPage, view.dataStore.loading, loadMore, finalRowHeight]);
 
  return (
    <GridViewProvider data={data} view={view} fields={fieldsData}>
      <div className={cn("grid-view").mod({ columnCount }).toClassName()}>
        <AutoSizer className={cn("grid-view").elem("resize").toClassName()}>
          {({ width, height }) => (
            <InfiniteLoader
              itemCount={itemCount}
              isItemLoaded={isItemLoaded}
              loadMoreItems={customLoadMore}
              threshold={Math.max(1, Math.floor(view.dataStore.pageSize / 4))}
              minimumBatchSize={Math.max(1, Math.floor(view.dataStore.pageSize / 2))}
            >
              {({ onItemsRendered, ref }) => (
                <FixedSizeGrid
                  className={cn("grid-view").elem("list").toClassName()}
                  ref={ref}
                  width={width}
                  height={height}
                  rowHeight={finalRowHeight}
                  overscanRowCount={Math.max(2, Math.floor(view.dataStore.pageSize / 2))}
                  columnCount={columnCount}
                  rowCount={loadedRows}
                  columnWidth={width / columnCount - 9.5}
                  onItemsRendered={onItemsRenderedWrap(onItemsRendered)}
                  style={{ overflowX: "hidden" }}
                >
                  {renderItem}
                </FixedSizeGrid>
              )}
            </InfiniteLoader>
          )}
        </AutoSizer>
      </div>
    </GridViewProvider>
  );
});