├── .gitignore ├── .nvmrc ├── .prettierignore ├── .prettierrc.js ├── CODE_OF_CONDUCT.md ├── Dockerfile ├── LICENSE ├── README.md ├── credentials.js ├── docker-compose.yml ├── notes └── .gitkeep ├── package-lock.json ├── package.json ├── public ├── checkmark.svg ├── chevron-down.svg ├── chevron-up.svg ├── cross.svg ├── favicon.ico ├── index.html ├── logo.svg └── style.css ├── scripts ├── build.js ├── init_db.sh └── seed.js ├── server ├── api.server.js └── package.json └── src ├── App.js ├── EditButton.js ├── Note.js ├── NoteEditor.js ├── NoteList.js ├── NoteListSkeleton.js ├── NotePreview.js ├── NoteSkeleton.js ├── SearchField.js ├── SidebarNote.js ├── SidebarNoteContent.js ├── Spinner.js ├── TextWithMarkdown.js ├── db.js └── framework ├── bootstrap.js └── router.js /.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 | /dist 14 | 15 | # notes 16 | notes/*.md 17 | 18 | # misc 19 | .DS_Store 20 | .eslintcache 21 | .env 22 | .env.local 23 | .env.development.local 24 | .env.test.local 25 | .env.production.local 26 | 27 | npm-debug.log* 28 | yarn-debug.log* 29 | yarn-error.log* 30 | 31 | # vscode 32 | .vscode 33 | -------------------------------------------------------------------------------- /.nvmrc: -------------------------------------------------------------------------------- 1 | lts/hydrogen -------------------------------------------------------------------------------- /.prettierignore: -------------------------------------------------------------------------------- 1 | # dependencies 2 | /node_modules 3 | /.pnp 4 | .pnp.js 5 | 6 | # testing 7 | /coverage 8 | 9 | # production 10 | /build 11 | /dist 12 | 13 | # misc 14 | .DS_Store 15 | .eslintcache 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 | 25 | *.html 26 | *.json 27 | *.md 28 | -------------------------------------------------------------------------------- /.prettierrc.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) Facebook, Inc. and its affiliates. 3 | * 4 | * This source code is licensed under the MIT license found in the 5 | * LICENSE file in the root directory of this source tree. 6 | * 7 | */ 8 | 9 | 'use strict'; 10 | 11 | module.exports = { 12 | arrowParens: 'always', 13 | bracketSpacing: false, 14 | singleQuote: true, 15 | jsxBracketSameLine: true, 16 | trailingComma: 'es5', 17 | printWidth: 80, 18 | }; 19 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as 6 | contributors and maintainers pledge to make participation in our project and 7 | our community a harassment-free experience for everyone, regardless of age, body 8 | size, disability, ethnicity, sex characteristics, gender identity and expression, 9 | level of experience, education, socio-economic status, nationality, personal 10 | appearance, race, religion, or sexual identity and orientation. 11 | 12 | ## Our Standards 13 | 14 | Examples of behavior that contributes to creating a positive environment 15 | include: 16 | 17 | * Using welcoming and inclusive language 18 | * Being respectful of differing viewpoints and experiences 19 | * Gracefully accepting constructive criticism 20 | * Focusing on what is best for the community 21 | * Showing empathy towards other community members 22 | 23 | Examples of unacceptable behavior by participants include: 24 | 25 | * The use of sexualized language or imagery and unwelcome sexual attention or 26 | advances 27 | * Trolling, insulting/derogatory comments, and personal or political attacks 28 | * Public or private harassment 29 | * Publishing others' private information, such as a physical or electronic 30 | address, without explicit permission 31 | * Other conduct which could reasonably be considered inappropriate in a 32 | professional setting 33 | 34 | ## Our Responsibilities 35 | 36 | Project maintainers are responsible for clarifying the standards of acceptable 37 | behavior and are expected to take appropriate and fair corrective action in 38 | response to any instances of unacceptable behavior. 39 | 40 | Project maintainers have the right and responsibility to remove, edit, or 41 | reject comments, commits, code, wiki edits, issues, and other contributions 42 | that are not aligned to this Code of Conduct, or to ban temporarily or 43 | permanently any contributor for other behaviors that they deem inappropriate, 44 | threatening, offensive, or harmful. 45 | 46 | ## Scope 47 | 48 | This Code of Conduct applies within all project spaces, and it also applies when 49 | an individual is representing the project or its community in public spaces. 50 | Examples of representing a project or community include using an official 51 | project e-mail address, posting via an official social media account, or acting 52 | as an appointed representative at an online or offline event. Representation of 53 | a project may be further defined and clarified by project maintainers. 54 | 55 | ## Enforcement 56 | 57 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 58 | reported by contacting the project team at . All 59 | complaints will be reviewed and investigated and will result in a response that 60 | is deemed necessary and appropriate to the circumstances. The project team is 61 | obligated to maintain confidentiality with regard to the reporter of an incident. 62 | Further details of specific enforcement policies may be posted separately. 63 | 64 | Project maintainers who do not follow or enforce the Code of Conduct in good 65 | faith may face temporary or permanent repercussions as determined by other 66 | members of the project's leadership. 67 | 68 | ## Attribution 69 | 70 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, 71 | available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html 72 | 73 | [homepage]: https://www.contributor-covenant.org 74 | 75 | For answers to common questions about this code of conduct, see 76 | https://www.contributor-covenant.org/faq 77 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM node:lts-hydrogen 2 | 3 | WORKDIR /opt/notes-app 4 | 5 | COPY package.json package-lock.json ./ 6 | 7 | RUN npm install --legacy-peer-deps 8 | 9 | COPY . . 10 | 11 | ENTRYPOINT [ "npm", "run" ] 12 | CMD [ "start" ] 13 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) Facebook, Inc. and its affiliates. 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # React Server Components Demo 2 | 3 | * [What is this?](#what-is-this) 4 | * [When will I be able to use this?](#when-will-i-be-able-to-use-this) 5 | * [Should I use this demo for benchmarks?](#should-i-use-this-demo-for-benchmarks) 6 | * [Setup](#setup) 7 | * [DB Setup](#db-setup) 8 | + [Step 1. Create the Database](#step-1-create-the-database) 9 | + [Step 2. Connect to the Database](#step-2-connect-to-the-database) 10 | + [Step 3. Run the seed script](#step-3-run-the-seed-script) 11 | * [Notes about this app](#notes-about-this-app) 12 | + [Interesting things to try](#interesting-things-to-try) 13 | * [Built by (A-Z)](#built-by-a-z) 14 | * [Code of Conduct](#code-of-conduct) 15 | * [License](#license) 16 | 17 | ## What is this? 18 | 19 | This is a demo app built with Server Components, an experimental React feature. **We strongly recommend [watching our talk introducing Server Components](https://reactjs.org/server-components) before exploring this demo.** The talk includes a walkthrough of the demo code and highlights key points of how Server Components work and what features they provide. 20 | 21 | **Update (March 2023):** This demo has been updated to match the [latest conventions](https://react.dev/blog/2023/03/22/react-labs-what-we-have-been-working-on-march-2023#react-server-components). 22 | 23 | ## When will I be able to use this? 24 | 25 | Server Components are an experimental feature and **are not ready for adoption**. For now, we recommend experimenting with Server Components via this demo app. **Use this in your projects at your own risk.** 26 | 27 | ## Should I use this demo for benchmarks? 28 | 29 | If you use this demo to compare React Server Components to the framework of your choice, keep this in mind: 30 | 31 | * **This demo doesn’t have server rendering.** Server Components are a separate (but complementary) technology from Server Rendering (SSR). Server Components let you run some of your components purely on the server. SSR, on the other hand, lets you generate HTML before any JavaScript loads. This demo *only* shows Server Components, and not SSR. Because it doesn't have SSR, the initial page load in this demo has a client-server network waterfall, and **will be much slower than any SSR framework**. However, Server Components are meant to be integrated together with SSR, and they *will* be in a future release. 32 | * **This demo doesn’t have an efficient bundling strategy.** When you use Server Components, a bundler plugin will automatically split the client JS bundle. However, the way it's currently being split is not necessarily optimal. We are investigating more efficient ways to split the bundles, but they are out of scope of this demo. 33 | * **This demo doesn’t have partial refetching.** Currently, when you click on different “notes”, the entire app shell is refetched from the server. However, that’s not ideal: for example, it’s unnecessary to refetch the sidebar content if all that changed is the inner content of the right pane. Partial refetching is an [open area of research](https://github.com/reactjs/rfcs/blob/main/text/0188-server-components.md#open-areas-of-research) and we don’t yet know how exactly it will work. 34 | 35 | This demo is provided “as is” to show the parts that are ready for experimentation. It is not intended to reflect the performance characteristics of a real app driven by a future stable release of Server Components. 36 | 37 | ## Setup 38 | 39 | You will need to have [Node 18 LTS](https://nodejs.org/en) in order to run this demo. (If you use `nvm`, run `nvm i` before running `npm install` to install the recommended Node version.) 40 | 41 | ``` 42 | npm install --legacy-peer-deps 43 | npm start 44 | ``` 45 | 46 | (Or `npm run start:prod` for a production build.) 47 | 48 | Then open http://localhost:4000. 49 | 50 | The app won't work until you set up the database, as described below. 51 | 52 |
53 | Setup with Docker (optional) 54 |

