Skip to content

Commit

Permalink
Merge pull request #248 from STUDIO-EYE/feat/SCRUM-312-MainPageTest
Browse files Browse the repository at this point in the history
hotfix: PP News Page 페이지네이션 스크롤 이슈 해결
  • Loading branch information
frombozztoang authored Dec 9, 2024
2 parents 030810e + ccf42e5 commit 49186c4
Show file tree
Hide file tree
Showing 7 changed files with 246 additions and 237 deletions.
25 changes: 15 additions & 10 deletions src/components/Pagination/NewsPagination.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ const NewsPagination = ({ postsPerPage, totalPosts, paginate }: IPaginationProps
const navigate = useNavigate();
const [currentPage, setCurrentPage] = useState(1);
const [currentPageRange, setCurrentPageRange] = useState(0);
const [shouldScroll, setShouldScroll] = useState(false);
const location = useLocation();

const pageNumbers = [];
Expand All @@ -37,37 +38,41 @@ const NewsPagination = ({ postsPerPage, totalPosts, paginate }: IPaginationProps

useEffect(() => {
const queryParams = new URLSearchParams(location.search);
const page = parseInt(queryParams.get('page') || '1', 10);
const page = parseInt(queryParams.get("page") || "1", 10);
setCurrentPage(page);
setIndex(page - 1);
const pageRange = Math.ceil(page / 10) - 1;
setCurrentPageRange(pageRange);
}, [location]);

// useEffect(() => {
// window.scrollTo({ top: 900, behavior: 'smooth' });
// }, [currentPage, currentPageRange]);
useEffect(() => {
if (shouldScroll) {
window.scrollTo({ top: 900, behavior: "smooth" });
setShouldScroll(false);
}
}, [shouldScroll]);

return (
<Wrapper>
{currentPageRange > 0 && (
<>
<PageLi onClick={() => setCurrentPageRange(0)} selected={false}>
{'<<'}
{"<<"}
</PageLi>
<PageLi onClick={handlePrevRange} selected={false}>
{'<'}
{"<"}
</PageLi>
</>
)}
{displayedPages.map((number) => (
<PageLi
key={number}
className='page-item'
className="page-item"
onClick={() => {
paginate(number + 1); // 페이지 인덱스를 1부터 시작하게 조정
paginate(number + 1);
setIndex(number);
navigate(`?page=${number + 1}`);
setShouldScroll(true);
}}
selected={number === index ? true : false}
>
Expand All @@ -77,10 +82,10 @@ const NewsPagination = ({ postsPerPage, totalPosts, paginate }: IPaginationProps
{currentPageRange < totalPageRanges - 1 && (
<>
<PageLi onClick={handleNextRange} selected={false}>
{'>'}
{">"}
</PageLi>
<PageLi onClick={() => setCurrentPageRange(totalPageRanges - 1)} selected={false}>
{'>>'}
{">>"}
</PageLi>
</>
)}
Expand Down
38 changes: 19 additions & 19 deletions src/components/PromotionAdmin/News/NewsList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { getNews } from '@/apis/PromotionAdmin/news';
import Pagination from '@/components/Pagination/Pagination';
import { useNavigate } from 'react-router-dom';

const NewsList = ({handler}:{handler:(id:number)=>void}) => {
const NewsList = ({ handler }: { handler: (id: number) => void }) => {
const { data, isLoading, error, refetch } = useQuery<INEWS[], Error>('newsList', getNews);
// const newsData: INEWS[]=data?data:[];

Expand All @@ -19,29 +19,29 @@ const NewsList = ({handler}:{handler:(id:number)=>void}) => {
setCurrentPage(pageNumber - 1); // 페이지 인덱스를 0부터 시작하게 조정
navigate(`?page=${pageNumber}`); // URL 쿼리 매개변수 업데이트
};
const currentArtworks = data?data.slice(indexOfFirstPost, indexOfLastPost):[];
const currentArtworks = data ? data.slice(indexOfFirstPost, indexOfLastPost) : [];

const handleClick=(id:number)=>{
const handleClick = (id: number) => {
handler(id)
};

return (
<div style={{flexDirection:'column'}}>
{isLoading?<h1>Loading...</h1>:
data?
<>
{currentArtworks.map((i)=>(
<div
key={i.id}
style={{marginBottom:"5px"}}
onClick={()=>handleClick(i.id)}
data-cy={`news-item-${i.id}`} >
<NewsItem data={i}/>
</div>
))}
<Pagination postsPerPage={postsPerPage} totalPosts={data.length} paginate={paginate} />
</>
:<>😊 뉴스 데이터가 존재하지 않습니다.</>}
<div style={{ flexDirection: 'column' }}>
{isLoading ? <h1>Loading...</h1> :
data ?
<>
{currentArtworks.map((i) => (
<div
key={i.id}
style={{ marginBottom: "5px" }}
onClick={() => handleClick(i.id)}
data-cy={`news-item-${i.id}`} >
<NewsItem data={i} />
</div>
))}
<Pagination postsPerPage={postsPerPage} totalPosts={data.length} paginate={paginate} />
</>
: <>😊 뉴스 데이터가 존재하지 않습니다.</>}
</div>
);
};
Expand Down
139 changes: 69 additions & 70 deletions src/pages/PromotionAdmin/NewsPage/NewsViewPage/NewsEditPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,16 +16,16 @@ import { AdapterDayjs } from '@mui/x-date-pickers/AdapterDayjs/AdapterDayjs';
const NewsEditPage = () => {
const { id } = useParams();
const [errorMessage, setErrorMessage] = useState(''); //데이터 업데이트 할 때
const news=useOutletContext<{news:INEWS,setIsEditing:(React.Dispatch<React.SetStateAction<boolean>>)}>();
const news = useOutletContext<{ news: INEWS, setIsEditing: (React.Dispatch<React.SetStateAction<boolean>>) }>();
const setIsEditing = useSetRecoilState(dataUpdateState);

const navigator = useNavigate();
const location = useLocation();
const currentPath = location.pathname;
const listPath = currentPath.substring(0, currentPath.lastIndexOf('/'));

const {register,getValues,setValue,watch,
}= useForm<INEWS>({
const { register, getValues, setValue, watch,
} = useForm<INEWS>({
defaultValues: {
title: news.news.title,
source: news.news.source,
Expand All @@ -44,8 +44,8 @@ const NewsEditPage = () => {
const handleChange = (e: React.ChangeEvent<HTMLInputElement> | React.ChangeEvent<HTMLTextAreaElement>) => {
setIsEditing(true);
const { name, value } = e.target;
if (/^\s|[~!@#$%^&*(),.?":{}|<>]/.test(value.charAt(0))) {return;}
setPutData((prevData) => ({...prevData,[name]: value,}));
if (/^\s|[~!@#$%^&*(),.?":{}|<>]/.test(value.charAt(0))) { return; }
setPutData((prevData) => ({ ...prevData, [name]: value, }));
};
const visibility = watch('visibility');
const handleChangeVisibility = (value: boolean) => {
Expand All @@ -59,15 +59,15 @@ const NewsEditPage = () => {
// return `${year}-${month}-${day}`;
// };

const handleCancelWriting=()=>{
if(window.confirm(MSG.CONFIRM_MSG.CANCLE)){
const handleCancelWriting = () => {
if (window.confirm(MSG.CONFIRM_MSG.CANCLE)) {
news.setIsEditing(false)
setIsEditing(false)
navigator(listPath);
}
}

const handlePut=async()=>{
const handlePut = async () => {
// const formData = new FormData();
const requestData = {
id: Number(id),
Expand All @@ -79,17 +79,17 @@ const NewsEditPage = () => {
};
// formData.append('dto', new Blob([JSON.stringify(requestData)], { type: 'application/json' }));

if(window.confirm(MSG.CONFIRM_MSG.SAVE)){
try{
const response=await putNews(requestData)
if (window.confirm(MSG.CONFIRM_MSG.SAVE)) {
try {
const response = await putNews(requestData)
// if (response.code === 400 && response.data === null) { //에러메시지 있을 때
alert(MSG.ALERT_MSG.SAVE)
news.setIsEditing(false)
setIsEditing(false)
navigator(listPath)
return;
alert(MSG.ALERT_MSG.SAVE)
news.setIsEditing(false)
setIsEditing(false)
navigator(listPath)
return;
// }
}catch (error: any) {
} catch (error: any) {
alert(MSG.CONFIRM_MSG.FAILED)
}
}
Expand All @@ -98,38 +98,38 @@ const NewsEditPage = () => {
//----------------------------------------
return (
<Container>
<div style={{display:'flex',flexDirection:'row',justifyContent:'space-between',marginBottom:5}}>
<div style={{ display: 'flex', flexDirection: 'row', justifyContent: 'space-between', marginBottom: 5 }}>
<Description>제목</Description>
<div style={{display:'flex',flexDirection:'row',marginTop:'auto',marginBottom:'auto'}}>
<SendButton onClick={handlePut} data-cy="news-submit-button">완료</SendButton>
<SendButton onClick={handleCancelWriting} data-cy="news-cancel-button">취소</SendButton>
<div style={{ display: 'flex', flexDirection: 'row', marginTop: 'auto', marginBottom: 'auto' }}>
<SendButton onClick={handlePut} data-cy="news-submit-button">완료</SendButton>
<SendButton onClick={handleCancelWriting} data-cy="news-cancel-button">취소</SendButton>
</div>
</div>
<InputBlock
{...register('title')}
name='title'
value={putData.title}
onChange={handleChange}
placeholder='News 제목'
data-cy='news-title-input'
style={{borderRadius:"5px",fontFamily:"pretendard-semiBold",marginRight:10}}/>
{...register('title')}
name='title'
value={putData.title}
onChange={handleChange}
placeholder='News 제목'
data-cy='news-title-input'
style={{ borderRadius: "5px", fontFamily: "pretendard-semiBold", marginRight: 10 }} />

<div>
<Description>출처/작성자</Description>
<InputBlock
{...register('source')}
name='source'
value={putData.source}
onChange={handleChange}
placeholder='출처/작성자'
data-cy='news-source-input'
style={{borderRadius:"5px",fontFamily:"pretendard-semiBold"}}/>
{...register('source')}
name='source'
value={putData.source}
onChange={handleChange}
placeholder='출처/작성자'
data-cy='news-source-input'
style={{ borderRadius: "5px", fontFamily: "pretendard-semiBold" }} />
</div>
<div style={{display:'flex',flexDirection:'row'}}>
<div style={{ display: 'flex', flexDirection: 'row' }}>
<div>
<Description>원문 날짜</Description>
<LocalizationProvider dateAdapter={AdapterDayjs}>
<DatePicker
<DatePicker
{...register('pubDate')}
format='YYYY-MM-DD'
value={dayjs(putData.pubDate)}
Expand All @@ -143,12 +143,12 @@ const NewsEditPage = () => {
textField: {
sx: {
backgroundColor: '#ffffff',
borderRadius:'5px',
fontFamily:'pretendard',
borderRadius: '5px',
fontFamily: 'pretendard',
fontSize: '14px',
margin: 'auto 0 auto 5px',
boxShadow: '1px 1px 4px 0.3px #c6c6c6',
'.MuiInputBase-input':{
'.MuiInputBase-input': {
padding: '10px',
},
'.MuiOutlinedInput-root': {
Expand All @@ -169,46 +169,46 @@ const NewsEditPage = () => {
/>
</LocalizationProvider>
</div>
<div style={{margin:'auto'}}>
<div style={{ margin: 'auto' }}>
<Description>공개 여부</Description>
<VisibilityWrapper>
<CheckBox
onClick={() => handleChangeVisibility(true)}
className='public'
selected={visibility}
data-cy="news-visibility-public"
>
공개
</CheckBox>
<CheckBox
onClick={() => handleChangeVisibility(false)}
className='private'
selected={!visibility}
data-cy="news-visibility-private"
>
비공개
</CheckBox>
<CheckBox
onClick={() => handleChangeVisibility(true)}
className='public'
selected={visibility}
data-cy="news-visibility-public"
>
공개
</CheckBox>
<CheckBox
onClick={() => handleChangeVisibility(false)}
className='private'
selected={!visibility}
data-cy="news-visibility-private"
>
비공개
</CheckBox>
</VisibilityWrapper>
</div>
</div>
<div>
<Description>링크</Description>
<InputBlock
{...register('url')}
name='url'
value={putData.url}
onChange={handleChange}
placeholder='기사 링크'
data-cy='news-link-input'
style={{borderRadius:"5px",fontFamily:"pretendard-semiBold"}}/>
{...register('url')}
name='url'
value={putData.url}
onChange={handleChange}
placeholder='기사 링크'
data-cy='news-link-input'
style={{ borderRadius: "5px", fontFamily: "pretendard-semiBold" }} />
</div>
</Container>
);
};

export default NewsEditPage;

const Container=styled.div`
const Container = styled.div`
min-width: 300px;
width: 100%;
Expand All @@ -220,10 +220,9 @@ border-radius: 5px;
overflow:hidden;
// white-space:nowrap;
text-overflow: ellipsis;
}
`
`;

const Title=styled.div`
const Title = styled.div`
padding: 5px;
font-size: 1em;
white-space: nowrap;
Expand All @@ -249,7 +248,7 @@ const SendButton = styled.button`
}
`;

const InputBlock=styled.input`
const InputBlock = styled.input`
outline: none;
font-family: pretendard;
font-size: 14px;
Expand Down
Loading

0 comments on commit 49186c4

Please sign in to comment.