Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[FEAT] BottomSheet 컴포넌트, 스토리북 #41

Merged
merged 21 commits into from
Nov 17, 2024
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
5af13cf
[FEAT] BottomSheet 컴포넌트, 스토리북
houony Nov 8, 2024
3d3cf25
[REFACTOR] BottomSheet 컴포넌트
houony Nov 10, 2024
7bf1a90
Merge branch 'main' of https://github.com/Findy-org/FINDY_FE into fea…
houony Nov 10, 2024
366e0cb
[CHORE] BottomSheet 컴포넌트, 스토리북
houony Nov 10, 2024
70ffaf2
refactor : add error handling, reduce redundancy
houony Nov 11, 2024
eb7d761
refactor: add MouseEvent and TouchEvent
houony Nov 11, 2024
beeb54a
Merge branch 'main' of https://github.com/Findy-org/FINDY_FE into fea…
houony Nov 11, 2024
a92c437
chore : remove try-catch
houony Nov 11, 2024
c1a3f12
refactor : remove calculation of drag velocity
houony Nov 11, 2024
c63dfac
Merge branch 'main' of https://github.com/Findy-org/FINDY_FE into fea…
houony Nov 11, 2024
2279cf6
refactor : improve BottomSheet animation and positioning
houony Nov 12, 2024
631810a
refactor : optimize drag handler with requestAnimationFrame
houony Nov 12, 2024
90d4e6a
refactor : remove unnecessary code, change handleDragEnd logic
houony Nov 12, 2024
f273b49
refactor : remove onClose
houony Nov 12, 2024
f8f8c1f
refactor : add early return at handleDragEnd
houony Nov 12, 2024
390eb14
refactor : change style to tailwind, change dragElastic
houony Nov 12, 2024
5bf5e10
refactor : change drag amount
houony Nov 13, 2024
489baf2
refactor : move BottomSheet framer setting to motions.ts
houony Nov 14, 2024
b2f0822
refactor : remove onClose, add BottomSheetHeader, remove backdrop, up…
houony Nov 14, 2024
f3ff5ab
chore : remove react-use-measure, debounce
houony Nov 15, 2024
a4d2f8b
refactor : remove AnimatePresence, setTimeout
houony Nov 15, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions .pnp.cjs

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

38 changes: 38 additions & 0 deletions src/components/common/BottomSheet/BottomSheet.stories.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
/* eslint-disable no-restricted-exports */
import { useState } from 'react';
import type { Meta, StoryObj } from '@storybook/react';

import { BottomSheet } from '.';
import { Button } from '../Button';

const meta = {
title: 'components/common/BottomSheet',
component: BottomSheet,
tags: ['autodocs'],
} satisfies Meta<typeof BottomSheet>;

export default meta;
type Story = StoryObj<typeof BottomSheet>;

export const Basic: Story = {
render: () => {
const [isOpen, setIsOpen] = useState(false);

const handleClickBottomSheet = () => setIsOpen(!isOpen);

return (
<>
<Button variant="primary" size="medium" onClick={handleClickBottomSheet}>
Open BottomSheet
</Button>
{isOpen && (
<BottomSheet resetTrigger={isOpen}>
<div className="flex flex-col gap-6 items-center">
<div>Contents ...</div>
</div>
</BottomSheet>
)}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

BottomSheet 렌더링 로직 개선이 필요합니다

  1. 조건부 렌더링({isOpen && ...})은 애니메이션 처리에 문제를 일으킬 수 있습니다. BottomSheet가 닫힐 때 애니메이션이 완료되기 전에 컴포넌트가 제거될 수 있습니다.

  2. resetTrigger prop의 용도와 네이밍이 명확하지 않습니다. 이전 리뷰에서 논의된 대로 boolean 타입으로 변경되었지만, 더 명확한 prop 이름이 필요해 보입니다.

-        {isOpen && (
-          <BottomSheet resetTrigger={isOpen}>
+        <BottomSheet 
+          isOpen={isOpen} 
+          onClose={() => setIsOpen(false)}
+        >
           <div className="flex flex-col gap-6 items-center">
             <div>Contents ...</div>
           </div>
-          </BottomSheet>
-        )}
+        </BottomSheet>

Committable suggestion skipped: line range outside the PR's diff.

</>
);
},
};
10 changes: 10 additions & 0 deletions src/components/common/BottomSheet/BottomSheet.types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { ComponentPropsWithoutRef, ReactNode } from 'react';

