├── .gitignore ├── LICENSE ├── README.md ├── api └── proxy.ts ├── assets └── dcard-reader.gif ├── package-lock.json ├── package.json ├── public ├── index.html ├── manifest.json └── robots.txt ├── src ├── App.tsx ├── components │ ├── LoadingPlaceHolder │ │ ├── LoadingPlaceHolder.tsx │ │ ├── index.ts │ │ └── style.ts │ ├── PostItem │ │ ├── PostItem.tsx │ │ ├── __tests__ │ │ │ └── postItem.test.tsx │ │ ├── index.ts │ │ └── style.ts │ ├── PostModal │ │ ├── PostModal.tsx │ │ ├── index.ts │ │ ├── modal.css │ │ └── style.ts │ ├── PostsContainer │ │ ├── PostsContainer.tsx │ │ ├── index.ts │ │ └── style.ts │ ├── ResponseInfo │ │ ├── ResponseInfo.tsx │ │ ├── index.ts │ │ └── style.ts │ └── TopicLabel │ │ ├── TopicLabel.tsx │ │ ├── index.ts │ │ └── style.ts ├── constant │ └── api.ts ├── hooks │ └── useFetchPost.tsx ├── index.css ├── index.tsx ├── react-app-env.d.ts ├── serviceWorker.ts └── utils │ └── media.ts ├── tsconfig.json └── yarn.lock /.gitignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. 2 | 3 | # dependencies 4 | /node_modules 5 | /.pnp 6 | .pnp.js 7 | 8 | # testing 9 | /coverage 10 | 11 | # production 12 | /build 13 | 14 | # misc 15 | .DS_Store 16 | .env.local 17 | .env.development.local 18 | .env.test.local 19 | .env.production.local 20 | 21 | npm-debug.log* 22 | yarn-debug.log* 23 | yarn-error.log* 24 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 Kyle Mo 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app) and TypeScript template. 2 | 3 | # Dcard Reader 4 | A webapp that imitate Dcard app. 5 | Using Virtualized List and lazy data-loading to enhance app performance. 6 | [![code style: prettier](https://img.shields.io/badge/code_style-prettier-ff69b4.svg?style=flat-square)](https://github.com/prettier/prettier) 7 | [![FOSSA Status](https://app.fossa.com/api/projects/git%2Bgithub.com%2Fkylemocode%2Fdcard-reader.svg?type=shield)](https://app.fossa.com/projects/git%2Bgithub.com%2Fkylemocode%2Fdcard-reader?ref=badge_shield) 8 | 9 | ![image](./assets/dcard-reader.gif) 10 | 11 | ## Installation 12 | 13 | ```shell 14 | $ git clone https://github.com/kylemocode/dcard-reader.git 15 | $ cd dcard-reader 16 | $ npm install && npm start (or using yarn instead) 17 | ``` 18 | 19 | ## Features: 20 | - [X] Virtualized List 21 | - [X] Infinite Scroll 22 | - [X] Lazy Load 23 | - [X] Performance 24 | - [X] Proxy Server 25 | 26 | ### Virtualized List 27 | Use `react-window` to achieve virtualized list which is a react components for efficiently rendering large lists and tabular data.As the Chrome Performance Monitor, It took less than **4.2MB JS heap size, 350 DOM** nodes on initial renderer, and of course, it's responsive. 28 | 29 | ### Infinite Scroll && Lazy Load 30 | Use `IntersectionObserver` API to achieve infinite scroll and only load more data while scrolling to current bottom boundary. 31 | 32 | ### Performance 33 | In addition to lazy-loading data, dcard-reader also use react core functions to enhance app performance, such as `React.memo`、`useCallback`、`useMemo`...etc. 34 | 35 | ### Proxy server 36 | To solve **CORS** problem in dcard 3rd-party-API, I choose to build my own backend proxy server which powered by `express`. 37 | 38 | ## Source Code File Structure 39 | ``` 40 | src 41 | ├── api 42 | │ └── proxy.ts 43 | ├── constant 44 | │ └── api.ts 45 | ├── hook 46 | │ └── useFetchPost.tsx 47 | ├── utils 48 | │ └── media.ts 49 | ├── components 50 | │ └── LoadingPlaceHolder 51 | │ └── PostItem 52 | │ └── PostModal 53 | │ └── PostContainer 54 | │ └── ResponseInfo 55 | │ └── TopicLabel 56 | └── App.tsx 57 | └── index.css 58 | └── index.tsx 59 | └── serviceWorker.ts 60 | ``` 61 | 62 | ## Roadmap 63 | - [ ] UI/UX (More Features) 64 | - [ ] Increase Unit Test Coverage 65 | - [ ] CICD Pipeline 66 | 67 | [![FOSSA Status](https://app.fossa.com/api/projects/git%2Bgithub.com%2Fkylemocode%2Fdcard-reader.svg?type=large)](https://app.fossa.com/projects/git%2Bgithub.com%2Fkylemocode%2Fdcard-reader?ref=badge_large) -------------------------------------------------------------------------------- /api/proxy.ts: -------------------------------------------------------------------------------- 1 | const express = require('express'); 2 | const bodyParser = require('body-parser'); 3 | const axios = require('axios'); 4 | const cors = require('cors'); 5 | 6 | const app = express(); 7 | 8 | app.use(bodyParser.urlencoded({ extended: true })); 9 | app.use(bodyParser.json()) 10 | app.use(cors()); 11 | 12 | app.get('/posts', async (req, res) => { 13 | const limit = req.query.limit; 14 | const before = req.query.before || undefined; 15 | try { 16 | if (before) { 17 | const data = await axios.get('https://dcard.tw/_api/posts?popular=true'+ '&limit=' + limit + '&before=' + before) 18 | res.json(data.data); 19 | } else { 20 | const data = await axios.get('https://dcard.tw/_api/posts?popular=true'+ '&limit=' + limit) 21 | res.json(data.data); 22 | } 23 | } catch(err) { 24 | console.log('error...', err) 25 | res.send(err); 26 | } 27 | }) 28 | 29 | app.get('/post/:id', async (req, res) => { 30 | const id = req.params.id; 31 | 32 | try { 33 | const data = await axios.get('https://dcard.tw/_api/posts/'+id) 34 | res.json(data.data); 35 | } catch(err) { 36 | res.send(err); 37 | } 38 | }) 39 | 40 | app.listen(5000, () => { 41 | console.log('server listening on 5000...') 42 | }) 43 | -------------------------------------------------------------------------------- /assets/dcard-reader.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kylemocode/dcard-reader/c8e41ee77c858791ea219862a7ee99c26d5280e6/assets/dcard-reader.gif -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "dcard-reader", 3 | "version": "0.1.0", 4 | "private": true, 5 | "dependencies": { 6 | "@testing-library/user-event": "^7.1.2", 7 | "@types/jest": "^24.0.0", 8 | "@types/node": "^12.0.0", 9 | "@types/react": "^16.9.0", 10 | "@types/react-dom": "^16.9.0", 11 | "@types/react-modal": "^3.10.5", 12 | "@types/react-virtualized-auto-sizer": "^1.0.0", 13 | "@types/react-window": "^1.8.1", 14 | "@types/styled-components": "^5.0.1", 15 | "axios": "^0.19.2", 16 | "body-parser": "^1.19.0", 17 | "cors": "^2.8.5", 18 | "express": "^4.17.1", 19 | "http-proxy": "^1.18.1", 20 | "react": "^16.13.1", 21 | "react-dom": "^16.13.1", 22 | "react-modal": "^3.11.2", 23 | "react-scripts": "3.4.1", 24 | "react-window": "^1.8.5", 25 | "styled-components": "^5.1.0", 26 | "typescript": "~3.7.2", 27 | "use-media": "^1.4.0" 28 | }, 29 | "scripts": { 30 | "start": "node ./api/proxy.ts | react-scripts start", 31 | "build": "react-scripts build", 32 | "test": "react-scripts test", 33 | "eject": "react-scripts eject" 34 | }, 35 | "eslintConfig": { 36 | "extends": "react-app" 37 | }, 38 | "browserslist": { 39 | "production": [ 40 | ">0.2%", 41 | "not dead", 42 | "not op_mini all" 43 | ], 44 | "development": [ 45 | "last 1 chrome version", 46 | "last 1 firefox version", 47 | "last 1 safari version" 48 | ] 49 | }, 50 | "devDependencies": { 51 | "@testing-library/jest-dom": "^4.2.4", 52 | "@testing-library/react": "^9.5.0" 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 15 | 16 | 25 | Dcard Reader 26 | 27 | 28 | 29 | 30 |
31 | 41 | 42 | 43 | -------------------------------------------------------------------------------- /public/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "short_name": "React App", 3 | "name": "Create React App Sample", 4 | "icons": [], 5 | "start_url": ".", 6 | "display": "standalone", 7 | "theme_color": "#000000", 8 | "background_color": "#ffffff" 9 | } -------------------------------------------------------------------------------- /public/robots.txt: -------------------------------------------------------------------------------- 1 | # https://www.robotstxt.org/robotstxt.html 2 | User-agent: * 3 | Disallow: 4 | -------------------------------------------------------------------------------- /src/App.tsx: -------------------------------------------------------------------------------- 1 | import React, { useState, useRef, useCallback, useMemo } from 'react'; 2 | import { FixedSizeList as List } from "react-window"; 3 | import useMedia from 'use-media'; 4 | 5 | import PostsContainer from './components/PostsContainer'; 6 | import PostItem from './components/PostItem'; 7 | import LoadingPlaceHolder from './components/LoadingPlaceHolder'; 8 | import PostModal from './components/PostModal'; 9 | import useFetchPost from './hooks/useFetchPost'; 10 | import { FetchPostHook } from './hooks/useFetchPost' 11 | import { size } from './utils/media'; 12 | 13 | const App: React.FC = () => { 14 | const [lastId, setLastId] = useState(null); 15 | const [isModalOpen, setIsModalOpen] = useState(false); 16 | const [modalPostId, setModalPostId] = useState(null); 17 | const { loading, error, posts, hasMore }: FetchPostHook = useFetchPost(lastId); 18 | 19 | // handle FixedSizeList width 20 | const isMobileL = useMedia({ maxWidth: size.mobileL }) 21 | const isTablet = useMedia({ maxWidth: size.tablet }) 22 | const listWidth = useMemo(() => { 23 | if (!isMobileL && !isTablet) { 24 | return 625; 25 | } else if (!isMobileL && isTablet) { 26 | return 450; 27 | } else { 28 | return 300; 29 | } 30 | }, [isMobileL, isTablet]); 31 | 32 | // modal controller 33 | const handleModalClose = () => { 34 | setIsModalOpen(false); 35 | } 36 | 37 | const handleModalOpen = (postId: number) => { 38 | setIsModalOpen(true); 39 | setModalPostId(postId); 40 | } 41 | 42 | // IntersectionObserver API to handle infinite scroll 43 | const observer = useRef(); 44 | const lastPostRef = useCallback(node => { 45 | if (loading) { 46 | return; 47 | } 48 | if (observer.current) { 49 | observer.current.disconnect(); 50 | } 51 | observer.current = new IntersectionObserver(entries => { 52 | if (entries[0].isIntersecting && hasMore) { 53 | setLastId(node.dataset.id); 54 | } 55 | }) 56 | if (node) observer.current.observe(node) 57 | }, [loading, hasMore]) 58 | 59 | return ( 60 | 61 | {posts.length ? <> 69 | {({ index, style }) => { 70 | if (posts.length === index + 1) { 71 | return
72 | { 80 | handleModalOpen(posts[index].id) 81 | }} 82 | /> 83 | {loading ? : null} 84 | {error ?
Fetching posts failed...
: null} 85 |
86 | } else { 87 | return
88 | { 96 | handleModalOpen(posts[index].id) 97 | }} 98 | /> 99 |
100 | } 101 | }} 102 |
103 | : ( 104 |
105 | 106 |
107 | )} 108 |
109 | ); 110 | } 111 | 112 | export default App; -------------------------------------------------------------------------------- /src/components/LoadingPlaceHolder/LoadingPlaceHolder.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react' 2 | 3 | import { S } from './style'; 4 | 5 | const LoadingPlaceHolder: React.FC = () => { 6 | return ( 7 | 8 | 9 | 10 | 11 | 12 | ) 13 | } 14 | 15 | export default React.memo(LoadingPlaceHolder); -------------------------------------------------------------------------------- /src/components/LoadingPlaceHolder/index.ts: -------------------------------------------------------------------------------- 1 | import LoadingPlaceHolder from './LoadingPlaceHolder'; 2 | 3 | export default LoadingPlaceHolder; -------------------------------------------------------------------------------- /src/components/LoadingPlaceHolder/style.ts: -------------------------------------------------------------------------------- 1 | import styled from 'styled-components'; 2 | 3 | export const S = { 4 | PlaceHolderContainer: styled.div` 5 | width: 100%; 6 | min-height: 120px; 7 | padding: 5px 10px; 8 | display: flex; 9 | flex-direction: column; 10 | align-items: flex-start; 11 | margin-top: 20px; 12 | `, 13 | TitlePlaceHolder: styled.div` 14 | background: linear-gradient(-45deg, #e3dede, #d1cdcd, #c2c0c0, #bab8b8); 15 | background-size: 400% 400%; 16 | animation: gradient 1.5s ease infinite; 17 | width: 120px; 18 | height: 15px; 19 | border-radius: 8px; 20 | margin-bottom: 10px; 21 | 22 | @keyframes gradient { 23 | 0% { 24 | background-position: 0% 50%; 25 | } 26 | 50% { 27 | background-position: 100% 50%; 28 | } 29 | 100% { 30 | background-position: 0% 50%; 31 | } 32 | } 33 | `, 34 | ContentPlaceHolder: styled.div` 35 | background: linear-gradient(-45deg, #e3dede, #d1cdcd, #c2c0c0, #bab8b8); 36 | background-size: 400% 400%; 37 | animation: gradient 1.5s ease infinite; 38 | width: 180px; 39 | height: 15px; 40 | border-radius: 8px; 41 | margin-bottom: 10px; 42 | 43 | @keyframes gradient { 44 | 0% { 45 | background-position: 0% 50%; 46 | } 47 | 50% { 48 | background-position: 100% 50%; 49 | } 50 | 100% { 51 | background-position: 0% 50%; 52 | } 53 | } 54 | ` 55 | 56 | } -------------------------------------------------------------------------------- /src/components/PostItem/PostItem.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | 3 | import { S } from './style'; 4 | import TopicLabel from '../TopicLabel'; 5 | import ResponseInfo from '../ResponseInfo'; 6 | 7 | interface props { 8 | postTitle: string; 9 | postExcerpt: string; 10 | likeCount: number; 11 | commentCount: number; 12 | topics: string[]; 13 | onClick: any; 14 | } 15 | 16 | const PostItem: React.FC = ({ postTitle, postExcerpt, topics, likeCount, commentCount, onClick }) => { 17 | 18 | const trimExcerpt = (excerpt: string | undefined) => { 19 | if (excerpt) { 20 | if (excerpt.length <= 50) { 21 | return excerpt; 22 | } 23 | const trimedExcerpt = excerpt.split('').slice(0, 50).join(''); 24 | return trimedExcerpt + '...'; 25 | } 26 | } 27 | 28 | return ( 29 | 30 | {postTitle} 31 | {trimExcerpt(postExcerpt)} 32 | 33 | {topics && topics.map((topic, index) => { 34 | return {topic} 35 | })} 36 | 37 | 41 | 42 | ) 43 | } 44 | 45 | export default PostItem; -------------------------------------------------------------------------------- /src/components/PostItem/__tests__/postItem.test.tsx: -------------------------------------------------------------------------------- 1 | import '@testing-library/jest-dom'; 2 | 3 | import React from 'react'; 4 | import {render, fireEvent, screen} from '@testing-library/react'; 5 | import PostItem from '..'; 6 | import PostModal from '../../PostModal'; 7 | 8 | describe('PostItem', () => { 9 | 10 | beforeEach(() => { 11 | jest.resetModules(); 12 | }); 13 | 14 | it('click PostItem', () => { 15 | const defaultProps = { 16 | postTitle: '', 17 | postExcerpt: '', 18 | likeCount: 0, 19 | commentCount: 0, 20 | topics: [], 21 | onClick: () => {} 22 | }; 23 | 24 | const createWrapperRenderer = (testProps = {}) => { 25 | const props = { 26 | ...defaultProps, 27 | ...testProps, 28 | }; 29 | 30 | return render(); 31 | }; 32 | 33 | const { getByTestId } = createWrapperRenderer(); 34 | 35 | fireEvent.click(getByTestId('postItem')) 36 | }) 37 | }) -------------------------------------------------------------------------------- /src/components/PostItem/index.ts: -------------------------------------------------------------------------------- 1 | import PostItem from './PostItem'; 2 | 3 | export default PostItem; -------------------------------------------------------------------------------- /src/components/PostItem/style.ts: -------------------------------------------------------------------------------- 1 | import styled from 'styled-components'; 2 | 3 | import { device } from '../../utils/media'; 4 | 5 | export const S = { 6 | ItemContainer: styled.div` 7 | width: 100%; 8 | min-height: 200px; 9 | box-sizing: border-box; 10 | padding: 5px 10px; 11 | border-bottom: solid 1px rgba(0,0,0,0.2); 12 | cursor: pointer; 13 | overflow: hidden; 14 | 15 | @media ${device.tablet} { 16 | min-height: 250px; 17 | } 18 | `, 19 | PostTitle: styled.p` 20 | font-weight: bold; 21 | font-size: 18px; 22 | `, 23 | PostExcerpt: styled.p` 24 | font-size: 13px; 25 | color: rgba(0,0,0,0.6); 26 | min-height: 36px; 27 | `, 28 | 29 | LabelsContainer: styled.div` 30 | width: 100%; 31 | display: flex; 32 | flex-wrap: wrap; 33 | min-height: 20px; 34 | ` 35 | 36 | } -------------------------------------------------------------------------------- /src/components/PostModal/PostModal.tsx: -------------------------------------------------------------------------------- 1 | import React, { useEffect, useState } from 'react' 2 | import Modal from "react-modal" 3 | import axios from 'axios'; 4 | 5 | import LoadingPlaceHolder from '../LoadingPlaceHolder'; 6 | import { S } from './style'; 7 | import { DCARD_SINGLE_POST_BASE_URL } from '../../constant/api'; 8 | import './modal.css'; 9 | 10 | interface props { 11 | isOpen: boolean; 12 | onRequestClose: any; 13 | postId: number | null; 14 | } 15 | 16 | const PostModal: React.FC = ({ isOpen, onRequestClose, postId }) => { 17 | const [postData, setPostData] = useState({ title: '', content: '', forumName: '' }); 18 | const [isLoading, setIsLoading] = useState(false); 19 | 20 | useEffect(() => { 21 | Modal.setAppElement('body'); 22 | }, []) 23 | 24 | useEffect(() => { 25 | if (postId) { 26 | setIsLoading(true) 27 | axios.get(DCARD_SINGLE_POST_BASE_URL + postId) 28 | .then((res) => setPostData({ title: res.data.title, content: res.data.content, forumName: res.data.forumName })) 29 | .then(() => setIsLoading(false)) 30 | } 31 | }, [postId]) 32 | 33 | return ( 34 | 51 | {isLoading ? : 52 | <> 53 | {postData.title} 54 | {postData.forumName} 55 | {postData.content} 56 |

