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

[FE] feat : 이미지 스켈레톤 적용 #1055

Merged
merged 8 commits into from
Jan 16, 2025
1 change: 1 addition & 0 deletions frontend/src/components/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,4 @@ export * from './common';
export * from './error';
export * from './highlight/components';
export * from './login';
export * from './skeleton';
30 changes: 30 additions & 0 deletions frontend/src/components/skeleton/ImgWithSkeleton/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import React, { useState } from 'react';

import * as S from './style';

interface ImgWithSkeletonProps {
children: React.ReactElement<React.ImgHTMLAttributes<HTMLImageElement>>;
imgWidth: string;
imgHeight: string;
}

const ImgWithSkeleton = ({ children, imgWidth, imgHeight }: ImgWithSkeletonProps) => {
const [isLoaded, setIsLoaded] = useState(false);

const handleImgLoad = () => {
setIsLoaded(true);
};

return (
<S.Container $width={imgWidth} $height={imgHeight}>
{!isLoaded && <S.ImgSkeleton />}
<S.ImgWrapper $isLoaded={isLoaded}>
{React.cloneElement(children, {
onLoad: handleImgLoad,
})}
Copy link
Contributor

Choose a reason for hiding this comment

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

지금은 children으로 단일 요소만 받고 있어서 cloneElement를 사용해도 큰 문제가 없을 것 같지만, 몇 가지 우려되는 상황이 있어 코멘트 남겨요!

  1. children으로 여러 개의 요소가 오는 경우. 즉, 여러 개의 요소를 하나의 스켈레톤 UI로 처리하는 경우. -> 한 페이지에 여러 개의 이미지가 뜨는 경우 각각에 스켈레톤을 적용하는 것이 오히려 전체적인 UI를 해치지는 않을지?
  2. children에 이미 onLoad 속성이 설정되어 있어 그게 무시되고 ImgWithSkeleton의 onLoad만 적용되는 경우.

위와 같은 상황이 발생할 수 있다면 renderProp 패턴 적용도 제안해봅니다! 바다의 생각이 궁금해요🫠

Copy link
Contributor Author

Choose a reason for hiding this comment

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

한 페이지에 여러 이미지가 있을 경우

비동기로 데이터를 가져왔거나 하나의 이미지라 로딩되었다하더라도 그게 모든 이미지가 로드되었다는 의미는 것은 아니에요. 이미지의 크기, 이미지가 있는 서버의 위치, 캐시 여부에 따라서 이미지의 개별적인 로드 속도는 다르죠.
그래서 여러 사이트에서 이미지 개별로 스켈레톤을 적용하는 것을 볼 수 있을거에요.

리뷰미의 경우, 데이터를 가져오는 동안 로딩 UI를 보여주지만 홈/리뷰 연결 페이지의 이미지 크기가 크기 때문에 캐시가 없을 경우 이미지 로드 속도가 걸리는 상황이에요. 그래서 이미지 개별에 대한 스켈레톤 컴포넌트를 만들었어요. 이미지가 여러개인 홈의 캐러셀의 경우 화면당 하나의 이미지를 보여주고 있고 리뷰미에서 커머스 서비스처럼 여러 이미지가 나오는 페이지는 없기 때문에 fe가 우려하는 상황은 없을 것 같아요.

onLoad

이미지에서 설정한 onLoad와 함께 실행할 수 있도록 변경했어요.

renderProp

만약 스켈레톤 컴포넌트가 이미지가 아니라 다른 요소에 대해서도 적용해야한다면, renderPro 패턴이 유용할 거에요.
다만, 앞서 언급했듯이 이미 로딩 UI가 있고 이미지의 느린 로드 속도에 따른 사용자 불편함을 줄이기 위해 탄생한 이미지용 스켈레톤이라는 점이 구현 시 중요한 포인트였어요. 또한 사용성 측면에서 상황별 스타일링이 커스텀된 이미지에 쉽게 적용할 수 있을 것도 중요한 고려 사항이었어요.

renderProps는 children을 이미지 외의 다른 요소로 받을 수 있는 유연함이 있지만, 스켈레톤 적용 시 사용하는 개발자가 추가로 render 함수에 대한 추가 작업이 필요해요. 하지만 현재 방식은 이미지를 children으로 받지만 하면 돼요. 보다 간단하고 직관적이죠.
또한 함수 컴포넌트가 렌더링될 때 컴포넌트 내부에서 정의된 모든 함수가 새로 생성되기 때문에, 비교적 간단한 이미지 스켈레톤 컴포넌트라는 역할에 비해 불필요한 렌더링이 발생하다는 단점도 존재해요.

Copy link
Contributor

@chysis chysis Jan 16, 2025

Choose a reason for hiding this comment

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

앞으로 기능이 더 확장되더라도 여러 이미지가 나오는 페이지는 없을 것 같네요! 만약 생긴다면 그때 더 고민해도 될 것 같아요.

이미지용 스켈레톤을 구현하게 된 배경 이해했습니다 :) 사용하는 개발자 입장에서는 render 함수를 만들기 보다는 children으로 넣는 것이 더 편하긴 하지요 👍

궁금한 것이, createElement도 새로운 요소를 생성하는 것인데 children으로 온 요소를 한 번 더 렌더링하는 게 아닌가요??

Copy link
Contributor Author

Choose a reason for hiding this comment

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

궁금한 것이, createElement도 새로운 요소를 생성하는 것인데 children으로 온 요소를 한 번 더 렌더링하는 게 아닌가요??

찾아보니, 둘의 렌더링 방식에 차이가 있다고 하네요

  • cloneElement는 React 엘리먼트에 대해 새로운 props를 추가하지만, props가 동일하다면 리렌더링을 방지합니다

  • Render Props 패턴은 부모 컴포넌트의 리렌더링 시 항상 새로운 함수가 생성되어 자식 컴포넌트도 다시 렌더링됩니다.

</S.ImgWrapper>
</S.Container>
);
};

