├── .funcignore ├── .github └── workflows │ └── azure-static-web-apps-kind-wave-0f8b93b1e.yml ├── .gitignore ├── .prettierignore ├── .prettierrc.js ├── .vscode ├── extensions.json ├── launch.json ├── settings.json └── tasks.json ├── CODE_OF_CONDUCT.md ├── LICENSE ├── README.md ├── README.orig.md ├── credentials.js ├── fs ├── index.js ├── package.json └── promises.js ├── function_notes_delete └── function.json ├── function_notes_post └── function.json ├── function_notes_put └── function.json ├── function_react ├── function.json └── index.server.js ├── funcutil ├── auth.js ├── babelregister.server.js └── react-utils.server.js ├── host.json ├── local.settings.json ├── 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 └── src ├── App.server.js ├── Cache.client.js ├── EditButton.client.js ├── LocationContext.client.js ├── Note.server.js ├── NoteEditor.client.js ├── NoteList.server.js ├── NoteListSkeleton.js ├── NotePreview.js ├── NoteSkeleton.js ├── Root.client.js ├── SearchField.client.js ├── SidebarNote.client.js ├── SidebarNote.js ├── Spinner.js ├── TextWithMarkdown.js ├── config.js ├── db.server.js └── index.client.js /.funcignore: -------------------------------------------------------------------------------- 1 | *.js.map 2 | *.ts 3 | .git* 4 | .vscode 5 | local.settings.json 6 | test 7 | tsconfig.json -------------------------------------------------------------------------------- /.github/workflows/azure-static-web-apps-kind-wave-0f8b93b1e.yml: -------------------------------------------------------------------------------- 1 | name: Azure Static Web Apps CI/CD 2 | 3 | on: 4 | push: 5 | branches: 6 | - azure-static-web-apps 7 | pull_request: 8 | types: [opened, synchronize, reopened, closed] 9 | branches: 10 | - azure-static-web-apps 11 | 12 | jobs: 13 | build_and_deploy_job: 14 | if: github.event_name == 'push' || (github.event_name == 'pull_request' && github.event.action != 'closed') 15 | runs-on: ubuntu-latest 16 | name: Build and Deploy Job 17 | steps: 18 | - uses: actions/checkout@v2 19 | with: 20 | submodules: true 21 | - name: Build app and API 22 | run: | # build and then remove package.json (so deploy step doesn't reinstall modules) 23 | npm install 24 | npm run build 25 | npm prune --production 26 | rm package.json package-lock.json 27 | ls -la build 28 | - name: Deploy 29 | id: builddeploy 30 | uses: Azure/static-web-apps-deploy@v0.0.1-preview 31 | with: 32 | azure_static_web_apps_api_token: ${{ secrets.AZURE_STATIC_WEB_APPS_API_TOKEN_KIND_WAVE_0F8B93B1E }} 33 | repo_token: ${{ secrets.GITHUB_TOKEN }} # Used for Github integrations (i.e. PR comments) 34 | action: "upload" 35 | ###### Repository/Build Configurations - These values can be configured to match you app requirements. ###### 36 | # For more information regarding Static Web App workflow configurations, please visit: https://aka.ms/swaworkflowconfig 37 | app_location: "build" # App source code path 38 | api_location: "/" # Api source code path - optional 39 | output_location: "" # Built app content directory - optional 40 | ###### End of Repository/Build Configurations ###### 41 | 42 | close_pull_request_job: 43 | if: github.event_name == 'pull_request' && github.event.action == 'closed' 44 | runs-on: ubuntu-latest 45 | name: Close Pull Request Job 46 | steps: 47 | - name: Close Pull Request 48 | id: closepullrequest 49 | uses: Azure/static-web-apps-deploy@v0.0.1-preview 50 | with: 51 | azure_static_web_apps_api_token: ${{ secrets.AZURE_STATIC_WEB_APPS_API_TOKEN_KIND_WAVE_0F8B93B1E }} 52 | action: "close" 53 | -------------------------------------------------------------------------------- /.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 | -------------------------------------------------------------------------------- /.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 | -------------------------------------------------------------------------------- /.vscode/extensions.json: -------------------------------------------------------------------------------- 1 | { 2 | "recommendations": [ 3 | "ms-azuretools.vscode-azurefunctions" 4 | ] 5 | } 6 | -------------------------------------------------------------------------------- /.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "0.2.0", 3 | "configurations": [ 4 | { 5 | "name": "Attach to Node Functions", 6 | "type": "node", 7 | "request": "attach", 8 | "port": 9229, 9 | "preLaunchTask": "func: host start" 10 | } 11 | ] 12 | } -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "azureFunctions.deploySubpath": ".", 3 | "azureFunctions.postDeployTask": "npm install", 4 | "azureFunctions.projectLanguage": "JavaScript", 5 | "azureFunctions.projectRuntime": "~3", 6 | "debug.internalConsoleOptions": "neverOpen", 7 | "azureFunctions.preDeployTask": "npm prune" 8 | } -------------------------------------------------------------------------------- /.vscode/tasks.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "2.0.0", 3 | "tasks": [ 4 | { 5 | "type": "func", 6 | "command": "host start", 7 | "problemMatcher": "$func-node-watch", 8 | "isBackground": true, 9 | "dependsOn": "npm install" 10 | }, 11 | { 12 | "type": "shell", 13 | "label": "npm install", 14 | "command": "npm install" 15 | }, 16 | { 17 | "type": "shell", 18 | "label": "npm prune", 19 | "command": "npm prune --production", 20 | "problemMatcher": [] 21 | } 22 | ] 23 | } -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 - Azure Static Web Apps 2 | 3 | This is a port of the [React Server Components "React Notes"](https://github.com/reactjs/server-components-demo) demo for Azure Static Web Apps. React Server Components is currently an experimental project, and the code here to make it work in Azure is equally experimental. For demonstration purposes only! 4 | 5 | **Live demo: https://react-notes.anthonychu.com/** 6 | 7 | Azure services used: 8 | - [Azure Static Web Apps](https://docs.microsoft.com/en-us/azure/static-web-apps/overview) (and Azure Functions) 9 | - Azure Database for PostgreSQL - Flexible Server 10 | 11 | See [original README](README.orig.md) for license and other info. 12 | 13 | ## Run locally 14 | 15 | 1. Fork and clone this repo. 16 | 17 | 1. Start an instance of Postgres locally with the demo's default credentials. Docker works great: 18 | ```bash 19 | docker run --name react-notes -p 5432:5432 -e POSTGRES_USER=notesadmin -e POSTGRES_PASSWORD=password -d postgres 20 | ``` 21 | 22 | 1. Install Azure Functions Core Tools. 23 | ```bash 24 | npm i -g azure-functions-core-tools@3 --unsafe-perm true 25 | ``` 26 | 27 | 1. Update `src/config.js` to use local Azure Functions URL: 28 | ```js 29 | module.exports = { 30 | apiBaseUrl: '/api' 31 | }; 32 | ``` 33 | 34 | 1. Build the app. 35 | ```bash 36 | npm install 37 | npm run build 38 | ``` 39 | 40 | 1. Start the Azure Functions app. 41 | ```bash 42 | func start 43 | ``` 44 | 45 | 1. Serve the frontend with a web server. Using Python here but anything works. 46 | ```bash 47 | python -m http.server 48 | ``` 49 | 50 | ## Deploy to Azure 51 | 52 | 1. Create a Postgres Database in Azure 53 | - [Azure Database for PostgreSQL - Flexible Server](https://docs.microsoft.com/en-us/azure/postgresql/flexible-server/quickstart-create-server-portal) recommended 54 | - Cheapest one works great 55 | 56 | 1. Seed database 57 | - Set `DB_HOST`, `DB_USER`, and `DB_PASSWORD` environment variables to match how you configured your Azure Postgres instance 58 | - Run `npm run seed` 59 | 60 | 1. Create an Azure Static Web App 61 | - App location: `build` 62 | - API location: `/` 63 | - Artifact (output) location: (leave blank) 64 | 65 | 1. The workflow needs to be modified to build the app properly. Add an Action to the generated workflow: 66 | ```yaml 67 | - name: Build app and API 68 | run: | # build and then remove package.json (so deploy step doesn't reinstall modules) 69 | npm install 70 | npm run build 71 | npm prune --production 72 | rm package.json package-lock.json 73 | ls -la build 74 | ``` 75 | Save and push the file to trigger another deployment. See [this file](.github/workflows/azure-static-web-apps-kind-wave-0f8b93b1e.yaml) for an example. 76 | 77 | 1. In the Azure portal, go to the Static Web App and open *Configuration*. Enter the following settings: 78 | | name | value | 79 | | --- | --- | 80 | | `BABEL_DISABLE_CACHE` | `1` | 81 | | `DB_HOST` | `.postgres.database.azure.com` | 82 | | `DB_USER` | your database username | 83 | | `DB_PASSWORD` | your database password | 84 | | `DB_SSL` | `1` | 85 | | `languageWorkers__node__arguments` | `--conditions=react-server` | 86 | | `NODE_ENV` | `production` | 87 | 88 | 1. Save the settings. It may take a few seconds to take effect. If all goes well, go to the app's URL and you should see the app. 89 | 90 | ## How does this work? 91 | 92 | 🚨 While it is fully functional, this is entirely experimental and for demonstration purposes only. Do not use for anything resembling production. 93 | 94 | A few changes were made to the demo app to work better in Azure. 95 | 96 | - Some React Server Components originally called a local HTTP endpoint. When it's running in Azure Functions, it's not advisible to make HTTP calls to itself. Those calls were converted to direct Postgres queries. 97 | - Some changes to the WebPack fonfig `scripts/build.js` to combine the contents of `build` and `publish` folders. 98 | - Changed Postgres config to enable SSL when calling an Azure database. 99 | 100 | ### Changes for Azure Functions / Static Web Apps 101 | 102 | - An HTTP function was created for every endpoint in the original demo. The functions themselves are all in `function_react/index.server.js`. 103 | - The function filename must end in `.server.js` to satisfy React Server Components conventions. 104 | - While Azure Functions supports Node.js 14, the version of Node.js currently available in Static Web Apps is 12. The demo app uses `fs/promises`, which is only in Node.js 14. Added a shim at `fs/promises.js` to get around this. 105 | - The demo requires the `--conditions` flag to be set in the Node.js process. This flag is set with `languageWorkers__node__arguments` app setting. Because Azure Functions starts the Node worker process before your app is loaded, you typically need to set an extra app setting (`WEBSITE_USE_PLACEHOLDER=0`) to delay the start of the worker process. However, function apps in Static Web Apps are not allowed to configure app settings starting with `WEBSITE_`. To get around this, if the `conditions` flag isn't set, there is code in `funcutil/babelregister.server.js` to cause a restart in the Node process. This is a huge hack and should never be used in a production app! 106 | - The `pipeToNodeWritable` function in React Server Components requires writing to a stream. Like some other serverless platforms, Azure Functions is unable to stream responses. We use a `memory-stream` for this. 107 | - `pipeToNodeWritable` looks up client components in a generated manifest. Because the manifest contains full paths from the build machine that are different than the paths in the Azure Functions environment, we use a proxy to select the file with the nearest matching name. See `funcutil/react-utils.server.js`. 108 | - CORS - When running locally and the frontend is served from a different port than the Azure Functions app, CORS is required. CORS is enabled on Azure Functions, but because the demo relies on an `X-Location` header, an additional `'Access-Control-Expose-Headers': 'X-Location'` must be added to responses. 109 | - Authentication was added to the app to allow only logged in users to view and modify their own notes. -------------------------------------------------------------------------------- /README.orig.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 | * [Setup](#setup) 6 | * [DB Setup](#db-setup) 7 | + [Step 1. Create the Database](#step-1-create-the-database) 8 | + [Step 2. Connect to the Database](#step-2-connect-to-the-database) 9 | + [Step 3. Run the seed script](#step-3-run-the-seed-script) 10 | * [Notes about this app](#notes-about-this-app) 11 | + [Interesting things to try](#interesting-things-to-try) 12 | * [Built by (A-Z)](#built-by-a-z) 13 | * [Code of Conduct](#code-of-conduct) 14 | * [License](#license) 15 | 16 | ## What is this? 17 | 18 | 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. 19 | 20 | ## When will I be able to use this? 21 | 22 | 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.** 23 | 24 | ## Setup 25 | 26 | You will need to have nodejs >=14.9.0 in order to run this demo. [Node 14 LTS](https://nodejs.org/en/about/releases/) is a good choice! 27 | 28 | ``` 29 | npm install 30 | npm start 31 | ``` 32 | 33 | (Or `npm run start:prod` for a production build.) 34 | 35 | Then open http://localhost:4000. 36 | 37 | The app won't work until you set up the database, as described below. 38 | 39 |
40 | Setup with Docker 41 |

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

