├── .gitignore
├── .prettierrc
├── README.md
├── package-lock.json
├── package.json
├── postcss.config.js
├── public
├── android-chrome-192x192.png
├── android-chrome-512x512.png
├── apple-touch-icon.png
├── favicon-16x16.png
├── favicon-32x32.png
├── favicon.ico
├── index.html
├── logo192.png
├── logo512.png
├── manifest.json
└── robots.txt
├── src
├── components
│ ├── application.js
│ ├── header.js
│ ├── item-list.js
│ ├── item.js
│ ├── mark-all-as-unpacked.js
│ └── new-item.js
├── global.d.ts
├── index.css
├── index.js
└── lib
│ ├── api.ts
│ ├── items.test.ts
│ ├── items.ts
│ ├── kebab-case.ts
│ ├── normalize.test.ts
│ ├── normalize.ts
│ ├── reducer.test.ts
│ ├── reducer.ts
│ └── slow-down.ts
├── tailwind.config.js
└── tsconfig.json
/.gitignore:
--------------------------------------------------------------------------------
1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
2 |
3 | # dependencies
4 | /node_modules
5 | /.pnp
6 | .pnp.js
7 |
8 | # testing
9 | /coverage
10 |
11 | # production
12 | /build
13 |
14 | # misc
15 | .DS_Store
16 | .env.local
17 | .env.development.local
18 | .env.test.local
19 | .env.production.local
20 |
21 | npm-debug.log*
22 | yarn-debug.log*
23 | yarn-error.log*
24 | .vscode/settings.json
25 |
--------------------------------------------------------------------------------
/.prettierrc:
--------------------------------------------------------------------------------
1 | {
2 | "printWidth": 80,
3 | "tabWidth": 2,
4 | "useTabs": false,
5 | "semi": true,
6 | "singleQuote": true,
7 | "trailingComma": "all",
8 | "bracketSpacing": true,
9 | "jsxBracketSameLine": false
10 | }
11 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Getting Started with Create React App
2 |
3 | This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
4 |
5 | ## Available Scripts
6 |
7 | In the project directory, you can run:
8 |
9 | ### `npm start`
10 |
11 | Runs the app in the development mode.\
12 | Open [http://localhost:3000](http://localhost:3000) to view it in your browser.
13 |
14 | The page will reload when you make changes.\
15 | You may also see any lint errors in the console.
16 |
17 | ### `npm test`
18 |
19 | Launches the test runner in the interactive watch mode.\
20 | See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
21 |
22 | ### `npm run build`
23 |
24 | Builds the app for production to the `build` folder.\
25 | It correctly bundles React in production mode and optimizes the build for the best performance.
26 |
27 | The build is minified and the filenames include the hashes.\
28 | Your app is ready to be deployed!
29 |
30 | See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
31 |
32 | ### `npm run eject`
33 |
34 | **Note: this is a one-way operation. Once you `eject`, you can't go back!**
35 |
36 | If you aren't satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
37 |
38 | Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you're on your own.
39 |
40 | You don't have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn't feel obligated to use this feature. However we understand that this tool wouldn't be useful if you couldn't customize it when you are ready for it.
41 |
42 | ## Learn More
43 |
44 | You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
45 |
46 | To learn React, check out the [React documentation](https://reactjs.org/).
47 |
48 | ### Code Splitting
49 |
50 | This section has moved here: [https://facebook.github.io/create-react-app/docs/code-splitting](https://facebook.github.io/create-react-app/docs/code-splitting)
51 |
52 | ### Analyzing the Bundle Size
53 |
54 | This section has moved here: [https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size](https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size)
55 |
56 | ### Making a Progressive Web App
57 |
58 | This section has moved here: [https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app](https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app)
59 |
60 | ### Advanced Configuration
61 |
62 | This section has moved here: [https://facebook.github.io/create-react-app/docs/advanced-configuration](https://facebook.github.io/create-react-app/docs/advanced-configuration)
63 |
64 | ### Deployment
65 |
66 | This section has moved here: [https://facebook.github.io/create-react-app/docs/deployment](https://facebook.github.io/create-react-app/docs/deployment)
67 |
68 | ### `npm run build` fails to minify
69 |
70 | This section has moved here: [https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify](https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify)
71 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "packing-list",
3 | "version": "0.1.0",
4 | "private": true,
5 | "dependencies": {
6 | "@reduxjs/toolkit": "^1.9.0",
7 | "@testing-library/jest-dom": "^5.16.5",
8 | "@testing-library/react": "^13.4.0",
9 | "@testing-library/user-event": "^13.5.0",
10 | "clsx": "^1.2.1",
11 | "prop-types": "^15.8.1",
12 | "react": "^18.2.0",
13 | "react-dom": "^18.2.0",
14 | "react-scripts": "5.0.1",
15 | "uuid": "^9.0.0"
16 | },
17 | "scripts": {
18 | "start": "react-scripts start",
19 | "build": "react-scripts build",
20 | "test": "react-scripts test",
21 | "eject": "react-scripts eject"
22 | },
23 | "eslintConfig": {
24 | "extends": [
25 | "react-app",
26 | "react-app/jest"
27 | ]
28 | },
29 | "browserslist": {
30 | "production": [
31 | ">0.2%",
32 | "not dead",
33 | "not op_mini all"
34 | ],
35 | "development": [
36 | "last 1 chrome version",
37 | "last 1 firefox version",
38 | "last 1 safari version"
39 | ]
40 | },
41 | "devDependencies": {
42 | "@types/uuid": "^8.3.4",
43 | "autoprefixer": "^10.4.12",
44 | "postcss": "^8.4.18",
45 | "prettier": "^2.7.1",
46 | "prettier-plugin-tailwindcss": "^0.1.13",
47 | "tailwindcss": "^3.2.1",
48 | "typescript": "^4.9.3"
49 | }
50 | }
51 |
--------------------------------------------------------------------------------
/postcss.config.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | plugins: {
3 | tailwindcss: {},
4 | autoprefixer: {},
5 | },
6 | }
7 |
--------------------------------------------------------------------------------
/public/android-chrome-192x192.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/stevekinney/packing-list/58f66ecdc5981190dae415aa67254cc81aa5cffa/public/android-chrome-192x192.png
--------------------------------------------------------------------------------
/public/android-chrome-512x512.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/stevekinney/packing-list/58f66ecdc5981190dae415aa67254cc81aa5cffa/public/android-chrome-512x512.png
--------------------------------------------------------------------------------
/public/apple-touch-icon.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/stevekinney/packing-list/58f66ecdc5981190dae415aa67254cc81aa5cffa/public/apple-touch-icon.png
--------------------------------------------------------------------------------
/public/favicon-16x16.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/stevekinney/packing-list/58f66ecdc5981190dae415aa67254cc81aa5cffa/public/favicon-16x16.png
--------------------------------------------------------------------------------
/public/favicon-32x32.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/stevekinney/packing-list/58f66ecdc5981190dae415aa67254cc81aa5cffa/public/favicon-32x32.png
--------------------------------------------------------------------------------
/public/favicon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/stevekinney/packing-list/58f66ecdc5981190dae415aa67254cc81aa5cffa/public/favicon.ico
--------------------------------------------------------------------------------
/public/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
12 |
13 |
17 |
18 |
27 | Packing List
28 |
29 |
30 |
31 |
32 |
42 |
43 |
44 |
--------------------------------------------------------------------------------
/public/logo192.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/stevekinney/packing-list/58f66ecdc5981190dae415aa67254cc81aa5cffa/public/logo192.png
--------------------------------------------------------------------------------
/public/logo512.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/stevekinney/packing-list/58f66ecdc5981190dae415aa67254cc81aa5cffa/public/logo512.png
--------------------------------------------------------------------------------
/public/manifest.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "Packing List",
3 | "short_name": "Packing List",
4 | "icons": [
5 | {
6 | "src": "/android-chrome-192x192.png",
7 | "sizes": "192x192",
8 | "type": "image/png"
9 | },
10 | {
11 | "src": "/android-chrome-512x512.png",
12 | "sizes": "512x512",
13 | "type": "image/png"
14 | }
15 | ],
16 | "theme_color": "#ffffff",
17 | "background_color": "#ffffff",
18 | "display": "standalone"
19 | }
20 |
--------------------------------------------------------------------------------
/public/robots.txt:
--------------------------------------------------------------------------------
1 | # https://www.robotstxt.org/robotstxt.html
2 | User-agent: *
3 | Disallow:
4 |
--------------------------------------------------------------------------------
/src/components/application.js:
--------------------------------------------------------------------------------
1 | import { useState } from 'react';
2 | import {
3 | createItem,
4 | filterItems,
5 | getInitialItems,
6 | removeItem,
7 | updateItem,
8 | } from '../lib/items';
9 | import Header from './header';
10 | import ItemList from './item-list';
11 | import MarkAllAsUnpacked from './mark-all-as-unpacked';
12 | import NewItem from './new-item';
13 |
14 | const Application = () => {
15 | const [items, setItems] = useState(getInitialItems());
16 | const [newItemName, setNewItemName] = useState('');
17 |
18 | const add = (name) => {
19 | const item = createItem(name);
20 | setItems([...items, item]);
21 | };
22 |
23 | const update = (id, updates) => {
24 | setItems(updateItem(items, id, updates));
25 | };
26 |
27 | const remove = (id) => {
28 | setItems(removeItem(items, id));
29 | };
30 |
31 | const unpackedItems = filterItems(items, { packed: false });
32 | const packedItems = filterItems(items, { packed: true });
33 |
34 | const markAllAsUnpacked = () => {
35 | return setItems(items.map((item) => ({ ...item, packed: false })));
36 | };
37 |
38 | return (
39 |
40 |
41 |
46 |
60 |
61 |
62 | );
63 | };
64 |
65 | export default Application;
66 |
--------------------------------------------------------------------------------
/src/components/header.js:
--------------------------------------------------------------------------------
1 | const Header = ({ items }) => (
2 |
8 | );
9 |
10 | export default Header;
11 |
--------------------------------------------------------------------------------
/src/components/item-list.js:
--------------------------------------------------------------------------------
1 | import { useState } from 'react';
2 | import { filterItems } from '../lib/items';
3 | import { toKebabCase } from '../lib/kebab-case';
4 | import Item from './item';
5 |
6 | const EmptyState = ({ id, items, filteredItems }) => (
7 |
8 | (No items.)
9 |
10 | );
11 |
12 | const ItemList = ({ title = 'Items', items, update, remove }) => {
13 | const [filter, setFilter] = useState('');
14 | const id = toKebabCase(title);
15 |
16 | const filteredItems = filterItems(items, { name: filter });
17 | const isEmpty = !items.length;
18 |
19 | return (
20 |
21 |
32 |
33 | {filteredItems.map((item) => (
34 |
35 | ))}
36 |
37 | {isEmpty && (
38 |
43 | )}
44 |
45 | );
46 | };
47 |
48 | export default ItemList;
49 |
--------------------------------------------------------------------------------
/src/components/item.js:
--------------------------------------------------------------------------------
1 | import clsx from 'clsx';
2 | import { useState } from 'react';
3 |
4 | const Item = ({ item, update, remove }) => {
5 | const [editing, setEditing] = useState(false);
6 |
7 | return (
8 |
9 | update(item.id, { packed: !item.packed })}
15 | />
16 |
22 | update(item.id, { name: event.target.value })}
27 | />
28 |
29 |
36 |
43 |
44 |
45 | );
46 | };
47 |
48 | export default Item;
49 |
--------------------------------------------------------------------------------
/src/components/mark-all-as-unpacked.js:
--------------------------------------------------------------------------------
1 | const MarkAllAsUnpacked = ({ onClick }) => (
2 |
3 |
6 |
7 | );
8 |
9 | export default MarkAllAsUnpacked;
10 |
--------------------------------------------------------------------------------
/src/components/new-item.js:
--------------------------------------------------------------------------------
1 | const NewItem = ({ newItemName, setNewItemName, addItem }) => {
2 | return (
3 |
34 | );
35 | };
36 |
37 | export default NewItem;
38 |
--------------------------------------------------------------------------------
/src/global.d.ts:
--------------------------------------------------------------------------------
1 | type ReturnTypes = U extends () => any ? ReturnType : never;
2 |
3 | type Item = {
4 | id: string;
5 | name: string;
6 | packed: boolean;
7 | };
8 |
--------------------------------------------------------------------------------
/src/index.css:
--------------------------------------------------------------------------------
1 | @tailwind base;
2 | @tailwind components;
3 | @tailwind utilities;
4 |
5 | *,
6 | html,
7 | body {
8 | @apply box-border;
9 | }
10 |
11 | html,
12 | body {
13 | @apply m-0 h-screen w-screen p-0;
14 | }
15 |
16 | #root {
17 | @apply h-screen w-screen;
18 | }
19 |
20 | h1,
21 | h2,
22 | h3,
23 | h4,
24 | h5,
25 | h6 {
26 | @apply font-bold leading-tight first:mt-0;
27 | }
28 |
29 | h1 {
30 | @apply text-4xl leading-tight;
31 | }
32 |
33 | h2 {
34 | @apply text-3xl;
35 | }
36 |
37 | h3 {
38 | @apply text-2xl;
39 | }
40 |
41 | h4 {
42 | @apply text-xl;
43 | }
44 |
45 | h5 {
46 | @apply text-lg;
47 | }
48 |
49 | h6 {
50 | @apply text-base;
51 | }
52 |
53 | p,
54 | ul,
55 | ol,
56 | dl {
57 | @apply mb-4 leading-relaxed;
58 | }
59 |
60 | input {
61 | @apply rounded-sm border-2 border-primary-700 bg-primary-100 p-2 placeholder-primary-400 accent-primary-600 shadow-sm transition-all ease-in invalid:border-red-800 invalid:bg-red-200 out-of-range:border-red-800 out-of-range:bg-red-200 hover:bg-primary-200 hover:accent-primary-700 focus:bg-primary-50 focus:outline-none disabled:border-slate-500 disabled:bg-slate-100 disabled:placeholder-slate-400;
62 | }
63 |
64 | button,
65 | button[type='button'],
66 | button[type='reset'],
67 | button[type='submit'] input[type='button'],
68 | input[type='submit'],
69 | input[type='reset'] {
70 | @apply inline-flex items-center justify-center border-2 border-primary-700 bg-primary-100 px-4 py-2 transition-colors ease-in hover:bg-primary-200 active:bg-primary-300;
71 | }
72 |
73 | input[type='checkbox'],
74 | input[type='radio'] {
75 | @apply hover:accent-primary-700;
76 | }
77 |
78 | input[type='range'] {
79 | @apply h-2 w-full cursor-pointer appearance-none rounded-lg bg-primary-100;
80 | }
81 |
82 | input[type='submit'],
83 | button[type='submit'] {
84 | @apply bg-primary-500 font-semibold text-white hover:bg-primary-600 active:bg-primary-700;
85 | }
86 |
87 | input[type='color'] {
88 | @apply h-12 p-1;
89 | }
90 |
91 | input[type='file']::-webkit-file-upload-button {
92 | @apply placeholder-red-400 accent-red-800;
93 | }
94 |
95 | input[type='date'],
96 | input[type='datetime'],
97 | input[type='datetime-local'],
98 | input[type='month'],
99 | input[type='week'],
100 | input[type='time'] {
101 | @apply text-primary-900;
102 | }
103 |
104 | label {
105 | @apply font-normal;
106 | }
107 |
108 | input:checked + label {
109 | @apply pl-2 font-semibold text-primary-900 transition-colors hover:text-primary-800;
110 | }
111 |
112 | select {
113 | @apply block w-full rounded border-2 border-purple-700 px-4 py-2 pr-8 shadow hover:bg-primary-200 hover:accent-primary-700 focus:bg-primary-50 focus:outline-none disabled:border-slate-500 disabled:bg-slate-100 disabled:placeholder-slate-400;
114 | }
115 |
--------------------------------------------------------------------------------
/src/index.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import ReactDOM from 'react-dom/client';
3 | import Application from './components/application';
4 |
5 | import './index.css';
6 |
7 | const root = ReactDOM.createRoot(document.getElementById('root'));
8 |
9 | root.render(
10 |
11 |
12 | ,
13 | );
14 |
--------------------------------------------------------------------------------
/src/lib/api.ts:
--------------------------------------------------------------------------------
1 | import { getInitialItems } from './items';
2 | import { sleep } from './slow-down';
3 |
4 | const delay = 2000;
5 | let items = getInitialItems();
6 |
7 | export const fetchItems = async () => {
8 | await sleep(delay);
9 | return items;
10 | };
11 |
12 | export const deleteItem = async (id: string) => {
13 | await sleep(delay);
14 | items = items.filter((item) => item.id !== id);
15 | return items;
16 | };
17 |
18 | export const patchItem = async (id: string, packed: boolean) => {
19 | await sleep(delay);
20 |
21 | let matchingItem: Item | undefined;
22 |
23 | items.map((item) => {
24 | if (item.id !== id) return item;
25 | matchingItem = {
26 | ...item,
27 | packed,
28 | };
29 | return matchingItem;
30 | });
31 |
32 | if (!matchingItem) {
33 | throw new Error(`There is no item with the id of "${id}."`);
34 | }
35 |
36 | return matchingItem;
37 | };
38 |
--------------------------------------------------------------------------------
/src/lib/items.test.ts:
--------------------------------------------------------------------------------
1 | import { filterItems, removeItem, updateItem } from './items';
2 |
3 | const items: Item[] = [
4 | { id: '1', name: 'Phone', packed: true },
5 | { id: '2', name: 'Wallet', packed: false },
6 | { id: '3', name: 'Keys', packed: false },
7 | ];
8 |
9 | describe('updateItem', () => {
10 | it('should change the name of an item', () => {
11 | const expected = 'iPhone';
12 | const results = updateItem(items, '1', { name: expected });
13 | expect(results).toEqual([
14 | { id: '1', name: expected, packed: true },
15 | { id: '2', name: 'Wallet', packed: false },
16 | { id: '3', name: 'Keys', packed: false },
17 | ]);
18 | });
19 |
20 | it('should change the status of an item', () => {
21 | const expected = true;
22 | const results = updateItem(items, '2', { packed: expected });
23 | expect(results).toEqual([
24 | { id: '1', name: 'Phone', packed: true },
25 | { id: '2', name: 'Wallet', packed: expected },
26 | { id: '3', name: 'Keys', packed: false },
27 | ]);
28 | });
29 |
30 | it('should change multiple properties of an item', () => {
31 | const expected = { packed: true, name: 'Hoodie' };
32 | const results = updateItem(items, '2', { ...expected });
33 | expect(results).toEqual([
34 | { id: '1', name: 'Phone', packed: true },
35 | { id: '2', name: expected.name, packed: expected.packed },
36 | { id: '3', name: 'Keys', packed: false },
37 | ]);
38 | });
39 | });
40 |
41 | describe('removeItems', () => {
42 | it('should remove an item by its ID', () => {
43 | expect(removeItem(items, '2')).toEqual([
44 | { id: '1', name: 'Phone', packed: true },
45 | { id: '3', name: 'Keys', packed: false },
46 | ]);
47 | });
48 | });
49 |
50 | describe('filterItems', () => {
51 | it('should filter by name', () => {
52 | const filter = { name: 'P' };
53 | const result = filterItems(items, filter);
54 | expect(result).toEqual([{ id: '1', name: 'Phone', packed: true }]);
55 | });
56 |
57 | it('should filter by status', () => {
58 | const filter = { packed: true };
59 | const result = filterItems(items, filter);
60 | expect(result).toEqual([{ id: '1', name: 'Phone', packed: true }]);
61 | });
62 |
63 | it('should filter by name and status', () => {
64 | const filter = { name: 'W', packed: false };
65 | const result = filterItems(items, filter);
66 | expect(result).toEqual([{ id: '2', name: 'Wallet', packed: false }]);
67 | });
68 | });
69 |
--------------------------------------------------------------------------------
/src/lib/items.ts:
--------------------------------------------------------------------------------
1 | import { v4 as id } from 'uuid';
2 |
3 | export const createItem = (name: string): Item => {
4 | return {
5 | id: id(),
6 | name,
7 | packed: false,
8 | };
9 | };
10 |
11 | let items = [
12 | 'Sweatshirt',
13 | 'Running shoes',
14 | 'AirPods',
15 | 'MacBook',
16 | 'iPad',
17 | 'USB-C cable',
18 | 'Lightning cable',
19 | 'Wallet',
20 | 'MagSafe cable',
21 | 'Apple Watch charger',
22 | 'Power brick',
23 | 'Toothbrush',
24 | 'Toothpaste',
25 | 'Deorderant',
26 | 'Backpack',
27 | 'Vitamins',
28 | 'Kindle',
29 | 'Micro-USB cable',
30 | 'Sleep mask',
31 | 'Ear plugs',
32 | 'Face masks',
33 | 'Sony Walkman',
34 | 'Emergency Vegan Bacon',
35 | ].map(createItem);
36 |
37 | const [first, second] = items;
38 |
39 | first.packed = true;
40 | second.packed = true;
41 |
42 | export const getInitialItems = (): Item[] => {
43 | return items;
44 | };
45 |
46 | export const updateItem = (
47 | items: Item[],
48 | id: string,
49 | updates: Partial- ,
50 | ) => {
51 | return items.map((item) => {
52 | if (item.id === id) return { ...item, ...updates };
53 | return item;
54 | });
55 | };
56 |
57 | export const removeItem = (items: Readonly
- , id: string) => {
58 | return items.filter((item) => {
59 | return item.id !== id;
60 | });
61 | };
62 |
63 | export const filterItems = (
64 | items: Item[] = [],
65 | properties: Readonly>,
66 | ) => {
67 | return items.filter((item) => {
68 | for (const [filterKey, filterValue] of Object.entries(properties)) {
69 | if (filterKey === 'name' && typeof filterValue === 'string') {
70 | return item.name.toLowerCase().startsWith(filterValue.toLowerCase());
71 | }
72 |
73 | if (filterKey === 'packed' && typeof filterValue === 'boolean') {
74 | return item.packed === filterValue;
75 | }
76 | }
77 | return false;
78 | });
79 | };
80 |
--------------------------------------------------------------------------------
/src/lib/kebab-case.ts:
--------------------------------------------------------------------------------
1 | export const toKebabCase = (s: string): string => {
2 | return s.toLowerCase().replace(/\s/g, '-');
3 | };
4 |
--------------------------------------------------------------------------------
/src/lib/normalize.test.ts:
--------------------------------------------------------------------------------
1 | import { normalize, normalizeWithSeparateLists } from './normalize';
2 |
3 | const items = [
4 | { id: '1', name: 'A Thing', packed: true },
5 | { id: '2', name: 'Another Thing', packed: true },
6 | { id: '3', name: 'Still Another Thing', packed: false },
7 | ];
8 |
9 | describe(normalize, () => {
10 | it('should normalize an array of items', () => {
11 | expect(normalize(items)).toEqual({
12 | ids: ['1', '2', '3'],
13 | items: {
14 | 1: {
15 | id: '1',
16 | name: 'A Thing',
17 | packed: true,
18 | },
19 | 2: {
20 | id: '2',
21 | name: 'Another Thing',
22 | packed: true,
23 | },
24 | 3: {
25 | id: '3',
26 | name: 'Still Another Thing',
27 | packed: false,
28 | },
29 | },
30 | });
31 | });
32 | });
33 |
34 | describe(normalizeWithSeparateLists, () => {
35 | it('should normalize but distinguish between packed and unpacked lists', () => {
36 | expect(normalizeWithSeparateLists(items)).toEqual({
37 | ids: ['1', '2', '3'],
38 | items: {
39 | 1: {
40 | id: '1',
41 | name: 'A Thing',
42 | packed: true,
43 | },
44 | 2: {
45 | id: '2',
46 | name: 'Another Thing',
47 | packed: true,
48 | },
49 | 3: {
50 | id: '3',
51 | name: 'Still Another Thing',
52 | packed: false,
53 | },
54 | },
55 | packedItemIds: ['1', '2'],
56 | unpackedItemIds: ['3'],
57 | });
58 | });
59 | });
60 |
--------------------------------------------------------------------------------
/src/lib/normalize.ts:
--------------------------------------------------------------------------------
1 | type NormalizedState = {
2 | items: { [key: string]: Item };
3 | ids: string[];
4 | };
5 |
6 | export const normalize = (state: Item[]): NormalizedState => {
7 | if (!Array.isArray(state)) {
8 | console.error('[normalize] Expecting an array, but received:', state);
9 | return state;
10 | }
11 |
12 | const ids = [];
13 | const items: NormalizedState['items'] = {};
14 |
15 | for (const item of state) {
16 | const { id } = item;
17 | ids.push(id);
18 | items[id] = item;
19 | }
20 |
21 | return { items, ids };
22 | };
23 |
24 | export const normalizeWithSeparateLists = (state: Item[] | NormalizedState) => {
25 | if (Array.isArray(state)) state = normalize(state);
26 |
27 | const { items } = state;
28 | const unpackedItemIds = [];
29 | const packedItemIds = [];
30 |
31 | for (const item of Object.values(items)) {
32 | if (item.packed) {
33 | packedItemIds.push(item.id);
34 | } else {
35 | unpackedItemIds.push(item.id);
36 | }
37 | }
38 |
39 | return {
40 | ...state,
41 | unpackedItemIds,
42 | packedItemIds,
43 | };
44 | };
45 |
--------------------------------------------------------------------------------
/src/lib/reducer.test.ts:
--------------------------------------------------------------------------------
1 | import { add, markAllAsUnpacked, reducer, remove, update } from './reducer';
2 |
3 | jest.mock('uuid', () => ({ v4: () => '123456789' }));
4 |
5 | const id = '1';
6 | const name = 'Sweatshirt';
7 |
8 | describe(reducer, () => {
9 | it('should add an item', () => {
10 | const result = reducer([], add(name));
11 | expect(result).toEqual([
12 | {
13 | id: '123456789',
14 | name,
15 | packed: false,
16 | },
17 | ]);
18 | });
19 |
20 | it('should update an item', () => {
21 | const result = reducer(
22 | [{ id, name, packed: false }],
23 | update(id, { packed: true }),
24 | );
25 |
26 | expect(result).toEqual([
27 | {
28 | id,
29 | name,
30 | packed: true,
31 | },
32 | ]);
33 | });
34 |
35 | it('should remove an item', () => {
36 | const items = [{ id, name, packed: false }];
37 | const result = reducer(items, remove(id));
38 | expect(result).toEqual([]);
39 | });
40 |
41 | it('should mark all items as unpacked', () => {
42 | const items = [
43 | { id: '1', name: 'Sweatshirt', packed: true },
44 | { id: '2', name: 'Sony Walkman', packed: true },
45 | ];
46 |
47 | const result = reducer(items, markAllAsUnpacked());
48 |
49 | expect(result).toEqual([
50 | { id: '1', name: 'Sweatshirt', packed: false },
51 | { id: '2', name: 'Sony Walkman', packed: false },
52 | ]);
53 | });
54 | });
55 |
--------------------------------------------------------------------------------
/src/lib/reducer.ts:
--------------------------------------------------------------------------------
1 | import { createAction } from '@reduxjs/toolkit';
2 | import { createItem, removeItem, updateItem } from './items';
3 |
4 | export const add = createAction('items/add', (name: string) => ({
5 | payload: { name },
6 | }));
7 |
8 | export const update = createAction(
9 | 'items/update',
10 | (id: string, properties: Partial
- ) => {
11 | return { payload: { id, ...properties } };
12 | },
13 | );
14 |
15 | export const remove = createAction('items/remove', (id: string) => ({
16 | payload: { id },
17 | }));
18 |
19 | export const markAllAsUnpacked = createAction('items/mark-all-as-unpacked');
20 |
21 | export type Action =
22 | | ReturnType
23 | | ReturnType
24 | | ReturnType
25 | | ReturnType;
26 |
27 | export const reducer = (items: Item[] = [], action: Action) => {
28 | if (action.type === add.type) {
29 | const item = createItem(action.payload.name);
30 | return [...items, item];
31 | }
32 |
33 | if (action.type === update.type) {
34 | const { id, ...properties } = action.payload;
35 | return updateItem(items, id, properties);
36 | }
37 |
38 | if (action.type === remove.type) {
39 | return removeItem(items, action.payload.id);
40 | }
41 |
42 | if (action.type === markAllAsUnpacked.type) {
43 | return items.map((item) => ({ ...item, packed: false }));
44 | }
45 |
46 | return items;
47 | };
48 |
--------------------------------------------------------------------------------
/src/lib/slow-down.ts:
--------------------------------------------------------------------------------
1 | export const sleep = (delay = 2000) => {
2 | return new Promise((resolve) => {
3 | setTimeout(() => {
4 | resolve(undefined);
5 | }, delay);
6 | });
7 | };
8 |
9 | export const block = (duration = 500) => {
10 | const start = performance.now();
11 | while (performance.now() < start + duration) {}
12 | };
13 |
14 | export const makeExpensive = any>(
15 | fn: F,
16 | duration = 0,
17 | ) => {
18 | return (...args: Parameters): ReturnType => {
19 | block(duration);
20 | return fn(...args);
21 | };
22 | };
23 |
--------------------------------------------------------------------------------
/tailwind.config.js:
--------------------------------------------------------------------------------
1 | /** @type {import('tailwindcss').Config} */
2 |
3 | const colors = require('tailwindcss/colors');
4 |
5 | module.exports = {
6 | content: ['./src/**/*.{js,jsx,ts,tsx}'],
7 | theme: {
8 | extend: {
9 | colors: { ...colors, primary: colors.purple },
10 | },
11 | },
12 | plugins: [],
13 | };
14 |
--------------------------------------------------------------------------------
/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | "target": "es5",
4 | "lib": ["dom", "dom.iterable", "esnext"],
5 | "allowJs": true,
6 | "skipLibCheck": true,
7 | "esModuleInterop": true,
8 | "allowSyntheticDefaultImports": true,
9 | "strict": true,
10 | "forceConsistentCasingInFileNames": true,
11 | "noFallthroughCasesInSwitch": true,
12 | "module": "esnext",
13 | "moduleResolution": "node",
14 | "resolveJsonModule": true,
15 | "isolatedModules": true,
16 | "noEmit": true,
17 | "jsx": "react-jsx"
18 | },
19 | "include": ["src"]
20 | }
21 |
--------------------------------------------------------------------------------