Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Thomas Dillard - Frontend Challenge #83

Open
wants to merge 15 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 2 additions & 0 deletions frontend/.eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ const ruleOverrides = {
'canonical/export-specifier-newline': 0,
'canonical/filename-match-regex': 0,
'canonical/import-specifier-newline': 0,
// The `allowLineSeparatedGroups` option doesn't exist for canonical/sort-keys: https://github.com/gajus/eslint-plugin-canonical/issues/20
'canonical/sort-keys': 1,
'default-case': 0,
'default-case-last': 0,
'import/extensions': 0,
Expand Down
130 changes: 130 additions & 0 deletions frontend/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
.pnpm-debug.log*

# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json

# Runtime data
pids
*.pid
*.seed
*.pid.lock

# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov

# Coverage directory used by tools like istanbul
coverage
*.lcov

# nyc test coverage
.nyc_output

# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt

# Bower dependency directory (https://bower.io/)
bower_components

# node-waf configuration
.lock-wscript

# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release

# Dependency directories
node_modules/
jspm_packages/

# Snowpack dependency directory (https://snowpack.dev/)
web_modules/

# TypeScript cache
*.tsbuildinfo

# Optional npm cache directory
.npm

# Optional eslint cache
.eslintcache

# Optional stylelint cache
.stylelintcache

# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/

# Optional REPL history
.node_repl_history

# Output of 'npm pack'
*.tgz

# Yarn Integrity file
.yarn-integrity

# dotenv environment variable files
.env
.env.development.local
.env.test.local
.env.production.local
.env.local

# parcel-bundler cache (https://parceljs.org/)
.cache
.parcel-cache

# Next.js build output
.next
out

# Nuxt.js build / generate output
.nuxt
dist

# Gatsby files
.cache/
# Comment in the public line in if your project uses Gatsby and not Next.js
# https://nextjs.org/blog/next-9-1#public-directory-support
# public

# vuepress build output
.vuepress/dist

# vuepress v2.x temp and cache directory
.temp
.cache

# Docusaurus cache and generated files
.docusaurus

# Serverless directories
.serverless/

# FuseBox cache
.fusebox/

# DynamoDB Local files
.dynamodb/

# TernJS port file
.tern-port

# Stores VSCode versions used for testing VSCode extensions
.vscode-test

# yarn v2
.yarn/cache
.yarn/unplugged
.yarn/build-state.yml
.yarn/install-state.gz
.pnp.*
1 change: 1 addition & 0 deletions frontend/.yarnrc.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
nodeLinker: node-modules
5 changes: 4 additions & 1 deletion frontend/jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,11 @@ const customJestConfig = {
// Add more setup options before each test is run
// setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
// if using TypeScript with a baseUrl set to the root directory then you need the below for alias' to work
moduleDirectories: ['node_modules', '<rootDir>/'],
moduleDirectories: ['node_modules', 'src'],
testEnvironment: 'jest-environment-jsdom',
moduleNameMapper: {
"^@/(.*)": "<rootDir>/src/$1"
}
};

// createJestConfig is exported this way to ensure that next/jest can load the Next.js config which is async
Expand Down
9 changes: 7 additions & 2 deletions frontend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,19 @@
"lint": "yarn lint:eslint && yarn lint:prettier",
"lint:eslint": "eslint './src/**/*.{js,ts,tsx}' --cache",
"lint:prettier": "prettier --ignore-path .gitignore --check './**/*.{js,ts,tsx}'",
"test": "NODE_ENV=test jest --watch",
"test": "NODE_ENV=test jest -c jest.config.js --watch",
"test:ci": "NODE_ENV=test jest --ci --reporters jest-silent-reporter"
},
"dependencies": {
"@stitches/react": "^1.2.8",
"@testing-library/user-event": "^14.4.3",
"next": "12.1.6",
"react": "18.2.0",
"react-dom": "18.2.0"
},
"devDependencies": {
"@testing-library/jest-dom": "^5.16.5",
"@testing-library/react": "^14.0.0",
"@types/jest": "28.1.3",
"@types/node": "18.0.0",
"@types/react": "18.0.14",
Expand All @@ -26,7 +30,8 @@
"eslint-config-canonical": "35.0.1",
"eslint-config-next": "12.1.6",
"eslint-config-prettier": "8.5.0",
"jest": "28.1.1",
"jest": "^29.5.0",
"jest-environment-jsdom": "^29.5.0",
"lint-staged": "13.0.3",
"prettier": "2.7.1",
"typescript": "4.7.4"
Expand Down
65 changes: 65 additions & 0 deletions frontend/src/__tests__/Modal.spec.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import { render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import React from 'react';
import { Modal } from '@/components/Modal';

const renderModal = (open: boolean, onClose = () => {}) => {
return render(
<Modal data-testId="modal" onClose={onClose} open={open}>
<input data-testid="input1" />
<input data-testid="input2" />
<button data-testid="button" type="button">
Close
</button>
</Modal>
);
};

describe('Modal', () => {
it('focuses on the first element when opened', async () => {
renderModal(true);
const firstElement = screen.getByTestId('input1');
await waitFor(() => expect(document.activeElement).not.toBe(document));

expect(document.activeElement).toBe(firstElement);
});

it('focuses on the next element when tab is pressed', async () => {
renderModal(true);
const secondElement = screen.getByTestId('input2');

await userEvent.keyboard('{Tab}');

expect(document.activeElement).toBe(secondElement);
});

it('focuses on the first element when tab is pressed on the last element', async () => {
renderModal(true);
const firstElement = screen.getByTestId('input1');
const lastElement = screen.getByTestId('button');

lastElement.focus();
await userEvent.keyboard('{Tab}');

expect(document.activeElement).toBe(firstElement);
});

it('focuses on the last element when shift + tab is pressed on first element', async () => {
renderModal(true);
const firstElement = screen.getByTestId('input1');
const lastElement = screen.getByTestId('button');

firstElement.focus();
await userEvent.keyboard('{Shift>}{Tab}');

expect(document.activeElement).toBe(lastElement);
});

it('closes the modal when escape key is pressed', async () => {
const handleClose = jest.fn();
renderModal(true, handleClose);
await userEvent.keyboard('{Escape}');

expect(handleClose).toHaveBeenCalled();
});
});
67 changes: 67 additions & 0 deletions frontend/src/components/Modal.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import { type PropsWithChildren, type HTMLAttributes } from 'react';
import { styled } from '@/utils/styles';
import { useEscapeKeyListener } from '@/utils/use-escape-trap';
import { useFocusTrap } from '@/utils/use-focus-trap';
import { useScrollLock } from '@/utils/use-scroll-lock';
import { ReactPortal } from './ReactPortal';

const ModalBackground = styled('div', {
backgroundColor: 'rgba(0,0,0,0.7)',
bottom: 0,
left: 0,
position: 'fixed',
right: 0,
top: 0,
zIndex: 10,
});

const ModalContainer = styled('div', {
backgroundColor: '#fefefe',
border: '1px solid #888',
boxShadow: '0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19)',
display: 'flex',
flexDirection: 'column',
height: '100%',
margin: 0,
padding: '20px',
width: '100%',

// eslint-disable-next-line canonical/sort-keys
'@md': {
borderRadius: '4px',
height: 'auto',
margin: '10% auto',
width: '50%',
},
});

type ModalProps = HTMLAttributes<HTMLDivElement> &
PropsWithChildren<{
onClose: () => void;
open: boolean;
}>;

// event.relatedTarget might be worth researching in the future
export const Modal = ({ children, open, onClose, ...props }: ModalProps) => {
const ref = useFocusTrap<HTMLDivElement>();
useScrollLock(open);
useEscapeKeyListener(onClose);

if (!open) return null;

return (
<ReactPortal>
<ModalBackground>
<ModalContainer
aria-hidden={!open}
aria-modal
ref={ref}
role="dialog"
{...props}
>
{children}
</ModalContainer>
</ModalBackground>
</ReactPortal>
);
};
37 changes: 37 additions & 0 deletions frontend/src/components/ReactPortal.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { type PropsWithChildren, useState } from 'react';
import { createPortal } from 'react-dom';
import { useIsomorphicLayoutEffect } from '@/utils/use-isomorphic-layout';

type WrapperId = string;

const createRootElement = (wrapperId: WrapperId) => {
const wrapperElement = document.createElement('div');
wrapperElement.setAttribute('id', wrapperId);
document.body.appendChild(wrapperElement);
return wrapperElement;
};

export const ReactPortal = ({
children,
wrapperId = 'contra-frontend-modal',
}: PropsWithChildren<{ wrapperId?: WrapperId }>) => {
const [domNode, setDomNode] = useState<HTMLDivElement | null>(null);

useIsomorphicLayoutEffect(() => {
let element = document.querySelector<HTMLDivElement>(wrapperId);
if (!element) {
element = createRootElement(wrapperId);
}

setDomNode(element);

return () => {
if (element?.parentNode) {
element.parentNode.removeChild(element);
}
};
}, [wrapperId]);

if (domNode === null) return null;
return createPortal(children, domNode);
};