42 |

Make sure you have docker and docker-compose installed then run:

43 |
docker-compose up
44 |

Running seed script

45 |

1. Run containers in the detached mode

46 |
docker-compose up -d
47 |

2. Run seed script

48 |
docker-compose exec notes-app npm run seed
49 |
50 | 51 | ## DB Setup 52 | 53 | This demo uses Postgres. First, follow its [installation link](https://wiki.postgresql.org/wiki/Detailed_installation_guides) for your platform. 54 | 55 | 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). 56 | 57 | The below example will set up the database for this app, assuming that you have a UNIX-like platform: 58 | 59 | ### Step 1. Create the Database 60 | 61 | ``` 62 | psql postgres 63 | 64 | CREATE DATABASE notesapi; 65 | CREATE ROLE notesadmin WITH LOGIN PASSWORD 'password'; 66 | ALTER ROLE notesadmin WITH SUPERUSER; 67 | ALTER DATABASE notesapi OWNER TO notesadmin; 68 | \q 69 | ``` 70 | 71 | ### Step 2. Connect to the Database 72 | 73 | ``` 74 | psql -d postgres -U notesadmin; 75 | 76 | \c notesapi 77 | 78 | DROP TABLE IF EXISTS notes; 79 | CREATE TABLE notes ( 80 | id SERIAL PRIMARY KEY, 81 | created_at TIMESTAMP NOT NULL, 82 | updated_at TIMESTAMP NOT NULL, 83 | title TEXT, 84 | body TEXT 85 | ); 86 | 87 | \q 88 | ``` 89 | 90 | ### Step 3. Run the seed script 91 | 92 | Finally, run `npm run seed` to populate some data. 93 | 94 | And you're done! 95 | 96 | ## Notes about this app 97 | 98 | The demo is a note-taking app called **React Notes**. It consists of a few major parts: 99 | 100 | - It uses a Webpack plugin (not defined in this repo) that allows us to only include client components in build artifacts 101 | - An Express server that: 102 | - Serves API endpoints used in the app 103 | - Renders Server Components into a special format that we can read on the client 104 | - A React app containing Server and Client components used to build React Notes 105 | 106 | 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). 107 | 108 | ### Interesting things to try 109 | 110 | - 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? 111 | - 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? 112 | - 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? 113 | - Search while on Slow 3G, observe the inline loading indicator. 114 | - Switch between two notes back and forth. Observe we don't send new responses next time we switch them again. 115 | - Uncomment the `fetch('http://localhost:4000/sleep/....')` call in `Note.server.js` or `NoteList.server.js` to introduce an artificial delay and trigger Suspense. 116 | - If you only uncomment it in `Note.server.js`, you'll see the fallback every time you open a note. 117 | - If you only uncomment it in `NoteList.server.js`, you'll see the list fallback on first page load. 118 | - If you uncomment it in both, it won't be very interesting because we have nothing new to show until they both respond. 119 | - Add a new Server Component and place it above the search bar in `App.server.js`. Import `db` from `db.server` and use `db.query()` from it to get the number of notes. Oberserve what happens when you add or delete a note. 120 | 121 | You can watch a [recorded walkthrough of all these demo points here](https://youtu.be/La4agIEgoNg?t=600) (with timestamps). 122 | 123 | ## Built by (A-Z) 124 | 125 | - [Andrew Clark](https://twitter.com/acdlite) 126 | - [Dan Abramov](https://twitter.com/dan_abramov) 127 | - [Joe Savona](https://twitter.com/en_JS) 128 | - [Lauren Tan](https://twitter.com/sugarpirate_) 129 | - [Sebastian Markbåge](https://twitter.com/sebmarkbage) 130 | - [Tate Strickland](http://www.tatestrickland.com/) (Design) 131 | 132 | ## [Code of Conduct](https://engineering.fb.com/codeofconduct/) 133 | 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. 134 | 135 | ## License 136 | This demo is MIT licensed. 137 | -------------------------------------------------------------------------------- /credentials.js: -------------------------------------------------------------------------------- 1 | const config = { 2 | host: process.env.DB_HOST || 'localhost', 3 | database: 'notesapi', 4 | user: process.env.DB_USER || 'notesadmin', 5 | password: process.env.DB_PASSWORD || 'password', 6 | port: '5432', 7 | }; 8 | 9 | if (process.env.DB_SSL) { 10 | config.ssl = { 11 | rejectUnauthorized: false, 12 | }; 13 | } 14 | 15 | module.exports = config; -------------------------------------------------------------------------------- /fs/index.js: -------------------------------------------------------------------------------- 1 | module.exports = require('fs'); -------------------------------------------------------------------------------- /fs/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "fs", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "keywords": [], 10 | "author": "", 11 | "license": "ISC" 12 | } 13 | -------------------------------------------------------------------------------- /fs/promises.js: -------------------------------------------------------------------------------- 1 | module.exports = require('fs').promises; -------------------------------------------------------------------------------- /function_notes_delete/function.json: -------------------------------------------------------------------------------- 1 | { 2 | "scriptFile": "../function_react/index.server.js", 3 | "entryPoint": "notesDeleteFunction", 4 | "bindings": [ 5 | { 6 | "authLevel": "anonymous", 7 | "type": "httpTrigger", 8 | "direction": "in", 9 | "name": "req", 10 | "methods": [ 11 | "delete" 12 | ], 13 | "route": "notes/{id}" 14 | }, 15 | { 16 | "type": "http", 17 | "direction": "out", 18 | "name": "$return" 19 | } 20 | ] 21 | } 22 | -------------------------------------------------------------------------------- /function_notes_post/function.json: -------------------------------------------------------------------------------- 1 | { 2 | "scriptFile": "../function_react/index.server.js", 3 | "entryPoint": "notesPostFunction", 4 | "bindings": [ 5 | { 6 | "authLevel": "anonymous", 7 | "type": "httpTrigger", 8 | "direction": "in", 9 | "name": "req", 10 | "methods": [ 11 | "post" 12 | ], 13 | "route": "notes" 14 | }, 15 | { 16 | "type": "http", 17 | "direction": "out", 18 | "name": "$return" 19 | } 20 | ] 21 | } 22 | -------------------------------------------------------------------------------- /function_notes_put/function.json: -------------------------------------------------------------------------------- 1 | { 2 | "scriptFile": "../function_react/index.server.js", 3 | "entryPoint": "notesPutFunction", 4 | "bindings": [ 5 | { 6 | "authLevel": "anonymous", 7 | "type": "httpTrigger", 8 | "direction": "in", 9 | "name": "req", 10 | "methods": [ 11 | "put" 12 | ], 13 | "route": "notes/{id}" 14 | }, 15 | { 16 | "type": "http", 17 | "direction": "out", 18 | "name": "$return" 19 | } 20 | ] 21 | } 22 | -------------------------------------------------------------------------------- /function_react/function.json: -------------------------------------------------------------------------------- 1 | { 2 | "scriptFile": "index.server.js", 3 | "entryPoint": "reactFunction", 4 | "bindings": [ 5 | { 6 | "authLevel": "anonymous", 7 | "type": "httpTrigger", 8 | "direction": "in", 9 | "name": "req", 10 | "methods": [ 11 | "get", 12 | "post" 13 | ], 14 | "route": "react" 15 | }, 16 | { 17 | "type": "http", 18 | "direction": "out", 19 | "name": "$return" 20 | } 21 | ] 22 | } 23 | -------------------------------------------------------------------------------- /function_react/index.server.js: -------------------------------------------------------------------------------- 1 | require('../funcutil/babelregister.server'); 2 | 3 | const React = require('react'); 4 | const ReactApp = require('../src/App.server').default; 5 | const { Pool } = require('pg'); 6 | const pool = new Pool(require('../credentials')); 7 | 8 | const { createResponseBody } = require('../funcutil/react-utils.server'); 9 | 10 | const { decodeAuthInfo } = require('../funcutil/auth'); 11 | 12 | async function reactFunction(context, req) { 13 | return await createResponse(context, req); 14 | } 15 | 16 | async function notesPutFunction(context, req) { 17 | const userInfo = decodeAuthInfo(req); 18 | if (!userInfo) { 19 | return { status: 401 }; 20 | } 21 | 22 | const now = new Date(); 23 | const updatedId = Number(req.params.id); 24 | await pool.query( 25 | 'update notes set title = $1, body = $2, updated_at = $3 where id = $4 and userid = $5', 26 | [req.body.title, req.body.body, now, updatedId, userInfo.userId] 27 | ); 28 | return await createResponse(context, req); 29 | } 30 | 31 | async function notesPostFunction(context, req) { 32 | const userInfo = decodeAuthInfo(req); 33 | if (!userInfo) { 34 | return { status: 401 }; 35 | } 36 | 37 | const now = new Date(); 38 | const result = await pool.query( 39 | 'insert into notes (title, body, created_at, updated_at, userid) values ($1, $2, $3, $3, $4) returning id', 40 | [req.body.title, req.body.body, now, userInfo.userId] 41 | ); 42 | const insertedId = result.rows[0].id; 43 | return await createResponse(context, req, insertedId); 44 | } 45 | 46 | async function notesDeleteFunction(context, req) { 47 | const userInfo = decodeAuthInfo(req); 48 | if (!userInfo) { 49 | return { status: 401 }; 50 | } 51 | 52 | await pool.query( 53 | 'delete from notes where id = $1 and userid = $2', 54 | [req.params.id, userInfo.userId]); 55 | return await createResponse(context, req); 56 | } 57 | 58 | async function createResponse(context, req, redirectToId) { 59 | const location = JSON.parse(req.query.location); 60 | 61 | if (redirectToId) { 62 | location.selectedId = redirectToId; 63 | } 64 | 65 | const userInfo = decodeAuthInfo(req); 66 | 67 | const props = { 68 | userInfo, 69 | selectedId: location.selectedId, 70 | isEditing: location.isEditing, 71 | searchText: location.searchText, 72 | }; 73 | 74 | if (userInfo) { 75 | context.log(JSON.stringify(userInfo, null, 2)); 76 | } 77 | 78 | const responseBody = await createResponseBody(React.createElement(ReactApp, props)); 79 | return { 80 | body: responseBody, 81 | headers: { 82 | 'X-Location': JSON.stringify(location), 83 | 'Access-Control-Expose-Headers': 'X-Location' 84 | } 85 | }; 86 | } 87 | 88 | module.exports = { 89 | reactFunction, 90 | notesDeleteFunction, 91 | notesPostFunction, 92 | notesPutFunction, 93 | }; -------------------------------------------------------------------------------- /funcutil/auth.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | 3 | // https://github.com/anthonychu/swa-api/blob/main/dist/auth.js 4 | 5 | 6 | function decodeAuthInfo(req) { 7 | if (!req) 8 | return; 9 | // This block sets a development user that has rights to upload 10 | // TODO: find a better way to do this 11 | if (process.env.FUNCTIONS_CORETOOLS_ENVIRONMENT) { 12 | return { 13 | identityProvider: "github", 14 | userId: "17baeed9bn1sa3e5dbs24283", 15 | userDetails: "testuser", 16 | userRoles: ["admin", "anonymous", "authenticated"], 17 | }; 18 | } 19 | var clientPrincipalHeader = "x-ms-client-principal"; 20 | if (req.headers[clientPrincipalHeader] == null) { 21 | return; 22 | } 23 | var buffer = Buffer.from(req.headers[clientPrincipalHeader], "base64"); 24 | var serializedJson = buffer.toString("ascii"); 25 | return JSON.parse(serializedJson); 26 | } 27 | 28 | module.exports = { 29 | decodeAuthInfo 30 | }; -------------------------------------------------------------------------------- /funcutil/babelregister.server.js: -------------------------------------------------------------------------------- 1 | try { 2 | const register = require('react-server-dom-webpack/node-register'); 3 | register(); 4 | const babelRegister = require('@babel/register'); 5 | babelRegister({ 6 | ignore: [ 7 | // ignore build except if preceeded by react-static-web-apps-auth/ (reference to my local package) 8 | // ignore node_modules except if followed by react-static-web-apps-auth 9 | /[\\\/]((?>>>>> exiting\n\n\n"); 25 | process.exit(1); 26 | } 27 | } -------------------------------------------------------------------------------- /funcutil/react-utils.server.js: -------------------------------------------------------------------------------- 1 | const { readFileSync } = require('fs'); 2 | const path = require('path'); 3 | const { pipeToNodeWritable } = require('react-server-dom-webpack/writer'); 4 | const MemoryStream = require('memory-stream'); 5 | 6 | let moduleMapCache = null; 7 | function getModuleMap() { 8 | if (moduleMapCache) { 9 | return moduleMapCache; 10 | } 11 | 12 | const manifest = readFileSync( 13 | path.resolve(__dirname, '../build/react-client-manifest.json'), 14 | 'utf8' 15 | ); 16 | const moduleMap = JSON.parse(manifest); 17 | 18 | moduleMapCache = new Proxy(moduleMap, { 19 | get: function (target, prop, receiver) { 20 | if (target[prop]) { 21 | return target[prop]; 22 | } 23 | 24 | const bestKey = findBestMatchedKey(target, prop); 25 | if (bestKey) { 26 | return target[bestKey]; 27 | } 28 | 29 | function findBestMatchedKey(target, prop) { 30 | const propChars = prop.split(''); 31 | const scoredKeys = Object.keys(target) 32 | .map(k => { 33 | // compare strings from end and return number of matching characters 34 | const keyChars = k.split(''); 35 | 36 | for (let i = 0; i < keyChars.length && i < propChars.length; i++) { 37 | if (keyChars[keyChars.length - i - 1] !== propChars[propChars.length - i - 1]) { 38 | return { 39 | key: k, 40 | matchedChars: i 41 | }; 42 | } 43 | } 44 | return { 45 | key: k, 46 | matchedChars: 0 47 | }; 48 | }) 49 | .sort((a, b) => b.matchedChars - a.matchedChars); 50 | 51 | if (scoredKeys.length && scoredKeys[0].matchedChars) { 52 | return scoredKeys[0].key; 53 | } 54 | } 55 | } 56 | }); 57 | return moduleMapCache; 58 | } 59 | 60 | function createResponseBody(reactElement) { 61 | return new Promise((resolve) => { 62 | const outputStream = new MemoryStream(); 63 | outputStream.on('finish', () => resolve(outputStream.toString())); 64 | pipeToNodeWritable(reactElement, outputStream, getModuleMap()); 65 | }); 66 | } 67 | 68 | module.exports = { 69 | getModuleMap, 70 | createResponseBody, 71 | }; -------------------------------------------------------------------------------- /host.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "2.0", 3 | "logging": { 4 | "applicationInsights": { 5 | "samplingSettings": { 6 | "isEnabled": true, 7 | "excludedTypes": "Request" 8 | } 9 | } 10 | }, 11 | "extensionBundle": { 12 | "id": "Microsoft.Azure.Functions.ExtensionBundle", 13 | "version": "[1.*, 2.0.0)" 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /local.settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "IsEncrypted": false, 3 | "Values": { 4 | "FUNCTIONS_WORKER_RUNTIME": "node", 5 | "AzureWebJobsStorage": "", 6 | "languageWorkers__node__arguments": "--conditions=react-server", 7 | "BABEL_DISABLE_CACHE": "1", 8 | "NODE_ENV": "production" 9 | }, 10 | "Host": { 11 | "CORS": "*" 12 | } 13 | } -------------------------------------------------------------------------------- /notes/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/anthonychu/azure-functions-reactjs-server-components-demo/ab8eb1745497c74f258b0e172c65bbee4f35a600/notes/.gitkeep -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "react-notes", 3 | "version": "0.1.0", 4 | "private": true, 5 | "engines": { 6 | }, 7 | "license": "MIT", 8 | "dependencies": { 9 | "@aaronpowell/react-static-web-apps-auth": "git+https://github.com/anthonychu/react-static-web-apps-auth.git#react-server-components", 10 | "@babel/core": "7.12.3", 11 | "@babel/register": "^7.12.1", 12 | "babel-loader": "8.1.0", 13 | "babel-preset-react-app": "10.0.0", 14 | "compression": "^1.7.4", 15 | "date-fns": "^2.16.1", 16 | "excerpts": "^0.0.3", 17 | "fs": "file:fs", 18 | "html-webpack-plugin": "4.5.0", 19 | "marked": "^1.2.5", 20 | "memory-stream": "^1.0.0", 21 | "pg": "^8.5.1", 22 | "react": "0.0.0-experimental-3310209d0", 23 | "react-dom": "0.0.0-experimental-3310209d0", 24 | "react-error-boundary": "^3.1.0", 25 | "react-fetch": "0.0.0-experimental-3310209d0", 26 | "react-fs": "0.0.0-experimental-3310209d0", 27 | "react-pg": "0.0.0-experimental-3310209d0", 28 | "react-server-dom-webpack": "0.0.0-experimental-3310209d0", 29 | "resolve": "1.12.0", 30 | "rimraf": "^3.0.2", 31 | "sanitize-html": "^2.2.0", 32 | "webpack": "4.44.2" 33 | }, 34 | "devDependencies": { 35 | "cross-env": "^7.0.3", 36 | "dotenv": "^8.2.0", 37 | "filemanager-webpack-plugin": "^3.0.0", 38 | "prettier": "1.19.1", 39 | "webpack-cli": "^4.2.0" 40 | }, 41 | "scripts": { 42 | "start": "concurrently \"npm run server:dev\" \"npm run bundler:dev\"", 43 | "start:prod": "concurrently \"npm run server:prod\" \"npm run bundler:prod\"", 44 | "server:dev": "cross-env NODE_ENV=development nodemon -- --conditions=react-server server", 45 | "server:prod": "cross-env NODE_ENV=production nodemon -- --conditions=react-server server", 46 | "bundler:dev": "cross-env NODE_ENV=development nodemon -- scripts/build.js", 47 | "bundler:prod": "cross-env NODE_ENV=production nodemon -- scripts/build.js", 48 | "prettier": "prettier --write **/*.js", 49 | "seed": "node ./scripts/seed.js", 50 | "build": "cross-env NODE_ENV=production node scripts/build.js" 51 | }, 52 | "babel": { 53 | "presets": [ 54 | [ 55 | "react-app", 56 | { 57 | "runtime": "automatic" 58 | } 59 | ] 60 | ] 61 | }, 62 | "nodemonConfig": { 63 | "ignore": [ 64 | "build/*" 65 | ] 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /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/anthonychu/azure-functions-reactjs-server-components-demo/ab8eb1745497c74f258b0e172c65bbee4f35a600/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; 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 | .login-pane { 648 | padding: 60px; 649 | } 650 | 651 | a.login.azure-swa-auth { 652 | display: block; 653 | } 654 | 655 | .sidebar-login { 656 | padding: 0 24px 16px; 657 | } 658 | 659 | /* ---------------------------------------------------------------------------*/ 660 | @keyframes spin { 661 | to { 662 | transform: rotate(360deg); 663 | } 664 | } 665 | @keyframes spin { 666 | to { 667 | transform: rotate(360deg); 668 | } 669 | } 670 | 671 | @keyframes shimmer { 672 | 0% { 673 | background-position: -200px 0; 674 | } 675 | 100% { 676 | background-position: calc(200px + 100%) 0; 677 | } 678 | } 679 | 680 | @keyframes slideIn { 681 | 0% { 682 | top: -10px; 683 | opacity: 0; 684 | } 685 | 100% { 686 | top: 0; 687 | opacity: 1; 688 | } 689 | } 690 | 691 | @keyframes flash { 692 | 0% { 693 | transform: scale(1); 694 | opacity: 1; 695 | } 696 | 50% { 697 | transform: scale(1.05); 698 | opacity: 0.9; 699 | } 700 | 100% { 701 | transform: scale(1); 702 | opacity: 1; 703 | } 704 | } 705 | -------------------------------------------------------------------------------- /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 | const FileManagerPlugin = require('filemanager-webpack-plugin'); 17 | 18 | const isProduction = process.env.NODE_ENV === 'production'; 19 | rimraf.sync(path.resolve(__dirname, '../build')); 20 | webpack( 21 | { 22 | mode: isProduction ? 'production' : 'development', 23 | devtool: isProduction ? 'source-map' : 'cheap-module-source-map', 24 | entry: [path.resolve(__dirname, '../src/index.client.js')], 25 | output: { 26 | path: path.resolve(__dirname, '../build'), 27 | filename: 'main.js', 28 | }, 29 | module: { 30 | rules: [ 31 | { 32 | test: /\.js$/, 33 | use: 'babel-loader', 34 | exclude: /node_modules/, 35 | }, 36 | ], 37 | }, 38 | plugins: [ 39 | new HtmlWebpackPlugin({ 40 | inject: true, 41 | template: path.resolve(__dirname, '../public/index.html'), 42 | }), 43 | new ReactServerWebpackPlugin({ isServer: false }), 44 | new FileManagerPlugin({ 45 | events: { 46 | // copy public folder over to build, but keep what's already in build 47 | onEnd: [ 48 | { 49 | mkdir: [path.resolve(__dirname, '../buildtemp')], 50 | }, 51 | { 52 | copy: [ 53 | { 54 | source: path.resolve(__dirname, '../public'), 55 | destination: path.resolve(__dirname, '../buildtemp') 56 | }, 57 | ] 58 | }, 59 | { 60 | copy: [ 61 | { 62 | source: path.resolve(__dirname, '../build'), 63 | destination: path.resolve(__dirname, '../buildtemp') 64 | }, 65 | ] 66 | }, 67 | { 68 | copy: [ 69 | { 70 | source: path.resolve(__dirname, '../buildtemp'), 71 | destination: path.resolve(__dirname, '../build') 72 | }, 73 | ] 74 | }, 75 | { 76 | delete: [path.resolve(__dirname, '../buildtemp')] 77 | }, 78 | ], 79 | }, 80 | }), 81 | ], 82 | }, 83 | (err, stats) => { 84 | if (err) { 85 | console.error(err.stack || err); 86 | if (err.details) { 87 | console.error(err.details); 88 | } 89 | process.exit(1); 90 | return; 91 | } 92 | const info = stats.toJson(); 93 | if (stats.hasErrors()) { 94 | console.log('Finished running webpack with errors.'); 95 | info.errors.forEach((e) => console.error(e)); 96 | process.exit(1); 97 | } else { 98 | console.log('Finished running webpack.'); 99 | } 100 | } 101 | ); 102 | -------------------------------------------------------------------------------- /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 | userid TEXT, 37 | body TEXT 38 | );`; 39 | const insertNoteStatement = `INSERT INTO notes(title, body, created_at, updated_at) 40 | VALUES ($1, $2, $3, $3) 41 | RETURNING *`; 42 | const seedData = [ 43 | [ 44 | 'Meeting Notes', 45 | 'This is an example note. It contains **Markdown**!', 46 | randomDateBetween(startOfThisYear, now), 47 | ], 48 | [ 49 | 'Make a thing', 50 | `It's very easy to make some words **bold** and other words *italic* with 51 | Markdown. You can even [link to React's website!](https://www.reactjs.org).`, 52 | randomDateBetween(startOfThisYear, now), 53 | ], 54 | [ 55 | 'A note with a very long title because sometimes you need more words', 56 | `You can write all kinds of [amazing](https://en.wikipedia.org/wiki/The_Amazing) 57 | notes in this app! These note live on the server in the \`notes\` folder. 58 | 59 | ![This app is powered by React](https://upload.wikimedia.org/wikipedia/commons/thumb/1/18/React_Native_Logo.png/800px-React_Native_Logo.png)`, 60 | randomDateBetween(startOfThisYear, now), 61 | ], 62 | ['I wrote this note today', 'It was an excellent note.', now], 63 | ]; 64 | 65 | async function seed() { 66 | await pool.query(dropTableStatement); 67 | await pool.query(createTableStatement); 68 | const res = await Promise.all( 69 | seedData.map((row) => pool.query(insertNoteStatement, row)) 70 | ); 71 | console.log(res); 72 | 73 | // const oldNotes = await readdir(path.resolve(NOTES_PATH)); 74 | // await Promise.all( 75 | // oldNotes 76 | // .filter((filename) => filename.endsWith('.md')) 77 | // .map((filename) => unlink(path.resolve(NOTES_PATH, filename))) 78 | // ); 79 | 80 | // await Promise.all( 81 | // res.map(({rows}) => { 82 | // const id = rows[0].id; 83 | // const content = rows[0].body; 84 | // const data = new Uint8Array(Buffer.from(content)); 85 | // return writeFile(path.resolve(NOTES_PATH, `${id}.md`), data, (err) => { 86 | // if (err) { 87 | // throw err; 88 | // } 89 | // }); 90 | // }) 91 | // ); 92 | } 93 | 94 | seed(); 95 | -------------------------------------------------------------------------------- /src/App.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 | import { Suspense } from 'react'; 10 | 11 | import Note from './Note.server'; 12 | import NoteList from './NoteList.server'; 13 | import EditButton from './EditButton.client'; 14 | import SearchField from './SearchField.client'; 15 | import NoteSkeleton from './NoteSkeleton'; 16 | import NoteListSkeleton from './NoteListSkeleton'; 17 | 18 | import { Logout, StaticWebAuthLogins } from "@aaronpowell/react-static-web-apps-auth"; 19 | 20 | export default function App({ selectedId, isEditing, searchText, userInfo }) { 21 | 22 | return ( 23 |
24 |
25 |
26 | 34 | React Notes 35 |
36 | { userInfo && 37 | <> 38 |
39 | {userInfo.userDetails} | 40 |
41 |
42 | 43 | New 44 |
45 | 50 | 51 | } 52 |
53 | { 54 | userInfo 55 | ?
56 | }> 57 | 58 | 59 |
60 | :
61 |

