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

도감 페이지 최적화 #130

Merged
merged 16 commits into from
Jul 18, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
09f8e02
Update README.md
cdm1263 Jun 23, 2024
398aad0
chore: pnp.cjs 업데이트
cdm1263 Jul 14, 2024
8d3681f
chore: yarn berry 업데이트
cdm1263 Jul 14, 2024
2ed887a
Merge branch 'Min' of github.com:side-project-pokehub/my-pokemon into…
cdm1263 Jul 14, 2024
f6a08c1
Design: pokemon grid의 최소 높이 적용 및 각 리스트의 너비, 높이 적용
cdm1263 Jul 16, 2024
50a9fe3
Feat: pokemon grid 내에 들어갈 요소의 갯수를 구하는 useGetGridElementWidth 훅 생성
cdm1263 Jul 16, 2024
9e31e0f
Feat: 뷰포트 내의 요소 개수를 측정하는 useElementCount 훅 생성
cdm1263 Jul 16, 2024
09d6bab
Refactor: windowing으로 보여지는 데이터의 갯수를 반응형으로 변경
cdm1263 Jul 16, 2024
b4ef9ce
Refactor: pokemon grid의 사이즈를 측정하는 사이드 이펙트 및 커스텀훅 적용
cdm1263 Jul 16, 2024
5179cbd
Refactor: 포켓몬 데이터를 batch 사이즈 단위로 나눠 불러오는 useQueries 커스텀 훅으로 리팩토링
cdm1263 Jul 16, 2024
03bcd2e
Feat: useQueries로 불러온 중첩 데이터를 평탄화하는 useFlatData 훅 생성
cdm1263 Jul 16, 2024
4dbcc1f
Refactor: 포켓몬 전체 데이터를 불러오는 로직 변경
cdm1263 Jul 16, 2024
c806de4
Fix : next config에 구글 유저 이미지 호스팅 주소 추가
cdm1263 Jul 16, 2024
abd5f7d
Refactor: ul 중복 제거
cdm1263 Jul 17, 2024
7bbffb8
Refactor: item을 element로 변수명 변경
cdm1263 Jul 18, 2024
1379a45
Merge pull request #129 from side-project-pokehub/Min
cdm1263 Jul 18, 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
2,126 changes: 1,063 additions & 1,063 deletions .pnp.cjs

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@

|<a href="https://github.com/cdm1263"><img src="https://avatars.githubusercontent.com/u/122417731?v=4" width=150px alt="차동민" />|<a href="https://github.com/BearHumanS"><img src="https://avatars.githubusercontent.com/u/115094069?v=4" width=150px alt="남기훈" />|<a href="https://github.com/DICEPT"><img src="https://avatars.githubusercontent.com/u/106785596?v=4" width=150px alt="박철민" />|
|:---------------------------------------------------------------------------------------------------------------------------------:|:---------------------------------------------------------------------------------------------------------------------------------:|:---------------------------------------------------------------------------------------------------------------------------------:|
| **[차동민](https://github.com/ChoEun-Sang)** | **[남기훈](https://github.com/BearHumanS)** | **[박철민](https://github.com/DICEPT)** |
| **[차동민](https://github.com/cdm1263)** | **[남기훈](https://github.com/BearHumanS)** | **[박철민](https://github.com/DICEPT)** |
|메인 도감 페이지 <br/> 카드 제작 페이지 <br/> 포켓몬 카드 제작| 도감 상세 페이지 <br/> 마이 페이지 <br/> SEO 최적화| 커뮤니티 페이지 <br/> 데스크탑, 모바일 UX/UI 디자인 <br/> 로딩 애니메이션 UI 제작 |
<br/>

Expand Down
4 changes: 4 additions & 0 deletions next.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,10 @@ const nextConfig = {
hostname: 'firebasestorage.googleapis.com',
// 필요한 경우 port와 pathname을 추가할 수 있습니다.
},
{
protocol: 'https',
hostname: 'lh3.googleusercontent.com',
},
],
},
};
Expand Down
9 changes: 6 additions & 3 deletions src/components/cardMaker/CardEditPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,14 @@ import Inner from '../Inner';
import { addDocument, getCountDocument } from '@/lib/firebaseQuery';
import useUserStore from '@/store/useUsersStore';
import { MouseEvent, useState } from 'react';
import { filteredPokemonData } from '@/lib/type';
import { useGetAllPokemon } from '@/query/qeuries';
import { PokemonType, filteredPokemonData } from '@/lib/type';
import { usePokemonQueries } from '@/query/qeuries';
import SearchPokemon from './searchPokemon/SearchPokemon';
import { useEffect } from 'react';
import SelectPokemonMobile from './selectPokemon/SelectPokemonMobile';
import { useRouter } from 'next/navigation';
import { UseQueryResult } from 'react-query';
import useFlatData from '@/hook/useFlatData';