57 | 退出 58 | } 59 |
60 | ) 61 | } 62 | 63 | export default PostModal; -------------------------------------------------------------------------------- /src/components/PostModal/index.ts: -------------------------------------------------------------------------------- 1 | import PostModal from './PostModal'; 2 | 3 | export default PostModal; -------------------------------------------------------------------------------- /src/components/PostModal/modal.css: -------------------------------------------------------------------------------- 1 | .modal-base { 2 | position: absolute; 3 | background-color: #fefefe; 4 | box-sizing: border-box; 5 | margin: auto; 6 | padding: 25px; 7 | border-radius: 7px; 8 | width: 50%; 9 | height: 100%; 10 | opacity: 0; 11 | -webkit-transition: all 0.2s ease-in-out; 12 | transition: all 0.2s ease-in-out; 13 | left: 0; 14 | right: 0; 15 | top: 0; 16 | bottom: 0; 17 | outline: none; 18 | overflow: scroll; 19 | 20 | } 21 | 22 | .modal-base_after-open { 23 | opacity: 1; 24 | transform: scale(1); 25 | } 26 | 27 | .modal-base_before-close { 28 | transform: scale(.2); 29 | opacity: 0; 30 | } 31 | 32 | .overlay-base { 33 | position: fixed; 34 | top: 0; 35 | left: 0; 36 | right: 0; 37 | bottom: 0; 38 | background-color: rgba(66, 66, 66, .5); 39 | opacity: 0; 40 | transition: all 0.3s ease-out; 41 | } 42 | 43 | .overlay-base_after-open { 44 | opacity: 1; 45 | } 46 | 47 | .overlay-base_before-close { 48 | opacity: 0; 49 | } 50 | 51 | @media (max-width: 425px) { 52 | .modal-base { 53 | width: 80%; 54 | height: 50%; 55 | } 56 | } -------------------------------------------------------------------------------- /src/components/PostModal/style.ts: -------------------------------------------------------------------------------- 1 | import styled from 'styled-components'; 2 | 3 | export const S = { 4 | PostTitle: styled.h3` 5 | font-weight: bold; 6 | `, 7 | PostContent: styled.p` 8 | font-size: 14px; 9 | `, 10 | PostButton: styled.button` 11 | background-color: #00324e; 12 | color: white; 13 | border-radius: 7px; 14 | min-height: 30px; 15 | min-width: 50px; 16 | cursor: pointer; 17 | 18 | :active { 19 | outline: none; 20 | } 21 | `, 22 | PostForumName: styled.p` 23 | color: #9ecde7; 24 | font-size: 14px; 25 | font-weight: bold; 26 | ` 27 | } -------------------------------------------------------------------------------- /src/components/PostsContainer/PostsContainer.tsx: -------------------------------------------------------------------------------- 1 | import React, { ReactNode } from 'react'; 2 | 3 | import { S } from './style'; 4 | 5 | interface props { 6 | children: ReactNode; 7 | } 8 | 9 | const PostsContainer: React.FC = ({ children }) => { 10 | return ( 11 | 12 | 13 | {children} 14 | 15 | 16 | ) 17 | } 18 | 19 | export default PostsContainer; -------------------------------------------------------------------------------- /src/components/PostsContainer/index.ts: -------------------------------------------------------------------------------- 1 | import PostsContainer from './PostsContainer'; 2 | 3 | export default PostsContainer; -------------------------------------------------------------------------------- /src/components/PostsContainer/style.ts: -------------------------------------------------------------------------------- 1 | import styled from 'styled-components'; 2 | 3 | import { device } from '../../utils/media'; 4 | 5 | export const S = { 6 | FullContainer: styled.div` 7 | width: 100vw; 8 | height: 100vh; 9 | background-color: #00324e; 10 | display: flex; 11 | justify-content: center; 12 | `, 13 | InnerContainer: styled.div` 14 | width: 75%; 15 | height: 100%; 16 | background-color: white; 17 | display: flex; 18 | flex-direction: column; 19 | align-items: center; 20 | 21 | @media ${device.tablet} { 22 | width: 80%; 23 | } 24 | @media ${device.mobileXL} { 25 | width: 98%; 26 | } 27 | @media ${device.mobileM} { 28 | width: 100%; 29 | } 30 | ` 31 | } -------------------------------------------------------------------------------- /src/components/ResponseInfo/ResponseInfo.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | 3 | import { S } from './style'; 4 | 5 | interface props { 6 | likeCount: number; 7 | commentCount: number 8 | } 9 | 10 | const ResponseInfo: React.FC = ({ likeCount, commentCount }) => { 11 | return ( 12 | 13 | 14 | {likeCount} 15 | 回應 16 | {commentCount} 17 | 18 | ) 19 | } 20 | 21 | export default ResponseInfo; -------------------------------------------------------------------------------- /src/components/ResponseInfo/index.ts: -------------------------------------------------------------------------------- 1 | import ResponseInfo from './ResponseInfo'; 2 | 3 | export default ResponseInfo; -------------------------------------------------------------------------------- /src/components/ResponseInfo/style.ts: -------------------------------------------------------------------------------- 1 | import styled from 'styled-components'; 2 | 3 | export const S = { 4 | ResponseContainer: styled.div` 5 | display: flex; 6 | align-items: center; 7 | font-size: 12px; 8 | `, 9 | ResponseImg: styled.img` 10 | width: 55px; 11 | height: 25px; 12 | margin-right: 5px; 13 | 14 | `, 15 | ResponseCount: styled.p` 16 | margin-right: 10px; 17 | color: rgba(0,0,0,0.5); 18 | 19 | `, 20 | CommentTitle: styled.p` 21 | margin-right: 5px; 22 | color: rgba(0,0,0,0.5); 23 | `, 24 | CommentCount: styled.p` 25 | margin-right: 5px; 26 | color: rgba(0,0,0,0.5); 27 | ` 28 | } -------------------------------------------------------------------------------- /src/components/TopicLabel/TopicLabel.tsx: -------------------------------------------------------------------------------- 1 | import React, { ReactNode } from 'react'; 2 | 3 | import { S } from './style'; 4 | 5 | interface props { 6 | children: ReactNode; 7 | } 8 | 9 | const TopicLabel: React.FC = ({ children }) => { 10 | return ( 11 | 12 | {children} 13 | 14 | ) 15 | } 16 | 17 | export default TopicLabel; -------------------------------------------------------------------------------- /src/components/TopicLabel/index.ts: -------------------------------------------------------------------------------- 1 | import TopicLabel from './TopicLabel'; 2 | 3 | export default TopicLabel; -------------------------------------------------------------------------------- /src/components/TopicLabel/style.ts: -------------------------------------------------------------------------------- 1 | import styled from 'styled-components'; 2 | 3 | export const S = { 4 | Label: styled.div` 5 | height: 20px; 6 | width: fit-content; 7 | width: -webkit-fit-content; 8 | width: -moz-fit-content; 9 | border-radius: 8px; 10 | background-color: #efefef; 11 | display: flex; 12 | justify-content: center; 13 | align-items: center; 14 | padding: 2px 6px; 15 | font-weight: bold; 16 | font-size: 10px; 17 | margin-right: 6px; 18 | margin-bottom: 5px; 19 | ` 20 | } -------------------------------------------------------------------------------- /src/constant/api.ts: -------------------------------------------------------------------------------- 1 | export const DCARD_POPULAR_POSTS_BASE_URL = 'http://localhost:5000/posts?'; 2 | 3 | export const DCARD_SINGLE_POST_BASE_URL = 'http://localhost:5000/post/'; 4 | 5 | export const API_POST_LIMIT = 25; -------------------------------------------------------------------------------- /src/hooks/useFetchPost.tsx: -------------------------------------------------------------------------------- 1 | import { useEffect, useState } from 'react'; 2 | import axios from 'axios'; 3 | 4 | import { DCARD_POPULAR_POSTS_BASE_URL, API_POST_LIMIT } from '../constant/api'; 5 | 6 | export interface FetchPostHook { 7 | loading: boolean; 8 | error: boolean; 9 | posts: any[]; 10 | hasMore: boolean; 11 | } 12 | 13 | export default function useFetchPost(lastId?: number | null) { 14 | const [loading, setLoading] = useState(true); 15 | const [error, setError] = useState(false); 16 | const [posts, setPosts] = useState([]); 17 | const [hasMore, setHasMore] = useState(true); 18 | 19 | useEffect(() => { 20 | setLoading(true); 21 | setError(false); 22 | 23 | if (lastId) { 24 | setTimeout(() => { 25 | axios.get(DCARD_POPULAR_POSTS_BASE_URL + '&limit=' + API_POST_LIMIT + '&before=' + lastId) 26 | .then((result) => { 27 | // @ts-ignore 28 | setPosts(prevPosts => { 29 | return [...prevPosts, ...result.data] 30 | }); 31 | setHasMore(result.data.length > 0); 32 | setLoading(false); 33 | }) 34 | .catch(() => { 35 | setError(true); 36 | }) 37 | }, 700) 38 | } else { 39 | // 第一次進入頁面 40 | axios.get(DCARD_POPULAR_POSTS_BASE_URL + '&limit=' + API_POST_LIMIT) 41 | .then((result) => { 42 | setPosts(result.data); 43 | setHasMore(result.data.length > 0); 44 | setLoading(false); 45 | }) 46 | .catch(() => { 47 | setError(true); 48 | }) 49 | } 50 | }, [lastId]) 51 | 52 | return { loading, error, posts, hasMore }; 53 | } 54 | -------------------------------------------------------------------------------- /src/index.css: -------------------------------------------------------------------------------- 1 | body { 2 | margin: 0; 3 | /* font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 4 | 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', 5 | sans-serif; */ 6 | -webkit-font-smoothing: antialiased; 7 | -moz-osx-font-smoothing: grayscale; 8 | font-family: 'Roboto','Helvetica Neue','Helvetica','Arial','微軟正黑體'; 9 | } 10 | 11 | code { 12 | font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New', 13 | monospace; 14 | } -------------------------------------------------------------------------------- /src/index.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import ReactDOM from 'react-dom'; 3 | import './index.css'; 4 | import App from './App'; 5 | import * as serviceWorker from './serviceWorker'; 6 | 7 | ReactDOM.render( 8 | 9 | 10 | , 11 | document.getElementById('root') 12 | ); 13 | 14 | serviceWorker.register(); 15 | -------------------------------------------------------------------------------- /src/react-app-env.d.ts: -------------------------------------------------------------------------------- 1 | /// 2 | -------------------------------------------------------------------------------- /src/serviceWorker.ts: -------------------------------------------------------------------------------- 1 | // This optional code is used to register a service worker. 2 | // register() is not called by default. 3 | 4 | // This lets the app load faster on subsequent visits in production, and gives 5 | // it offline capabilities. However, it also means that developers (and users) 6 | // will only see deployed updates on subsequent visits to a page, after all the 7 | // existing tabs open on the page have been closed, since previously cached 8 | // resources are updated in the background. 9 | 10 | // To learn more about the benefits of this model and instructions on how to 11 | // opt-in, read https://bit.ly/CRA-PWA 12 | 13 | const isLocalhost = Boolean( 14 | window.location.hostname === 'localhost' || 15 | // [::1] is the IPv6 localhost address. 16 | window.location.hostname === '[::1]' || 17 | // 127.0.0.0/8 are considered localhost for IPv4. 18 | window.location.hostname.match( 19 | /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/ 20 | ) 21 | ); 22 | 23 | type Config = { 24 | onSuccess?: (registration: ServiceWorkerRegistration) => void; 25 | onUpdate?: (registration: ServiceWorkerRegistration) => void; 26 | }; 27 | 28 | export function register(config?: Config) { 29 | if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) { 30 | // The URL constructor is available in all browsers that support SW. 31 | const publicUrl = new URL( 32 | process.env.PUBLIC_URL, 33 | window.location.href 34 | ); 35 | if (publicUrl.origin !== window.location.origin) { 36 | // Our service worker won't work if PUBLIC_URL is on a different origin 37 | // from what our page is served on. This might happen if a CDN is used to 38 | // serve assets; see https://github.com/facebook/create-react-app/issues/2374 39 | return; 40 | } 41 | 42 | window.addEventListener('load', () => { 43 | const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`; 44 | 45 | if (isLocalhost) { 46 | // This is running on localhost. Let's check if a service worker still exists or not. 47 | checkValidServiceWorker(swUrl, config); 48 | 49 | // Add some additional logging to localhost, pointing developers to the 50 | // service worker/PWA documentation. 51 | navigator.serviceWorker.ready.then(() => { 52 | console.log( 53 | 'This web app is being served cache-first by a service ' + 54 | 'worker. To learn more, visit https://bit.ly/CRA-PWA' 55 | ); 56 | }); 57 | } else { 58 | // Is not localhost. Just register service worker 59 | registerValidSW(swUrl, config); 60 | } 61 | }); 62 | } 63 | } 64 | 65 | function registerValidSW(swUrl: string, config?: Config) { 66 | navigator.serviceWorker 67 | .register(swUrl) 68 | .then(registration => { 69 | registration.onupdatefound = () => { 70 | const installingWorker = registration.installing; 71 | if (installingWorker == null) { 72 | return; 73 | } 74 | installingWorker.onstatechange = () => { 75 | if (installingWorker.state === 'installed') { 76 | if (navigator.serviceWorker.controller) { 77 | // At this point, the updated precached content has been fetched, 78 | // but the previous service worker will still serve the older 79 | // content until all client tabs are closed. 80 | console.log( 81 | 'New content is available and will be used when all ' + 82 | 'tabs for this page are closed. See https://bit.ly/CRA-PWA.' 83 | ); 84 | 85 | // Execute callback 86 | if (config && config.onUpdate) { 87 | config.onUpdate(registration); 88 | } 89 | } else { 90 | // At this point, everything has been precached. 91 | // It's the perfect time to display a 92 | // "Content is cached for offline use." message. 93 | console.log('Content is cached for offline use.'); 94 | 95 | // Execute callback 96 | if (config && config.onSuccess) { 97 | config.onSuccess(registration); 98 | } 99 | } 100 | } 101 | }; 102 | }; 103 | }) 104 | .catch(error => { 105 | console.error('Error during service worker registration:', error); 106 | }); 107 | } 108 | 109 | function checkValidServiceWorker(swUrl: string, config?: Config) { 110 | // Check if the service worker can be found. If it can't reload the page. 111 | fetch(swUrl, { 112 | headers: { 'Service-Worker': 'script' } 113 | }) 114 | .then(response => { 115 | // Ensure service worker exists, and that we really are getting a JS file. 116 | const contentType = response.headers.get('content-type'); 117 | if ( 118 | response.status === 404 || 119 | (contentType != null && contentType.indexOf('javascript') === -1) 120 | ) { 121 | // No service worker found. Probably a different app. Reload the page. 122 | navigator.serviceWorker.ready.then(registration => { 123 | registration.unregister().then(() => { 124 | window.location.reload(); 125 | }); 126 | }); 127 | } else { 128 | // Service worker found. Proceed as normal. 129 | registerValidSW(swUrl, config); 130 | } 131 | }) 132 | .catch(() => { 133 | console.log( 134 | 'No internet connection found. App is running in offline mode.' 135 | ); 136 | }); 137 | } 138 | 139 | export function unregister() { 140 | if ('serviceWorker' in navigator) { 141 | navigator.serviceWorker.ready 142 | .then(registration => { 143 | registration.unregister(); 144 | }) 145 | .catch(error => { 146 | console.error(error.message); 147 | }); 148 | } 149 | } 150 | -------------------------------------------------------------------------------- /src/utils/media.ts: -------------------------------------------------------------------------------- 1 | export const size = { 2 | mobileS: '320px', 3 | mobileM: '375px', 4 | mobileL: '425px', 5 | mobileXL: '450px', 6 | tablet: '768px', 7 | } 8 | 9 | export const device = { 10 | mobileS: `(max-width: ${size.mobileS})`, 11 | mobileM: `(max-width: ${size.mobileM})`, 12 | mobileL: `(max-width: ${size.mobileL})`, 13 | mobileXL: `(max-width: ${size.mobileXL})`, 14 | tablet: `(max-width: ${size.tablet})`, 15 | }; -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "es5", 4 | "lib": [ 5 | "dom", 6 | "dom.iterable", 7 | "esnext" 8 | ], 9 | "allowJs": true, 10 | "skipLibCheck": true, 11 | "esModuleInterop": true, 12 | "allowSyntheticDefaultImports": true, 13 | "strict": true, 14 | "forceConsistentCasingInFileNames": true, 15 | "module": "esnext", 16 | "moduleResolution": "node", 17 | "resolveJsonModule": true, 18 | "isolatedModules": true, 19 | "noEmit": true, 20 | "jsx": "react" 21 | }, 22 | "include": [ 23 | "src" 24 | ] 25 | } 26 | --------------------------------------------------------------------------------