import React, { ComponentProps, useCallback, useImperativeHandle, useRef, useState } from 'react'; import { NativeScrollEvent, NativeSyntheticEvent, ScrollView, View } from 'react-native'; import { Gradient, SemanticColor } from '../../foundation'; import { usePrevious } from 'react-use-native'; import { getTabsHeight } from './utils'; import { LayoutStyleProp } from '../../internal/utils/utilTypes'; import { noop } from '../../internal/utils/functions'; import { TabItemView } from './TabItemView'; import { TabItem } from './types'; import { ContainerBottomDivider } from '../utils/ContainerBottomDivider'; import { AnimatedActiveDivider } from './AnimatedActiveDivider'; interface Props { type: 'hug' | 'fill'; list: TabItem[]; size: 'large' | 'medium'; activeIndex: number; showDivider?: boolean; showActiveDivider?: boolean; scrollContentRightExtraPadding?: number; bounces?: ComponentProps['bounces']; removeScreenPadding?: boolean; } /** * # Tabs 컴포넌트의 Ref 인터페이스 * * ScrollView 컴포넌트 ref 객체를 상속하므로 * `hug` 타입일 경우에만 동작합니다. (fill 타입은 ScrollView 없음) * * ### scrollToIndex * - 특정 인덱스의 아이템이 ScrollView 수평 중앙에 위치하도록 스크롤합니다. */ export interface TabsRef extends ScrollView { scrollToIndex: (index: number, animated?: boolean) => void; } /** * # Tabs * * * ## Props * * ### `type` * - `'hug'`: 탭 아이템의 너비가 내용에 맞춰 조정됨. 스크롤 가능 * - `'fill'`: 탭 아이템마다 동일한 너비를 가짐. 스크롤 불가능 * * * ### `list` * - 탭 아이템 목록. 각 아이템 데이터는 `TabItem` 타입에 호환되어야 합니다. * * * ### `size` * - `'large'`: 컨테이너 높이 52dp * - `'medium'`: 컨테이너 높이 48dp * * * ### `activeIndex` * - 선택한 탭 인덱스 * * * ### `showDivider` (optional) * - 컨테이너 하단 테두리 표시 여부 (기본값 true) * * * ### `showActiveDivider` (optional) * - 선택된 탭 아이템 하단 굵은 테두리 표시 여부 (기본값 true) * * * ### `scrollContentRightExtraPadding` (optional) * - 'hug' 타입일 경우 사용 가능 * - 마지막 탭 아이템 우측에 추가 여백을 줘야 할 때 사용 (디자인시스템 스펙엔 없는 기능) * * * ### `bounces` (optional) * - 'hug' 타입일 경우 사용 가능 * - ScrollView bounces prop 조정 (기본값 true) (디자인시스템에 고려하지는 않은 속성) * * * ### `removeScreenPadding` (optional) * - Tabs 컴포넌트가 스크린 폭을 꽉 채우지 않는 사용 사례가 생길 것에 대비해, 내장된 스크린 패딩을 제거하는 옵션을 임의로 추가했습니다. * * * @example * ```tsx * * // 실제로 사용할 때는 ScrollView/FlatList 와 함께 사용되는 경우가 많을텐데, 예제는 컴포넌트 사용 방법만 간단히 설명하겠습니다. * * // hug 타입 * function HugTypeExampleComponent() { * const [activeIndex, setActiveIndex] = useState(0); * * const list: TabItem[] = [ * { label: '고수 정보', onPress: setActiveIndex, iconName: 'home_filled' }, * { label: '포트폴리오', onPress: setActiveIndex, disabled: true }, * { label: '사진/동영상', onPress: setActiveIndex, redDot: true }, * { * label: '리뷰', * count: props.count, * onPress: setActiveIndex, * // 슬롯의 영역 높이는 컨테이너 높이와 같으므로 컨텐츠의 수직 정렬을 조정해야 할 수 있습니다. * rightSlot: ( * * * * ), * }, * // ... * ] * * return ( * * ); * } * * * // fill 타입 * function FillTypeExampleComponent() { * const [activeIndex, setActiveIndex] = useState(0); * * const list: TabItem[] = [ * { label: '숨고생활', onPress: setActiveIndex, redDot: true }, * { * label: '고수센터', * onPress: setActiveIndex, * rightSlot: ( * // 슬롯의 영역 높이는 컨테이너 높이와 같으므로 컨텐츠의 수직 정렬을 조정해야 할 수 있습니다. * * * * ), * }, * ] * * return ( * * ); * } * ``` */ export const Tabs = React.forwardRef( ( { type, list, size, activeIndex, showDivider = true, showActiveDivider = true, scrollContentRightExtraPadding, bounces = true, layoutStyle, removeScreenPadding, }, ref, ) => { const SCREEN_HORIZONTAL_PADDING = removeScreenPadding ? 0 : 16; // 각 탭 아이템들의 레이아웃 정보 획득/갱신이 완료될 때 재렌더를 한번 일으키기 위한 state const [isLayoutDone, setIsLayoutDone] = useState(false); // 각 탭 아이템들의 레이아웃 정보 저장 const itemsLayout = useRef<{ x: number; width: number }[]>([]); // 스크롤뷰가 차지하는 뷰 영역 너비 const scrollViewWidth = useRef(0); // 스크롤뷰 내부 컨텐츠 너비 const scrollContentWidth = useRef(0); const scrollViewRef = useRef(null); const { shouldShowRightGradient, handleScroll } = useShouldShowRightGradient(type); // 특정 인덱스의 아이템이 ScrollView 수평 중앙에 위치하도록 스크롤하는 함수 const scrollToIndex = useCallback((index: number, animated = true) => { // '누른 아이템의 x 좌표' (여기로만 스크롤하면 화면 좌측에 아이템 좌측이 붙음) const currentX: number = itemsLayout.current[index]?.x ?? 0; // 누른 아이템의 너비 절반을 더하여 아이템의 중앙을 나타내는 좌표로 만듦 (여기로 스크롤하면 화면 좌측에 아이템 중앙이 위치함) const itemMiddleX = currentX + (itemsLayout.current[index]?.width ?? 0) / 2; // '누른 아이템의 x 좌표'가 컨테이너 중앙으로 오도록 scrollViewWidth/2 만큼 덜 스크롤 해야 함 const destination = itemMiddleX - scrollViewWidth.current / 2; scrollViewRef.current?.scrollTo({ x: destination, animated }); }, []); const prevLayoutDone = usePrevious(isLayoutDone); const prevActiveIndex = usePrevious(activeIndex); if ( // 탭 아이템들이 레이아웃 계산이 완료될때마다 활성화된 인덱스로 스크롤 (isLayoutDone !== prevLayoutDone && isLayoutDone === true) || // 활성화된 인덱스 변경될 때마다 해당 인덱스로 스크롤 activeIndex !== prevActiveIndex ) { scrollToIndex(activeIndex); } useImperativeHandle( ref, () => { if (!scrollViewRef.current || !isLayoutDone) return null; return Object.assign(scrollViewRef.current, { scrollToIndex, }); }, [isLayoutDone, scrollToIndex], ); // 각각의 탭 아이템의 레이아웃 이벤트 발생시 호출되는 핸들러 const handleTabItemLayout = (index: number) => (x: number, width: number) => { // 탭 아이템에 레이아웃 변경이 일어나면 인덱스 순서대로 이 함수가 실행됨 itemsLayout.current[index] = { x, width }; if (index === list.length - 1) { // 마운트시점이든 특정 아이템이 변할때든 마지막 아이템에서 이 함수가 호출되면 모든 아이템들의 레이아웃이 끝났다고 볼 수 있음. setIsLayoutDone(true); } else { // 마지막 아이템이 아닌 아이템에서 이 함수가 호출됐다는건 레이아웃 재계산이 필요하다는 뜻 setIsLayoutDone(false); } }; const isScrollContentOverflow = scrollContentWidth.current > scrollViewWidth.current; return ( {showDivider ? : null} {type === 'hug' ? ( { scrollViewWidth.current = nativeEvent.layout.width; }} onContentSizeChange={(w) => { scrollContentWidth.current = w; }} onScroll={handleScroll} scrollEventThrottle={16} // (참고) throttle 16 초과하면 빠른 스크롤시 그래디언트가 사라지지 않음 contentContainerStyle={{ paddingHorizontal: SCREEN_HORIZONTAL_PADDING, gap: 16, paddingRight: scrollContentRightExtraPadding, }} horizontal bounces={bounces} showsHorizontalScrollIndicator={false}> {list.map((item, index) => { return ( ); })} {showActiveDivider ? ( ) : null} ) : ( {list.map((item, index) => { return ( ); })} {showActiveDivider ? ( ) : null} )} {type === 'hug' && isScrollContentOverflow ? ( ) : null} ); }, ); function useShouldShowRightGradient(type: 'hug' | 'fill') { const [shouldShowRightGradient, setShouldShowRightGradient] = useState(true); const handleScroll = useCallback((e: NativeSyntheticEvent) => { const TOLERANCE = 1; const viewportWidth = Math.floor(e.nativeEvent.layoutMeasurement.width); const contentWidth = Math.floor(e.nativeEvent.contentSize.width); const currentPositionX = Math.floor(e.nativeEvent.contentOffset.x); setShouldShowRightGradient(currentPositionX + viewportWidth < contentWidth - TOLERANCE); }, []); const isHugType = type === 'hug'; return { shouldShowRightGradient: isHugType ? shouldShowRightGradient : false, handleScroll: isHugType ? handleScroll : noop, }; }