import React, { PropsWithChildren } from 'react';
import { Icon, IconName, SemanticColor, TypoIncludingEmoji } from '../../foundation';
import { DimensionValue, GestureResponderEvent, TouchableHighlight, View } from 'react-native';
import { ThrottleOptions, useThrottledPressHandler } from '../../internal/utils/useThrottledPressHandler';
import { isAndroid, isNotNil } from '../../internal/utils/functions';
import Animated, { LinearTransition, FadeIn, FadeOut, Easing } from 'react-native-reanimated';
import { Spin } from '../spin/Spin';
export type CommonButtonProps = {
type: 'primary' | 'secondary' | 'tertiary' | 'danger' | 'ghost_primary' | 'ghost_secondary' | 'ghost_danger';
/** 버튼 텍스트 */
label: string;
/**
* 아이콘 이름
* - 버튼 label의 좌측에 위치할 아이콘 이름을 입력합니다.
* - 'ghost_*' 타입 버튼은 우측에 위치합니다.
* - 'icon_only' 타입 버튼은 필수로 icon 이름을 입력합니다.
*/
icon?: IconName;
disabled?: boolean;
/**
* 버튼 크기
* - 값을 입력하지 않으면 'large'로 설정됩니다.
* - 각 크기별 높이 값은 아래와 같습니다.
* - 'large': 48
* - 'medium': 40
* - 'small': 36
* - 'tiny': 28
*/
size?: 'large' | 'medium' | 'small' | 'tiny'; // default: large
onPress: (e: GestureResponderEvent) => void;
/**
* 버튼 너비
* - 값을 입력하지 않으면 '100%'로 설정됩니다.
* - 'icon_only' 타입 버튼은 너비가 고정되어 있습니다.
* ex) 200, '50%'
*/
width?: DimensionValue;
flex?: number;
/**
* @deprecated
* 텍스트 크기를 자동으로 조절할지 여부
* 필요한 경우가 아니라면 텍스트 크기를 조절하지 않는 것이 좋습니다.
*/
allowFontScaling?: boolean;
/**
* 로딩중 여부 (pending state)
*/
loading?: boolean;
/**
* 로딩 시작시 좌측 아이콘 사라지는 애니메이션을 딜레이
* - 기본값 100 (ms)
*/
leftIconExitingAnimDelay?: number;
/**
* 버튼 컨테이너의 레이아웃 애니메이션 비활성화 여부
* - 기본값 true
*/
disableLayoutAnimation?: boolean;
};
/**
* 'icon_only' 타입 버튼의 size는 large로 고정됩니다.
* 'icon_only' 타입 버튼의 width는 48로 고정됩니다.
*/
export type IconButtonProps = {
type: 'icon_only';
icon: IconName;
disabled?: boolean;
onPress: (e: GestureResponderEvent) => void;
loading?: boolean;
};
export type ButtonProps = (CommonButtonProps | IconButtonProps) &
ThrottleOptions & {
/**
* 로딩 애니메이션을 포함해 버튼 내 모든 애니메이션을 제거합니다.
* 버튼이 주변 뷰 애니메이션 등에 영향을 받아 이상 동작을 하는 경우 사용합니다. (ex. 버튼이 사라질 때 잔상이 남는 현상)
*/
forceDisableAnimation?: boolean;
};
/**
* # [Component] Button
* Prisma 디자인 시스템
*
* ## Props
* - `type` 값에 따라 prop 사용 여부가 다를 수 있습니다.
*
*
* ### `type`
* - 'primary' | 'secondary' | 'tertiary' | 'danger' | 'ghost_primary' | 'ghost_secondary' | 'ghost_danger' | 'icon_only'
*
*
* ### `label`
* - 버튼에 표시할 문자열
*
*
* ### `size`
* (기본값 'large')
* - 'large' | 'medium' | 'small' | 'tiny'
*
*
* ### `disabled`
* - 버튼 비활성화 여부
* - 스타일이 변경되며 onPress 이벤트가 동작하지 않습니다.
*
*
* ### `onPress`
* - 버튼을 누르면 실행할 함수 (`disabled` true 아닐 때만)
*
*
* ### `icon`
* - 버튼 내부 좌측에 위치할 아이콘 이름을 입력합니다.
* - 'ghost_*' 타입 버튼은 아이콘이 우측에 위치합니다.
* - 'icon_only' 타입 버튼은 필수로 icon 이름을 입력합니다.
*
*
* ### `width`
* - 버튼 너비 (기본값 '100%')
* - 'icon_only' 타입 버튼은 너비가 고정되어 있습니다.
*
* ex) 200, '50%'
*
*
* ### `flex`
* - flexbox 값을 사용하려면 숫자를 전달하세요.
*
*
* ### `allowFontScaling`
* - 시스템 폰트사이즈 설정에 따라 버튼 텍스트 크기를 자동으로 조절할지 여부 (기본값 true)
*
*
* ### `throttle`
* - 버튼 throttle 옵션 (사용 방법은 타입정의 문서 참고)
*
*
* ### `loading`
* (기본값 `false`)
* - 로딩중 여부 (pending state)
* - 로딩중엔 버튼 터치가 비활성화 됩니다.
* - 'primary' | 'secondary' | 'tertiary' | 'danger' 타입은 좌측에 로딩 스피너가 표시됩니다.
*
*
* ### `leftIconExitingAnimDelay`
* (기본값 `100`ms)
* - 좌측 아이콘이 있는 버튼인 경우, 로딩이 시작되면 아이콘이 사라지면서 스피너가 보이기 시작하는데, 스피너를 더 늦게/빠르게 보이도록 조정할 수 있습니다.
* - 로딩이 빨리끝나는 기능에서 실제 로딩 소요시간 대비 작은값을 주면 아이콘이 깜빡이듯 보이는 문제를 완화할 수 있습니다.
* - 반대로 큰 값을 주면 로딩 스피너가 보이기 전에 로딩이 끝나 로딩 스피너를 안보이게 할 수 있습니다.
*
*
* ### `disableLayoutAnimation`
* (기본값 true)
* - 버튼의 로딩 스피너 등장/제거시 버튼의 너비가 자연스럽게 변하도록 애니메이션을 추가해야 할 때 false 전달하세요.
*
*
* ### `forceDisableAnimation`
* (기본값 false)
* - 로딩 애니메이션을 포함해 버튼 내 모든 애니메이션을 제거합니다.
* - 버튼이 주변 뷰 애니메이션 등에 영향을 받아 이상 동작을 하는 경우 사용합니다. (ex. 버튼이 사라질 때 잔상이 남는 현상)
*
*
* ## 컴포넌트 사용 예시
* @example
* ```tsx
* // 기본 버튼
*
*
*
*
* // 아이콘을 추가할 수 있음
*
*
*
* // 아이콘 타입 버튼
*
*
*
* // flex 컨테이너의 자식일 때 레이아웃
*
*
*
* // flex 대신 width 사용 (고정폭)
*
*
*
* // flex 대신 width 사용 (퍼센트)
*
*
*
* // disable, 로딩 처리, throttle 딜레이 조정
*
*
* ```
*/
export function Button(props: ButtonProps): React.JSX.Element {
return (
);
}
// 로딩중 버튼 텍스트의 이동 애니메이션을 위한 공통 애니메이션
const TextLinerTransition = LinearTransition.duration(300).easing(Easing.out(Easing.ease));
// 버튼 컴포넌트 크기 변화를 부드럽게 애니메이션 처리하기 위한 wrapped component
const AnimatedTouchableHighlight = Animated.createAnimatedComponent(TouchableHighlight);
const ButtonBox: React.FC> = (props) => {
const { type, onPress, disabled, loading = false, forceDisableAnimation = false } = props;
const size = type === 'icon_only' ? 'large' : props.size ?? 'large'; // default: large
const width = type === 'icon_only' ? 48 : props.width;
const flex = type === 'icon_only' ? undefined : props.flex;
const isGhostType = type === 'ghost_primary' || type === 'ghost_secondary' || type === 'ghost_danger';
const backgroundColor = (() => {
if (type === 'primary') return disabled ? SemanticColor.bg_tertiary : SemanticColor.bg_purple_enabled;
if (type === 'secondary' || type === 'icon_only') return SemanticColor.bg_primary;
if (type === 'tertiary') return disabled ? SemanticColor.bg_tertiary : SemanticColor.bg_secondary;
if (type === 'danger') return disabled ? SemanticColor.bg_tertiary : SemanticColor.bg_red_enabled;
// ghost or else
return undefined;
})();
const underlayColor = (() => {
if (type === 'primary') return SemanticColor.bg_purple_pressed;
if (type === 'secondary' || type === 'icon_only') return SemanticColor.bg_secondary;
if (type === 'tertiary') return SemanticColor.bg_quaternary;
if (type === 'danger') return SemanticColor.bg_red_pressed;
if (isGhostType) return SemanticColor.bg_secondary;
return undefined;
})();
/**
* 모든 버튼의 높이값은 고정되어있기때문에 borderWidth로 인해 높이가 변동하지 않습니다
*/
const borderStyle = (() => {
if (type === 'secondary' || type === 'icon_only') {
return {
borderColor: SemanticColor.border_secondary,
borderWidth: 1,
};
}
return { borderColor: undefined, borderWidth: undefined };
})();
const height = (() => {
if (size === 'large') return 48;
if (size === 'medium') return 40;
if (size === 'small') return 36;
return 28; //tiny
})();
const throttledPressHandler = useThrottledPressHandler(onPress, props.throttle);
const alignSelf = (() => {
if (type === 'icon_only') return undefined;
// flex, width가 설정되어있을 경우, 사용자가 너비를 조절하기 위한 의도가 있으므로 content 영역만큼 너비를 갖지 않습니다
if (isNotNil(flex) || isNotNil(width)) return undefined;
// content 영역만큼 너비를 갖도록 설정합니다
return 'flex-start';
})();
// 버튼 컨테이너 크기 변화에 애니메이션 적용 여부
const animationNotNeeded = type === 'icon_only' || isGhostType || (props.disableLayoutAnimation ?? true);
// 버튼 내 모든 애니메이션 강제 제거
const TouchableOrAnimatedTouchable = forceDisableAnimation ? TouchableHighlight : AnimatedTouchableHighlight;
return (
{props.children}
);
};
const ButtonContent: React.FC> = (props) => {
const { type, disabled, icon, loading = false, forceDisableAnimation = false } = props;
const textColor = (() => {
if (type === 'primary') return disabled ? 'text_tertiary' : 'text_white';
if (type === 'secondary' || type === 'icon_only') return disabled ? 'text_quaternary' : 'text_primary';
if (type === 'tertiary') return disabled ? 'text_tertiary' : 'text_primary';
if (type === 'danger') return disabled ? 'text_tertiary' : 'text_white';
if (type === 'ghost_primary') return disabled ? 'text_quaternary' : 'text_purple';
if (type === 'ghost_secondary') return disabled ? 'text_quaternary' : 'text_secondary';
if (type === 'ghost_danger') return disabled ? 'text_quaternary' : 'state_text_error';
return undefined;
})();
/**
* 'icon_only' 타입 버튼은 아이콘만 표시하며 early return.
*/
if (type === 'icon_only') {
return (
);
}
const size = props.size ?? 'large'; // default: large
const allowFontScaling = props.allowFontScaling !== false; // default: true
const typoType = (() => {
if (size === 'large') return 'button_16_semibold';
if (size === 'tiny') return 'button_12_semibold';
return 'button_14_semibold';
})();
const gapBetweenIconAndLabel = (() => {
if (size === 'medium' || size === 'small' || size === 'tiny') return 4;
return 8; // large
})();
const iconSize = (() => {
if (size === 'medium' || size === 'small') return 16;
if (size === 'tiny') return 14;
return 20; // large
})();
const isGhostType = type === 'ghost_primary' || type === 'ghost_secondary' || type === 'ghost_danger';
// 버튼 컨테이너 크기 변화에 애니메이션 적용 여부
const animationNotNeeded = isGhostType;
// 버튼 내 모든 애니메이션 강제 제거
const ViewOrAnimatedView = forceDisableAnimation ? View : Animated.View;
const leftIcon = icon && !isGhostType && (
// 등장 애니메이션은 현 구현에서 지원할 수 없음. 화면 진입시 아이콘이 즉시 보여야 하는데, entering 넣으면 로딩에 관계없이 스르륵 나타남.
);
const leftIconOrSpin = (() => {
if (animationNotNeeded) return null;
if (!loading) {
return leftIcon;
} else {
return (
);
}
})();
const rightIcon = icon && isGhostType && (
);
const paddingHorizontal = (() => {
if (size === 'large') return 16;
if (size === 'medium' || size === 'small') return 12;
return 8; // tiny
})();
const ellipsizeMode = (() => {
// 로딩 표현 중일 땐 말줄임 하는게 디자인 요구사항
if (loading) return 'tail';
// HACK: 원래 요구사항은 플랫폼 분기 없이 'clip' 적용하여 말줄임 없이 자르는 것이었으나 안드로이드는 'tail' 처리함
// - 안드로이드는 단어 단위로 끝을 자름. 말줄임 없이 자르면 길어서 잘린건지 텍스트가 원래 짧은건지 구분이 안 됨.
return isAndroid() ? 'tail' : 'clip';
})();
return (
{leftIconOrSpin}
라벨 변경시, 레이아웃이 변경되면서 불필요한 애니메이션 발생하는 문제 해소
key={props.label ?? 'empty'}
layout={animationNotNeeded ? undefined : TextLinerTransition}
style={{ flexShrink: 1 }}>
{props.label ?? ''}
{rightIcon}
);
};