All files / app/(tabs)/forum/components/community MasonryFeed.tsx

90% Statements 36/40
66.66% Branches 16/24
88.88% Functions 8/9
89.47% Lines 34/38

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                        1x 1x 1x 1x                           1x           1x             1x           1x               1x                 1x             12x 6x   6x 6x 6x 6x 6x     6x                           7x   7x   7x 1x 1x 1x 1x       7x                                   7x 1x             6x 2x                         4x                                             8x   8x                                 1x  
/**
 * MasonryFeed - 瀑布流布局组件
 *
 * Pinterest/小红书风格的双列瀑布流
 */
 
import React, { memo, useCallback, useMemo, useState } from 'react';
import { Dimensions, RefreshControl, ScrollView } from 'react-native';
import { styled, YStack, Stack, Spinner, Text } from 'tamagui';
 
import { PostCard, PostCardData } from './PostCard';
 
const { width: SCREEN_WIDTH } = Dimensions.get('window');
const COLUMN_GAP = 12;
const HORIZONTAL_PADDING = 16;
const COLUMN_WIDTH = (SCREEN_WIDTH - HORIZONTAL_PADDING * 2 - COLUMN_GAP) / 2;
 
export interface MasonryFeedProps {
  data: PostCardData[];
  onPostPress?: (post: PostCardData) => void;
  onLikePress?: (post: PostCardData) => void;
  onAuthorPress?: (author: PostCardData['author']) => void;
  onRefresh?: () => Promise<void>;
  onEndReached?: () => void;
  isLoading?: boolean;
  isRefreshing?: boolean;
  ListEmptyComponent?: React.ReactNode;
}
 
const FeedContainer = styled(Stack, {
  name: 'FeedContainer',
  flex: 1,
  backgroundColor: '$backgroundSubtle',
});
 
const ColumnsContainer = styled(Stack, {
  name: 'ColumnsContainer',
  flexDirection: 'row',
  paddingHorizontal: HORIZONTAL_PADDING,
  gap: COLUMN_GAP,
});
 
const Column = styled(YStack, {
  name: 'MasonryColumn',
  flex: 1,
  gap: COLUMN_GAP,
});
 
const LoadingContainer = styled(YStack, {
  name: 'LoadingContainer',
  flex: 1,
  alignItems: 'center',
  justifyContent: 'center',
  padding: '$8',
});
 
const EmptyContainer = styled(YStack, {
  name: 'EmptyContainer',
  flex: 1,
  alignItems: 'center',
  justifyContent: 'center',
  padding: '$8',
  gap: '$3',
});
 
const EmptyText = styled(Text, {
  name: 'EmptyText',
  fontSize: '$4',
  textAlign: 'center',
});
 
function distributeToColumns(data: PostCardData[], columnCount: number): PostCardData[][] {
  const columns: PostCardData[][] = Array.from({ length: columnCount }, () => []);
  const columnHeights: number[] = Array(columnCount).fill(0);
 
  data.forEach((item) => {
    const shortestColumn = columnHeights.indexOf(Math.min(...columnHeights));
    columns[shortestColumn].push(item);
    const estimatedHeight = (item.imageHeight || COLUMN_WIDTH * 1.2) + 80;
    columnHeights[shortestColumn] += estimatedHeight;
  });
 
  return columns;
}
 
function MasonryFeedComponent({
  data,
  onPostPress,
  onLikePress,
  onAuthorPress,
  onRefresh,
  onEndReached,
  isLoading = false,
  isRefreshing = false,
  ListEmptyComponent,
}: MasonryFeedProps) {
  const [refreshing, setRefreshing] = useState(false);
 
  const columns = useMemo(() => distributeToColumns(data, 2), [data]);
 
  const handleRefresh = useCallback(async () => {
    Eif (onRefresh) {
      setRefreshing(true);
      await onRefresh();
      setRefreshing(false);
    }
  }, [onRefresh]);
 
  const handleScroll = useCallback(
    (event: {
      nativeEvent: {
        contentOffset: { y: number };
        contentSize: { height: number };
        layoutMeasurement: { height: number };
      };
    }) => {
      const { contentOffset, contentSize, layoutMeasurement } = event.nativeEvent;
      const isCloseToBottom =
        contentOffset.y + layoutMeasurement.height >= contentSize.height - 200;
      if (isCloseToBottom && onEndReached) {
        onEndReached();
      }
    },
    [onEndReached]
  );
 
  if (isLoading && data.length === 0) {
    return (
      <LoadingContainer>
        <Spinner size="large" color="$primary" />
      </LoadingContainer>
    );
  }
 
  if (!isLoading && data.length === 0) {
    return (
      <EmptyContainer>
        {ListEmptyComponent || (
          <>
            <Text fontSize={48}>🐾</Text>
            <EmptyText>还没有帖子</EmptyText>
            <EmptyText fontSize="$3">成为第一个分享的人吧!</EmptyText>
          </>
        )}
      </EmptyContainer>
    );
  }
 
  return (
    <FeedContainer>
      <ScrollView
        showsVerticalScrollIndicator={false}
        onScroll={handleScroll}
        scrollEventThrottle={16}
        refreshControl={
          onRefresh ? (
            <RefreshControl
              refreshing={refreshing || isRefreshing}
              onRefresh={handleRefresh}
              tintColor="#7FB093"
              colors={['#7FB093']}
            />
          ) : undefined
        }
        contentContainerStyle={{
          paddingTop: COLUMN_GAP,
          paddingBottom: 100,
        }}
      >
        <ColumnsContainer>
          {columns.map((columnData, columnIndex) => (
            <Column key={`column-${columnIndex}`}>
              {columnData.map((item) => (
                <PostCard
                  key={item.id}
                  data={item}
                  columnWidth={COLUMN_WIDTH}
                  onPress={onPostPress}
                  onLikePress={onLikePress}
                  onAuthorPress={onAuthorPress}
                />
              ))}
            </Column>
          ))}
        </ColumnsContainer>
      </ScrollView>
    </FeedContainer>
  );
}
 
export const MasonryFeed = memo(MasonryFeedComponent);