You can also start dev build of the app by using docker-compose.

55 |

⚠️ This is completely optional, and is only for people who prefer Docker to global installs!

56 |

If you prefer Docker, make sure you have docker and docker-compose installed then run:

57 |
docker-compose up
58 |

Running seed script

59 |

1. Run containers in the detached mode

60 |
docker-compose up -d
61 |

2. Run seed script

62 |
docker-compose exec notes-app npm run seed
63 |

If you'd rather not use Docker, skip this section and continue below.

64 |
65 | 66 | ## DB Setup 67 | 68 | This demo uses Postgres. First, follow its [installation link](https://wiki.postgresql.org/wiki/Detailed_installation_guides) for your platform. 69 | 70 | Alternatively, you can check out this [fork](https://github.com/pomber/server-components-demo/) which will let you run the demo app without needing a database. However, you won't be able to execute SQL queries (but fetch should still work). There is also [another fork](https://github.com/prisma/server-components-demo) that uses Prisma with SQLite, so it doesn't require additional setup. 71 | 72 | The below example will set up the database for this app, assuming that you have a UNIX-like platform: 73 | 74 | ### Step 1. Create the Database 75 | 76 | ``` 77 | psql postgres 78 | 79 | CREATE DATABASE notesapi; 80 | CREATE ROLE notesadmin WITH LOGIN PASSWORD 'password'; 81 | ALTER ROLE notesadmin WITH SUPERUSER; 82 | ALTER DATABASE notesapi OWNER TO notesadmin; 83 | \q 84 | ``` 85 | 86 | ### Step 2. Connect to the Database 87 | 88 | ``` 89 | psql -d postgres -U notesadmin; 90 | 91 | \c notesapi 92 | 93 | DROP TABLE IF EXISTS notes; 94 | CREATE TABLE notes ( 95 | id SERIAL PRIMARY KEY, 96 | created_at TIMESTAMP NOT NULL, 97 | updated_at TIMESTAMP NOT NULL, 98 | title TEXT, 99 | body TEXT 100 | ); 101 | 102 | \q 103 | ``` 104 | 105 | ### Step 3. Run the seed script 106 | 107 | Finally, run `npm run seed` to populate some data. 108 | 109 | And you're done! 110 | 111 | ## Notes about this app 112 | 113 | The demo is a note-taking app called **React Notes**. It consists of a few major parts: 114 | 115 | - It uses a Webpack plugin (not defined in this repo) that allows us to only include client components in build artifacts 116 | - An Express server that: 117 | - Serves API endpoints used in the app 118 | - Renders Server Components into a special format that we can read on the client 119 | - A React app containing Server and Client components used to build React Notes 120 | 121 | This demo is built on top of our Webpack plugin, but this is not how we envision using Server Components when they are stable. They are intended to be used in a framework that supports server rendering — for example, in Next.js. This is an early demo -- the real integration will be developed in the coming months. Learn more in the [announcement post](https://reactjs.org/server-components). 122 | 123 | ### Interesting things to try 124 | 125 | - Expand note(s) by hovering over the note in the sidebar, and clicking the expand/collapse toggle. Next, create or delete a note. What happens to the expanded notes? 126 | - Change a note's title while editing, and notice how editing an existing item animates in the sidebar. What happens if you edit a note in the middle of the list? 127 | - Search for any title. With the search text still in the search input, create a new note with a title matching the search text. What happens? 128 | - Search while on Slow 3G, observe the inline loading indicator. 129 | - Switch between two notes back and forth. Observe we don't send new responses next time we switch them again. 130 | - Uncomment the `await fetch('http://localhost:4000/sleep/....')` call in `Note.js` or `NoteList.js` to introduce an artificial delay and trigger Suspense. 131 | - If you only uncomment it in `Note.js`, you'll see the fallback every time you open a note. 132 | - If you only uncomment it in `NoteList.js`, you'll see the list fallback on first page load. 133 | - If you uncomment it in both, it won't be very interesting because we have nothing new to show until they both respond. 134 | - Add a new Server Component and place it above the search bar in `App.js`. Import `db` from `db.js` and use `await db.query()` from it to get the number of notes. Oberserve what happens when you add or delete a note. 135 | 136 | You can watch a [recorded walkthrough of all these demo points here](https://youtu.be/La4agIEgoNg?t=600) with timestamps. (**Note:** this recording is slightly outdated because the repository has been updated to match the [latest conventions](https://react.dev/blog/2023/03/22/react-labs-what-we-have-been-working-on-march-2023#react-server-components).) 137 | 138 | ## Built by (A-Z) 139 | 140 | - [Andrew Clark](https://twitter.com/acdlite) 141 | - [Dan Abramov](https://twitter.com/dan_abramov) 142 | - [Joe Savona](https://twitter.com/en_JS) 143 | - [Lauren Tan](https://twitter.com/sugarpirate_) 144 | - [Sebastian Markbåge](https://twitter.com/sebmarkbage) 145 | - [Tate Strickland](http://www.tatestrickland.com/) (Design) 146 | 147 | ## [Code of Conduct](https://engineering.fb.com/codeofconduct/) 148 | Facebook has adopted a Code of Conduct that we expect project participants to adhere to. Please read the [full text](https://engineering.fb.com/codeofconduct/) so that you can understand what actions will and will not be tolerated. 149 | 150 | ## License 151 | This demo is MIT licensed. 152 | -------------------------------------------------------------------------------- /credentials.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | host: process.env.DB_HOST || 'localhost', 3 | database: 'notesapi', 4 | user: 'notesadmin', 5 | password: 'password', 6 | port: '5432', 7 | }; 8 | -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: "3.8" 2 | services: 3 | postgres: 4 | image: postgres:13 5 | environment: 6 | POSTGRES_USER: notesadmin 7 | POSTGRES_PASSWORD: password 8 | POSTGRES_DB: notesapi 9 | ports: 10 | - '5432:5432' 11 | volumes: 12 | - ./scripts/init_db.sh:/docker-entrypoint-initdb.d/init_db.sh 13 | - db:/var/lib/postgresql/data 14 | 15 | notes-app: 16 | build: 17 | context: . 18 | depends_on: 19 | - postgres 20 | ports: 21 | - '4000:4000' 22 | environment: 23 | DB_HOST: postgres 24 | PORT: 4000 25 | volumes: 26 | - ./notes:/opt/notes-app/notes 27 | - ./public:/opt/notes-app/public 28 | - ./scripts:/opt/notes-app/scripts 29 | - ./server:/opt/notes-app/server 30 | - ./src:/opt/notes-app/src 31 | - ./credentials.js:/opt/notes-app/credentials.js 32 | 33 | volumes: 34 | db: 35 | -------------------------------------------------------------------------------- /notes/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/reactjs/server-components-demo/95fcac10102d20722af60506af3b785b557c5fd7/notes/.gitkeep -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "react-notes", 3 | "version": "0.1.0", 4 | "private": true, 5 | "engines": { 6 | "node": ">=14.9.0" 7 | }, 8 | "license": "MIT", 9 | "dependencies": { 10 | "@babel/core": "7.21.3", 11 | "@babel/plugin-transform-modules-commonjs": "^7.21.2", 12 | "@babel/preset-react": "^7.18.6", 13 | "@babel/register": "^7.21.0", 14 | "acorn-jsx": "^5.3.2", 15 | "acorn-loose": "^8.3.0", 16 | "babel-loader": "8.3.0", 17 | "compression": "^1.7.4", 18 | "concurrently": "^7.6.0", 19 | "date-fns": "^2.29.3", 20 | "excerpts": "^0.0.3", 21 | "express": "^4.18.2", 22 | "html-webpack-plugin": "5.5.0", 23 | "marked": "^4.2.12", 24 | "nodemon": "^2.0.21", 25 | "pg": "^8.10.0", 26 | "react": "18.3.0-next-1308e49a6-20230330", 27 | "react-dom": "18.3.0-next-1308e49a6-20230330", 28 | "react-error-boundary": "^3.1.4", 29 | "react-server-dom-webpack": "18.3.0-next-1308e49a6-20230330", 30 | "resolve": "1.22.1", 31 | "rimraf": "^4.4.0", 32 | "sanitize-html": "^2.10.0", 33 | "server-only": "^0.0.1", 34 | "webpack": "5.76.2" 35 | }, 36 | "devDependencies": { 37 | "cross-env": "^7.0.3", 38 | "prettier": "1.19.1" 39 | }, 40 | "scripts": { 41 | "start": "concurrently \"npm run server:dev\" \"npm run bundler:dev\"", 42 | "start:prod": "concurrently \"npm run server:prod\" \"npm run bundler:prod\"", 43 | "server:dev": "cross-env NODE_ENV=development nodemon -- --conditions=react-server server", 44 | "server:prod": "cross-env NODE_ENV=production nodemon -- --conditions=react-server server", 45 | "bundler:dev": "cross-env NODE_ENV=development nodemon -- scripts/build.js", 46 | "bundler:prod": "cross-env NODE_ENV=production nodemon -- scripts/build.js", 47 | "prettier": "prettier --write **/*.js", 48 | "seed": "node ./scripts/seed.js" 49 | }, 50 | "babel": { 51 | "presets": [ 52 | [ 53 | "@babel/preset-react", 54 | { 55 | "runtime": "automatic" 56 | } 57 | ] 58 | ] 59 | }, 60 | "nodemonConfig": { 61 | "ignore": [ 62 | "build/*" 63 | ] 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /public/checkmark.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /public/chevron-down.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /public/chevron-up.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /public/cross.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/reactjs/server-components-demo/95fcac10102d20722af60506af3b785b557c5fd7/public/favicon.ico -------------------------------------------------------------------------------- /public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | React Notes 9 | 10 | 11 |
12 | 31 | 32 | 33 | -------------------------------------------------------------------------------- /public/logo.svg: -------------------------------------------------------------------------------- 1 | 2 | React Logo 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /public/style.css: -------------------------------------------------------------------------------- 1 | /* -------------------------------- CSSRESET --------------------------------*/ 2 | /* CSS Reset adapted from https://dev.to/hankchizljaw/a-modern-css-reset-6p3 */ 3 | /* Box sizing rules */ 4 | *, 5 | *::before, 6 | *::after { 7 | box-sizing: border-box; 8 | } 9 | 10 | /* Remove default padding */ 11 | ul[class], 12 | ol[class] { 13 | padding: 0; 14 | } 15 | 16 | /* Remove default margin */ 17 | body, 18 | h1, 19 | h2, 20 | h3, 21 | h4, 22 | p, 23 | ul[class], 24 | ol[class], 25 | li, 26 | figure, 27 | figcaption, 28 | blockquote, 29 | dl, 30 | dd { 31 | margin: 0; 32 | } 33 | 34 | /* Set core body defaults */ 35 | body { 36 | min-height: 100vh; 37 | scroll-behavior: smooth; 38 | text-rendering: optimizeSpeed; 39 | line-height: 1.5; 40 | } 41 | 42 | /* Remove list styles on ul, ol elements with a class attribute */ 43 | ul[class], 44 | ol[class] { 45 | list-style: none; 46 | } 47 | 48 | /* A elements that don't have a class get default styles */ 49 | a:not([class]) { 50 | text-decoration-skip-ink: auto; 51 | } 52 | 53 | /* Make images easier to work with */ 54 | img { 55 | max-width: 100%; 56 | display: block; 57 | } 58 | 59 | /* Natural flow and rhythm in articles by default */ 60 | article > * + * { 61 | margin-block-start: 1em; 62 | } 63 | 64 | /* Inherit fonts for inputs and buttons */ 65 | input, 66 | button, 67 | textarea, 68 | select { 69 | font: inherit; 70 | } 71 | 72 | /* Remove all animations and transitions for people that prefer not to see them */ 73 | @media (prefers-reduced-motion: reduce) { 74 | * { 75 | animation-duration: 0.01ms !important; 76 | animation-iteration-count: 1 !important; 77 | transition-duration: 0.01ms !important; 78 | scroll-behavior: auto !important; 79 | } 80 | } 81 | /* -------------------------------- /CSSRESET --------------------------------*/ 82 | 83 | :root { 84 | /* Colors */ 85 | --main-border-color: #ddd; 86 | --primary-border: #037dba; 87 | --gray-20: #404346; 88 | --gray-60: #8a8d91; 89 | --gray-70: #bcc0c4; 90 | --gray-80: #c9ccd1; 91 | --gray-90: #e4e6eb; 92 | --gray-95: #f0f2f5; 93 | --gray-100: #f5f7fa; 94 | --primary-blue: #037dba; 95 | --secondary-blue: #0396df; 96 | --tertiary-blue: #c6efff; 97 | --flash-blue: #4cf7ff; 98 | --outline-blue: rgba(4, 164, 244, 0.6); 99 | --navy-blue: #035e8c; 100 | --red-25: #bd0d2a; 101 | --secondary-text: #65676b; 102 | --white: #fff; 103 | --yellow: #fffae1; 104 | 105 | --outline-box-shadow: 0 0 0 2px var(--outline-blue); 106 | --outline-box-shadow-contrast: 0 0 0 2px var(--navy-blue); 107 | 108 | /* Fonts */ 109 | --sans-serif: -apple-system, system-ui, BlinkMacSystemFont, 'Segoe UI', Roboto, 110 | Ubuntu, Helvetica, sans-serif; 111 | --monospace: Menlo, Consolas, Monaco, Liberation Mono, Lucida Console, 112 | monospace; 113 | } 114 | 115 | html { 116 | font-size: 100%; 117 | } 118 | 119 | body { 120 | font-family: var(--sans-serif); 121 | background: var(--gray-100); 122 | font-weight: 400; 123 | line-height: 1.75; 124 | } 125 | 126 | h1, 127 | h2, 128 | h3, 129 | h4, 130 | h5 { 131 | margin: 0; 132 | font-weight: 700; 133 | line-height: 1.3; 134 | } 135 | 136 | h1 { 137 | font-size: 3.052rem; 138 | } 139 | h2 { 140 | font-size: 2.441rem; 141 | } 142 | h3 { 143 | font-size: 1.953rem; 144 | } 145 | h4 { 146 | font-size: 1.563rem; 147 | } 148 | h5 { 149 | font-size: 1.25rem; 150 | } 151 | small, 152 | .text_small { 153 | font-size: 0.8rem; 154 | } 155 | pre, 156 | code { 157 | font-family: var(--monospace); 158 | border-radius: 6px; 159 | } 160 | pre { 161 | background: var(--gray-95); 162 | padding: 12px; 163 | line-height: 1.5; 164 | } 165 | code { 166 | background: var(--yellow); 167 | padding: 0 3px; 168 | font-size: 0.94rem; 169 | word-break: break-word; 170 | } 171 | pre code { 172 | background: none; 173 | } 174 | a { 175 | color: var(--primary-blue); 176 | } 177 | 178 | .text-with-markdown h1, 179 | .text-with-markdown h2, 180 | .text-with-markdown h3, 181 | .text-with-markdown h4, 182 | .text-with-markdown h5 { 183 | margin-block: 2rem 0.7rem; 184 | margin-inline: 0; 185 | } 186 | 187 | .text-with-markdown blockquote { 188 | font-style: italic; 189 | color: var(--gray-20); 190 | border-left: 3px solid var(--gray-80); 191 | padding-left: 10px; 192 | } 193 | 194 | hr { 195 | border: 0; 196 | height: 0; 197 | border-top: 1px solid rgba(0, 0, 0, 0.1); 198 | border-bottom: 1px solid rgba(255, 255, 255, 0.3); 199 | } 200 | 201 | /* ---------------------------------------------------------------------------*/ 202 | .main { 203 | display: flex; 204 | height: 100vh; 205 | width: 100%; 206 | overflow: hidden; 207 | } 208 | 209 | .col { 210 | height: 100%; 211 | } 212 | .col:last-child { 213 | flex-grow: 1; 214 | } 215 | 216 | .logo { 217 | height: 20px; 218 | width: 22px; 219 | margin-inline-end: 10px; 220 | } 221 | 222 | .edit-button { 223 | border-radius: 100px; 224 | letter-spacing: 0.12em; 225 | text-transform: uppercase; 226 | padding: 6px 20px 8px; 227 | cursor: pointer; 228 | font-weight: 700; 229 | outline-style: none; 230 | } 231 | .edit-button--solid { 232 | background: var(--primary-blue); 233 | color: var(--white); 234 | border: none; 235 | margin-inline-start: 6px; 236 | transition: all 0.2s ease-in-out; 237 | } 238 | .edit-button--solid:hover { 239 | background: var(--secondary-blue); 240 | } 241 | .edit-button--solid:focus { 242 | box-shadow: var(--outline-box-shadow-contrast); 243 | } 244 | .edit-button--outline { 245 | background: var(--white); 246 | color: var(--primary-blue); 247 | border: 1px solid var(--primary-blue); 248 | margin-inline-start: 12px; 249 | transition: all 0.1s ease-in-out; 250 | } 251 | .edit-button--outline:disabled { 252 | opacity: 0.5; 253 | } 254 | .edit-button--outline:hover:not([disabled]) { 255 | background: var(--primary-blue); 256 | color: var(--white); 257 | } 258 | .edit-button--outline:focus { 259 | box-shadow: var(--outline-box-shadow); 260 | } 261 | 262 | ul.notes-list { 263 | padding: 16px 0; 264 | } 265 | .notes-list > li { 266 | padding: 0 16px; 267 | } 268 | .notes-empty { 269 | padding: 16px; 270 | } 271 | 272 | .sidebar { 273 | background: var(--white); 274 | box-shadow: 0px 8px 24px rgba(0, 0, 0, 0.1), 0px 2px 2px rgba(0, 0, 0, 0.1); 275 | overflow-y: scroll; 276 | z-index: 1000; 277 | flex-shrink: 0; 278 | max-width: 350px; 279 | min-width: 250px; 280 | width: 30%; 281 | } 282 | .sidebar-header { 283 | letter-spacing: 0.15em; 284 | text-transform: uppercase; 285 | padding: 36px 16px 16px; 286 | display: flex; 287 | align-items: center; 288 | } 289 | .sidebar-menu { 290 | padding: 0 16px 16px; 291 | display: flex; 292 | justify-content: space-between; 293 | } 294 | .sidebar-menu > .search { 295 | position: relative; 296 | flex-grow: 1; 297 | } 298 | .sidebar-note-list-item { 299 | position: relative; 300 | margin-bottom: 12px; 301 | padding: 16px; 302 | width: 100%; 303 | display: flex; 304 | justify-content: space-between; 305 | align-items: flex-start; 306 | flex-wrap: wrap; 307 | max-height: 100px; 308 | transition: max-height 250ms ease-out; 309 | transform: scale(1); 310 | } 311 | .sidebar-note-list-item.note-expanded { 312 | max-height: 300px; 313 | transition: max-height 0.5s ease; 314 | } 315 | .sidebar-note-list-item.flash { 316 | animation-name: flash; 317 | animation-duration: 0.6s; 318 | } 319 | 320 | .sidebar-note-open { 321 | position: absolute; 322 | top: 0; 323 | left: 0; 324 | right: 0; 325 | bottom: 0; 326 | width: 100%; 327 | z-index: 0; 328 | border: none; 329 | border-radius: 6px; 330 | text-align: start; 331 | background: var(--gray-95); 332 | cursor: pointer; 333 | outline-style: none; 334 | color: transparent; 335 | font-size: 0px; 336 | } 337 | .sidebar-note-open:focus { 338 | box-shadow: var(--outline-box-shadow); 339 | } 340 | .sidebar-note-open:hover { 341 | background: var(--gray-90); 342 | } 343 | .sidebar-note-header { 344 | z-index: 1; 345 | max-width: 85%; 346 | pointer-events: none; 347 | } 348 | .sidebar-note-header > strong { 349 | display: block; 350 | font-size: 1.25rem; 351 | line-height: 1.2; 352 | white-space: nowrap; 353 | overflow: hidden; 354 | text-overflow: ellipsis; 355 | } 356 | .sidebar-note-toggle-expand { 357 | z-index: 2; 358 | border-radius: 50%; 359 | height: 24px; 360 | border: 1px solid var(--gray-60); 361 | cursor: pointer; 362 | flex-shrink: 0; 363 | visibility: hidden; 364 | opacity: 0; 365 | cursor: default; 366 | transition: visibility 0s linear 20ms, opacity 300ms; 367 | outline-style: none; 368 | } 369 | .sidebar-note-toggle-expand:focus { 370 | box-shadow: var(--outline-box-shadow); 371 | } 372 | .sidebar-note-open:hover + .sidebar-note-toggle-expand, 373 | .sidebar-note-open:focus + .sidebar-note-toggle-expand, 374 | .sidebar-note-toggle-expand:hover, 375 | .sidebar-note-toggle-expand:focus { 376 | visibility: visible; 377 | opacity: 1; 378 | transition: visibility 0s linear 0s, opacity 300ms; 379 | } 380 | .sidebar-note-toggle-expand img { 381 | width: 10px; 382 | height: 10px; 383 | } 384 | 385 | .sidebar-note-excerpt { 386 | pointer-events: none; 387 | z-index: 2; 388 | flex: 1 1 250px; 389 | color: var(--secondary-text); 390 | position: relative; 391 | animation: slideIn 100ms; 392 | } 393 | 394 | .search input { 395 | padding: 0 16px; 396 | border-radius: 100px; 397 | border: 1px solid var(--gray-90); 398 | width: 100%; 399 | height: 100%; 400 | outline-style: none; 401 | } 402 | .search input:focus { 403 | box-shadow: var(--outline-box-shadow); 404 | } 405 | .search .spinner { 406 | position: absolute; 407 | right: 10px; 408 | top: 10px; 409 | } 410 | 411 | .note-viewer { 412 | display: flex; 413 | align-items: center; 414 | justify-content: center; 415 | } 416 | .note { 417 | background: var(--white); 418 | box-shadow: 0px 0px 5px rgba(0, 0, 0, 0.1), 0px 0px 1px rgba(0, 0, 0, 0.1); 419 | border-radius: 8px; 420 | height: 95%; 421 | width: 95%; 422 | min-width: 400px; 423 | padding: 8%; 424 | overflow-y: auto; 425 | } 426 | .note--empty-state { 427 | margin-inline: 20px 20px; 428 | } 429 | .note-text--empty-state { 430 | font-size: 1.5rem; 431 | } 432 | .note-header { 433 | display: flex; 434 | justify-content: space-between; 435 | align-items: center; 436 | flex-wrap: wrap-reverse; 437 | margin-inline-start: -12px; 438 | } 439 | .note-menu { 440 | display: flex; 441 | justify-content: space-between; 442 | align-items: center; 443 | flex-grow: 1; 444 | } 445 | .note-title { 446 | line-height: 1.3; 447 | flex-grow: 1; 448 | overflow-wrap: break-word; 449 | margin-inline-start: 12px; 450 | } 451 | .note-updated-at { 452 | color: var(--secondary-text); 453 | white-space: nowrap; 454 | margin-inline-start: 12px; 455 | } 456 | .note-preview { 457 | margin-block-start: 50px; 458 | } 459 | 460 | .note-editor { 461 | background: var(--white); 462 | display: flex; 463 | height: 100%; 464 | width: 100%; 465 | padding: 58px; 466 | overflow-y: auto; 467 | } 468 | .note-editor .label { 469 | margin-bottom: 20px; 470 | } 471 | .note-editor-form { 472 | display: flex; 473 | flex-direction: column; 474 | width: 400px; 475 | flex-shrink: 0; 476 | position: sticky; 477 | top: 0; 478 | } 479 | .note-editor-form input, 480 | .note-editor-form textarea { 481 | background: none; 482 | border: 1px solid var(--gray-70); 483 | border-radius: 2px; 484 | font-family: var(--monospace); 485 | font-size: 0.8rem; 486 | padding: 12px; 487 | outline-style: none; 488 | } 489 | .note-editor-form input:focus, 490 | .note-editor-form textarea:focus { 491 | box-shadow: var(--outline-box-shadow); 492 | } 493 | .note-editor-form input { 494 | height: 44px; 495 | margin-bottom: 16px; 496 | } 497 | .note-editor-form textarea { 498 | height: 100%; 499 | max-width: 400px; 500 | } 501 | .note-editor-menu { 502 | display: flex; 503 | justify-content: flex-end; 504 | align-items: center; 505 | margin-bottom: 12px; 506 | } 507 | .note-editor-preview { 508 | margin-inline-start: 40px; 509 | width: 100%; 510 | } 511 | .note-editor-done, 512 | .note-editor-delete { 513 | display: flex; 514 | justify-content: space-between; 515 | align-items: center; 516 | border-radius: 100px; 517 | letter-spacing: 0.12em; 518 | text-transform: uppercase; 519 | padding: 6px 20px 8px; 520 | cursor: pointer; 521 | font-weight: 700; 522 | margin-inline-start: 12px; 523 | outline-style: none; 524 | transition: all 0.2s ease-in-out; 525 | } 526 | .note-editor-done:disabled, 527 | .note-editor-delete:disabled { 528 | opacity: 0.5; 529 | } 530 | .note-editor-done { 531 | border: none; 532 | background: var(--primary-blue); 533 | color: var(--white); 534 | } 535 | .note-editor-done:focus { 536 | box-shadow: var(--outline-box-shadow-contrast); 537 | } 538 | .note-editor-done:hover:not([disabled]) { 539 | background: var(--secondary-blue); 540 | } 541 | .note-editor-delete { 542 | border: 1px solid var(--red-25); 543 | background: var(--white); 544 | color: var(--red-25); 545 | } 546 | .note-editor-delete:focus { 547 | box-shadow: var(--outline-box-shadow); 548 | } 549 | .note-editor-delete:hover:not([disabled]) { 550 | background: var(--red-25); 551 | color: var(--white); 552 | } 553 | /* Hack to color our svg */ 554 | .note-editor-delete:hover:not([disabled]) img { 555 | filter: grayscale(1) invert(1) brightness(2); 556 | } 557 | .note-editor-done > img { 558 | width: 14px; 559 | } 560 | .note-editor-delete > img { 561 | width: 10px; 562 | } 563 | .note-editor-done > img, 564 | .note-editor-delete > img { 565 | margin-inline-end: 12px; 566 | } 567 | .note-editor-done[disabled], 568 | .note-editor-delete[disabled] { 569 | opacity: 0.5; 570 | } 571 | 572 | .label { 573 | display: inline-block; 574 | border-radius: 100px; 575 | letter-spacing: 0.05em; 576 | text-transform: uppercase; 577 | font-weight: 700; 578 | padding: 4px 14px; 579 | } 580 | .label--preview { 581 | background: rgba(38, 183, 255, 0.15); 582 | color: var(--primary-blue); 583 | } 584 | 585 | .text-with-markdown p { 586 | margin-bottom: 16px; 587 | } 588 | .text-with-markdown img { 589 | width: 100%; 590 | } 591 | 592 | /* https://codepen.io/mandelid/pen/vwKoe */ 593 | .spinner { 594 | display: inline-block; 595 | transition: opacity linear 0.1s 0.2s; 596 | width: 20px; 597 | height: 20px; 598 | border: 3px solid rgba(80, 80, 80, 0.5); 599 | border-radius: 50%; 600 | border-top-color: #fff; 601 | animation: spin 1s ease-in-out infinite; 602 | opacity: 0; 603 | } 604 | .spinner--active { 605 | opacity: 1; 606 | } 607 | 608 | .skeleton::after { 609 | content: 'Loading...'; 610 | } 611 | .skeleton { 612 | height: 100%; 613 | background-color: #eee; 614 | background-image: linear-gradient(90deg, #eee, #f5f5f5, #eee); 615 | background-size: 200px 100%; 616 | background-repeat: no-repeat; 617 | border-radius: 4px; 618 | display: block; 619 | line-height: 1; 620 | width: 100%; 621 | animation: shimmer 1.2s ease-in-out infinite; 622 | color: transparent; 623 | } 624 | .skeleton:first-of-type { 625 | margin: 0; 626 | } 627 | .skeleton--button { 628 | border-radius: 100px; 629 | padding: 6px 20px 8px; 630 | width: auto; 631 | } 632 | .v-stack + .v-stack { 633 | margin-block-start: 0.8em; 634 | } 635 | 636 | .offscreen { 637 | border: 0; 638 | clip: rect(0, 0, 0, 0); 639 | height: 1px; 640 | margin: -1px; 641 | overflow: hidden; 642 | padding: 0; 643 | width: 1px; 644 | position: absolute; 645 | } 646 | 647 | /* ---------------------------------------------------------------------------*/ 648 | @keyframes spin { 649 | to { 650 | transform: rotate(360deg); 651 | } 652 | } 653 | @keyframes spin { 654 | to { 655 | transform: rotate(360deg); 656 | } 657 | } 658 | 659 | @keyframes shimmer { 660 | 0% { 661 | background-position: -200px 0; 662 | } 663 | 100% { 664 | background-position: calc(200px + 100%) 0; 665 | } 666 | } 667 | 668 | @keyframes slideIn { 669 | 0% { 670 | top: -10px; 671 | opacity: 0; 672 | } 673 | 100% { 674 | top: 0; 675 | opacity: 1; 676 | } 677 | } 678 | 679 | @keyframes flash { 680 | 0% { 681 | transform: scale(1); 682 | opacity: 1; 683 | } 684 | 50% { 685 | transform: scale(1.05); 686 | opacity: 0.9; 687 | } 688 | 100% { 689 | transform: scale(1); 690 | opacity: 1; 691 | } 692 | } 693 | -------------------------------------------------------------------------------- /scripts/build.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) Facebook, Inc. and its affiliates. 3 | * 4 | * This source code is licensed under the MIT license found in the 5 | * LICENSE file in the root directory of this source tree. 6 | * 7 | */ 8 | 9 | 'use strict'; 10 | 11 | const path = require('path'); 12 | const rimraf = require('rimraf'); 13 | const webpack = require('webpack'); 14 | const HtmlWebpackPlugin = require('html-webpack-plugin'); 15 | const ReactServerWebpackPlugin = require('react-server-dom-webpack/plugin'); 16 | 17 | const isProduction = process.env.NODE_ENV === 'production'; 18 | rimraf.sync(path.resolve(__dirname, '../build')); 19 | webpack( 20 | { 21 | mode: isProduction ? 'production' : 'development', 22 | devtool: isProduction ? 'source-map' : 'cheap-module-source-map', 23 | entry: [path.resolve(__dirname, '../src/framework/bootstrap.js')], 24 | output: { 25 | path: path.resolve(__dirname, '../build'), 26 | filename: 'main.js', 27 | }, 28 | module: { 29 | rules: [ 30 | { 31 | test: /\.js$/, 32 | use: 'babel-loader', 33 | exclude: /node_modules/, 34 | }, 35 | ], 36 | }, 37 | plugins: [ 38 | new HtmlWebpackPlugin({ 39 | inject: true, 40 | template: path.resolve(__dirname, '../public/index.html'), 41 | }), 42 | new ReactServerWebpackPlugin({isServer: false}), 43 | ], 44 | }, 45 | (err, stats) => { 46 | if (err) { 47 | console.error(err.stack || err); 48 | if (err.details) { 49 | console.error(err.details); 50 | } 51 | process.exit(1); 52 | return; 53 | } 54 | const info = stats.toJson(); 55 | if (stats.hasErrors()) { 56 | console.log('Finished running webpack with errors.'); 57 | info.errors.forEach((e) => console.error(e)); 58 | process.exit(1); 59 | } else { 60 | console.log('Finished running webpack.'); 61 | } 62 | } 63 | ); 64 | -------------------------------------------------------------------------------- /scripts/init_db.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | set -e 3 | 4 | psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" --dbname "$POSTGRES_DB" <<-EOSQL 5 | DROP TABLE IF EXISTS notes; 6 | CREATE TABLE notes ( 7 | id SERIAL PRIMARY KEY, 8 | created_at TIMESTAMP NOT NULL, 9 | updated_at TIMESTAMP NOT NULL, 10 | title TEXT, 11 | body TEXT 12 | ); 13 | EOSQL 14 | -------------------------------------------------------------------------------- /scripts/seed.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) Facebook, Inc. and its affiliates. 3 | * 4 | * This source code is licensed under the MIT license found in the 5 | * LICENSE file in the root directory of this source tree. 6 | * 7 | */ 8 | 9 | 'use strict'; 10 | 11 | const fs = require('fs'); 12 | const path = require('path'); 13 | const {Pool} = require('pg'); 14 | const {readdir, unlink, writeFile} = require('fs/promises'); 15 | const startOfYear = require('date-fns/startOfYear'); 16 | const credentials = require('../credentials'); 17 | 18 | const NOTES_PATH = './notes'; 19 | const pool = new Pool(credentials); 20 | 21 | const now = new Date(); 22 | const startOfThisYear = startOfYear(now); 23 | // Thanks, https://stackoverflow.com/a/9035732 24 | function randomDateBetween(start, end) { 25 | return new Date( 26 | start.getTime() + Math.random() * (end.getTime() - start.getTime()) 27 | ); 28 | } 29 | 30 | const dropTableStatement = 'DROP TABLE IF EXISTS notes;'; 31 | const createTableStatement = `CREATE TABLE notes ( 32 | id SERIAL PRIMARY KEY, 33 | created_at TIMESTAMP NOT NULL, 34 | updated_at TIMESTAMP NOT NULL, 35 | title TEXT, 36 | body TEXT 37 | );`; 38 | const insertNoteStatement = `INSERT INTO notes(title, body, created_at, updated_at) 39 | VALUES ($1, $2, $3, $3) 40 | RETURNING *`; 41 | const seedData = [ 42 | [ 43 | 'Meeting Notes', 44 | 'This is an example note. It contains **Markdown**!', 45 | randomDateBetween(startOfThisYear, now), 46 | ], 47 | [ 48 | 'Make a thing', 49 | `It's very easy to make some words **bold** and other words *italic* with 50 | Markdown. You can even [link to React's website!](https://www.reactjs.org).`, 51 | randomDateBetween(startOfThisYear, now), 52 | ], 53 | [ 54 | 'A note with a very long title because sometimes you need more words', 55 | `You can write all kinds of [amazing](https://en.wikipedia.org/wiki/The_Amazing) 56 | notes in this app! These note live on the server in the \`notes\` folder. 57 | 58 | ![This app is powered by React](https://upload.wikimedia.org/wikipedia/commons/thumb/1/18/React_Native_Logo.png/800px-React_Native_Logo.png)`, 59 | randomDateBetween(startOfThisYear, now), 60 | ], 61 | ['I wrote this note today', 'It was an excellent note.', now], 62 | ]; 63 | 64 | async function seed() { 65 | await pool.query(dropTableStatement); 66 | await pool.query(createTableStatement); 67 | const res = await Promise.all( 68 | seedData.map((row) => pool.query(insertNoteStatement, row)) 69 | ); 70 | 71 | const oldNotes = await readdir(path.resolve(NOTES_PATH)); 72 | await Promise.all( 73 | oldNotes 74 | .filter((filename) => filename.endsWith('.md')) 75 | .map((filename) => unlink(path.resolve(NOTES_PATH, filename))) 76 | ); 77 | 78 | await Promise.all( 79 | res.map(({rows}) => { 80 | const id = rows[0].id; 81 | const content = rows[0].body; 82 | const data = new Uint8Array(Buffer.from(content)); 83 | return writeFile(path.resolve(NOTES_PATH, `${id}.md`), data, (err) => { 84 | if (err) { 85 | throw err; 86 | } 87 | }); 88 | }) 89 | ); 90 | } 91 | 92 | seed(); 93 | -------------------------------------------------------------------------------- /server/api.server.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) Facebook, Inc. and its affiliates. 3 | * 4 | * This source code is licensed under the MIT license found in the 5 | * LICENSE file in the root directory of this source tree. 6 | * 7 | */ 8 | 9 | 'use strict'; 10 | 11 | const register = require('react-server-dom-webpack/node-register'); 12 | register(); 13 | const babelRegister = require('@babel/register'); 14 | 15 | babelRegister({ 16 | ignore: [/[\\\/](build|server|node_modules)[\\\/]/], 17 | presets: [['@babel/preset-react', {runtime: 'automatic'}]], 18 | plugins: ['@babel/transform-modules-commonjs'], 19 | }); 20 | 21 | const express = require('express'); 22 | const compress = require('compression'); 23 | const {readFileSync} = require('fs'); 24 | const {unlink, writeFile} = require('fs').promises; 25 | const {renderToPipeableStream} = require('react-server-dom-webpack/server'); 26 | const path = require('path'); 27 | const {Pool} = require('pg'); 28 | const React = require('react'); 29 | const ReactApp = require('../src/App').default; 30 | 31 | // Don't keep credentials in the source tree in a real app! 32 | const pool = new Pool(require('../credentials')); 33 | 34 | const PORT = process.env.PORT || 4000; 35 | const app = express(); 36 | 37 | app.use(compress()); 38 | app.use(express.json()); 39 | 40 | app 41 | .listen(PORT, () => { 42 | console.log(`React Notes listening at ${PORT}...`); 43 | }) 44 | .on('error', function(error) { 45 | if (error.syscall !== 'listen') { 46 | throw error; 47 | } 48 | const isPipe = (portOrPipe) => Number.isNaN(portOrPipe); 49 | const bind = isPipe(PORT) ? 'Pipe ' + PORT : 'Port ' + PORT; 50 | switch (error.code) { 51 | case 'EACCES': 52 | console.error(bind + ' requires elevated privileges'); 53 | process.exit(1); 54 | break; 55 | case 'EADDRINUSE': 56 | console.error(bind + ' is already in use'); 57 | process.exit(1); 58 | break; 59 | default: 60 | throw error; 61 | } 62 | }); 63 | 64 | function handleErrors(fn) { 65 | return async function(req, res, next) { 66 | try { 67 | return await fn(req, res); 68 | } catch (x) { 69 | next(x); 70 | } 71 | }; 72 | } 73 | 74 | app.get( 75 | '/', 76 | handleErrors(async function(_req, res) { 77 | await waitForWebpack(); 78 | const html = readFileSync( 79 | path.resolve(__dirname, '../build/index.html'), 80 | 'utf8' 81 | ); 82 | // Note: this is sending an empty HTML shell, like a client-side-only app. 83 | // However, the intended solution (which isn't built out yet) is to read 84 | // from the Server endpoint and turn its response into an HTML stream. 85 | res.send(html); 86 | }) 87 | ); 88 | 89 | async function renderReactTree(res, props) { 90 | await waitForWebpack(); 91 | const manifest = readFileSync( 92 | path.resolve(__dirname, '../build/react-client-manifest.json'), 93 | 'utf8' 94 | ); 95 | const moduleMap = JSON.parse(manifest); 96 | const {pipe} = renderToPipeableStream( 97 | React.createElement(ReactApp, props), 98 | moduleMap 99 | ); 100 | pipe(res); 101 | } 102 | 103 | function sendResponse(req, res, redirectToId) { 104 | const location = JSON.parse(req.query.location); 105 | if (redirectToId) { 106 | location.selectedId = redirectToId; 107 | } 108 | res.set('X-Location', JSON.stringify(location)); 109 | renderReactTree(res, { 110 | selectedId: location.selectedId, 111 | isEditing: location.isEditing, 112 | searchText: location.searchText, 113 | }); 114 | } 115 | 116 | app.get('/react', function(req, res) { 117 | sendResponse(req, res, null); 118 | }); 119 | 120 | const NOTES_PATH = path.resolve(__dirname, '../notes'); 121 | 122 | app.post( 123 | '/notes', 124 | handleErrors(async function(req, res) { 125 | const now = new Date(); 126 | const result = await pool.query( 127 | 'insert into notes (title, body, created_at, updated_at) values ($1, $2, $3, $3) returning id', 128 | [req.body.title, req.body.body, now] 129 | ); 130 | const insertedId = result.rows[0].id; 131 | await writeFile( 132 | path.resolve(NOTES_PATH, `${insertedId}.md`), 133 | req.body.body, 134 | 'utf8' 135 | ); 136 | sendResponse(req, res, insertedId); 137 | }) 138 | ); 139 | 140 | app.put( 141 | '/notes/:id', 142 | handleErrors(async function(req, res) { 143 | const now = new Date(); 144 | const updatedId = Number(req.params.id); 145 | await pool.query( 146 | 'update notes set title = $1, body = $2, updated_at = $3 where id = $4', 147 | [req.body.title, req.body.body, now, updatedId] 148 | ); 149 | await writeFile( 150 | path.resolve(NOTES_PATH, `${updatedId}.md`), 151 | req.body.body, 152 | 'utf8' 153 | ); 154 | sendResponse(req, res, null); 155 | }) 156 | ); 157 | 158 | app.delete( 159 | '/notes/:id', 160 | handleErrors(async function(req, res) { 161 | await pool.query('delete from notes where id = $1', [req.params.id]); 162 | await unlink(path.resolve(NOTES_PATH, `${req.params.id}.md`)); 163 | sendResponse(req, res, null); 164 | }) 165 | ); 166 | 167 | app.get( 168 | '/notes', 169 | handleErrors(async function(_req, res) { 170 | const {rows} = await pool.query('select * from notes order by id desc'); 171 | res.json(rows); 172 | }) 173 | ); 174 | 175 | app.get( 176 | '/notes/:id', 177 | handleErrors(async function(req, res) { 178 | const {rows} = await pool.query('select * from notes where id = $1', [ 179 | req.params.id, 180 | ]); 181 | res.json(rows[0]); 182 | }) 183 | ); 184 | 185 | app.get('/sleep/:ms', function(req, res) { 186 | setTimeout(() => { 187 | res.json({ok: true}); 188 | }, req.params.ms); 189 | }); 190 | 191 | app.use(express.static('build')); 192 | app.use(express.static('public')); 193 | 194 | async function waitForWebpack() { 195 | while (true) { 196 | try { 197 | readFileSync(path.resolve(__dirname, '../build/index.html')); 198 | return; 199 | } catch (err) { 200 | console.log( 201 | 'Could not find webpack build output. Will retry in a second...' 202 | ); 203 | await new Promise((resolve) => setTimeout(resolve, 1000)); 204 | } 205 | } 206 | } 207 | -------------------------------------------------------------------------------- /server/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "type": "commonjs", 3 | "main": "./api.server.js" 4 | } 5 | -------------------------------------------------------------------------------- /src/App.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) Facebook, Inc. and its affiliates. 3 | * 4 | * This source code is licensed under the MIT license found in the 5 | * LICENSE file in the root directory of this source tree. 6 | * 7 | */ 8 | 9 | import {Suspense} from 'react'; 10 | 11 | import Note from './Note'; 12 | import NoteList from './NoteList'; 13 | import EditButton from './EditButton'; 14 | import SearchField from './SearchField'; 15 | import NoteSkeleton from './NoteSkeleton'; 16 | import NoteListSkeleton from './NoteListSkeleton'; 17 | 18 | export default function App({selectedId, isEditing, searchText}) { 19 | return ( 20 |
21 |
22 |
23 | 31 | React Notes 32 |
33 |
34 | 35 | New 36 |
37 | 42 |
43 |
44 | }> 45 | 46 | 47 |
48 |
49 | ); 50 | } 51 | -------------------------------------------------------------------------------- /src/EditButton.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) Facebook, Inc. and its affiliates. 3 | * 4 | * This source code is licensed under the MIT license found in the 5 | * LICENSE file in the root directory of this source tree. 6 | * 7 | */ 8 | 9 | 'use client'; 10 | 11 | import {useTransition} from 'react'; 12 | import {useRouter} from './framework/router'; 13 | 14 | export default function EditButton({noteId, children}) { 15 | const [isPending, startTransition] = useTransition(); 16 | const {navigate} = useRouter(); 17 | const isDraft = noteId == null; 18 | return ( 19 | 36 | ); 37 | } 38 | -------------------------------------------------------------------------------- /src/Note.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) Facebook, Inc. and its affiliates. 3 | * 4 | * This source code is licensed under the MIT license found in the 5 | * LICENSE file in the root directory of this source tree. 6 | * 7 | */ 8 | 9 | import {format} from 'date-fns'; 10 | 11 | // Uncomment if you want to read from a file instead. 12 | // import {readFile} from 'fs/promises'; 13 | // import {resolve} from 'path'; 14 | 15 | import NotePreview from './NotePreview'; 16 | import EditButton from './EditButton'; 17 | import NoteEditor from './NoteEditor'; 18 | 19 | export default async function Note({selectedId, isEditing}) { 20 | if (selectedId === null) { 21 | if (isEditing) { 22 | return ( 23 | 24 | ); 25 | } else { 26 | return ( 27 |
28 | 29 | Click a note on the left to view something! 🥺 30 | 31 |
32 | ); 33 | } 34 | } 35 | 36 | const noteResponse = await fetch(`http://localhost:4000/notes/${selectedId}`); 37 | const note = await noteResponse.json(); 38 | 39 | let {id, title, body, updated_at} = note; 40 | const updatedAt = new Date(updated_at); 41 | 42 | // We could also read from a file instead. 43 | // body = await readFile(resolve(`./notes/${note.id}.md`), 'utf8'); 44 | 45 | // Now let's see how the Suspense boundary above lets us not block on this. 46 | // await fetch('http://localhost:4000/sleep/3000'); 47 | 48 | if (isEditing) { 49 | return ; 50 | } else { 51 | return ( 52 |
53 |
54 |

