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: 용어집 무한스크롤 #136

Open
wants to merge 11 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
"clsx": "^1.1.1",
"facepaint": "^1.2.1",
"file-loader": "^6.2.0",
"intersection-observer": "^0.12.0",
"prism-react-renderer": "^1.2.1",
"react": "^17.0.1",
"react-dom": "^17.0.1",
Expand Down
35 changes: 17 additions & 18 deletions src/components/WikiTable/WikiTable.tsx
Original file line number Diff line number Diff line change
@@ -1,25 +1,19 @@
import React, { useEffect } from 'react';
import React, { useCallback, useEffect, useRef } from 'react';
import { WikiWord } from 'types';

import WikiTableRow from './WikiTableRow';
import useInfiniteScroll from '../../hooks/useInfiniteScroll';

import usePagination from '../../hooks/usePagination';

export default function WikiTable({ words = [] }: { words: string[] }) {
const { onPrevious, onNext, currentPage, result, isLastPage, isFirstPage } =
usePagination({
source: words,
offset: 2,
});
export default function WikiTable({ words = [] }: { words: WikiWord[] }) {
const { result, onNext } = useInfiniteScroll({
source: words,
});
const getLastRow = (index): boolean => {
return result.length - 1 == index;
};

return (
<>
<span>{currentPage}</span>
<button onClick={onPrevious} disabled={isFirstPage}>
Previous
</button>
<button onClick={onNext} disabled={isLastPage}>
Next
</button>
<table width="100%" summary="Web Analytics Handbook 용어사전">
<thead>
<tr style={{ borderBottom: 'none' }}>
Expand All @@ -28,8 +22,13 @@ export default function WikiTable({ words = [] }: { words: string[] }) {
</tr>
</thead>
<tbody>
{result.map(word => (
<WikiTableRow key={word.name} {...word} />
{result.map((word, index) => (
<WikiTableRow
key={word.name}
{...word}
last={getLastRow(index)}
onNext={onNext}
/>
Copy link
Member

Choose a reason for hiding this comment

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

layer tree가 업데이트 될 때마다 table의 width 값이 계속 바뀌네요 ㅎㅎㅠ 새로 추가되는 콘텐츠에 따라 기존에 있던 table의 너비가 달라지니 당연한 거긴 한데 사용자 경험 측면에서 자연스럽지 않아 보이는군요.. 반응형을 생각했을 때 table 구조가 용어 사전을 보기에 적절한 UI인지도 논의가 필요할 것 같아요

2021-10-08.8.45.00.mov

.

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로 변경되야될것으로 보이네요!

))}
</tbody>
</table>
Expand Down
30 changes: 24 additions & 6 deletions src/components/WikiTable/WikiTableRow.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,30 @@
import React from 'react';
import useIntersectionObserver from 'hooks/useIntersectionObserver';
import React, { useEffect } from 'react';

import { WikiWord } from '../../types';
type wikiTableRowProps = {
description: string;
name: string;
last: boolean;
onNext: () => void;
};
export default function WikiTableRow({
name,
description,
last,
onNext,
}: wikiTableRowProps) {
const { ref, entry } = useIntersectionObserver({ freezeOnceVisible: true });

export default function WikiTableRow({ name, description }: WikiWord) {
return (
<tr>
useEffect(() => {
if (entry?.isIntersecting) onNext();
}, [entry]);

const content = (
<>
<td>{name}</td>
<td>{description}</td>
</tr>
</>
);

return last ? <tr ref={ref}>{content}</tr> : <tr>{content}</tr>;
}
51 changes: 51 additions & 0 deletions src/hooks/useInfiniteScroll.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import { useEffect, useState } from 'react';
import { WikiWord } from 'types';

type Args = {
source: WikiWord[];
limit: number;
offset: number;
};

type Returns = {
result: WikiWord[];
currentOffest: number;
isLastOffset: boolean;
onNext: () => void;
};
const usePagination = ({
source = [],
limit = 10,
offset = 0,
}: Args): Returns => {
const getResult = (): WikiWord[] => {
const startIdx = 0;
const endIdx: number = currentOffest;
return source.slice(startIdx, endIdx);
};
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
Contributor Author

Choose a reason for hiding this comment

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

넵! 타입지정!


const getMaxOffset = (): number => {
return source.length;
};

const [currentOffest, setCurrentOffest] = useState<number>(limit);

useEffect(() => {
if (currentOffest !== limit) setCurrentOffest(limit);
else getResult();
}, [source]);

const onNext = () => {
if (currentOffest >= getMaxOffset()) return;
setCurrentOffest(currentOffest + limit);
};

return {
result: getResult(),
currentOffest,
isLastOffset: currentOffest > getMaxOffset(),
onNext,
};
};

export default usePagination;
44 changes: 44 additions & 0 deletions src/hooks/useIntersectionObserver.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import { RefObject, useEffect, useRef, useState } from 'react';
import 'intersection-observer';
interface Args extends IntersectionObserverInit {
freezeOnceVisible?: boolean;
delay?: number;
}

function useIntersectionObserver({
threshold = 0,
root = null,
rootMargin = '0%',
freezeOnceVisible = false,
delay = 0,
}: Args): {
ref: RefObject<Element> | null;
entry: IntersectionObserverEntry | undefined;
} {
const ref = useRef<HTMLFormElement | null>(null);
const [entry, setEntry] = useState<IntersectionObserverEntry>();

const frozen: boolean = entry?.isIntersecting && freezeOnceVisible;
const updateEntry = ([entry]: IntersectionObserverEntry[]): void => {
setTimeout(() => {
setEntry(entry);
}, delay);
};

useEffect(() => {
const node = ref?.current; // DOM Ref
if (frozen || !node) return;

const observerParams = { threshold, root, rootMargin };
const observer = new IntersectionObserver(updateEntry, observerParams);

observer.observe(node);
return () => observer.disconnect();

// eslint-disable-next-line react-hooks/exhaustive-deps
}, [ref, threshold, root, rootMargin, frozen]);

return { ref, entry };
}

export default useIntersectionObserver;
Copy link
Member

Choose a reason for hiding this comment

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

so 깔끔한 훅이네요! 굿굿