export default ImgWithSkeleton;
47 changes: 47 additions & 0 deletions frontend/src/components/skeleton/ImgWithSkeleton/style.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import styled from '@emotion/styled';

interface ContainerProps {
$width: string;
$height: string;
}
export const Container = styled.div<ContainerProps>`
position: relative;
width: ${(props) => props.$width};
height: ${(props) => props.$height};
`;
export const ImgWrapper = styled.div<{ $isLoaded: boolean }>`
position: absolute;
top: 0;
left: 0;

width: 100%;
height: 100%;

opacity: ${(props) => (props.$isLoaded ? 1 : 0)};

transition: opacity 300ms;
`;
export const ImgSkeleton = styled.div`
width: 100%;
height: 100%;

background-image: linear-gradient(
135deg,
${({ theme }) => theme.colors.lightGray} 40%,
rgba(246, 246, 246, 0.89) 50%,
${({ theme }) => theme.colors.lightGray} 85%
);
background-size: 200% 100%;
border-radius: ${({ theme }) => theme.borderRadius.basic};

animation: skeleton-animation 1.5s infinite linear;

@keyframes skeleton-animation {
0% {
background-position: 200% 0;
}
100% {
background-position: -200% 0;
}
}
`;
1 change: 1 addition & 0 deletions frontend/src/components/skeleton/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { default as ImgWithSkeleton } from './ImgWithSkeleton';
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,11 @@ import { useRef, useState, useEffect } from 'react';

import nextArrowIcon from '@/assets/nextArrow.svg';
import prevArrowIcon from '@/assets/prevArrow.svg';
import { ImgWithSkeleton } from '@/components';
import { breakpoints } from '@/styles/theme';

import useSlideImgSize from '../../hooks/useSlideImgSize';

import * as S from './styles';