62 | Welcome to the a demo of React Server Components running on Azure Static Web Apps. 63 | See the GitHub repo to learn more. 64 |
  65 |

66 |

67 | To view and edit notes, log in with one of these providers:
  68 |

69 | 70 |
71 | } 72 |
73 | ); 74 | } 75 | -------------------------------------------------------------------------------- /src/Cache.client.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 {unstable_getCacheForType, unstable_useCacheRefresh} from 'react'; 10 | import {createFromFetch} from 'react-server-dom-webpack'; 11 | import { apiBaseUrl } from './config'; 12 | 13 | function createResponseCache() { 14 | return new Map(); 15 | } 16 | 17 | export function useRefresh() { 18 | const refreshCache = unstable_useCacheRefresh(); 19 | return function refresh(key, seededResponse) { 20 | refreshCache(createResponseCache, new Map([[key, seededResponse]])); 21 | }; 22 | } 23 | 24 | export function useServerResponse(location) { 25 | const key = JSON.stringify(location); 26 | const cache = unstable_getCacheForType(createResponseCache); 27 | let response = cache.get(key); 28 | if (response) { 29 | return response; 30 | } 31 | const env = process.env.NODE_ENV; 32 | response = createFromFetch( 33 | fetch(apiBaseUrl + '/react?location=' + encodeURIComponent(key)) 34 | ); 35 | cache.set(key, response); 36 | return response; 37 | } 38 | -------------------------------------------------------------------------------- /src/EditButton.client.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 {unstable_useTransition} from 'react'; 10 | 11 | import {useLocation} from './LocationContext.client'; 12 | 13 | export default function EditButton({noteId, children}) { 14 | const [, setLocation] = useLocation(); 15 | const [startTransition, isPending] = unstable_useTransition(); 16 | const isDraft = noteId == null; 17 | return ( 18 | 36 | ); 37 | } 38 | -------------------------------------------------------------------------------- /src/LocationContext.client.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 {createContext, useContext} from 'react'; 10 | 11 | export const LocationContext = createContext(); 12 | export function useLocation() { 13 | return useContext(LocationContext); 14 | } 15 | -------------------------------------------------------------------------------- /src/Note.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 | import { fetch } from 'react-fetch'; 10 | import { readFile } from 'react-fs'; 11 | import { format } from 'date-fns'; 12 | import path from 'path'; 13 | 14 | import { db } from './db.server'; 15 | import NotePreview from './NotePreview'; 16 | import EditButton from './EditButton.client'; 17 | import NoteEditor from './NoteEditor.client'; 18 | 19 | export default function Note({ selectedId, isEditing, userInfo }) { 20 | let note = null; 21 | 22 | if (selectedId !== null && userInfo) { 23 | const notes = db.query( 24 | 'select * from notes where id = $1 and userid = $2', 25 | [ selectedId, userInfo.userId ] 26 | ).rows; 27 | 28 | if (notes.length) { 29 | note = notes[0]; 30 | } 31 | } 32 | 33 | if (note === null) { 34 | if (isEditing) { 35 | return ( 36 | 37 | ); 38 | } else { 39 | return ( 40 |
41 | 42 | Click a note on the left to view something! 🥺 43 | 44 |
45 | ); 46 | } 47 | } 48 | 49 | let { id, title, body, updated_at } = note; 50 | const updatedAt = new Date(updated_at); 51 | 52 | // We could also read from a file instead. 53 | // body = readFile(path.resolve(`./notes/${note.id}.md`), 'utf8'); 54 | 55 | // Now let's see how the Suspense boundary above lets us not block on this. 56 | // fetch('http://localhost:4000/sleep/3000'); 57 | 58 | if (isEditing) { 59 | return ; 60 | } else { 61 | return ( 62 |
63 |
64 |

{title}

65 |
66 | 67 | Last updated on {format(updatedAt, "d MMM yyyy 'at' h:mm bb")} 68 | 69 | Edit 70 |
71 |
72 | 73 |
74 | ); 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /src/NoteEditor.client.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 {useState, unstable_useTransition} from 'react'; 10 | import {createFromReadableStream} from 'react-server-dom-webpack'; 11 | import {apiBaseUrl} from './config'; 12 | 13 | import NotePreview from './NotePreview'; 14 | import {useRefresh} from './Cache.client'; 15 | import {useLocation} from './LocationContext.client'; 16 | 17 | export default function NoteEditor({noteId, initialTitle, initialBody}) { 18 | const refresh = useRefresh(); 19 | const [title, setTitle] = useState(initialTitle); 20 | const [body, setBody] = useState(initialBody); 21 | const [location, setLocation] = useLocation(); 22 | const [startNavigating, isNavigating] = unstable_useTransition(); 23 | const [isSaving, saveNote] = useMutation({ 24 | endpoint: noteId !== null ? `${apiBaseUrl}/notes/${noteId}` : `${apiBaseUrl}/notes`, 25 | method: noteId !== null ? 'PUT' : 'POST', 26 | }); 27 | const [isDeleting, deleteNote] = useMutation({ 28 | endpoint: `${apiBaseUrl}/notes/${noteId}`, 29 | method: 'DELETE', 30 | }); 31 | 32 | async function handleSave() { 33 | const payload = {title, body}; 34 | const requestedLocation = { 35 | selectedId: noteId, 36 | isEditing: false, 37 | searchText: location.searchText, 38 | }; 39 | const response = await saveNote(payload, requestedLocation); 40 | navigate(response); 41 | } 42 | 43 | async function handleDelete() { 44 | const payload = {}; 45 | const requestedLocation = { 46 | selectedId: null, 47 | isEditing: false, 48 | searchText: location.searchText, 49 | }; 50 | const response = await deleteNote(payload, requestedLocation); 51 | navigate(response); 52 | } 53 | 54 | function navigate(response) { 55 | let cacheKey = response.headers.get('X-Location'); 56 | let nextLocation = JSON.parse(cacheKey); 57 | const seededResponse = createFromReadableStream(response.body); 58 | startNavigating(() => { 59 | refresh(cacheKey, seededResponse); 60 | setLocation(nextLocation); 61 | }); 62 | } 63 | 64 | const isDraft = noteId === null; 65 | return ( 66 |
67 |
e.preventDefault()}> 71 | 74 | { 79 | setTitle(e.target.value); 80 | }} 81 | /> 82 | 85 |