├── .babelrc ├── .eslintignore ├── .github └── workflows │ ├── ci.yml │ └── codeql.yml ├── .gitignore ├── .lintstagedrc.cjs ├── .nvmrc ├── .prettierignore ├── .simple-git-hooks.cjs ├── .stylelintignore ├── .yarn ├── plugins │ └── plugin-prepare-lifecycle.cjs └── releases │ └── yarn-3.7.0.cjs ├── .yarnrc.yml ├── LICENSE ├── README.md ├── build ├── base.js ├── config.js ├── react.client.babel.js ├── react.server.babel.js ├── server.babel.js └── template.js ├── jsconfig.json ├── package.json ├── postcss.config.cjs ├── public ├── external.svg ├── favicon.ico ├── logo.svg └── manifest.json ├── server ├── dev.js ├── index.js └── template.pug ├── src ├── .babelrc ├── App.js ├── api │ ├── create-api-client.js │ ├── create-api-server.js │ └── index.js ├── components │ ├── Comment │ │ ├── index.js │ │ └── styles.scss │ ├── Item │ │ ├── index.js │ │ └── styles.scss │ └── Spinner │ │ ├── index.js │ │ └── styles.scss ├── entry-client.js ├── entry-server.js ├── store │ ├── actions.js │ ├── index.js │ ├── reducers.js │ ├── selectors.js │ └── types.js ├── styles │ └── app.scss ├── utils │ ├── index.js │ └── ssr.js └── views │ ├── CreateListView.js │ ├── ItemList │ ├── index.js │ └── styles.scss │ ├── ItemView │ ├── index.js │ └── styles.scss │ └── UserView │ ├── index.js │ └── styles.scss ├── vercel.json └── yarn.lock /.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "presets": [ 3 | [ 4 | "@1stg", 5 | {} 6 | ] 7 | ], 8 | "targets": { 9 | "esmodules": true 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /.eslintignore: -------------------------------------------------------------------------------- 1 | .yarn 2 | dist 3 | !/.*.js 4 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: 4 | - push 5 | - pull_request 6 | 7 | jobs: 8 | default: 9 | strategy: 10 | matrix: 11 | node: 12 | - 16 13 | os: 14 | - macOS-latest 15 | - ubuntu-latest 16 | runs-on: ${{ matrix.os }} 17 | steps: 18 | - uses: actions/checkout@v4 19 | 20 | - uses: actions/setup-node@v4 21 | with: 22 | node-version: ${{ matrix.node }} 23 | cache: yarn 24 | 25 | - name: Install Dependencies 26 | run: yarn --immutable 27 | 28 | - name: Lint, Build 29 | run: | 30 | yarn lint 31 | yarn build 32 | env: 33 | EFF_NO_LINK_RULES: true 34 | PARSER_NO_WATCH: true 35 | -------------------------------------------------------------------------------- /.github/workflows/codeql.yml: -------------------------------------------------------------------------------- 1 | name: CodeQL 2 | 3 | on: 4 | push: 5 | branches: 6 | - master 7 | pull_request: 8 | branches: 9 | - master 10 | schedule: 11 | - cron: 39 11 * * 1 12 | 13 | jobs: 14 | analyze: 15 | name: Analyze 16 | runs-on: ubuntu-latest 17 | permissions: 18 | actions: read 19 | contents: read 20 | security-events: write 21 | 22 | strategy: 23 | fail-fast: false 24 | matrix: 25 | language: 26 | - javascript 27 | 28 | steps: 29 | - name: Checkout 30 | uses: actions/checkout@v4 31 | 32 | - name: Initialize CodeQL 33 | uses: github/codeql-action/init@v3 34 | with: 35 | languages: ${{ matrix.language }} 36 | queries: +security-and-quality 37 | 38 | - name: Autobuild 39 | uses: github/codeql-action/autobuild@v3 40 | 41 | - name: Perform CodeQL Analysis 42 | uses: github/codeql-action/analyze@v3 43 | with: 44 | category: '/language:${{ matrix.language }}' 45 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | dist 2 | node_modules 3 | sync 4 | *.log 5 | .*cache 6 | .yarn/* 7 | !.yarn/plugins 8 | !.yarn/releases 9 | -------------------------------------------------------------------------------- /.lintstagedrc.cjs: -------------------------------------------------------------------------------- 1 | module.exports = require('@1stg/lint-staged') 2 | -------------------------------------------------------------------------------- /.nvmrc: -------------------------------------------------------------------------------- 1 | 16.20.2 2 | -------------------------------------------------------------------------------- /.prettierignore: -------------------------------------------------------------------------------- 1 | .yarn 2 | dist 3 | -------------------------------------------------------------------------------- /.simple-git-hooks.cjs: -------------------------------------------------------------------------------- 1 | module.exports = require('@1stg/simple-git-hooks') 2 | -------------------------------------------------------------------------------- /.stylelintignore: -------------------------------------------------------------------------------- 1 | .*rc 2 | .gitignore 3 | *.cjs 4 | *.ico 5 | *.js 6 | *.json 7 | *.lock 8 | *.md 9 | *.pug 10 | *.svg 11 | *.yml 12 | dist 13 | node_modules 14 | LICENSE 15 | -------------------------------------------------------------------------------- /.yarn/plugins/plugin-prepare-lifecycle.cjs: -------------------------------------------------------------------------------- 1 | module.exports={name:"plugin-prepare-lifecycle",factory:e=>({hooks:{afterAllInstalled(r){if(!r.topLevelWorkspace.manifest.scripts.get("prepare"))return;e("@yarnpkg/shell").execute("yarn prepare")}}})}; 2 | -------------------------------------------------------------------------------- /.yarnrc.yml: -------------------------------------------------------------------------------- 1 | enableGlobalCache: true 2 | 3 | nodeLinker: node-modules 4 | 5 | plugins: 6 | - checksum: 37b2361b1502b2054e6779788c0e9bdd6a90ce49852a8cad2feda79b0614ec94f06fb6e78951f5f95429c610d7934dd077caa47413a0227378a102c55161616d 7 | path: .yarn/plugins/plugin-prepare-lifecycle.cjs 8 | spec: "https://github.com/un-es/yarn-plugin-prepare-lifecycle/releases/download/v0.0.1/index.js" 9 | 10 | yarnPath: .yarn/releases/yarn-3.7.0.cjs 11 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2017 JounQin 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 | # react-hackernews 2 | 3 | [![Travis](https://img.shields.io/travis/com/JounQin/react-hackernews/master.svg)](https://travis-ci.com/JounQin/react-hackernews) 4 | [![code style: prettier](https://img.shields.io/badge/code_style-prettier-ff69b4.svg)](https://github.com/prettier/prettier) 5 | 6 | HackerNews clone built with React, ReactRouter & Redux, with full page server-side rendering 7 | 8 |

9 | 10 | react-hackernews 11 |
12 | Live Demo 13 |
14 |

15 | 16 | ## Features 17 | 18 | > Note: in practice, it is unnecessary to code-split for an app of this size (where each async chunk is only a few kilobytes), nor is it optimal to extract an extra CSS file (which is only 1kb) -- they are used simply because this is a demo app showcasing all the supported features. In real apps, you should always measure and optimize based on your actual app constraints. 19 | 20 | - Server Side Rendering 21 | - react + react-router + redux working together 22 | - Server-side data pre-fetching 23 | - Client-side state & DOM hydration 24 | - Automatically inlines CSS used by rendered components only 25 | - Preload / prefetch resource hints 26 | - Route-level code splitting 27 | - custom dynamic title for SEO 28 | - Progressive Web App 29 | - App manifest 30 | - Service worker 31 | - 100/100 Lighthouse score 32 | - Experience 33 | - Hot-reload in development 34 | - CSS extraction for production 35 | 36 | ## Inspired by 37 | 38 | [vue-hackernews-2.0](https://github.com/vuejs/vue-hackernews-2.0) 39 | 40 | [react-server-renderer](https://github.com/JounQin/react-server-renderer) / [vue-server-renderer](https://ssr.vuejs.org) 41 | 42 | [react-async-component](https://github.com/ctrlplusb/react-async-component) / [react-async-bootstrapper](https://github.com/ctrlplusb/react-async-bootstrapper) 43 | 44 | [react-style-loader](https://github.com/JounQin/react-style-loader) / [vue-style-loader](https://github.com/vuejs/vue-style-loader) 45 | 46 | ## Architecture Overview 47 | 48 | screen shot 2016-08-11 at 6 06 57 pm 49 | 50 | ## Build Setup 51 | 52 | **Requires Node.js 7+** 53 | 54 | ```bash 55 | # install dependencies 56 | npm install # or yarn 57 | 58 | # serve in dev mode, with hot reload at localhost:4000 59 | yarn dev 60 | 61 | # build for production 62 | yarn build 63 | 64 | # If you care about node_modules size 65 | yarn run prune 66 | 67 | # serve in production mode 68 | yarn start 69 | ``` 70 | 71 | ## License 72 | 73 | MIT 74 | -------------------------------------------------------------------------------- /build/base.js: -------------------------------------------------------------------------------- 1 | import FriendlyErrorsWebpackPlugin from '@soda/friendly-errors-webpack-plugin' 2 | import MiniCssExtractPlugin from 'mini-css-extract-plugin' 3 | import webpack from 'webpack' 4 | 5 | import { NODE_ENV, __DEV__, hasType, resolve } from './config.js' 6 | 7 | const options = { 8 | sourceMap: __DEV__, 9 | } 10 | 11 | const cssLoaders = manualInject => [ 12 | manualInject 13 | ? { 14 | loader: 'react-style-loader', 15 | options: { 16 | manualInject, 17 | }, 18 | } 19 | : MiniCssExtractPlugin.loader, 20 | { 21 | loader: 'css-loader', 22 | options: { 23 | ...options, 24 | esModule: false, 25 | }, 26 | }, 27 | { 28 | loader: 'postcss-loader', 29 | options, 30 | }, 31 | { 32 | loader: 'sass-loader', 33 | options, 34 | }, 35 | ] 36 | 37 | export const babelLoader = _isServer => ({ 38 | test: /\.js$/, 39 | loader: 'babel-loader', 40 | exclude: /node_modules/, 41 | options: { 42 | cacheDirectory: true, 43 | }, 44 | }) 45 | 46 | /** 47 | * @type {import('webpack').Configuration} 48 | */ 49 | export const baseConfig = { 50 | mode: NODE_ENV, 51 | resolve: { 52 | alias: { 53 | lodash$: 'lodash-es', 54 | }, 55 | extensions: ['.js', '.scss'], 56 | modules: [resolve('src'), 'node_modules'], 57 | }, 58 | module: { 59 | rules: [ 60 | { 61 | test: /\.pug$/, 62 | loader: 'pug-plain-loader', 63 | options: { 64 | pretty: __DEV__, 65 | }, 66 | }, 67 | { 68 | test: /\.scss$/, 69 | oneOf: [ 70 | { 71 | test: /app.scss$/, 72 | use: cssLoaders(), 73 | }, 74 | { 75 | use: cssLoaders(true), 76 | }, 77 | ], 78 | }, 79 | ], 80 | }, 81 | plugins: [ 82 | new webpack.DefinePlugin({ 83 | __DEV__, 84 | }), 85 | new MiniCssExtractPlugin({ 86 | filename: `[name].[${hasType}].css`, 87 | }), 88 | new FriendlyErrorsWebpackPlugin(), 89 | ], 90 | } 91 | -------------------------------------------------------------------------------- /build/config.js: -------------------------------------------------------------------------------- 1 | import { createRequire } from 'module' 2 | import path from 'path' 3 | 4 | export const NODE_ENV = process.env.NODE_ENV || 'development' 5 | 6 | export const __DEV__ = NODE_ENV === 'development' 7 | 8 | export const hasType = __DEV__ ? 'hash' : 'contenthash' 9 | 10 | export const serverHost = '0.0.0.0' 11 | 12 | const DEFAULT_PORT = 4000 13 | 14 | export const serverPort = process.env.PORT || DEFAULT_PORT 15 | 16 | export const publicPath = '/' 17 | 18 | export const { resolve } = path 19 | 20 | export const runtimeRequire = 21 | // eslint-disable-next-line camelcase 22 | typeof __non_webpack_require__ === 'undefined' 23 | ? createRequire(path.resolve('__test__.js')) 24 | : // eslint-disable-next-line camelcase 25 | __non_webpack_require__ 26 | -------------------------------------------------------------------------------- /build/react.client.babel.js: -------------------------------------------------------------------------------- 1 | import { ReactSSRClientPlugin } from 'react-server-renderer/client-plugin' 2 | import webpack from 'webpack' 3 | import { merge } from 'webpack-merge' 4 | import { GenerateSW } from 'workbox-webpack-plugin' 5 | 6 | import { babelLoader, baseConfig } from './base.js' 7 | import { __DEV__, publicPath, hasType, resolve } from './config.js' 8 | 9 | /** 10 | * @type {import('webpack').Configuration} 11 | */ 12 | export const clientConfig = merge(baseConfig, { 13 | entry: { 14 | app: [resolve('src/entry-client.js')], 15 | }, 16 | resolve: { 17 | alias: { 18 | 'create-api': './create-api-client.js', 19 | }, 20 | }, 21 | output: { 22 | publicPath, 23 | path: resolve('dist/static'), 24 | filename: `[name].[${hasType}].js`, 25 | }, 26 | module: { 27 | rules: [babelLoader()], 28 | }, 29 | optimization: { 30 | runtimeChunk: { 31 | name: 'manifest', 32 | }, 33 | splitChunks: { 34 | cacheGroups: { 35 | vendors: { 36 | chunks: 'initial', 37 | name: 'vendors', 38 | test: /node_modules/, 39 | }, 40 | }, 41 | }, 42 | }, 43 | plugins: [ 44 | new webpack.DefinePlugin({ 45 | 'process.env.REACT_ENV': '"client"', 46 | __SERVER__: false, 47 | }), 48 | new ReactSSRClientPlugin({ 49 | filename: '../react-ssr-client-manifest.json', 50 | }), 51 | ], 52 | }) 53 | 54 | if (!__DEV__) { 55 | clientConfig.plugins.push( 56 | new GenerateSW({ 57 | cacheId: 'react-hn', 58 | swDest: 'service-worker.js', 59 | dontCacheBustURLsMatching: /./, 60 | exclude: [/index\.html$/, /\.map$/, /\.json$/], 61 | runtimeCaching: [ 62 | { 63 | urlPattern: /^https?:\/\//, 64 | handler: 'NetworkFirst', 65 | }, 66 | ], 67 | }), 68 | ) 69 | } 70 | 71 | export default clientConfig 72 | -------------------------------------------------------------------------------- /build/react.server.babel.js: -------------------------------------------------------------------------------- 1 | import { ReactSSRServerPlugin } from 'react-server-renderer/server-plugin' 2 | import webpack from 'webpack' 3 | import { merge } from 'webpack-merge' 4 | import nodeExternals from 'webpack-node-externals' 5 | 6 | import { babelLoader, baseConfig } from './base.js' 7 | import { resolve } from './config.js' 8 | 9 | /** 10 | * @type {import('webpack').Configuration} 11 | */ 12 | export const serverConfig = merge(baseConfig, { 13 | entry: resolve('src/entry-server.js'), 14 | resolve: { 15 | alias: { 16 | 'create-api': './create-api-server.js', 17 | }, 18 | }, 19 | target: 'node', 20 | output: { 21 | path: resolve('dist'), 22 | filename: `[name].[chunkhash].js`, 23 | libraryTarget: 'commonjs2', 24 | }, 25 | externals: nodeExternals({ 26 | allowlist: /\.s?css$/, 27 | }), 28 | module: { 29 | rules: [babelLoader(true)], 30 | }, 31 | plugins: [ 32 | new webpack.DefinePlugin({ 33 | 'process.env.REACT_ENV': '"server"', 34 | __SERVER__: true, 35 | }), 36 | new ReactSSRServerPlugin(), 37 | ], 38 | }) 39 | 40 | export default serverConfig 41 | -------------------------------------------------------------------------------- /build/server.babel.js: -------------------------------------------------------------------------------- 1 | import nodeExternals from 'webpack-node-externals' 2 | 3 | import { babelLoader } from './base.js' 4 | import { NODE_ENV, resolve } from './config.js' 5 | 6 | export default { 7 | mode: NODE_ENV, 8 | entry: resolve('server/index.js'), 9 | output: { 10 | path: resolve('dist'), 11 | filename: 'server.js', 12 | }, 13 | target: 'node', 14 | externals: nodeExternals(), 15 | module: { 16 | rules: [babelLoader(true)], 17 | }, 18 | } 19 | -------------------------------------------------------------------------------- /build/template.js: -------------------------------------------------------------------------------- 1 | import { writeFileSync } from 'fs' 2 | import path from 'path' 3 | import { fileURLToPath } from 'url' 4 | 5 | import { minify } from 'html-minifier' 6 | import { renderFile } from 'pug' 7 | 8 | const result = minify(renderFile('server/template.pug'), { 9 | collapseWhitespace: true, 10 | minifyCSS: true, 11 | minifyJS: true, 12 | }) 13 | 14 | writeFileSync( 15 | path.resolve(fileURLToPath(import.meta.url), '../../dist/template.html'), 16 | result, 17 | ) 18 | -------------------------------------------------------------------------------- /jsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "@1stg/tsconfig/node16", 3 | "compilerOptions": { 4 | "paths": { 5 | "*": ["./src/*"] 6 | } 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "react-hackernews", 3 | "version": "0.0.12", 4 | "type": "module", 5 | "description": "HackerNews clone built with React, ReactRouter & Redux, with server-side rendering", 6 | "repository": "git@github.com:JounQin/react-hackernews.git", 7 | "author": "JounQin ", 8 | "license": "MIT", 9 | "private": true, 10 | "packageManager": "yarn@3.8.5", 11 | "scripts": { 12 | "build": "rimraf dist && cross-env DEBUG='1stg:*' NODE_ENV=production run-p build:react:client build:react:server build:server build:template", 13 | "build:react:client": "webpack --config=build/react.client.babel.js --color --progress", 14 | "build:react:server": "webpack --config=build/react.server.babel.js --color --progress", 15 | "build:server": "webpack --config build/server.babel.js --color --progress", 16 | "build:template": "mkdir -p dist/static && node build/template.js", 17 | "dev": "cross-env DEBUG='1stg:*' babel-node server", 18 | "lint": "run-p 'lint:*'", 19 | "lint:es": "eslint . --cache --max-warnings=10", 20 | "lint:style": "stylelint . --cache", 21 | "prepare": "simple-git-hooks || exit 0", 22 | "prune": "cross-env YARN_ENABLE_OFFLINE_MODE=1 yarn workspaces focus --production", 23 | "start": "cross-env DEBUG='1stg:*' NODE_ENV=production node dist/server" 24 | }, 25 | "dependencies": { 26 | "connected-react-router": "^6.9.3", 27 | "core-js": "^3.35.1", 28 | "cross-env": "^7.0.3", 29 | "debug": "^4.3.4", 30 | "firebase": "^10.7.2", 31 | "history": "^4.10.1", 32 | "hoist-non-react-statics": "^3.3.2", 33 | "koa": "^2.15.0", 34 | "koa-cash": "^4.1.1", 35 | "koa-compose": "^4.1.0", 36 | "koa-compress": "^5.1.1", 37 | "koa-logger": "^3.2.1", 38 | "koa-mount": "^4.0.0", 39 | "koa-static-cache": "^5.1.4", 40 | "lodash-es": "^4.17.21", 41 | "lru-cache": "^10.1.0", 42 | "path-to-regexp": "^6.2.1", 43 | "react": "^18.2.0", 44 | "react-dom": "^18.2.0", 45 | "react-loadable": "^5.5.0", 46 | "react-redux": "^9.1.0", 47 | "react-router": "^5.3.4", 48 | "react-router-config": "^5.1.1", 49 | "react-router-dom": "^5.3.4", 50 | "react-server-renderer": "^2.0.3", 51 | "react-transition-group": "^4.4.5", 52 | "redux": "^5.0.1", 53 | "redux-thunk": "^3.1.0", 54 | "serialize-javascript": "^6.0.2" 55 | }, 56 | "devDependencies": { 57 | "@1stg/app-config": "^10.0.1", 58 | "@babel/node": "^7.23.9", 59 | "@commitlint/cli": "^18.6.1", 60 | "@soda/friendly-errors-webpack-plugin": "^1.8.1", 61 | "@types/webpack": "^4.41.38", 62 | "@unts/patch-package": "^8.0.0", 63 | "babel-loader": "^8.3.0", 64 | "css-loader": "^5.2.7", 65 | "eslint": "^8.56.0", 66 | "eslint-import-resolver-typescript": "^3.6.1", 67 | "html-minifier": "^4.0.0", 68 | "koa-webpack": "^6.0.0", 69 | "lint-staged": "^15.2.2", 70 | "mini-css-extract-plugin": "^1.6.2", 71 | "npm-run-all2": "^6.1.2", 72 | "postcss-loader": "^4.3.0", 73 | "prettier": "^3.2.5", 74 | "prop-types": "^15.8.1", 75 | "pug": "^3.0.2", 76 | "pug-plain-loader": "^1.1.0", 77 | "react-style-loader": "^3.0.1", 78 | "rimraf": "^5.0.5", 79 | "sass": "^1.71.0", 80 | "sass-loader": "^10.5.2", 81 | "simple-git-hooks": "^2.9.0", 82 | "stylelint": "^16.1.0", 83 | "webpack": "^4.47.0", 84 | "webpack-cli": "^4.10.0", 85 | "webpack-merge": "^5.10.0", 86 | "webpack-node-externals": "^3.0.0", 87 | "workbox-webpack-plugin": "^7.0.0" 88 | }, 89 | "resolutions": { 90 | "prettier": "^3.2.5" 91 | }, 92 | "browserslist": [ 93 | "extends @1stg/browserslist-config" 94 | ], 95 | "commitlint": { 96 | "extends": "@1stg" 97 | }, 98 | "eslintConfig": { 99 | "extends": [ 100 | "@1stg/eslint-config/loose" 101 | ], 102 | "settings": { 103 | "import/resolver": { 104 | "typescript": { 105 | "project": "jsconfig.json" 106 | } 107 | } 108 | }, 109 | "env": { 110 | "browser": true 111 | }, 112 | "globals": { 113 | "__DEV__": false, 114 | "__SERVER__": false 115 | }, 116 | "rules": { 117 | "markup/markup": "off", 118 | "unicorn/prefer-node-protocol": "off" 119 | }, 120 | "overrides": [ 121 | { 122 | "files": "**/store/*", 123 | "rules": { 124 | "sonarjs/no-small-switch": "off" 125 | } 126 | } 127 | ] 128 | }, 129 | "prettier": "@1stg/prettier-config", 130 | "renovate": { 131 | "extends": [ 132 | "github>1stG/configs" 133 | ] 134 | }, 135 | "stylelint": { 136 | "extends": [ 137 | "@1stg/stylelint-config/scss/loose", 138 | "@1stg/stylelint-config/modules" 139 | ] 140 | } 141 | } 142 | -------------------------------------------------------------------------------- /postcss.config.cjs: -------------------------------------------------------------------------------- 1 | const config = { 2 | plugins: { 3 | autoprefixer: null, 4 | }, 5 | } 6 | 7 | if (process.env.NODE_ENV === 'production') { 8 | config.plugins.cssnano = null 9 | } 10 | 11 | module.exports = config 12 | -------------------------------------------------------------------------------- /public/external.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | External Link 4 | 5 | 9 | 13 | 14 | -------------------------------------------------------------------------------- /public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JounQin/react-hackernews/71eae3399856967038723b403120472446ad518a/public/favicon.ico -------------------------------------------------------------------------------- /public/logo.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | React Logo 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /public/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "React Hackernews", 3 | "short_name": "React HN", 4 | "icons": [ 5 | { 6 | "src": "/public/logo.svg", 7 | "sizes": "48x48 72x72 96x96 128x128 256x256 512x512", 8 | "type": "image/svg" 9 | } 10 | ], 11 | "start_url": "/top", 12 | "background_color": "#f2f3f5", 13 | "display": "standalone", 14 | "theme_color": "#00d8ff" 15 | } 16 | -------------------------------------------------------------------------------- /server/dev.js: -------------------------------------------------------------------------------- 1 | import _debug from 'debug' 2 | import koaWebpack from 'koa-webpack' 3 | import MFS from 'memory-fs' 4 | import webpack from 'webpack' 5 | 6 | import { resolve } from '../build/config.js' 7 | import { clientConfig } from '../build/react.client.babel.js' 8 | import { serverConfig } from '../build/react.server.babel.js' 9 | 10 | const debug = _debug('1stg:server:dev') 11 | 12 | export default after => { 13 | let _resolve, clientManifest, bundle, fs 14 | 15 | const readyPromise = new Promise(resolve => { 16 | _resolve = resolve 17 | }) 18 | 19 | const ready = (...args) => { 20 | _resolve() 21 | after(...args) 22 | } 23 | 24 | const clientCompiler = webpack(clientConfig) 25 | 26 | const webpackMiddlewarePromise = koaWebpack({ 27 | compiler: clientCompiler, 28 | devMiddleware: { 29 | stats: { 30 | colors: true, 31 | }, 32 | }, 33 | }) 34 | 35 | clientCompiler.plugin('done', stats => { 36 | stats = stats.toJson() 37 | 38 | // eslint-disable-next-line unicorn/no-array-callback-reference 39 | stats.errors.forEach(debug) 40 | 41 | // eslint-disable-next-line unicorn/no-array-callback-reference 42 | stats.warnings.forEach(debug) 43 | 44 | if (stats.errors.length > 0) { 45 | return 46 | } 47 | 48 | webpackMiddlewarePromise.then(webpackMiddleware => { 49 | fs = webpackMiddleware.devMiddleware.fileSystem 50 | 51 | clientManifest = JSON.parse( 52 | fs.readFileSync(resolve('dist/react-ssr-client-manifest.json')), 53 | ) 54 | 55 | if (bundle) { 56 | ready({ bundle, clientManifest, fs }) 57 | } 58 | }) 59 | }) 60 | 61 | const mfs = new MFS() 62 | const serverCompiler = webpack(serverConfig) 63 | serverCompiler.outputFileSystem = mfs 64 | 65 | serverCompiler.watch({}, (err, stats) => { 66 | if (err) throw err 67 | stats = stats.toJson() 68 | if (stats.errors.length > 0) { 69 | return 70 | } 71 | 72 | bundle = JSON.parse( 73 | mfs.readFileSync(resolve('dist/react-ssr-server-bundle.json')), 74 | ) 75 | 76 | if (clientManifest) { 77 | ready({ bundle, clientManifest, fs }) 78 | } 79 | }) 80 | 81 | return { readyPromise, webpackMiddlewarePromise } 82 | } 83 | -------------------------------------------------------------------------------- /server/index.js: -------------------------------------------------------------------------------- 1 | import fs from 'fs' 2 | import { createRequire } from 'module' 3 | import path from 'path' 4 | 5 | import _debug from 'debug' 6 | import Koa from 'koa' 7 | import cash from 'koa-cash' 8 | import compose from 'koa-compose' 9 | import compress from 'koa-compress' 10 | import logger from 'koa-logger' 11 | import mount from 'koa-mount' 12 | import serve from 'koa-static-cache' 13 | import { LRUCache } from 'lru-cache' 14 | import { createBundleRenderer } from 'react-server-renderer' 15 | 16 | import { 17 | __DEV__, 18 | resolve, 19 | runtimeRequire, 20 | serverHost, 21 | serverPort, 22 | } from '../build/config.js' 23 | 24 | const require = createRequire(path.resolve('__test__.js')) 25 | 26 | const debug = _debug('1stg:server') 27 | 28 | const template = __DEV__ 29 | ? require('pug').renderFile(resolve('server/template.pug'), { 30 | pretty: true, 31 | }) 32 | : fs.readFileSync(resolve('dist/template.html'), 'utf8') 33 | 34 | const app = new Koa() 35 | 36 | /** 37 | * @type {Promise} 38 | */ 39 | let ready 40 | /** 41 | * @type {import('react-server-renderer').Renderer} 42 | */ 43 | let renderer 44 | 45 | const MAX_AGE = 1000 * 3600 * 24 * 365 // one year 46 | 47 | const STATUS_OK = 200 48 | const STATUS_NOT_FOUND = 404 49 | 50 | const cache = new LRUCache({ 51 | max: 1000, 52 | ttl: 1000 * 60 * 15, 53 | }) 54 | 55 | const middlewares = [ 56 | logger(), 57 | mount( 58 | '/public', 59 | serve(resolve('public'), { 60 | maxAge: MAX_AGE, 61 | }), 62 | ), 63 | async (ctx, next) => { 64 | if (__DEV__) { 65 | await ready 66 | } else if (await ctx.cashed()) { 67 | return 68 | } 69 | 70 | if ( 71 | ctx.method !== 'GET' || 72 | ctx.url.lastIndexOf('.') > ctx.url.lastIndexOf('/') || 73 | !['*/*', 'text/html'].some(mimeType => 74 | ctx.get('Accept').includes(mimeType), 75 | ) 76 | ) { 77 | return next() 78 | } 79 | 80 | const context = { ctx, title: 'React Hackernews' } 81 | 82 | ctx.respond = false 83 | 84 | const { res } = ctx 85 | 86 | renderer 87 | .renderToStream(context) 88 | .on('afterRender', () => { 89 | ctx.status = context.code || STATUS_OK 90 | ctx.set({ 91 | 'Content-Type': 'text/html', 92 | }) 93 | }) 94 | .on('error', async err => { 95 | console.dir(err) 96 | 97 | const { status, url, stack } = err 98 | 99 | if (url) { 100 | ctx.status = 302 101 | ctx.set({ Location: url }) 102 | return res.end() 103 | } 104 | 105 | ctx.status = status || 500 106 | 107 | if (status === STATUS_NOT_FOUND) { 108 | return res.end('404 | Page Not Found') 109 | } 110 | res.end('500 | Internal Server Error') 111 | debug(`error during render : ${url}`) 112 | debug(stack) 113 | }) 114 | .pipe(res) 115 | }, 116 | ] 117 | 118 | const createRenderer = (bundle, options) => 119 | createBundleRenderer(bundle, { 120 | ...options, 121 | template, 122 | basedir: resolve('dist/static'), 123 | runInNewContext: false, 124 | }) 125 | 126 | if (__DEV__) { 127 | import('./dev.js') 128 | .then(({ default: dev }) => { 129 | let webpackMiddlewarePromise 130 | ;({ readyPromise: ready, webpackMiddlewarePromise } = dev( 131 | ({ bundle, clientManifest }) => { 132 | renderer = createRenderer(bundle, { 133 | clientManifest, 134 | }) 135 | }, 136 | )) 137 | return webpackMiddlewarePromise 138 | }) 139 | // eslint-disable-next-line unicorn/prefer-top-level-await 140 | .then(webpackMiddleware => app.use(webpackMiddleware)) 141 | } else { 142 | renderer = createRenderer( 143 | runtimeRequire(resolve('dist/react-ssr-server-bundle.json')), 144 | { 145 | clientManifest: runtimeRequire( 146 | resolve('dist/react-ssr-client-manifest.json'), 147 | ), 148 | }, 149 | ) 150 | 151 | const files = {} 152 | 153 | middlewares.splice( 154 | 1, 155 | 0, 156 | compress(), 157 | serve( 158 | resolve('dist/static'), 159 | { 160 | maxAge: MAX_AGE, 161 | }, 162 | files, 163 | ), 164 | cash({ 165 | get: key => cache.get(key), 166 | set: (key, value) => cache.set(key, value), 167 | }), 168 | ) 169 | 170 | files['/service-worker.js'].maxAge = 0 171 | } 172 | 173 | app.use(compose(middlewares)) 174 | 175 | app.listen(serverPort, serverHost, () => { 176 | debug(`Server start listening at %s:%s`, serverHost, serverPort) 177 | }) 178 | -------------------------------------------------------------------------------- /server/template.pug: -------------------------------------------------------------------------------- 1 | html(lang='en') 2 | head 3 | title {{ title }} 4 | meta(charset='UTF-8') 5 | meta(http-equiv='X-UA-Compatible', content='ie=edge') 6 | meta( 7 | name='description', 8 | content='HackerNews clone built with React, ReactRouter & Redux, with server-side rendering' 9 | ) 10 | meta(name='theme-color', content='#00d8ff') 11 | meta(name='viewport', content='width=device-width, initial-scale=1') 12 | link(rel='apple-touch-icon', sizes='120x120', href='/public/logo.svg') 13 | link(rel='shortcut icon', sizes='48x48', href='/public/favicon.ico') 14 | link(rel='manifest', href='/public/manifest.json') 15 | style. 16 | #skip a { 17 | position: absolute; 18 | left: -10000px; 19 | top: auto; 20 | width: 1px; 21 | height: 1 px; 22 | overflow: hidden; 23 | } 24 | #skip a:focus { 25 | position: static; 26 | width: auto; 27 | height: auto; 28 | } 29 | body 30 | #skip 31 | a(href='#app') skip to content 32 | #app 33 | -------------------------------------------------------------------------------- /src/.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "presets": [ 3 | [ 4 | "@1stg", 5 | { 6 | "react": true, 7 | "isTSX": true 8 | } 9 | ] 10 | ] 11 | } 12 | -------------------------------------------------------------------------------- /src/App.js: -------------------------------------------------------------------------------- 1 | import { startCase } from 'lodash' 2 | import PropTypes from 'prop-types' 3 | import React, { Fragment } from 'react' 4 | import Loadable from 'react-loadable' 5 | import { Redirect } from 'react-router' 6 | import { renderRoutes } from 'react-router-config' 7 | import { withRouter, NavLink } from 'react-router-dom' 8 | import { Transition, TransitionGroup } from 'react-transition-group' 9 | 10 | import 'styles/app.scss' 11 | 12 | const resolver = loader => 13 | // eslint-disable-next-line @babel/new-cap 14 | Loadable({ 15 | loader, 16 | loading: () => null, 17 | }) 18 | 19 | const createListView = id => 20 | resolver(() => import('views/CreateListView.js').then(m => m.default(id))) 21 | 22 | const RedirectToTop = () => 23 | 24 | RedirectToTop.preload = ({ context }) => (context.url = '/top') 25 | 26 | export const routes = [ 27 | { 28 | path: '/', 29 | exact: true, 30 | component: RedirectToTop, 31 | }, 32 | { 33 | path: '/top/:page(\\d+)?', 34 | component: createListView('top'), 35 | }, 36 | { 37 | path: '/new/:page(\\d+)?', 38 | component: createListView('new'), 39 | }, 40 | { 41 | path: '/show/:page(\\d+)?', 42 | component: createListView('show'), 43 | }, 44 | { 45 | path: '/ask/:page(\\d+)?', 46 | component: createListView('ask'), 47 | }, 48 | { 49 | path: '/job/:page(\\d+)?', 50 | component: createListView('job'), 51 | }, 52 | { 53 | path: '/item/:id(\\d+)', 54 | component: resolver(() => import('views/ItemView/index.js')), 55 | }, 56 | { 57 | path: '/user/:id', 58 | component: resolver(() => import('views/UserView/index.js')), 59 | }, 60 | { 61 | path: '*', 62 | component: class NotFound extends React.PureComponent { 63 | static propTypes = { 64 | staticContext: PropTypes.object, 65 | } 66 | 67 | constructor(props, context) { 68 | super(props, context) 69 | if (this.props.staticContext) { 70 | this.props.staticContext.code = 404 71 | } 72 | } 73 | 74 | render() { 75 | return 'Custom 404 Page, will you implement it?' 76 | } 77 | }, 78 | }, 79 | ] 80 | 81 | const transitionStyles = { 82 | entering: { 83 | opacity: 0, 84 | }, 85 | entered: { 86 | opacity: 1, 87 | }, 88 | } 89 | 90 | @withRouter 91 | export default class App extends React.PureComponent { 92 | static propTypes = { 93 | location: PropTypes.object.isRequired, 94 | } 95 | 96 | render() { 97 | const { location } = this.props 98 | return ( 99 | <> 100 |
101 |
102 | 106 | React Logo 111 | 112 | 122 | 128 | Built with React.js 129 | 130 | 131 |
132 |
133 | 134 | 140 | {status => ( 141 |
145 | {renderRoutes(routes, null, { location })} 146 |
147 | )} 148 |
149 |
150 | 151 | ) 152 | } 153 | } 154 | -------------------------------------------------------------------------------- /src/api/create-api-client.js: -------------------------------------------------------------------------------- 1 | import { initializeApp } from 'firebase/app' 2 | import { getDatabase, ref } from 'firebase/database' 3 | 4 | export function createAPI({ config, version }) { 5 | const app = initializeApp(config) 6 | const database = getDatabase(app) 7 | return ref(database, version) 8 | } 9 | -------------------------------------------------------------------------------- /src/api/create-api-server.js: -------------------------------------------------------------------------------- 1 | import { initializeApp } from 'firebase/app' 2 | import { child, getDatabase, onValue, ref } from 'firebase/database' 3 | import { LRUCache } from 'lru-cache' 4 | 5 | /** 6 | * @typedef {import('./index.js').DatabaseApi} DatabaseApi 7 | */ 8 | 9 | export function createAPI({ config, version }) { 10 | /** 11 | * @type {DatabaseApi} 12 | */ 13 | let api 14 | // this piece of code may run multiple times in development mode, 15 | // so we attach the instantiated API to `process` to avoid duplications 16 | if (process.__API__) { 17 | api = process.__API__ 18 | } else { 19 | const app = initializeApp(config) 20 | const database = getDatabase(app) 21 | 22 | api = process.__API__ = ref(database, version) 23 | 24 | api.onServer = true 25 | 26 | // fetched item cache 27 | api.cachedItems = new LRUCache({ 28 | max: 1000, 29 | ttl: 1000 * 60 * 15, // 15 min cache 30 | }) 31 | 32 | // cache the latest story ids 33 | api.cachedIds = {} 34 | ;['top', 'new', 'show', 'ask', 'job'].forEach(type => { 35 | onValue(child(api, `${type}stories`), snapshot => { 36 | api.cachedIds[type] = snapshot.val() 37 | }) 38 | }) 39 | } 40 | 41 | return api 42 | } 43 | -------------------------------------------------------------------------------- /src/api/index.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @typedef {import('firebase/database').DatabaseReference} DatabaseReference 3 | * @typedef { import('lru-cache').LRUCache } LRUCache 4 | * @typedef {DatabaseReference & { onServer?: boolean; cachedItems?: LRUCache; cachedIds?: Record }} DatabaseApi 5 | */ 6 | 7 | // this is aliased in webpack config based on server/client build 8 | // eslint-disable-next-line import/no-unresolved 9 | import { createAPI } from 'create-api' 10 | import { child, get, onValue } from 'firebase/database' 11 | 12 | const logRequests = !!process.env.DEBUG_API 13 | 14 | /** 15 | * @type {DatabaseApi} 16 | */ 17 | const api = createAPI({ 18 | version: '/v0', 19 | config: { 20 | databaseURL: 'https://hacker-news.firebaseio.com', 21 | }, 22 | }) 23 | 24 | // warm the front page cache every 15 min 25 | // make sure to do this only once across all requests 26 | if (api.onServer) { 27 | warmCache() 28 | } 29 | 30 | function warmCache() { 31 | fetchItems((api.cachedIds?.top || []).slice(0, 30)) 32 | setTimeout(warmCache, 1000 * 60 * 15) 33 | } 34 | 35 | async function fetch(path) { 36 | if (logRequests) { 37 | console.log(`fetching ${path}...`) 38 | } 39 | 40 | const cache = api.cachedItems 41 | if (cache?.has(path)) { 42 | if (logRequests) { 43 | console.log(`cache hit for ${path}.`) 44 | } 45 | return cache.get(path) 46 | } 47 | 48 | const snapshot = await get(child(api, path)) 49 | const val = snapshot.val() 50 | // mark the timestamp when this item is cached 51 | if (val) { 52 | val.__lastUpdated = Date.now() 53 | } 54 | if (cache) { 55 | cache.set(path, val) 56 | } 57 | if (logRequests) { 58 | console.log(`fetched ${path}.`) 59 | } 60 | return val 61 | } 62 | 63 | export function fetchIdsByType(type) { 64 | return api.cachedIds?.[type] 65 | ? Promise.resolve(api.cachedIds[type]) 66 | : fetch(`${type}stories`) 67 | } 68 | 69 | export function fetchItem(id) { 70 | return fetch(`item/${id}`) 71 | } 72 | 73 | export function fetchItems(ids) { 74 | return Promise.all(ids.map(id => fetchItem(id))) 75 | } 76 | 77 | export function fetchUser(id) { 78 | return fetch(`user/${id}`) 79 | } 80 | 81 | export function watchList(type, cb) { 82 | let first = true 83 | const ref = child(api, `${type}stories`) 84 | return onValue(ref, snapshot => { 85 | if (first) { 86 | first = false 87 | } else { 88 | cb(snapshot.val()) 89 | } 90 | }) 91 | } 92 | -------------------------------------------------------------------------------- /src/components/Comment/index.js: -------------------------------------------------------------------------------- 1 | import PropTypes from 'prop-types' 2 | import React, { useState } from 'react' 3 | import { connect } from 'react-redux' 4 | import { Link } from 'react-router-dom' 5 | 6 | import styles from './styles.scss' 7 | 8 | import { withSsr, timeAgo } from 'utils' 9 | 10 | const pluralize = n => n + (n === 1 ? ' reply' : ' replies') 11 | 12 | const Comment = ({ comments, id }) => { 13 | const [open, setOpen] = useState(true) 14 | 15 | const comment = comments?.[id] 16 | 17 | return comment ? ( 18 |
  • 19 |
    20 | {comment.by ? ( 21 | {comment.by} 22 | ) : null} 23 | {' ' + timeAgo(comment.time)} ago 24 |
    25 |
    [Deleted]', 29 | }} 30 | /> 31 | {comment.kids?.length > 0 && ( 32 | <> 33 | 40 |
      44 | {comment.kids.map(id => ( 45 | 49 | ))} 50 |
    51 | 52 | )} 53 |
  • 54 | ) : null 55 | } 56 | 57 | Comment.propTypes = { 58 | comments: PropTypes.object, 59 | id: PropTypes.number.isRequired, 60 | } 61 | 62 | export default connect(({ items }) => ({ comments: items }))( 63 | withSsr(styles)(Comment), 64 | ) 65 | -------------------------------------------------------------------------------- /src/components/Comment/styles.scss: -------------------------------------------------------------------------------- 1 | .comment-children .comment-children { 2 | margin-left: 1.5em; 3 | } 4 | 5 | .comment { 6 | border-top: 1px solid #eee; 7 | position: relative; 8 | 9 | .by, 10 | .text, 11 | .toggle { 12 | font-size: 0.9em; 13 | margin: 1em 0; 14 | } 15 | 16 | .by { 17 | color: #828282; 18 | 19 | a { 20 | color: #828282; 21 | text-decoration: underline; 22 | } 23 | } 24 | 25 | .text { 26 | overflow-wrap: break-word; 27 | 28 | a:hover { 29 | color: #ff6600; 30 | } 31 | 32 | pre { 33 | white-space: pre-wrap; 34 | } 35 | } 36 | 37 | .toggle { 38 | background-color: #fffbf2; 39 | padding: 0.3em 0.5em; 40 | border-radius: 4px; 41 | 42 | a { 43 | color: #828282; 44 | cursor: pointer; 45 | } 46 | 47 | &.open { 48 | padding: 0; 49 | background-color: transparent; 50 | margin-bottom: -0.5em; 51 | } 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/components/Item/index.js: -------------------------------------------------------------------------------- 1 | import PropTypes from 'prop-types' 2 | import React from 'react' 3 | import { Link } from 'react-router-dom' 4 | 5 | import styles from './styles.scss' 6 | 7 | import { withSsr, host, timeAgo } from 'utils' 8 | 9 | const Item = ({ item }) => ( 10 |
  • 11 | {item.score} 12 | 13 | {item.url ? ( 14 | <> 15 | 20 | {item.title} 21 | 22 | ({host(item.url)}) 23 | 24 | ) : ( 25 | {item.title} 26 | )} 27 | 28 |
    29 | 30 | {item.type === 'job' ? null : ( 31 | 32 | by {item.by}{' '} 33 | 34 | )} 35 | {timeAgo(item.time)} ago 36 | {item.type === 'job' ? null : ( 37 | 38 | {' '} 39 | | {item.descendants} comments 40 | 41 | )} 42 | 43 | {item.type === 'story' ? null : ( 44 | {' ' + item.type} 45 | )} 46 |
  • 47 | ) 48 | 49 | Item.propTypes = { 50 | item: PropTypes.object.isRequired, 51 | } 52 | 53 | export default withSsr(styles, true)(Item) 54 | -------------------------------------------------------------------------------- /src/components/Item/styles.scss: -------------------------------------------------------------------------------- 1 | .news-item { 2 | background-color: #fff; 3 | padding: 20px 30px 20px 80px; 4 | border-bottom: 1px solid #eee; 5 | position: relative; 6 | line-height: 20px; 7 | 8 | .score { 9 | color: #00d8ff; 10 | font-size: 1.1em; 11 | font-weight: 700; 12 | position: absolute; 13 | top: 50%; 14 | left: 0; 15 | width: 80px; 16 | text-align: center; 17 | margin-top: -10px; 18 | } 19 | 20 | .meta, 21 | .host { 22 | font-size: 0.85em; 23 | color: #828282; 24 | 25 | a { 26 | color: #828282; 27 | text-decoration: underline; 28 | &:hover { 29 | color: #00d8ff; 30 | } 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/components/Spinner/index.js: -------------------------------------------------------------------------------- 1 | import PropTypes from 'prop-types' 2 | import React from 'react' 3 | 4 | import styles from './styles.scss' 5 | 6 | import { withSsr } from 'utils' 7 | 8 | const Spinner = ({ show }) => 9 | show ? ( 10 | 16 | 25 | 26 | ) : null 27 | 28 | Spinner.propTypes = { 29 | show: PropTypes.bool.isRequired, 30 | } 31 | 32 | export default withSsr(styles)(Spinner) 33 | -------------------------------------------------------------------------------- /src/components/Spinner/styles.scss: -------------------------------------------------------------------------------- 1 | @use "sass:math"; 2 | 3 | $offset: 126; 4 | $duration: 1.4s; 5 | 6 | .spinner { 7 | transition: opacity 0.15s ease; 8 | animation: rotator $duration linear infinite; 9 | animation-play-state: paused; 10 | &.show { 11 | animation-play-state: running; 12 | } 13 | } 14 | 15 | @keyframes rotator { 16 | from { 17 | transform: scale(0.5) rotate(0deg); 18 | } 19 | to { 20 | transform: scale(0.5) rotate(270deg); 21 | } 22 | } 23 | 24 | .spinner .path { 25 | stroke: #00d8ff; 26 | stroke-dasharray: $offset; 27 | stroke-dashoffset: 0; 28 | transform-origin: center; 29 | animation: dash $duration ease-in-out infinite; 30 | } 31 | 32 | @keyframes dash { 33 | from { 34 | stroke-dashoffset: $offset; 35 | } 36 | 50% { 37 | stroke-dashoffset: math.div($offset, 2); 38 | transform: rotate(135deg); 39 | } 40 | to { 41 | stroke-dashoffset: $offset; 42 | transform: rotate(450deg); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/entry-client.js: -------------------------------------------------------------------------------- 1 | import { ConnectedRouter } from 'connected-react-router' 2 | import React from 'react' 3 | // eslint-disable-next-line react/no-deprecated, sonar/deprecation 4 | import { hydrate } from 'react-dom' 5 | import Loadable from 'react-loadable' 6 | import { Provider } from 'react-redux' 7 | 8 | import App from 'App' 9 | import createStore, { history } from 'store' 10 | 11 | const store = createStore(window.__INITIAL_STATE__) 12 | 13 | if (!__DEV__) { 14 | delete window.__INITIAL_STATE__ 15 | } 16 | 17 | const render = () => 18 | Loadable.preloadReady().then(() => 19 | hydrate( 20 | 21 | 22 | 23 | 24 | , 25 | document.querySelector('#app'), 26 | ), 27 | ) 28 | 29 | render() 30 | 31 | if (__DEV__) { 32 | // eslint-disable-next-line no-undef 33 | module.hot.accept('App', render) 34 | } 35 | 36 | if ( 37 | !__DEV__ && 38 | (location.protocol === 'https:' || 39 | ['127.0.0.1', 'localhost'].includes(location.hostname)) && 40 | navigator.serviceWorker 41 | ) { 42 | navigator.serviceWorker.register('/service-worker.js') 43 | } 44 | -------------------------------------------------------------------------------- /src/entry-server.js: -------------------------------------------------------------------------------- 1 | import React from 'react' 2 | import Loadable from 'react-loadable' 3 | import { Provider } from 'react-redux' 4 | import { StaticRouter } from 'react-router' 5 | import { matchRoutes } from 'react-router-config' 6 | 7 | import App, { routes } from 'App' 8 | import createStore from 'store' 9 | 10 | const preloadAll = Loadable.preloadAll() 11 | 12 | export default context => 13 | // eslint-disable-next-line no-async-promise-executor 14 | new Promise(async (resolve, reject) => { 15 | await preloadAll 16 | 17 | const { ctx } = context 18 | 19 | const store = createStore() 20 | 21 | const matched = matchRoutes(routes, ctx.url) 22 | 23 | try { 24 | for (const { 25 | match, 26 | route: { component }, 27 | } of matched) { 28 | let comp 29 | 30 | if (typeof component.preload === 'function') { 31 | comp = await component.preload({ match, store, context }) 32 | } 33 | 34 | if (!comp) { 35 | continue 36 | } 37 | 38 | comp = (comp && comp.default) || comp 39 | 40 | if (typeof comp.preload === 'function') { 41 | await comp.preload({ match, store, context }) 42 | } 43 | } 44 | 45 | const { status, url } = context 46 | if (status || url) { 47 | return reject(context) 48 | } 49 | } catch (e) { 50 | return reject(e) 51 | } 52 | 53 | Object.defineProperty(context, 'state', { 54 | get() { 55 | return store.getState() 56 | }, 57 | }) 58 | 59 | resolve( 60 | 61 | 65 | 66 | 67 | , 68 | ) 69 | }) 70 | -------------------------------------------------------------------------------- /src/store/actions.js: -------------------------------------------------------------------------------- 1 | import { activeIds } from './selectors.js' 2 | import TYPES from './types.js' 3 | 4 | import { 5 | fetchIdsByType as _fetchIdsByType, 6 | fetchItems as _fetchItems, 7 | fetchUser as _fetchUser, 8 | } from 'api' 9 | 10 | export const setLoading = loading => ({ 11 | type: TYPES.SET_LOADING, 12 | loading, 13 | }) 14 | 15 | export const setActiveType = activeType => ({ 16 | type: TYPES.SET_ACTIVE_TYPE, 17 | activeType, 18 | }) 19 | 20 | export const setList = (listType, ids) => ({ 21 | type: TYPES.SET_LIST, 22 | listType, 23 | ids, 24 | }) 25 | 26 | export const setItems = items => ({ 27 | type: TYPES.SET_ITEMS, 28 | items, 29 | }) 30 | 31 | export const setUser = (id, user) => ({ 32 | type: TYPES.SET_USER, 33 | id, 34 | user, 35 | }) 36 | 37 | export const fetchListData = (type, page) => dispatch => { 38 | dispatch(setActiveType(type)) 39 | return _fetchIdsByType(type) 40 | .then(ids => dispatch(setList(type, ids))) 41 | .then(() => dispatch(ensureActiveItems(page))) 42 | } 43 | 44 | export const fetchItems = ids => (dispatch, getState) => { 45 | // on the client, the store itself serves as a cache. 46 | // only fetch items that we do not already have, or has expired (3 minutes) 47 | const now = Date.now() 48 | const state = getState() 49 | ids = ids.filter(id => { 50 | const item = state.items[id] 51 | if (!item) { 52 | return true 53 | } 54 | return now - item.__lastUpdated > 1000 * 60 * 3 55 | }) 56 | 57 | return ids.length > 0 58 | ? _fetchItems(ids).then(items => dispatch(setItems(items))) 59 | : Promise.resolve() 60 | } 61 | 62 | export const ensureActiveItems = page => (dispatch, getState) => 63 | dispatch(fetchItems(activeIds(getState(), page))) 64 | 65 | export const fetchUser = id => (dispatch, getState) => 66 | getState().users[id] 67 | ? Promise.resolve() 68 | : _fetchUser(id).then(user => dispatch(setUser(id, user))) 69 | -------------------------------------------------------------------------------- /src/store/index.js: -------------------------------------------------------------------------------- 1 | import { connectRouter, routerMiddleware } from 'connected-react-router' 2 | import { createBrowserHistory, createMemoryHistory } from 'history' 3 | import { 4 | compose, 5 | combineReducers, 6 | legacy_createStore as createStore, 7 | applyMiddleware, 8 | } from 'redux' 9 | import { thunk } from 'redux-thunk' 10 | 11 | import * as reducers from './reducers.js' 12 | 13 | export const history = __SERVER__ 14 | ? createMemoryHistory() 15 | : createBrowserHistory() 16 | 17 | const createRootReducer = () => 18 | combineReducers({ 19 | router: connectRouter(history), 20 | ...reducers, 21 | }) 22 | 23 | const composeEnhancers = 24 | (__DEV__ && !__SERVER__ && window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__) || 25 | compose 26 | 27 | export default initialState => 28 | createStore( 29 | createRootReducer(), 30 | initialState, 31 | composeEnhancers(applyMiddleware(routerMiddleware(history), thunk)), 32 | ) 33 | 34 | export * from './actions.js' 35 | export * from './selectors.js' 36 | -------------------------------------------------------------------------------- /src/store/reducers.js: -------------------------------------------------------------------------------- 1 | import TYPES from './types.js' 2 | 3 | export const loading = (state = false, action) => { 4 | switch (action.type) { 5 | case TYPES.SET_LOADING: { 6 | return action.loading 7 | } 8 | default: { 9 | return state 10 | } 11 | } 12 | } 13 | 14 | export const activeType = (state = null, action) => { 15 | switch (action.type) { 16 | case TYPES.SET_ACTIVE_TYPE: { 17 | return action.activeType 18 | } 19 | default: { 20 | return state 21 | } 22 | } 23 | } 24 | 25 | export const itemsPerPage = (state = 20) => state 26 | 27 | export const items = (state = {}, action) => { 28 | switch (action.type) { 29 | case TYPES.SET_ITEMS: { 30 | return { 31 | ...state, 32 | ...action.items.reduce((result, item) => { 33 | if (item) { 34 | result[item.id] = item 35 | } 36 | return result 37 | }, {}), 38 | } 39 | } 40 | default: { 41 | return state 42 | } 43 | } 44 | } 45 | 46 | export const users = (state = {}, action) => { 47 | switch (action.type) { 48 | case TYPES.SET_USER: { 49 | return { 50 | ...state, 51 | [action.id]: action.user || false, 52 | } 53 | } 54 | default: { 55 | return state 56 | } 57 | } 58 | } 59 | 60 | export const lists = ( 61 | // eslint-disable-next-line unicorn/no-object-as-default-parameter 62 | state = { 63 | top: [], 64 | new: [], 65 | show: [], 66 | ask: [], 67 | job: [], 68 | }, 69 | action, 70 | ) => { 71 | switch (action.type) { 72 | case TYPES.SET_LIST: { 73 | return { 74 | ...state, 75 | [action.listType]: action.ids, 76 | } 77 | } 78 | default: { 79 | return state 80 | } 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /src/store/selectors.js: -------------------------------------------------------------------------------- 1 | export const activeIds = (state, page = 1) => { 2 | const { activeType, itemsPerPage, lists } = state 3 | 4 | if (!activeType) { 5 | return [] 6 | } 7 | 8 | const start = (page - 1) * itemsPerPage 9 | const end = page * itemsPerPage 10 | 11 | return lists[activeType].slice(start, end) 12 | } 13 | 14 | export const activeItems = (state, page) => 15 | activeIds(state, page) 16 | .map(id => state.items[id]) 17 | .filter(Boolean) 18 | -------------------------------------------------------------------------------- /src/store/types.js: -------------------------------------------------------------------------------- 1 | export default { 2 | SET_LOADING: 'SET_LOADING', 3 | SET_ACTIVE_TYPE: 'SET_ACTIVE_TYPE', 4 | SET_LIST: 'SET_LIST', 5 | SET_ITEMS: 'SET_ITEMS', 6 | SET_USER: 'SET_USER', 7 | } 8 | -------------------------------------------------------------------------------- /src/styles/app.scss: -------------------------------------------------------------------------------- 1 | body { 2 | font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, 3 | Ubuntu, Cantarell, 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif; 4 | font-size: 15px; 5 | background-color: #f2f3f5; 6 | margin: 0; 7 | padding-top: 55px; 8 | color: #34495e; 9 | overflow-y: scroll; 10 | } 11 | 12 | a { 13 | color: #34495e; 14 | text-decoration: none; 15 | } 16 | 17 | .header { 18 | background-color: #20232a; 19 | position: fixed; 20 | z-index: 999; 21 | top: 0; 22 | left: 0; 23 | right: 0; 24 | 25 | a { 26 | position: relative; 27 | padding: 15px 25px; 28 | color: rgba(255, 255, 255, 0.8); 29 | line-height: 24px; 30 | display: inline-block; 31 | vertical-align: middle; 32 | font-weight: 300; 33 | letter-spacing: 0.075em; 34 | transition: all 0.5s; 35 | 36 | &.active, 37 | &:hover { 38 | color: #00d8ff; 39 | } 40 | } 41 | 42 | .github { 43 | display: inline-flex; 44 | color: #fff; 45 | font-size: 0.9em; 46 | padding-right: 0; 47 | margin-left: auto; 48 | 49 | img { 50 | margin-left: 2px; 51 | } 52 | } 53 | 54 | @media (max-width: 800px) { 55 | .header-content, 56 | a { 57 | padding-left: 15px; 58 | padding-right: 15px; 59 | } 60 | } 61 | 62 | @media (max-width: 600px) { 63 | a { 64 | padding-left: 10px; 65 | padding-right: 10px; 66 | } 67 | } 68 | 69 | @media (max-width: 500px) { 70 | .github { 71 | display: none; 72 | } 73 | } 74 | } 75 | 76 | .logo { 77 | width: 24px; 78 | } 79 | 80 | .header-content { 81 | display: flex; 82 | margin: 0px auto; 83 | max-width: 800px; 84 | box-sizing: border-box; 85 | 86 | > a { 87 | padding-left: 0; 88 | } 89 | } 90 | 91 | .inner { 92 | display: flex; 93 | overflow: auto hidden; 94 | 95 | a { 96 | &:focus { 97 | background-color: #373940; 98 | } 99 | 100 | &.active { 101 | font-weight: 400; 102 | 103 | &:focus { 104 | color: #fff; 105 | } 106 | 107 | &:after { 108 | content: ''; 109 | position: absolute; 110 | bottom: 0; 111 | left: 50%; 112 | transform: translate3d(-50%, 0, 0); 113 | width: 100%; 114 | height: 2px; 115 | background-color: #00d8ff; 116 | } 117 | } 118 | } 119 | } 120 | 121 | .view { 122 | max-width: 800px; 123 | margin: 0 auto; 124 | position: relative; 125 | opacity: 0; 126 | transition: all 0.2s ease; 127 | } 128 | -------------------------------------------------------------------------------- /src/utils/index.js: -------------------------------------------------------------------------------- 1 | export * from './ssr.js' 2 | 3 | export function host(url) { 4 | const host = url.replace(/^https?:\/\//, '').replace(/\/.*$/, '') 5 | const parts = host.split('.').slice(-1 * 3) 6 | if (parts[0] === 'www') parts.shift() 7 | return parts.join('.') 8 | } 9 | 10 | export function timeAgo(time) { 11 | const between = Date.now() / 1000 - Number(time) 12 | if (between < 3600) { 13 | return pluralize(Math.trunc(between / 60), ' minute') 14 | } 15 | if (between < 60 * 60 * 24) { 16 | return pluralize(Math.trunc((between / 60) * 60), ' hour') 17 | } 18 | return pluralize(Math.trunc((between / 60) * 60 * 24), ' day') 19 | } 20 | 21 | function pluralize(time, label) { 22 | if (time === 1) { 23 | return time + label 24 | } 25 | return time + label + 's' 26 | } 27 | -------------------------------------------------------------------------------- /src/utils/ssr.js: -------------------------------------------------------------------------------- 1 | import hoistStatics from 'hoist-non-react-statics' 2 | import PropTypes from 'prop-types' 3 | import React from 'react' 4 | import { withRouter } from 'react-router' 5 | 6 | // eslint-disable-next-line sonarjs/cognitive-complexity 7 | export const withSsr = (styles, router = true, title) => { 8 | if (typeof router !== 'boolean') { 9 | title = router 10 | router = true 11 | } 12 | 13 | return Component => { 14 | class SsrComponent extends React.PureComponent { 15 | static displayName = `Ssr${ 16 | Component.displayName || Component.name || 'Component' 17 | }` 18 | 19 | static propTypes = { 20 | staticContext: PropTypes.object, 21 | } 22 | 23 | constructor(props, context) { 24 | super(props, context) 25 | if (styles.__inject__) { 26 | styles.__inject__(this.props.staticContext) 27 | } 28 | 29 | this.setTitle() 30 | } 31 | 32 | setTitle() { 33 | const t = typeof title === 'function' ? title.call(this, this) : title 34 | 35 | if (!t) { 36 | return 37 | } 38 | 39 | if (__SERVER__) { 40 | this.props.staticContext.title = `React Hackernews | ${t}` 41 | return 42 | } 43 | 44 | Promise.resolve(t).then(title => { 45 | if (title) { 46 | document.title = `React Hackernews | ${title}` 47 | } 48 | }) 49 | } 50 | 51 | render() { 52 | return 53 | } 54 | } 55 | 56 | return hoistStatics( 57 | router ? withRouter(SsrComponent) : SsrComponent, 58 | Component, 59 | ) 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /src/views/CreateListView.js: -------------------------------------------------------------------------------- 1 | import hoistStatics from 'hoist-non-react-statics' 2 | import PropTypes from 'prop-types' 3 | import React from 'react' 4 | import { connect } from 'react-redux' 5 | 6 | import ItemList from './ItemList/index.js' 7 | 8 | import { activeItems, fetchListData } from 'store' 9 | 10 | export default type => { 11 | @connect( 12 | (state, props) => ({ 13 | activeItems: activeItems(state, props.match.params.page), 14 | }), 15 | (dispatch, props) => ({ 16 | fetchListData: () => 17 | dispatch(fetchListData(type, props.match.params.page)), 18 | }), 19 | ) 20 | class ListView extends React.PureComponent { 21 | static propTypes = { 22 | match: PropTypes.object.isRequired, 23 | } 24 | 25 | static preload({ store, match }) { 26 | return store.dispatch(fetchListData(type, match.params.page)) 27 | } 28 | 29 | render() { 30 | return ( 31 | 35 | ) 36 | } 37 | } 38 | 39 | return hoistStatics(ListView, ItemList) 40 | } 41 | -------------------------------------------------------------------------------- /src/views/ItemList/index.js: -------------------------------------------------------------------------------- 1 | import { startCase } from 'lodash' 2 | import { pathToRegexp } from 'path-to-regexp' 3 | import PropTypes from 'prop-types' 4 | import React from 'react' 5 | import { connect } from 'react-redux' 6 | import { Link } from 'react-router-dom' 7 | import { CSSTransition, TransitionGroup } from 'react-transition-group' 8 | 9 | import styles from './styles.scss' 10 | 11 | import { watchList } from 'api' 12 | import Item from 'components/Item/index.js' 13 | import Spinner from 'components/Spinner/index.js' 14 | import { 15 | activeItems, 16 | setLoading, 17 | setList, 18 | ensureActiveItems, 19 | fetchListData, 20 | } from 'store' 21 | import { withSsr } from 'utils' 22 | 23 | @connect( 24 | (state, props) => ({ 25 | loading: state.loading, 26 | activeItems: activeItems(state, props.match.params.page), 27 | itemsPerPage: state.itemsPerPage, 28 | lists: state.lists, 29 | }), 30 | ( 31 | dispatch, 32 | { 33 | type, 34 | match: { 35 | params: { page }, 36 | }, 37 | }, 38 | ) => ({ 39 | setLoading: loading => dispatch(setLoading(loading)), 40 | setList: (listType, ids) => dispatch(setList(listType, ids)), 41 | fetchListData: () => dispatch(fetchListData(type, page)), 42 | ensureActiveItems: () => dispatch(ensureActiveItems(page)), 43 | }), 44 | ) 45 | @withSsr(styles, false, ({ props }) => startCase(props.type)) 46 | export default class ItemList extends React.PureComponent { 47 | static propTypes = { 48 | loading: PropTypes.bool.isRequired, 49 | activeItems: PropTypes.array.isRequired, 50 | match: PropTypes.object.isRequired, 51 | location: PropTypes.object.isRequired, 52 | itemsPerPage: PropTypes.number.isRequired, 53 | lists: PropTypes.object.isRequired, 54 | type: PropTypes.string.isRequired, 55 | fetchListData: PropTypes.func.isRequired, 56 | history: PropTypes.object.isRequired, 57 | setLoading: PropTypes.func.isRequired, 58 | setList: PropTypes.func.isRequired, 59 | ensureActiveItems: PropTypes.func.isRequired, 60 | } 61 | 62 | state = { 63 | displayedPage: this.page, 64 | displayedItems: this.props.activeItems, 65 | itemTransition: 'item', 66 | transition: 'slide-right', 67 | } 68 | 69 | get page() { 70 | return Number(this.props.match.params.page) || 1 71 | } 72 | 73 | get maxPage() { 74 | const { itemsPerPage, lists, type } = this.props 75 | return Math.ceil(lists[type].length / itemsPerPage) 76 | } 77 | 78 | get hasMore() { 79 | return this.page < this.maxPage 80 | } 81 | 82 | loadItems(to = this.page, from = -1) { 83 | this.props.setLoading(true) 84 | 85 | this.props.fetchListData().then(() => { 86 | if (this.page < 0 || this.page > this.maxPage) { 87 | this.props.history.replace(`/${this.props.type}`) 88 | return 89 | } 90 | 91 | const transition = 92 | from === -1 ? '' : to > from ? 'slide-left' : 'slide-right' 93 | 94 | this.setState( 95 | { 96 | displayedPage: -1, 97 | itemTransition: '', 98 | transition, 99 | }, 100 | () => 101 | setTimeout( 102 | () => { 103 | this.setState( 104 | { 105 | displayedPage: to, 106 | displayedItems: this.props.activeItems, 107 | }, 108 | () => { 109 | this.props.setLoading(false) 110 | }, 111 | ) 112 | }, 113 | transition ? 500 : 0, 114 | ), 115 | ) 116 | }) 117 | } 118 | 119 | isSameLocation(prev, curr) { 120 | return prev.pathname === curr.pathname && prev.search === curr.search 121 | } 122 | 123 | componentDidMount() { 124 | const { history, type, match } = this.props 125 | 126 | this.unwatchList = watchList(type, ids => { 127 | this.props.setList(type, ids) 128 | this.props.ensureActiveItems().then(() => { 129 | this.setState({ 130 | displayedItems: this.props.activeItems, 131 | }) 132 | }) 133 | }) 134 | 135 | this.unwatchPage = history.listen(location => { 136 | const { 137 | params: { page: prevPage }, 138 | path, 139 | } = match 140 | if ( 141 | this.isSameLocation(this.props.location, location) || 142 | !pathToRegexp(path).test(location.pathname) 143 | ) { 144 | return 145 | } 146 | setTimeout(() => 147 | // eslint-disable-next-line unicorn/consistent-destructuring 148 | this.loadItems(this.props.match.params.page, prevPage || 1), 149 | ) 150 | }) 151 | } 152 | 153 | componentWillUnmount() { 154 | this.unwatchList() 155 | this.unwatchPage() 156 | } 157 | 158 | render() { 159 | const { page, maxPage, hasMore, props, state } = this 160 | const { loading, type } = props 161 | const { displayedItems, displayedPage, itemTransition, transition } = state 162 | 163 | return ( 164 |
    165 |
    166 | {page > 1 ? ( 167 | < prev 168 | ) : ( 169 | < prev 170 | )} 171 | 172 | {page}/{maxPage} 173 | 174 | {hasMore ? ( 175 | more > 176 | ) : ( 177 | more > 178 | )} 179 |
    180 | 0} 182 | classNames={transition} 183 | timeout={transition ? 500 : 0} 184 | onEntered={() => { 185 | this.setState({ 186 | itemTransition: 'item', 187 | }) 188 | }} 189 | > 190 |
    191 | {maxPage && !loading ? ( 192 | 193 | {displayedItems.map(item => ( 194 | 199 | 200 | 201 | ))} 202 | 203 | ) : ( 204 |
    205 | 206 |
    207 | )} 208 |
    209 |
    210 |
    211 | ) 212 | } 213 | } 214 | -------------------------------------------------------------------------------- /src/views/ItemList/styles.scss: -------------------------------------------------------------------------------- 1 | .news-view { 2 | margin-top: 45px; 3 | } 4 | 5 | .news-list-nav, 6 | .news-list { 7 | background-color: #fff; 8 | border-radius: 2px; 9 | } 10 | 11 | .news-list-nav { 12 | padding: 15px 30px; 13 | position: fixed; 14 | text-align: center; 15 | top: 55px; 16 | left: 0; 17 | right: 0; 18 | z-index: 998; 19 | box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1); 20 | a { 21 | margin: 0 1em; 22 | } 23 | .disabled { 24 | color: #ccc; 25 | } 26 | } 27 | 28 | .news-list { 29 | position: absolute; 30 | margin: 30px 0; 31 | width: 100%; 32 | transition: all 0.5s cubic-bezier(0.55, 0, 0.1, 1); 33 | 34 | .loading { 35 | text-align: center; 36 | padding: 20px; 37 | } 38 | 39 | ul { 40 | list-style-type: none; 41 | padding: 0; 42 | margin: 0; 43 | } 44 | } 45 | 46 | .slide-right-enter, 47 | .slide-right-exit.slide-right-exit-active { 48 | opacity: 0; 49 | transform: translate(30px, 0); 50 | } 51 | 52 | .slide-left-enter, 53 | .slide-left-exit.slide-left-exit-active { 54 | opacity: 0; 55 | transform: translate(-30px, 0); 56 | } 57 | 58 | .slide-left-enter.slide-left-enter-active, 59 | .slide-right-enter.slide-right-enter-active { 60 | opacity: 1; 61 | transform: translate(0, 0); 62 | } 63 | 64 | .item-enter-active, 65 | .item-exit-active { 66 | position: absolute; 67 | z-index: 1; 68 | transition: all 0.5s cubic-bezier(0.55, 0, 0.1, 1); 69 | } 70 | 71 | .item-enter, 72 | .item-exit.item-exit-active { 73 | opacity: 0; 74 | transform: translate(30px, 0); 75 | } 76 | 77 | .item-exit, 78 | .item-enter.item-enter-active { 79 | opacity: 1; 80 | transform: translate(0, 0); 81 | } 82 | 83 | @media (max-width: 800px) { 84 | .news-list { 85 | margin: 10px 0; 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /src/views/ItemView/index.js: -------------------------------------------------------------------------------- 1 | import PropTypes from 'prop-types' 2 | import React from 'react' 3 | import { connect } from 'react-redux' 4 | import { Link } from 'react-router-dom' 5 | 6 | import styles from './styles.scss' 7 | 8 | import Comment from 'components/Comment/index.js' 9 | import Spinner from 'components/Spinner/index.js' 10 | import { fetchItems } from 'store' 11 | import { withSsr, host, timeAgo } from 'utils' 12 | 13 | @connect( 14 | ({ items }) => ({ items }), 15 | dispatch => ({ 16 | fetchItems: ids => dispatch(fetchItems(ids)), 17 | }), 18 | ) 19 | @withSsr(styles, false, ({ props }) => { 20 | const { 21 | items, 22 | match: { 23 | params: { id }, 24 | }, 25 | } = props 26 | return items[id] && items[id].title 27 | }) 28 | export default class ItemView extends React.PureComponent { 29 | static propTypes = { 30 | items: PropTypes.object.isRequired, 31 | match: PropTypes.object.isRequired, 32 | fetchItems: PropTypes.func.isRequired, 33 | } 34 | 35 | state = { 36 | loading: false, 37 | } 38 | 39 | static preload({ match, store }) { 40 | const { id } = match.params 41 | return store.dispatch(fetchItems([id])) 42 | } 43 | 44 | get item() { 45 | return this.props.items[this.props.match.params.id] 46 | } 47 | 48 | fetchItems() { 49 | const { item } = this 50 | 51 | if (!item?.kids) { 52 | return 53 | } 54 | 55 | this.setState({ 56 | loading: true, 57 | }) 58 | 59 | this.fetchComments(item).then(() => 60 | this.setState({ 61 | loading: false, 62 | }), 63 | ) 64 | } 65 | 66 | fetchComments(item) { 67 | if (item?.kids) { 68 | return this.props 69 | .fetchItems(item.kids) 70 | .then(() => 71 | Promise.all( 72 | item.kids.map(id => this.fetchComments(this.props.items[id])), 73 | ), 74 | ) 75 | } 76 | } 77 | 78 | componentDidMount() { 79 | this.fetchItems() 80 | } 81 | 82 | render() { 83 | const { loading } = this.state 84 | const { item } = this 85 | 86 | return item ? ( 87 |
    88 |
    89 | 94 |

    {item.title}

    95 |
    96 | {item.url ? ({host(item.url)}) : null} 97 |

    98 | {item.score} points | by{' '} 99 | {item.by} 100 | {' ' + timeAgo(item.time)} ago 101 |

    102 |
    103 |
    104 |

    105 | {item.kids ? item.descendants + ' comments' : 'No comments yet.'} 106 | 107 |

    108 | {loading || !item.kids ? null : ( 109 |
      110 | {item.kids.map(id => ( 111 | 115 | ))} 116 |
    117 | )} 118 |
    119 |
    120 | ) : null 121 | } 122 | } 123 | -------------------------------------------------------------------------------- /src/views/ItemView/styles.scss: -------------------------------------------------------------------------------- 1 | .item-view-header { 2 | background-color: #fff; 3 | padding: 1.8em 2em 1em; 4 | box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1); 5 | 6 | h1 { 7 | display: inline; 8 | font-size: 1.5em; 9 | margin: 0; 10 | margin-right: 0.5em; 11 | } 12 | 13 | .host, 14 | .meta, 15 | .meta a { 16 | color: #828282; 17 | } 18 | 19 | .meta a { 20 | text-decoration: underline; 21 | } 22 | } 23 | 24 | .item-view-comments { 25 | background-color: #fff; 26 | margin-top: 10px; 27 | padding: 0 2em 0.5em; 28 | } 29 | 30 | .item-view-comments-header { 31 | margin: 0; 32 | font-size: 1.1em; 33 | padding: 1em 0; 34 | position: relative; 35 | 36 | .spinner { 37 | display: inline-block; 38 | margin: -15px 0; 39 | } 40 | } 41 | 42 | .comment-children { 43 | list-style-type: none; 44 | padding: 0; 45 | margin: 0; 46 | } 47 | 48 | @media (max-width: 600px) { 49 | .item-view-header h1 { 50 | font-size: 1.25em; 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/views/UserView/index.js: -------------------------------------------------------------------------------- 1 | import PropTypes from 'prop-types' 2 | import React from 'react' 3 | import { connect } from 'react-redux' 4 | 5 | import styles from './styles.scss' 6 | 7 | import { fetchUser } from 'store' 8 | import { withSsr, timeAgo } from 'utils' 9 | 10 | const USER_NOT_FOUND = 'User Not Found' 11 | 12 | @connect( 13 | ({ users }) => ({ users }), 14 | (dispatch, props) => ({ 15 | fetchUser: () => dispatch(fetchUser(props.match.params.id)), 16 | }), 17 | ) 18 | @withSsr(styles, false, self => { 19 | const { 20 | users, 21 | match: { 22 | params: { id }, 23 | }, 24 | } = self.props 25 | const user = users[id] 26 | 27 | if (user) { 28 | return id 29 | } 30 | 31 | if (user === false) { 32 | return USER_NOT_FOUND 33 | } 34 | 35 | if (!__SERVER__) { 36 | return self.props.fetchUser().then(() => (users[id] ? id : USER_NOT_FOUND)) 37 | } 38 | }) 39 | export default class UserView extends React.PureComponent { 40 | static propTypes = { 41 | match: PropTypes.object.isRequired, 42 | users: PropTypes.object.isRequired, 43 | // eslint-disable-next-line react/no-unused-prop-types 44 | fetchUser: PropTypes.func.isRequired, 45 | } 46 | 47 | get user() { 48 | const { match, users } = this.props 49 | return users[match.params.id] 50 | } 51 | 52 | static preload({ match, store }) { 53 | return store.dispatch(fetchUser(match.params.id)) 54 | } 55 | 56 | render() { 57 | const { user } = this 58 | 59 | return ( 60 |
    61 | {user ? ( 62 | <> 63 |

    User : {user.id}

    64 |
      65 |
    • 66 | Created: {timeAgo(user.created)}{' '} 67 | ago 68 |
    • 69 |
    • 70 | Karma: {user.karma} 71 |
    • 72 | {user.about ? ( 73 |
    • 77 | ) : null} 78 |
    79 |

    80 | 81 | submissions 82 | {' '} 83 | | 84 | 85 | comments 86 | 87 |

    88 | 89 | ) : user === false ? ( 90 |

    User not found.

    91 | ) : null} 92 |
    93 | ) 94 | } 95 | } 96 | -------------------------------------------------------------------------------- /src/views/UserView/styles.scss: -------------------------------------------------------------------------------- 1 | .user-view { 2 | background-color: #fff; 3 | box-sizing: border-box; 4 | padding: 2em 3em; 5 | h1 { 6 | margin: 0; 7 | font-size: 1.5em; 8 | } 9 | .meta { 10 | list-style-type: none; 11 | padding: 0; 12 | } 13 | .label { 14 | display: inline-block; 15 | min-width: 4em; 16 | } 17 | .about { 18 | margin: 1em 0; 19 | } 20 | .links a { 21 | text-decoration: underline; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /vercel.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "react-hackernews", 3 | "version": 2, 4 | "alias": [ 5 | "react-hn.vercel.app" 6 | ], 7 | "github": { 8 | "silent": true 9 | }, 10 | "rewrites": [ 11 | { 12 | "source": "/(.*)", 13 | "destination": "https://react-hacknews.herokuapp.com/$1" 14 | } 15 | ] 16 | } 17 | --------------------------------------------------------------------------------