export interface Slide {
Expand Down Expand Up @@ -37,6 +40,7 @@ const InfinityCarousel = ({ slideList }: InfinityCarouselProps) => {
const [deltaX, setDeltaX] = useState(0); // 현재 드래그 중인 위치와 시작 위치 사이의 차이

const slideRef = useRef<HTMLDivElement>(null);
const { imgSize } = useSlideImgSize({ slideRef });

const slideLength = slideList.length;
// 첫 슬라이드와 마지막 슬라이드의 복제본을 각각 맨 뒤, 맨 처음에 추가
Expand Down Expand Up @@ -151,7 +155,9 @@ const InfinityCarousel = ({ slideList }: InfinityCarouselProps) => {
{clonedSlideList.map((slide, index) => (
<S.SlideItem key={index}>
<S.SlideContent>
<img src={slide.imageSrc} alt={slide.alt} />
<ImgWithSkeleton imgHeight={imgSize.height} imgWidth={imgSize.width}>
<S.SlideContentImg src={slide.imageSrc} alt={slide.alt} />
</ImgWithSkeleton>
</S.SlideContent>
</S.SlideItem>
))}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,10 +46,10 @@ export const SlideContent = styled.div`
justify-content: space-between;

width: 100%;
`;

img {
width: 80%;
}
export const SlideContentImg = styled.img`
width: 100%;
`;

export const PrevButton = styled.button`
Expand Down
42 changes: 42 additions & 0 deletions frontend/src/pages/HomePage/hooks/useSlideImgSize.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import { useEffect, useState } from 'react';
Copy link
Contributor Author

Choose a reason for hiding this comment

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

구현 배경

홈 페이지의 경우, 이미지가 퍼센트로 설정되어 있고 768px이하에서 height가 설정되어 있지 않아서 이미지에 따라 자동으로 설정되는 상황이었어요. slideRef로 width를 받아올 수 있어서 캐러셀 이미지 비율을 사용해 height를 지정하는 방식을 사용했어요.


import { debounce } from '@/utils';

const DEBOUNCE_TIME = 300;

interface UseSlideImgSizeProps {
slideRef: React.RefObject<HTMLDivElement>;
}
const useSlideImgSize = ({ slideRef }: UseSlideImgSizeProps) => {
interface ImgSize {
width: string;
height: string;
}
const [imgSize, setImgSize] = useState<ImgSize>({ width: '', height: '' });

const updateImgSize = () => {
if (!slideRef.current) return;

const slideDomRect = slideRef.current.getBoundingClientRect();
const width = Math.ceil(slideDomRect.width * 0.8 * 0.1);
const height = width * 0.61;

setImgSize({ width: `${width}rem`, height: `${height}rem` });
};

const debouncedUpdateImgSize = debounce(updateImgSize, DEBOUNCE_TIME);

useEffect(() => {
updateImgSize();

document.addEventListener('resize', debouncedUpdateImgSize);

return () => {
document.removeEventListener('resize', debouncedUpdateImgSize);
};
}, [slideRef]);

return { imgSize };
};

export default useSlideImgSize;
27 changes: 12 additions & 15 deletions frontend/src/pages/ReviewZonePage/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ import { useNavigate } from 'react-router';
import { useRecoilState } from 'recoil';

import ReviewZoneIcon from '@/assets/reviewZone.svg';
import { Button } from '@/components';
import { ROUTE } from '@/constants/route';
import { Button, ImgWithSkeleton } from '@/components';
import { ROUTE } from '@/constants';
import { useGetReviewGroupData, useSearchParamAndQuery, useModals } from '@/hooks';
import { reviewRequestCodeAtom } from '@/recoil';
import { calculateParticle } from '@/utils';
Expand All @@ -15,6 +15,11 @@ import * as S from './styles';
const MODAL_KEYS = {
content: 'CONTENT_MODAL',
};
const BUTTON_SIZE = {
width: '28rem',
height: '8.5rem',
};
const IMG_HEIGHT = '15rem';

const ReviewZonePage = () => {
const { isOpen, openModal, closeModal } = useModals();
Expand Down Expand Up @@ -46,29 +51,21 @@ const ReviewZonePage = () => {

return (
<S.ReviewZonePage>
<S.ReviewZoneMainImg src={ReviewZoneIcon} alt="" />
<ImgWithSkeleton imgWidth={BUTTON_SIZE.width} imgHeight={IMG_HEIGHT}>
<S.ReviewZoneMainImg src={ReviewZoneIcon} alt="" $height={IMG_HEIGHT} />
</ImgWithSkeleton>
<S.ReviewGuideContainer>
<S.ReviewGuide>{`${reviewGroupData.projectName}${calculateParticle({ target: reviewGroupData.projectName, particles: { withFinalConsonant: '을', withoutFinalConsonant: '를' } })} 함께한`}</S.ReviewGuide>
<S.ReviewGuide>{`${reviewGroupData.revieweeName}의 리뷰 공간이에요`}</S.ReviewGuide>
</S.ReviewGuideContainer>
<S.ButtonContainer>
<Button
styleType="primary"
type="button"
onClick={handleReviewWritingButtonClick}
style={{ width: '28rem', height: '8.5rem' }}
>
<Button styleType="primary" type="button" onClick={handleReviewWritingButtonClick} style={BUTTON_SIZE}>
<S.ButtonTextContainer>
<S.ButtonText>리뷰 쓰기</S.ButtonText>
<S.ButtonDescription>작성한 리뷰는 익명으로 제출돼요</S.ButtonDescription>
</S.ButtonTextContainer>
</Button>
<Button
styleType="secondary"
type="button"
onClick={handleReviewListButtonClick}
style={{ width: '28rem', height: '8.5rem' }}
>
<Button styleType="secondary" type="button" onClick={handleReviewListButtonClick} style={BUTTON_SIZE}>
<S.ButtonTextContainer>
<S.ButtonText>리뷰 확인하기</S.ButtonText>
<S.ButtonDescription>비밀번호로 내가 받은 리뷰를 확인할 수 있어요</S.ButtonDescription>
Expand Down
5 changes: 3 additions & 2 deletions frontend/src/pages/ReviewZonePage/styles.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,9 @@ export const ReviewZonePage = styled.div`
justify-content: center;
`;

export const ReviewZoneMainImg = styled.img`
export const ReviewZoneMainImg = styled.img<{ $height: string }>`
width: 43rem;
height: 23rem;
height: ${(props) => props.$height};
`;

export const ReviewGuideContainer = styled.div`
Expand All @@ -25,6 +25,7 @@ export const ReviewGuideContainer = styled.div`
align-items: center;
justify-content: center;

margin-top: 3rem;
padding-left: 0.2rem;
`;

Expand Down
Loading