All files / apps/host/src/screens/Home index.tsx

97.97% Statements 97/99
85% Branches 51/60
93.1% Functions 27/29
100% Lines 91/91

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 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                                                                                      2x                       17x                                                                           2x                   2x 17x 17x 17x 17x 17x 17x 17x   17x   17x 17x 17x 17x   17x             17x   17x 17x   17x 1x     17x 1x     17x 17x   2x 2x         17x 17x   17x 5x     17x 84x 84x       17x 17x 2x 2x 2x       17x 1x 1x   1x   1x         1x     17x         17x   4x 1x         17x         4x 1x     4x 1x 1x       1x           17x 17x 4x                     13x     17x 1x     17x   2x 1x 1x 1x           17x   56x         1x             1x               17x   2x         17x 17x       17x 17x               17x 17x         17x         17x   17x 1x                     16x 3x                                       13x 2x                                     11x                                             17x                                     2x                                    
import React, { useCallback, useEffect, useMemo, useRef } from 'react';
import Carousel, { ICarouselInstance } from 'react-native-reanimated-carousel';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import {
  ActivityIndicator,
  ImageSourcePropType,
  InteractionManager,
  StyleSheet,
  Text,
  View,
} from 'react-native';
 
import { useFocusEffect } from '@react-navigation/native';
 
import { Avatar } from '@repo/ui/components/Avatar';
import { Button } from '@repo/ui/components/Button';
import { makeStyles } from '@repo/ui/themes/makeStyles';
import { useTheme } from '@repo/ui/themes/ThemeContext';
import type { Theme } from '@repo/ui/themes/types';
import { textStyles } from '@repo/ui/themes/typography';
 
import { REALLOCATION_DESTINATION_HOME } from '@repo/constants/request';
import { SCREENS } from '@repo/constants/screens';
 
import { useDisabledFeatures } from '@repo/hooks/useFlags';
 
import { BalloonPendingRequest } from '@/components/BalloonPendingRequest';
import BalloonRequest from '@/components/BalloonRequest';
 
import { useAuth } from '@/contexts/AuthContext';
import { useFabHidden, useFabStateSelector, useSetFabOffset } from '@/contexts/FabContext';
 
import { useRefreshNotifications } from '@/hooks/notifications/useRefreshNotifications';
import { useRegistrationData } from '@/hooks/useRegistrationData';
import { useGetRequestsWithoutPagination } from '@/hooks/useRequest';
 
import { SCREEN_WIDTH } from '@/utils/dimensions';
 
import { CACHE_TIME } from '@/constants/apis';
 
import type { AppStackParamList, AppStackScreenProps } from '@/types/navigation';
import { RequestCategory, RequestStatus } from '@/types/request';
 
const ITEM_WIDTH = SCREEN_WIDTH + 80;
 
interface MenuItem {
  id: string;
  title?: string;
  subtitle?: string;
  mascot: ImageSourcePropType;
  path?: Exclude<keyof AppStackParamList, typeof SCREENS.REQUEST_DETAIL>;
  isPending?: boolean;
  pendingCount?: number;
}
 
const getMenuItems = (assets: Theme['assets']): MenuItem[] => [
  {
    id: '1',
    title: 'TIME OFF',
    subtitle: 'YOUR TEAMMATES WILL\nMISS YOU A LOT',
    mascot: assets.timeOffMascot,
    path: SCREENS.TIME_OFF,
  },
  {
    id: '2',
    title: 'REALLOCATION',
    subtitle: "CHANGING YOUR SEAT DOESN'T\nCHANGE YOUR MIND",
    mascot: assets.reallocationMascot,
    path: SCREENS.REALLOCATION,
  },
  {
    id: '3',
    title: 'MEAL\nRESERVATION',
    subtitle: 'CODING IS EASIER ON A\nFULL STOMACH',
    mascot: assets.mealMascot,
    path: SCREENS.MEAL_RESERVATION,
  },
  {
    id: '4',
    title: 'BOOK A ROOM',
    subtitle: 'SHHH! LET KEEP SECRET\nTHING IN SECRET ROOM',
    mascot: assets.bookRoomMascot,
    path: SCREENS.BOOK_ROOM,
  },
  {
    id: '5',
    title: 'MAINTENANCE',
    subtitle: 'THERE IS NOTHING BROKEN,\nTHAT IS JUST A FEATURE',
    mascot: assets.maintenanceMascot,
    path: SCREENS.MAINTENANCE,
  },
];
 
const SCREEN_CATEGORY_MAP: Partial<Record<string, RequestCategory>> = {
  [SCREENS.TIME_OFF]: RequestCategory.TIME_OFF,
  [SCREENS.REALLOCATION]: RequestCategory.REALLOCATION,
  [SCREENS.MEAL_RESERVATION]: RequestCategory.MEAL_RESERVATION,
  [SCREENS.BOOK_ROOM]: RequestCategory.BOOK_ROOM,
  [SCREENS.MAINTENANCE]: RequestCategory.MAINTENANCE,
};
 