export type Props = ComponentPropsWithoutRef<'div'> & {
resetTrigger?: boolean;
children?: ReactNode;
keemsebin marked this conversation as resolved.
Show resolved Hide resolved
};

export type DragInfo = {
delta: { x: number; y: number };
};
72 changes: 72 additions & 0 deletions src/components/common/BottomSheet/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
import { memo, useState } from 'react';
import { motion, useDragControls, AnimatePresence } from 'framer-motion';

import { useBottomSheet } from '@/hooks/common/useBottomSheet';

import { Props } from './BottomSheet.types';

import { Button } from '../Button';
import { Portal } from '../Portal';

const Content = ({ children }: React.PropsWithChildren) => (
<div className="w-full text-black p-6">{children}</div>
keemsebin marked this conversation as resolved.
Show resolved Hide resolved
);

export const BottomSheet = memo(({ children, resetTrigger = false }: Props) => {
const dragControls = useDragControls();
keemsebin marked this conversation as resolved.
Show resolved Hide resolved

const { sheetHeight, isHidden, isInteractionDisabled, handleDrag, handleDragEnd, resetSheet } =
useBottomSheet(resetTrigger);

return (
<Portal isOpen={!isHidden}>
<div
className={`absolute top-0 left-0 w-full h-full transition-opacity duration-300 ${
isHidden ? 'opacity-0 pointer-events-none' : 'opacity-70 pointer-events-auto'
}`}
onClick={resetSheet}
/>

<AnimatePresence>
keemsebin marked this conversation as resolved.
Show resolved Hide resolved
{!isHidden && (
<motion.div
className="absolute bottom-0 left-0 w-full bg-white shadow-[0px_-4px_10px_0px_rgba(0,0,0,0.1)] rounded-t-3xl p-4 overflow-hidden"
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

shadow 값이 혹시 적용이 안돼서 요렇게 하신건가요?!
shadow-[0px_-4px_10px_0px_rgba(0,0,0,0.1)]

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

넵 기본 tailwind shadow 설정을 적용했을 때는 그림자가 잘 보이지 않아서 커스텀 값 넣었습니다

style={{ height: sheetHeight }}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

styletailwindCSS 둘 다 사용하신 이유가 있으신가욥??

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

sheetHeight은 드래그에 따라 동적으로 변하는 값이어서 tailwind를 통해 적용하기 어려워, style 속성을 따로 적용했습니다

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

tailwind도 동적으로 변경 가능해요~!

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

아하 JIT로 tailwind도 동적으로 적용 가능한 것 확인했습니다!
그렇지만 바텀시트 특성상 드래그에 따라 sheetHeight 값이 자주 변하고, css 속성 중 height 값만 변하기 때문에 동적 클래스로 적용하는 않는 편이 성능이나 유지보수에서 더 나을 것이라고 생각하는데 그대로 두어도 괜찮을까요?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

height만 동적으로 변경하면 되지 않을까요?? 성능이나 유지보수 어디에 문제가 생기는지 궁금합니당

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

문제가 생긴다기 보다..! tailwind에서 매번 새로운 동적 클래스를 생성하는 성능보다 style에서 직접 다루는 것이 더 나을 거라고 생각했습니당
큰 차이가 없다면 통일성을 위해서 tailwind로 바꿀까요?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

어짜피 계산된 값이 들어갈텐데, style속성에 넣어도 새로운 값을 업데이트 하는건 똑같지 않나요??

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

저의 생각은 굳이 style,tailwind를 나눌 필요는 없어 보여요! 유지보수 측면에서도 css가 나눠져 있는 것 보단 하나에서 관리 하는게 좋을 것 같아요. 실제 성능상 유의미한 변화가 있는 지 체크 해보시면 좋을 것 같습니다~!

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

아하 알겠습니다! 확인해보고 수정해서 올리겠습니당

drag="y"
dragControls={dragControls}
dragElastic={0}
dragConstraints={{ top: 0, bottom: 0 }}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

요 속성들이 다 적용되고 있는게 맞나요??
불필요한 속성이 있다면 지워도 될 것 같아요.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

네 이 속성들은 다 적용되고 있습니당

onDrag={handleDrag}
onDragEnd={handleDragEnd}
animate={{ height: sheetHeight, opacity: isHidden ? 0 : 1 }}
transition={{ type: 'spring', stiffness: 170, damping: 30, duration: 0.3 }}
onPointerDown={(e) => !isInteractionDisabled && dragControls.start(e)}
exit={{ height: 0, opacity: 0 }}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

framer 관련 객체들 저는 constants의 motion.ts 에서 관리하는데, 따로 빼도 깔끔할것 같네요!

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

아하 확인했습니다! 수정해서 올리겠습니당

>
<div className="w-20 h-1.5 bg-primary mx-auto rounded-full" />
<Content>{children}</Content>
</motion.div>
)}
</AnimatePresence>
</Portal>
);
});

