├── .prettierrc.json ├── .husky ├── .gitignore └── pre-commit ├── .babelrc ├── jest.setup.ts ├── public ├── quote.png ├── favicon.ico └── vercel.svg ├── .prettierignore ├── jsconfig.json ├── next-env.d.ts ├── test-utils ├── test-component │ ├── test-component.module.css │ └── TestComponent.tsx └── resizeWindow.ts ├── utils └── percentage.ts ├── .github └── screenshots │ └── dev-quotes-screenshot.png ├── .vscode └── settings.json ├── components ├── QuoteSocialSharing │ ├── QuoteSocialSharing.module.css │ └── QuoteSocialSharing.tsx ├── Quote │ ├── getQuote.ts │ ├── QuoteLoading.tsx │ ├── QuoteError.tsx │ ├── QuoteText.tsx │ ├── Quote.module.css │ └── Quote.tsx ├── QuoteControls │ ├── QuoteControls.module.css │ └── QuoteControls.tsx ├── QuoteProgress │ ├── QuoteProgress.tsx │ └── QuoteProgress.module.css └── ProgressBar │ └── ProgressBar.tsx ├── lint-staged.config.js ├── __tests__ ├── utils │ └── percentage.test.ts ├── configuration │ └── jest.test.tsx └── components │ ├── QuoteProgress.test.tsx │ ├── QuoteSocialSharing.test.tsx │ ├── ProgressBar.test.tsx │ ├── QuoteControls.test.tsx │ └── Quote.test.tsx ├── pages ├── _app.tsx ├── index.tsx └── api │ └── quote.ts ├── .gitignore ├── jest.config.js ├── tsconfig.json ├── styles ├── globals.css └── pages │ └── Home.module.css ├── package.json ├── .eslintrc.js ├── hooks └── useProgress.ts └── README.md /.prettierrc.json: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.husky/.gitignore: -------------------------------------------------------------------------------- 1 | _ 2 | -------------------------------------------------------------------------------- /.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "presets": ["next/babel"] 3 | } 4 | -------------------------------------------------------------------------------- /jest.setup.ts: -------------------------------------------------------------------------------- 1 | import "@testing-library/jest-dom"; 2 | -------------------------------------------------------------------------------- /.husky/pre-commit: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | . "$(dirname "$0")/_/husky.sh" 3 | 4 | yarn lint-staged -------------------------------------------------------------------------------- /public/quote.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EddyVinck/dev-quotes/HEAD/public/quote.png -------------------------------------------------------------------------------- /.prettierignore: -------------------------------------------------------------------------------- 1 | # Ignore artifacts: 2 | build 3 | coverage 4 | out 5 | .next 6 | node_modules -------------------------------------------------------------------------------- /public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EddyVinck/dev-quotes/HEAD/public/favicon.ico -------------------------------------------------------------------------------- /jsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "typeAcquisition": { 3 | "include": ["jest"] 4 | } 5 | } 6 | -------------------------------------------------------------------------------- /next-env.d.ts: -------------------------------------------------------------------------------- 1 | /// 2 | /// 3 | -------------------------------------------------------------------------------- /test-utils/test-component/test-component.module.css: -------------------------------------------------------------------------------- 1 | .test-component { 2 | font-size: 18px; 3 | } 4 | -------------------------------------------------------------------------------- /utils/percentage.ts: -------------------------------------------------------------------------------- 1 | export function percentage(value: number, max: number): number { 2 | return (value / max) * 100; 3 | } 4 | -------------------------------------------------------------------------------- /.github/screenshots/dev-quotes-screenshot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EddyVinck/dev-quotes/HEAD/.github/screenshots/dev-quotes-screenshot.png -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "editor.formatOnSave": true, 3 | "editor.codeActionsOnSave": { 4 | "source.fixAll.eslint": true 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /components/QuoteSocialSharing/QuoteSocialSharing.module.css: -------------------------------------------------------------------------------- 1 | .container { 2 | display: flex; 3 | } 4 | .container a { 5 | margin-right: 8px; 6 | } 7 | -------------------------------------------------------------------------------- /components/Quote/getQuote.ts: -------------------------------------------------------------------------------- 1 | import { QuoteResponse } from "../../pages/api/quote"; 2 | 3 | export function getQuote(): Promise { 4 | return fetch("/api/quote").then((res) => res.json()); 5 | } 6 | -------------------------------------------------------------------------------- /components/Quote/QuoteLoading.tsx: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import { QuoteText } from "./QuoteText"; 3 | 4 | export const QuoteLoading: React.FC = () => { 5 | return ; 6 | }; 7 | -------------------------------------------------------------------------------- /test-utils/test-component/TestComponent.tsx: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import styles from "./test-component.module.css"; 3 | 4 | export const TestComponent: React.FC = ({ children }) => { 5 | return
{children}
; 6 | }; 7 | -------------------------------------------------------------------------------- /lint-staged.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | // Run type-check on changes to TypeScript files 3 | "**/*.ts?(x)": () => "yarn type-check", 4 | // Run ESLint on changes to JavaScript/TypeScript files 5 | "**/*.(ts|js)?(x)": filenames => `yarn lint ${filenames.join(" ")}` 6 | }; 7 | -------------------------------------------------------------------------------- /test-utils/resizeWindow.ts: -------------------------------------------------------------------------------- 1 | export const resizeWindow = (width: number, height: number): void => { 2 | /* eslint-disable */ 3 | // @ts-ignore 4 | window.innerWidth = width; 5 | // @ts-ignore 6 | window.innerHeight = height; 7 | /* eslint-enable */ 8 | window.dispatchEvent(new Event("resize")); 9 | }; 10 | -------------------------------------------------------------------------------- /components/Quote/QuoteError.tsx: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import { QuoteText } from "./QuoteText"; 3 | 4 | export const QuoteError: React.FC = () => { 5 | return ( 6 | 10 | ); 11 | }; 12 | -------------------------------------------------------------------------------- /components/Quote/QuoteText.tsx: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import styles from "./Quote.module.css"; 3 | 4 | interface Props { 5 | quote: string; 6 | author: string; 7 | } 8 | 9 | export const QuoteText: React.FC = ({ quote, author }) => { 10 | return ( 11 |
12 |
{quote}
13 |
{author}
14 |
15 | ); 16 | }; 17 | -------------------------------------------------------------------------------- /__tests__/utils/percentage.test.ts: -------------------------------------------------------------------------------- 1 | import { percentage } from "../../utils/percentage"; 2 | 3 | describe("percentage helper function", () => { 4 | test("percentage calculates percentages correctly", () => { 5 | const result = percentage(50, 100); 6 | expect(result).toBe(50); 7 | }); 8 | test("percentage returns 100 if the value is equal to the maximum value", () => { 9 | const result = percentage(8000, 8000); 10 | expect(result).toBe(100); 11 | }); 12 | }); 13 | -------------------------------------------------------------------------------- /pages/_app.tsx: -------------------------------------------------------------------------------- 1 | import { AppProps } from "next/dist/next-server/lib/router/router"; 2 | import "../styles/globals.css"; 3 | import { QueryClient, QueryClientProvider } from "react-query"; 4 | 5 | const queryClient = new QueryClient(); 6 | 7 | const MyApp: React.FC = ({ Component, pageProps }) => { 8 | return ( 9 | 10 | ; 11 | 12 | ); 13 | }; 14 | 15 | export default MyApp; 16 | -------------------------------------------------------------------------------- /.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 | # next.js 12 | /.next/ 13 | /out/ 14 | 15 | # production 16 | /build 17 | 18 | # misc 19 | .DS_Store 20 | *.pem 21 | 22 | # debug 23 | npm-debug.log* 24 | yarn-debug.log* 25 | yarn-error.log* 26 | 27 | # local env files 28 | .env.local 29 | .env.development.local 30 | .env.test.local 31 | .env.production.local 32 | 33 | # vercel 34 | .vercel 35 | -------------------------------------------------------------------------------- /__tests__/configuration/jest.test.tsx: -------------------------------------------------------------------------------- 1 | import { render, screen } from "@testing-library/react"; 2 | import { TestComponent } from "../../test-utils/test-component/TestComponent"; 3 | 4 | describe("Jest is working as intended", () => { 5 | test("Jest can parse JSX and run assertions", () => { 6 | render(
test content
); 7 | 8 | expect(screen.getByText(/test content/i)).toBeInTheDocument(); 9 | }); 10 | test("Jest can handle .tsx file imports", () => { 11 | render(test component); 12 | 13 | expect(screen.getByText(/test component/i)).toBeInTheDocument(); 14 | }); 15 | }); 16 | -------------------------------------------------------------------------------- /components/QuoteControls/QuoteControls.module.css: -------------------------------------------------------------------------------- 1 | .quoteControls { 2 | background: white; 3 | border: 1px solid black; 4 | } 5 | @supports (display: grid) { 6 | .quoteControls { 7 | display: grid; 8 | grid-template-columns: 1fr; 9 | } 10 | 11 | @media screen and (min-width: 768px) { 12 | .quoteControls { 13 | grid-template-columns: 1fr 1fr; 14 | } 15 | } 16 | } 17 | .quoteControls button { 18 | border: 1px solid black; 19 | padding: 8px 16px; 20 | background: none; 21 | font-weight: 600; 22 | } 23 | .quoteControls button[aria-checked="true"] { 24 | background: blue; 25 | color: white; 26 | } 27 | -------------------------------------------------------------------------------- /jest.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | roots: [''], 3 | moduleFileExtensions: ['ts', 'tsx', 'js', 'json', 'jsx'], 4 | testPathIgnorePatterns: ['/.next/', '/node_modules/'], 5 | transformIgnorePatterns: ['[/\\\\]node_modules[/\\\\].+\\.(ts|tsx)$'], 6 | transform: { 7 | '^.+\\.(ts|tsx)$': 'babel-jest', 8 | }, 9 | watchPlugins: ['jest-watch-typeahead/filename', 'jest-watch-typeahead/testname'], 10 | moduleNameMapper: { 11 | '\\.(css|less|sass|scss)$': 'identity-obj-proxy', 12 | '\\.(gif|ttf|eot|svg|png)$': '/test/__mocks__/fileMock.js', 13 | }, 14 | setupFilesAfterEnv: ['/jest.setup.ts'], 15 | }; 16 | -------------------------------------------------------------------------------- /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 | "strict": true, 12 | "forceConsistentCasingInFileNames": true, 13 | "noEmit": true, 14 | "esModuleInterop": true, 15 | "module": "esnext", 16 | "moduleResolution": "node", 17 | "resolveJsonModule": true, 18 | "isolatedModules": true, 19 | "jsx": "preserve" 20 | }, 21 | "include": [ 22 | "next-env.d.ts", 23 | "**/*.ts", 24 | "**/*.tsx" 25 | ], 26 | "exclude": [ 27 | "node_modules" 28 | ] 29 | } 30 | -------------------------------------------------------------------------------- /components/QuoteProgress/QuoteProgress.tsx: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import { ProgressBar } from "../ProgressBar/ProgressBar"; 3 | import styles from "./QuoteProgress.module.css"; 4 | 5 | interface Props { 6 | value: number; 7 | max: number; 8 | id?: string; 9 | } 10 | 11 | export const QuoteProgress: React.FC = ({ 12 | value, 13 | max, 14 | id = "quote-timer-progress", 15 | ...props 16 | }) => { 17 | return ( 18 |
19 | 22 | 23 |
24 | ); 25 | }; 26 | -------------------------------------------------------------------------------- /components/ProgressBar/ProgressBar.tsx: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import { percentage } from "../../utils/percentage"; 3 | 4 | export interface ProgressBarProps { 5 | value: number; 6 | max: number; 7 | id: string; 8 | } 9 | 10 | export const ProgressBar: React.FC = ({ 11 | value, 12 | max, 13 | id, 14 | children, 15 | ...props 16 | }) => { 17 | const progress = percentage(value, max); 18 | return ( 19 |
20 | {children} 21 | 22 | {progress}% 23 |
24 | {progress}% 25 |
26 |
27 |
28 | ); 29 | }; 30 | -------------------------------------------------------------------------------- /components/Quote/Quote.module.css: -------------------------------------------------------------------------------- 1 | .quoteBlock { 2 | display: flex; 3 | justify-content: center; 4 | align-items: center; 5 | flex-direction: column; 6 | min-height: 260px; 7 | width: 100%; 8 | max-width: 820px; 9 | padding: 10px; 10 | margin: 0; 11 | background: black; 12 | } 13 | @media (min-width: 768px) { 14 | .quoteBlock { 15 | padding: 20px; 16 | } 17 | } 18 | .quoteText { 19 | text-align: center; 20 | color: white; 21 | font-size: clamp(18px, 4vw, 22px); 22 | quotes: "“" "”" "‘" "’"; 23 | } 24 | .quoteText::before { 25 | content: open-quote; 26 | } 27 | .quoteText::after { 28 | content: close-quote; 29 | } 30 | .quoteText::before, 31 | .quoteText::after { 32 | font-size: clamp(22px, 6vw, 28px); 33 | color: darkgray; 34 | } 35 | .quoteBlock figcaption { 36 | color: darkgray; 37 | } 38 | -------------------------------------------------------------------------------- /styles/globals.css: -------------------------------------------------------------------------------- 1 | html, 2 | body { 3 | padding: 0; 4 | margin: 0; 5 | font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Roboto, Oxygen, 6 | Ubuntu, Cantarell, Fira Sans, Droid Sans, Helvetica Neue, sans-serif; 7 | } 8 | 9 | a { 10 | color: inherit; 11 | text-decoration: none; 12 | } 13 | 14 | * { 15 | box-sizing: border-box; 16 | -webkit-font-smoothing: antialiased; 17 | -moz-osx-font-smoothing: grayscale; 18 | } 19 | 20 | .visually-hidden { 21 | clip: rect(0 0 0 0); 22 | clip-path: inset(50%); 23 | height: 1px; 24 | overflow: hidden; 25 | position: absolute; 26 | white-space: nowrap; 27 | width: 1px; 28 | } 29 | 30 | @media (hover: none) { 31 | .hover-only { 32 | display: none; 33 | } 34 | } 35 | @media (hover: hover) { 36 | .touch-only { 37 | display: none; 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /pages/index.tsx: -------------------------------------------------------------------------------- 1 | import * as React from "react"; 2 | import Head from "next/head"; 3 | import styles from "../styles/pages/Home.module.css"; 4 | import { Quote } from "../components/Quote/Quote"; 5 | 6 | const Home: React.FC = () => { 7 | return ( 8 |
9 | 10 | DevQuotes! 11 | 12 | 13 | 14 |
15 |

Welcome to Dev Quotes!

16 | 17 |
18 | 19 |
20 | Powered by{" "} 21 | DevQuotes logo 22 | DevQuotes 23 |
24 |
25 | ); 26 | }; 27 | 28 | export default Home; 29 | -------------------------------------------------------------------------------- /__tests__/components/QuoteProgress.test.tsx: -------------------------------------------------------------------------------- 1 | import { render, screen } from "@testing-library/react"; 2 | import { QuoteProgress } from "../../components/QuoteProgress/QuoteProgress"; 3 | 4 | describe("QuoteProgress", () => { 5 | test('should display an element with the "progressbar" role with the right values', async () => { 6 | render(); 7 | expect(await screen.findByRole("progressbar")).toBeInTheDocument(); 8 | expect(await screen.findByRole("progressbar")).toHaveProperty("value", 10); 9 | expect(await screen.findByRole("progressbar")).toHaveProperty("max", 100); 10 | expect(await screen.findByRole("progressbar")).toHaveProperty("id", "test"); 11 | }); 12 | test("renders a label not visible to users without screenreaders", async () => { 13 | render(); 14 | const label = await screen.findByText(/time/i); 15 | expect(label).toBeInTheDocument(); 16 | expect(label).toHaveClass("visually-hidden"); 17 | }); 18 | }); 19 | -------------------------------------------------------------------------------- /public/vercel.svg: -------------------------------------------------------------------------------- 1 | 3 | 4 | -------------------------------------------------------------------------------- /__tests__/components/QuoteSocialSharing.test.tsx: -------------------------------------------------------------------------------- 1 | import { render, screen } from "@testing-library/react"; 2 | import { QuoteSocialSharing } from "../../components/QuoteSocialSharing/QuoteSocialSharing"; 3 | 4 | describe("QuoteSocialSharing", () => { 5 | test("should render a text in the link href", () => { 6 | const text = '"this is a fancy quote" - Eddy Vinck'; 7 | 8 | render(); 9 | 10 | const links = screen.getAllByRole("link"); 11 | 12 | links.forEach((link) => { 13 | expect(link).toHaveAttribute("href"); 14 | expect((link.getAttribute("href") as string).includes(text)).toBeTruthy(); 15 | }); 16 | }); 17 | 18 | // This is a bit tricky because it would require the global styles to be available in the test 19 | // Will skip this for now, since this would essentially be testing the CSS which works correctly when viewed in the browser 20 | // Perhaps this would be a great test to do with and end-to-end tool like Cypress 21 | test.todo( 22 | "should render the correct whatsapp link when a device can or cannot hover" 23 | ); 24 | }); 25 | -------------------------------------------------------------------------------- /__tests__/components/ProgressBar.test.tsx: -------------------------------------------------------------------------------- 1 | import { render, screen } from "@testing-library/react"; 2 | import { ProgressBar } from "../../components/ProgressBar/ProgressBar"; 3 | 4 | describe("ProgressBar", () => { 5 | test('should display an element with the "progressbar" role', async () => { 6 | render(); 7 | expect(await screen.findByRole("progressbar")).toBeInTheDocument(); 8 | }); 9 | test("renders a label", async () => { 10 | render( 11 | 12 | 13 | 14 | ); 15 | expect(await screen.findByLabelText(/progress/i)).toBeInTheDocument(); 16 | }); 17 | test("the visual representation of the progress bar has the correct width", async () => { 18 | const { container } = render( 19 | 20 | 21 | 22 | ); 23 | const span = container.querySelector("span"); 24 | expect(span).toHaveAttribute("style", "width: 10%;"); 25 | }); 26 | }); 27 | -------------------------------------------------------------------------------- /pages/api/quote.ts: -------------------------------------------------------------------------------- 1 | import type { NextApiRequest, NextApiResponse } from "next"; 2 | 3 | export interface QuoteData { 4 | author: string; 5 | id: number; 6 | quote: string; 7 | } 8 | 9 | export interface QuoteError extends Pick { 10 | error: string; 11 | } 12 | 13 | const quoteBaseUrl = "http://quotes.stormconsultancy.co.uk"; 14 | const quoteEndpoint = `${quoteBaseUrl}/random.json`; 15 | 16 | const ErrorQuote: QuoteError = { 17 | author: "Eddy Vinck", 18 | quote: "This error could have been a quote, but an error occurred!", 19 | error: "Something went wrong!", 20 | id: -1, 21 | }; 22 | 23 | export type QuoteResponse = QuoteData & QuoteError; 24 | 25 | export default async ( 26 | req: NextApiRequest, 27 | res: NextApiResponse 28 | ): Promise => { 29 | try { 30 | const quoteRequest = await fetch(quoteEndpoint, { 31 | method: "get", 32 | headers: { 33 | "Content-Type": "application/json", 34 | }, 35 | }); 36 | const quoteData = await quoteRequest.json(); 37 | return res.status(200).json(quoteData); 38 | } catch (error) { 39 | return res.status(500).json({ ...ErrorQuote, error: error.message }); 40 | } 41 | }; 42 | -------------------------------------------------------------------------------- /components/QuoteControls/QuoteControls.tsx: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import { useProgress } from "../../hooks/useProgress"; 3 | import styles from "./QuoteControls.module.css"; 4 | import { QuoteProgress } from "../QuoteProgress/QuoteProgress"; 5 | 6 | interface Props { 7 | fetchNewQuote: () => void; 8 | loopTime?: number; 9 | } 10 | 11 | export const QuoteControls: React.FC = ({ 12 | fetchNewQuote, 13 | loopTime = 8000, 14 | }) => { 15 | const { 16 | isEnabled: isLoopingQuotes, 17 | timeLeft, 18 | toggleIsEnabled: toggleQuoteLoop, 19 | } = useProgress(fetchNewQuote, loopTime); 20 | 21 | const progressValue = 22 | isLoopingQuotes === false ? loopTime : loopTime - timeLeft; 23 | 24 | const handleNewQuoteClick = (): void => { 25 | if (isLoopingQuotes === false) { 26 | fetchNewQuote(); 27 | } 28 | }; 29 | 30 | return ( 31 |
32 | 33 |
34 | 37 | 44 |
45 |
46 | ); 47 | }; 48 | -------------------------------------------------------------------------------- /components/QuoteSocialSharing/QuoteSocialSharing.tsx: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import { FacebookIcon, TwitterIcon, WhatsappIcon } from "react-share"; 3 | import styles from "./QuoteSocialSharing.module.css"; 4 | 5 | interface Props { 6 | text: string; 7 | } 8 | 9 | export const QuoteSocialSharing: React.FC = ({ text }) => { 10 | return ( 11 | 43 | ); 44 | }; 45 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "dev-quotes", 3 | "version": "0.1.0", 4 | "private": true, 5 | "scripts": { 6 | "dev": "next dev", 7 | "build": "next build", 8 | "start": "next start", 9 | "test": "jest", 10 | "type-check": "tsc --project tsconfig.json --pretty --noEmit", 11 | "lint": "eslint --ext js,jsx,ts,tsx --fix", 12 | "postinstall": "husky install" 13 | }, 14 | "dependencies": { 15 | "next": "10.1.3", 16 | "react": "17.0.2", 17 | "react-dom": "17.0.2", 18 | "react-query": "^3.13.10", 19 | "react-share": "^4.4.0" 20 | }, 21 | "devDependencies": { 22 | "@babel/core": "^7.13.15", 23 | "@testing-library/dom": "^7.30.3", 24 | "@testing-library/jest-dom": "^5.11.10", 25 | "@testing-library/react": "^11.2.6", 26 | "@testing-library/user-event": "^13.1.3", 27 | "@types/jest": "^26.0.22", 28 | "@types/react": "^17.0.3", 29 | "@types/react-test-renderer": "^17.0.1", 30 | "@typescript-eslint/eslint-plugin": "^4.22.0", 31 | "@typescript-eslint/parser": "^4.22.0", 32 | "babel-jest": "^26.6.3", 33 | "eslint": "^7.24.0", 34 | "eslint-config-prettier": "^8.2.0", 35 | "eslint-plugin-prettier": "^3.4.0", 36 | "eslint-plugin-react": "^7.23.2", 37 | "eslint-plugin-react-hooks": "^4.2.0", 38 | "husky": "^6.0.0", 39 | "identity-obj-proxy": "^3.0.0", 40 | "jest": "^26.6.3", 41 | "jest-watch-typeahead": "^0.6.2", 42 | "lint-staged": "^10.5.4", 43 | "prettier": "2.2.1", 44 | "react-test-renderer": "^17.0.2", 45 | "typescript": "^4.2.4" 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /.eslintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | root: true, 3 | env: { 4 | node: true, 5 | es6: true, 6 | }, 7 | parserOptions: { ecmaVersion: 8 }, // to enable features such as async/await 8 | ignorePatterns: ["node_modules/*", ".next/*", ".out/*", "!.prettierrc.js"], // We don't want to lint generated files nor node_modules, but we want to lint .prettierrc.js (ignored by default by eslint) 9 | extends: ["eslint:recommended"], 10 | overrides: [ 11 | { 12 | files: ["**/*.ts", "**/*.tsx"], 13 | parser: "@typescript-eslint/parser", 14 | settings: { react: { version: "detect" } }, 15 | env: { 16 | browser: true, 17 | node: true, 18 | es6: true, 19 | }, 20 | extends: [ 21 | "plugin:prettier/recommended", 22 | "eslint:recommended", 23 | "plugin:@typescript-eslint/recommended", // TypeScript rules 24 | "plugin:react/recommended", // React rules 25 | "plugin:react-hooks/recommended", // React hooks rules 26 | ], 27 | rules: { 28 | "prettier/prettier": ["error", {}, { usePrettierrc: true }], // Includes prettier rules 29 | // We will use TypeScript's types for component props instead 30 | "react/prop-types": "off", 31 | // No need to import React when using Next.js 32 | "react/react-in-jsx-scope": "off", 33 | "@typescript-eslint/no-unused-vars": ["error"], 34 | "@typescript-eslint/explicit-function-return-type": [ 35 | "warn", 36 | { 37 | allowExpressions: true, 38 | allowConciseArrowFunctionExpressionsStartingWithVoid: true, 39 | }, 40 | ], 41 | }, 42 | }, 43 | ], 44 | }; 45 | -------------------------------------------------------------------------------- /__tests__/components/QuoteControls.test.tsx: -------------------------------------------------------------------------------- 1 | import { act, render, screen } from "@testing-library/react"; 2 | import userEvent from "@testing-library/user-event"; 3 | import { QuoteControls } from "../../components/QuoteControls/QuoteControls"; 4 | 5 | beforeEach(() => { 6 | jest.useFakeTimers(); 7 | }); 8 | afterEach(() => { 9 | jest.useRealTimers(); 10 | }); 11 | describe("QuoteControls", () => { 12 | test('runs the passed function when "new quote" is clicked', () => { 13 | const fetchNewQuote = jest.fn(); 14 | render(); 15 | 16 | userEvent.click(screen.getByText(/new quote/i)); 17 | expect(fetchNewQuote).toHaveBeenCalled(); 18 | }); 19 | test('disables the "new quote" button when "loop quotes" is enabled and enables it when the looping is turned off', () => { 20 | const fetchNewQuote = jest.fn(); 21 | render(); 22 | 23 | userEvent.click(screen.getByText(/loop quotes/i)); 24 | const button = screen.getByText(/new quote/i); 25 | expect(button).toBeDisabled(); 26 | userEvent.click(screen.getByText(/loop quotes/i)); 27 | expect(button).toBeEnabled(); 28 | }); 29 | test("passes the right progressValue to the progress bar", async () => { 30 | const fetchNewQuote = jest.fn(); 31 | render(); 32 | 33 | act(() => { 34 | userEvent.click(screen.getByText(/loop quotes/i)); 35 | jest.advanceTimersByTime(500); 36 | }); 37 | expect(screen.queryByRole("progressbar")).toHaveValue(500); 38 | expect(screen.queryByRole("progressbar")).toHaveTextContent("50%"); 39 | jest.clearAllTimers(); 40 | }); 41 | }); 42 | -------------------------------------------------------------------------------- /components/Quote/Quote.tsx: -------------------------------------------------------------------------------- 1 | import React, { useCallback } from "react"; 2 | import { useQuery } from "react-query"; 3 | import { QuoteData } from "../../pages/api/quote"; 4 | import { QuoteControls } from "../QuoteControls/QuoteControls"; 5 | import { QuoteSocialSharing } from "../QuoteSocialSharing/QuoteSocialSharing"; 6 | import { getQuote } from "./getQuote"; 7 | import { QuoteError } from "./QuoteError"; 8 | import { QuoteLoading } from "./QuoteLoading"; 9 | import { QuoteText } from "./QuoteText"; 10 | 11 | export function getSharingText(quote: string, author: string): string { 12 | const newLine = "%0D"; 13 | const hashtag = "%23"; 14 | const sharingText = `"${quote}" ${newLine.repeat( 15 | 2 16 | )}- ${author} ${hashtag}devquotes`; 17 | return sharingText; 18 | } 19 | 20 | export const Quote: React.FC = () => { 21 | const { data, status, refetch } = useQuery("quote", getQuote, { 22 | refetchOnWindowFocus: false, 23 | }); 24 | const fetchNewQuote = useCallback(() => refetch(), [refetch]); 25 | 26 | if (status === "loading") return ; 27 | if (status === "error" || (data && data.error)) return ; 28 | if (status === "success" && data) { 29 | const { quote, author } = data as QuoteData; 30 | const sharingText = getSharingText(quote, author); 31 | 32 | return ( 33 |
34 | 35 | 36 |

Share on social media

37 | 38 |
39 | ); 40 | } 41 | 42 | // This code should never be reachable, since react-query's status will never be "idle" if you do not pass it the `enabled: false` option. There is a test to make sure of this. 43 | throw new Error("Something went wrong."); 44 | }; 45 | -------------------------------------------------------------------------------- /styles/pages/Home.module.css: -------------------------------------------------------------------------------- 1 | .container { 2 | min-height: 100vh; 3 | padding: 0 0.5rem; 4 | display: flex; 5 | flex-direction: column; 6 | justify-content: center; 7 | align-items: center; 8 | } 9 | 10 | .main { 11 | padding: 5rem 0; 12 | flex: 1; 13 | display: flex; 14 | flex-direction: column; 15 | justify-content: center; 16 | align-items: center; 17 | max-width: 92%; 18 | } 19 | @media screen and (min-width: 768px) { 20 | .main { 21 | max-width: 740px; 22 | } 23 | } 24 | 25 | .footer { 26 | width: 100%; 27 | height: 100px; 28 | border-top: 1px solid #eaeaea; 29 | display: flex; 30 | justify-content: center; 31 | align-items: center; 32 | } 33 | 34 | .footer img { 35 | margin: 0 0.5rem; 36 | } 37 | 38 | .footer a { 39 | display: flex; 40 | justify-content: center; 41 | align-items: center; 42 | } 43 | 44 | .title a { 45 | color: #0070f3; 46 | text-decoration: none; 47 | } 48 | 49 | .title a:hover, 50 | .title a:focus, 51 | .title a:active { 52 | text-decoration: underline; 53 | } 54 | 55 | .title { 56 | margin: 0 0 4rem; 57 | line-height: 1.15; 58 | font-size: clamp(1.8rem, 10vw, 3rem); 59 | } 60 | 61 | .title, 62 | .description { 63 | text-align: center; 64 | } 65 | 66 | .description { 67 | line-height: 1.5; 68 | font-size: 1.5rem; 69 | } 70 | 71 | .code { 72 | background: #fafafa; 73 | border-radius: 5px; 74 | padding: 0.75rem; 75 | font-size: 1.1rem; 76 | font-family: Menlo, Monaco, Lucida Console, Liberation Mono, DejaVu Sans Mono, 77 | Bitstream Vera Sans Mono, Courier New, monospace; 78 | } 79 | 80 | .grid { 81 | display: flex; 82 | align-items: center; 83 | justify-content: center; 84 | flex-wrap: wrap; 85 | max-width: 800px; 86 | margin-top: 3rem; 87 | } 88 | 89 | .card { 90 | margin: 1rem; 91 | flex-basis: 45%; 92 | padding: 1.5rem; 93 | text-align: left; 94 | color: inherit; 95 | text-decoration: none; 96 | border: 1px solid #eaeaea; 97 | border-radius: 10px; 98 | transition: color 0.15s ease, border-color 0.15s ease; 99 | } 100 | 101 | .card:hover, 102 | .card:focus, 103 | .card:active { 104 | color: #0070f3; 105 | border-color: #0070f3; 106 | } 107 | 108 | .card h3 { 109 | margin: 0 0 1rem 0; 110 | font-size: 1.5rem; 111 | } 112 | 113 | .card p { 114 | margin: 0; 115 | font-size: 1.25rem; 116 | line-height: 1.5; 117 | } 118 | 119 | .logo { 120 | height: 1em; 121 | } 122 | 123 | @media (max-width: 600px) { 124 | .grid { 125 | width: 100%; 126 | flex-direction: column; 127 | } 128 | } 129 | -------------------------------------------------------------------------------- /components/QuoteProgress/QuoteProgress.module.css: -------------------------------------------------------------------------------- 1 | /* Altered version of https://codepen.io/team/css-tricks/pen/PNNQxm */ 2 | .progressBar progress[value] { 3 | /* Get rid of the default appearance */ 4 | appearance: none; 5 | /* This unfortunately leaves a trail of border behind in Firefox and Opera. We can remove that by setting the border to none. */ 6 | border: none; 7 | /* Add dimensions */ 8 | width: 100%; 9 | height: 20px; 10 | /* Although firefox doesn't provide any additional pseudo class to style the progress element container, any style applied here works on the container. */ 11 | background-color: whiteSmoke; 12 | border-radius: 3px; 13 | box-shadow: 0 2px 3px rgba(0, 0, 0, 0.5) inset; 14 | /* Of all IE, only IE10 supports progress element that too partially. It only allows to change the background-color of the progress value using the 'color' attribute. */ 15 | color: royalblue; 16 | position: relative; 17 | margin: 0; 18 | } 19 | 20 | /* 21 | Webkit browsers provide two pseudo classes that can be use to style HTML5 progress element. 22 | -webkit-progress-bar -> To style the progress element container 23 | -webkit-progress-value -> To style the progress element value. 24 | */ 25 | 26 | .progressBar progress[value]::-webkit-progress-bar { 27 | background-color: whiteSmoke; 28 | border-radius: 3px; 29 | box-shadow: 0 2px 3px rgba(0, 0, 0, 0.5) inset; 30 | } 31 | 32 | .progressBar progress[value]::-webkit-progress-value { 33 | position: relative; 34 | background-size: 35px 20px, 100% 100%, 100% 100%; 35 | border-radius: 3px; 36 | background-color: blue; 37 | } 38 | 39 | .progressBar progress[value]::-webkit-progress-value:after { 40 | content: ""; 41 | position: absolute; 42 | width: 5px; 43 | height: 5px; 44 | top: 7px; 45 | right: 7px; 46 | background-color: white; 47 | border-radius: 100%; 48 | } 49 | 50 | .progressBar progress[value]::-moz-progress-bar { 51 | background-image: -moz-linear-gradient( 52 | top, 53 | rgba(255, 255, 255, 0.25), 54 | rgba(0, 0, 0, 0.2) 55 | ), 56 | -moz-linear-gradient(left, blue, blue); 57 | 58 | background-size: 35px 20px, 100% 100%, 100% 100%; 59 | border-radius: 3px; 60 | } 61 | 62 | /* Fallback technique styles */ 63 | .progressBar progress .progress-bar { 64 | background-color: whiteSmoke; 65 | border-radius: 3px; 66 | box-shadow: 0 2px 3px rgba(0, 0, 0, 0.5) inset; 67 | 68 | /* Dimensions should be similar to the parent progress element. */ 69 | width: 100%; 70 | height: 20px; 71 | } 72 | 73 | .progressBar progress .progress-bar span { 74 | background-color: royalblue; 75 | border-radius: 3px; 76 | 77 | display: block; 78 | text-indent: -9999px; 79 | } 80 | -------------------------------------------------------------------------------- /hooks/useProgress.ts: -------------------------------------------------------------------------------- 1 | import { useCallback, useEffect, useRef, useState } from "react"; 2 | 3 | export function useProgress( 4 | callback: () => void | Promise, 5 | loopTime = 5000 6 | ): { 7 | isEnabled: boolean; 8 | isCallbackRunning: boolean; 9 | timeLeft: number; 10 | toggleIsEnabled: (overrideToggleValue?: boolean) => void; 11 | } { 12 | const promise = useCallback(() => Promise.resolve(callback()), [callback]); 13 | const [isEnabled, setIsEnabled] = useState(false); 14 | const [isTimerRunning, setIsTimerRunning] = useState(false); 15 | const [timeLeft, setTimeLeft] = useState(loopTime); 16 | const timeLeftIntervalRef = useRef(-1); 17 | const [isCallbackRunning, setIsCallbackRunning] = useState(false); 18 | 19 | function clearTimerInterval(): void { 20 | clearInterval(timeLeftIntervalRef.current); 21 | timeLeftIntervalRef.current = -1; 22 | } 23 | 24 | function toggleIsEnabled(overrideToggleValue?: boolean): void { 25 | clearTimerInterval(); 26 | setTimeLeft(loopTime); 27 | const toggleValue = 28 | typeof overrideToggleValue !== "undefined" 29 | ? overrideToggleValue 30 | : !isEnabled; 31 | 32 | setIsEnabled(toggleValue); 33 | setIsTimerRunning(toggleValue); 34 | } 35 | 36 | const pauseProgress = useCallback(() => { 37 | clearTimerInterval(); 38 | setIsTimerRunning(false); 39 | }, []); 40 | 41 | function continueProgress(): void { 42 | setIsTimerRunning(true); 43 | } 44 | 45 | const runProvidedCallback = useCallback(() => { 46 | pauseProgress(); 47 | setIsCallbackRunning(true); 48 | promise().finally(() => { 49 | setIsCallbackRunning(false); 50 | continueProgress(); 51 | }); 52 | }, [pauseProgress, promise]); 53 | 54 | useEffect( 55 | function runCallbackOnInterval() { 56 | const timerInterval = 50; 57 | const shouldSetNewInterval = 58 | isEnabled && isTimerRunning && timeLeftIntervalRef.current === -1; 59 | if (shouldSetNewInterval) { 60 | timeLeftIntervalRef.current = window.setInterval(() => { 61 | if (isTimerRunning) { 62 | setTimeLeft((previousTime) => { 63 | const newTime = previousTime - timerInterval; 64 | if (newTime <= 0) { 65 | runProvidedCallback(); 66 | return loopTime; 67 | } 68 | return newTime; 69 | }); 70 | } 71 | }, timerInterval); 72 | } 73 | }, 74 | [isEnabled, isTimerRunning, loopTime, runProvidedCallback] 75 | ); 76 | 77 | useEffect(() => { 78 | return function cleanupUseProgress() { 79 | clearTimerInterval(); 80 | }; 81 | }, []); 82 | 83 | return { 84 | isEnabled, 85 | timeLeft, 86 | toggleIsEnabled, 87 | isCallbackRunning, 88 | }; 89 | } 90 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ![Dev Quotes homepage](./.github/screenshots/dev-quotes-screenshot.png) 2 | 3 | # Dev Quotes 4 | 5 | What is Dev Quotes? It's a small project with a professional setup used to revisit NextJS and to try out some tools I had not tried before including CSS Modules and `react-query`. Everything is written in strict TypeScript, even the tests. It connects to a public API for the quotes. You can find the API here: http://quotes.stormconsultancy.co.uk/ 6 | 7 | The project can be viewed live here: [https://devquotes.vercel.app/](https://devquotes.vercel.app/) (version of `main` branch) 8 | 9 | 10 | ## Table of contents 11 | - [Dev Quotes](#dev-quotes) 12 | - [Table of contents](#table-of-contents) 13 | - [Getting Started](#getting-started) 14 | - [Application features](#application-features) 15 | - [Tests](#tests) 16 | - [Tech used](#tech-used) 17 | - [NextJS](#nextjs) 18 | 19 | ## Getting Started 20 | 21 | First, run the development server: 22 | 23 | ```bash 24 | npm run dev 25 | # or 26 | yarn dev 27 | ``` 28 | 29 | Open [http://localhost:3000](http://localhost:3000) with your browser to see the result. 30 | 31 | [API routes](https://nextjs.org/docs/api-routes/introduction) can be accessed on [http://localhost:3000/api/quote](http://localhost:3000/api/quote). This endpoint can be edited in `pages/api/quote.ts`. 32 | 33 | The `pages/api` directory is mapped to `/api/*`. Files in this directory are treated as [API routes](https://nextjs.org/docs/api-routes/introduction) instead of React pages. 34 | 35 | To run the tests: 36 | 37 | ```bash 38 | npm test 39 | # or 40 | yarn test 41 | ``` 42 | 43 | ## Application features 44 | 45 | - Fetch a single quote 46 | - Continuously fetch new quotes in a loop on a timer, indicated by a progress bar. Kind of like a slide show. 47 | - Share quotes on Twitter, Facebook or WhatsApp 48 | 49 | ## Tests 50 | 51 | The tests can be found in the `__tests__` directory. The tests are also written in TypeScript. 52 | 53 | Jest features like fake timers and mocking have been used to skip timers and to mock requests. 54 | 55 | React Testing Library has been used to mimic user interactions as much as possible in the tests. 56 | 57 | ## Tech used 58 | 59 | - TypeScript 60 | - ReactJS 61 | - NextJS 62 | - CSS modules 63 | - Jest 64 | - React Testing Library 65 | - react-share 66 | - Babel 67 | - ESLint 68 | - Prettier 69 | - Husky 70 | - Lint Staged 71 | 72 | ### NextJS 73 | 74 | This is a [Next.js](https://nextjs.org/) project bootstrapped with [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app). 75 | 76 | To learn more about Next.js, take a look at the following resources: 77 | 78 | - [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API. 79 | - [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial. 80 | 81 | You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js/) - your feedback and contributions are welcome! 82 | 83 | The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js. 84 | 85 | Check out our [Next.js deployment documentation](https://nextjs.org/docs/deployment) for more details. 86 | -------------------------------------------------------------------------------- /__tests__/components/Quote.test.tsx: -------------------------------------------------------------------------------- 1 | import { act, render, screen, waitFor } from "@testing-library/react"; 2 | import userEvent from "@testing-library/user-event"; 3 | import * as ReactQuery from "react-query"; 4 | import { getQuote } from "../../components/Quote/getQuote"; 5 | import { Quote } from "../../components/Quote/Quote"; 6 | import { QuoteResponse } from "../../pages/api/quote"; 7 | const { QueryClient, QueryClientProvider } = ReactQuery; 8 | 9 | jest.mock("../../components/Quote/getQuote", () => { 10 | const mockGetQuote = jest.fn().mockResolvedValue({ 11 | id: 0, 12 | quote: "test quote", 13 | author: "Eddy Vinck", 14 | error: "", 15 | }); 16 | 17 | return { 18 | getQuote: mockGetQuote, 19 | }; 20 | }); 21 | 22 | const mockQuotes: QuoteResponse[] = [ 23 | { 24 | quote: "I'm going to make him an offer he can't refuse.", 25 | author: "The Godfather", 26 | id: 1, 27 | error: "", 28 | }, 29 | { 30 | quote: "My precious.", 31 | author: "The Lord of the Rings", 32 | id: 2, 33 | error: "", 34 | }, 35 | ]; 36 | 37 | describe("Quote", () => { 38 | beforeEach(() => { 39 | (getQuote as jest.Mock).mockClear(); 40 | jest.useFakeTimers(); 41 | }); 42 | afterEach(() => { 43 | jest.useRealTimers(); 44 | }); 45 | const queryClient = new QueryClient(); 46 | const MockReactQueryProvider: React.FC = ({ children }) => ( 47 | {children} 48 | ); 49 | 50 | test("renders the loader when there is no initial data", async () => { 51 | render( 52 | 53 | 54 | 55 | ); 56 | expect(screen.getByText(/loading/i)).toBeInTheDocument(); 57 | }); 58 | 59 | test("renders with mocked data", async () => { 60 | render( 61 | 62 | 63 | 64 | ); 65 | await waitFor(() => expect(getQuote).toHaveBeenCalledTimes(1)); 66 | const blockquote = screen.getByRole("figure"); 67 | expect(blockquote).toBeInTheDocument(); 68 | expect(blockquote).toHaveTextContent(/test quote/i); 69 | expect(blockquote.querySelector("figcaption")).toHaveTextContent( 70 | /eddy vinck/i 71 | ); 72 | }); 73 | test('fetches a new quote when "new quote" is clicked', async () => { 74 | render( 75 | 76 | 77 | 78 | ); 79 | await waitFor(() => expect(getQuote).toHaveBeenCalledTimes(1)); 80 | 81 | ((getQuote as unknown) as jest.Mock).mockImplementationOnce( 82 | () => mockQuotes[0] 83 | ); 84 | userEvent.click(screen.getByText(/new quote/i)); 85 | await waitFor(() => expect(getQuote).toHaveBeenCalledTimes(2)); 86 | const blockquote = screen.getByRole("figure"); 87 | expect(blockquote).toBeInTheDocument(); 88 | expect(blockquote).toHaveTextContent(/make him an offer/i); 89 | expect(blockquote.querySelector("figcaption")).toHaveTextContent( 90 | /the godfather/i 91 | ); 92 | }); 93 | 94 | describe("looping quotes", () => { 95 | test('continuously fetches a new quote when "loop quotes" is clicked', async () => { 96 | render( 97 | 98 | 99 | 100 | ); 101 | 102 | // First, toggle the looping (1 request) 103 | userEvent.click(await screen.findByText(/loop quotes/i)); 104 | await waitFor(() => expect(getQuote).toHaveBeenCalledTimes(1)); 105 | ((getQuote as unknown) as jest.Mock).mockImplementationOnce( 106 | () => mockQuotes[0] 107 | ); 108 | 109 | // wait for getQuote to run (2 requests) 110 | act(() => { 111 | jest.runAllTimers(); 112 | }); 113 | await waitFor(() => expect(getQuote).toHaveBeenCalledTimes(2)); 114 | 115 | ((getQuote as unknown) as jest.Mock).mockImplementationOnce( 116 | () => mockQuotes[1] 117 | ); 118 | 119 | // wait for getQuote to run (3 requests) 120 | act(() => { 121 | jest.runAllTimers(); 122 | }); 123 | await waitFor(() => expect(getQuote).toHaveBeenCalledTimes(3)); 124 | 125 | const blockquote = screen.getByRole("figure"); 126 | expect(blockquote).toBeInTheDocument(); 127 | expect(blockquote).toHaveTextContent(/precious/i); 128 | expect(blockquote.querySelector("figcaption")).toHaveTextContent( 129 | /lord of the rings/i 130 | ); 131 | }); 132 | 133 | test('"new quote" is disabled when "loop quotes" is enabled', async () => { 134 | render( 135 | 136 | 137 | 138 | ); 139 | await waitFor(() => expect(getQuote).toHaveBeenCalledTimes(1)); 140 | userEvent.click(screen.getByText(/loop quotes/i)); 141 | expect(screen.getByText(/new quote/i)).toBeDisabled(); 142 | }); 143 | }); 144 | 145 | // According to the react-query documentation: 146 | // status: String 147 | // Will be: 148 | // idle if the query is idle. This only happens if a query is initialized with enabled: false and no initial data is available. 149 | // So this test is just verification that that should never happen 150 | // See: https://react-query.tanstack.com/reference/useQuery 151 | test('useQuery should not be passed an `enabled: false` option because that would cause an unhandled status "idle" to become possible', async () => { 152 | const useQuerySpy = jest.spyOn(ReactQuery, "useQuery"); 153 | render( 154 | 155 | 156 | 157 | ); 158 | await waitFor(() => expect(getQuote).toHaveBeenCalledTimes(1)); 159 | expect(useQuerySpy).toHaveBeenCalledWith("quote", getQuote, { 160 | refetchOnWindowFocus: false, 161 | }); 162 | }); 163 | }); 164 | --------------------------------------------------------------------------------