{title}

55 |
56 | 57 | Last updated on {format(updatedAt, "d MMM yyyy 'at' h:mm bb")} 58 | 59 | Edit 60 |
61 |
62 | 63 |
64 | ); 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /src/NoteEditor.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) Facebook, Inc. and its affiliates. 3 | * 4 | * This source code is licensed under the MIT license found in the 5 | * LICENSE file in the root directory of this source tree. 6 | * 7 | */ 8 | 9 | 'use client'; 10 | 11 | import {useState, useTransition} from 'react'; 12 | import {useRouter, useMutation} from './framework/router'; 13 | 14 | import NotePreview from './NotePreview'; 15 | 16 | export default function NoteEditor({noteId, initialTitle, initialBody}) { 17 | const [title, setTitle] = useState(initialTitle); 18 | const [body, setBody] = useState(initialBody); 19 | const {location} = useRouter(); 20 | const [isNavigating, startNavigating] = useTransition(); 21 | const [isSaving, saveNote] = useMutation({ 22 | endpoint: noteId !== null ? `/notes/${noteId}` : `/notes`, 23 | method: noteId !== null ? 'PUT' : 'POST', 24 | }); 25 | const [isDeleting, deleteNote] = useMutation({ 26 | endpoint: `/notes/${noteId}`, 27 | method: 'DELETE', 28 | }); 29 | 30 | async function handleSave() { 31 | const payload = {title, body}; 32 | const requestedLocation = { 33 | selectedId: noteId, 34 | isEditing: false, 35 | searchText: location.searchText, 36 | }; 37 | await saveNote(payload, requestedLocation); 38 | } 39 | 40 | async function handleDelete() { 41 | const payload = {}; 42 | const requestedLocation = { 43 | selectedId: null, 44 | isEditing: false, 45 | searchText: location.searchText, 46 | }; 47 | await deleteNote(payload, requestedLocation); 48 | } 49 | 50 | const isDraft = noteId === null; 51 | return ( 52 |
53 |
e.preventDefault()}> 57 | 60 | { 65 | setTitle(e.target.value); 66 | }} 67 | /> 68 | 71 |