diff --git a/apps/nextjs-app/.env.example b/apps/nextjs-app/.env.example new file mode 100644 index 00000000..1eabee36 --- /dev/null +++ b/apps/nextjs-app/.env.example @@ -0,0 +1,4 @@ +NEXT_PUBLIC_API_URL=http://localhost:8080/api +NEXT_PUBLIC_ENABLE_API_MOCKING=false +NEXT_PUBLIC_MOCK_API_PORT=8080 +NEXT_PUBLIC_URL=http://localhost:3000 \ No newline at end of file diff --git a/apps/nextjs-app/.env.example-e2e b/apps/nextjs-app/.env.example-e2e new file mode 100644 index 00000000..1eabee36 --- /dev/null +++ b/apps/nextjs-app/.env.example-e2e @@ -0,0 +1,4 @@ +NEXT_PUBLIC_API_URL=http://localhost:8080/api +NEXT_PUBLIC_ENABLE_API_MOCKING=false +NEXT_PUBLIC_MOCK_API_PORT=8080 +NEXT_PUBLIC_URL=http://localhost:3000 \ No newline at end of file diff --git a/apps/nextjs-app/.eslintrc.cjs b/apps/nextjs-app/.eslintrc.cjs new file mode 100644 index 00000000..410fbe9f --- /dev/null +++ b/apps/nextjs-app/.eslintrc.cjs @@ -0,0 +1,154 @@ +module.exports = { + root: true, + env: { + node: true, + es6: true, + }, + parserOptions: { ecmaVersion: 'latest', sourceType: 'module' }, + ignorePatterns: [ + 'node_modules/*', + 'public/mockServiceWorker.js', + 'generators/*', + ], + extends: ['eslint:recommended', 'next/core-web-vitals'], + plugins: ['check-file'], + overrides: [ + { + files: ['**/*.ts', '**/*.tsx'], + parser: '@typescript-eslint/parser', + settings: { + react: { version: 'detect' }, + 'import/resolver': { + typescript: {}, + }, + }, + env: { + browser: true, + node: true, + es6: true, + }, + extends: [ + 'eslint:recommended', + 'plugin:import/errors', + 'plugin:import/warnings', + 'plugin:import/typescript', + 'plugin:@typescript-eslint/recommended', + 'plugin:react/recommended', + 'plugin:react-hooks/recommended', + 'plugin:jsx-a11y/recommended', + 'plugin:prettier/recommended', + 'plugin:testing-library/react', + 'plugin:jest-dom/recommended', + 'plugin:tailwindcss/recommended', + 'plugin:vitest/legacy-recommended', + ], + rules: { + '@next/next/no-img-element': 'off', + 'import/no-restricted-paths': [ + 'error', + { + zones: [ + // disables cross-feature imports: + // eg. src/features/discussions should not import from src/features/comments, etc. + { + target: './src/features/auth', + from: './src/features', + except: ['./auth'], + }, + { + target: './src/features/comments', + from: './src/features', + except: ['./comments'], + }, + { + target: './src/features/discussions', + from: './src/features', + except: ['./discussions'], + }, + { + target: './src/features/teams', + from: './src/features', + except: ['./teams'], + }, + { + target: './src/features/users', + from: './src/features', + except: ['./users'], + }, + // enforce unidirectional codebase: + + // e.g. src/app can import from src/features but not the other way around + { + target: './src/features', + from: './src/app', + }, + + // e.g src/features and src/app can import from these shared modules but not the other way around + { + target: [ + './src/components', + './src/hooks', + './src/lib', + './src/types', + './src/utils', + ], + from: ['./src/features', './src/app'], + }, + ], + }, + ], + 'import/no-cycle': 'error', + 'linebreak-style': ['error', 'unix'], + 'react/prop-types': 'off', + 'import/order': [ + 'error', + { + groups: [ + 'builtin', + 'external', + 'internal', + 'parent', + 'sibling', + 'index', + 'object', + ], + 'newlines-between': 'always', + alphabetize: { order: 'asc', caseInsensitive: true }, + }, + ], + 'import/default': 'off', + 'import/no-named-as-default-member': 'off', + 'import/no-named-as-default': 'off', + 'react/react-in-jsx-scope': 'off', + 'jsx-a11y/anchor-is-valid': 'off', + '@typescript-eslint/no-unused-vars': ['error'], + '@typescript-eslint/explicit-function-return-type': ['off'], + '@typescript-eslint/explicit-module-boundary-types': ['off'], + '@typescript-eslint/no-empty-function': ['off'], + '@typescript-eslint/no-explicit-any': ['off'], + 'prettier/prettier': ['error', {}, { usePrettierrc: true }], + 'check-file/filename-naming-convention': [ + 'error', + { + 'src/!(pages)/*.{ts,tsx}': 'KEBAB_CASE', + }, + { + ignoreMiddleExtensions: true, + }, + ], + }, + }, + { + plugins: ['check-file'], + files: ['src/**/!(__tests__)/*'], + rules: { + 'check-file/folder-naming-convention': [ + 'error', + { + '**/*': 'KEBAB_CASE', + }, + ], + }, + }, + ], +}; diff --git a/apps/nextjs-app/.gitignore b/apps/nextjs-app/.gitignore new file mode 100644 index 00000000..dc32fea3 --- /dev/null +++ b/apps/nextjs-app/.gitignore @@ -0,0 +1,43 @@ +# See https://help.github.com/articles/ignoring-files/ for more about ignoring files. + +# dependencies +/node_modules +/.pnp +.pnp.js + +# testing +/coverage +/test-results/ +/playwright-report/ +/blob-report/ +/playwright/.cache/ +/e2e/.auth/ + +# storybook +migration-storybook.log +storybook.log +storybook-static + + +# production +/dist + +# misc +.DS_Store +.env +.env.local +.env.development.local +.env.test.local +.env.production.local + +npm-debug.log* +yarn-debug.log* +yarn-error.log* + + +# local +mocked-db.json + +/.next +/.vite +tsconfig.tsbuildinfo \ No newline at end of file diff --git a/apps/nextjs-app/.prettierignore b/apps/nextjs-app/.prettierignore new file mode 100644 index 00000000..5acb4c91 --- /dev/null +++ b/apps/nextjs-app/.prettierignore @@ -0,0 +1 @@ +*.hbs \ No newline at end of file diff --git a/apps/nextjs-app/.prettierrc b/apps/nextjs-app/.prettierrc new file mode 100644 index 00000000..e59f1ac5 --- /dev/null +++ b/apps/nextjs-app/.prettierrc @@ -0,0 +1,7 @@ +{ + "singleQuote": true, + "trailingComma": "all", + "printWidth": 80, + "tabWidth": 2, + "useTabs": false +} diff --git a/apps/nextjs-app/.storybook/main.ts b/apps/nextjs-app/.storybook/main.ts new file mode 100644 index 00000000..808ced22 --- /dev/null +++ b/apps/nextjs-app/.storybook/main.ts @@ -0,0 +1,20 @@ +module.exports = { + stories: ['../src/**/*.stories.mdx', '../src/**/*.stories.@(js|jsx|ts|tsx)'], + + addons: [ + '@storybook/addon-actions', + '@storybook/addon-links', + '@storybook/node-logger', + '@storybook/addon-essentials', + '@storybook/addon-interactions', + '@storybook/addon-docs', + '@storybook/addon-a11y', + ], + framework: '@storybook/nextjs', + docs: { + autodocs: 'tag', + }, + typescript: { + reactDocgen: 'react-docgen-typescript', + }, +}; diff --git a/apps/nextjs-app/.storybook/preview.tsx b/apps/nextjs-app/.storybook/preview.tsx new file mode 100644 index 00000000..9d181d43 --- /dev/null +++ b/apps/nextjs-app/.storybook/preview.tsx @@ -0,0 +1,8 @@ +import React from 'react'; +import '../src/styles/globals.css'; + +export const parameters = { + actions: { argTypesRegex: '^on[A-Z].*' }, +}; + +export const decorators = [(Story) => ]; diff --git a/apps/nextjs-app/.vscode/extensions.json b/apps/nextjs-app/.vscode/extensions.json new file mode 100644 index 00000000..1cd1faf7 --- /dev/null +++ b/apps/nextjs-app/.vscode/extensions.json @@ -0,0 +1,9 @@ +{ + "recommendations": [ + "dbaeumer.vscode-eslint", + "esbenp.prettier-vscode", + "dsznajder.es7-react-js-snippets", + "mariusalchimavicius.json-to-ts", + "bradlc.vscode-tailwindcss" + ] +} diff --git a/apps/nextjs-app/.vscode/settings.json b/apps/nextjs-app/.vscode/settings.json new file mode 100644 index 00000000..1947a0d0 --- /dev/null +++ b/apps/nextjs-app/.vscode/settings.json @@ -0,0 +1,6 @@ +{ + "editor.formatOnSave": true, + "editor.codeActionsOnSave": { + "source.fixAll.eslint": "explicit" + } +} diff --git a/apps/nextjs-app/README.md b/apps/nextjs-app/README.md new file mode 100644 index 00000000..b91ef588 --- /dev/null +++ b/apps/nextjs-app/README.md @@ -0,0 +1,32 @@ +# Next.js Pages Application + +## Get Started + +Prerequisites: + +- Node 20+ +- Yarn 1.22+ + +To set up the app execute the following commands. + +```bash +git clone https://github.com/alan2207/bulletproof-react.git +cd bulletproof-react +cd apps/nextjs-pages +cp .env.example .env +yarn install +``` + +#### `yarn run-mock-server` + +Make sure to start the mock server before running the app. +The mock server runs on [http://localhost:8080/api](http://localhost:8080/api). + +##### `yarn dev` + +Runs the app in the development mode.\ +Open [http://localhost:3000](http://localhost:3000) to view it in the browser. + +## Project Structure + +Since the `pages` folder isn't very flexible and doesn't allow file collocation, we are keeping the `app` folder which is our application layer where we compose all the features, and then we just re-export Next.js page specific files (the pages and `getServerSideProps`) from the `pages` folder so Next.js can pick them up and serve as pages. diff --git a/apps/nextjs-app/__mocks__/vitest-env.d.ts b/apps/nextjs-app/__mocks__/vitest-env.d.ts new file mode 100644 index 00000000..97ce4524 --- /dev/null +++ b/apps/nextjs-app/__mocks__/vitest-env.d.ts @@ -0,0 +1,2 @@ +/// +/// diff --git a/apps/nextjs-app/__mocks__/zustand.ts b/apps/nextjs-app/__mocks__/zustand.ts new file mode 100644 index 00000000..ef8fb9e8 --- /dev/null +++ b/apps/nextjs-app/__mocks__/zustand.ts @@ -0,0 +1,52 @@ +import { act } from '@testing-library/react'; +import { afterEach, vi } from 'vitest'; +import * as zustand from 'zustand'; + +const { create: actualCreate, createStore: actualCreateStore } = + await vi.importActual('zustand'); + +// a variable to hold reset functions for all stores declared in the app +export const storeResetFns = new Set<() => void>(); + +const createUncurried = (stateCreator: zustand.StateCreator) => { + const store = actualCreate(stateCreator); + const initialState = store.getInitialState(); + storeResetFns.add(() => { + store.setState(initialState, true); + }); + return store; +}; + +// when creating a store, we get its initial state, create a reset function and add it in the set +export const create = ((stateCreator: zustand.StateCreator) => { + // to support curried version of create + return typeof stateCreator === 'function' + ? createUncurried(stateCreator) + : createUncurried; +}) as typeof zustand.create; + +const createStoreUncurried = (stateCreator: zustand.StateCreator) => { + const store = actualCreateStore(stateCreator); + const initialState = store.getInitialState(); + storeResetFns.add(() => { + store.setState(initialState, true); + }); + return store; +}; + +// when creating a store, we get its initial state, create a reset function and add it in the set +export const createStore = ((stateCreator: zustand.StateCreator) => { + // to support curried version of createStore + return typeof stateCreator === 'function' + ? createStoreUncurried(stateCreator) + : createStoreUncurried; +}) as typeof zustand.createStore; + +// reset all stores after each test run +afterEach(() => { + act(() => { + storeResetFns.forEach((resetFn) => { + resetFn(); + }); + }); +}); diff --git a/apps/nextjs-app/e2e/.eslintrc.cjs b/apps/nextjs-app/e2e/.eslintrc.cjs new file mode 100644 index 00000000..30644b49 --- /dev/null +++ b/apps/nextjs-app/e2e/.eslintrc.cjs @@ -0,0 +1,5 @@ +module.exports = { + root: true, + parser: '@typescript-eslint/parser', + extends: 'plugin:playwright/recommended', +}; diff --git a/apps/nextjs-app/e2e/tests/auth.setup.ts b/apps/nextjs-app/e2e/tests/auth.setup.ts new file mode 100644 index 00000000..1117cc38 --- /dev/null +++ b/apps/nextjs-app/e2e/tests/auth.setup.ts @@ -0,0 +1,42 @@ +import { test as setup, expect } from '@playwright/test'; +import { createUser } from '../../src/testing/data-generators'; + +const authFile = 'e2e/.auth/user.json'; + +setup('authenticate', async ({ page }) => { + const user = createUser(); + + await page.goto('/'); + await page.getByRole('button', { name: 'Get started' }).click(); + await page.waitForURL('/auth/login'); + await page.getByRole('link', { name: 'Register' }).click(); + + // registration: + await page.getByLabel('First Name').click(); + await page.getByLabel('First Name').fill(user.firstName); + await page.getByLabel('Last Name').click(); + await page.getByLabel('Last Name').fill(user.lastName); + await page.getByLabel('Email Address').click(); + await page.getByLabel('Email Address').fill(user.email); + await page.getByLabel('Password').click(); + await page.getByLabel('Password').fill(user.password); + await page.getByLabel('Team Name').click(); + await page.getByLabel('Team Name').fill(user.teamName); + await page.getByRole('button', { name: 'Register' }).click(); + await page.waitForURL('/app'); + + // log out: + await page.getByRole('button', { name: 'Open user menu' }).click(); + await page.getByRole('menuitem', { name: 'Sign Out' }).click(); + await page.waitForURL('/auth/login?redirectTo=%2Fapp'); + + // log in: + await page.getByLabel('Email Address').click(); + await page.getByLabel('Email Address').fill(user.email); + await page.getByLabel('Password').click(); + await page.getByLabel('Password').fill(user.password); + await page.getByRole('button', { name: 'Log in' }).click(); + await page.waitForURL('/app'); + + await page.context().storageState({ path: authFile }); +}); diff --git a/apps/nextjs-app/e2e/tests/profile.spec.ts b/apps/nextjs-app/e2e/tests/profile.spec.ts new file mode 100644 index 00000000..21d48c33 --- /dev/null +++ b/apps/nextjs-app/e2e/tests/profile.spec.ts @@ -0,0 +1,17 @@ +import { test, expect } from '@playwright/test'; + +test('profile', async ({ page }) => { + // update user: + await page.goto('/app'); + await page.getByRole('button', { name: 'Open user menu' }).click(); + await page.getByRole('menuitem', { name: 'Your Profile' }).click(); + await page.getByRole('button', { name: 'Update Profile' }).click(); + await page.getByLabel('Bio').click(); + await page.getByLabel('Bio').fill('My bio'); + await page.getByRole('button', { name: 'Submit' }).click(); + await page + .getByLabel('Profile Updated') + .getByRole('button', { name: 'Close' }) + .click(); + await expect(page.getByText('My bio')).toBeVisible(); +}); diff --git a/apps/nextjs-app/e2e/tests/smoke.spec.ts b/apps/nextjs-app/e2e/tests/smoke.spec.ts new file mode 100644 index 00000000..9398601e --- /dev/null +++ b/apps/nextjs-app/e2e/tests/smoke.spec.ts @@ -0,0 +1,95 @@ +import { test, expect } from '@playwright/test'; + +import { + createDiscussion, + createComment, +} from '../../src/testing/data-generators'; +test('smoke', async ({ page }) => { + const discussion = createDiscussion(); + const comment = createComment(); + + await page.goto('/'); + await page.getByRole('button', { name: 'Get started' }).click(); + await page.waitForURL('/app'); + + // create discussion: + await page.getByRole('link', { name: 'Discussions' }).click(); + await page.waitForURL('/app/discussions'); + + await page.getByRole('button', { name: 'Create Discussion' }).click(); + await page.getByLabel('Title').click(); + await page.getByLabel('Title').fill(discussion.title); + await page.getByLabel('Body').click(); + await page.getByLabel('Body').fill(discussion.body); + await page.getByRole('button', { name: 'Submit' }).click(); + await page + .getByLabel('Discussion Created') + .getByRole('button', { name: 'Close' }) + .click(); + + // visit discussion page: + await page.getByRole('link', { name: 'View' }).click(); + + await expect( + page.getByRole('heading', { name: discussion.title }), + ).toBeVisible(); + await expect(page.getByText(discussion.body)).toBeVisible(); + + // update discussion: + await page.getByRole('button', { name: 'Update Discussion' }).click(); + await page.getByLabel('Title').click(); + await page.getByLabel('Title').fill(`${discussion.title} - updated`); + await page.getByLabel('Body').click(); + await page.getByLabel('Body').fill(`${discussion.body} - updated`); + await page.getByRole('button', { name: 'Submit' }).click(); + await page + .getByLabel('Discussion Updated') + .getByRole('button', { name: 'Close' }) + .click(); + + await expect( + page.getByRole('heading', { name: `${discussion.title} - updated` }), + ).toBeVisible(); + await expect(page.getByText(`${discussion.body} - updated`)).toBeVisible(); + + // create comment: + await page.getByRole('button', { name: 'Create Comment' }).click(); + await page.getByLabel('Body').click(); + await page.getByLabel('Body').fill(comment.body); + await page.getByRole('button', { name: 'Submit' }).click(); + await expect(page.getByText(comment.body)).toBeVisible(); + await page + .getByLabel('Comment Created') + .getByRole('button', { name: 'Close' }) + .click(); + + // delete comment: + await page.getByRole('button', { name: 'Delete Comment' }).click(); + await expect( + page.getByText('Are you sure you want to delete this comment?'), + ).toBeVisible(); + await page.getByRole('button', { name: 'Delete Comment' }).click(); + await page + .getByLabel('Comment Deleted') + .getByRole('button', { name: 'Close' }) + .click(); + await expect( + page.getByRole('heading', { name: 'No Comments Found' }), + ).toBeVisible(); + await expect(page.getByText(comment.body)).toBeHidden(); + + // go back to discussions: + await page.getByRole('link', { name: 'Discussions' }).click(); + await page.waitForURL('/app/discussions'); + + // delete discussion: + await page.getByRole('button', { name: 'Delete Discussion' }).click(); + await page.getByRole('button', { name: 'Delete Discussion' }).click(); + await page + .getByLabel('Discussion Deleted') + .getByRole('button', { name: 'Close' }) + .click(); + await expect( + page.getByRole('heading', { name: 'No Entries Found' }), + ).toBeVisible(); +}); diff --git a/apps/nextjs-app/generators/component/component.stories.tsx.hbs b/apps/nextjs-app/generators/component/component.stories.tsx.hbs new file mode 100644 index 00000000..c3198d90 --- /dev/null +++ b/apps/nextjs-app/generators/component/component.stories.tsx.hbs @@ -0,0 +1,15 @@ +import { Meta, StoryObj } from '@storybook/react'; + +import { {{ properCase name }} } from './{{ kebabCase name }}'; + +const meta: Meta = { + component: {{ properCase name }}, +}; + +export default meta; + +type Story = StoryObj; + +export const Default: Story = { + args: {} +}; diff --git a/apps/nextjs-app/generators/component/component.tsx.hbs b/apps/nextjs-app/generators/component/component.tsx.hbs new file mode 100644 index 00000000..23971155 --- /dev/null +++ b/apps/nextjs-app/generators/component/component.tsx.hbs @@ -0,0 +1,11 @@ +import * as React from "react"; + +export type {{properCase name}}Props = {}; + +export const {{properCase name}} = (props: {{properCase name}}Props) => { + return ( +
+ {{properCase name}} +
+ ); +}; \ No newline at end of file diff --git a/apps/nextjs-app/generators/component/index.cjs b/apps/nextjs-app/generators/component/index.cjs new file mode 100644 index 00000000..0aa8d068 --- /dev/null +++ b/apps/nextjs-app/generators/component/index.cjs @@ -0,0 +1,56 @@ +const path = require('path'); +const fs = require('fs'); + +const featuresDir = path.join(process.cwd(), 'src/features'); +const features = fs.readdirSync(featuresDir); + +/** + * + * @type {import('plop').PlopGenerator} + */ +module.exports = { + description: 'Component Generator', + prompts: [ + { + type: 'input', + name: 'name', + message: 'component name', + }, + { + type: 'list', + name: 'feature', + message: 'Which feature does this component belong to?', + choices: ['components', ...features], + when: () => features.length > 0, + }, + { + type: 'input', + name: 'folder', + message: 'folder in components', + when: ({ feature }) => !feature || feature === 'components', + }, + ], + actions: (answers) => { + const componentGeneratePath = + !answers.feature || answers.feature === 'components' + ? 'src/components/{{folder}}' + : 'src/features/{{feature}}/components'; + return [ + { + type: 'add', + path: componentGeneratePath + '/{{kebabCase name}}/index.ts', + templateFile: 'generators/component/index.ts.hbs', + }, + { + type: 'add', + path: componentGeneratePath + '/{{kebabCase name}}/{{kebabCase name}}.tsx', + templateFile: 'generators/component/component.tsx.hbs', + }, + { + type: 'add', + path: componentGeneratePath + '/{{kebabCase name}}/{{kebabCase name}}.stories.tsx', + templateFile: 'generators/component/component.stories.tsx.hbs', + }, + ]; + }, +}; diff --git a/apps/nextjs-app/generators/component/index.ts.hbs b/apps/nextjs-app/generators/component/index.ts.hbs new file mode 100644 index 00000000..2991d2e6 --- /dev/null +++ b/apps/nextjs-app/generators/component/index.ts.hbs @@ -0,0 +1 @@ +export * from './{{ kebabCase name }}'; diff --git a/apps/nextjs-app/index.html b/apps/nextjs-app/index.html new file mode 100644 index 00000000..7c865abb --- /dev/null +++ b/apps/nextjs-app/index.html @@ -0,0 +1,18 @@ + + + + + + + + + + + Bulletproof React + + + +
+ + + diff --git a/apps/nextjs-app/lint-staged.config.mjs b/apps/nextjs-app/lint-staged.config.mjs new file mode 100644 index 00000000..08cf0dcc --- /dev/null +++ b/apps/nextjs-app/lint-staged.config.mjs @@ -0,0 +1,14 @@ +import path from 'path'; + +const buildEslintCommand = (filenames) => { + return `next lint --fix --file ${filenames + .filter((f) => f.includes('/src/')) + .map((f) => path.relative(process.cwd(), f)) + .join(' --file ')}`; +}; + +const config = { + '*.{ts,tsx}': [buildEslintCommand, "bash -c 'yarn check-types'"], +}; + +export default config; diff --git a/apps/nextjs-app/mock-server.ts b/apps/nextjs-app/mock-server.ts new file mode 100644 index 00000000..8e217267 --- /dev/null +++ b/apps/nextjs-app/mock-server.ts @@ -0,0 +1,29 @@ +import { createMiddleware } from '@mswjs/http-middleware'; +import cors from 'cors'; +import express from 'express'; +import logger from 'pino-http'; + +import { initializeDb } from './src/testing/mocks/db'; +import { handlers } from './src/testing/mocks/handlers'; + +const app = express(); + +app.use( + cors({ + origin: process.env.NEXT_PUBLIC_URL, + credentials: true, + }), +); + +app.use(express.json()); +app.use(logger({ level: 'silent' })); +app.use(createMiddleware(...handlers)); + +initializeDb().then(() => { + console.log('Mock DB initialized'); + app.listen(process.env.NEXT_PUBLIC_MOCK_API_PORT, () => { + console.log( + `Mock API server started at http://localhost:${process.env.NEXT_PUBLIC_MOCK_API_PORT}`, + ); + }); +}); diff --git a/apps/nextjs-app/next-env.d.ts b/apps/nextjs-app/next-env.d.ts new file mode 100644 index 00000000..fd36f949 --- /dev/null +++ b/apps/nextjs-app/next-env.d.ts @@ -0,0 +1,6 @@ +/// +/// +/// + +// NOTE: This file should not be edited +// see https://nextjs.org/docs/basic-features/typescript for more information. diff --git a/apps/nextjs-app/next.config.mjs b/apps/nextjs-app/next.config.mjs new file mode 100644 index 00000000..d5456a15 --- /dev/null +++ b/apps/nextjs-app/next.config.mjs @@ -0,0 +1,6 @@ +/** @type {import('next').NextConfig} */ +const nextConfig = { + reactStrictMode: true, +}; + +export default nextConfig; diff --git a/apps/nextjs-app/package.json b/apps/nextjs-app/package.json new file mode 100644 index 00000000..f0e7f8c7 --- /dev/null +++ b/apps/nextjs-app/package.json @@ -0,0 +1,119 @@ +{ + "name": "bulletproof-react-nextjs-pages", + "version": "1.0.0", + "private": true, + "type": "module", + "scripts": { + "dev": "next dev", + "build": "next build", + "start": "next start", + "lint": "next lint", + "test": "vitest", + "test-e2e": "pm2 start \"yarn run-mock-server\" --name server && yarn playwright test", + "prepare": "husky", + "check-types": "tsc --project tsconfig.json --pretty --noEmit", + "generate": "plop", + "storybook": "storybook dev -p 6006", + "build-storybook": "storybook build", + "run-mock-server": "tsx ./mock-server.ts" + }, + "dependencies": { + "@hookform/resolvers": "^3.3.4", + "@next/env": "^14.2.5", + "@ngneat/falso": "^7.2.0", + "@radix-ui/react-dialog": "^1.0.5", + "@radix-ui/react-dropdown-menu": "^2.0.6", + "@radix-ui/react-icons": "^1.3.0", + "@radix-ui/react-label": "^2.0.2", + "@radix-ui/react-slot": "^1.0.2", + "@radix-ui/react-switch": "^1.0.3", + "@tanstack/react-query": "^5.32.0", + "@tanstack/react-query-devtools": "^5.32.0", + "axios": "^1.6.8", + "class-variance-authority": "^0.7.0", + "clsx": "^2.1.1", + "dayjs": "^1.11.11", + "eslint-plugin-check-file": "^2.8.0", + "isomorphic-dompurify": "^2.14.0", + "lucide-react": "^0.378.0", + "marked": "^12.0.2", + "nanoid": "^5.0.7", + "next": "^14.2.5", + "react": "^18.3.1", + "react-dom": "^18.3.1", + "react-error-boundary": "^4.0.13", + "react-hook-form": "^7.51.3", + "react-query-auth": "^2.3.0", + "tailwind-merge": "^2.3.0", + "tailwindcss-animate": "^1.0.7", + "zod": "^3.23.4", + "zustand": "^4.5.2" + }, + "devDependencies": { + "@eslint/eslintrc": "^3.0.2", + "@mswjs/data": "^0.16.1", + "@mswjs/http-middleware": "^0.10.1", + "@playwright/test": "^1.43.1", + "@storybook/addon-a11y": "^8.0.10", + "@storybook/addon-actions": "^8.0.9", + "@storybook/addon-essentials": "^8.0.9", + "@storybook/addon-links": "^8.0.9", + "@storybook/nextjs": "^8.2.9", + "@storybook/node-logger": "^8.0.9", + "@storybook/react": "^8.0.9", + "@tailwindcss/typography": "^0.5.13", + "@testing-library/jest-dom": "^6.4.2", + "@testing-library/react": "^15.0.5", + "@testing-library/user-event": "^14.5.2", + "@types/cors": "^2.8.17", + "@types/dompurify": "^3.0.5", + "@types/js-cookie": "^3.0.6", + "@types/marked": "^6.0.0", + "@types/node": "^20.12.7", + "@types/react": "^18.3.1", + "@types/react-dom": "^18.3.0", + "@typescript-eslint/eslint-plugin": "^7.8.0", + "@typescript-eslint/parser": "^7.8.0", + "@vitejs/plugin-react": "^4.2.1", + "autoprefixer": "^10.4.19", + "cors": "^2.8.5", + "dotenv": "^16.4.5", + "eslint": "8", + "eslint-config-next": "^14.2.5", + "eslint-config-prettier": "^9.1.0", + "eslint-import-resolver-typescript": "^3.6.1", + "eslint-plugin-import": "^2.29.1", + "eslint-plugin-jest-dom": "^5.4.0", + "eslint-plugin-jsx-a11y": "^6.8.0", + "eslint-plugin-playwright": "^1.6.0", + "eslint-plugin-prettier": "^5.1.3", + "eslint-plugin-react": "^7.34.1", + "eslint-plugin-react-hooks": "^4.6.2", + "eslint-plugin-tailwindcss": "^3.15.1", + "eslint-plugin-testing-library": "^6.2.2", + "eslint-plugin-vitest": "^0.5.4", + "express": "^4.19.2", + "husky": "^9.0.11", + "jest-environment-jsdom": "^29.7.0", + "js-cookie": "^3.0.5", + "jsdom": "^24.0.0", + "lint-staged": "^15.2.2", + "msw": "^2.2.14", + "next-router-mock": "^0.9.13", + "pino-http": "^10.1.0", + "pino-pretty": "^11.1.0", + "plop": "^4.0.1", + "pm2": "^5.4.0", + "postcss": "^8.4.38", + "prettier": "^3.2.5", + "storybook": "^8.0.9", + "tailwindcss": "^3.4.3", + "tsx": "^4.17.0", + "typescript": "^5.4.5", + "vite-tsconfig-paths": "^4.3.2", + "vitest": "^1.5.2" + }, + "msw": { + "workerDirectory": "public" + } +} diff --git a/apps/nextjs-app/playwright.config.ts b/apps/nextjs-app/playwright.config.ts new file mode 100644 index 00000000..fa902a63 --- /dev/null +++ b/apps/nextjs-app/playwright.config.ts @@ -0,0 +1,56 @@ +import { defineConfig, devices } from '@playwright/test'; + +const PORT = 3000; + +/** + * Read environment variables from file. + * https://github.com/motdotla/dotenv + */ +// require('dotenv').config(); + +/** + * See https://playwright.dev/docs/test-configuration. + */ +export default defineConfig({ + testDir: './e2e', + /* Run tests in files in parallel */ + fullyParallel: true, + /* Fail the build on CI if you accidentally left test.only in the source code. */ + forbidOnly: !!process.env.CI, + /* Retry on CI only */ + retries: process.env.CI ? 2 : 0, + /* Opt out of parallel tests on CI. */ + workers: process.env.CI ? 1 : undefined, + /* Reporter to use. See https://playwright.dev/docs/test-reporters */ + reporter: 'html', + /* Shared settings for all the projects below. See https://playwright.dev/docs/api/class-testoptions. */ + use: { + /* Base URL to use in actions like `await page.goto('/')`. */ + // baseURL: 'http://127.0.0.1:3000', + + /* Collect trace when retrying the failed test. See https://playwright.dev/docs/trace-viewer */ + trace: 'on-first-retry', + }, + + /* Configure projects for major browsers */ + projects: [ + { name: 'setup', testMatch: /.*\.setup\.ts/ }, + { + name: 'chromium', + testMatch: /.*\.spec\.ts/, + use: { + ...devices['Desktop Chrome'], + storageState: 'e2e/.auth/user.json', + }, + dependencies: ['setup'], + }, + ], + + /* Run your local dev server before starting the tests */ + webServer: { + command: `yarn dev --port ${PORT}`, + timeout: 10 * 1000, + port: PORT, + reuseExistingServer: !process.env.CI, + }, +}); diff --git a/apps/nextjs-app/plopfile.cjs b/apps/nextjs-app/plopfile.cjs new file mode 100644 index 00000000..8ef24186 --- /dev/null +++ b/apps/nextjs-app/plopfile.cjs @@ -0,0 +1,9 @@ +const componentGenerator = require('./generators/component/index'); + +/** + * + * @param {import('plop').NodePlopAPI} plop + */ +module.exports = function (plop) { + plop.setGenerator('component', componentGenerator); +}; diff --git a/apps/nextjs-app/postcss.config.cjs b/apps/nextjs-app/postcss.config.cjs new file mode 100644 index 00000000..12a703d9 --- /dev/null +++ b/apps/nextjs-app/postcss.config.cjs @@ -0,0 +1,6 @@ +module.exports = { + plugins: { + tailwindcss: {}, + autoprefixer: {}, + }, +}; diff --git a/apps/nextjs-app/public/_redirects b/apps/nextjs-app/public/_redirects new file mode 100644 index 00000000..f8243379 --- /dev/null +++ b/apps/nextjs-app/public/_redirects @@ -0,0 +1 @@ +/* /index.html 200 \ No newline at end of file diff --git a/apps/nextjs-app/public/favicon.ico b/apps/nextjs-app/public/favicon.ico new file mode 100644 index 00000000..a11777cc Binary files /dev/null and b/apps/nextjs-app/public/favicon.ico differ diff --git a/apps/nextjs-app/public/logo.svg b/apps/nextjs-app/public/logo.svg new file mode 100644 index 00000000..9dfc1c05 --- /dev/null +++ b/apps/nextjs-app/public/logo.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/nextjs-app/public/logo192.png b/apps/nextjs-app/public/logo192.png new file mode 100644 index 00000000..fc44b0a3 Binary files /dev/null and b/apps/nextjs-app/public/logo192.png differ diff --git a/apps/nextjs-app/public/logo512.png b/apps/nextjs-app/public/logo512.png new file mode 100644 index 00000000..a4e47a65 Binary files /dev/null and b/apps/nextjs-app/public/logo512.png differ diff --git a/apps/nextjs-app/public/mockServiceWorker.js b/apps/nextjs-app/public/mockServiceWorker.js new file mode 100644 index 00000000..15751fa1 --- /dev/null +++ b/apps/nextjs-app/public/mockServiceWorker.js @@ -0,0 +1,284 @@ +/* eslint-disable */ +/* tslint:disable */ + +/** + * Mock Service Worker. + * @see https://github.com/mswjs/msw + * - Please do NOT modify this file. + * - Please do NOT serve this file on production. + */ + +const PACKAGE_VERSION = '2.3.5' +const INTEGRITY_CHECKSUM = '26357c79639bfa20d64c0efca2a87423' +const IS_MOCKED_RESPONSE = Symbol('isMockedResponse') +const activeClientIds = new Set() + +self.addEventListener('install', function () { + self.skipWaiting() +}) + +self.addEventListener('activate', function (event) { + event.waitUntil(self.clients.claim()) +}) + +self.addEventListener('message', async function (event) { + const clientId = event.source.id + + if (!clientId || !self.clients) { + return + } + + const client = await self.clients.get(clientId) + + if (!client) { + return + } + + const allClients = await self.clients.matchAll({ + type: 'window', + }) + + switch (event.data) { + case 'KEEPALIVE_REQUEST': { + sendToClient(client, { + type: 'KEEPALIVE_RESPONSE', + }) + break + } + + case 'INTEGRITY_CHECK_REQUEST': { + sendToClient(client, { + type: 'INTEGRITY_CHECK_RESPONSE', + payload: { + packageVersion: PACKAGE_VERSION, + checksum: INTEGRITY_CHECKSUM, + }, + }) + break + } + + case 'MOCK_ACTIVATE': { + activeClientIds.add(clientId) + + sendToClient(client, { + type: 'MOCKING_ENABLED', + payload: true, + }) + break + } + + case 'MOCK_DEACTIVATE': { + activeClientIds.delete(clientId) + break + } + + case 'CLIENT_CLOSED': { + activeClientIds.delete(clientId) + + const remainingClients = allClients.filter((client) => { + return client.id !== clientId + }) + + // Unregister itself when there are no more clients + if (remainingClients.length === 0) { + self.registration.unregister() + } + + break + } + } +}) + +self.addEventListener('fetch', function (event) { + const { request } = event + + // Bypass navigation requests. + if (request.mode === 'navigate') { + return + } + + // Opening the DevTools triggers the "only-if-cached" request + // that cannot be handled by the worker. Bypass such requests. + if (request.cache === 'only-if-cached' && request.mode !== 'same-origin') { + return + } + + // Bypass all requests when there are no active clients. + // Prevents the self-unregistered worked from handling requests + // after it's been deleted (still remains active until the next reload). + if (activeClientIds.size === 0) { + return + } + + // Generate unique request ID. + const requestId = crypto.randomUUID() + event.respondWith(handleRequest(event, requestId)) +}) + +async function handleRequest(event, requestId) { + const client = await resolveMainClient(event) + const response = await getResponse(event, client, requestId) + + // Send back the response clone for the "response:*" life-cycle events. + // Ensure MSW is active and ready to handle the message, otherwise + // this message will pend indefinitely. + if (client && activeClientIds.has(client.id)) { + ;(async function () { + const responseClone = response.clone() + + sendToClient( + client, + { + type: 'RESPONSE', + payload: { + requestId, + isMockedResponse: IS_MOCKED_RESPONSE in response, + type: responseClone.type, + status: responseClone.status, + statusText: responseClone.statusText, + body: responseClone.body, + headers: Object.fromEntries(responseClone.headers.entries()), + }, + }, + [responseClone.body], + ) + })() + } + + return response +} + +// Resolve the main client for the given event. +// Client that issues a request doesn't necessarily equal the client +// that registered the worker. It's with the latter the worker should +// communicate with during the response resolving phase. +async function resolveMainClient(event) { + const client = await self.clients.get(event.clientId) + + if (client?.frameType === 'top-level') { + return client + } + + const allClients = await self.clients.matchAll({ + type: 'window', + }) + + return allClients + .filter((client) => { + // Get only those clients that are currently visible. + return client.visibilityState === 'visible' + }) + .find((client) => { + // Find the client ID that's recorded in the + // set of clients that have registered the worker. + return activeClientIds.has(client.id) + }) +} + +async function getResponse(event, client, requestId) { + const { request } = event + + // Clone the request because it might've been already used + // (i.e. its body has been read and sent to the client). + const requestClone = request.clone() + + function passthrough() { + const headers = Object.fromEntries(requestClone.headers.entries()) + + // Remove internal MSW request header so the passthrough request + // complies with any potential CORS preflight checks on the server. + // Some servers forbid unknown request headers. + delete headers['x-msw-intention'] + + return fetch(requestClone, { headers }) + } + + // Bypass mocking when the client is not active. + if (!client) { + return passthrough() + } + + // Bypass initial page load requests (i.e. static assets). + // The absence of the immediate/parent client in the map of the active clients + // means that MSW hasn't dispatched the "MOCK_ACTIVATE" event yet + // and is not ready to handle requests. + if (!activeClientIds.has(client.id)) { + return passthrough() + } + + // Notify the client that a request has been intercepted. + const requestBuffer = await request.arrayBuffer() + const clientMessage = await sendToClient( + client, + { + type: 'REQUEST', + payload: { + id: requestId, + url: request.url, + mode: request.mode, + method: request.method, + headers: Object.fromEntries(request.headers.entries()), + cache: request.cache, + credentials: request.credentials, + destination: request.destination, + integrity: request.integrity, + redirect: request.redirect, + referrer: request.referrer, + referrerPolicy: request.referrerPolicy, + body: requestBuffer, + keepalive: request.keepalive, + }, + }, + [requestBuffer], + ) + + switch (clientMessage.type) { + case 'MOCK_RESPONSE': { + return respondWithMock(clientMessage.data) + } + + case 'PASSTHROUGH': { + return passthrough() + } + } + + return passthrough() +} + +function sendToClient(client, message, transferrables = []) { + return new Promise((resolve, reject) => { + const channel = new MessageChannel() + + channel.port1.onmessage = (event) => { + if (event.data && event.data.error) { + return reject(event.data.error) + } + + resolve(event.data) + } + + client.postMessage( + message, + [channel.port2].concat(transferrables.filter(Boolean)), + ) + }) +} + +async function respondWithMock(response) { + // Setting response status code to 0 is a no-op. + // However, when responding with a "Response.error()", the produced Response + // instance will have status code set to 0. Since it's not possible to create + // a Response instance with status code 0, handle that use-case separately. + if (response.status === 0) { + return Response.error() + } + + const mockedResponse = new Response(response.body, response) + + Reflect.defineProperty(mockedResponse, IS_MOCKED_RESPONSE, { + value: true, + enumerable: true, + }) + + return mockedResponse +} diff --git a/apps/nextjs-app/public/robots.txt b/apps/nextjs-app/public/robots.txt new file mode 100644 index 00000000..e9e57dc4 --- /dev/null +++ b/apps/nextjs-app/public/robots.txt @@ -0,0 +1,3 @@ +# https://www.robotstxt.org/robotstxt.html +User-agent: * +Disallow: diff --git a/apps/nextjs-app/src/app/pages/app/dashboard.tsx b/apps/nextjs-app/src/app/pages/app/dashboard.tsx new file mode 100644 index 00000000..9035fa5d --- /dev/null +++ b/apps/nextjs-app/src/app/pages/app/dashboard.tsx @@ -0,0 +1,45 @@ +import { ReactElement } from 'react'; + +import { ContentLayout, DashboardLayout } from '@/components/layouts'; +import { useUser } from '@/lib/auth'; +import { ROLES } from '@/lib/authorization'; + +export const DashboardPage = () => { + const user = useUser(); + if (!user.data) return null; + + return ( + <> +