const CardEditPage = () => {
const [isSaving, setIsSaving] = useState<boolean>(false);
Expand All @@ -28,7 +30,8 @@ const CardEditPage = () => {
setPokemonData,
pokemonName,
} = useSelectedPokemonForCard();
const { data } = useGetAllPokemon(1017);
const queries = usePokemonQueries(1017);
const data = useFlatData(queries as UseQueryResult<PokemonType>[]);
const filteredPokemonData = {} as filteredPokemonData;

useEffect(() => {
Expand Down
7 changes: 5 additions & 2 deletions src/components/cardMaker/searchPokemon/SearchPokemon.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,12 @@ import styles from './search.module.scss';
import { POKEMON_NAME } from '@/lib/pokemonName';
import { reverseObject } from '@/lib/util/reverseObject';
import { POKEMON_TYPES } from '@/lib/constants';
import { useGetAllPokemon } from '@/query/qeuries';
import { usePokemonQueries } from '@/query/qeuries';
import { IoSearch } from '@react-icons/all-files/io5/IoSearch';
import { PokemonType, TypesType } from '@/lib/type';
import SearchDropdown from './SearchDropdown';
import useFlatData from '@/hook/useFlatData';
import { UseQueryResult } from 'react-query';

const SearchPokemon = () => {
const [text, setText] = useState<string>('');
Expand All @@ -15,7 +17,8 @@ const SearchPokemon = () => {
const [foundPokemon, setFoundPokemon] = useState<
(PokemonType | undefined)[] | null
>(null);
const { data } = useGetAllPokemon(1017);
const queries = usePokemonQueries(1017);
const data = useFlatData(queries as UseQueryResult<PokemonType>[]);

useEffect(() => {
const handleClickOutside = (event: MouseEvent) => {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
import { PokemonType } from '@/lib/type';
import { useGetAllPokemon } from '@/query/qeuries';
import { usePokemonQueries } from '@/query/qeuries';
import { useCallback, useEffect, useState } from 'react';
import SelectPokemonLayout from './SelectPokemonLayout';
import styles from './select.module.scss';
import useCalculateInnerWidth from '@/hook/useCalculateInnerWidth';
import useFlatData from '@/hook/useFlatData';
import { UseQueryResult } from 'react-query';

const SelectPokemonRandom = () => {
const { data } = useGetAllPokemon(1017);
const queries = usePokemonQueries(1017);
const data = useFlatData(queries as UseQueryResult<PokemonType>[]);
const [randomPokemons, setRandomPokemons] = useState<PokemonType[]>([]);
const windowWidth = useCalculateInnerWidth();
let POKEMONS_PER_PAGE = 3;
Expand Down
3 changes: 3 additions & 0 deletions src/components/dex/PokemonDex.module.scss
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
display: grid;
grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
gap: 20px;
min-height: calc(100vh - 166px);

@include mobile {
grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
Expand All @@ -12,6 +13,8 @@
}

.pokemon_list_element {
width: 100%;
height: 315px;
display: flex;
position: relative;
align-items: center;
Expand Down
33 changes: 31 additions & 2 deletions src/components/dex/PokemonDex.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,47 @@
import useFilteredPokemonData from '@/hook/useFilteredPokemonData';
import useVisibleDataByScroll from '@/hook/useVisibleDataByScroll';
import Loading from '../loading/Loading';
import { useLayoutEffect, useState } from 'react';
import useElementCount from '@/hook/useElementCount';
import useGetGridElementWidth from '@/hook/useGetGridElementWidth';

const PokemonDex = () => {
const { filteredData, isLoading } = useFilteredPokemonData();
const visibleData = useVisibleDataByScroll(filteredData);
const [ulWidth, setUlWidth] = useState(0);
const itemWidth = useGetGridElementWidth(ulWidth);
const { ulRef, elementCount } = useElementCount(itemWidth, 315, 20);

useLayoutEffect(() => {
if (!ulRef.current) return;

const handleResize = (entries: ResizeObserverEntry[]) => {
for (let entry of entries) {
if (entry.target === ulRef.current) {
const { width } = entry.contentRect;
setUlWidth(width);
}
}
};

const resizeObserver = new ResizeObserver(handleResize);
resizeObserver.observe(ulRef.current);

return () => {
if (ulRef.current) {
resizeObserver.unobserve(ulRef.current);

Check warning on line 34 in src/components/dex/PokemonDex.tsx

View workflow job for this annotation

GitHub Actions / Lint

The ref value 'ulRef.current' will likely have changed by the time this effect cleanup function runs. If this ref points to a node rendered by React, copy 'ulRef.current' to a variable inside the effect, and use that variable in the cleanup function
}
};
}, [filteredData]);

Check warning on line 37 in src/components/dex/PokemonDex.tsx

View workflow job for this annotation

GitHub Actions / Lint

React Hook useLayoutEffect has a missing dependency: 'ulRef'. Either include it or remove the dependency array

const visibleData = useVisibleDataByScroll(filteredData, elementCount.total);

if (isLoading) {
return <Loading />;
}

return (
<Inner>
<ul className={styles.pokemon_grid}>
<ul className={styles.pokemon_grid} ref={ulRef}>
{visibleData.length
? visibleData.map((data) => (
<PokemonDexElement data={data} key={data.name} />
Expand Down
34 changes: 16 additions & 18 deletions src/components/dex/PokemonDexElementLayout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -34,24 +34,22 @@ const PokemonDexElementLayout = ({
};

return (
<ul>
<motion.li
whileHover={{
scale: 1.02,
boxShadow: `rgba(0, 0, 0, 0.10) 0px 3px 20px`,
}}
transition={{ duration: 0.2 }}
className={`${styles.pokemon_list_element} ${getHighlightClass()} ${
className || ''
}`}
onClick={onClick}
>
<div className={styles.pokemon_number}>
<span>{`${number()}`}</span>
</div>
{children}
</motion.li>
</ul>
<motion.li
whileHover={{
scale: 1.02,
boxShadow: `rgba(0, 0, 0, 0.10) 0px 3px 20px`,
}}
transition={{ duration: 0.2 }}
className={`${styles.pokemon_list_element} ${getHighlightClass()} ${
className || ''
}`}
onClick={onClick}
>
<div className={styles.pokemon_number}>
<span>{`${number()}`}</span>
</div>
{children}
</motion.li>
);
};

Expand Down
59 changes: 59 additions & 0 deletions src/hook/useElementCount.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import { useState, useEffect, useRef } from 'react';

interface ElementCount {
rows: number;
columns: number;
total: number;
}

const useElementCount = (
elementWidth: number,
elementHeight: number,
gap: number,
) => {
const ulRef = useRef<HTMLUListElement>(null);
const [elementCount, setElementCount] = useState<ElementCount>({
rows: 0,
columns: 0,
total: 0,
});

useEffect(() => {
const calculateElementCount = (entries: IntersectionObserverEntry[]) => {
if (elementWidth) {
for (let entry of entries) {
if (entry.isIntersecting && entry.target === ulRef.current) {
const ulElement = entry.target as HTMLUListElement;
const ulWidth = ulElement.offsetWidth;
const ulHeight = ulElement.offsetHeight;

const columns = Math.ceil((ulWidth + gap) / (elementWidth + gap));
const rows = Math.ceil((ulHeight + gap) / (elementHeight + gap));
const total = columns * rows;
setElementCount({ rows, columns, total });
}
}
}
};

const observer = new IntersectionObserver(calculateElementCount, {
root: null,
rootMargin: '0px',
threshold: 0.1,
});

if (ulRef.current) {
observer.observe(ulRef.current);
}

return () => {
if (ulRef.current) {
observer.unobserve(ulRef.current);

Check warning on line 51 in src/hook/useElementCount.ts

View workflow job for this annotation

GitHub Actions / Lint

The ref value 'ulRef.current' will likely have changed by the time this effect cleanup function runs. If this ref points to a node rendered by React, copy 'ulRef.current' to a variable inside the effect, and use that variable in the cleanup function
}
};
}, [elementWidth, elementHeight, gap]);

return { ulRef, elementCount };
};

export default useElementCount;
17 changes: 10 additions & 7 deletions src/hook/useFilteredPokemonData.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,20 +3,22 @@
import { PokemonType, TypesType } from '@/lib/type';
import { reverseObject } from '@/lib/util/reverseObject';
import { useMemo } from 'react';
import { useGetAllPokemon } from '@/query/qeuries';
import { usePokemonQueries } from '@/query/qeuries';
import useSelectedStore from '@/store/useSelectedStore';
import useSearchInputText from '@/store/useSearchInputText';
import useFlatData from './useFlatData';
import { UseQueryResult } from 'react-query';

const useFilteredPokemonData = () => {
const { data: allPokemonData, isLoading } = useGetAllPokemon(1017);
const queries = usePokemonQueries(1017);
const allData = useFlatData(queries as UseQueryResult<PokemonType>[]);
const { selectedPlate } = useSelectedStore();
const { inputText } = useSearchInputText();
const reversedPokemonNameObject = reverseObject(POKEMON_NAME);

const filteredData = useMemo(() => {
if (!allPokemonData) return [];

return allPokemonData.filter((data: PokemonType) => {
if (!allData.length) return [];
return allData.filter((data: PokemonType) => {
if (inputText) {
return reversedPokemonNameObject[data?.name]?.includes(inputText);
}
Expand All @@ -30,8 +32,9 @@
),
);
});
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [allPokemonData, inputText, selectedPlate]);
}, [allData, inputText, selectedPlate]);

Check warning on line 35 in src/hook/useFilteredPokemonData.ts

View workflow job for this annotation

GitHub Actions / Lint

React Hook useMemo has a missing dependency: 'reversedPokemonNameObject'. Either include it or remove the dependency array

const isLoading = !allData.length;

return { filteredData, isLoading };
};
Expand Down
18 changes: 18 additions & 0 deletions src/hook/useFlatData.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { PokemonType } from '@/lib/type';
import { useEffect, useState } from 'react';
import { UseQueryResult } from 'react-query';

const useFlatData = (queries: UseQueryResult<PokemonType>[]) => {
const [allData, setAllData] = useState<PokemonType[]>([]);

useEffect(() => {
const newData = queries.flatMap((query) => query.data || []);
if (newData.length !== allData.length) {
setAllData(newData);
}
}, [queries]);

Check warning on line 13 in src/hook/useFlatData.ts

View workflow job for this annotation

GitHub Actions / Lint

React Hook useEffect has a missing dependency: 'allData.length'. Either include it or remove the dependency array

return allData;
};

export default useFlatData;
22 changes: 22 additions & 0 deletions src/hook/useGetGridElementWidth.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { useState, useEffect } from 'react';

const useGetGridElementWidth = (gridWidth: number) => {
const [elementWidth, setElement] = useState(0);

useEffect(() => {
const minElementWidth = 200;
const gap = 20;

const maxElements = Math.floor((gridWidth + gap) / (minElementWidth + gap));

const totalGapWidth = (maxElements - 1) * gap;
const remainingWidth = gridWidth - totalGapWidth;
const elementWidth = remainingWidth / maxElements;

setElement(elementWidth);
}, [gridWidth]);

return elementWidth;
};

export default useGetGridElementWidth;
9 changes: 6 additions & 3 deletions src/hook/useVisibleDataByScroll.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,16 @@
import { PokemonType } from '@/lib/type';
import { useEffect, useState } from 'react';

const useVisibleDataByScroll = (filteredData: PokemonType[]) => {
const useVisibleDataByScroll = (
filteredData: PokemonType[],
itemsPerPage: number,
) => {
const [visibleData, setVisibleData] = useState<PokemonType[]>([]);
const [pageNum, setPageNum] = useState(1);

useEffect(() => {
setVisibleData(filteredData.slice(0, pageNum * 20));
}, [filteredData, pageNum]);
setVisibleData(filteredData.slice(0, pageNum * itemsPerPage));
}, [filteredData, pageNum, itemsPerPage]);

const handleScroll = () => {
const { scrollTop, clientHeight, scrollHeight } = document.documentElement;
Expand Down
12 changes: 4 additions & 8 deletions src/lib/poketApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,14 +25,10 @@ export const getPokemonSpecies = async (url: string) => {
return fetchData(`${url}`, 'get');
};

export const getAllPokemonDetails = async (limit: number) => {
const data = await fetchData(`pokemon?limit=${limit}`, 'get');
const pokemonDetailDatas: PokemonType[] = await Promise.all(
data.results.map((item: Pokemon) => fetchData(item.url, 'get')),
);
return pokemonDetailDatas;
};

export const getEvolvesDatas = async (url: string) => {
return fetchData(`${url}`, 'get');
};

export const getPokemonDetails = async (url: string) => {
return fetchData(url, 'get');
};
Loading
Loading