export const BottomSheetDemo = () => {
const [isOpen, setIsOpen] = useState(false);

const handleClickBottomSheet = () => setIsOpen(!isOpen);

return (
<>
<Button variant="primary" size="medium" onClick={handleClickBottomSheet}>
Open BottomSheet
</Button>
<BottomSheet resetTrigger={isOpen}>
<div className="flex flex-col gap-6 items-center">
<div>BottomSheet Content</div>
</div>
</BottomSheet>
</>
);
};
3 changes: 3 additions & 0 deletions src/constants/bottomSheetOptions.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export const INITIAL_HEIGHT = 150;
export const MIN_VISIBLE_HEIGHT = 60;
export const MAX_HEIGHT = window.innerHeight * 0.9;
88 changes: 88 additions & 0 deletions src/hooks/common/useBottomSheet.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
import { useState, useCallback, useRef, useEffect } from 'react';
import { animate } from 'framer-motion';

import { DragInfo } from '@/components/common/BottomSheet/BottomSheet.types';
import { INITIAL_HEIGHT, MIN_VISIBLE_HEIGHT, MAX_HEIGHT } from '@/constants/bottomSheetOptions';

export const useBottomSheet = (resetTrigger: boolean) => {
const [sheetHeight, setSheetHeight] = useState(INITIAL_HEIGHT);
const [isHidden, setIsHidden] = useState(false);
const [isInteractionDisabled, setIsInteractionDisabled] = useState(false);
const dragOffsetRef = useRef(0);
const initialPositionRef = useRef(INITIAL_HEIGHT);
const dragStartTimeRef = useRef<number | null>(null);
const lastDragPositionRef = useRef(0);
const lastVelocityRef = useRef(0);

useEffect(() => {
if (resetTrigger) {
setSheetHeight(INITIAL_HEIGHT);
setIsHidden(false);
setIsInteractionDisabled(false);
dragOffsetRef.current = 0;
initialPositionRef.current = INITIAL_HEIGHT;
dragStartTimeRef.current = null;
}
}, [resetTrigger]);

const handleDrag = useCallback(
(_: MouseEvent | TouchEvent | PointerEvent, info: DragInfo) => {
if (isInteractionDisabled) return;

if (!dragStartTimeRef.current) {
dragStartTimeRef.current = Date.now();
lastDragPositionRef.current = info.delta.y;
}

requestAnimationFrame(() => {
const dragAmount = -info.delta.y;
dragOffsetRef.current += dragAmount;

const velocity =
(lastDragPositionRef.current - info.delta.y) /
(Date.now() - (dragStartTimeRef.current || Date.now()));
lastVelocityRef.current = velocity;

const newHeight = Math.min(
Math.max(initialPositionRef.current + dragOffsetRef.current, MIN_VISIBLE_HEIGHT),
MAX_HEIGHT
);
setSheetHeight(newHeight);
});
},
[isInteractionDisabled]
);
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

에러 처리 로직 추가 필요

드래그 핸들러에서 발생할 수 있는 예외 상황에 대한 처리가 필요합니다.

 const handleDrag = useCallback(
   (_: MouseEvent | TouchEvent | PointerEvent, info: DragInfo) => {
     if (isInteractionDisabled) return;
+    
+    try {
       if (!dragStartTimeRef.current) {
         dragStartTimeRef.current = Date.now();
         lastDragPositionRef.current = info.delta.y;
       }

       requestAnimationFrame(() => {
         const dragAmount = -info.delta.y;
         dragOffsetRef.current += dragAmount;

         const velocity =
           (lastDragPositionRef.current - info.delta.y) /
           (Date.now() - (dragStartTimeRef.current || Date.now()));
         lastVelocityRef.current = velocity;

         const newHeight = Math.min(
           Math.max(initialPositionRef.current + dragOffsetRef.current, MIN_VISIBLE_HEIGHT),
           MAX_HEIGHT
         );
         setSheetHeight(newHeight);
       });
+    } catch (error) {
+      console.error('드래그 처리 중 오류 발생:', error);
+      resetSheet();
+    }
   },
   [isInteractionDisabled]
 );

Committable suggestion skipped: line range outside the PR's diff.


const handleDragEnd = useCallback(() => {
const velocity = lastVelocityRef.current;
const projectedHeight = sheetHeight + velocity * 100;

const snapPoints = [MIN_VISIBLE_HEIGHT, INITIAL_HEIGHT, MAX_HEIGHT];
const nearestSnapPoint = snapPoints.reduce((prev, curr) =>
Math.abs(curr - projectedHeight) < Math.abs(prev - projectedHeight) ? curr : prev
);

animate(sheetHeight, nearestSnapPoint, {
duration: 0.3,
ease: 'easeOut',
onUpdate: (value) => setSheetHeight(value),
onComplete: () => {
if (nearestSnapPoint === MIN_VISIBLE_HEIGHT) {
setIsHidden(true);
setIsInteractionDisabled(true);
}
},
});
}, [sheetHeight]);

const resetSheet = useCallback(() => {
setSheetHeight(INITIAL_HEIGHT);
setIsHidden(false);
setIsInteractionDisabled(false);
dragOffsetRef.current = 0;
initialPositionRef.current = INITIAL_HEIGHT;
dragStartTimeRef.current = null;
}, []);
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

코드 중복 제거 필요

resetSheet 함수의 로직이 useEffect의 로직과 중복됩니다. 공통 함수로 추출하면 좋을 것 같습니다.

+const resetSheetState = () => {
+  setSheetHeight(INITIAL_HEIGHT);
+  setIsHidden(false);
+  setIsInteractionDisabled(false);
+  dragOffsetRef.current = 0;
+  initialPositionRef.current = INITIAL_HEIGHT;
+  dragStartTimeRef.current = null;
+};

 useEffect(() => {
-  if (resetTrigger) {
-    setSheetHeight(INITIAL_HEIGHT);
-    setIsHidden(false);
-    setIsInteractionDisabled(false);
-    dragOffsetRef.current = 0;
-    initialPositionRef.current = INITIAL_HEIGHT;
-    dragStartTimeRef.current = null;
-  }
+  if (resetTrigger) resetSheetState();
 }, [resetTrigger]);

-const resetSheet = useCallback(() => {
-  setSheetHeight(INITIAL_HEIGHT);
-  setIsHidden(false);
-  setIsInteractionDisabled(false);
-  dragOffsetRef.current = 0;
-  initialPositionRef.current = INITIAL_HEIGHT;
-  dragStartTimeRef.current = null;
-}, []);
+const resetSheet = useCallback(resetSheetState, []);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const resetSheet = useCallback(() => {
setSheetHeight(INITIAL_HEIGHT);
setIsHidden(false);
setIsInteractionDisabled(false);
dragOffsetRef.current = 0;
initialPositionRef.current = INITIAL_HEIGHT;
dragStartTimeRef.current = null;
}, []);
const resetSheetState = () => {
setSheetHeight(INITIAL_HEIGHT);
setIsHidden(false);
setIsInteractionDisabled(false);
dragOffsetRef.current = 0;
initialPositionRef.current = INITIAL_HEIGHT;
dragStartTimeRef.current = null;
};
useEffect(() => {
if (resetTrigger) resetSheetState();
}, [resetTrigger]);
const resetSheet = useCallback(resetSheetState, []);


return { sheetHeight, isHidden, isInteractionDisabled, handleDrag, handleDragEnd, resetSheet };
};
Loading