+ Welcome {`${user.data?.firstName} ${user.data?.lastName}`} +

+

+ Your role is : {user.data?.role} +

+

In this application you can:

+ {user.data?.role === ROLES.USER && ( +
    +
  • Create comments in discussions
  • +
  • Delete own comments
  • +
+ )} + {user.data?.role === ROLES.ADMIN && ( +
    +
  • Create discussions
  • +
  • Edit discussions
  • +
  • Delete discussions
  • +
  • Comment on discussions
  • +
  • Delete all comments
  • +
+ )} + + ); +}; + +DashboardPage.getLayout = (page: ReactElement) => { + return ( + + {page} + + ); +}; diff --git a/apps/nextjs-app/src/app/pages/app/discussions/__tests__/discussion.test.tsx b/apps/nextjs-app/src/app/pages/app/discussions/__tests__/discussion.test.tsx new file mode 100644 index 00000000..7afa3c00 --- /dev/null +++ b/apps/nextjs-app/src/app/pages/app/discussions/__tests__/discussion.test.tsx @@ -0,0 +1,152 @@ +import mockRouter from 'next-router-mock'; + +import { + renderApp, + screen, + userEvent, + waitFor, + createDiscussion, + createUser, + within, + waitForLoadingToFinish, +} from '@/testing/test-utils'; + +import { DiscussionPage } from '../discussion'; + +const renderDiscussion = async () => { + const fakeUser = await createUser(); + const fakeDiscussion = await createDiscussion({ teamId: fakeUser.teamId }); + + mockRouter.query = { discussionId: fakeDiscussion.id }; + + const utils = await renderApp(, { + user: fakeUser, + path: `/app/discussions/:discussionId`, + url: `/app/discussions/${fakeDiscussion.id}`, + }); + + await waitForLoadingToFinish(); + + await screen.findByText(fakeDiscussion.title); + + return { + ...utils, + fakeUser, + fakeDiscussion, + }; +}; + +test('should render discussion', async () => { + const { fakeDiscussion } = await renderDiscussion(); + expect(screen.getByText(fakeDiscussion.body)).toBeInTheDocument(); +}); + +test('should update discussion', async () => { + const { fakeDiscussion } = await renderDiscussion(); + + const titleUpdate = '-Updated'; + const bodyUpdate = '-Updated'; + + await userEvent.click( + screen.getByRole('button', { name: /update discussion/i }), + ); + + const drawer = await screen.findByRole('dialog', { + name: /update discussion/i, + }); + + const titleField = within(drawer).getByText(/title/i); + const bodyField = within(drawer).getByText(/body/i); + + const newTitle = `${fakeDiscussion.title}${titleUpdate}`; + const newBody = `${fakeDiscussion.body}${bodyUpdate}`; + + // replacing the title with the new title + await userEvent.type(titleField, newTitle); + + // appending updated to the body + await userEvent.type(bodyField, bodyUpdate); + + const submitButton = within(drawer).getByRole('button', { + name: /submit/i, + }); + + await userEvent.click(submitButton); + + await waitFor(() => expect(drawer).not.toBeInTheDocument()); + + expect( + await screen.findByRole('heading', { name: newTitle }), + ).toBeInTheDocument(); + expect(await screen.findByText(newBody)).toBeInTheDocument(); +}); + +test( + 'should create and delete a comment on the discussion', + async () => { + await renderDiscussion(); + + const comment = 'Hello World'; + + await userEvent.click( + screen.getByRole('button', { name: /create comment/i }), + ); + + const drawer = await screen.findByRole('dialog', { + name: /create comment/i, + }); + + const bodyField = await within(drawer).findByText(/body/i); + + await userEvent.type(bodyField, comment); + + const submitButton = await within(drawer).findByRole('button', { + name: /submit/i, + }); + + await userEvent.click(submitButton); + + await waitFor(() => expect(drawer).not.toBeInTheDocument()); + + await screen.findByText(comment); + + const commentsList = await screen.findByRole('list', { + name: 'comments', + }); + + const commentElements = + await within(commentsList).findAllByRole('listitem'); + + const commentElement = commentElements[0]; + + expect(commentElement).toBeInTheDocument(); + + const deleteCommentButton = within(commentElement).getByRole('button', { + name: /delete comment/i, + // exact: false, + }); + + await userEvent.click(deleteCommentButton); + + const confirmationDialog = await screen.findByRole('dialog', { + name: /delete comment/i, + }); + + const confirmationDeleteButton = await within( + confirmationDialog, + ).findByRole('button', { + name: /delete/i, + }); + + await userEvent.click(confirmationDeleteButton); + + await screen.findByText(/comment deleted/i); + + await waitFor(() => { + expect(within(commentsList).queryByText(comment)).not.toBeInTheDocument(); + }); + }, + { + timeout: 20000, + }, +); diff --git a/apps/nextjs-app/src/app/pages/app/discussions/__tests__/discussions.test.tsx b/apps/nextjs-app/src/app/pages/app/discussions/__tests__/discussions.test.tsx new file mode 100644 index 00000000..de253e36 --- /dev/null +++ b/apps/nextjs-app/src/app/pages/app/discussions/__tests__/discussions.test.tsx @@ -0,0 +1,99 @@ +import type { Mock } from 'vitest'; + +import { createDiscussion } from '@/testing/data-generators'; +import { + renderApp, + screen, + userEvent, + waitFor, + waitForLoadingToFinish, + within, +} from '@/testing/test-utils'; +import { formatDate } from '@/utils/format'; + +import { DiscussionsPage } from '../discussions'; + +beforeAll(() => { + vi.spyOn(console, 'error').mockImplementation(() => {}); +}); + +afterAll(() => { + (console.error as Mock).mockRestore(); +}); + +test( + 'should create, render and delete discussions', + { timeout: 10000 }, + async () => { + await renderApp(); + + await waitForLoadingToFinish(); + + const newDiscussion = createDiscussion(); + + expect(await screen.findByText(/no entries/i)).toBeInTheDocument(); + + await userEvent.click( + screen.getByRole('button', { name: /create discussion/i }), + ); + + const drawer = await screen.findByRole('dialog', { + name: /create discussion/i, + }); + + const titleField = within(drawer).getByText(/title/i); + const bodyField = within(drawer).getByText(/body/i); + + await userEvent.type(titleField, newDiscussion.title); + await userEvent.type(bodyField, newDiscussion.body); + + const submitButton = within(drawer).getByRole('button', { + name: /submit/i, + }); + + await userEvent.click(submitButton); + + await waitFor(() => expect(drawer).not.toBeInTheDocument()); + + const row = await screen.findByRole( + 'row', + { + name: `${newDiscussion.title} ${formatDate(newDiscussion.createdAt)} View Delete Discussion`, + }, + { timeout: 5000 }, + ); + + expect( + within(row).getByRole('cell', { + name: newDiscussion.title, + }), + ).toBeInTheDocument(); + + await userEvent.click( + within(row).getByRole('button', { + name: /delete discussion/i, + }), + ); + + const confirmationDialog = await screen.findByRole('dialog', { + name: /delete discussion/i, + }); + + const confirmationDeleteButton = within(confirmationDialog).getByRole( + 'button', + { + name: /delete discussion/i, + }, + ); + + await userEvent.click(confirmationDeleteButton); + + await screen.findByText(/discussion deleted/i); + + expect( + within(row).queryByRole('cell', { + name: newDiscussion.title, + }), + ).not.toBeInTheDocument(); + }, +); diff --git a/apps/nextjs-app/src/app/pages/app/discussions/discussion.tsx b/apps/nextjs-app/src/app/pages/app/discussions/discussion.tsx new file mode 100644 index 00000000..fcf8d683 --- /dev/null +++ b/apps/nextjs-app/src/app/pages/app/discussions/discussion.tsx @@ -0,0 +1,92 @@ +import { + dehydrate, + HydrationBoundary, + QueryClient, +} from '@tanstack/react-query'; +import { GetServerSideProps, InferGetServerSidePropsType } from 'next'; +import { useRouter } from 'next/router'; +import { ReactElement } from 'react'; +import { ErrorBoundary } from 'react-error-boundary'; + +import { ContentLayout, DashboardLayout } from '@/components/layouts'; +import { Spinner } from '@/components/ui/spinner'; +import { getInfiniteCommentsQueryOptions } from '@/features/comments/api/get-comments'; +import { Comments } from '@/features/comments/components/comments'; +import { + useDiscussion, + getDiscussionQueryOptions, +} from '@/features/discussions/api/get-discussion'; +import { DiscussionView } from '@/features/discussions/components/discussion-view'; + +type DiscussionPageProps = { + dehydratedState?: unknown; +}; + +export const getServerSideProps = (async ({ query, req }) => { + const queryClient = new QueryClient(); + const discussionId = query.discussionId as string; + const cookie = req.headers.cookie; + + await queryClient.prefetchQuery( + getDiscussionQueryOptions(discussionId, cookie), + ); + await queryClient.prefetchInfiniteQuery( + getInfiniteCommentsQueryOptions(discussionId, cookie), + ); + + return { + props: { + dehydratedState: dehydrate(queryClient), + }, + }; +}) satisfies GetServerSideProps; + +export const DiscussionPage = () => { + const router = useRouter(); + const discussionId = router.query.discussionId as string; + + const discussionQuery = useDiscussion({ + discussionId, + }); + + if (discussionQuery.isLoading) { + return ( +
+ +
+ ); + } + + const discussion = discussionQuery.data?.data; + + if (!discussion) return null; + + return ( + + +
+ Failed to load comments. Try to refresh the page.
+ } + > + + + +
+ ); +}; + +DiscussionPage.getLayout = (page: ReactElement) => { + return {page}; +}; + +export const PublicDiscussionPage = ({ + dehydratedState, +}: InferGetServerSidePropsType) => { + return ( + + + + ); +}; diff --git a/apps/nextjs-app/src/app/pages/app/discussions/discussions.tsx b/apps/nextjs-app/src/app/pages/app/discussions/discussions.tsx new file mode 100644 index 00000000..afce34ae --- /dev/null +++ b/apps/nextjs-app/src/app/pages/app/discussions/discussions.tsx @@ -0,0 +1,37 @@ +import { useQueryClient } from '@tanstack/react-query'; +import { ReactElement } from 'react'; + +import { ContentLayout, DashboardLayout } from '@/components/layouts'; +import { getInfiniteCommentsQueryOptions } from '@/features/comments/api/get-comments'; +import { CreateDiscussion } from '@/features/discussions/components/create-discussion'; +import { DiscussionsList } from '@/features/discussions/components/discussions-list'; + +export const DiscussionsPage = () => { + const queryClient = useQueryClient(); + + return ( + <> +
+ +
+
+ { + // Prefetch the comments data when the user hovers over the link in the list + queryClient.prefetchInfiniteQuery( + getInfiniteCommentsQueryOptions(id), + ); + }} + /> +
+ + ); +}; + +DiscussionsPage.getLayout = (page: ReactElement) => { + return ( + + {page} + + ); +}; diff --git a/apps/nextjs-app/src/app/pages/app/profile.tsx b/apps/nextjs-app/src/app/pages/app/profile.tsx new file mode 100644 index 00000000..744a6927 --- /dev/null +++ b/apps/nextjs-app/src/app/pages/app/profile.tsx @@ -0,0 +1,57 @@ +import { ReactElement } from 'react'; + +import { ContentLayout, DashboardLayout } from '@/components/layouts'; +import { UpdateProfile } from '@/features/users/components/update-profile'; +import { useUser } from '@/lib/auth'; + +type EntryProps = { + label: string; + value: string; +}; +const Entry = ({ label, value }: EntryProps) => ( +
+
{label}
+
+ {value} +
+
+); + +export const ProfilePage = () => { + const user = useUser(); + + if (!user.data) return null; + + return ( +
+
+
+

+ User Information +

+ +
+

+ Personal details of the user. +

+
+
+
+ + + + + +
+
+
+ ); +}; + +ProfilePage.getLayout = (page: ReactElement) => { + return ( + + {page} + + ); +}; diff --git a/apps/nextjs-app/src/app/pages/app/users.tsx b/apps/nextjs-app/src/app/pages/app/users.tsx new file mode 100644 index 00000000..b0524e32 --- /dev/null +++ b/apps/nextjs-app/src/app/pages/app/users.tsx @@ -0,0 +1,26 @@ +import { ReactElement } from 'react'; + +import { ContentLayout, DashboardLayout } from '@/components/layouts'; +import { UsersList } from '@/features/users/components/users-list'; +import { Authorization, ROLES } from '@/lib/authorization'; + +export const UsersPage = () => { + return ( + + Only admin can view this.} + allowedRoles={[ROLES.ADMIN]} + > + + + + ); +}; + +UsersPage.getLayout = (page: ReactElement) => { + return ( + + {page} + + ); +}; diff --git a/apps/nextjs-app/src/app/pages/auth/login.tsx b/apps/nextjs-app/src/app/pages/auth/login.tsx new file mode 100644 index 00000000..69e9d238 --- /dev/null +++ b/apps/nextjs-app/src/app/pages/auth/login.tsx @@ -0,0 +1,22 @@ +import { useRouter } from 'next/router'; +import { ReactElement } from 'react'; + +import { AuthLayout } from '@/components/layouts/auth-layout'; +import { LoginForm } from '@/features/auth/components/login-form'; + +export const LoginPage = () => { + const router = useRouter(); + const { redirectTo } = router.query; + + return ( + + router.replace(`${redirectTo ? `${redirectTo}` : '/app'}`) + } + /> + ); +}; + +LoginPage.getLayout = (page: ReactElement) => { + return {page}; +}; diff --git a/apps/nextjs-app/src/app/pages/auth/register.tsx b/apps/nextjs-app/src/app/pages/auth/register.tsx new file mode 100644 index 00000000..d3858967 --- /dev/null +++ b/apps/nextjs-app/src/app/pages/auth/register.tsx @@ -0,0 +1,35 @@ +import { useRouter } from 'next/router'; +import { ReactElement, useState } from 'react'; + +import { AuthLayout } from '@/components/layouts/auth-layout'; +import { RegisterForm } from '@/features/auth/components/register-form'; +import { useTeams } from '@/features/teams/api/get-teams'; + +export const RegisterPage = () => { + const router = useRouter(); + + const { redirectTo } = router.query; + + const [chooseTeam, setChooseTeam] = useState(false); + + const teamsQuery = useTeams({ + queryConfig: { + enabled: chooseTeam, + }, + }); + + return ( + + router.replace(`${redirectTo ? `${redirectTo}` : '/app'}`) + } + chooseTeam={chooseTeam} + setChooseTeam={() => setChooseTeam(!chooseTeam)} + teams={teamsQuery.data?.data} + /> + ); +}; + +RegisterPage.getLayout = (page: ReactElement) => { + return {page}; +}; diff --git a/apps/nextjs-app/src/app/provider.tsx b/apps/nextjs-app/src/app/provider.tsx new file mode 100644 index 00000000..cb269351 --- /dev/null +++ b/apps/nextjs-app/src/app/provider.tsx @@ -0,0 +1,40 @@ +import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; +import { ReactQueryDevtools } from '@tanstack/react-query-devtools'; +import * as React from 'react'; +import { ErrorBoundary } from 'react-error-boundary'; + +import { MainErrorFallback } from '@/components/errors/main'; +import { Notifications } from '@/components/ui/notifications'; +import { Spinner } from '@/components/ui/spinner'; +import { queryConfig } from '@/lib/react-query'; + +type AppProviderProps = { + children: React.ReactNode; +}; + +export const AppProvider = ({ children }: AppProviderProps) => { + const [queryClient] = React.useState( + () => + new QueryClient({ + defaultOptions: queryConfig, + }), + ); + + return ( + + + + } + > + + + {process.env.DEV && } + + {children} + + + + ); +}; diff --git a/apps/nextjs-app/src/components/errors/main.tsx b/apps/nextjs-app/src/components/errors/main.tsx new file mode 100644 index 00000000..660a5ac5 --- /dev/null +++ b/apps/nextjs-app/src/components/errors/main.tsx @@ -0,0 +1,18 @@ +import { Button } from '../ui/button'; + +export const MainErrorFallback = () => { + return ( +
+

Ooops, something went wrong :(

+ +
+ ); +}; diff --git a/apps/nextjs-app/src/components/layouts/auth-layout.tsx b/apps/nextjs-app/src/components/layouts/auth-layout.tsx new file mode 100644 index 00000000..30369771 --- /dev/null +++ b/apps/nextjs-app/src/components/layouts/auth-layout.tsx @@ -0,0 +1,49 @@ +import { useRouter } from 'next/router'; +import * as React from 'react'; +import { useEffect } from 'react'; + +import { Head } from '@/components/seo'; +import { Link } from '@/components/ui/link'; +import { useUser } from '@/lib/auth'; + +type LayoutProps = { + children: React.ReactNode; + title: string; +}; + +export const AuthLayout = ({ children, title }: LayoutProps) => { + const user = useUser(); + + const router = useRouter(); + + useEffect(() => { + if (user.data) { + router.replace('/app'); + } + }, [user.data, router]); + + return ( + <> + +
+
+
+ + Workflow + +
+ +

+ {title} +

+
+ +
+
+ {children} +
+
+
+ + ); +}; diff --git a/apps/nextjs-app/src/components/layouts/content-layout.tsx b/apps/nextjs-app/src/components/layouts/content-layout.tsx new file mode 100644 index 00000000..8b09c411 --- /dev/null +++ b/apps/nextjs-app/src/components/layouts/content-layout.tsx @@ -0,0 +1,24 @@ +import * as React from 'react'; + +import { Head } from '../seo'; + +type ContentLayoutProps = { + children: React.ReactNode; + title: string; +}; + +export const ContentLayout = ({ children, title }: ContentLayoutProps) => { + return ( + <> + +
+
+

{title}

+
+
+ {children} +
+
+ + ); +}; diff --git a/apps/nextjs-app/src/components/layouts/dashboard-layout.tsx b/apps/nextjs-app/src/components/layouts/dashboard-layout.tsx new file mode 100644 index 00000000..c4c07cb9 --- /dev/null +++ b/apps/nextjs-app/src/components/layouts/dashboard-layout.tsx @@ -0,0 +1,251 @@ +import { Home, PanelLeft, Folder, Users, User2 } from 'lucide-react'; +import NextLink from 'next/link'; +import { useRouter } from 'next/router'; +import { useEffect, useState, Suspense } from 'react'; +import { ErrorBoundary } from 'react-error-boundary'; + +import { Button } from '@/components/ui/button'; +import { Drawer, DrawerContent, DrawerTrigger } from '@/components/ui/drawer'; +import { Spinner } from '@/components/ui/spinner'; +import { AuthLoader, useLogout } from '@/lib/auth'; +import { ROLES, useAuthorization } from '@/lib/authorization'; +import { cn } from '@/utils/cn'; + +import { + DropdownMenu, + DropdownMenuContent, + DropdownMenuItem, + DropdownMenuSeparator, + DropdownMenuTrigger, +} from '../ui/dropdown'; +import { Link } from '../ui/link'; + +type SideNavigationItem = { + name: string; + to: string; + icon: (props: React.SVGProps) => JSX.Element; +}; + +const Logo = () => { + return ( + + Workflow + + Bulletproof React + + + ); +}; + +const Progress = () => { + const router = useRouter(); + const [progress, setProgress] = useState(0); + + useEffect(() => { + const handleRouteChangeStart = () => { + setProgress(0); + const timer = setInterval(() => { + setProgress((oldProgress) => { + if (oldProgress === 100) { + clearInterval(timer); + return 100; + } + const newProgress = oldProgress + 10; + return newProgress > 100 ? 100 : newProgress; + }); + }, 300); + + return () => { + clearInterval(timer); + }; + }; + + const handleRouteChangeComplete = () => { + setProgress(100); + setTimeout(() => { + setProgress(0); + }, 500); // Adjust the delay as needed + }; + + router.events.on('routeChangeStart', handleRouteChangeStart); + router.events.on('routeChangeComplete', handleRouteChangeComplete); + router.events.on('routeChangeError', handleRouteChangeComplete); + + return () => { + router.events.off('routeChangeStart', handleRouteChangeStart); + router.events.off('routeChangeComplete', handleRouteChangeComplete); + router.events.off('routeChangeError', handleRouteChangeComplete); + }; + }, [router.events]); + + if (progress === 0) { + return null; + } + + return ( +
+ ); +}; + +const Layout = ({ children }: { children: React.ReactNode }) => { + const logout = useLogout(); + const { checkAccess } = useAuthorization(); + const router = useRouter(); + const navigation = [ + { name: 'Dashboard', to: '/app', icon: Home }, + { name: 'Discussions', to: '/app/discussions', icon: Folder }, + checkAccess({ allowedRoles: [ROLES.ADMIN] }) && { + name: 'Users', + to: '/app/users', + icon: Users, + }, + ].filter(Boolean) as SideNavigationItem[]; + + return ( +
+ +
+
+ + + + + + + + + + + + + + + router.push('/app/profile')} + className={cn('block px-4 py-2 text-sm text-gray-700')} + > + Your Profile + + + logout.mutate({})} + > + Sign Out + + + +
+
+ {children} +
+
+
+ ); +}; + +export const DashboardLayout = ({ + children, +}: { + children: React.ReactNode; +}) => { + const router = useRouter(); + return ( + + + + + } + > + Something went wrong!} + > + ( +
+ +
+ )} + > + {children} +
+
+
+
+ ); +}; diff --git a/apps/nextjs-app/src/components/layouts/index.ts b/apps/nextjs-app/src/components/layouts/index.ts new file mode 100644 index 00000000..fc6f49f3 --- /dev/null +++ b/apps/nextjs-app/src/components/layouts/index.ts @@ -0,0 +1,2 @@ +export * from './content-layout'; +export * from './dashboard-layout'; diff --git a/apps/nextjs-app/src/components/seo/head.tsx b/apps/nextjs-app/src/components/seo/head.tsx new file mode 100644 index 00000000..8269f173 --- /dev/null +++ b/apps/nextjs-app/src/components/seo/head.tsx @@ -0,0 +1,15 @@ +import NextHead from 'next/head'; + +type HeadProps = { + title?: string; + description?: string; +}; + +export const Head = ({ title = '', description = '' }: HeadProps = {}) => { + return ( + + {title} + + + ); +}; diff --git a/apps/nextjs-app/src/components/seo/index.ts b/apps/nextjs-app/src/components/seo/index.ts new file mode 100644 index 00000000..b6f0ab75 --- /dev/null +++ b/apps/nextjs-app/src/components/seo/index.ts @@ -0,0 +1 @@ +export * from './head'; diff --git a/apps/nextjs-app/src/components/ui/button/button.stories.tsx b/apps/nextjs-app/src/components/ui/button/button.stories.tsx new file mode 100644 index 00000000..3cd81eea --- /dev/null +++ b/apps/nextjs-app/src/components/ui/button/button.stories.tsx @@ -0,0 +1,17 @@ +import { Meta, StoryObj } from '@storybook/react'; + +import { Button } from './button'; + +const meta: Meta = { + component: Button, +}; + +export default meta; +type Story = StoryObj; + +export const Default: Story = { + args: { + children: 'Button', + variant: 'default', + }, +}; diff --git a/apps/nextjs-app/src/components/ui/button/button.tsx b/apps/nextjs-app/src/components/ui/button/button.tsx new file mode 100644 index 00000000..55b4eada --- /dev/null +++ b/apps/nextjs-app/src/components/ui/button/button.tsx @@ -0,0 +1,76 @@ +import { Slot } from '@radix-ui/react-slot'; +import { cva, type VariantProps } from 'class-variance-authority'; +import * as React from 'react'; + +import { cn } from '@/utils/cn'; + +import { Spinner } from '../spinner'; + +const buttonVariants = cva( + 'inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50', + { + variants: { + variant: { + default: + 'bg-primary text-primary-foreground shadow hover:bg-primary/90', + destructive: + 'bg-destructive text-destructive-foreground shadow-sm hover:bg-destructive/90', + outline: + 'border border-input bg-background shadow-sm hover:bg-accent hover:text-accent-foreground', + secondary: + 'bg-secondary text-secondary-foreground shadow-sm hover:bg-secondary/80', + ghost: 'hover:bg-accent hover:text-accent-foreground', + link: 'text-primary underline-offset-4 hover:underline', + }, + size: { + default: 'h-9 px-4 py-2', + sm: 'h-8 rounded-md px-3 text-xs', + lg: 'h-10 rounded-md px-8', + icon: 'size-9', + }, + }, + defaultVariants: { + variant: 'default', + size: 'default', + }, + }, +); + +export type ButtonProps = React.ButtonHTMLAttributes & + VariantProps & { + asChild?: boolean; + isLoading?: boolean; + icon?: React.ReactNode; + }; + +const Button = React.forwardRef( + ( + { + className, + variant, + size, + asChild = false, + children, + isLoading, + icon, + ...props + }, + ref, + ) => { + const Comp = asChild ? Slot : 'button'; + return ( + + {isLoading && } + {!isLoading && icon && {icon}} + {children} + + ); + }, +); +Button.displayName = 'Button'; + +export { Button, buttonVariants }; diff --git a/apps/nextjs-app/src/components/ui/button/index.ts b/apps/nextjs-app/src/components/ui/button/index.ts new file mode 100644 index 00000000..eaf5eea7 --- /dev/null +++ b/apps/nextjs-app/src/components/ui/button/index.ts @@ -0,0 +1 @@ +export * from './button'; diff --git a/apps/nextjs-app/src/components/ui/dialog/__tests__/dialog.test.tsx b/apps/nextjs-app/src/components/ui/dialog/__tests__/dialog.test.tsx new file mode 100644 index 00000000..f12895df --- /dev/null +++ b/apps/nextjs-app/src/components/ui/dialog/__tests__/dialog.test.tsx @@ -0,0 +1,68 @@ +import * as React from 'react'; + +import { Button } from '@/components/ui/button'; +import { useDisclosure } from '@/hooks/use-disclosure'; +import { rtlRender, screen, userEvent, waitFor } from '@/testing/test-utils'; + +import { + Dialog, + DialogContent, + DialogFooter, + DialogHeader, + DialogTitle, + DialogTrigger, +} from '../dialog'; + +const openButtonText = 'Open Modal'; +const cancelButtonText = 'Cancel'; +const titleText = 'Modal Title'; + +const TestDialog = () => { + const { close, open, isOpen } = useDisclosure(); + const cancelButtonRef = React.useRef(null); + + return ( + { + if (!isOpen) { + close(); + } else { + open(); + } + }} + > + + + + + + {titleText} + + + + + + + + + ); +}; + +test('should handle basic dialog flow', async () => { + rtlRender(); + + expect(screen.queryByText(titleText)).not.toBeInTheDocument(); + + await userEvent.click(screen.getByRole('button', { name: openButtonText })); + + expect(await screen.findByText(titleText)).toBeInTheDocument(); + + await userEvent.click(screen.getByRole('button', { name: cancelButtonText })); + + await waitFor(() => + expect(screen.queryByText(titleText)).not.toBeInTheDocument(), + ); +}); diff --git a/apps/nextjs-app/src/components/ui/dialog/confirmation-dialog/__tests__/confirmation-dialog.test.tsx b/apps/nextjs-app/src/components/ui/dialog/confirmation-dialog/__tests__/confirmation-dialog.test.tsx new file mode 100644 index 00000000..c56e701a --- /dev/null +++ b/apps/nextjs-app/src/components/ui/dialog/confirmation-dialog/__tests__/confirmation-dialog.test.tsx @@ -0,0 +1,37 @@ +import { Button } from '@/components/ui/button'; +import { rtlRender, screen, userEvent, waitFor } from '@/testing/test-utils'; + +import { ConfirmationDialog } from '../confirmation-dialog'; + +test('should handle confirmation flow', async () => { + const titleText = 'Are you sure?'; + const bodyText = 'Are you sure you want to delete this item?'; + const confirmationButtonText = 'Confirm'; + const openButtonText = 'Open'; + + await rtlRender( + {confirmationButtonText}} + triggerButton={} + />, + ); + + expect(screen.queryByText(titleText)).not.toBeInTheDocument(); + + await userEvent.click(screen.getByRole('button', { name: openButtonText })); + + expect(await screen.findByText(titleText)).toBeInTheDocument(); + + expect(screen.getByText(bodyText)).toBeInTheDocument(); + + await userEvent.click(screen.getByRole('button', { name: 'Cancel' })); + + await waitFor(() => + expect(screen.queryByText(titleText)).not.toBeInTheDocument(), + ); + + expect(screen.queryByText(bodyText)).not.toBeInTheDocument(); +}); diff --git a/apps/nextjs-app/src/components/ui/dialog/confirmation-dialog/confirmation-dialog.stories.tsx b/apps/nextjs-app/src/components/ui/dialog/confirmation-dialog/confirmation-dialog.stories.tsx new file mode 100644 index 00000000..3f787b42 --- /dev/null +++ b/apps/nextjs-app/src/components/ui/dialog/confirmation-dialog/confirmation-dialog.stories.tsx @@ -0,0 +1,33 @@ +import { Meta, StoryObj } from '@storybook/react'; + +import { Button } from '@/components/ui/button'; + +import { ConfirmationDialog } from './confirmation-dialog'; + +const meta: Meta = { + component: ConfirmationDialog, +}; + +export default meta; + +type Story = StoryObj; + +export const Danger: Story = { + args: { + icon: 'danger', + title: 'Confirmation', + body: 'Hello World', + confirmButton: , + triggerButton: , + }, +}; + +export const Info: Story = { + args: { + icon: 'info', + title: 'Confirmation', + body: 'Hello World', + confirmButton: , + triggerButton: , + }, +}; diff --git a/apps/nextjs-app/src/components/ui/dialog/confirmation-dialog/confirmation-dialog.tsx b/apps/nextjs-app/src/components/ui/dialog/confirmation-dialog/confirmation-dialog.tsx new file mode 100644 index 00000000..c8da8312 --- /dev/null +++ b/apps/nextjs-app/src/components/ui/dialog/confirmation-dialog/confirmation-dialog.tsx @@ -0,0 +1,88 @@ +import { CircleAlert, Info } from 'lucide-react'; +import * as React from 'react'; +import { useEffect } from 'react'; + +import { Button } from '@/components/ui/button'; +import { useDisclosure } from '@/hooks/use-disclosure'; + +import { + Dialog, + DialogContent, + DialogFooter, + DialogHeader, + DialogTitle, + DialogTrigger, +} from '../dialog'; + +export type ConfirmationDialogProps = { + triggerButton: React.ReactElement; + confirmButton: React.ReactElement; + title: string; + body?: string; + cancelButtonText?: string; + icon?: 'danger' | 'info'; + isDone?: boolean; +}; + +export const ConfirmationDialog = ({ + triggerButton, + confirmButton, + title, + body = '', + cancelButtonText = 'Cancel', + icon = 'danger', + isDone = false, +}: ConfirmationDialogProps) => { + const { close, open, isOpen } = useDisclosure(); + const cancelButtonRef = React.useRef(null); + + useEffect(() => { + if (isDone) { + close(); + } + }, [isDone, close]); + + return ( + { + if (!isOpen) { + close(); + } else { + open(); + } + }} + > + {triggerButton} + + + + {' '} + {icon === 'danger' && ( + + + +
+ {body && ( +
+

{body}

+
+ )} +
+ + + {confirmButton} + + +
+
+ ); +}; diff --git a/apps/nextjs-app/src/components/ui/dialog/confirmation-dialog/index.ts b/apps/nextjs-app/src/components/ui/dialog/confirmation-dialog/index.ts new file mode 100644 index 00000000..e8b63583 --- /dev/null +++ b/apps/nextjs-app/src/components/ui/dialog/confirmation-dialog/index.ts @@ -0,0 +1 @@ +export * from './confirmation-dialog'; diff --git a/apps/nextjs-app/src/components/ui/dialog/dialog.stories.tsx b/apps/nextjs-app/src/components/ui/dialog/dialog.stories.tsx new file mode 100644 index 00000000..7873b6ae --- /dev/null +++ b/apps/nextjs-app/src/components/ui/dialog/dialog.stories.tsx @@ -0,0 +1,63 @@ +import { Meta, StoryObj } from '@storybook/react'; +import * as React from 'react'; + +import { Button } from '@/components/ui/button'; +import { useDisclosure } from '@/hooks/use-disclosure'; + +import { + Dialog, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle, + DialogTrigger, +} from './dialog'; + +const DemoDialog = () => { + const { close, open, isOpen } = useDisclosure(); + const cancelButtonRef = React.useRef(null); + + return ( + { + if (!isOpen) { + close(); + } else { + open(); + } + }} + > + + + + + + Edit profile + Lorem ipsum + +
Lorem ipsum
+ + + + + +
+
+ ); +}; + +const meta: Meta = { + component: Dialog, +}; + +export default meta; + +type Story = StoryObj; + +export const Demo: Story = { + render: () => , +}; diff --git a/apps/nextjs-app/src/components/ui/dialog/dialog.tsx b/apps/nextjs-app/src/components/ui/dialog/dialog.tsx new file mode 100644 index 00000000..e9a1caae --- /dev/null +++ b/apps/nextjs-app/src/components/ui/dialog/dialog.tsx @@ -0,0 +1,120 @@ +import * as DialogPrimitive from '@radix-ui/react-dialog'; +import { Cross2Icon } from '@radix-ui/react-icons'; +import * as React from 'react'; + +import { cn } from '@/utils/cn'; + +const Dialog = DialogPrimitive.Root; + +const DialogTrigger = DialogPrimitive.Trigger; + +const DialogPortal = DialogPrimitive.Portal; + +const DialogClose = DialogPrimitive.Close; + +const DialogOverlay = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, ...props }, ref) => ( + +)); +DialogOverlay.displayName = DialogPrimitive.Overlay.displayName; + +const DialogContent = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, children, ...props }, ref) => ( + + + + {children} + + + Close + + + +)); +DialogContent.displayName = DialogPrimitive.Content.displayName; + +const DialogHeader = ({ + className, + ...props +}: React.HTMLAttributes) => ( +
+); +DialogHeader.displayName = 'DialogHeader'; + +const DialogFooter = ({ + className, + ...props +}: React.HTMLAttributes) => ( +
+); +DialogFooter.displayName = 'DialogFooter'; + +const DialogTitle = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, ...props }, ref) => ( + +)); +DialogTitle.displayName = DialogPrimitive.Title.displayName; + +const DialogDescription = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, ...props }, ref) => ( + +)); +DialogDescription.displayName = DialogPrimitive.Description.displayName; + +export { + Dialog, + DialogPortal, + DialogOverlay, + DialogTrigger, + DialogClose, + DialogContent, + DialogHeader, + DialogFooter, + DialogTitle, + DialogDescription, +}; diff --git a/apps/nextjs-app/src/components/ui/dialog/index.ts b/apps/nextjs-app/src/components/ui/dialog/index.ts new file mode 100644 index 00000000..c25eeb7f --- /dev/null +++ b/apps/nextjs-app/src/components/ui/dialog/index.ts @@ -0,0 +1,2 @@ +export * from './dialog'; +export * from './confirmation-dialog'; diff --git a/apps/nextjs-app/src/components/ui/drawer/__tests__/drawer.test.tsx b/apps/nextjs-app/src/components/ui/drawer/__tests__/drawer.test.tsx new file mode 100644 index 00000000..42123362 --- /dev/null +++ b/apps/nextjs-app/src/components/ui/drawer/__tests__/drawer.test.tsx @@ -0,0 +1,66 @@ +import { Button } from '@/components/ui/button'; +import { rtlRender, screen, userEvent, waitFor } from '@/testing/test-utils'; + +import { + Drawer, + DrawerClose, + DrawerContent, + DrawerFooter, + DrawerHeader, + DrawerTitle, + DrawerTrigger, +} from '../drawer'; + +const openButtonText = 'Open Drawer'; +const titleText = 'Drawer Title'; +const cancelButtonText = 'Cancel'; +const drawerContentText = 'Hello From Drawer'; + +const TestDrawer = () => { + return ( + + + + + +
+ + {titleText} + +
{drawerContentText}
+
+ + + + + +
+
+ ); +}; + +test('should handle basic drawer flow', async () => { + await rtlRender(); + + expect(screen.queryByText(titleText)).not.toBeInTheDocument(); + + await userEvent.click( + screen.getByRole('button', { + name: openButtonText, + }), + ); + + expect(await screen.findByText(titleText)).toBeInTheDocument(); + + await userEvent.click( + screen.getByRole('button', { + name: cancelButtonText, + }), + ); + + await waitFor(() => + expect(screen.queryByText(titleText)).not.toBeInTheDocument(), + ); +}); diff --git a/apps/nextjs-app/src/components/ui/drawer/drawer.stories.tsx b/apps/nextjs-app/src/components/ui/drawer/drawer.stories.tsx new file mode 100644 index 00000000..c81d77d0 --- /dev/null +++ b/apps/nextjs-app/src/components/ui/drawer/drawer.stories.tsx @@ -0,0 +1,64 @@ +import { Meta, StoryObj } from '@storybook/react'; + +import { Button } from '@/components/ui/button'; +import { useDisclosure } from '@/hooks/use-disclosure'; + +import { + Drawer, + DrawerClose, + DrawerContent, + DrawerDescription, + DrawerFooter, + DrawerHeader, + DrawerTitle, + DrawerTrigger, +} from './drawer'; + +const meta: Meta = { + component: Drawer, +}; + +export default meta; + +type Story = StoryObj; + +const DemoDrawer = () => { + const { close, open, isOpen } = useDisclosure(); + + return ( + { + if (!isOpen) { + close(); + } else { + open(); + } + }} + > + + + + +
+ + Drawer Header + + Lorem ipsum dolor sit amet, consectetur adipiscing elit. + + +
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
+
+ + + + + +
+
+ ); +}; + +export const Default: Story = { + render: () => , +}; diff --git a/apps/nextjs-app/src/components/ui/drawer/drawer.tsx b/apps/nextjs-app/src/components/ui/drawer/drawer.tsx new file mode 100644 index 00000000..f4f2306d --- /dev/null +++ b/apps/nextjs-app/src/components/ui/drawer/drawer.tsx @@ -0,0 +1,139 @@ +import * as DrawerPrimitive from '@radix-ui/react-dialog'; +import { Cross2Icon } from '@radix-ui/react-icons'; +import { cva, type VariantProps } from 'class-variance-authority'; +import * as React from 'react'; + +import { cn } from '@/utils/cn'; + +const Drawer = DrawerPrimitive.Root; + +const DrawerTrigger = DrawerPrimitive.Trigger; + +const DrawerClose = DrawerPrimitive.Close; + +const DrawerPortal = DrawerPrimitive.Portal; + +const DrawerOverlay = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, ...props }, ref) => ( + +)); +DrawerOverlay.displayName = DrawerPrimitive.Overlay.displayName; + +const drawerVariants = cva( + 'fixed z-50 gap-4 bg-background p-6 shadow-lg transition ease-in-out data-[state=closed]:duration-300 data-[state=open]:duration-500 data-[state=open]:animate-in data-[state=closed]:animate-out', + { + variants: { + side: { + top: 'inset-x-0 top-0 border-b data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top', + bottom: + 'inset-x-0 bottom-0 border-t data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom', + left: 'inset-y-0 left-0 h-full w-3/4 border-r data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left sm:max-w-sm', + right: + 'inset-y-0 right-0 h-full w-3/4 border-l data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right sm:max-w-sm', + }, + }, + defaultVariants: { + side: 'right', + }, + }, +); + +type DrawerContentProps = React.ComponentPropsWithoutRef< + typeof DrawerPrimitive.Content +> & + VariantProps; + +const DrawerContent = React.forwardRef< + React.ElementRef, + DrawerContentProps +>(({ side = 'right', className, children, ...props }, ref) => ( + + + + {children} + + + Close + + + +)); +DrawerContent.displayName = DrawerPrimitive.Content.displayName; + +const DrawerHeader = ({ + className, + ...props +}: React.HTMLAttributes) => ( +
+); +DrawerHeader.displayName = 'DrawerHeader'; + +const DrawerFooter = ({ + className, + ...props +}: React.HTMLAttributes) => ( +
+); +DrawerFooter.displayName = 'DrawerFooter'; + +const DrawerTitle = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, ...props }, ref) => ( + +)); +DrawerTitle.displayName = DrawerPrimitive.Title.displayName; + +const DrawerDescription = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, ...props }, ref) => ( + +)); +DrawerDescription.displayName = DrawerPrimitive.Description.displayName; + +export { + Drawer, + DrawerPortal, + DrawerOverlay, + DrawerTrigger, + DrawerClose, + DrawerContent, + DrawerHeader, + DrawerFooter, + DrawerTitle, + DrawerDescription, +}; diff --git a/apps/nextjs-app/src/components/ui/drawer/index.ts b/apps/nextjs-app/src/components/ui/drawer/index.ts new file mode 100644 index 00000000..a150839b --- /dev/null +++ b/apps/nextjs-app/src/components/ui/drawer/index.ts @@ -0,0 +1 @@ +export * from './drawer'; diff --git a/apps/nextjs-app/src/components/ui/dropdown/dropdown.tsx b/apps/nextjs-app/src/components/ui/dropdown/dropdown.tsx new file mode 100644 index 00000000..94294654 --- /dev/null +++ b/apps/nextjs-app/src/components/ui/dropdown/dropdown.tsx @@ -0,0 +1,203 @@ +import * as DropdownMenuPrimitive from '@radix-ui/react-dropdown-menu'; +import { + CheckIcon, + ChevronRightIcon, + DotFilledIcon, +} from '@radix-ui/react-icons'; +import * as React from 'react'; + +import { cn } from '@/utils/cn'; + +const DropdownMenu = DropdownMenuPrimitive.Root; + +const DropdownMenuTrigger = DropdownMenuPrimitive.Trigger; + +const DropdownMenuGroup = DropdownMenuPrimitive.Group; + +const DropdownMenuPortal = DropdownMenuPrimitive.Portal; + +const DropdownMenuSub = DropdownMenuPrimitive.Sub; + +const DropdownMenuRadioGroup = DropdownMenuPrimitive.RadioGroup; + +const DropdownMenuSubTrigger = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef & { + inset?: boolean; + } +>(({ className, inset, children, ...props }, ref) => ( + + {children} + + +)); +DropdownMenuSubTrigger.displayName = + DropdownMenuPrimitive.SubTrigger.displayName; + +const DropdownMenuSubContent = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, ...props }, ref) => ( + +)); +DropdownMenuSubContent.displayName = + DropdownMenuPrimitive.SubContent.displayName; + +const DropdownMenuContent = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, sideOffset = 4, ...props }, ref) => ( + + + +)); +DropdownMenuContent.displayName = DropdownMenuPrimitive.Content.displayName; + +const DropdownMenuItem = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef & { + inset?: boolean; + } +>(({ className, inset, ...props }, ref) => ( + +)); +DropdownMenuItem.displayName = DropdownMenuPrimitive.Item.displayName; + +const DropdownMenuCheckboxItem = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, children, checked, ...props }, ref) => ( + + + + + + + {children} + +)); +DropdownMenuCheckboxItem.displayName = + DropdownMenuPrimitive.CheckboxItem.displayName; + +const DropdownMenuRadioItem = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, children, ...props }, ref) => ( + + + + + + + {children} + +)); +DropdownMenuRadioItem.displayName = DropdownMenuPrimitive.RadioItem.displayName; + +const DropdownMenuLabel = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef & { + inset?: boolean; + } +>(({ className, inset, ...props }, ref) => ( + +)); +DropdownMenuLabel.displayName = DropdownMenuPrimitive.Label.displayName; + +const DropdownMenuSeparator = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, ...props }, ref) => ( + +)); +DropdownMenuSeparator.displayName = DropdownMenuPrimitive.Separator.displayName; + +const DropdownMenuShortcut = ({ + className, + ...props +}: React.HTMLAttributes) => { + return ( + + ); +}; +DropdownMenuShortcut.displayName = 'DropdownMenuShortcut'; + +export { + DropdownMenu, + DropdownMenuTrigger, + DropdownMenuContent, + DropdownMenuItem, + DropdownMenuCheckboxItem, + DropdownMenuRadioItem, + DropdownMenuLabel, + DropdownMenuSeparator, + DropdownMenuShortcut, + DropdownMenuGroup, + DropdownMenuPortal, + DropdownMenuSub, + DropdownMenuSubContent, + DropdownMenuSubTrigger, + DropdownMenuRadioGroup, +}; diff --git a/apps/nextjs-app/src/components/ui/dropdown/index.ts b/apps/nextjs-app/src/components/ui/dropdown/index.ts new file mode 100644 index 00000000..b96a997b --- /dev/null +++ b/apps/nextjs-app/src/components/ui/dropdown/index.ts @@ -0,0 +1 @@ +export * from './dropdown'; diff --git a/apps/nextjs-app/src/components/ui/form/__tests__/form.test.tsx b/apps/nextjs-app/src/components/ui/form/__tests__/form.test.tsx new file mode 100644 index 00000000..b2bb4110 --- /dev/null +++ b/apps/nextjs-app/src/components/ui/form/__tests__/form.test.tsx @@ -0,0 +1,74 @@ +import { SubmitHandler } from 'react-hook-form'; +import { z } from 'zod'; + +import { Button } from '@/components/ui/button'; +import { rtlRender, screen, waitFor, userEvent } from '@/testing/test-utils'; + +import { Form } from '../form'; +import { Input } from '../input'; + +const testData = { + title: 'Hello World', +}; + +const schema = z.object({ + title: z.string().min(1, 'Required'), +}); + +test('should render and submit a basic Form component', async () => { + const handleSubmit = vi.fn() as SubmitHandler>; + + rtlRender( +
+ {({ register, formState }) => ( + <> + + + + + )} +
, + ); + + await userEvent.type(screen.getByLabelText(/title/i), testData.title); + + await userEvent.click(screen.getByRole('button', { name: /submit/i })); + + await waitFor(() => + expect(handleSubmit).toHaveBeenCalledWith(testData, expect.anything()), + ); +}); + +test('should fail submission if validation fails', async () => { + const handleSubmit = vi.fn() as SubmitHandler>; + + rtlRender( +
+ {({ register, formState }) => ( + <> + + + + + )} +
, + ); + + await userEvent.click(screen.getByRole('button', { name: /submit/i })); + + await screen.findByRole('alert', { name: /required/i }); + + expect(handleSubmit).toHaveBeenCalledTimes(0); +}); diff --git a/apps/nextjs-app/src/components/ui/form/error.tsx b/apps/nextjs-app/src/components/ui/form/error.tsx new file mode 100644 index 00000000..5b2b0557 --- /dev/null +++ b/apps/nextjs-app/src/components/ui/form/error.tsx @@ -0,0 +1,17 @@ +export type ErrorProps = { + errorMessage?: string | null; +}; + +export const Error = ({ errorMessage }: ErrorProps) => { + if (!errorMessage) return null; + + return ( +
+ {errorMessage} +
+ ); +}; diff --git a/apps/nextjs-app/src/components/ui/form/field-wrapper.tsx b/apps/nextjs-app/src/components/ui/form/field-wrapper.tsx new file mode 100644 index 00000000..3320eb72 --- /dev/null +++ b/apps/nextjs-app/src/components/ui/form/field-wrapper.tsx @@ -0,0 +1,30 @@ +import * as React from 'react'; +import { type FieldError } from 'react-hook-form'; + +import { Error } from './error'; +import { Label } from './label'; + +type FieldWrapperProps = { + label?: string; + className?: string; + children: React.ReactNode; + error?: FieldError | undefined; +}; + +export type FieldWrapperPassThroughProps = Omit< + FieldWrapperProps, + 'className' | 'children' +>; + +export const FieldWrapper = (props: FieldWrapperProps) => { + const { label, error, children } = props; + return ( +
+ + +
+ ); +}; diff --git a/apps/nextjs-app/src/components/ui/form/form-drawer.tsx b/apps/nextjs-app/src/components/ui/form/form-drawer.tsx new file mode 100644 index 00000000..0d7572a8 --- /dev/null +++ b/apps/nextjs-app/src/components/ui/form/form-drawer.tsx @@ -0,0 +1,69 @@ +import * as React from 'react'; + +import { useDisclosure } from '@/hooks/use-disclosure'; + +import { Button } from '../button'; +import { + Drawer, + DrawerClose, + DrawerContent, + DrawerFooter, + DrawerHeader, + DrawerTrigger, + DrawerTitle, +} from '../drawer'; + +type FormDrawerProps = { + isDone: boolean; + triggerButton: React.ReactElement; + submitButton: React.ReactElement; + title: string; + children: React.ReactNode; +}; + +export const FormDrawer = ({ + title, + children, + isDone, + triggerButton, + submitButton, +}: FormDrawerProps) => { + const { close, open, isOpen } = useDisclosure(); + + React.useEffect(() => { + if (isDone) { + close(); + } + }, [isDone, close]); + + return ( + { + if (!isOpen) { + close(); + } else { + open(); + } + }} + > + {triggerButton} + +
+ + {title} + +
{children}
+
+ + + + + {submitButton} + +
+
+ ); +}; diff --git a/apps/nextjs-app/src/components/ui/form/form.stories.tsx b/apps/nextjs-app/src/components/ui/form/form.stories.tsx new file mode 100644 index 00000000..071c78df --- /dev/null +++ b/apps/nextjs-app/src/components/ui/form/form.stories.tsx @@ -0,0 +1,87 @@ +import { Meta, StoryObj } from '@storybook/react'; +import { z } from 'zod'; + +import { Button } from '../button'; + +import { Form } from './form'; +import { FormDrawer } from './form-drawer'; +import { Input } from './input'; +import { Select } from './select'; +import { Textarea } from './textarea'; + +const MyForm = ({ hideSubmit = false }: { hideSubmit?: boolean }) => { + return ( +
{ + alert(JSON.stringify(values, null, 2)); + }} + schema={z.object({ + title: z.string().min(1, 'Required'), + description: z.string().min(1, 'Required'), + type: z.string().min(1, 'Required'), + })} + id="my-form" + > + {({ register, formState }) => ( + <> + +