type HomeScreenProps = AppStackScreenProps<typeof SCREENS.HOME>;
 
export const HomeScreen = ({ navigation, route }: HomeScreenProps) => {
  const { theme } = useTheme();
  const errorStyles = useErrorStyles();
  const menuItems = useMemo(() => getMenuItems(theme.assets), [theme.assets]);
  const insets = useSafeAreaInsets();
  const paddingTop = insets.top;
  const fabOffset = useFabStateSelector(s => s.fabOffset);
  const setFabOffset = useSetFabOffset();
 
  const { allowHomeAccess = false, scrollIndex: savedScrollIndex } = route.params || {};
 
  const carouselRef = useRef<ICarouselInstance>(null);
  const currentIndexRef = useRef(0);
  const isRefreshingFromNotificationRef = useRef(false);
  const isRefreshingFromResolveRef = useRef(allowHomeAccess);
 
  const { data, isLoading, isError, refetch, isRefetching } = useGetRequestsWithoutPagination({
    status: RequestStatus.PENDING,
    actionable: true,
    showHistories: true,
    staleTime: CACHE_TIME.MEDIUM,
  });
 
  const pendingCount = data?.items?.length || 0;
 
  const { user } = useAuth();
  const { meInfo } = useRegistrationData(user?.email || '');
 
  const handlePressProfile = useCallback(() => {
    navigation.navigate(SCREENS.PROFILE);
  }, [navigation]);
 
  const handleRetry = useCallback(() => {
    refetch();
  }, [refetch]);
 
  const { value: disableFeatures } = useDisabledFeatures();
  const getRealIndex = useCallback(
    (index: number) => {
      const len = menuItems.length;
      return ((index % len) + len) % len;
    },
    [menuItems.length],
  );
 
  const filteredMenuItems = useMemo(() => {
    let items = menuItems;
 
    if (meInfo?.room?.id?.toUpperCase() === REALLOCATION_DESTINATION_HOME.toUpperCase()) {
      items = items.filter(item => item.path !== SCREENS.MEAL_RESERVATION);
    }
 
    return items.filter(item => {
      const category = item.path ? SCREEN_CATEGORY_MAP[item.path] : undefined;
      return !category || !disableFeatures[category];
    });
  }, [menuItems, meInfo?.room?.id, disableFeatures]);
 
  useEffect(() => {
    if (allowHomeAccess) {
      isRefreshingFromResolveRef.current = true;
      const t = setTimeout(() => (isRefreshingFromResolveRef.current = false), 1000);
      return () => clearTimeout(t);
    }
  }, [allowHomeAccess]);
 
  const handleNotificationRefresh = useCallback(async () => {
    isRefreshingFromNotificationRef.current = true;
    const index = currentIndexRef.current;
 
    await refetch();
 
    navigation.setParams({
      allowHomeAccess,
      scrollIndex: index,
    });
 
    setTimeout(() => (isRefreshingFromNotificationRef.current = false), 100);
  }, [refetch, navigation, allowHomeAccess]);
 
  useRefreshNotifications({
    onRefresh: handleNotificationRefresh,
    isRefetching,
  });
 
  useFocusEffect(
    useCallback(() => {
      if (fabOffset !== 0) {
        setFabOffset(0);
      }
    }, [fabOffset, setFabOffset]),
  );
 
  useFocusEffect(
    useCallback(() => {
      // `isRefetching` is a dependency, so refetching on a query that stays empty
      // would re-run this effect and refetch again — forever. `isError` breaks that
      // loop; recovery goes through the explicit retry button instead.
      if (!data && !isError) {
        refetch();
      }
 
      if (savedScrollIndex !== undefined && !allowHomeAccess && !isLoading && !isRefetching) {
        InteractionManager.runAfterInteractions(() => {
          carouselRef.current?.scrollTo({
            index: savedScrollIndex,
            animated: false,
          });
          currentIndexRef.current = savedScrollIndex;
        });
      }
    }, [refetch, data, isError, savedScrollIndex, allowHomeAccess, isLoading, isRefetching]),
  );
 
  const menuItemsWithPending = useMemo(() => {
    if (pendingCount > 0) {
      return [
        ...filteredMenuItems,
        {
          id: '0',
          isPending: true,
          pendingCount,
          mascot: theme.assets.pendingMascot,
        },
      ];
    }
 
    return filteredMenuItems;
  }, [pendingCount, filteredMenuItems, theme.assets]);
 
  const handlePressPendingRequests = useCallback(() => {
    navigation.navigate(SCREENS.PENDING_REQUESTS);
  }, [navigation]);
 
  const handlePressMenuItem = useCallback(
    (item: MenuItem) => {
      if (item.isPending) {
        navigation.navigate(SCREENS.PENDING_REQUESTS);
      } else Eif (item.path) {
        navigation.navigate(item.path);
      }
    },
    [navigation],
  );
 
  const renderItem = useCallback(
    ({ item }: { item: MenuItem }) => (
      <View style={styles.page}>
        {item.isPending ? (
          <BalloonPendingRequest
            pendingCount={item.pendingCount || 0}
            image={item.mascot}
            onPress={() => handlePressMenuItem(item)}
          />
        ) : (
          <BalloonRequest
            title={item.title!}
            subtitle={item.subtitle!}
            image={item.mascot}
            onPress={() => handlePressMenuItem(item)}
          />
        )}
      </View>
    ),
    [handlePressMenuItem],
  );
 
  const handleSnapToItem = useCallback(
    (index: number) => {
      currentIndexRef.current = getRealIndex(index);
    },
    [getRealIndex],
  );
 
  const containerStyle = useMemo(
    () => [styles.container, { paddingTop, backgroundColor: theme.colors.background.page }],
    [paddingTop, theme.colors.background.page],
  );
 
  const loadingContainerStyle = useMemo(
    () => [
      styles.container,
      styles.loadingContainer,
      { backgroundColor: theme.colors.background.page },
    ],
    [theme.colors.background.page],
  );
 
  const avatarContainerStyle = useMemo(
    () => [styles.avatarContainer, { top: paddingTop }],
    [paddingTop],
  );
 
  const shouldShowLoading =
    (!data && isLoading) ||
    (isRefetching &&
      (isRefreshingFromNotificationRef.current || isRefreshingFromResolveRef.current));
 
  // Hide the chat FAB while the Home screen has no content to sit on top of
  useFabHidden(shouldShowLoading || isError);
 
  if (shouldShowLoading) {
    return (
      <View
        style={loadingContainerStyle}
        accessibilityRole="progressbar"
        accessibilityLabel="Loading"
      >
        <ActivityIndicator size="large" color={theme.colors.ui.blue} />
      </View>
    );
  }
 
  if (isError) {
    return (
      <View style={loadingContainerStyle} testID="home-error">
        <Text style={errorStyles.title} accessibilityRole="header">
          Something happened!
        </Text>
        <Text style={errorStyles.message}>We could not load your requests.</Text>
        <Button
          testID="home-error-retry"
          onPress={handleRetry}
          style={errorStyles.button}
          accessibilityRole="button"
          accessibilityLabel="Try again"
          accessibilityHint="Reloads your pending requests"
        >
          Try Again
        </Button>
      </View>
    );
  }
 
  if (pendingCount && !allowHomeAccess) {
    return (
      <View style={containerStyle}>
        <View style={avatarContainerStyle}>
          <Avatar
            uri={user?.photoURL || undefined}
            name={user?.displayName || 'User'}
            size={theme.metrics.spacing[11]}
            onPress={handlePressProfile}
          />
        </View>
        <BalloonPendingRequest
          pendingCount={pendingCount}
          image={theme.assets.pendingMascot}
          onPress={handlePressPendingRequests}
        />
      </View>
    );
  }
 
  return (
    <View style={containerStyle}>
      <View style={avatarContainerStyle}>
        <Avatar
          uri={user?.photoURL || undefined}
          name={user?.displayName || 'User'}
          size={theme.metrics.spacing[11]}
          onPress={handlePressProfile}
        />
      </View>
      <Carousel
        ref={carouselRef}
        data={menuItemsWithPending}
        width={ITEM_WIDTH}
        loop
        pagingEnabled
        onSnapToItem={handleSnapToItem}
        renderItem={renderItem}
      />
    </View>
  );
};
 
const useErrorStyles = makeStyles(theme => ({
  title: {
    ...textStyles.content.semiBold,
    fontSize: theme.metrics.textSize[24],
    fontWeight: theme.metrics.fontWeight.bold,
    color: theme.colors.text.heading,
  },
  message: {
    ...textStyles.content.regular,
    fontSize: theme.metrics.textSize[16],
    color: theme.colors.text.muted,
    marginTop: theme.metrics.spacing[2],
    marginBottom: theme.metrics.spacing[6],
  },
  button: {
    width: theme.metrics.spacing[25],
  },
}));
 
const styles = StyleSheet.create({
  loadingContainer: {
    justifyContent: 'center',
  },
  container: {
    flex: 1,
    alignItems: 'center',
  },
  page: {
    alignItems: 'center',
    flex: 1,
  },
  avatarContainer: {
    position: 'absolute',
    left: 12,
    zIndex: 20,
  },
});