├── .gitignore
├── CODE_OF_CONDUCT.md
├── CONTRIBUTING.md
├── LICENSE
├── README.md
├── assets
├── aws-exports.png
├── basic-vite-cdk-cognito-auth.png
├── basic-vite.png
├── chat-ui-vite.png
├── empty-vite.png
├── full-stack-chat-ui-cognito-auth-01.png
├── full-stack-chat-ui-cognito-auth-02.png
├── full-stack-chat-ui-cognito-auth-03.png
├── full-stack-chat-ui-cognito-auth-04.png
├── fullstack-chat-ui-cognito-auth-architecture.png
├── fullstack-vite-cdk-cognito-auth-01.png
├── fullstack-vite-cdk-cognito-auth-02.png
└── fullstack-vite-cdk-cognito-auth-architecture.png
├── basic-vite
├── .eslintrc.cjs
├── README.md
├── index.html
├── package-lock.json
├── package.json
├── postcss.config.js
├── prettier.config.cjs
├── public
│ ├── favicon.ico
│ ├── images
│ │ ├── android-chrome-192x192.png
│ │ ├── android-chrome-512x512.png
│ │ ├── apple-touch-icon.png
│ │ ├── favicon-16x16.png
│ │ ├── favicon-32x32.png
│ │ ├── favicon.ico
│ │ └── logo.png
│ └── manifest.json
├── src
│ ├── app.tsx
│ ├── common
│ │ ├── api-client
│ │ │ ├── api-client.ts
│ │ │ └── items-api-client.ts
│ │ ├── constants.ts
│ │ ├── helpers
│ │ │ ├── storage-helper.ts
│ │ │ └── text-helper.ts
│ │ ├── hooks
│ │ │ ├── use-navigation-panel-state.ts
│ │ │ └── use-on-follow.ts
│ │ ├── i18n
│ │ │ └── property-filter-i18n-strings.ts
│ │ ├── types.ts
│ │ └── utils.ts
│ ├── components
│ │ ├── base-app-layout.tsx
│ │ ├── global-header.tsx
│ │ ├── navigation-panel.tsx
│ │ └── wrappers
│ │ │ ├── router-button-dropdown.tsx
│ │ │ ├── router-button.tsx
│ │ │ └── router-link.tsx
│ ├── main.tsx
│ ├── pages
│ │ ├── dashboard
│ │ │ ├── dashboard-header.tsx
│ │ │ ├── dashboard-page.tsx
│ │ │ ├── items-table.tsx
│ │ │ └── statistics-block.tsx
│ │ ├── not-found.tsx
│ │ └── section1
│ │ │ ├── add-item
│ │ │ └── add-item-page.tsx
│ │ │ ├── all-items
│ │ │ ├── all-items-header.tsx
│ │ │ ├── all-items-page.tsx
│ │ │ └── all-items-table.tsx
│ │ │ └── view-item
│ │ │ └── view-item-page.tsx
│ ├── styles
│ │ └── app.scss
│ └── vite-env.d.ts
├── tsconfig.json
├── tsconfig.node.json
└── vite.config.ts
├── chat-ui-vite
├── .eslintrc.cjs
├── README.md
├── index.html
├── package-lock.json
├── package.json
├── postcss.config.js
├── prettier.config.cjs
├── public
│ ├── favicon.ico
│ ├── images
│ │ ├── android-chrome-192x192.png
│ │ ├── android-chrome-512x512.png
│ │ ├── apple-touch-icon.png
│ │ ├── favicon-16x16.png
│ │ ├── favicon-32x32.png
│ │ ├── favicon.ico
│ │ └── logo.png
│ └── manifest.json
├── src
│ ├── app.tsx
│ ├── common
│ │ ├── constants.ts
│ │ ├── helpers
│ │ │ └── storage-helper.ts
│ │ ├── hooks
│ │ │ ├── use-navigation-panel-state.ts
│ │ │ └── use-on-follow.ts
│ │ └── types.ts
│ ├── components
│ │ ├── base-app-layout.tsx
│ │ ├── chat-ui
│ │ │ ├── chat-ui-input-panel.tsx
│ │ │ ├── chat-ui-message-list.tsx
│ │ │ ├── chat-ui-message.tsx
│ │ │ ├── chat-ui.tsx
│ │ │ └── types.tsx
│ │ ├── global-header.tsx
│ │ ├── navigation-panel.tsx
│ │ └── wrappers
│ │ │ ├── router-button-dropdown.tsx
│ │ │ ├── router-button.tsx
│ │ │ └── router-link.tsx
│ ├── main.tsx
│ ├── pages
│ │ ├── chat-page.tsx
│ │ └── not-found.tsx
│ ├── styles
│ │ ├── app.scss
│ │ └── chat-ui.module.scss
│ └── vite-env.d.ts
├── tsconfig.json
├── tsconfig.node.json
└── vite.config.ts
├── empty-vite
├── .eslintrc.cjs
├── README.md
├── index.html
├── package-lock.json
├── package.json
├── postcss.config.js
├── prettier.config.cjs
├── public
│ ├── favicon.ico
│ ├── images
│ │ ├── android-chrome-192x192.png
│ │ ├── android-chrome-512x512.png
│ │ ├── apple-touch-icon.png
│ │ ├── favicon-16x16.png
│ │ ├── favicon-32x32.png
│ │ ├── favicon.ico
│ │ └── logo.png
│ └── manifest.json
├── src
│ ├── app.tsx
│ ├── common
│ │ ├── constants.ts
│ │ ├── helpers
│ │ │ └── storage-helper.ts
│ │ ├── hooks
│ │ │ ├── use-navigation-panel-state.ts
│ │ │ └── use-on-follow.ts
│ │ └── types.ts
│ ├── components
│ │ ├── base-app-layout.tsx
│ │ ├── global-header.tsx
│ │ ├── navigation-panel.tsx
│ │ └── wrappers
│ │ │ ├── router-button-dropdown.tsx
│ │ │ ├── router-button.tsx
│ │ │ └── router-link.tsx
│ ├── main.tsx
│ ├── pages
│ │ ├── home.tsx
│ │ └── not-found.tsx
│ ├── styles
│ │ └── app.scss
│ └── vite-env.d.ts
├── tsconfig.json
├── tsconfig.node.json
└── vite.config.ts
├── full-stack-chat-ui-cognito-auth
├── .eslintrc.cjs
├── .npmignore
├── README.md
├── bin
│ └── index.ts
├── cdk.json
├── functions
│ └── api-handler
│ │ ├── index.py
│ │ ├── requirements.txt
│ │ ├── routes
│ │ ├── chat.py
│ │ └── health.py
│ │ └── utils.py
├── jest.config.js
├── lib
│ ├── infrastructure-stack.ts
│ └── utils.ts
├── package-lock.json
├── package.json
├── prettier.config.cjs
├── tsconfig.json
└── user-interface
│ ├── .eslintrc.cjs
│ ├── README.md
│ ├── index.html
│ ├── package-lock.json
│ ├── package.json
│ ├── postcss.config.js
│ ├── prettier.config.cjs
│ ├── public
│ ├── aws-exports.template.json
│ ├── favicon.ico
│ ├── images
│ │ ├── android-chrome-192x192.png
│ │ ├── android-chrome-512x512.png
│ │ ├── apple-touch-icon.png
│ │ ├── favicon-16x16.png
│ │ ├── favicon-32x32.png
│ │ ├── favicon.ico
│ │ └── logo.png
│ └── manifest.json
│ ├── src
│ ├── app.tsx
│ ├── common
│ │ ├── api-client
│ │ │ ├── api-client-base.ts
│ │ │ ├── api-client.ts
│ │ │ └── chat-api-client.ts
│ │ ├── constants.ts
│ │ ├── helpers
│ │ │ └── storage-helper.ts
│ │ ├── hooks
│ │ │ ├── use-navigation-panel-state.ts
│ │ │ └── use-on-follow.ts
│ │ └── types.ts
│ ├── components
│ │ ├── app-configured.tsx
│ │ ├── base-app-layout.tsx
│ │ ├── chat-ui
│ │ │ ├── Avatar.tsx
│ │ │ ├── BaseChatMessage.tsx
│ │ │ ├── CopyButton.tsx
│ │ │ ├── chat-ui-input-panel.tsx
│ │ │ ├── chat-ui-message.tsx
│ │ │ ├── chat-ui.tsx
│ │ │ └── types.tsx
│ │ ├── global-header.tsx
│ │ ├── navigation-panel.tsx
│ │ └── wrappers
│ │ │ ├── router-button-dropdown.tsx
│ │ │ ├── router-button.tsx
│ │ │ └── router-link.tsx
│ ├── main.tsx
│ ├── pages
│ │ ├── chat-page.tsx
│ │ └── not-found.tsx
│ ├── styles
│ │ ├── app.scss
│ │ └── chat-ui.module.scss
│ └── vite-env.d.ts
│ ├── tsconfig.json
│ ├── tsconfig.node.json
│ └── vite.config.ts
└── fullstack-vite-cdk-cognito-auth
├── .eslintrc.cjs
├── .npmignore
├── README.md
├── bin
└── index.ts
├── cdk.json
├── functions
└── api-handler
│ ├── index.py
│ ├── requirements.txt
│ ├── routes
│ ├── health.py
│ └── items.py
│ └── utils.py
├── jest.config.js
├── lib
├── infrastructure-stack.ts
└── utils.ts
├── package-lock.json
├── package.json
├── prettier.config.cjs
├── tsconfig.json
└── user-interface
├── index.html
├── package.json
├── postcss.config.js
├── prettier.config.cjs
├── public
├── aws-exports.template.json
├── favicon.ico
├── images
│ ├── android-chrome-192x192.png
│ ├── android-chrome-512x512.png
│ ├── apple-touch-icon.png
│ ├── favicon-16x16.png
│ ├── favicon-32x32.png
│ ├── favicon.ico
│ └── logo.png
└── manifest.json
├── src
├── app.tsx
├── common
│ ├── api-client
│ │ ├── api-client-base.ts
│ │ ├── api-client.ts
│ │ └── items-api-client.ts
│ ├── constants.ts
│ ├── helpers
│ │ ├── storage-helper.ts
│ │ └── text-helper.ts
│ ├── hooks
│ │ ├── use-form.ts
│ │ ├── use-navigation-panel-state.ts
│ │ └── use-on-follow.ts
│ ├── i18n
│ │ └── property-filter-i18n-strings.ts
│ ├── types.ts
│ └── utils.ts
├── components
│ ├── app-configured.tsx
│ ├── base-app-layout.tsx
│ ├── global-header.tsx
│ ├── modals
│ │ └── item-delete-modal.tsx
│ ├── navigation-panel.tsx
│ └── wrappers
│ │ ├── router-button-dropdown.tsx
│ │ ├── router-button.tsx
│ │ └── router-link.tsx
├── main.tsx
├── pages
│ ├── dashboard
│ │ ├── dashboard-header.tsx
│ │ ├── dashboard-page.tsx
│ │ ├── items-table.tsx
│ │ └── statistics-block.tsx
│ ├── not-found.tsx
│ └── section1
│ │ ├── add-item
│ │ └── add-item-page.tsx
│ │ ├── all-items
│ │ ├── all-items-header.tsx
│ │ ├── all-items-page.tsx
│ │ └── all-items-table.tsx
│ │ └── view-item
│ │ └── view-item-page.tsx
├── styles
│ └── app.scss
└── vite-env.d.ts
├── tsconfig.json
├── tsconfig.node.json
└── vite.config.ts
/CODE_OF_CONDUCT.md:
--------------------------------------------------------------------------------
1 | ## Code of Conduct
2 | This project has adopted the [Amazon Open Source Code of Conduct](https://aws.github.io/code-of-conduct).
3 | For more information see the [Code of Conduct FAQ](https://aws.github.io/code-of-conduct-faq) or contact
4 | opensource-codeofconduct@amazon.com with any additional questions or comments.
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | # Contributing Guidelines
2 |
3 | Thank you for your interest in contributing to our project. Whether it's a bug report, new feature, correction, or additional
4 | documentation, we greatly value feedback and contributions from our community.
5 |
6 | Please read through this document before submitting any issues or pull requests to ensure we have all the necessary
7 | information to effectively respond to your bug report or contribution.
8 |
9 |
10 | ## Reporting Bugs/Feature Requests
11 |
12 | We welcome you to use the GitHub issue tracker to report bugs or suggest features.
13 |
14 | When filing an issue, please check existing open, or recently closed, issues to make sure somebody else hasn't already
15 | reported the issue. Please try to include as much information as you can. Details like these are incredibly useful:
16 |
17 | * A reproducible test case or series of steps
18 | * The version of our code being used
19 | * Any modifications you've made relevant to the bug
20 | * Anything unusual about your environment or deployment
21 |
22 |
23 | ## Contributing via Pull Requests
24 | Contributions via pull requests are much appreciated. Before sending us a pull request, please ensure that:
25 |
26 | 1. You are working against the latest source on the *main* branch.
27 | 2. You check existing open, and recently merged, pull requests to make sure someone else hasn't addressed the problem already.
28 | 3. You open an issue to discuss any significant work - we would hate for your time to be wasted.
29 |
30 | To send us a pull request, please:
31 |
32 | 1. Fork the repository.
33 | 2. Modify the source; please focus on the specific change you are contributing. If you also reformat all the code, it will be hard for us to focus on your change.
34 | 3. Ensure local tests pass.
35 | 4. Commit to your fork using clear commit messages.
36 | 5. Send us a pull request, answering any default questions in the pull request interface.
37 | 6. Pay attention to any automated CI failures reported in the pull request, and stay involved in the conversation.
38 |
39 | GitHub provides additional document on [forking a repository](https://help.github.com/articles/fork-a-repo/) and
40 | [creating a pull request](https://help.github.com/articles/creating-a-pull-request/).
41 |
42 |
43 | ## Finding contributions to work on
44 | Looking at the existing issues is a great way to find something to contribute on. As our projects, by default, use the default GitHub issue labels (enhancement/bug/duplicate/help wanted/invalid/question/wontfix), looking at any 'help wanted' issues is a great place to start.
45 |
46 |
47 | ## Code of Conduct
48 | This project has adopted the [Amazon Open Source Code of Conduct](https://aws.github.io/code-of-conduct).
49 | For more information see the [Code of Conduct FAQ](https://aws.github.io/code-of-conduct-faq) or contact
50 | opensource-codeofconduct@amazon.com with any additional questions or comments.
51 |
52 |
53 | ## Security issue notifications
54 | If you discover a potential security issue in this project we ask that you notify AWS/Amazon Security via our [vulnerability reporting page](http://aws.amazon.com/security/vulnerability-reporting/). Please do **not** create a public github issue.
55 |
56 |
57 | ## Licensing
58 |
59 | See the [LICENSE](LICENSE) file for our project's licensing. We will ask you to confirm the licensing of your contribution.
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT No Attribution
2 |
3 | Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy of
6 | this software and associated documentation files (the "Software"), to deal in
7 | the Software without restriction, including without limitation the rights to
8 | use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
9 | the Software, and to permit persons to whom the Software is furnished to do so.
10 |
11 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
12 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
13 | FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
14 | COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
15 | IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
16 | CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
17 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Cloudscape Examples
2 |
3 | [https://cloudscape.design/](https://cloudscape.design/)
4 |
5 | Cloudscape is an open source design system for the cloud. Cloudscape offers user interface guidelines, front-end components, design resources, and development tools for building intuitive, engaging, and inclusive user experiences at scale.
6 |
7 | This repository provides ready-to-use examples of Cloudscape React projects.
8 |
9 | 
10 | 
11 | 
12 |
13 |
14 | # Examples
15 |
16 | |Name|Description|
17 | |:-------------|:-------------|
18 | |[Empty Cloudscape app](empty-vite) | Cloudscape example built with React Router and Vite.|
19 | |[Basic Cloudscape app](basic-vite) | Cloudscape example built with React Router and Vite, featuring a dashboard page, a table page, details page, and an add page.|
20 | |[Fullstack Cloudscape app with CDK and Cognito auth](fullstack-vite-cdk-cognito-auth) | Cloudscape fullstack example built with React Router and Vite, featuring a dashboard page, a table page, details page, and an add page. It is deployable with AWS CDK (Cloud Development Kit). The example deploys the frontend as a static website to an S3 bucket and serves it with Amazon CloudFront. It utilizes Amazon Cognito for authentication and Amplify UI for React for the login user interface. Data is stored in Amazon DynamoDB. The REST API is implemented with Amazon API Gateway and AWS Lambda and uses Powertools for AWS Lambda.|
21 | | [Chat UI for Cloudscape](chat-ui-vite) | Cloudscape example featuring a Chat UI, with a message input field and a list of messages.|
22 | |[Fullstack Chat UI app with CDK and Cognito auth](full-stack-chat-ui-cognito-auth) | Cloudscape fullstack Chat UI example built with React Router and Vite, featuring a chat bot page. It is deployable with AWS CDK (Cloud Development Kit). The example deploys the frontend as a static website to an S3 bucket and serves it with Amazon CloudFront. It utilizes Amazon Cognito for authentication and Amplify UI for React for the login user interface. The REST API is implemented with Amazon API Gateway and AWS Lambda and uses Powertools for AWS Lambda.|
23 |
24 |
25 | # License
26 |
27 | This library is licensed under the MIT-0 License. See the LICENSE file.
28 |
29 | - [License](LICENSE) of the project.
30 | - [Code of Conduct](CODE_OF_CONDUCT.md) of the project.
31 | - [CONTRIBUTING](CONTRIBUTING.md#security-issue-notifications) for more information.
32 |
33 | # Legal Disclaimer
34 |
35 | You should consider doing your own independent assessment before using the content in this repository for production purposes. This may include (amongst other things) testing, securing, and optimizing the content provided in this repository, based on your specific quality control practices and standards.
--------------------------------------------------------------------------------
/assets/aws-exports.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/aws-samples/cloudscape-examples/35055cf8fb197302784028998a9d8c3c55acea78/assets/aws-exports.png
--------------------------------------------------------------------------------
/assets/basic-vite-cdk-cognito-auth.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/aws-samples/cloudscape-examples/35055cf8fb197302784028998a9d8c3c55acea78/assets/basic-vite-cdk-cognito-auth.png
--------------------------------------------------------------------------------
/assets/basic-vite.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/aws-samples/cloudscape-examples/35055cf8fb197302784028998a9d8c3c55acea78/assets/basic-vite.png
--------------------------------------------------------------------------------
/assets/chat-ui-vite.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/aws-samples/cloudscape-examples/35055cf8fb197302784028998a9d8c3c55acea78/assets/chat-ui-vite.png
--------------------------------------------------------------------------------
/assets/empty-vite.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/aws-samples/cloudscape-examples/35055cf8fb197302784028998a9d8c3c55acea78/assets/empty-vite.png
--------------------------------------------------------------------------------
/assets/full-stack-chat-ui-cognito-auth-01.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/aws-samples/cloudscape-examples/35055cf8fb197302784028998a9d8c3c55acea78/assets/full-stack-chat-ui-cognito-auth-01.png
--------------------------------------------------------------------------------
/assets/full-stack-chat-ui-cognito-auth-02.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/aws-samples/cloudscape-examples/35055cf8fb197302784028998a9d8c3c55acea78/assets/full-stack-chat-ui-cognito-auth-02.png
--------------------------------------------------------------------------------
/assets/full-stack-chat-ui-cognito-auth-03.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/aws-samples/cloudscape-examples/35055cf8fb197302784028998a9d8c3c55acea78/assets/full-stack-chat-ui-cognito-auth-03.png
--------------------------------------------------------------------------------
/assets/full-stack-chat-ui-cognito-auth-04.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/aws-samples/cloudscape-examples/35055cf8fb197302784028998a9d8c3c55acea78/assets/full-stack-chat-ui-cognito-auth-04.png
--------------------------------------------------------------------------------
/assets/fullstack-chat-ui-cognito-auth-architecture.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/aws-samples/cloudscape-examples/35055cf8fb197302784028998a9d8c3c55acea78/assets/fullstack-chat-ui-cognito-auth-architecture.png
--------------------------------------------------------------------------------
/assets/fullstack-vite-cdk-cognito-auth-01.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/aws-samples/cloudscape-examples/35055cf8fb197302784028998a9d8c3c55acea78/assets/fullstack-vite-cdk-cognito-auth-01.png
--------------------------------------------------------------------------------
/assets/fullstack-vite-cdk-cognito-auth-02.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/aws-samples/cloudscape-examples/35055cf8fb197302784028998a9d8c3c55acea78/assets/fullstack-vite-cdk-cognito-auth-02.png
--------------------------------------------------------------------------------
/assets/fullstack-vite-cdk-cognito-auth-architecture.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/aws-samples/cloudscape-examples/35055cf8fb197302784028998a9d8c3c55acea78/assets/fullstack-vite-cdk-cognito-auth-architecture.png
--------------------------------------------------------------------------------
/basic-vite/.eslintrc.cjs:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | root: true,
3 | env: { browser: true, es2020: true },
4 | extends: [
5 | 'eslint:recommended',
6 | 'plugin:@typescript-eslint/recommended',
7 | 'plugin:react-hooks/recommended',
8 | ],
9 | ignorePatterns: ['dist', '.eslintrc.cjs'],
10 | parser: '@typescript-eslint/parser',
11 | plugins: ['react-refresh'],
12 | rules: {
13 | 'react-refresh/only-export-components': ['warn', { allowConstantExport: true }],
14 | },
15 | };
16 |
--------------------------------------------------------------------------------
/basic-vite/README.md:
--------------------------------------------------------------------------------
1 | # Basic Cloudscape App
2 |
3 | [https://cloudscape.design/](https://cloudscape.design/)
4 |
5 | Cloudscape is an open source design system for the cloud. Cloudscape offers user interface guidelines, front-end components, design resources, and development tools for building intuitive, engaging, and inclusive user experiences at scale.
6 |
7 |
8 | 
9 |
10 |
11 | ## Vite.js
12 |
13 | [https://vitejs.dev/](https://vitejs.dev/)
14 |
15 | Vite.js is a modern, fast front-end build tool that significantly improves the developer experience when building web applications.
16 |
17 | ## Development
18 | 1. Clone this repository to your local machine
19 | ```bash
20 | git clone https://github.com/aws-samples/cloudscape-examples
21 | cd cloudscape-examples/basic-vite
22 | ```
23 | 2. Install the project dependencies by running:
24 | ```bash
25 | npm install
26 | ```
27 | 3. To start the development server, run:
28 | ```bash
29 | npm run dev
30 | ```
31 |
32 | This command will start a local development server at ``http://localhost:3000`` (or a different port if 3000 is in use). The server will hot-reload if you make edits to any of the source files.
33 |
34 | ## Building the App
35 | To build the application for production, run:
36 | ```bash
37 | npm run build
38 | ```
39 | This command will generate a dist folder containing the production build of your app. Vite optimizes your project for the best performance during this process.
40 |
41 | ## Running the App Locally
42 | After building the app, you can serve it locally using:
43 | ```bash
44 | npm run preview
45 | ```
46 | This command serves the production build from the dist folder, allowing you to preview the app before deployment.
--------------------------------------------------------------------------------
/basic-vite/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
12 |
17 |
18 |
19 | Example App
20 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
--------------------------------------------------------------------------------
/basic-vite/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "cloudscape-app",
3 | "private": true,
4 | "version": "0.0.0",
5 | "type": "module",
6 | "scripts": {
7 | "dev": "vite",
8 | "build": "tsc && vite build",
9 | "preview": "vite preview",
10 | "lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0",
11 | "format": "npx prettier --ignore-path .gitignore --write \"**/*.+(tsx|js|ts|json)\""
12 | },
13 | "dependencies": {
14 | "@cloudscape-design/components": "^3.0.611",
15 | "@cloudscape-design/design-tokens": "^3.0.35",
16 | "@cloudscape-design/global-styles": "^1.0.27",
17 | "react": "^18.2.0",
18 | "react-dom": "^18.2.0",
19 | "react-router-dom": "^6.22.0"
20 | },
21 | "devDependencies": {
22 | "@types/react": "^18.2.55",
23 | "@types/react-dom": "^18.2.19",
24 | "@typescript-eslint/eslint-plugin": "^6.21.0",
25 | "@typescript-eslint/parser": "^6.21.0",
26 | "@vitejs/plugin-react": "^4.3.2",
27 | "autoprefixer": "^10.4.17",
28 | "eslint": "^8.56.0",
29 | "eslint-plugin-react-hooks": "^4.6.0",
30 | "eslint-plugin-react-refresh": "^0.4.5",
31 | "postcss": "^8.4.38",
32 | "sass": "^1.75.0",
33 | "typescript": "^5.4.5",
34 | "vite": "^5.4.8"
35 | },
36 | "overrides": {
37 | "react-virtual": {
38 | "react": "^18.0.0"
39 | }
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/basic-vite/postcss.config.js:
--------------------------------------------------------------------------------
1 | export default {
2 | plugins: {
3 | autoprefixer: {},
4 | },
5 | };
6 |
--------------------------------------------------------------------------------
/basic-vite/prettier.config.cjs:
--------------------------------------------------------------------------------
1 | // eslint-disable-next-line no-undef
2 | module.export = {
3 | semi: true,
4 | trailingComma: "es5",
5 | singleQuote: false,
6 | tabWidth: 2,
7 | useTabs: false,
8 | };
9 |
--------------------------------------------------------------------------------
/basic-vite/public/favicon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/aws-samples/cloudscape-examples/35055cf8fb197302784028998a9d8c3c55acea78/basic-vite/public/favicon.ico
--------------------------------------------------------------------------------
/basic-vite/public/images/android-chrome-192x192.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/aws-samples/cloudscape-examples/35055cf8fb197302784028998a9d8c3c55acea78/basic-vite/public/images/android-chrome-192x192.png
--------------------------------------------------------------------------------
/basic-vite/public/images/android-chrome-512x512.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/aws-samples/cloudscape-examples/35055cf8fb197302784028998a9d8c3c55acea78/basic-vite/public/images/android-chrome-512x512.png
--------------------------------------------------------------------------------
/basic-vite/public/images/apple-touch-icon.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/aws-samples/cloudscape-examples/35055cf8fb197302784028998a9d8c3c55acea78/basic-vite/public/images/apple-touch-icon.png
--------------------------------------------------------------------------------
/basic-vite/public/images/favicon-16x16.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/aws-samples/cloudscape-examples/35055cf8fb197302784028998a9d8c3c55acea78/basic-vite/public/images/favicon-16x16.png
--------------------------------------------------------------------------------
/basic-vite/public/images/favicon-32x32.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/aws-samples/cloudscape-examples/35055cf8fb197302784028998a9d8c3c55acea78/basic-vite/public/images/favicon-32x32.png
--------------------------------------------------------------------------------
/basic-vite/public/images/favicon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/aws-samples/cloudscape-examples/35055cf8fb197302784028998a9d8c3c55acea78/basic-vite/public/images/favicon.ico
--------------------------------------------------------------------------------
/basic-vite/public/images/logo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/aws-samples/cloudscape-examples/35055cf8fb197302784028998a9d8c3c55acea78/basic-vite/public/images/logo.png
--------------------------------------------------------------------------------
/basic-vite/public/manifest.json:
--------------------------------------------------------------------------------
1 | {
2 | "id": "/",
3 | "start_url": "/",
4 | "name": "Example App",
5 | "short_name": "Example App",
6 | "description": "Example App sample",
7 | "theme_color": "#000000",
8 | "background_color": "#ffffff",
9 | "display": "standalone",
10 | "icons": [
11 | {
12 | "src": "/images/android-chrome-192x192.png",
13 | "sizes": "192x192",
14 | "type": "image/png"
15 | },
16 | {
17 | "src": "/images/android-chrome-512x512.png",
18 | "sizes": "512x512",
19 | "type": "image/png"
20 | }
21 | ]
22 | }
23 |
--------------------------------------------------------------------------------
/basic-vite/src/app.tsx:
--------------------------------------------------------------------------------
1 | import {
2 | HashRouter,
3 | BrowserRouter,
4 | Routes,
5 | Route,
6 | Outlet,
7 | } from "react-router-dom";
8 | import { USE_BROWSER_ROUTER } from "./common/constants";
9 | import GlobalHeader from "./components/global-header";
10 | import DashboardPage from "./pages/dashboard/dashboard-page";
11 | import ViewItemPage from "./pages/section1/view-item/view-item-page";
12 | import AllItemsPage from "./pages/section1/all-items/all-items-page";
13 | import AddItemPage from "./pages/section1/add-item/add-item-page";
14 | import NotFound from "./pages/not-found";
15 | import "./styles/app.scss";
16 |
17 | export default function App() {
18 | const Router = USE_BROWSER_ROUTER ? BrowserRouter : HashRouter;
19 |
20 | return (
21 |
22 |
23 |
24 |
25 |
26 |
27 | } />
28 | }>
29 | } />
30 | } />
31 | } />
32 |
33 | } />
34 |
35 |
36 |
37 |
38 | );
39 | }
40 |
--------------------------------------------------------------------------------
/basic-vite/src/common/api-client/api-client.ts:
--------------------------------------------------------------------------------
1 | import { ItemsApiClient } from "./items-api-client";
2 |
3 | export class ApiClient {
4 | private _itemsClient: ItemsApiClient | undefined;
5 |
6 | public get items() {
7 | if (!this._itemsClient) {
8 | this._itemsClient = new ItemsApiClient();
9 | }
10 |
11 | return this._itemsClient;
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/basic-vite/src/common/api-client/items-api-client.ts:
--------------------------------------------------------------------------------
1 | import { Item } from "../types";
2 | import { Utils } from "../utils";
3 |
4 | export class ItemsApiClient {
5 | async getItems(): Promise- {
6 | await Utils.promiseSetTimeout(1000);
7 |
8 | const retValue: Item[] = [];
9 |
10 | for (let i = 0; i < 150; i++) {
11 | retValue.push({
12 | itemId: i.toString(),
13 | name: `Item ${i}`,
14 | type: `Type ${i}`,
15 | status: i % 10 === 0 ? "warning" : i % 15 === 1 ? "error" : "success",
16 | details: i * 10,
17 | });
18 | }
19 |
20 | return retValue;
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/basic-vite/src/common/constants.ts:
--------------------------------------------------------------------------------
1 | export const APP_NAME = "Example App";
2 | export const USE_BROWSER_ROUTER = true;
3 |
--------------------------------------------------------------------------------
/basic-vite/src/common/helpers/storage-helper.ts:
--------------------------------------------------------------------------------
1 | import { Mode, applyMode } from "@cloudscape-design/global-styles";
2 | import { NavigationPanelState } from "../types";
3 |
4 | const PREFIX = "example-app";
5 | const THEME_STORAGE_NAME = `${PREFIX}-theme`;
6 | const NAVIGATION_PANEL_STATE_STORAGE_NAME = `${PREFIX}-navigation-panel-state`;
7 |
8 | export abstract class StorageHelper {
9 | static getTheme() {
10 | const value = localStorage.getItem(THEME_STORAGE_NAME) ?? Mode.Light;
11 | const theme = value === Mode.Dark ? Mode.Dark : Mode.Light;
12 |
13 | return theme;
14 | }
15 |
16 | static applyTheme(theme: Mode) {
17 | localStorage.setItem(THEME_STORAGE_NAME, theme);
18 | applyMode(theme);
19 |
20 | document.documentElement.style.setProperty(
21 | "--app-color-scheme",
22 | theme === Mode.Dark ? "dark" : "light"
23 | );
24 |
25 | return theme;
26 | }
27 |
28 | static getNavigationPanelState(): NavigationPanelState {
29 | const value =
30 | localStorage.getItem(NAVIGATION_PANEL_STATE_STORAGE_NAME) ??
31 | JSON.stringify({
32 | collapsed: true,
33 | });
34 |
35 | let state: NavigationPanelState | null = null;
36 | try {
37 | state = JSON.parse(value);
38 | } catch {
39 | state = {};
40 | }
41 |
42 | return state ?? {};
43 | }
44 |
45 | static setNavigationPanelState(state: Partial) {
46 | const currentState = this.getNavigationPanelState();
47 | const newState = { ...currentState, ...state };
48 | const stateStr = JSON.stringify(newState);
49 | localStorage.setItem(NAVIGATION_PANEL_STATE_STORAGE_NAME, stateStr);
50 |
51 | return newState;
52 | }
53 | }
54 |
--------------------------------------------------------------------------------
/basic-vite/src/common/helpers/text-helper.ts:
--------------------------------------------------------------------------------
1 | export abstract class TextHelper {
2 | static getTextFilterCounterText(count = 0) {
3 | return `${count} ${count === 1 ? "match" : "matches"}`;
4 | }
5 |
6 | static getHeaderCounterText(
7 | items: ReadonlyArray,
8 | selectedItems: ReadonlyArray | undefined,
9 | ) {
10 | return selectedItems && selectedItems?.length > 0
11 | ? `(${selectedItems.length}/${items.length})`
12 | : `(${items.length})`;
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/basic-vite/src/common/hooks/use-navigation-panel-state.ts:
--------------------------------------------------------------------------------
1 | import { useState } from "react";
2 | import { StorageHelper } from "../helpers/storage-helper";
3 | import { NavigationPanelState } from "../types";
4 |
5 | export function useNavigationPanelState(): [
6 | NavigationPanelState,
7 | (state: Partial) => void,
8 | ] {
9 | const [currentState, setCurrentState] = useState(
10 | StorageHelper.getNavigationPanelState(),
11 | );
12 |
13 | const onChange = (state: Partial) => {
14 | setCurrentState(StorageHelper.setNavigationPanelState(state));
15 | };
16 |
17 | return [currentState, onChange];
18 | }
19 |
--------------------------------------------------------------------------------
/basic-vite/src/common/hooks/use-on-follow.ts:
--------------------------------------------------------------------------------
1 | import { useCallback } from "react";
2 | import { useNavigate } from "react-router";
3 |
4 | interface FollowDetail {
5 | external?: boolean;
6 | href?: string;
7 | }
8 |
9 | export function useOnFollow() {
10 | const navigate = useNavigate();
11 |
12 | return useCallback(
13 | (event: CustomEvent): void => {
14 | if (
15 | event.detail.external === true ||
16 | typeof event.detail.href === "undefined"
17 | ) {
18 | return;
19 | }
20 |
21 | event.preventDefault();
22 | navigate(event.detail.href);
23 | },
24 | [navigate],
25 | );
26 | }
27 |
--------------------------------------------------------------------------------
/basic-vite/src/common/i18n/property-filter-i18n-strings.ts:
--------------------------------------------------------------------------------
1 | import { PropertyFilterProps } from "@cloudscape-design/components";
2 |
3 | export const PropertyFilterI18nStrings: PropertyFilterProps.I18nStrings = {
4 | filteringAriaLabel: "your choice",
5 | dismissAriaLabel: "Dismiss",
6 |
7 | groupValuesText: "Values",
8 | groupPropertiesText: "Properties",
9 | operatorsText: "Operators",
10 |
11 | operationAndText: "and",
12 | operationOrText: "or",
13 |
14 | operatorLessText: "Less than",
15 | operatorLessOrEqualText: "Less than or equal",
16 | operatorGreaterText: "Greater than",
17 | operatorGreaterOrEqualText: "Greater than or equal",
18 | operatorContainsText: "Contains",
19 | operatorDoesNotContainText: "Does not contain",
20 | operatorEqualsText: "Equals",
21 | operatorDoesNotEqualText: "Does not equal",
22 |
23 | editTokenHeader: "Edit filter",
24 | propertyText: "Property",
25 | operatorText: "Operator",
26 | valueText: "Value",
27 | cancelActionText: "Cancel",
28 | applyActionText: "Apply",
29 | allPropertiesLabel: "All properties",
30 |
31 | tokenLimitShowMore: "Show more",
32 | tokenLimitShowFewer: "Show fewer",
33 | clearFiltersText: "Clear filters",
34 | removeTokenButtonAriaLabel: (token) =>
35 | `Remove token ${token.propertyKey} ${token.operator} ${token.value}`,
36 | enteredTextLabel: (text) => `Use: "${text}"`,
37 | };
38 |
--------------------------------------------------------------------------------
/basic-vite/src/common/types.ts:
--------------------------------------------------------------------------------
1 | import { StatusIndicatorProps } from "@cloudscape-design/components";
2 |
3 | export interface NavigationPanelState {
4 | collapsed?: boolean;
5 | collapsedSections?: Record;
6 | }
7 |
8 | export interface Item {
9 | itemId: string;
10 | name: string;
11 | type: string;
12 | status: StatusIndicatorProps.Type;
13 | details: number;
14 | }
15 |
--------------------------------------------------------------------------------
/basic-vite/src/common/utils.ts:
--------------------------------------------------------------------------------
1 | export abstract class Utils {
2 | static promiseSetTimeout(duration: number) {
3 | return new Promise((resolve) => {
4 | setTimeout(() => {
5 | resolve("Done");
6 | }, duration);
7 | });
8 | }
9 |
10 | static urlSearchParamsToRecord(
11 | params: URLSearchParams
12 | ): Record {
13 | const record: Record = {};
14 |
15 | for (const [key, value] of params.entries()) {
16 | record[key] = value;
17 | }
18 |
19 | return record;
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/basic-vite/src/components/base-app-layout.tsx:
--------------------------------------------------------------------------------
1 | import { AppLayout, AppLayoutProps } from "@cloudscape-design/components";
2 | import { useNavigationPanelState } from "../common/hooks/use-navigation-panel-state";
3 | import NavigationPanel from "./navigation-panel";
4 |
5 | export default function BaseAppLayout(props: AppLayoutProps) {
6 | const [navigationPanelState, setNavigationPanelState] =
7 | useNavigationPanelState();
8 |
9 | return (
10 | }
13 | navigationOpen={!navigationPanelState.collapsed}
14 | onNavigationChange={({ detail }) =>
15 | setNavigationPanelState({ collapsed: !detail.open })
16 | }
17 | toolsHide={true}
18 | {...props}
19 | />
20 | );
21 | }
22 |
--------------------------------------------------------------------------------
/basic-vite/src/components/global-header.tsx:
--------------------------------------------------------------------------------
1 | import { useState } from "react";
2 | import { TopNavigation } from "@cloudscape-design/components";
3 | import { Mode } from "@cloudscape-design/global-styles";
4 | import { StorageHelper } from "../common/helpers/storage-helper";
5 | import { APP_NAME } from "../common/constants";
6 |
7 | export default function GlobalHeader() {
8 | const [theme, setTheme] = useState(StorageHelper.getTheme());
9 |
10 | const onChangeThemeClick = () => {
11 | if (theme === Mode.Dark) {
12 | setTheme(StorageHelper.applyTheme(Mode.Light));
13 | } else {
14 | setTheme(StorageHelper.applyTheme(Mode.Dark));
15 | }
16 | };
17 |
18 | return (
19 |
23 |
36 |
37 | );
38 | }
39 |
--------------------------------------------------------------------------------
/basic-vite/src/components/navigation-panel.tsx:
--------------------------------------------------------------------------------
1 | import {
2 | SideNavigation,
3 | SideNavigationProps,
4 | } from "@cloudscape-design/components";
5 | import { useNavigationPanelState } from "../common/hooks/use-navigation-panel-state";
6 | import { useState } from "react";
7 | import { useOnFollow } from "../common/hooks/use-on-follow";
8 | import { APP_NAME } from "../common/constants";
9 | import { useLocation } from "react-router-dom";
10 |
11 | export default function NavigationPanel() {
12 | const location = useLocation();
13 | const onFollow = useOnFollow();
14 | const [navigationPanelState, setNavigationPanelState] =
15 | useNavigationPanelState();
16 |
17 | const [items] = useState(() => {
18 | const items: SideNavigationProps.Item[] = [
19 | {
20 | type: "link",
21 | text: "Dashboard",
22 | href: "/",
23 | },
24 | {
25 | type: "section",
26 | text: "Section 1",
27 | items: [{ type: "link", text: "Items", href: "/section1" }],
28 | },
29 | {
30 | type: "section",
31 | text: "Section 2",
32 | items: [
33 | { type: "link", text: "Item 1", href: "/section2/item1" },
34 | { type: "link", text: "Item 2", href: "/section2/item2" },
35 | { type: "link", text: "Item 2", href: "/section2/item3" },
36 | ],
37 | },
38 | ];
39 |
40 | items.push(
41 | { type: "divider" },
42 | {
43 | type: "link",
44 | text: "Documentation",
45 | href: "https://github.com/aws-samples/cloudscape-examples",
46 | external: true,
47 | }
48 | );
49 |
50 | return items;
51 | });
52 |
53 | const onChange = ({
54 | detail,
55 | }: {
56 | detail: SideNavigationProps.ChangeDetail;
57 | }) => {
58 | const sectionIndex = items.indexOf(detail.item);
59 | setNavigationPanelState({
60 | collapsedSections: {
61 | ...navigationPanelState.collapsedSections,
62 | [sectionIndex]: !detail.expanded,
63 | },
64 | });
65 | };
66 |
67 | return (
68 | {
74 | if (value.type === "section") {
75 | const collapsed =
76 | navigationPanelState.collapsedSections?.[idx] === true;
77 | value.defaultExpanded = !collapsed;
78 | }
79 |
80 | return value;
81 | })}
82 | />
83 | );
84 | }
85 |
--------------------------------------------------------------------------------
/basic-vite/src/components/wrappers/router-button-dropdown.tsx:
--------------------------------------------------------------------------------
1 | import {
2 | ButtonDropdownProps,
3 | ButtonDropdown,
4 | } from "@cloudscape-design/components";
5 | import { useOnFollow } from "../../common/hooks/use-on-follow";
6 |
7 | export default function RouterButtonDropdown(props: ButtonDropdownProps) {
8 | const onFollow = useOnFollow();
9 |
10 | return ;
11 | }
12 |
--------------------------------------------------------------------------------
/basic-vite/src/components/wrappers/router-button.tsx:
--------------------------------------------------------------------------------
1 | import { ButtonProps, Button } from "@cloudscape-design/components";
2 | import { useOnFollow } from "../../common/hooks/use-on-follow";
3 |
4 | export default function RouterButton(props: ButtonProps) {
5 | const onFollow = useOnFollow();
6 |
7 | return ;
8 | }
9 |
--------------------------------------------------------------------------------
/basic-vite/src/components/wrappers/router-link.tsx:
--------------------------------------------------------------------------------
1 | import { Link, LinkProps } from "@cloudscape-design/components";
2 | import { useOnFollow } from "../../common/hooks/use-on-follow";
3 |
4 | export default function RouterLink(props: LinkProps) {
5 | const onFollow = useOnFollow();
6 |
7 | return ;
8 | }
9 |
--------------------------------------------------------------------------------
/basic-vite/src/main.tsx:
--------------------------------------------------------------------------------
1 | import React from "react";
2 | import ReactDOM from "react-dom/client";
3 | import { StorageHelper } from "./common/helpers/storage-helper";
4 | import App from "./app";
5 | import "@cloudscape-design/global-styles/index.css";
6 |
7 | const root = ReactDOM.createRoot(
8 | document.getElementById("root") as HTMLElement
9 | );
10 |
11 | const theme = StorageHelper.getTheme();
12 | StorageHelper.applyTheme(theme);
13 |
14 | root.render(
15 |
16 |
17 |
18 | );
19 |
--------------------------------------------------------------------------------
/basic-vite/src/pages/dashboard/dashboard-header.tsx:
--------------------------------------------------------------------------------
1 | import { Header, SpaceBetween } from "@cloudscape-design/components";
2 | import RouterButton from "../../components/wrappers/router-button";
3 | import RouterButtonDropdown from "../../components/wrappers/router-button-dropdown";
4 |
5 | export default function DashboardHeader() {
6 | return (
7 |
11 | View Items
12 |
21 | Add data
22 |
23 |
24 | }
25 | >
26 | Dashboard
27 |
28 | );
29 | }
30 |
--------------------------------------------------------------------------------
/basic-vite/src/pages/dashboard/dashboard-page.tsx:
--------------------------------------------------------------------------------
1 | import { APP_NAME } from "../../common/constants";
2 | import {
3 | BreadcrumbGroup,
4 | ContentLayout,
5 | SpaceBetween,
6 | } from "@cloudscape-design/components";
7 | import { useOnFollow } from "../../common/hooks/use-on-follow";
8 | import BaseAppLayout from "../../components/base-app-layout";
9 | import DashboardHeader from "./dashboard-header";
10 | import ItemsTable from "./items-table";
11 | import StatisticsBlock from "./statistics-block";
12 |
13 | export default function DashboardPage() {
14 | const onFollow = useOnFollow();
15 |
16 | return (
17 |
28 | }
29 | content={
30 | }>
31 |
32 |
33 |
34 |
35 |
36 | }
37 | />
38 | );
39 | }
40 |
--------------------------------------------------------------------------------
/basic-vite/src/pages/dashboard/statistics-block.tsx:
--------------------------------------------------------------------------------
1 | import {
2 | Container,
3 | Header,
4 | ColumnLayout,
5 | Box,
6 | } from "@cloudscape-design/components";
7 |
8 | export default function StatisticsBlock() {
9 | return (
10 | Statistics}>
11 |
12 |
16 |
17 |
Something Else
18 |
11
19 |
20 |
21 |
Another Item
22 |
18
23 |
24 |
28 |
29 |
30 | );
31 | }
32 |
--------------------------------------------------------------------------------
/basic-vite/src/pages/not-found.tsx:
--------------------------------------------------------------------------------
1 | import {
2 | Alert,
3 | BreadcrumbGroup,
4 | Container,
5 | ContentLayout,
6 | Header,
7 | SpaceBetween,
8 | } from "@cloudscape-design/components";
9 | import { useOnFollow } from "../common/hooks/use-on-follow";
10 | import { APP_NAME } from "../common/constants";
11 | import BaseAppLayout from "../components/base-app-layout";
12 |
13 | export default function NotFound() {
14 | const onFollow = useOnFollow();
15 |
16 | return (
17 |
34 | }
35 | content={
36 | 404. Page Not Found}
38 | >
39 |
40 |
41 |
42 | The page you are looking for does not exist.
43 |
44 |
45 |
46 |
47 | }
48 | />
49 | );
50 | }
51 |
--------------------------------------------------------------------------------
/basic-vite/src/pages/section1/add-item/add-item-page.tsx:
--------------------------------------------------------------------------------
1 | import {
2 | BreadcrumbGroup,
3 | Button,
4 | Container,
5 | ContentLayout,
6 | Form,
7 | FormField,
8 | Header,
9 | Input,
10 | SpaceBetween,
11 | } from "@cloudscape-design/components";
12 | import { useState } from "react";
13 | import { APP_NAME } from "../../../common/constants";
14 | import { useOnFollow } from "../../../common/hooks/use-on-follow";
15 | import BaseAppLayout from "../../../components/base-app-layout";
16 | import RouterButton from "../../../components/wrappers/router-button";
17 |
18 | export default function AddItemPage() {
19 | const onFollow = useOnFollow();
20 | const [submitting, setSubmitting] = useState(false);
21 | const [globalError, setGlobalError] = useState(undefined);
22 |
23 | const submitForm = async () => {
24 | setSubmitting(true);
25 | setGlobalError("Not implemented yet");
26 | setSubmitting(false);
27 | };
28 | return (
29 |
50 | }
51 | content={
52 |
55 | Add Item
56 |
57 | }
58 | >
59 |
92 |
93 |
94 | }
95 | />
96 | );
97 | }
98 |
--------------------------------------------------------------------------------
/basic-vite/src/pages/section1/all-items/all-items-header.tsx:
--------------------------------------------------------------------------------
1 | import {
2 | Button,
3 | Header,
4 | HeaderProps,
5 | SpaceBetween,
6 | } from "@cloudscape-design/components";
7 | import RouterButton from "../../../components/wrappers/router-button";
8 | import { useNavigate } from "react-router-dom";
9 | import { Item } from "../../../common/types";
10 |
11 | interface AllItemsPageHeaderProps extends HeaderProps {
12 | title?: string;
13 | createButtonText?: string;
14 | selectedItems: readonly Item[];
15 | }
16 |
17 | export function AllItemsPageHeader({
18 | title = "Items",
19 | ...props
20 | }: AllItemsPageHeaderProps) {
21 | const navigate = useNavigate();
22 |
23 | return (
24 |
28 |
29 |
33 | navigate(`/section1/items/${props.selectedItems[0].itemId}`)
34 | }
35 | >
36 | View
37 |
38 |
42 | Delete
43 |
44 |
49 | Add Item
50 |
51 |
52 | }
53 | {...props}
54 | >
55 | {title}
56 |
57 | );
58 | }
59 |
--------------------------------------------------------------------------------
/basic-vite/src/pages/section1/all-items/all-items-page.tsx:
--------------------------------------------------------------------------------
1 | import { BreadcrumbGroup } from "@cloudscape-design/components";
2 | import { APP_NAME } from "../../../common/constants";
3 | import { useOnFollow } from "../../../common/hooks/use-on-follow";
4 | import BaseAppLayout from "../../../components/base-app-layout";
5 | import AllItemsTable from "./all-items-table";
6 |
7 | export default function AllItemsPage() {
8 | const onFollow = useOnFollow();
9 |
10 | return (
11 |
26 | }
27 | content={}
28 | />
29 | );
30 | }
31 |
--------------------------------------------------------------------------------
/basic-vite/src/styles/app.scss:
--------------------------------------------------------------------------------
1 | * {
2 | box-sizing: border-box;
3 | }
4 |
5 | :root {
6 | --app-color-scheme: light;
7 | color-scheme: var(--app-color-scheme);
8 | }
9 |
10 | html,
11 | body,
12 | #root,
13 | div[data-amplify-authenticator],
14 | div[data-amplify-theme] {
15 | height: 100%;
16 | }
17 |
18 | body {
19 | background-color: #ffffff;
20 | overflow-y: scroll;
21 | }
22 |
23 | body.awsui-dark-mode {
24 | background-color: #0e1b2a;
25 | }
26 |
--------------------------------------------------------------------------------
/basic-vite/src/vite-env.d.ts:
--------------------------------------------------------------------------------
1 | ///
2 |
--------------------------------------------------------------------------------
/basic-vite/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | "target": "ES2020",
4 | "useDefineForClassFields": true,
5 | "lib": ["ES2020", "DOM", "DOM.Iterable"],
6 | "module": "ESNext",
7 | "skipLibCheck": true,
8 |
9 | /* Bundler mode */
10 | "moduleResolution": "bundler",
11 | "allowImportingTsExtensions": true,
12 | "resolveJsonModule": true,
13 | "isolatedModules": true,
14 | "noEmit": true,
15 | "jsx": "react-jsx",
16 |
17 | /* Linting */
18 | "strict": true,
19 | "noUnusedLocals": true,
20 | "noUnusedParameters": true,
21 | "noFallthroughCasesInSwitch": true
22 | },
23 | "include": ["src"],
24 | "references": [{ "path": "./tsconfig.node.json" }]
25 | }
26 |
--------------------------------------------------------------------------------
/basic-vite/tsconfig.node.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | "composite": true,
4 | "skipLibCheck": true,
5 | "module": "ESNext",
6 | "moduleResolution": "bundler",
7 | "allowSyntheticDefaultImports": true,
8 | "strict": true
9 | },
10 | "include": ["vite.config.ts"]
11 | }
12 |
--------------------------------------------------------------------------------
/basic-vite/vite.config.ts:
--------------------------------------------------------------------------------
1 | import { defineConfig } from "vite";
2 | import react from "@vitejs/plugin-react";
3 |
4 | // https://vitejs.dev/config/
5 | export default defineConfig({
6 | plugins: [react()],
7 | server: {
8 | port: 3000,
9 | },
10 | });
11 |
--------------------------------------------------------------------------------
/chat-ui-vite/.eslintrc.cjs:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | root: true,
3 | env: { browser: true, es2020: true },
4 | extends: [
5 | 'eslint:recommended',
6 | 'plugin:@typescript-eslint/recommended',
7 | 'plugin:react-hooks/recommended',
8 | ],
9 | ignorePatterns: ['dist', '.eslintrc.cjs'],
10 | parser: '@typescript-eslint/parser',
11 | plugins: ['react-refresh'],
12 | rules: {
13 | 'react-refresh/only-export-components': ['warn', { allowConstantExport: true }],
14 | },
15 | };
16 |
--------------------------------------------------------------------------------
/chat-ui-vite/README.md:
--------------------------------------------------------------------------------
1 | # Chat UI Cloudscape App
2 |
3 | [https://cloudscape.design/](https://cloudscape.design/)
4 |
5 | Cloudscape is an open source design system for the cloud. Cloudscape offers user interface guidelines, front-end components, design resources, and development tools for building intuitive, engaging, and inclusive user experiences at scale.
6 |
7 |
8 | 
9 |
10 |
11 | ## Vite.js
12 |
13 | [https://vitejs.dev/](https://vitejs.dev/)
14 |
15 | Vite.js is a modern, fast front-end build tool that significantly improves the developer experience when building web applications.
16 |
17 | ## Development
18 | 1. Clone this repository to your local machine
19 | ```bash
20 | git clone https://github.com/aws-samples/cloudscape-examples
21 | cd cloudscape-examples/chat-ui-vite
22 | ```
23 | 2. Install the project dependencies by running:
24 | ```bash
25 | npm install
26 | ```
27 | 3. To start the development server, run:
28 | ```bash
29 | npm run dev
30 | ```
31 |
32 | This command will start a local development server at ``http://localhost:3000`` (or a different port if 3000 is in use). The server will hot-reload if you make edits to any of the source files.
33 |
34 | ## Building the App
35 | To build the application for production, run:
36 | ```bash
37 | npm run build
38 | ```
39 | This command will generate a dist folder containing the production build of your app. Vite optimizes your project for the best performance during this process.
40 |
41 | ## Running the App Locally
42 | After building the app, you can serve it locally using:
43 | ```bash
44 | npm run preview
45 | ```
46 | This command serves the production build from the dist folder, allowing you to preview the app before deployment.
--------------------------------------------------------------------------------
/chat-ui-vite/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
12 |
17 |
18 |
19 | Example App
20 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
--------------------------------------------------------------------------------
/chat-ui-vite/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "cloudscape-app",
3 | "private": true,
4 | "version": "0.0.0",
5 | "type": "module",
6 | "scripts": {
7 | "dev": "vite",
8 | "build": "tsc && vite build",
9 | "preview": "vite preview",
10 | "lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0",
11 | "format": "npx prettier --ignore-path .gitignore --write \"**/*.+(tsx|js|ts|json)\""
12 | },
13 | "dependencies": {
14 | "@cloudscape-design/components": "^3.0.611",
15 | "@cloudscape-design/design-tokens": "^3.0.35",
16 | "@cloudscape-design/global-styles": "^1.0.27",
17 | "react": "^18.2.0",
18 | "react-dom": "^18.2.0",
19 | "react-markdown": "^9.0.1",
20 | "react-router-dom": "^6.22.0",
21 | "react-textarea-autosize": "^8.5.3",
22 | "remark-gfm": "^4.0.0"
23 | },
24 | "devDependencies": {
25 | "@types/react": "^18.2.55",
26 | "@types/react-dom": "^18.2.19",
27 | "@typescript-eslint/eslint-plugin": "^6.21.0",
28 | "@typescript-eslint/parser": "^6.21.0",
29 | "@vitejs/plugin-react": "^4.3.2",
30 | "autoprefixer": "^10.4.17",
31 | "eslint": "^8.56.0",
32 | "eslint-plugin-react-hooks": "^4.6.0",
33 | "eslint-plugin-react-refresh": "^0.4.5",
34 | "postcss": "^8.4.35",
35 | "sass": "^1.70.0",
36 | "typescript": "^5.2.2",
37 | "vite": "^5.4.8"
38 | },
39 | "overrides": {
40 | "react-virtual": {
41 | "react": "^18.0.0"
42 | }
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/chat-ui-vite/postcss.config.js:
--------------------------------------------------------------------------------
1 | export default {
2 | plugins: {
3 | autoprefixer: {},
4 | },
5 | };
6 |
--------------------------------------------------------------------------------
/chat-ui-vite/prettier.config.cjs:
--------------------------------------------------------------------------------
1 | // eslint-disable-next-line no-undef
2 | module.export = {
3 | semi: true,
4 | trailingComma: "es5",
5 | singleQuote: false,
6 | tabWidth: 2,
7 | useTabs: false,
8 | };
9 |
--------------------------------------------------------------------------------
/chat-ui-vite/public/favicon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/aws-samples/cloudscape-examples/35055cf8fb197302784028998a9d8c3c55acea78/chat-ui-vite/public/favicon.ico
--------------------------------------------------------------------------------
/chat-ui-vite/public/images/android-chrome-192x192.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/aws-samples/cloudscape-examples/35055cf8fb197302784028998a9d8c3c55acea78/chat-ui-vite/public/images/android-chrome-192x192.png
--------------------------------------------------------------------------------
/chat-ui-vite/public/images/android-chrome-512x512.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/aws-samples/cloudscape-examples/35055cf8fb197302784028998a9d8c3c55acea78/chat-ui-vite/public/images/android-chrome-512x512.png
--------------------------------------------------------------------------------
/chat-ui-vite/public/images/apple-touch-icon.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/aws-samples/cloudscape-examples/35055cf8fb197302784028998a9d8c3c55acea78/chat-ui-vite/public/images/apple-touch-icon.png
--------------------------------------------------------------------------------
/chat-ui-vite/public/images/favicon-16x16.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/aws-samples/cloudscape-examples/35055cf8fb197302784028998a9d8c3c55acea78/chat-ui-vite/public/images/favicon-16x16.png
--------------------------------------------------------------------------------
/chat-ui-vite/public/images/favicon-32x32.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/aws-samples/cloudscape-examples/35055cf8fb197302784028998a9d8c3c55acea78/chat-ui-vite/public/images/favicon-32x32.png
--------------------------------------------------------------------------------
/chat-ui-vite/public/images/favicon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/aws-samples/cloudscape-examples/35055cf8fb197302784028998a9d8c3c55acea78/chat-ui-vite/public/images/favicon.ico
--------------------------------------------------------------------------------
/chat-ui-vite/public/images/logo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/aws-samples/cloudscape-examples/35055cf8fb197302784028998a9d8c3c55acea78/chat-ui-vite/public/images/logo.png
--------------------------------------------------------------------------------
/chat-ui-vite/public/manifest.json:
--------------------------------------------------------------------------------
1 | {
2 | "id": "/",
3 | "start_url": "/",
4 | "name": "Example App",
5 | "short_name": "Example App",
6 | "description": "Example App sample",
7 | "theme_color": "#000000",
8 | "background_color": "#ffffff",
9 | "display": "standalone",
10 | "icons": [
11 | {
12 | "src": "/images/android-chrome-192x192.png",
13 | "sizes": "192x192",
14 | "type": "image/png"
15 | },
16 | {
17 | "src": "/images/android-chrome-512x512.png",
18 | "sizes": "512x512",
19 | "type": "image/png"
20 | }
21 | ]
22 | }
23 |
--------------------------------------------------------------------------------
/chat-ui-vite/src/app.tsx:
--------------------------------------------------------------------------------
1 | import { HashRouter, BrowserRouter, Routes, Route } from "react-router-dom";
2 | import { USE_BROWSER_ROUTER } from "./common/constants";
3 | import GlobalHeader from "./components/global-header";
4 | import NotFound from "./pages/not-found";
5 | import ChatPage from "./pages/chat-page";
6 | import "./styles/app.scss";
7 |
8 | export default function App() {
9 | const Router = USE_BROWSER_ROUTER ? BrowserRouter : HashRouter;
10 |
11 | return (
12 |
13 |
14 |
15 |
16 |
17 |
18 | } />
19 | } />
20 |
21 |
22 |
23 |
24 | );
25 | }
26 |
--------------------------------------------------------------------------------
/chat-ui-vite/src/common/constants.ts:
--------------------------------------------------------------------------------
1 | export const APP_NAME = "Example App";
2 | export const USE_BROWSER_ROUTER = true;
3 |
--------------------------------------------------------------------------------
/chat-ui-vite/src/common/helpers/storage-helper.ts:
--------------------------------------------------------------------------------
1 | import { Mode, applyMode } from "@cloudscape-design/global-styles";
2 | import { NavigationPanelState } from "../types";
3 |
4 | const PREFIX = "example-app";
5 | const THEME_STORAGE_NAME = `${PREFIX}-theme`;
6 | const NAVIGATION_PANEL_STATE_STORAGE_NAME = `${PREFIX}-navigation-panel-state`;
7 |
8 | export abstract class StorageHelper {
9 | static getTheme() {
10 | const value = localStorage.getItem(THEME_STORAGE_NAME) ?? Mode.Light;
11 | const theme = value === Mode.Dark ? Mode.Dark : Mode.Light;
12 |
13 | return theme;
14 | }
15 |
16 | static applyTheme(theme: Mode) {
17 | localStorage.setItem(THEME_STORAGE_NAME, theme);
18 | applyMode(theme);
19 |
20 | document.documentElement.style.setProperty(
21 | "--app-color-scheme",
22 | theme === Mode.Dark ? "dark" : "light"
23 | );
24 |
25 | return theme;
26 | }
27 |
28 | static getNavigationPanelState(): NavigationPanelState {
29 | const value =
30 | localStorage.getItem(NAVIGATION_PANEL_STATE_STORAGE_NAME) ??
31 | JSON.stringify({
32 | collapsed: true,
33 | });
34 |
35 | let state: NavigationPanelState | null = null;
36 | try {
37 | state = JSON.parse(value);
38 | } catch {
39 | state = {};
40 | }
41 |
42 | return state ?? {};
43 | }
44 |
45 | static setNavigationPanelState(state: Partial) {
46 | const currentState = this.getNavigationPanelState();
47 | const newState = { ...currentState, ...state };
48 | const stateStr = JSON.stringify(newState);
49 | localStorage.setItem(NAVIGATION_PANEL_STATE_STORAGE_NAME, stateStr);
50 |
51 | return newState;
52 | }
53 | }
54 |
--------------------------------------------------------------------------------
/chat-ui-vite/src/common/hooks/use-navigation-panel-state.ts:
--------------------------------------------------------------------------------
1 | import { useState } from "react";
2 | import { StorageHelper } from "../helpers/storage-helper";
3 | import { NavigationPanelState } from "../types";
4 |
5 | export function useNavigationPanelState(): [
6 | NavigationPanelState,
7 | (state: Partial) => void,
8 | ] {
9 | const [currentState, setCurrentState] = useState(
10 | StorageHelper.getNavigationPanelState(),
11 | );
12 |
13 | const onChange = (state: Partial) => {
14 | setCurrentState(StorageHelper.setNavigationPanelState(state));
15 | };
16 |
17 | return [currentState, onChange];
18 | }
19 |
--------------------------------------------------------------------------------
/chat-ui-vite/src/common/hooks/use-on-follow.ts:
--------------------------------------------------------------------------------
1 | import { useCallback } from "react";
2 | import { useNavigate } from "react-router";
3 |
4 | interface FollowDetail {
5 | external?: boolean;
6 | href?: string;
7 | }
8 |
9 | export function useOnFollow() {
10 | const navigate = useNavigate();
11 |
12 | return useCallback(
13 | (event: CustomEvent): void => {
14 | if (
15 | event.detail.external === true ||
16 | typeof event.detail.href === "undefined"
17 | ) {
18 | return;
19 | }
20 |
21 | event.preventDefault();
22 | navigate(event.detail.href);
23 | },
24 | [navigate],
25 | );
26 | }
27 |
--------------------------------------------------------------------------------
/chat-ui-vite/src/common/types.ts:
--------------------------------------------------------------------------------
1 | export interface NavigationPanelState {
2 | collapsed?: boolean;
3 | collapsedSections?: Record;
4 | }
5 |
--------------------------------------------------------------------------------
/chat-ui-vite/src/components/base-app-layout.tsx:
--------------------------------------------------------------------------------
1 | import { AppLayout, AppLayoutProps } from "@cloudscape-design/components";
2 | import { useNavigationPanelState } from "../common/hooks/use-navigation-panel-state";
3 | import NavigationPanel from "./navigation-panel";
4 |
5 | export default function BaseAppLayout(props: AppLayoutProps) {
6 | const [navigationPanelState, setNavigationPanelState] =
7 | useNavigationPanelState();
8 |
9 | return (
10 | }
13 | navigationOpen={!navigationPanelState.collapsed}
14 | onNavigationChange={({ detail }) =>
15 | setNavigationPanelState({ collapsed: !detail.open })
16 | }
17 | toolsHide={true}
18 | {...props}
19 | />
20 | );
21 | }
22 |
--------------------------------------------------------------------------------
/chat-ui-vite/src/components/chat-ui/chat-ui-message-list.tsx:
--------------------------------------------------------------------------------
1 | import { SpaceBetween } from "@cloudscape-design/components";
2 | import { ChatMessage } from "./types";
3 | import ChatUIMessage from "./chat-ui-message";
4 |
5 | export interface ChatUIMessageListProps {
6 | messages?: ChatMessage[];
7 | showCopyButton?: boolean;
8 | }
9 |
10 | export default function ChatUIMessageList(props: ChatUIMessageListProps) {
11 | const messages = props.messages || [];
12 |
13 | return (
14 |
15 | {messages.map((message, idx) => (
16 |
21 | ))}
22 |
23 | );
24 | }
25 |
--------------------------------------------------------------------------------
/chat-ui-vite/src/components/chat-ui/chat-ui.tsx:
--------------------------------------------------------------------------------
1 | import { StatusIndicator } from "@cloudscape-design/components";
2 | import { ChatMessage } from "./types";
3 | import ChatUIInputPanel from "./chat-ui-input-panel";
4 | import { useEffect } from "react";
5 | import ChatUIMessageList from "./chat-ui-message-list";
6 | import styles from "../../styles/chat-ui.module.scss";
7 |
8 | export interface ChatUIProps {
9 | loading?: boolean;
10 | running?: boolean;
11 | messages?: ChatMessage[];
12 | welcomeText?: string;
13 | inputPlaceholderText?: string;
14 | sendButtonText?: string;
15 | showCopyButton?: boolean;
16 | onSendMessage?: (message: string) => void;
17 | }
18 |
19 | export abstract class ChatScrollState {
20 | static userHasScrolled = false;
21 | static skipNextScrollEvent = false;
22 | static skipNextHistoryUpdate = false;
23 | }
24 |
25 | export function ChatUI(props: ChatUIProps) {
26 | useEffect(() => {
27 | const onWindowScroll = () => {
28 | if (ChatScrollState.skipNextScrollEvent) {
29 | ChatScrollState.skipNextScrollEvent = false;
30 | return;
31 | }
32 |
33 | const isScrollToTheEnd =
34 | Math.abs(
35 | window.innerHeight +
36 | window.scrollY -
37 | document.documentElement.scrollHeight
38 | ) <= 10;
39 |
40 | if (!isScrollToTheEnd) {
41 | ChatScrollState.userHasScrolled = true;
42 | } else {
43 | ChatScrollState.userHasScrolled = false;
44 | }
45 | };
46 |
47 | window.addEventListener("scroll", onWindowScroll);
48 |
49 | return () => {
50 | window.removeEventListener("scroll", onWindowScroll);
51 | };
52 | }, []);
53 |
54 | return (
55 |
56 |
60 |
61 | {props.messages?.length === 0 && !props.loading && (
62 |
{props.welcomeText ?? "ChatBot"}
63 | )}
64 | {props.loading && (
65 |
66 | Loading
67 |
68 | )}
69 |
70 |
71 |
72 |
73 |
74 | );
75 | }
76 |
--------------------------------------------------------------------------------
/chat-ui-vite/src/components/chat-ui/types.tsx:
--------------------------------------------------------------------------------
1 | export enum ChatMessageType {
2 | AI = "ai",
3 | Human = "human",
4 | }
5 |
6 | export interface ChatMessage {
7 | type: ChatMessageType;
8 | content: string;
9 | }
10 |
--------------------------------------------------------------------------------
/chat-ui-vite/src/components/global-header.tsx:
--------------------------------------------------------------------------------
1 | import { useState } from "react";
2 | import { TopNavigation } from "@cloudscape-design/components";
3 | import { Mode } from "@cloudscape-design/global-styles";
4 | import { StorageHelper } from "../common/helpers/storage-helper";
5 | import { APP_NAME } from "../common/constants";
6 |
7 | export default function GlobalHeader() {
8 | const [theme, setTheme] = useState(StorageHelper.getTheme());
9 |
10 | const onChangeThemeClick = () => {
11 | if (theme === Mode.Dark) {
12 | setTheme(StorageHelper.applyTheme(Mode.Light));
13 | } else {
14 | setTheme(StorageHelper.applyTheme(Mode.Dark));
15 | }
16 | };
17 |
18 | return (
19 |
23 |
36 |
37 | );
38 | }
39 |
--------------------------------------------------------------------------------
/chat-ui-vite/src/components/navigation-panel.tsx:
--------------------------------------------------------------------------------
1 | import {
2 | SideNavigation,
3 | SideNavigationProps,
4 | } from "@cloudscape-design/components";
5 | import { useNavigationPanelState } from "../common/hooks/use-navigation-panel-state";
6 | import { useState } from "react";
7 | import { useOnFollow } from "../common/hooks/use-on-follow";
8 | import { APP_NAME } from "../common/constants";
9 | import { useLocation } from "react-router-dom";
10 |
11 | export default function NavigationPanel() {
12 | const location = useLocation();
13 | const onFollow = useOnFollow();
14 | const [navigationPanelState, setNavigationPanelState] =
15 | useNavigationPanelState();
16 |
17 | const [items] = useState(() => {
18 | const items: SideNavigationProps.Item[] = [
19 | {
20 | type: "link",
21 | text: "Chat",
22 | href: "/",
23 | },
24 | {
25 | type: "section",
26 | text: "Section",
27 | items: [
28 | { type: "link", text: "Item 1", href: "/section/item1" },
29 | { type: "link", text: "Item 2", href: "/section/item2" },
30 | { type: "link", text: "Item 2", href: "/section/item3" },
31 | ],
32 | },
33 | ];
34 |
35 | items.push(
36 | { type: "divider" },
37 | {
38 | type: "link",
39 | text: "Documentation",
40 | href: "https://github.com/aws-samples/cloudscape-examples",
41 | external: true,
42 | }
43 | );
44 |
45 | return items;
46 | });
47 |
48 | const onChange = ({
49 | detail,
50 | }: {
51 | detail: SideNavigationProps.ChangeDetail;
52 | }) => {
53 | const sectionIndex = items.indexOf(detail.item);
54 | setNavigationPanelState({
55 | collapsedSections: {
56 | ...navigationPanelState.collapsedSections,
57 | [sectionIndex]: !detail.expanded,
58 | },
59 | });
60 | };
61 |
62 | return (
63 | {
69 | if (value.type === "section") {
70 | const collapsed =
71 | navigationPanelState.collapsedSections?.[idx] === true;
72 | value.defaultExpanded = !collapsed;
73 | }
74 |
75 | return value;
76 | })}
77 | />
78 | );
79 | }
80 |
--------------------------------------------------------------------------------
/chat-ui-vite/src/components/wrappers/router-button-dropdown.tsx:
--------------------------------------------------------------------------------
1 | import {
2 | ButtonDropdownProps,
3 | ButtonDropdown,
4 | } from "@cloudscape-design/components";
5 | import { useOnFollow } from "../../common/hooks/use-on-follow";
6 |
7 | export default function RouterButtonDropdown(props: ButtonDropdownProps) {
8 | const onFollow = useOnFollow();
9 |
10 | return ;
11 | }
12 |
--------------------------------------------------------------------------------
/chat-ui-vite/src/components/wrappers/router-button.tsx:
--------------------------------------------------------------------------------
1 | import { ButtonProps, Button } from "@cloudscape-design/components";
2 | import { useOnFollow } from "../../common/hooks/use-on-follow";
3 |
4 | export default function RouterButton(props: ButtonProps) {
5 | const onFollow = useOnFollow();
6 |
7 | return ;
8 | }
9 |
--------------------------------------------------------------------------------
/chat-ui-vite/src/components/wrappers/router-link.tsx:
--------------------------------------------------------------------------------
1 | import { Link, LinkProps } from "@cloudscape-design/components";
2 | import { useOnFollow } from "../../common/hooks/use-on-follow";
3 |
4 | export default function RouterLink(props: LinkProps) {
5 | const onFollow = useOnFollow();
6 |
7 | return ;
8 | }
9 |
--------------------------------------------------------------------------------
/chat-ui-vite/src/main.tsx:
--------------------------------------------------------------------------------
1 | import React from "react";
2 | import ReactDOM from "react-dom/client";
3 | import { StorageHelper } from "./common/helpers/storage-helper";
4 | import App from "./app";
5 | import "@cloudscape-design/global-styles/index.css";
6 |
7 | const root = ReactDOM.createRoot(
8 | document.getElementById("root") as HTMLElement
9 | );
10 |
11 | const theme = StorageHelper.getTheme();
12 | StorageHelper.applyTheme(theme);
13 |
14 | root.render(
15 |
16 |
17 |
18 | );
19 |
--------------------------------------------------------------------------------
/chat-ui-vite/src/pages/chat-page.tsx:
--------------------------------------------------------------------------------
1 | import { useState } from "react";
2 | import BaseAppLayout from "../components/base-app-layout";
3 | import { ChatUI } from "../components/chat-ui/chat-ui";
4 | import { ChatMessage, ChatMessageType } from "../components/chat-ui/types";
5 |
6 | export default function ChatPage() {
7 | const [running, setRunning] = useState(false);
8 | const [messages, setMessages] = useState([]);
9 |
10 | const sendMessage = (message: string) => {
11 | setRunning(true);
12 | setMessages((prevMessages) => [
13 | ...prevMessages,
14 | { type: ChatMessageType.Human, content: message },
15 | {
16 | type: ChatMessageType.AI,
17 | content: "",
18 | },
19 | ]);
20 |
21 | setTimeout(() => {
22 | setMessages((prevMessages) => [
23 | ...prevMessages.splice(0, prevMessages.length - 1),
24 | {
25 | type: ChatMessageType.AI,
26 | content:
27 | "I am a chatbot. Please try to connect me to Amazon Bedrock.",
28 | },
29 | ]);
30 |
31 | setRunning(false);
32 | }, 1000);
33 | };
34 |
35 | return (
36 |
43 | }
44 | />
45 | );
46 | }
47 |
--------------------------------------------------------------------------------
/chat-ui-vite/src/pages/not-found.tsx:
--------------------------------------------------------------------------------
1 | import {
2 | Alert,
3 | BreadcrumbGroup,
4 | Container,
5 | ContentLayout,
6 | Header,
7 | SpaceBetween,
8 | } from "@cloudscape-design/components";
9 | import { useOnFollow } from "../common/hooks/use-on-follow";
10 | import { APP_NAME } from "../common/constants";
11 | import BaseAppLayout from "../components/base-app-layout";
12 |
13 | export default function NotFound() {
14 | const onFollow = useOnFollow();
15 |
16 | return (
17 |
34 | }
35 | content={
36 | 404. Page Not Found}
38 | >
39 |
40 |
41 |
42 | The page you are looking for does not exist.
43 |
44 |
45 |
46 |
47 | }
48 | />
49 | );
50 | }
51 |
--------------------------------------------------------------------------------
/chat-ui-vite/src/styles/app.scss:
--------------------------------------------------------------------------------
1 | * {
2 | box-sizing: border-box;
3 | }
4 |
5 | :root {
6 | --app-color-scheme: light;
7 | color-scheme: var(--app-color-scheme);
8 | }
9 |
10 | html,
11 | body,
12 | #root,
13 | div[data-amplify-authenticator],
14 | div[data-amplify-theme] {
15 | height: 100%;
16 | }
17 |
18 | body {
19 | background-color: #ffffff;
20 | overflow-y: scroll;
21 | }
22 |
23 | body.awsui-dark-mode {
24 | background-color: #0e1b2a;
25 | }
26 |
--------------------------------------------------------------------------------
/chat-ui-vite/src/styles/chat-ui.module.scss:
--------------------------------------------------------------------------------
1 | @use "@cloudscape-design/design-tokens/index" as awsui;
2 |
3 | .chat_container {
4 | margin-bottom: -40px;
5 | min-height: calc(100vh - 96px);
6 | display: flex;
7 | flex-direction: column;
8 | justify-content: space-between;
9 | }
10 |
11 | @media (min-width: 466px) {
12 | .chat_container {
13 | min-height: calc(100vh - 104px);
14 | }
15 | }
16 |
17 | @media (min-width: 689px) {
18 | .chat_container {
19 | min-height: calc(100vh - 60px);
20 | }
21 | }
22 |
23 | @media (min-width: 913px) {
24 | .chat_container {
25 | min-height: calc(100vh - 68px);
26 | }
27 | }
28 |
29 | .welcome_text {
30 | color: awsui.$color-text-body-default;
31 | font-size: 3rem;
32 | font-weight: bolder;
33 | opacity: 0.4;
34 | }
35 |
36 | .input_container {
37 | position: sticky;
38 | bottom: 0;
39 | padding-bottom: awsui.$space-scaled-l;
40 | padding-top: awsui.$space-scaled-xxl;
41 | background: linear-gradient(
42 | to bottom,
43 | transparent 0%,
44 | awsui.$color-background-container-content 20%
45 | );
46 | margin-left: -8px;
47 | margin-right: -8px;
48 | container-type: inline-size;
49 | container-name: input_container;
50 | }
51 |
52 | .input_textarea_container {
53 | display: grid;
54 | grid-template-columns: 1fr auto;
55 | align-items: center;
56 | gap: 4px;
57 | }
58 |
59 | .input_textarea {
60 | resize: none;
61 | border: none;
62 | padding: 12px 12px 12px 4px;
63 | background-color: transparent;
64 | outline: none;
65 | width: 100%;
66 | height: 100%;
67 | font-size: 1rem;
68 | }
69 |
70 | .btn_chabot_message_copy {
71 | float: right;
72 | }
73 |
--------------------------------------------------------------------------------
/chat-ui-vite/src/vite-env.d.ts:
--------------------------------------------------------------------------------
1 | ///
2 |
--------------------------------------------------------------------------------
/chat-ui-vite/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | "target": "ES2020",
4 | "useDefineForClassFields": true,
5 | "lib": ["ES2020", "DOM", "DOM.Iterable"],
6 | "module": "ESNext",
7 | "skipLibCheck": true,
8 |
9 | /* Bundler mode */
10 | "moduleResolution": "bundler",
11 | "allowImportingTsExtensions": true,
12 | "resolveJsonModule": true,
13 | "isolatedModules": true,
14 | "noEmit": true,
15 | "jsx": "react-jsx",
16 |
17 | /* Linting */
18 | "strict": true,
19 | "noUnusedLocals": true,
20 | "noUnusedParameters": true,
21 | "noFallthroughCasesInSwitch": true
22 | },
23 | "include": ["src"],
24 | "references": [{ "path": "./tsconfig.node.json" }]
25 | }
26 |
--------------------------------------------------------------------------------
/chat-ui-vite/tsconfig.node.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | "composite": true,
4 | "skipLibCheck": true,
5 | "module": "ESNext",
6 | "moduleResolution": "bundler",
7 | "allowSyntheticDefaultImports": true,
8 | "strict": true
9 | },
10 | "include": ["vite.config.ts"]
11 | }
12 |
--------------------------------------------------------------------------------
/chat-ui-vite/vite.config.ts:
--------------------------------------------------------------------------------
1 | import { defineConfig } from "vite";
2 | import react from "@vitejs/plugin-react";
3 |
4 | // https://vitejs.dev/config/
5 | export default defineConfig({
6 | plugins: [react()],
7 | server: {
8 | port: 3000,
9 | },
10 | });
11 |
--------------------------------------------------------------------------------
/empty-vite/.eslintrc.cjs:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | root: true,
3 | env: { browser: true, es2020: true },
4 | extends: [
5 | 'eslint:recommended',
6 | 'plugin:@typescript-eslint/recommended',
7 | 'plugin:react-hooks/recommended',
8 | ],
9 | ignorePatterns: ['dist', '.eslintrc.cjs'],
10 | parser: '@typescript-eslint/parser',
11 | plugins: ['react-refresh'],
12 | rules: {
13 | 'react-refresh/only-export-components': ['warn', { allowConstantExport: true }],
14 | },
15 | };
16 |
--------------------------------------------------------------------------------
/empty-vite/README.md:
--------------------------------------------------------------------------------
1 | # Empty Cloudscape App
2 |
3 | [https://cloudscape.design/](https://cloudscape.design/)
4 |
5 | Cloudscape is an open source design system for the cloud. Cloudscape offers user interface guidelines, front-end components, design resources, and development tools for building intuitive, engaging, and inclusive user experiences at scale.
6 |
7 |
8 | 
9 |
10 |
11 | ## Vite.js
12 |
13 | [https://vitejs.dev/](https://vitejs.dev/)
14 |
15 | Vite.js is a modern, fast front-end build tool that significantly improves the developer experience when building web applications.
16 |
17 | ## Development
18 | 1. Clone this repository to your local machine
19 | ```bash
20 | git clone https://github.com/aws-samples/cloudscape-examples
21 | cd cloudscape-examples/empty-vite
22 | ```
23 | 2. Install the project dependencies by running:
24 | ```bash
25 | npm install
26 | ```
27 | 3. To start the development server, run:
28 | ```bash
29 | npm run dev
30 | ```
31 |
32 | This command will start a local development server at ``http://localhost:3000`` (or a different port if 3000 is in use). The server will hot-reload if you make edits to any of the source files.
33 |
34 | ## Building the App
35 | To build the application for production, run:
36 | ```bash
37 | npm run build
38 | ```
39 | This command will generate a dist folder containing the production build of your app. Vite optimizes your project for the best performance during this process.
40 |
41 | ## Running the App Locally
42 | After building the app, you can serve it locally using:
43 | ```bash
44 | npm run preview
45 | ```
46 | This command serves the production build from the dist folder, allowing you to preview the app before deployment.
--------------------------------------------------------------------------------
/empty-vite/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
12 |
17 |
18 |
19 | Example App
20 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
--------------------------------------------------------------------------------
/empty-vite/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "cloudscape-app",
3 | "private": true,
4 | "version": "0.0.0",
5 | "type": "module",
6 | "scripts": {
7 | "dev": "vite",
8 | "build": "tsc && vite build",
9 | "preview": "vite preview",
10 | "lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0",
11 | "format": "npx prettier --ignore-path .gitignore --write \"**/*.+(tsx|js|ts|json)\""
12 | },
13 | "dependencies": {
14 | "@cloudscape-design/components": "^3.0.611",
15 | "@cloudscape-design/design-tokens": "^3.0.35",
16 | "@cloudscape-design/global-styles": "^1.0.27",
17 | "react": "^18.2.0",
18 | "react-dom": "^18.2.0",
19 | "react-router-dom": "^6.22.0"
20 | },
21 | "devDependencies": {
22 | "@types/react": "^18.2.55",
23 | "@types/react-dom": "^18.2.19",
24 | "@typescript-eslint/eslint-plugin": "^6.21.0",
25 | "@typescript-eslint/parser": "^6.21.0",
26 | "@vitejs/plugin-react": "^4.3.2",
27 | "autoprefixer": "^10.4.17",
28 | "eslint": "^8.56.0",
29 | "eslint-plugin-react-hooks": "^4.6.0",
30 | "eslint-plugin-react-refresh": "^0.4.5",
31 | "postcss": "^8.4.35",
32 | "sass": "^1.70.0",
33 | "typescript": "^5.2.2",
34 | "vite": "^5.4.8"
35 | },
36 | "overrides": {
37 | "react-virtual": {
38 | "react": "^18.0.0"
39 | }
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/empty-vite/postcss.config.js:
--------------------------------------------------------------------------------
1 | export default {
2 | plugins: {
3 | autoprefixer: {},
4 | },
5 | };
6 |
--------------------------------------------------------------------------------
/empty-vite/prettier.config.cjs:
--------------------------------------------------------------------------------
1 | // eslint-disable-next-line no-undef
2 | module.export = {
3 | semi: true,
4 | trailingComma: "es5",
5 | singleQuote: false,
6 | tabWidth: 2,
7 | useTabs: false,
8 | };
9 |
--------------------------------------------------------------------------------
/empty-vite/public/favicon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/aws-samples/cloudscape-examples/35055cf8fb197302784028998a9d8c3c55acea78/empty-vite/public/favicon.ico
--------------------------------------------------------------------------------
/empty-vite/public/images/android-chrome-192x192.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/aws-samples/cloudscape-examples/35055cf8fb197302784028998a9d8c3c55acea78/empty-vite/public/images/android-chrome-192x192.png
--------------------------------------------------------------------------------
/empty-vite/public/images/android-chrome-512x512.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/aws-samples/cloudscape-examples/35055cf8fb197302784028998a9d8c3c55acea78/empty-vite/public/images/android-chrome-512x512.png
--------------------------------------------------------------------------------
/empty-vite/public/images/apple-touch-icon.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/aws-samples/cloudscape-examples/35055cf8fb197302784028998a9d8c3c55acea78/empty-vite/public/images/apple-touch-icon.png
--------------------------------------------------------------------------------
/empty-vite/public/images/favicon-16x16.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/aws-samples/cloudscape-examples/35055cf8fb197302784028998a9d8c3c55acea78/empty-vite/public/images/favicon-16x16.png
--------------------------------------------------------------------------------
/empty-vite/public/images/favicon-32x32.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/aws-samples/cloudscape-examples/35055cf8fb197302784028998a9d8c3c55acea78/empty-vite/public/images/favicon-32x32.png
--------------------------------------------------------------------------------
/empty-vite/public/images/favicon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/aws-samples/cloudscape-examples/35055cf8fb197302784028998a9d8c3c55acea78/empty-vite/public/images/favicon.ico
--------------------------------------------------------------------------------
/empty-vite/public/images/logo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/aws-samples/cloudscape-examples/35055cf8fb197302784028998a9d8c3c55acea78/empty-vite/public/images/logo.png
--------------------------------------------------------------------------------
/empty-vite/public/manifest.json:
--------------------------------------------------------------------------------
1 | {
2 | "id": "/",
3 | "start_url": "/",
4 | "name": "Example App",
5 | "short_name": "Example App",
6 | "description": "Example App sample",
7 | "theme_color": "#000000",
8 | "background_color": "#ffffff",
9 | "display": "standalone",
10 | "icons": [
11 | {
12 | "src": "/images/android-chrome-192x192.png",
13 | "sizes": "192x192",
14 | "type": "image/png"
15 | },
16 | {
17 | "src": "/images/android-chrome-512x512.png",
18 | "sizes": "512x512",
19 | "type": "image/png"
20 | }
21 | ]
22 | }
23 |
--------------------------------------------------------------------------------
/empty-vite/src/app.tsx:
--------------------------------------------------------------------------------
1 | import { HashRouter, BrowserRouter, Routes, Route } from "react-router-dom";
2 | import { USE_BROWSER_ROUTER } from "./common/constants";
3 | import GlobalHeader from "./components/global-header";
4 | import HomePage from "./pages/home";
5 | import "./styles/app.scss";
6 | import NotFound from "./pages/not-found";
7 |
8 | export default function App() {
9 | const Router = USE_BROWSER_ROUTER ? BrowserRouter : HashRouter;
10 |
11 | return (
12 |
13 |
14 |
15 |
16 |
17 |
18 | } />
19 | } />
20 |
21 |
22 |
23 |
24 | );
25 | }
26 |
--------------------------------------------------------------------------------
/empty-vite/src/common/constants.ts:
--------------------------------------------------------------------------------
1 | export const APP_NAME = "Example App";
2 | export const USE_BROWSER_ROUTER = true;
3 |
--------------------------------------------------------------------------------
/empty-vite/src/common/helpers/storage-helper.ts:
--------------------------------------------------------------------------------
1 | import { Mode, applyMode } from "@cloudscape-design/global-styles";
2 | import { NavigationPanelState } from "../types";
3 |
4 | const PREFIX = "example-app";
5 | const THEME_STORAGE_NAME = `${PREFIX}-theme`;
6 | const NAVIGATION_PANEL_STATE_STORAGE_NAME = `${PREFIX}-navigation-panel-state`;
7 |
8 | export abstract class StorageHelper {
9 | static getTheme() {
10 | const value = localStorage.getItem(THEME_STORAGE_NAME) ?? Mode.Light;
11 | const theme = value === Mode.Dark ? Mode.Dark : Mode.Light;
12 |
13 | return theme;
14 | }
15 |
16 | static applyTheme(theme: Mode) {
17 | localStorage.setItem(THEME_STORAGE_NAME, theme);
18 | applyMode(theme);
19 |
20 | document.documentElement.style.setProperty(
21 | "--app-color-scheme",
22 | theme === Mode.Dark ? "dark" : "light"
23 | );
24 |
25 | return theme;
26 | }
27 |
28 | static getNavigationPanelState(): NavigationPanelState {
29 | const value =
30 | localStorage.getItem(NAVIGATION_PANEL_STATE_STORAGE_NAME) ??
31 | JSON.stringify({
32 | collapsed: true,
33 | });
34 |
35 | let state: NavigationPanelState | null = null;
36 | try {
37 | state = JSON.parse(value);
38 | } catch {
39 | state = {};
40 | }
41 |
42 | return state ?? {};
43 | }
44 |
45 | static setNavigationPanelState(state: Partial) {
46 | const currentState = this.getNavigationPanelState();
47 | const newState = { ...currentState, ...state };
48 | const stateStr = JSON.stringify(newState);
49 | localStorage.setItem(NAVIGATION_PANEL_STATE_STORAGE_NAME, stateStr);
50 |
51 | return newState;
52 | }
53 | }
54 |
--------------------------------------------------------------------------------
/empty-vite/src/common/hooks/use-navigation-panel-state.ts:
--------------------------------------------------------------------------------
1 | import { useState } from "react";
2 | import { StorageHelper } from "../helpers/storage-helper";
3 | import { NavigationPanelState } from "../types";
4 |
5 | export function useNavigationPanelState(): [
6 | NavigationPanelState,
7 | (state: Partial) => void,
8 | ] {
9 | const [currentState, setCurrentState] = useState(
10 | StorageHelper.getNavigationPanelState(),
11 | );
12 |
13 | const onChange = (state: Partial) => {
14 | setCurrentState(StorageHelper.setNavigationPanelState(state));
15 | };
16 |
17 | return [currentState, onChange];
18 | }
19 |
--------------------------------------------------------------------------------
/empty-vite/src/common/hooks/use-on-follow.ts:
--------------------------------------------------------------------------------
1 | import { useCallback } from "react";
2 | import { useNavigate } from "react-router";
3 |
4 | interface FollowDetail {
5 | external?: boolean;
6 | href?: string;
7 | }
8 |
9 | export function useOnFollow() {
10 | const navigate = useNavigate();
11 |
12 | return useCallback(
13 | (event: CustomEvent): void => {
14 | if (
15 | event.detail.external === true ||
16 | typeof event.detail.href === "undefined"
17 | ) {
18 | return;
19 | }
20 |
21 | event.preventDefault();
22 | navigate(event.detail.href);
23 | },
24 | [navigate],
25 | );
26 | }
27 |
--------------------------------------------------------------------------------
/empty-vite/src/common/types.ts:
--------------------------------------------------------------------------------
1 | export interface NavigationPanelState {
2 | collapsed?: boolean;
3 | collapsedSections?: Record;
4 | }
5 |
--------------------------------------------------------------------------------
/empty-vite/src/components/base-app-layout.tsx:
--------------------------------------------------------------------------------
1 | import { AppLayout, AppLayoutProps } from "@cloudscape-design/components";
2 | import { useNavigationPanelState } from "../common/hooks/use-navigation-panel-state";
3 | import NavigationPanel from "./navigation-panel";
4 |
5 | export default function BaseAppLayout(props: AppLayoutProps) {
6 | const [navigationPanelState, setNavigationPanelState] =
7 | useNavigationPanelState();
8 |
9 | return (
10 | }
13 | navigationOpen={!navigationPanelState.collapsed}
14 | onNavigationChange={({ detail }) =>
15 | setNavigationPanelState({ collapsed: !detail.open })
16 | }
17 | toolsHide={true}
18 | {...props}
19 | />
20 | );
21 | }
22 |
--------------------------------------------------------------------------------
/empty-vite/src/components/global-header.tsx:
--------------------------------------------------------------------------------
1 | import { useState } from "react";
2 | import { TopNavigation } from "@cloudscape-design/components";
3 | import { Mode } from "@cloudscape-design/global-styles";
4 | import { StorageHelper } from "../common/helpers/storage-helper";
5 | import { APP_NAME } from "../common/constants";
6 |
7 | export default function GlobalHeader() {
8 | const [theme, setTheme] = useState(StorageHelper.getTheme());
9 |
10 | const onChangeThemeClick = () => {
11 | if (theme === Mode.Dark) {
12 | setTheme(StorageHelper.applyTheme(Mode.Light));
13 | } else {
14 | setTheme(StorageHelper.applyTheme(Mode.Dark));
15 | }
16 | };
17 |
18 | return (
19 |
23 |
36 |
37 | );
38 | }
39 |
--------------------------------------------------------------------------------
/empty-vite/src/components/navigation-panel.tsx:
--------------------------------------------------------------------------------
1 | import {
2 | SideNavigation,
3 | SideNavigationProps,
4 | } from "@cloudscape-design/components";
5 | import { useNavigationPanelState } from "../common/hooks/use-navigation-panel-state";
6 | import { useState } from "react";
7 | import { useOnFollow } from "../common/hooks/use-on-follow";
8 | import { APP_NAME } from "../common/constants";
9 | import { useLocation } from "react-router-dom";
10 |
11 | export default function NavigationPanel() {
12 | const location = useLocation();
13 | const onFollow = useOnFollow();
14 | const [navigationPanelState, setNavigationPanelState] =
15 | useNavigationPanelState();
16 |
17 | const [items] = useState(() => {
18 | const items: SideNavigationProps.Item[] = [
19 | {
20 | type: "link",
21 | text: "Home",
22 | href: "/",
23 | },
24 | {
25 | type: "section",
26 | text: "Section",
27 | items: [
28 | { type: "link", text: "Item 1", href: "/section/item1" },
29 | { type: "link", text: "Item 2", href: "/section/item2" },
30 | { type: "link", text: "Item 2", href: "/section/item3" },
31 | ],
32 | },
33 | ];
34 |
35 | items.push(
36 | { type: "divider" },
37 | {
38 | type: "link",
39 | text: "Documentation",
40 | href: "https://github.com/aws-samples/cloudscape-examples",
41 | external: true,
42 | }
43 | );
44 |
45 | return items;
46 | });
47 |
48 | const onChange = ({
49 | detail,
50 | }: {
51 | detail: SideNavigationProps.ChangeDetail;
52 | }) => {
53 | const sectionIndex = items.indexOf(detail.item);
54 | setNavigationPanelState({
55 | collapsedSections: {
56 | ...navigationPanelState.collapsedSections,
57 | [sectionIndex]: !detail.expanded,
58 | },
59 | });
60 | };
61 |
62 | return (
63 | {
69 | if (value.type === "section") {
70 | const collapsed =
71 | navigationPanelState.collapsedSections?.[idx] === true;
72 | value.defaultExpanded = !collapsed;
73 | }
74 |
75 | return value;
76 | })}
77 | />
78 | );
79 | }
80 |
--------------------------------------------------------------------------------
/empty-vite/src/components/wrappers/router-button-dropdown.tsx:
--------------------------------------------------------------------------------
1 | import {
2 | ButtonDropdownProps,
3 | ButtonDropdown,
4 | } from "@cloudscape-design/components";
5 | import { useOnFollow } from "../../common/hooks/use-on-follow";
6 |
7 | export default function RouterButtonDropdown(props: ButtonDropdownProps) {
8 | const onFollow = useOnFollow();
9 |
10 | return ;
11 | }
12 |
--------------------------------------------------------------------------------
/empty-vite/src/components/wrappers/router-button.tsx:
--------------------------------------------------------------------------------
1 | import { ButtonProps, Button } from "@cloudscape-design/components";
2 | import { useOnFollow } from "../../common/hooks/use-on-follow";
3 |
4 | export default function RouterButton(props: ButtonProps) {
5 | const onFollow = useOnFollow();
6 |
7 | return ;
8 | }
9 |
--------------------------------------------------------------------------------
/empty-vite/src/components/wrappers/router-link.tsx:
--------------------------------------------------------------------------------
1 | import { Link, LinkProps } from "@cloudscape-design/components";
2 | import { useOnFollow } from "../../common/hooks/use-on-follow";
3 |
4 | export default function RouterLink(props: LinkProps) {
5 | const onFollow = useOnFollow();
6 |
7 | return ;
8 | }
9 |
--------------------------------------------------------------------------------
/empty-vite/src/main.tsx:
--------------------------------------------------------------------------------
1 | import React from "react";
2 | import ReactDOM from "react-dom/client";
3 | import { StorageHelper } from "./common/helpers/storage-helper";
4 | import App from "./app";
5 | import "@cloudscape-design/global-styles/index.css";
6 |
7 | const root = ReactDOM.createRoot(
8 | document.getElementById("root") as HTMLElement
9 | );
10 |
11 | const theme = StorageHelper.getTheme();
12 | StorageHelper.applyTheme(theme);
13 |
14 | root.render(
15 |
16 |
17 |
18 | );
19 |
--------------------------------------------------------------------------------
/empty-vite/src/pages/home.tsx:
--------------------------------------------------------------------------------
1 | import { TextContent } from "@cloudscape-design/components";
2 | import BaseAppLayout from "../components/base-app-layout";
3 |
4 | export default function HomePage() {
5 | return (
6 |
9 | Home Page
10 |
11 | }
12 | />
13 | );
14 | }
15 |
--------------------------------------------------------------------------------
/empty-vite/src/pages/not-found.tsx:
--------------------------------------------------------------------------------
1 | import {
2 | Alert,
3 | BreadcrumbGroup,
4 | Container,
5 | ContentLayout,
6 | Header,
7 | SpaceBetween,
8 | } from "@cloudscape-design/components";
9 | import { useOnFollow } from "../common/hooks/use-on-follow";
10 | import { APP_NAME } from "../common/constants";
11 | import BaseAppLayout from "../components/base-app-layout";
12 |
13 | export default function NotFound() {
14 | const onFollow = useOnFollow();
15 |
16 | return (
17 |
34 | }
35 | content={
36 | 404. Page Not Found}
38 | >
39 |
40 |
41 |
42 | The page you are looking for does not exist.
43 |
44 |
45 |
46 |
47 | }
48 | />
49 | );
50 | }
51 |
--------------------------------------------------------------------------------
/empty-vite/src/styles/app.scss:
--------------------------------------------------------------------------------
1 | * {
2 | box-sizing: border-box;
3 | }
4 |
5 | :root {
6 | --app-color-scheme: light;
7 | color-scheme: var(--app-color-scheme);
8 | }
9 |
10 | html,
11 | body,
12 | #root,
13 | div[data-amplify-authenticator],
14 | div[data-amplify-theme] {
15 | height: 100%;
16 | }
17 |
18 | body {
19 | background-color: #ffffff;
20 | overflow-y: scroll;
21 | }
22 |
23 | body.awsui-dark-mode {
24 | background-color: #0e1b2a;
25 | }
26 |
--------------------------------------------------------------------------------
/empty-vite/src/vite-env.d.ts:
--------------------------------------------------------------------------------
1 | ///
2 |
--------------------------------------------------------------------------------
/empty-vite/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | "target": "ES2020",
4 | "useDefineForClassFields": true,
5 | "lib": ["ES2020", "DOM", "DOM.Iterable"],
6 | "module": "ESNext",
7 | "skipLibCheck": true,
8 |
9 | /* Bundler mode */
10 | "moduleResolution": "bundler",
11 | "allowImportingTsExtensions": true,
12 | "resolveJsonModule": true,
13 | "isolatedModules": true,
14 | "noEmit": true,
15 | "jsx": "react-jsx",
16 |
17 | /* Linting */
18 | "strict": true,
19 | "noUnusedLocals": true,
20 | "noUnusedParameters": true,
21 | "noFallthroughCasesInSwitch": true
22 | },
23 | "include": ["src"],
24 | "references": [{ "path": "./tsconfig.node.json" }]
25 | }
26 |
--------------------------------------------------------------------------------
/empty-vite/tsconfig.node.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | "composite": true,
4 | "skipLibCheck": true,
5 | "module": "ESNext",
6 | "moduleResolution": "bundler",
7 | "allowSyntheticDefaultImports": true,
8 | "strict": true
9 | },
10 | "include": ["vite.config.ts"]
11 | }
12 |
--------------------------------------------------------------------------------
/empty-vite/vite.config.ts:
--------------------------------------------------------------------------------
1 | import { defineConfig } from "vite";
2 | import react from "@vitejs/plugin-react";
3 |
4 | // https://vitejs.dev/config/
5 | export default defineConfig({
6 | plugins: [react()],
7 | server: {
8 | port: 3000,
9 | },
10 | });
11 |
--------------------------------------------------------------------------------
/full-stack-chat-ui-cognito-auth/.eslintrc.cjs:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | root: true,
3 | env: { browser: true, es2020: true },
4 | extends: [
5 | 'eslint:recommended',
6 | 'plugin:@typescript-eslint/recommended',
7 | 'plugin:react-hooks/recommended',
8 | ],
9 | ignorePatterns: ['dist', '.eslintrc.cjs'],
10 | parser: '@typescript-eslint/parser',
11 | plugins: ['react-refresh'],
12 | rules: {
13 | 'react-refresh/only-export-components': ['warn', { allowConstantExport: true }],
14 | },
15 | };
16 |
--------------------------------------------------------------------------------
/full-stack-chat-ui-cognito-auth/.npmignore:
--------------------------------------------------------------------------------
1 | *.ts
2 | !*.d.ts
3 |
4 | # CDK asset staging directory
5 | .cdk.staging
6 | cdk.out
7 |
--------------------------------------------------------------------------------
/full-stack-chat-ui-cognito-auth/bin/index.ts:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env node
2 | import "source-map-support/register";
3 | import * as cdk from "aws-cdk-lib";
4 | import { InfrastructureStack } from "../lib/infrastructure-stack";
5 |
6 | const app = new cdk.App();
7 | new InfrastructureStack(app, "ChatUiInfrastructureStack", {
8 | /* If you don't specify 'env', this stack will be environment-agnostic.
9 | * Account/Region-dependent features and context lookups will not work,
10 | * but a single synthesized template can be deployed anywhere. */
11 | /* Uncomment the next line to specialize this stack for the AWS Account
12 | * and Region that are implied by the current CLI configuration. */
13 | // env: { account: process.env.CDK_DEFAULT_ACCOUNT, region: process.env.CDK_DEFAULT_REGION },
14 | /* Uncomment the next line if you know exactly what Account and Region you
15 | * want to deploy the stack to. */
16 | // env: { account: '123456789012', region: 'us-east-1' },
17 | /* For more information, see https://docs.aws.amazon.com/cdk/latest/guide/environments.html */
18 | });
19 |
--------------------------------------------------------------------------------
/full-stack-chat-ui-cognito-auth/cdk.json:
--------------------------------------------------------------------------------
1 | {
2 | "app": "npx ts-node --prefer-ts-exts bin/index.ts",
3 | "watch": {
4 | "include": ["**"],
5 | "exclude": [
6 | "README.md",
7 | "cdk*.json",
8 | "**/*.d.ts",
9 | "**/*.js",
10 | "tsconfig.json",
11 | "package*.json",
12 | "yarn.lock",
13 | "node_modules",
14 | "test"
15 | ]
16 | },
17 | "context": {
18 | "@aws-cdk/aws-lambda:recognizeLayerVersion": true,
19 | "@aws-cdk/core:checkSecretUsage": true,
20 | "@aws-cdk/core:target-partitions": ["aws", "aws-cn"],
21 | "@aws-cdk-containers/ecs-service-extensions:enableDefaultLogDriver": true,
22 | "@aws-cdk/aws-ec2:uniqueImdsv2TemplateName": true,
23 | "@aws-cdk/aws-ecs:arnFormatIncludesClusterName": true,
24 | "@aws-cdk/aws-iam:minimizePolicies": true,
25 | "@aws-cdk/core:validateSnapshotRemovalPolicy": true,
26 | "@aws-cdk/aws-codepipeline:crossAccountKeyAliasStackSafeResourceName": true,
27 | "@aws-cdk/aws-s3:createDefaultLoggingPolicy": true,
28 | "@aws-cdk/aws-sns-subscriptions:restrictSqsDescryption": true,
29 | "@aws-cdk/aws-apigateway:disableCloudWatchRole": true,
30 | "@aws-cdk/core:enablePartitionLiterals": true,
31 | "@aws-cdk/aws-events:eventsTargetQueueSameAccount": true,
32 | "@aws-cdk/aws-iam:standardizedServicePrincipals": true,
33 | "@aws-cdk/aws-ecs:disableExplicitDeploymentControllerForCircuitBreaker": true,
34 | "@aws-cdk/aws-iam:importedRoleStackSafeDefaultPolicyName": true,
35 | "@aws-cdk/aws-s3:serverAccessLogsUseBucketPolicy": true,
36 | "@aws-cdk/aws-route53-patters:useCertificate": true,
37 | "@aws-cdk/customresources:installLatestAwsSdkDefault": false,
38 | "@aws-cdk/aws-rds:databaseProxyUniqueResourceName": true,
39 | "@aws-cdk/aws-codedeploy:removeAlarmsFromDeploymentGroup": true,
40 | "@aws-cdk/aws-apigateway:authorizerChangeDeploymentLogicalId": true,
41 | "@aws-cdk/aws-ec2:launchTemplateDefaultUserData": true,
42 | "@aws-cdk/aws-secretsmanager:useAttachedSecretResourcePolicyForSecretTargetAttachments": true,
43 | "@aws-cdk/aws-redshift:columnId": true,
44 | "@aws-cdk/aws-stepfunctions-tasks:enableEmrServicePolicyV2": true,
45 | "@aws-cdk/aws-ec2:restrictDefaultSecurityGroup": true,
46 | "@aws-cdk/aws-apigateway:requestValidatorUniqueId": true,
47 | "@aws-cdk/aws-kms:aliasNameRef": true,
48 | "@aws-cdk/aws-autoscaling:generateLaunchTemplateInsteadOfLaunchConfig": true,
49 | "@aws-cdk/core:includePrefixInUniqueNameGeneration": true,
50 | "@aws-cdk/aws-efs:denyAnonymousAccess": true,
51 | "@aws-cdk/aws-opensearchservice:enableOpensearchMultiAzWithStandby": true,
52 | "@aws-cdk/aws-lambda-nodejs:useLatestRuntimeVersion": true,
53 | "@aws-cdk/aws-efs:mountTargetOrderInsensitiveLogicalId": true,
54 | "@aws-cdk/aws-rds:auroraClusterChangeScopeOfInstanceParameterGroupWithEachParameters": true,
55 | "@aws-cdk/aws-appsync:useArnForSourceApiAssociationIdentifier": true,
56 | "@aws-cdk/aws-rds:preventRenderingDeprecatedCredentials": true,
57 | "@aws-cdk/aws-codepipeline-actions:useNewDefaultBranchForCodeCommitSource": true,
58 | "@aws-cdk/aws-cloudwatch-actions:changeLambdaPermissionLogicalIdForLambdaAction": true
59 | }
60 | }
61 |
--------------------------------------------------------------------------------
/full-stack-chat-ui-cognito-auth/functions/api-handler/index.py:
--------------------------------------------------------------------------------
1 | import os
2 | import json
3 | from pydantic import ValidationError
4 | from botocore.exceptions import ClientError
5 | from aws_lambda_powertools.utilities import parameters
6 | from aws_lambda_powertools import Logger, Tracer
7 | from aws_lambda_powertools.logging import correlation_paths
8 | from aws_lambda_powertools.utilities.typing import LambdaContext
9 | from aws_lambda_powertools.event_handler.api_gateway import Response
10 | from aws_lambda_powertools.event_handler import (
11 | APIGatewayRestResolver,
12 | CORSConfig,
13 | content_types,
14 | )
15 | from utils import CustomEncoder
16 | from routes.health import router as health_router
17 | from routes.chat import router as chat_router
18 |
19 | tracer = Tracer()
20 | logger = Logger()
21 |
22 | X_ORIGIN_VERIFY_SECRET_ARN = os.environ.get("X_ORIGIN_VERIFY_SECRET_ARN")
23 |
24 | cors_config = CORSConfig(allow_origin="*", max_age=300)
25 | app = APIGatewayRestResolver(
26 | cors=cors_config,
27 | strip_prefixes=["/v1"],
28 | serializer=lambda obj: json.dumps(obj, cls=CustomEncoder),
29 | )
30 |
31 | app.include_router(health_router)
32 | app.include_router(chat_router)
33 |
34 |
35 | @app.exception_handler(ClientError)
36 | def handle_value_error(e: ClientError):
37 | logger.exception(e)
38 |
39 | return Response(
40 | status_code=200,
41 | content_type=content_types.APPLICATION_JSON,
42 | body=json.dumps(
43 | {"error": True, "message": str(e)},
44 | cls=CustomEncoder,
45 | ),
46 | )
47 |
48 |
49 | @app.exception_handler(ValidationError)
50 | def handle_value_error(e: ValidationError):
51 | logger.exception(e)
52 |
53 | return Response(
54 | status_code=200,
55 | content_type=content_types.APPLICATION_JSON,
56 | body=json.dumps(
57 | {"error": True, "message": [str(error) for error in e.errors()]},
58 | cls=CustomEncoder,
59 | ),
60 | )
61 |
62 |
63 | def get_origin_verify_header_value():
64 | origin_verify_header_value = parameters.get_secret(
65 | X_ORIGIN_VERIFY_SECRET_ARN, transform="json", max_age=60
66 | )["headerValue"]
67 |
68 | return origin_verify_header_value
69 |
70 |
71 | @logger.inject_lambda_context(
72 | log_event=True, correlation_id_path=correlation_paths.API_GATEWAY_REST
73 | )
74 | @tracer.capture_lambda_handler
75 | def handler(event: dict, context: LambdaContext) -> dict:
76 | origin_verify_header_value = get_origin_verify_header_value()
77 | if event["headers"]["X-Origin-Verify"] == origin_verify_header_value:
78 | return app.resolve(event, context)
79 |
80 | return {"statusCode": 403, "body": "Forbidden"}
81 |
--------------------------------------------------------------------------------
/full-stack-chat-ui-cognito-auth/functions/api-handler/requirements.txt:
--------------------------------------------------------------------------------
1 | pydantic==2.6.1
--------------------------------------------------------------------------------
/full-stack-chat-ui-cognito-auth/functions/api-handler/routes/chat.py:
--------------------------------------------------------------------------------
1 | import os
2 | import uuid
3 | import boto3
4 | from datetime import datetime
5 | from pydantic import BaseModel
6 | from aws_lambda_powertools import Logger, Tracer
7 | from aws_lambda_powertools.event_handler.api_gateway import Router
8 |
9 | tracer = Tracer()
10 | router = Router()
11 | logger = Logger()
12 |
13 |
14 |
15 | @router.post("/chat")
16 | @tracer.capture_method
17 | def chat():
18 | data: dict = router.current_event.json_body
19 |
20 | logger.info(data)
21 |
22 | return {"ok": True, "response":data}
23 |
--------------------------------------------------------------------------------
/full-stack-chat-ui-cognito-auth/functions/api-handler/routes/health.py:
--------------------------------------------------------------------------------
1 | from aws_lambda_powertools import Logger, Tracer
2 | from aws_lambda_powertools.event_handler.api_gateway import Router
3 |
4 | tracer = Tracer()
5 | router = Router()
6 | logger = Logger()
7 |
8 |
9 | @router.get("/health")
10 | @tracer.capture_method
11 | def health():
12 | return {"ok": True}
13 |
--------------------------------------------------------------------------------
/full-stack-chat-ui-cognito-auth/functions/api-handler/utils.py:
--------------------------------------------------------------------------------
1 | import json
2 | import uuid
3 | import decimal
4 |
5 |
6 | class CustomEncoder(json.JSONEncoder):
7 | def default(self, obj):
8 | if isinstance(obj, decimal.Decimal):
9 | if obj % 1 > 0:
10 | return float(obj)
11 | else:
12 | return int(obj)
13 |
14 | if isinstance(obj, uuid.UUID):
15 | return str(obj)
16 |
17 | return super(CustomEncoder, self).default(obj)
18 |
--------------------------------------------------------------------------------
/full-stack-chat-ui-cognito-auth/jest.config.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | testEnvironment: 'node',
3 | roots: ['/test'],
4 | testMatch: ['**/*.test.ts'],
5 | transform: {
6 | '^.+\\.tsx?$': 'ts-jest'
7 | }
8 | };
9 |
--------------------------------------------------------------------------------
/full-stack-chat-ui-cognito-auth/lib/utils.ts:
--------------------------------------------------------------------------------
1 | import * as fs from "node:fs";
2 | import * as path from "node:path";
3 |
4 | export abstract class Utils {
5 | static copyDirRecursive(sourceDir: string, targetDir: string): void {
6 | if (!fs.existsSync(targetDir)) {
7 | fs.mkdirSync(targetDir);
8 | }
9 |
10 | const files = fs.readdirSync(sourceDir);
11 |
12 | for (const file of files) {
13 | const sourceFilePath = path.join(sourceDir, file);
14 | const targetFilePath = path.join(targetDir, file);
15 | const stats = fs.statSync(sourceFilePath);
16 |
17 | if (stats.isDirectory()) {
18 | Utils.copyDirRecursive(sourceFilePath, targetFilePath);
19 | } else {
20 | fs.copyFileSync(sourceFilePath, targetFilePath);
21 | }
22 | }
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/full-stack-chat-ui-cognito-auth/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "cloudscape-cdk-app",
3 | "version": "0.1.0",
4 | "bin": {
5 | "fullstack-vite-cdk-cognito-auth": "bin/index.js"
6 | },
7 | "scripts": {
8 | "build": "tsc",
9 | "watch": "tsc -w",
10 | "test": "jest",
11 | "cdk": "cdk",
12 | "format": "npx prettier --ignore-path .gitignore --write \"**/*.+(tsx|js|ts|json)\""
13 | },
14 | "devDependencies": {
15 | "@types/jest": "^29.5.11",
16 | "@types/node": "20.11.6",
17 | "aws-cdk": "2.137.0",
18 | "jest": "^29.7.0",
19 | "ts-jest": "^29.1.2",
20 | "ts-node": "^10.9.2",
21 | "typescript": "~5.3.3"
22 | },
23 | "dependencies": {
24 | "@aws-cdk/aws-apigatewayv2-alpha": "^2.114.1-alpha.0",
25 | "@aws-cdk/aws-cognito-identitypool-alpha": "^2.137.0-alpha.0",
26 | "@aws-cdk/aws-lambda-python-alpha": "^2.137.0-alpha.0",
27 | "@cloudscape-design/design-tokens": "^3.0.34",
28 | "aws-cdk-lib": "2.137.0",
29 | "constructs": "^10.0.0",
30 | "source-map-support": "^0.5.21"
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/full-stack-chat-ui-cognito-auth/prettier.config.cjs:
--------------------------------------------------------------------------------
1 | // eslint-disable-next-line no-undef
2 | module.export = {
3 | semi: true,
4 | trailingComma: "es5",
5 | singleQuote: false,
6 | tabWidth: 2,
7 | useTabs: false,
8 | };
9 |
--------------------------------------------------------------------------------
/full-stack-chat-ui-cognito-auth/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | "target": "ES2020",
4 | "module": "commonjs",
5 | "lib": [
6 | "es2020",
7 | "dom"
8 | ],
9 | "declaration": true,
10 | "strict": true,
11 | "noImplicitAny": true,
12 | "strictNullChecks": true,
13 | "noImplicitThis": true,
14 | "alwaysStrict": true,
15 | "noUnusedLocals": false,
16 | "noUnusedParameters": false,
17 | "noImplicitReturns": true,
18 | "noFallthroughCasesInSwitch": false,
19 | "inlineSourceMap": true,
20 | "inlineSources": true,
21 | "experimentalDecorators": true,
22 | "strictPropertyInitialization": false,
23 | "typeRoots": [
24 | "./node_modules/@types"
25 | ]
26 | },
27 | "exclude": [
28 | "node_modules",
29 | "cdk.out"
30 | ]
31 | }
32 |
--------------------------------------------------------------------------------
/full-stack-chat-ui-cognito-auth/user-interface/.eslintrc.cjs:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | root: true,
3 | env: { browser: true, es2020: true },
4 | extends: [
5 | 'eslint:recommended',
6 | 'plugin:@typescript-eslint/recommended',
7 | 'plugin:react-hooks/recommended',
8 | ],
9 | ignorePatterns: ['dist', '.eslintrc.cjs'],
10 | parser: '@typescript-eslint/parser',
11 | plugins: ['react-refresh'],
12 | rules: {
13 | 'react-refresh/only-export-components': ['warn', { allowConstantExport: true }],
14 | },
15 | };
16 |
--------------------------------------------------------------------------------
/full-stack-chat-ui-cognito-auth/user-interface/README.md:
--------------------------------------------------------------------------------
1 | # Chat UI Cloudscape App
2 |
3 | [https://cloudscape.design/](https://cloudscape.design/)
4 |
5 | Cloudscape is an open source design system for the cloud. Cloudscape offers user interface guidelines, front-end components, design resources, and development tools for building intuitive, engaging, and inclusive user experiences at scale.
6 |
7 |
8 | 
9 |
10 |
11 | ## Vite.js
12 |
13 | [https://vitejs.dev/](https://vitejs.dev/)
14 |
15 | Vite.js is a modern, fast front-end build tool that significantly improves the developer experience when building web applications.
16 |
17 | ## Development
18 | 1. Clone this repository to your local machine
19 | ```bash
20 | git clone https://github.com/aws-samples/cloudscape-examples
21 | cd cloudscape-examples/chat-ui-vite
22 | ```
23 | 2. Install the project dependencies by running:
24 | ```bash
25 | npm install
26 | ```
27 | 3. To start the development server, run:
28 | ```bash
29 | npm run dev
30 | ```
31 |
32 | This command will start a local development server at ``http://localhost:3000`` (or a different port if 3000 is in use). The server will hot-reload if you make edits to any of the source files.
33 |
34 | ## Building the App
35 | To build the application for production, run:
36 | ```bash
37 | npm run build
38 | ```
39 | This command will generate a dist folder containing the production build of your app. Vite optimizes your project for the best performance during this process.
40 |
41 | ## Running the App Locally
42 | After building the app, you can serve it locally using:
43 | ```bash
44 | npm run preview
45 | ```
46 | This command serves the production build from the dist folder, allowing you to preview the app before deployment.
--------------------------------------------------------------------------------
/full-stack-chat-ui-cognito-auth/user-interface/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
12 |
17 |
18 |
19 | Example App
20 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
--------------------------------------------------------------------------------
/full-stack-chat-ui-cognito-auth/user-interface/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "cloudscape-app",
3 | "private": true,
4 | "version": "0.0.0",
5 | "type": "module",
6 | "scripts": {
7 | "dev": "vite",
8 | "build": "tsc && vite build",
9 | "preview": "vite preview",
10 | "lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0",
11 | "format": "npx prettier --ignore-path .gitignore --write \"**/*.+(tsx|js|ts|json)\""
12 | },
13 | "dependencies": {
14 | "@aws-amplify/ui-react": "^6.1.3",
15 | "@cloudscape-design/components": "^3.0.611",
16 | "@cloudscape-design/design-tokens": "^3.0.35",
17 | "@cloudscape-design/global-styles": "^1.0.27",
18 | "aws-amplify": "^6.0.15",
19 | "react": "^18.2.0",
20 | "react-dom": "^18.2.0",
21 | "react-markdown": "^9.0.1",
22 | "react-router-dom": "^6.22.0",
23 | "react-textarea-autosize": "^8.5.3",
24 | "remark-gfm": "^4.0.0"
25 | },
26 | "devDependencies": {
27 | "@types/react": "^18.2.55",
28 | "@types/react-dom": "^18.2.19",
29 | "@typescript-eslint/eslint-plugin": "^6.21.0",
30 | "@typescript-eslint/parser": "^6.21.0",
31 | "@vitejs/plugin-react": "^4.3.2",
32 | "autoprefixer": "^10.4.17",
33 | "eslint": "^8.56.0",
34 | "eslint-plugin-react-hooks": "^4.6.0",
35 | "eslint-plugin-react-refresh": "^0.4.5",
36 | "postcss": "^8.4.35",
37 | "sass": "^1.70.0",
38 | "typescript": "^5.2.2",
39 | "vite": "^5.4.8"
40 | },
41 | "overrides": {
42 | "react-virtual": {
43 | "react": "^18.0.0"
44 | }
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/full-stack-chat-ui-cognito-auth/user-interface/postcss.config.js:
--------------------------------------------------------------------------------
1 | export default {
2 | plugins: {
3 | autoprefixer: {},
4 | },
5 | };
6 |
--------------------------------------------------------------------------------
/full-stack-chat-ui-cognito-auth/user-interface/prettier.config.cjs:
--------------------------------------------------------------------------------
1 | // eslint-disable-next-line no-undef
2 | module.export = {
3 | semi: true,
4 | trailingComma: "es5",
5 | singleQuote: false,
6 | tabWidth: 2,
7 | useTabs: false,
8 | };
9 |
--------------------------------------------------------------------------------
/full-stack-chat-ui-cognito-auth/user-interface/public/aws-exports.template.json:
--------------------------------------------------------------------------------
1 | {
2 | "region": "eu-west-1",
3 | "Auth": {
4 | "Cognito": {
5 | "userPoolClientId": "0000000000000000000000000",
6 | "userPoolId": "eu-west-0_AAAAAAAAA",
7 | "identityPoolId": "eu-west-1:aaaaaaaa-aaaaaaaaa-aaaa-aaaaaaaaaaaa"
8 | }
9 | },
10 | "API": {
11 | "REST": {
12 | "RestApi": { "endpoint": "https://aaaaaaaaaaaaaa.cloudfront.net/api/v1" }
13 | }
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/full-stack-chat-ui-cognito-auth/user-interface/public/favicon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/aws-samples/cloudscape-examples/35055cf8fb197302784028998a9d8c3c55acea78/full-stack-chat-ui-cognito-auth/user-interface/public/favicon.ico
--------------------------------------------------------------------------------
/full-stack-chat-ui-cognito-auth/user-interface/public/images/android-chrome-192x192.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/aws-samples/cloudscape-examples/35055cf8fb197302784028998a9d8c3c55acea78/full-stack-chat-ui-cognito-auth/user-interface/public/images/android-chrome-192x192.png
--------------------------------------------------------------------------------
/full-stack-chat-ui-cognito-auth/user-interface/public/images/android-chrome-512x512.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/aws-samples/cloudscape-examples/35055cf8fb197302784028998a9d8c3c55acea78/full-stack-chat-ui-cognito-auth/user-interface/public/images/android-chrome-512x512.png
--------------------------------------------------------------------------------
/full-stack-chat-ui-cognito-auth/user-interface/public/images/apple-touch-icon.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/aws-samples/cloudscape-examples/35055cf8fb197302784028998a9d8c3c55acea78/full-stack-chat-ui-cognito-auth/user-interface/public/images/apple-touch-icon.png
--------------------------------------------------------------------------------
/full-stack-chat-ui-cognito-auth/user-interface/public/images/favicon-16x16.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/aws-samples/cloudscape-examples/35055cf8fb197302784028998a9d8c3c55acea78/full-stack-chat-ui-cognito-auth/user-interface/public/images/favicon-16x16.png
--------------------------------------------------------------------------------
/full-stack-chat-ui-cognito-auth/user-interface/public/images/favicon-32x32.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/aws-samples/cloudscape-examples/35055cf8fb197302784028998a9d8c3c55acea78/full-stack-chat-ui-cognito-auth/user-interface/public/images/favicon-32x32.png
--------------------------------------------------------------------------------
/full-stack-chat-ui-cognito-auth/user-interface/public/images/favicon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/aws-samples/cloudscape-examples/35055cf8fb197302784028998a9d8c3c55acea78/full-stack-chat-ui-cognito-auth/user-interface/public/images/favicon.ico
--------------------------------------------------------------------------------
/full-stack-chat-ui-cognito-auth/user-interface/public/images/logo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/aws-samples/cloudscape-examples/35055cf8fb197302784028998a9d8c3c55acea78/full-stack-chat-ui-cognito-auth/user-interface/public/images/logo.png
--------------------------------------------------------------------------------
/full-stack-chat-ui-cognito-auth/user-interface/public/manifest.json:
--------------------------------------------------------------------------------
1 | {
2 | "id": "/",
3 | "start_url": "/",
4 | "name": "Example App",
5 | "short_name": "Example App",
6 | "description": "Example App sample",
7 | "theme_color": "#000000",
8 | "background_color": "#ffffff",
9 | "display": "standalone",
10 | "icons": [
11 | {
12 | "src": "/images/android-chrome-192x192.png",
13 | "sizes": "192x192",
14 | "type": "image/png"
15 | },
16 | {
17 | "src": "/images/android-chrome-512x512.png",
18 | "sizes": "512x512",
19 | "type": "image/png"
20 | }
21 | ]
22 | }
23 |
--------------------------------------------------------------------------------
/full-stack-chat-ui-cognito-auth/user-interface/src/app.tsx:
--------------------------------------------------------------------------------
1 | import { HashRouter, BrowserRouter, Routes, Route } from "react-router-dom";
2 | import { USE_BROWSER_ROUTER } from "./common/constants";
3 | import GlobalHeader from "./components/global-header";
4 | import NotFound from "./pages/not-found";
5 | import ChatPage from "./pages/chat-page";
6 | import "./styles/app.scss";
7 |
8 | export default function App() {
9 | const Router = USE_BROWSER_ROUTER ? BrowserRouter : HashRouter;
10 |
11 | return (
12 |
13 |
14 |
15 |
16 |
17 |
18 | } />
19 | } />
20 |
21 |
22 |
23 |
24 | );
25 | }
26 |
--------------------------------------------------------------------------------
/full-stack-chat-ui-cognito-auth/user-interface/src/common/api-client/api-client-base.ts:
--------------------------------------------------------------------------------
1 | import { fetchAuthSession } from "aws-amplify/auth";
2 |
3 | export abstract class ApiClientBase {
4 | protected async getHeaders() {
5 | return {
6 | Authorization: `Bearer ${await this.getIdToken()}`,
7 | };
8 | }
9 |
10 | protected async getIdToken() {
11 | const session = await fetchAuthSession();
12 | return session.tokens?.idToken?.toString();
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/full-stack-chat-ui-cognito-auth/user-interface/src/common/api-client/api-client.ts:
--------------------------------------------------------------------------------
1 | import { ChatApiClient } from "./chat-api-client";
2 |
3 | export class ApiClient {
4 | private _chatClient: ChatApiClient | undefined;
5 |
6 | public get chatClient() {
7 | if (!this._chatClient) {
8 | this._chatClient = new ChatApiClient();
9 | }
10 |
11 | return this._chatClient;
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/full-stack-chat-ui-cognito-auth/user-interface/src/common/api-client/chat-api-client.ts:
--------------------------------------------------------------------------------
1 | import { post} from "aws-amplify/api";
2 | import { API_NAME } from "../constants";
3 | import { ApiClientBase } from "./api-client-base";
4 |
5 | export class ChatApiClient extends ApiClientBase {
6 | async chat(message:string): Promise {
7 | const headers = await this.getHeaders();
8 | const restOperation = post({
9 | apiName: API_NAME,
10 | path: "/chat",
11 | options: {
12 | headers,
13 | body:{
14 | message: message
15 | }
16 | },
17 | });
18 |
19 | const response = await restOperation.response;
20 | const data = (await response.body.json()) as any;
21 |
22 | return data;
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/full-stack-chat-ui-cognito-auth/user-interface/src/common/constants.ts:
--------------------------------------------------------------------------------
1 | export const APP_NAME = "Example App";
2 | export const USE_BROWSER_ROUTER = true;
3 | export const API_NAME = "RestApi";
--------------------------------------------------------------------------------
/full-stack-chat-ui-cognito-auth/user-interface/src/common/helpers/storage-helper.ts:
--------------------------------------------------------------------------------
1 | import { Mode, applyMode } from "@cloudscape-design/global-styles";
2 | import { NavigationPanelState } from "../types";
3 |
4 | const PREFIX = "example-app";
5 | const THEME_STORAGE_NAME = `${PREFIX}-theme`;
6 | const NAVIGATION_PANEL_STATE_STORAGE_NAME = `${PREFIX}-navigation-panel-state`;
7 |
8 | export abstract class StorageHelper {
9 | static getTheme() {
10 | const value = localStorage.getItem(THEME_STORAGE_NAME) ?? Mode.Light;
11 | const theme = value === Mode.Dark ? Mode.Dark : Mode.Light;
12 |
13 | return theme;
14 | }
15 |
16 | static applyTheme(theme: Mode) {
17 | localStorage.setItem(THEME_STORAGE_NAME, theme);
18 | applyMode(theme);
19 |
20 | document.documentElement.style.setProperty(
21 | "--app-color-scheme",
22 | theme === Mode.Dark ? "dark" : "light"
23 | );
24 |
25 | return theme;
26 | }
27 |
28 | static getNavigationPanelState(): NavigationPanelState {
29 | const value =
30 | localStorage.getItem(NAVIGATION_PANEL_STATE_STORAGE_NAME) ??
31 | JSON.stringify({
32 | collapsed: true,
33 | });
34 |
35 | let state: NavigationPanelState | null = null;
36 | try {
37 | state = JSON.parse(value);
38 | } catch {
39 | state = {};
40 | }
41 |
42 | return state ?? {};
43 | }
44 |
45 | static setNavigationPanelState(state: Partial) {
46 | const currentState = this.getNavigationPanelState();
47 | const newState = { ...currentState, ...state };
48 | const stateStr = JSON.stringify(newState);
49 | localStorage.setItem(NAVIGATION_PANEL_STATE_STORAGE_NAME, stateStr);
50 |
51 | return newState;
52 | }
53 | }
54 |
--------------------------------------------------------------------------------
/full-stack-chat-ui-cognito-auth/user-interface/src/common/hooks/use-navigation-panel-state.ts:
--------------------------------------------------------------------------------
1 | import { useState } from "react";
2 | import { StorageHelper } from "../helpers/storage-helper";
3 | import { NavigationPanelState } from "../types";
4 |
5 | export function useNavigationPanelState(): [
6 | NavigationPanelState,
7 | (state: Partial) => void,
8 | ] {
9 | const [currentState, setCurrentState] = useState(
10 | StorageHelper.getNavigationPanelState(),
11 | );
12 |
13 | const onChange = (state: Partial) => {
14 | setCurrentState(StorageHelper.setNavigationPanelState(state));
15 | };
16 |
17 | return [currentState, onChange];
18 | }
19 |
--------------------------------------------------------------------------------
/full-stack-chat-ui-cognito-auth/user-interface/src/common/hooks/use-on-follow.ts:
--------------------------------------------------------------------------------
1 | import { useCallback } from "react";
2 | import { useNavigate } from "react-router";
3 |
4 | interface FollowDetail {
5 | external?: boolean;
6 | href?: string;
7 | }
8 |
9 | export function useOnFollow() {
10 | const navigate = useNavigate();
11 |
12 | return useCallback(
13 | (event: CustomEvent): void => {
14 | if (
15 | event.detail.external === true ||
16 | typeof event.detail.href === "undefined"
17 | ) {
18 | return;
19 | }
20 |
21 | event.preventDefault();
22 | navigate(event.detail.href);
23 | },
24 | [navigate],
25 | );
26 | }
27 |
--------------------------------------------------------------------------------
/full-stack-chat-ui-cognito-auth/user-interface/src/common/types.ts:
--------------------------------------------------------------------------------
1 | export interface NavigationPanelState {
2 | collapsed?: boolean;
3 | collapsedSections?: Record;
4 | }
5 |
--------------------------------------------------------------------------------
/full-stack-chat-ui-cognito-auth/user-interface/src/components/base-app-layout.tsx:
--------------------------------------------------------------------------------
1 | import { AppLayout, AppLayoutProps } from "@cloudscape-design/components";
2 | import { useNavigationPanelState } from "../common/hooks/use-navigation-panel-state";
3 | import NavigationPanel from "./navigation-panel";
4 |
5 | export default function BaseAppLayout(props: AppLayoutProps) {
6 | const [navigationPanelState, setNavigationPanelState] =
7 | useNavigationPanelState();
8 |
9 | return (
10 | }
13 | navigationOpen={!navigationPanelState.collapsed}
14 | onNavigationChange={({ detail }) =>
15 | setNavigationPanelState({ collapsed: !detail.open })
16 | }
17 | toolsHide={true}
18 | {...props}
19 | />
20 | );
21 | }
22 |
--------------------------------------------------------------------------------
/full-stack-chat-ui-cognito-auth/user-interface/src/components/chat-ui/Avatar.tsx:
--------------------------------------------------------------------------------
1 | import { Popover } from "@cloudscape-design/components";
2 | import styles from "../../styles/chat-ui.module.scss";
3 | import { ReactElement } from "react";
4 |
5 | export function Avatar(props: {
6 | readonly name?: string;
7 | readonly content?: ReactElement;
8 | readonly role: "ai" | "human";
9 | readonly waiting?: boolean;
10 | }) {
11 | return (
12 |
28 | {props.waiting ? (
29 |
30 |
31 |
32 |
33 |
34 | ) : (
35 | <>
36 |
47 | {props.content ? (
48 |
56 | {props.content}
57 |
58 | ) : (
59 |
65 | {(props.name ?? "A")[0].toUpperCase()}
66 |
67 | )}
68 |
69 | >
70 | )}
71 |
72 | );
73 | }
74 |
--------------------------------------------------------------------------------
/full-stack-chat-ui-cognito-auth/user-interface/src/components/chat-ui/CopyButton.tsx:
--------------------------------------------------------------------------------
1 | import {
2 | Button,
3 | Popover,
4 | StatusIndicator,
5 | } from "@cloudscape-design/components";
6 |
7 | export function CopyWithPopoverButton(props: {
8 | readonly text?: string;
9 | readonly onCopy: () => void;
10 | readonly disabled?: boolean;
11 | }) {
12 | return (
13 |
20 | {props.text ?? "Copied to clipboard"}
21 |
22 | }
23 | >
24 |
30 |
31 | );
32 | }
33 |
--------------------------------------------------------------------------------
/full-stack-chat-ui-cognito-auth/user-interface/src/components/chat-ui/chat-ui-message.tsx:
--------------------------------------------------------------------------------
1 | import remarkGfm from "remark-gfm";
2 | import ReactMarkdown from "react-markdown";
3 | import { ChatMessage, ChatMessageType } from "./types";
4 | import styles from "../../styles/chat-ui.module.scss";
5 | import { BaseChatMessage } from "./BaseChatMessage";
6 | import React, { ReactElement } from "react";
7 |
8 | export interface ChatUIMessageProps {
9 | readonly message: ChatMessage;
10 | readonly renderExpandableContent?:(message:ChatMessage) => ReactElement | undefined;
11 | readonly onSendFeedback?: (feedback: any, message: ChatMessage) => void;
12 |
13 | }
14 |
15 |
16 | export default function ChatUIMessage(props: ChatUIMessageProps) {
17 | return (
18 | {
21 | navigator.clipboard.writeText(props.message.content);
22 | }}
23 | onFeedback={
24 | Object.keys(props.message.content).length > 0
25 | ? (feedback) => {
26 | props.onSendFeedback?.(feedback, props.message, )
27 | }
28 | : undefined
29 | }
30 | expandableContent={props.renderExpandableContent?.(props.message)}
31 | waiting={props.message.content.length === 0}
32 | name={props.message?.type === ChatMessageType.AI ? "Ai" : "User"}
33 | >
34 |
35 |
43 | {children}
44 |
45 | );
46 | },
47 | table(props) {
48 | const { children, ...rest } = props;
49 | return (
50 |
53 | );
54 | },
55 | th(props) {
56 | const { children, ...rest } = props;
57 | return (
58 |
59 | {children}
60 | |
61 | );
62 | },
63 | td(props) {
64 | const { children, ...rest } = props;
65 | return (
66 |
67 | {children}
68 | |
69 | );
70 | },
71 | }}
72 | >
73 | {props.message.content.trim()}
74 |
75 |
76 |
77 |
78 | );
79 | }
80 |
--------------------------------------------------------------------------------
/full-stack-chat-ui-cognito-auth/user-interface/src/components/chat-ui/chat-ui.tsx:
--------------------------------------------------------------------------------
1 | import { SpaceBetween, StatusIndicator } from "@cloudscape-design/components";
2 | import { ChatMessage } from "./types";
3 | import ChatUIInputPanel from "./chat-ui-input-panel";
4 | import ChatUIMessage from "./chat-ui-message";
5 | import styles from "../../styles/chat-ui.module.scss";
6 | import { ReactElement, useEffect } from "react";
7 |
8 | export interface ChatUIProps {
9 | loading?: boolean;
10 | running?: boolean;
11 | messages?: ChatMessage[];
12 | welcomeText?: string;
13 | inputPlaceholderText?: string;
14 | sendButtonText?: string;
15 | renderExpandableContent?:(message:ChatMessage) => ReactElement | undefined;
16 | onSendMessage?: (message: string) => void;
17 | onSendFeedback?: (feedback: string, message: ChatMessage) => void;
18 | }
19 |
20 | export abstract class ChatScrollState {
21 | static userHasScrolled = false;
22 | static skipNextScrollEvent = false;
23 | static skipNextHistoryUpdate = false;
24 | }
25 |
26 | export function ChatUI(props: ChatUIProps) {
27 | const messages = props.messages || [];
28 |
29 | useEffect(() => {
30 | const onWindowScroll = () => {
31 | if (ChatScrollState.skipNextScrollEvent) {
32 | ChatScrollState.skipNextScrollEvent = false;
33 | return;
34 | }
35 |
36 | const isScrollToTheEnd =
37 | Math.abs(
38 | window.innerHeight +
39 | window.scrollY -
40 | document.documentElement.scrollHeight
41 | ) <= 10;
42 |
43 | if (!isScrollToTheEnd) {
44 | ChatScrollState.userHasScrolled = true;
45 | } else {
46 | ChatScrollState.userHasScrolled = false;
47 | }
48 | };
49 |
50 | window.addEventListener("scroll", onWindowScroll);
51 |
52 | return () => {
53 | window.removeEventListener("scroll", onWindowScroll);
54 | };
55 | }, []);
56 |
57 | return (
58 |
59 |
60 | {messages.map((message, idx) => {
61 | return (
62 |
68 | );
69 | })}
70 |
71 |
72 | {messages.length == 0 && !props.loading && (
73 |
{props.welcomeText ?? "Chat Bot demo app"}
74 | )}
75 | {props.loading && (
76 |
77 | Loading
78 |
79 | )}
80 |
81 |
82 |
83 |
84 |
85 | );
86 | }
87 |
--------------------------------------------------------------------------------
/full-stack-chat-ui-cognito-auth/user-interface/src/components/chat-ui/types.tsx:
--------------------------------------------------------------------------------
1 | export enum ChatMessageType {
2 | AI = "ai",
3 | Human = "human",
4 | }
5 |
6 | export interface ChatMessage {
7 | type: ChatMessageType;
8 | content: string;
9 | metadata?: any;
10 | }
11 |
--------------------------------------------------------------------------------
/full-stack-chat-ui-cognito-auth/user-interface/src/components/global-header.tsx:
--------------------------------------------------------------------------------
1 | import { useEffect, useState } from "react";
2 | import { signOut, fetchAuthSession } from "aws-amplify/auth";
3 | import {
4 | ButtonDropdownProps,
5 | TopNavigation,
6 | } from "@cloudscape-design/components";
7 | import { Mode } from "@cloudscape-design/global-styles";
8 | import { StorageHelper } from "../common/helpers/storage-helper";
9 | import { APP_NAME } from "../common/constants";
10 | import { useOnFollow } from "../common/hooks/use-on-follow";
11 |
12 | export default function GlobalHeader() {
13 | const onFollow = useOnFollow();
14 | const [userName, setUserName] = useState(null);
15 | const [theme, setTheme] = useState(StorageHelper.getTheme());
16 |
17 | useEffect(() => {
18 | (async () => {
19 | const session = await fetchAuthSession();
20 |
21 | if (!session) {
22 | signOut();
23 | return;
24 | }
25 |
26 | setUserName(session.tokens?.idToken?.payload?.email?.toString() ?? "");
27 | })();
28 | }, []);
29 |
30 | const onChangeThemeClick = () => {
31 | if (theme === Mode.Dark) {
32 | setTheme(StorageHelper.applyTheme(Mode.Light));
33 | } else {
34 | setTheme(StorageHelper.applyTheme(Mode.Dark));
35 | }
36 | };
37 |
38 | const onUserProfileClick = ({
39 | detail,
40 | }: {
41 | detail: ButtonDropdownProps.ItemClickDetails;
42 | }) => {
43 | if (detail.id === "signout") {
44 | signOut();
45 | }
46 | };
47 |
48 | return (
49 |
53 |
79 |
80 | );
81 | }
82 |
--------------------------------------------------------------------------------
/full-stack-chat-ui-cognito-auth/user-interface/src/components/navigation-panel.tsx:
--------------------------------------------------------------------------------
1 | import {
2 | SideNavigation,
3 | SideNavigationProps,
4 | } from "@cloudscape-design/components";
5 | import { useNavigationPanelState } from "../common/hooks/use-navigation-panel-state";
6 | import { useState } from "react";
7 | import { useOnFollow } from "../common/hooks/use-on-follow";
8 | import { APP_NAME } from "../common/constants";
9 | import { useLocation } from "react-router-dom";
10 |
11 | export default function NavigationPanel() {
12 | const location = useLocation();
13 | const onFollow = useOnFollow();
14 | const [navigationPanelState, setNavigationPanelState] =
15 | useNavigationPanelState();
16 |
17 | const [items] = useState(() => {
18 | const items: SideNavigationProps.Item[] = [
19 | {
20 | type: "link",
21 | text: "Chat",
22 | href: "/",
23 | },
24 | ];
25 |
26 | items.push(
27 | { type: "divider" },
28 | {
29 | type: "link",
30 | text: "Documentation",
31 | href: "https://github.com/aws-samples/cloudscape-examples",
32 | external: true,
33 | }
34 | );
35 |
36 | return items;
37 | });
38 |
39 | const onChange = ({
40 | detail,
41 | }: {
42 | detail: SideNavigationProps.ChangeDetail;
43 | }) => {
44 | const sectionIndex = items.indexOf(detail.item);
45 | setNavigationPanelState({
46 | collapsedSections: {
47 | ...navigationPanelState.collapsedSections,
48 | [sectionIndex]: !detail.expanded,
49 | },
50 | });
51 | };
52 |
53 | return (
54 | {
60 | if (value.type === "section") {
61 | const collapsed =
62 | navigationPanelState.collapsedSections?.[idx] === true;
63 | value.defaultExpanded = !collapsed;
64 | }
65 |
66 | return value;
67 | })}
68 | />
69 | );
70 | }
71 |
--------------------------------------------------------------------------------
/full-stack-chat-ui-cognito-auth/user-interface/src/components/wrappers/router-button-dropdown.tsx:
--------------------------------------------------------------------------------
1 | import {
2 | ButtonDropdownProps,
3 | ButtonDropdown,
4 | } from "@cloudscape-design/components";
5 | import { useOnFollow } from "../../common/hooks/use-on-follow";
6 |
7 | export default function RouterButtonDropdown(props: ButtonDropdownProps) {
8 | const onFollow = useOnFollow();
9 |
10 | return ;
11 | }
12 |
--------------------------------------------------------------------------------
/full-stack-chat-ui-cognito-auth/user-interface/src/components/wrappers/router-button.tsx:
--------------------------------------------------------------------------------
1 | import { ButtonProps, Button } from "@cloudscape-design/components";
2 | import { useOnFollow } from "../../common/hooks/use-on-follow";
3 |
4 | export default function RouterButton(props: ButtonProps) {
5 | const onFollow = useOnFollow();
6 |
7 | return ;
8 | }
9 |
--------------------------------------------------------------------------------
/full-stack-chat-ui-cognito-auth/user-interface/src/components/wrappers/router-link.tsx:
--------------------------------------------------------------------------------
1 | import { Link, LinkProps } from "@cloudscape-design/components";
2 | import { useOnFollow } from "../../common/hooks/use-on-follow";
3 |
4 | export default function RouterLink(props: LinkProps) {
5 | const onFollow = useOnFollow();
6 |
7 | return ;
8 | }
9 |
--------------------------------------------------------------------------------
/full-stack-chat-ui-cognito-auth/user-interface/src/main.tsx:
--------------------------------------------------------------------------------
1 | import React from "react";
2 | import ReactDOM from "react-dom/client";
3 | import AppConfigured from "./components/app-configured";
4 | import { StorageHelper } from "./common/helpers/storage-helper";
5 | import "@cloudscape-design/global-styles/index.css";
6 |
7 | const root = ReactDOM.createRoot(
8 | document.getElementById("root") as HTMLElement,
9 | );
10 |
11 | const theme = StorageHelper.getTheme();
12 | StorageHelper.applyTheme(theme);
13 |
14 | root.render(
15 |
16 |
17 | ,
18 | );
19 |
--------------------------------------------------------------------------------
/full-stack-chat-ui-cognito-auth/user-interface/src/pages/chat-page.tsx:
--------------------------------------------------------------------------------
1 | import React, { useState } from "react";
2 | import BaseAppLayout from "../components/base-app-layout";
3 | import { ChatUI } from "../components/chat-ui/chat-ui";
4 | import { ChatMessage, ChatMessageType } from "../components/chat-ui/types";
5 | import { Badge, SpaceBetween } from "@cloudscape-design/components";
6 | import { ApiClient } from "../common/api-client/api-client";
7 |
8 | export default function ChatPage() {
9 | const [running, setRunning] = useState(false);
10 | const [messages, setMessages] = useState([]);
11 |
12 |
13 |
14 | const renderExpandableContent = (message:ChatMessage) => {
15 | return (
16 | message.type === ChatMessageType.AI ?
17 |
18 |
19 |
20 | latency: {message.metadata?.latencyMs}ms
21 |
22 |
23 | :
24 | undefined
25 | )
26 | }
27 | const sendMessage = async (message: string) => {
28 | setRunning(true);
29 | setMessages((prevMessages) => [
30 | ...prevMessages,
31 | { type: ChatMessageType.Human, content: message },
32 | { type: ChatMessageType.AI, content: ""}
33 | ])
34 |
35 | const apiClient = new ApiClient();
36 |
37 | const startTime = performance.now();
38 | const result = await apiClient.chatClient.chat(message);
39 | const endTime = performance.now();
40 |
41 | const elapsedTime = endTime - startTime;
42 |
43 | setMessages((prevMessages) => [
44 | ...prevMessages.slice(0, prevMessages.length - 1), // Copy all but the last item
45 | {
46 | type: ChatMessageType.AI,
47 | content: result.response.message,
48 | metadata:{latencyMs: elapsedTime}
49 | },
50 | ]);
51 | setRunning(false);
52 | };
53 |
54 | const onSendFeedback = (feedback: any, message: ChatMessage) => {
55 | console.log(feedback, message);
56 | }
57 |
58 | return (
59 |
68 | }
69 | />
70 | );
71 | }
72 |
--------------------------------------------------------------------------------
/full-stack-chat-ui-cognito-auth/user-interface/src/pages/not-found.tsx:
--------------------------------------------------------------------------------
1 | import {
2 | Alert,
3 | BreadcrumbGroup,
4 | Container,
5 | ContentLayout,
6 | Header,
7 | SpaceBetween,
8 | } from "@cloudscape-design/components";
9 | import { useOnFollow } from "../common/hooks/use-on-follow";
10 | import { APP_NAME } from "../common/constants";
11 | import BaseAppLayout from "../components/base-app-layout";
12 |
13 | export default function NotFound() {
14 | const onFollow = useOnFollow();
15 |
16 | return (
17 |
34 | }
35 | content={
36 | 404. Page Not Found}
38 | >
39 |
40 |
41 |
42 | The page you are looking for does not exist.
43 |
44 |
45 |
46 |
47 | }
48 | />
49 | );
50 | }
51 |
--------------------------------------------------------------------------------
/full-stack-chat-ui-cognito-auth/user-interface/src/styles/app.scss:
--------------------------------------------------------------------------------
1 | * {
2 | box-sizing: border-box;
3 | }
4 |
5 | :root {
6 | --app-color-scheme: light;
7 | color-scheme: var(--app-color-scheme);
8 | }
9 |
10 | html,
11 | body,
12 | #root,
13 | div[data-amplify-authenticator],
14 | div[data-amplify-theme] {
15 | height: 100%;
16 | }
17 |
18 | body {
19 | background-color: #ffffff;
20 | overflow-y: scroll;
21 | }
22 |
23 | body.awsui-dark-mode {
24 | background-color: #0e1b2a;
25 | }
26 |
--------------------------------------------------------------------------------
/full-stack-chat-ui-cognito-auth/user-interface/src/styles/chat-ui.module.scss:
--------------------------------------------------------------------------------
1 | @use "@cloudscape-design/design-tokens/index" as awsui;
2 |
3 | .chat_container {
4 | margin-bottom: -40px;
5 | min-height: calc(100vh - 96px);
6 | display: flex;
7 | flex-direction: column;
8 | justify-content: space-between;
9 | }
10 |
11 | @media (min-width: 466px) {
12 | .chat_container {
13 | min-height: calc(100vh - 104px);
14 | }
15 | }
16 |
17 | @media (min-width: 689px) {
18 | .chat_container {
19 | min-height: calc(100vh - 60px);
20 | }
21 | }
22 |
23 | @media (min-width: 913px) {
24 | .chat_container {
25 | min-height: calc(100vh - 68px);
26 | }
27 | }
28 |
29 | .welcome_text {
30 | color: awsui.$color-text-body-default;
31 | font-size: 3rem;
32 | font-weight: bolder;
33 | opacity: 0.4;
34 | }
35 |
36 | .input_container {
37 | position: sticky;
38 | bottom: 0;
39 | padding-bottom: awsui.$space-scaled-l;
40 | padding-top: awsui.$space-scaled-xxl;
41 | background: linear-gradient(
42 | to bottom,
43 | transparent 0%,
44 | awsui.$color-background-container-content 20%
45 | );
46 | margin-left: -8px;
47 | margin-right: -8px;
48 | container-type: inline-size;
49 | container-name: input_container;
50 | }
51 |
52 | .input_textarea_container {
53 | display: grid;
54 | grid-template-columns: 1fr auto;
55 | align-items: center;
56 | gap: 4px;
57 | }
58 |
59 | .input_textarea {
60 | resize: none;
61 | border: none;
62 | padding: 12px 12px 12px 4px;
63 | background-color: transparent;
64 | outline: none;
65 | width: 100%;
66 | height: 100%;
67 | font-size: 1rem;
68 | }
69 |
70 | .btn_chabot_message_copy {
71 | float: right;
72 | }
73 |
74 | .markdown {
75 | font-size: 1em;
76 | }
77 |
78 | .markdown p {
79 | margin: 0px;
80 | }
81 |
82 | .wave {
83 | position: relative;
84 | width: 29px;
85 | height: 29px;
86 | top: 50%;
87 | left: 50%;
88 | transform: translate(-50%, -50%);
89 | }
90 | .wave .dot {
91 | display: inline-block;
92 | width: 6px;
93 | height: 6px;
94 | border-radius: 50%;
95 | margin-right: 3px;
96 | background: #fff;
97 | animation: wave 1.3s linear infinite;
98 | }
99 | .wave .dot:nth-child(2) {
100 | animation-delay: -1.1s;
101 | }
102 | .wave .dot:nth-child(3) {
103 | animation-delay: -0.9s;
104 | }
105 |
106 | @keyframes wave {
107 | 0%,
108 | 60%,
109 | 100% {
110 | transform: initial;
111 | }
112 | 30% {
113 | transform: translateY(-10px);
114 | }
115 | }
116 |
--------------------------------------------------------------------------------
/full-stack-chat-ui-cognito-auth/user-interface/src/vite-env.d.ts:
--------------------------------------------------------------------------------
1 | ///
2 |
--------------------------------------------------------------------------------
/full-stack-chat-ui-cognito-auth/user-interface/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | "target": "ES2020",
4 | "useDefineForClassFields": true,
5 | "lib": ["ES2020", "DOM", "DOM.Iterable"],
6 | "module": "ESNext",
7 | "skipLibCheck": true,
8 |
9 | /* Bundler mode */
10 | "moduleResolution": "bundler",
11 | "allowImportingTsExtensions": true,
12 | "resolveJsonModule": true,
13 | "isolatedModules": true,
14 | "noEmit": true,
15 | "jsx": "react-jsx",
16 |
17 | /* Linting */
18 | "strict": true,
19 | "noUnusedLocals": true,
20 | "noUnusedParameters": true,
21 | "noFallthroughCasesInSwitch": true
22 | },
23 | "include": ["src"],
24 | "references": [{ "path": "./tsconfig.node.json" }]
25 | }
26 |
--------------------------------------------------------------------------------
/full-stack-chat-ui-cognito-auth/user-interface/tsconfig.node.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | "composite": true,
4 | "skipLibCheck": true,
5 | "module": "ESNext",
6 | "moduleResolution": "bundler",
7 | "allowSyntheticDefaultImports": true,
8 | "strict": true
9 | },
10 | "include": ["vite.config.ts"]
11 | }
12 |
--------------------------------------------------------------------------------
/full-stack-chat-ui-cognito-auth/user-interface/vite.config.ts:
--------------------------------------------------------------------------------
1 | import { defineConfig } from "vite";
2 | import react from "@vitejs/plugin-react";
3 |
4 | // https://vitejs.dev/config/
5 | export default defineConfig({
6 | plugins: [react()],
7 | server: {
8 | port: 3000,
9 | },
10 | });
11 |
--------------------------------------------------------------------------------
/fullstack-vite-cdk-cognito-auth/.eslintrc.cjs:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | root: true,
3 | env: { browser: true, es2020: true },
4 | extends: [
5 | 'eslint:recommended',
6 | 'plugin:@typescript-eslint/recommended',
7 | 'plugin:react-hooks/recommended',
8 | ],
9 | ignorePatterns: ['dist', '.eslintrc.cjs'],
10 | parser: '@typescript-eslint/parser',
11 | plugins: ['react-refresh'],
12 | rules: {
13 | 'react-refresh/only-export-components': ['warn', { allowConstantExport: true }],
14 | },
15 | };
16 |
--------------------------------------------------------------------------------
/fullstack-vite-cdk-cognito-auth/.npmignore:
--------------------------------------------------------------------------------
1 | *.ts
2 | !*.d.ts
3 |
4 | # CDK asset staging directory
5 | .cdk.staging
6 | cdk.out
7 |
--------------------------------------------------------------------------------
/fullstack-vite-cdk-cognito-auth/bin/index.ts:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env node
2 | import "source-map-support/register";
3 | import * as cdk from "aws-cdk-lib";
4 | import { InfrastructureStack } from "../lib/infrastructure-stack";
5 |
6 | const app = new cdk.App();
7 | new InfrastructureStack(app, "InfrastructureStack", {
8 | /* If you don't specify 'env', this stack will be environment-agnostic.
9 | * Account/Region-dependent features and context lookups will not work,
10 | * but a single synthesized template can be deployed anywhere. */
11 | /* Uncomment the next line to specialize this stack for the AWS Account
12 | * and Region that are implied by the current CLI configuration. */
13 | // env: { account: process.env.CDK_DEFAULT_ACCOUNT, region: process.env.CDK_DEFAULT_REGION },
14 | /* Uncomment the next line if you know exactly what Account and Region you
15 | * want to deploy the stack to. */
16 | // env: { account: '123456789012', region: 'us-east-1' },
17 | /* For more information, see https://docs.aws.amazon.com/cdk/latest/guide/environments.html */
18 | });
19 |
--------------------------------------------------------------------------------
/fullstack-vite-cdk-cognito-auth/cdk.json:
--------------------------------------------------------------------------------
1 | {
2 | "app": "npx ts-node --prefer-ts-exts bin/index.ts",
3 | "watch": {
4 | "include": ["**"],
5 | "exclude": [
6 | "README.md",
7 | "cdk*.json",
8 | "**/*.d.ts",
9 | "**/*.js",
10 | "tsconfig.json",
11 | "package*.json",
12 | "yarn.lock",
13 | "node_modules",
14 | "test"
15 | ]
16 | },
17 | "context": {
18 | "@aws-cdk/aws-lambda:recognizeLayerVersion": true,
19 | "@aws-cdk/core:checkSecretUsage": true,
20 | "@aws-cdk/core:target-partitions": ["aws", "aws-cn"],
21 | "@aws-cdk-containers/ecs-service-extensions:enableDefaultLogDriver": true,
22 | "@aws-cdk/aws-ec2:uniqueImdsv2TemplateName": true,
23 | "@aws-cdk/aws-ecs:arnFormatIncludesClusterName": true,
24 | "@aws-cdk/aws-iam:minimizePolicies": true,
25 | "@aws-cdk/core:validateSnapshotRemovalPolicy": true,
26 | "@aws-cdk/aws-codepipeline:crossAccountKeyAliasStackSafeResourceName": true,
27 | "@aws-cdk/aws-s3:createDefaultLoggingPolicy": true,
28 | "@aws-cdk/aws-sns-subscriptions:restrictSqsDescryption": true,
29 | "@aws-cdk/aws-apigateway:disableCloudWatchRole": true,
30 | "@aws-cdk/core:enablePartitionLiterals": true,
31 | "@aws-cdk/aws-events:eventsTargetQueueSameAccount": true,
32 | "@aws-cdk/aws-iam:standardizedServicePrincipals": true,
33 | "@aws-cdk/aws-ecs:disableExplicitDeploymentControllerForCircuitBreaker": true,
34 | "@aws-cdk/aws-iam:importedRoleStackSafeDefaultPolicyName": true,
35 | "@aws-cdk/aws-s3:serverAccessLogsUseBucketPolicy": true,
36 | "@aws-cdk/aws-route53-patters:useCertificate": true,
37 | "@aws-cdk/customresources:installLatestAwsSdkDefault": false,
38 | "@aws-cdk/aws-rds:databaseProxyUniqueResourceName": true,
39 | "@aws-cdk/aws-codedeploy:removeAlarmsFromDeploymentGroup": true,
40 | "@aws-cdk/aws-apigateway:authorizerChangeDeploymentLogicalId": true,
41 | "@aws-cdk/aws-ec2:launchTemplateDefaultUserData": true,
42 | "@aws-cdk/aws-secretsmanager:useAttachedSecretResourcePolicyForSecretTargetAttachments": true,
43 | "@aws-cdk/aws-redshift:columnId": true,
44 | "@aws-cdk/aws-stepfunctions-tasks:enableEmrServicePolicyV2": true,
45 | "@aws-cdk/aws-ec2:restrictDefaultSecurityGroup": true,
46 | "@aws-cdk/aws-apigateway:requestValidatorUniqueId": true,
47 | "@aws-cdk/aws-kms:aliasNameRef": true,
48 | "@aws-cdk/aws-autoscaling:generateLaunchTemplateInsteadOfLaunchConfig": true,
49 | "@aws-cdk/core:includePrefixInUniqueNameGeneration": true,
50 | "@aws-cdk/aws-efs:denyAnonymousAccess": true,
51 | "@aws-cdk/aws-opensearchservice:enableOpensearchMultiAzWithStandby": true,
52 | "@aws-cdk/aws-lambda-nodejs:useLatestRuntimeVersion": true,
53 | "@aws-cdk/aws-efs:mountTargetOrderInsensitiveLogicalId": true,
54 | "@aws-cdk/aws-rds:auroraClusterChangeScopeOfInstanceParameterGroupWithEachParameters": true,
55 | "@aws-cdk/aws-appsync:useArnForSourceApiAssociationIdentifier": true,
56 | "@aws-cdk/aws-rds:preventRenderingDeprecatedCredentials": true,
57 | "@aws-cdk/aws-codepipeline-actions:useNewDefaultBranchForCodeCommitSource": true,
58 | "@aws-cdk/aws-cloudwatch-actions:changeLambdaPermissionLogicalIdForLambdaAction": true
59 | }
60 | }
61 |
--------------------------------------------------------------------------------
/fullstack-vite-cdk-cognito-auth/functions/api-handler/index.py:
--------------------------------------------------------------------------------
1 | import os
2 | import json
3 | from pydantic import ValidationError
4 | from botocore.exceptions import ClientError
5 | from aws_lambda_powertools.utilities import parameters
6 | from aws_lambda_powertools import Logger, Tracer
7 | from aws_lambda_powertools.logging import correlation_paths
8 | from aws_lambda_powertools.utilities.typing import LambdaContext
9 | from aws_lambda_powertools.event_handler.api_gateway import Response
10 | from aws_lambda_powertools.event_handler import (
11 | APIGatewayRestResolver,
12 | CORSConfig,
13 | content_types,
14 | )
15 | from utils import CustomEncoder
16 | from routes.health import router as health_router
17 | from routes.items import router as items_router
18 |
19 | tracer = Tracer()
20 | logger = Logger()
21 |
22 | X_ORIGIN_VERIFY_SECRET_ARN = os.environ.get("X_ORIGIN_VERIFY_SECRET_ARN")
23 |
24 | cors_config = CORSConfig(allow_origin="*", max_age=300)
25 | app = APIGatewayRestResolver(
26 | cors=cors_config,
27 | strip_prefixes=["/v1"],
28 | serializer=lambda obj: json.dumps(obj, cls=CustomEncoder),
29 | )
30 |
31 | app.include_router(health_router)
32 | app.include_router(items_router)
33 |
34 |
35 | @app.exception_handler(ClientError)
36 | def handle_value_error(e: ClientError):
37 | logger.exception(e)
38 |
39 | return Response(
40 | status_code=200,
41 | content_type=content_types.APPLICATION_JSON,
42 | body=json.dumps(
43 | {"error": True, "message": str(e)},
44 | cls=CustomEncoder,
45 | ),
46 | )
47 |
48 |
49 | @app.exception_handler(ValidationError)
50 | def handle_value_error(e: ValidationError):
51 | logger.exception(e)
52 |
53 | return Response(
54 | status_code=200,
55 | content_type=content_types.APPLICATION_JSON,
56 | body=json.dumps(
57 | {"error": True, "message": [str(error) for error in e.errors()]},
58 | cls=CustomEncoder,
59 | ),
60 | )
61 |
62 |
63 | def get_origin_verify_header_value():
64 | origin_verify_header_value = parameters.get_secret(
65 | X_ORIGIN_VERIFY_SECRET_ARN, transform="json", max_age=60
66 | )["headerValue"]
67 |
68 | return origin_verify_header_value
69 |
70 |
71 | @logger.inject_lambda_context(
72 | log_event=True, correlation_id_path=correlation_paths.API_GATEWAY_REST
73 | )
74 | @tracer.capture_lambda_handler
75 | def handler(event: dict, context: LambdaContext) -> dict:
76 | origin_verify_header_value = get_origin_verify_header_value()
77 | if event["headers"]["X-Origin-Verify"] == origin_verify_header_value:
78 | return app.resolve(event, context)
79 |
80 | return {"statusCode": 403, "body": "Forbidden"}
81 |
--------------------------------------------------------------------------------
/fullstack-vite-cdk-cognito-auth/functions/api-handler/requirements.txt:
--------------------------------------------------------------------------------
1 | pydantic==2.6.1
--------------------------------------------------------------------------------
/fullstack-vite-cdk-cognito-auth/functions/api-handler/routes/health.py:
--------------------------------------------------------------------------------
1 | from aws_lambda_powertools import Logger, Tracer
2 | from aws_lambda_powertools.event_handler.api_gateway import Router
3 |
4 | tracer = Tracer()
5 | router = Router()
6 | logger = Logger()
7 |
8 |
9 | @router.get("/health")
10 | @tracer.capture_method
11 | def health():
12 | return {"ok": True}
13 |
--------------------------------------------------------------------------------
/fullstack-vite-cdk-cognito-auth/functions/api-handler/routes/items.py:
--------------------------------------------------------------------------------
1 | import os
2 | import uuid
3 | import boto3
4 | from datetime import datetime
5 | from pydantic import BaseModel
6 | from aws_lambda_powertools import Logger, Tracer
7 | from aws_lambda_powertools.event_handler.api_gateway import Router
8 |
9 | tracer = Tracer()
10 | router = Router()
11 | logger = Logger()
12 |
13 | dynamodb = boto3.resource("dynamodb")
14 | ITEMS_TABLE_NAME = os.environ.get("ITEMS_TABLE_NAME")
15 |
16 |
17 | class CreateItemRequest(BaseModel):
18 | name: str
19 | type: str
20 | status: str
21 | details: int
22 |
23 |
24 | @router.get("/items")
25 | @tracer.capture_method
26 | def items():
27 | table = dynamodb.Table(ITEMS_TABLE_NAME)
28 | response = table.scan()
29 | items = response['Items']
30 |
31 | while 'LastEvaluatedKey' in response:
32 | response = table.scan(ExclusiveStartKey=response['LastEvaluatedKey'])
33 | items.extend(response['Items'])
34 |
35 | return {"ok": True, "data": items}
36 |
37 |
38 | @router.get("/items/")
39 | @tracer.capture_method
40 | def get_item(item_id: str):
41 | table = dynamodb.Table(ITEMS_TABLE_NAME)
42 |
43 | response = table.get_item(
44 | Key={
45 | "itemId": item_id,
46 | }
47 | )
48 |
49 | item = response.get('Item', None)
50 |
51 | return {"ok": True, "data": item}
52 |
53 |
54 | @router.put("/items")
55 | @tracer.capture_method
56 | def create_item():
57 | data: dict = router.current_event.json_body
58 | generic_request = CreateItemRequest(**data)
59 |
60 | item_id = str(uuid.uuid4())
61 | timestamp = datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%S.%fZ")
62 | table = dynamodb.Table(ITEMS_TABLE_NAME)
63 |
64 | response = table.put_item(Item={
65 | "itemId": item_id,
66 | "name": generic_request.name,
67 | "type": generic_request.type,
68 | "status": generic_request.status,
69 | "details": generic_request.details,
70 | "created_at": timestamp,
71 | "updated_at": timestamp
72 | })
73 |
74 | logger.info(response)
75 |
76 | return {"ok": True}
77 |
78 |
79 | @router.delete("/items/")
80 | @tracer.capture_method
81 | def delete_item(item_id: str):
82 | table = dynamodb.Table(ITEMS_TABLE_NAME)
83 |
84 | response = table.delete_item(
85 | Key={
86 | "itemId": item_id
87 | }
88 | )
89 |
90 | logger.info(response)
91 |
92 | return {"ok": True}
93 |
--------------------------------------------------------------------------------
/fullstack-vite-cdk-cognito-auth/functions/api-handler/utils.py:
--------------------------------------------------------------------------------
1 | import json
2 | import uuid
3 | import decimal
4 |
5 |
6 | class CustomEncoder(json.JSONEncoder):
7 | def default(self, obj):
8 | if isinstance(obj, decimal.Decimal):
9 | if obj % 1 > 0:
10 | return float(obj)
11 | else:
12 | return int(obj)
13 |
14 | if isinstance(obj, uuid.UUID):
15 | return str(obj)
16 |
17 | return super(CustomEncoder, self).default(obj)
18 |
--------------------------------------------------------------------------------
/fullstack-vite-cdk-cognito-auth/jest.config.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | testEnvironment: 'node',
3 | roots: ['/test'],
4 | testMatch: ['**/*.test.ts'],
5 | transform: {
6 | '^.+\\.tsx?$': 'ts-jest'
7 | }
8 | };
9 |
--------------------------------------------------------------------------------
/fullstack-vite-cdk-cognito-auth/lib/utils.ts:
--------------------------------------------------------------------------------
1 | import * as fs from "node:fs";
2 | import * as path from "node:path";
3 |
4 | export abstract class Utils {
5 | static copyDirRecursive(sourceDir: string, targetDir: string): void {
6 | if (!fs.existsSync(targetDir)) {
7 | fs.mkdirSync(targetDir);
8 | }
9 |
10 | const files = fs.readdirSync(sourceDir);
11 |
12 | for (const file of files) {
13 | const sourceFilePath = path.join(sourceDir, file);
14 | const targetFilePath = path.join(targetDir, file);
15 | const stats = fs.statSync(sourceFilePath);
16 |
17 | if (stats.isDirectory()) {
18 | Utils.copyDirRecursive(sourceFilePath, targetFilePath);
19 | } else {
20 | fs.copyFileSync(sourceFilePath, targetFilePath);
21 | }
22 | }
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/fullstack-vite-cdk-cognito-auth/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "cloudscape-cdk-app",
3 | "version": "0.1.0",
4 | "bin": {
5 | "fullstack-vite-cdk-cognito-auth": "bin/index.js"
6 | },
7 | "scripts": {
8 | "build": "tsc",
9 | "watch": "tsc -w",
10 | "test": "jest",
11 | "cdk": "cdk",
12 | "format": "npx prettier --ignore-path .gitignore --write \"**/*.+(tsx|js|ts|json)\""
13 | },
14 | "devDependencies": {
15 | "@types/jest": "^29.5.11",
16 | "@types/node": "20.11.6",
17 | "aws-cdk": "2.137.0",
18 | "jest": "^29.7.0",
19 | "ts-jest": "^29.1.2",
20 | "ts-node": "^10.9.2",
21 | "typescript": "~5.3.3"
22 | },
23 | "dependencies": {
24 | "@aws-cdk/aws-apigatewayv2-alpha": "^2.114.1-alpha.0",
25 | "@aws-cdk/aws-cognito-identitypool-alpha": "^2.137.0-alpha.0",
26 | "@aws-cdk/aws-lambda-python-alpha": "^2.137.0-alpha.0",
27 | "@cloudscape-design/design-tokens": "^3.0.34",
28 | "aws-cdk-lib": "2.137.0",
29 | "constructs": "^10.0.0",
30 | "source-map-support": "^0.5.21"
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/fullstack-vite-cdk-cognito-auth/prettier.config.cjs:
--------------------------------------------------------------------------------
1 | // eslint-disable-next-line no-undef
2 | module.export = {
3 | semi: true,
4 | trailingComma: "es5",
5 | singleQuote: false,
6 | tabWidth: 2,
7 | useTabs: false,
8 | };
9 |
--------------------------------------------------------------------------------
/fullstack-vite-cdk-cognito-auth/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | "target": "ES2020",
4 | "module": "commonjs",
5 | "lib": [
6 | "es2020",
7 | "dom"
8 | ],
9 | "declaration": true,
10 | "strict": true,
11 | "noImplicitAny": true,
12 | "strictNullChecks": true,
13 | "noImplicitThis": true,
14 | "alwaysStrict": true,
15 | "noUnusedLocals": false,
16 | "noUnusedParameters": false,
17 | "noImplicitReturns": true,
18 | "noFallthroughCasesInSwitch": false,
19 | "inlineSourceMap": true,
20 | "inlineSources": true,
21 | "experimentalDecorators": true,
22 | "strictPropertyInitialization": false,
23 | "typeRoots": [
24 | "./node_modules/@types"
25 | ]
26 | },
27 | "exclude": [
28 | "node_modules",
29 | "cdk.out"
30 | ]
31 | }
32 |
--------------------------------------------------------------------------------
/fullstack-vite-cdk-cognito-auth/user-interface/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
12 |
17 |
18 |
19 | Example App
20 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
--------------------------------------------------------------------------------
/fullstack-vite-cdk-cognito-auth/user-interface/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "cloudscape-app",
3 | "private": true,
4 | "version": "0.0.0",
5 | "type": "module",
6 | "scripts": {
7 | "dev": "vite",
8 | "build": "tsc && vite build",
9 | "preview": "vite preview",
10 | "lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0",
11 | "format": "npx prettier --ignore-path .gitignore --write \"**/*.+(tsx|js|ts|json)\""
12 | },
13 | "dependencies": {
14 | "@aws-amplify/ui-react": "^6.1.3",
15 | "@cloudscape-design/components": "^3.0.611",
16 | "@cloudscape-design/design-tokens": "^3.0.35",
17 | "@cloudscape-design/global-styles": "^1.0.27",
18 | "aws-amplify": "^6.0.15",
19 | "react": "^18.2.0",
20 | "react-dom": "^18.2.0",
21 | "react-router-dom": "^6.22.0"
22 | },
23 | "devDependencies": {
24 | "@types/react": "^18.2.55",
25 | "@types/react-dom": "^18.2.19",
26 | "@typescript-eslint/eslint-plugin": "^6.21.0",
27 | "@typescript-eslint/parser": "^6.21.0",
28 | "@vitejs/plugin-react": "^4.3.2",
29 | "autoprefixer": "^10.4.17",
30 | "eslint": "^8.56.0",
31 | "eslint-plugin-react-hooks": "^4.6.0",
32 | "eslint-plugin-react-refresh": "^0.4.5",
33 | "postcss": "^8.4.35",
34 | "sass": "^1.70.0",
35 | "typescript": "^5.2.2",
36 | "vite": "^5.4.8"
37 | },
38 | "overrides": {
39 | "react-virtual": {
40 | "react": "^18.0.0"
41 | }
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/fullstack-vite-cdk-cognito-auth/user-interface/postcss.config.js:
--------------------------------------------------------------------------------
1 | export default {
2 | plugins: {
3 | autoprefixer: {},
4 | },
5 | };
6 |
--------------------------------------------------------------------------------
/fullstack-vite-cdk-cognito-auth/user-interface/prettier.config.cjs:
--------------------------------------------------------------------------------
1 | // eslint-disable-next-line no-undef
2 | module.export = {
3 | semi: true,
4 | trailingComma: "es5",
5 | singleQuote: false,
6 | tabWidth: 2,
7 | useTabs: false,
8 | };
9 |
--------------------------------------------------------------------------------
/fullstack-vite-cdk-cognito-auth/user-interface/public/aws-exports.template.json:
--------------------------------------------------------------------------------
1 | {
2 | "region": "eu-west-1",
3 | "Auth": {
4 | "Cognito": {
5 | "userPoolClientId": "0000000000000000000000000",
6 | "userPoolId": "eu-west-0_AAAAAAAAA",
7 | "identityPoolId": "eu-west-1:aaaaaaaa-aaaaaaaaa-aaaa-aaaaaaaaaaaa"
8 | }
9 | },
10 | "API": {
11 | "REST": {
12 | "RestApi": { "endpoint": "https://aaaaaaaaaaaaaa.cloudfront.net/api/v1" }
13 | }
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/fullstack-vite-cdk-cognito-auth/user-interface/public/favicon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/aws-samples/cloudscape-examples/35055cf8fb197302784028998a9d8c3c55acea78/fullstack-vite-cdk-cognito-auth/user-interface/public/favicon.ico
--------------------------------------------------------------------------------
/fullstack-vite-cdk-cognito-auth/user-interface/public/images/android-chrome-192x192.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/aws-samples/cloudscape-examples/35055cf8fb197302784028998a9d8c3c55acea78/fullstack-vite-cdk-cognito-auth/user-interface/public/images/android-chrome-192x192.png
--------------------------------------------------------------------------------
/fullstack-vite-cdk-cognito-auth/user-interface/public/images/android-chrome-512x512.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/aws-samples/cloudscape-examples/35055cf8fb197302784028998a9d8c3c55acea78/fullstack-vite-cdk-cognito-auth/user-interface/public/images/android-chrome-512x512.png
--------------------------------------------------------------------------------
/fullstack-vite-cdk-cognito-auth/user-interface/public/images/apple-touch-icon.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/aws-samples/cloudscape-examples/35055cf8fb197302784028998a9d8c3c55acea78/fullstack-vite-cdk-cognito-auth/user-interface/public/images/apple-touch-icon.png
--------------------------------------------------------------------------------
/fullstack-vite-cdk-cognito-auth/user-interface/public/images/favicon-16x16.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/aws-samples/cloudscape-examples/35055cf8fb197302784028998a9d8c3c55acea78/fullstack-vite-cdk-cognito-auth/user-interface/public/images/favicon-16x16.png
--------------------------------------------------------------------------------
/fullstack-vite-cdk-cognito-auth/user-interface/public/images/favicon-32x32.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/aws-samples/cloudscape-examples/35055cf8fb197302784028998a9d8c3c55acea78/fullstack-vite-cdk-cognito-auth/user-interface/public/images/favicon-32x32.png
--------------------------------------------------------------------------------
/fullstack-vite-cdk-cognito-auth/user-interface/public/images/favicon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/aws-samples/cloudscape-examples/35055cf8fb197302784028998a9d8c3c55acea78/fullstack-vite-cdk-cognito-auth/user-interface/public/images/favicon.ico
--------------------------------------------------------------------------------
/fullstack-vite-cdk-cognito-auth/user-interface/public/images/logo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/aws-samples/cloudscape-examples/35055cf8fb197302784028998a9d8c3c55acea78/fullstack-vite-cdk-cognito-auth/user-interface/public/images/logo.png
--------------------------------------------------------------------------------
/fullstack-vite-cdk-cognito-auth/user-interface/public/manifest.json:
--------------------------------------------------------------------------------
1 | {
2 | "id": "/",
3 | "start_url": "/",
4 | "name": "Example App",
5 | "short_name": "Example App",
6 | "description": "Example App sample",
7 | "theme_color": "#000000",
8 | "background_color": "#ffffff",
9 | "display": "standalone",
10 | "icons": [
11 | {
12 | "src": "/images/android-chrome-192x192.png",
13 | "sizes": "192x192",
14 | "type": "image/png"
15 | },
16 | {
17 | "src": "/images/android-chrome-512x512.png",
18 | "sizes": "512x512",
19 | "type": "image/png"
20 | }
21 | ]
22 | }
23 |
--------------------------------------------------------------------------------
/fullstack-vite-cdk-cognito-auth/user-interface/src/app.tsx:
--------------------------------------------------------------------------------
1 | import {
2 | HashRouter,
3 | BrowserRouter,
4 | Routes,
5 | Route,
6 | Outlet,
7 | } from "react-router-dom";
8 | import { USE_BROWSER_ROUTER } from "./common/constants";
9 | import GlobalHeader from "./components/global-header";
10 | import DashboardPage from "./pages/dashboard/dashboard-page";
11 | import ViewItemPage from "./pages/section1/view-item/view-item-page";
12 | import AllItemsPage from "./pages/section1/all-items/all-items-page";
13 | import AddItemPage from "./pages/section1/add-item/add-item-page";
14 | import NotFound from "./pages/not-found";
15 | import "./styles/app.scss";
16 |
17 | export default function App() {
18 | const Router = USE_BROWSER_ROUTER ? BrowserRouter : HashRouter;
19 |
20 | return (
21 |
22 |
23 |
24 |
25 |
26 |
27 | } />
28 | }>
29 | } />
30 | } />
31 | } />
32 |
33 | } />
34 |
35 |
36 |
37 |
38 | );
39 | }
40 |
--------------------------------------------------------------------------------
/fullstack-vite-cdk-cognito-auth/user-interface/src/common/api-client/api-client-base.ts:
--------------------------------------------------------------------------------
1 | import { fetchAuthSession } from "aws-amplify/auth";
2 |
3 | export abstract class ApiClientBase {
4 | protected async getHeaders() {
5 | return {
6 | Authorization: `Bearer ${await this.getIdToken()}`,
7 | };
8 | }
9 |
10 | protected async getIdToken() {
11 | const session = await fetchAuthSession();
12 | return session.tokens?.idToken?.toString();
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/fullstack-vite-cdk-cognito-auth/user-interface/src/common/api-client/api-client.ts:
--------------------------------------------------------------------------------
1 | import { ItemsApiClient } from "./items-api-client";
2 |
3 | export class ApiClient {
4 | private _itemsClient: ItemsApiClient | undefined;
5 |
6 | public get items() {
7 | if (!this._itemsClient) {
8 | this._itemsClient = new ItemsApiClient();
9 | }
10 |
11 | return this._itemsClient;
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/fullstack-vite-cdk-cognito-auth/user-interface/src/common/api-client/items-api-client.ts:
--------------------------------------------------------------------------------
1 | import { get, put, del } from "aws-amplify/api";
2 | import { Item } from "../types";
3 | import { API_NAME } from "../constants";
4 | import { ApiClientBase } from "./api-client-base";
5 |
6 | export class ItemsApiClient extends ApiClientBase {
7 | async getItems(): Promise- {
8 | const headers = await this.getHeaders();
9 | const restOperation = get({
10 | apiName: API_NAME,
11 | path: "/items",
12 | options: {
13 | headers,
14 | },
15 | });
16 |
17 | const response = await restOperation.response;
18 | const { data = [] } = (await response.body.json()) as any;
19 |
20 | return data;
21 | }
22 |
23 | async addItem(item: Omit
- ): Promise {
24 | const headers = await this.getHeaders();
25 | const restOperation = put({
26 | apiName: API_NAME,
27 | path: "/items",
28 | options: {
29 | headers,
30 | body: {
31 | ...item,
32 | },
33 | },
34 | });
35 |
36 | const response = await restOperation.response;
37 | const data = (await response.body.json()) as any;
38 |
39 | return data.ok;
40 | }
41 |
42 | async getItem(id: string): Promise
- {
43 | const headers = await this.getHeaders();
44 | const restOperation = get({
45 | apiName: API_NAME,
46 | path: `/items/${id}`,
47 | options: {
48 | headers,
49 | },
50 | });
51 |
52 | const response = await restOperation.response;
53 | const { data } = (await response.body.json()) as any;
54 |
55 | return data;
56 | }
57 |
58 | async deleteItem(id: string): Promise {
59 | const headers = await this.getHeaders();
60 | const restOperation = del({
61 | apiName: API_NAME,
62 | path: `/items/${id}`,
63 | options: {
64 | headers,
65 | },
66 | });
67 |
68 | await restOperation.response;
69 | }
70 | }
71 |
--------------------------------------------------------------------------------
/fullstack-vite-cdk-cognito-auth/user-interface/src/common/constants.ts:
--------------------------------------------------------------------------------
1 | export const APP_NAME = "Example App";
2 | export const USE_BROWSER_ROUTER = true;
3 | export const API_NAME = "RestApi";
4 |
--------------------------------------------------------------------------------
/fullstack-vite-cdk-cognito-auth/user-interface/src/common/helpers/storage-helper.ts:
--------------------------------------------------------------------------------
1 | import { Mode, applyMode } from "@cloudscape-design/global-styles";
2 | import { NavigationPanelState } from "../types";
3 |
4 | const PREFIX = "example-app";
5 | const THEME_STORAGE_NAME = `${PREFIX}-theme`;
6 | const NAVIGATION_PANEL_STATE_STORAGE_NAME = `${PREFIX}-navigation-panel-state`;
7 |
8 | export abstract class StorageHelper {
9 | static getTheme() {
10 | const value = localStorage.getItem(THEME_STORAGE_NAME) ?? Mode.Light;
11 | const theme = value === Mode.Dark ? Mode.Dark : Mode.Light;
12 |
13 | return theme;
14 | }
15 |
16 | static applyTheme(theme: Mode) {
17 | localStorage.setItem(THEME_STORAGE_NAME, theme);
18 | applyMode(theme);
19 |
20 | document.documentElement.style.setProperty(
21 | "--app-color-scheme",
22 | theme === Mode.Dark ? "dark" : "light"
23 | );
24 |
25 | return theme;
26 | }
27 |
28 | static getNavigationPanelState(): NavigationPanelState {
29 | const value =
30 | localStorage.getItem(NAVIGATION_PANEL_STATE_STORAGE_NAME) ??
31 | JSON.stringify({
32 | collapsed: true,
33 | });
34 |
35 | let state: NavigationPanelState | null = null;
36 | try {
37 | state = JSON.parse(value);
38 | } catch {
39 | state = {};
40 | }
41 |
42 | return state ?? {};
43 | }
44 |
45 | static setNavigationPanelState(state: Partial) {
46 | const currentState = this.getNavigationPanelState();
47 | const newState = { ...currentState, ...state };
48 | const stateStr = JSON.stringify(newState);
49 | localStorage.setItem(NAVIGATION_PANEL_STATE_STORAGE_NAME, stateStr);
50 |
51 | return newState;
52 | }
53 | }
54 |
--------------------------------------------------------------------------------
/fullstack-vite-cdk-cognito-auth/user-interface/src/common/helpers/text-helper.ts:
--------------------------------------------------------------------------------
1 | export abstract class TextHelper {
2 | static getTextFilterCounterText(count = 0) {
3 | return `${count} ${count === 1 ? "match" : "matches"}`;
4 | }
5 |
6 | static getHeaderCounterText(
7 | items: ReadonlyArray,
8 | selectedItems: ReadonlyArray | undefined,
9 | ) {
10 | return selectedItems && selectedItems?.length > 0
11 | ? `(${selectedItems.length}/${items.length})`
12 | : `(${items.length})`;
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/fullstack-vite-cdk-cognito-auth/user-interface/src/common/hooks/use-form.ts:
--------------------------------------------------------------------------------
1 | import { useCallback, useState } from "react";
2 | import { Utils } from "../utils";
3 |
4 | export interface UseFormProps {
5 | initialValue: T | (() => T);
6 | validate: (form: T) => Record | null;
7 | }
8 |
9 | export function useForm(props: UseFormProps) {
10 | const [initialProps] = useState(props);
11 | const [data, setData] = useState(() => {
12 | const value = Utils.isFunction(props.initialValue)
13 | ? props.initialValue()
14 | : props.initialValue;
15 |
16 | return {
17 | dirty: false,
18 | value,
19 | };
20 | });
21 | const [errors, setErrors] = useState>({});
22 |
23 | const validate = useCallback(() => {
24 | const errors = initialProps.validate(data.value);
25 | setErrors(errors ?? {});
26 | setData((current) => ({ ...current, dirty: true }));
27 |
28 | return errors === null || Object.keys(errors).length === 0;
29 | }, [data, initialProps]);
30 |
31 | const onChange = useCallback(
32 | (partial: Partial, resetDirty = false) => {
33 | setData((current) => {
34 | let dirty = current.dirty;
35 | if (resetDirty) {
36 | dirty = false;
37 | }
38 |
39 | const updatedData = {
40 | ...current,
41 | dirty,
42 | value: { ...current.value, ...partial },
43 | };
44 |
45 | if (dirty) {
46 | const errors = initialProps.validate(updatedData.value);
47 | setErrors(errors ?? {});
48 | }
49 |
50 | return updatedData;
51 | });
52 | },
53 | [initialProps]
54 | );
55 |
56 | return { data: data.value, onChange, errors, validate };
57 | }
58 |
--------------------------------------------------------------------------------
/fullstack-vite-cdk-cognito-auth/user-interface/src/common/hooks/use-navigation-panel-state.ts:
--------------------------------------------------------------------------------
1 | import { useState } from "react";
2 | import { StorageHelper } from "../helpers/storage-helper";
3 | import { NavigationPanelState } from "../types";
4 |
5 | export function useNavigationPanelState(): [
6 | NavigationPanelState,
7 | (state: Partial) => void,
8 | ] {
9 | const [currentState, setCurrentState] = useState(
10 | StorageHelper.getNavigationPanelState(),
11 | );
12 |
13 | const onChange = (state: Partial) => {
14 | setCurrentState(StorageHelper.setNavigationPanelState(state));
15 | };
16 |
17 | return [currentState, onChange];
18 | }
19 |
--------------------------------------------------------------------------------
/fullstack-vite-cdk-cognito-auth/user-interface/src/common/hooks/use-on-follow.ts:
--------------------------------------------------------------------------------
1 | import { useCallback } from "react";
2 | import { useNavigate } from "react-router";
3 |
4 | interface FollowDetail {
5 | external?: boolean;
6 | href?: string;
7 | }
8 |
9 | export function useOnFollow() {
10 | const navigate = useNavigate();
11 |
12 | return useCallback(
13 | (event: CustomEvent): void => {
14 | if (
15 | event.detail.external === true ||
16 | typeof event.detail.href === "undefined"
17 | ) {
18 | return;
19 | }
20 |
21 | event.preventDefault();
22 | navigate(event.detail.href);
23 | },
24 | [navigate],
25 | );
26 | }
27 |
--------------------------------------------------------------------------------
/fullstack-vite-cdk-cognito-auth/user-interface/src/common/i18n/property-filter-i18n-strings.ts:
--------------------------------------------------------------------------------
1 | import { PropertyFilterProps } from "@cloudscape-design/components";
2 |
3 | export const PropertyFilterI18nStrings: PropertyFilterProps.I18nStrings = {
4 | filteringAriaLabel: "your choice",
5 | dismissAriaLabel: "Dismiss",
6 |
7 | groupValuesText: "Values",
8 | groupPropertiesText: "Properties",
9 | operatorsText: "Operators",
10 |
11 | operationAndText: "and",
12 | operationOrText: "or",
13 |
14 | operatorLessText: "Less than",
15 | operatorLessOrEqualText: "Less than or equal",
16 | operatorGreaterText: "Greater than",
17 | operatorGreaterOrEqualText: "Greater than or equal",
18 | operatorContainsText: "Contains",
19 | operatorDoesNotContainText: "Does not contain",
20 | operatorEqualsText: "Equals",
21 | operatorDoesNotEqualText: "Does not equal",
22 |
23 | editTokenHeader: "Edit filter",
24 | propertyText: "Property",
25 | operatorText: "Operator",
26 | valueText: "Value",
27 | cancelActionText: "Cancel",
28 | applyActionText: "Apply",
29 | allPropertiesLabel: "All properties",
30 |
31 | tokenLimitShowMore: "Show more",
32 | tokenLimitShowFewer: "Show fewer",
33 | clearFiltersText: "Clear filters",
34 | removeTokenButtonAriaLabel: (token) =>
35 | `Remove token ${token.propertyKey} ${token.operator} ${token.value}`,
36 | enteredTextLabel: (text) => `Use: "${text}"`,
37 | };
38 |
--------------------------------------------------------------------------------
/fullstack-vite-cdk-cognito-auth/user-interface/src/common/types.ts:
--------------------------------------------------------------------------------
1 | import { StatusIndicatorProps } from "@cloudscape-design/components";
2 |
3 | export interface NavigationPanelState {
4 | collapsed?: boolean;
5 | collapsedSections?: Record;
6 | }
7 |
8 | export interface Item {
9 | itemId: string;
10 | name: string;
11 | type: string;
12 | status: StatusIndicatorProps.Type;
13 | details: number;
14 | }
15 |
--------------------------------------------------------------------------------
/fullstack-vite-cdk-cognito-auth/user-interface/src/common/utils.ts:
--------------------------------------------------------------------------------
1 | export abstract class Utils {
2 | static promiseSetTimeout(duration: number) {
3 | return new Promise((resolve) => {
4 | setTimeout(() => {
5 | resolve("Done");
6 | }, duration);
7 | });
8 | }
9 |
10 | static urlSearchParamsToRecord(
11 | params: URLSearchParams
12 | ): Record {
13 | const record: Record = {};
14 |
15 | for (const [key, value] of params.entries()) {
16 | record[key] = value;
17 | }
18 |
19 | return record;
20 | }
21 |
22 | static isFunction(value: unknown): value is Function {
23 | return typeof value === "function";
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/fullstack-vite-cdk-cognito-auth/user-interface/src/components/base-app-layout.tsx:
--------------------------------------------------------------------------------
1 | import { AppLayout, AppLayoutProps } from "@cloudscape-design/components";
2 | import { useNavigationPanelState } from "../common/hooks/use-navigation-panel-state";
3 | import NavigationPanel from "./navigation-panel";
4 |
5 | export default function BaseAppLayout(props: AppLayoutProps) {
6 | const [navigationPanelState, setNavigationPanelState] =
7 | useNavigationPanelState();
8 |
9 | return (
10 | }
13 | navigationOpen={!navigationPanelState.collapsed}
14 | onNavigationChange={({ detail }) =>
15 | setNavigationPanelState({ collapsed: !detail.open })
16 | }
17 | toolsHide={true}
18 | {...props}
19 | />
20 | );
21 | }
22 |
--------------------------------------------------------------------------------
/fullstack-vite-cdk-cognito-auth/user-interface/src/components/global-header.tsx:
--------------------------------------------------------------------------------
1 | import { useEffect, useState } from "react";
2 | import { signOut, fetchAuthSession } from "aws-amplify/auth";
3 | import {
4 | ButtonDropdownProps,
5 | TopNavigation,
6 | } from "@cloudscape-design/components";
7 | import { Mode } from "@cloudscape-design/global-styles";
8 | import { StorageHelper } from "../common/helpers/storage-helper";
9 | import { APP_NAME } from "../common/constants";
10 | import { useOnFollow } from "../common/hooks/use-on-follow";
11 |
12 | export default function GlobalHeader() {
13 | const onFollow = useOnFollow();
14 | const [userName, setUserName] = useState(null);
15 | const [theme, setTheme] = useState(StorageHelper.getTheme());
16 |
17 | useEffect(() => {
18 | (async () => {
19 | const session = await fetchAuthSession();
20 |
21 | if (!session) {
22 | signOut();
23 | return;
24 | }
25 |
26 | setUserName(session.tokens?.idToken?.payload?.email?.toString() ?? "");
27 | })();
28 | }, []);
29 |
30 | const onChangeThemeClick = () => {
31 | if (theme === Mode.Dark) {
32 | setTheme(StorageHelper.applyTheme(Mode.Light));
33 | } else {
34 | setTheme(StorageHelper.applyTheme(Mode.Dark));
35 | }
36 | };
37 |
38 | const onUserProfileClick = ({
39 | detail,
40 | }: {
41 | detail: ButtonDropdownProps.ItemClickDetails;
42 | }) => {
43 | if (detail.id === "signout") {
44 | signOut();
45 | }
46 | };
47 |
48 | return (
49 |
53 |
79 |
80 | );
81 | }
82 |
--------------------------------------------------------------------------------
/fullstack-vite-cdk-cognito-auth/user-interface/src/components/modals/item-delete-modal.tsx:
--------------------------------------------------------------------------------
1 | import {
2 | Modal,
3 | Box,
4 | SpaceBetween,
5 | Button,
6 | Alert,
7 | } from "@cloudscape-design/components";
8 | import { Item } from "../../common/types";
9 |
10 | export interface ItemDeleteModalProps {
11 | visible: boolean;
12 | item?: Item;
13 | onDelete: () => void;
14 | onDiscard: () => void;
15 | }
16 |
17 | export default function ItemDeleteModal(props: ItemDeleteModalProps) {
18 | return (
19 |
26 |
27 |
30 |
37 |
38 |
39 | }
40 | >
41 | {props.item && (
42 |
43 |
44 | Permanently delete item{" "}
45 |
46 | {props.item.name}
47 |
48 | ? You can't undo this action.
49 |
50 | Item Id: {props.item.itemId}
51 |
52 | Proceeding with this action will delete the item.
53 |
54 |
55 | )}
56 |
57 | );
58 | }
59 |
--------------------------------------------------------------------------------
/fullstack-vite-cdk-cognito-auth/user-interface/src/components/navigation-panel.tsx:
--------------------------------------------------------------------------------
1 | import {
2 | SideNavigation,
3 | SideNavigationProps,
4 | } from "@cloudscape-design/components";
5 | import { useNavigationPanelState } from "../common/hooks/use-navigation-panel-state";
6 | import { useState } from "react";
7 | import { useOnFollow } from "../common/hooks/use-on-follow";
8 | import { APP_NAME } from "../common/constants";
9 | import { useLocation } from "react-router-dom";
10 |
11 | export default function NavigationPanel() {
12 | const location = useLocation();
13 | const onFollow = useOnFollow();
14 | const [navigationPanelState, setNavigationPanelState] =
15 | useNavigationPanelState();
16 |
17 | const [items] = useState(() => {
18 | const items: SideNavigationProps.Item[] = [
19 | {
20 | type: "link",
21 | text: "Dashboard",
22 | href: "/",
23 | },
24 | {
25 | type: "section",
26 | text: "Section 1",
27 | items: [{ type: "link", text: "Items", href: "/section1" }],
28 | },
29 | {
30 | type: "section",
31 | text: "Section 2",
32 | items: [
33 | { type: "link", text: "Item 1", href: "/section2/item1" },
34 | { type: "link", text: "Item 2", href: "/section2/item2" },
35 | { type: "link", text: "Item 2", href: "/section2/item3" },
36 | ],
37 | },
38 | ];
39 |
40 | items.push(
41 | { type: "divider" },
42 | {
43 | type: "link",
44 | text: "Documentation",
45 | href: "https://github.com/aws-samples/cloudscape-examples",
46 | external: true,
47 | }
48 | );
49 |
50 | return items;
51 | });
52 |
53 | const onChange = ({
54 | detail,
55 | }: {
56 | detail: SideNavigationProps.ChangeDetail;
57 | }) => {
58 | const sectionIndex = items.indexOf(detail.item);
59 | setNavigationPanelState({
60 | collapsedSections: {
61 | ...navigationPanelState.collapsedSections,
62 | [sectionIndex]: !detail.expanded,
63 | },
64 | });
65 | };
66 |
67 | return (
68 | {
74 | if (value.type === "section") {
75 | const collapsed =
76 | navigationPanelState.collapsedSections?.[idx] === true;
77 | value.defaultExpanded = !collapsed;
78 | }
79 |
80 | return value;
81 | })}
82 | />
83 | );
84 | }
85 |
--------------------------------------------------------------------------------
/fullstack-vite-cdk-cognito-auth/user-interface/src/components/wrappers/router-button-dropdown.tsx:
--------------------------------------------------------------------------------
1 | import {
2 | ButtonDropdownProps,
3 | ButtonDropdown,
4 | } from "@cloudscape-design/components";
5 | import { useOnFollow } from "../../common/hooks/use-on-follow";
6 |
7 | export default function RouterButtonDropdown(props: ButtonDropdownProps) {
8 | const onFollow = useOnFollow();
9 |
10 | return ;
11 | }
12 |
--------------------------------------------------------------------------------
/fullstack-vite-cdk-cognito-auth/user-interface/src/components/wrappers/router-button.tsx:
--------------------------------------------------------------------------------
1 | import { ButtonProps, Button } from "@cloudscape-design/components";
2 | import { useOnFollow } from "../../common/hooks/use-on-follow";
3 |
4 | export default function RouterButton(props: ButtonProps) {
5 | const onFollow = useOnFollow();
6 |
7 | return ;
8 | }
9 |
--------------------------------------------------------------------------------
/fullstack-vite-cdk-cognito-auth/user-interface/src/components/wrappers/router-link.tsx:
--------------------------------------------------------------------------------
1 | import { Link, LinkProps } from "@cloudscape-design/components";
2 | import { useOnFollow } from "../../common/hooks/use-on-follow";
3 |
4 | export default function RouterLink(props: LinkProps) {
5 | const onFollow = useOnFollow();
6 |
7 | return ;
8 | }
9 |
--------------------------------------------------------------------------------
/fullstack-vite-cdk-cognito-auth/user-interface/src/main.tsx:
--------------------------------------------------------------------------------
1 | import React from "react";
2 | import ReactDOM from "react-dom/client";
3 | import AppConfigured from "./components/app-configured";
4 | import { StorageHelper } from "./common/helpers/storage-helper";
5 | import "@cloudscape-design/global-styles/index.css";
6 |
7 | const root = ReactDOM.createRoot(
8 | document.getElementById("root") as HTMLElement,
9 | );
10 |
11 | const theme = StorageHelper.getTheme();
12 | StorageHelper.applyTheme(theme);
13 |
14 | root.render(
15 |
16 |
17 | ,
18 | );
19 |
--------------------------------------------------------------------------------
/fullstack-vite-cdk-cognito-auth/user-interface/src/pages/dashboard/dashboard-header.tsx:
--------------------------------------------------------------------------------
1 | import { Header, SpaceBetween } from "@cloudscape-design/components";
2 | import RouterButton from "../../components/wrappers/router-button";
3 | import RouterButtonDropdown from "../../components/wrappers/router-button-dropdown";
4 |
5 | export default function DashboardHeader() {
6 | return (
7 |
11 | View Items
12 |
21 | Add data
22 |
23 |
24 | }
25 | >
26 | Dashboard
27 |
28 | );
29 | }
30 |
--------------------------------------------------------------------------------
/fullstack-vite-cdk-cognito-auth/user-interface/src/pages/dashboard/dashboard-page.tsx:
--------------------------------------------------------------------------------
1 | import { APP_NAME } from "../../common/constants";
2 | import {
3 | BreadcrumbGroup,
4 | ContentLayout,
5 | SpaceBetween,
6 | } from "@cloudscape-design/components";
7 | import { useOnFollow } from "../../common/hooks/use-on-follow";
8 | import BaseAppLayout from "../../components/base-app-layout";
9 | import DashboardHeader from "./dashboard-header";
10 | import ItemsTable from "./items-table";
11 | import StatisticsBlock from "./statistics-block";
12 |
13 | export default function DashboardPage() {
14 | const onFollow = useOnFollow();
15 |
16 | return (
17 |
28 | }
29 | content={
30 | }>
31 |
32 |
33 |
34 |
35 |
36 | }
37 | />
38 | );
39 | }
40 |
--------------------------------------------------------------------------------
/fullstack-vite-cdk-cognito-auth/user-interface/src/pages/dashboard/statistics-block.tsx:
--------------------------------------------------------------------------------
1 | import {
2 | Container,
3 | Header,
4 | ColumnLayout,
5 | Box,
6 | } from "@cloudscape-design/components";
7 |
8 | export default function StatisticsBlock() {
9 | return (
10 | Statistics}>
11 |
12 |
16 |
17 |
Something Else
18 |
11
19 |
20 |
21 |
Another Item
22 |
18
23 |
24 |
28 |
29 |
30 | );
31 | }
32 |
--------------------------------------------------------------------------------
/fullstack-vite-cdk-cognito-auth/user-interface/src/pages/not-found.tsx:
--------------------------------------------------------------------------------
1 | import {
2 | Alert,
3 | BreadcrumbGroup,
4 | Container,
5 | ContentLayout,
6 | Header,
7 | SpaceBetween,
8 | } from "@cloudscape-design/components";
9 | import { useOnFollow } from "../common/hooks/use-on-follow";
10 | import { APP_NAME } from "../common/constants";
11 | import BaseAppLayout from "../components/base-app-layout";
12 |
13 | export default function NotFound() {
14 | const onFollow = useOnFollow();
15 |
16 | return (
17 |
34 | }
35 | content={
36 | 404. Page Not Found}
38 | >
39 |
40 |
41 |
42 | The page you are looking for does not exist.
43 |
44 |
45 |
46 |
47 | }
48 | />
49 | );
50 | }
51 |
--------------------------------------------------------------------------------
/fullstack-vite-cdk-cognito-auth/user-interface/src/pages/section1/all-items/all-items-header.tsx:
--------------------------------------------------------------------------------
1 | import {
2 | Button,
3 | Header,
4 | HeaderProps,
5 | SpaceBetween,
6 | } from "@cloudscape-design/components";
7 | import RouterButton from "../../../components/wrappers/router-button";
8 | import { useNavigate } from "react-router-dom";
9 | import { Item } from "../../../common/types";
10 | import { useState } from "react";
11 | import ItemDeleteModal from "../../../components/modals/item-delete-modal";
12 | import { ApiClient } from "../../../common/api-client/api-client";
13 |
14 | interface AllItemsPageHeaderProps extends HeaderProps {
15 | title?: string;
16 | createButtonText?: string;
17 | selectedItems: readonly Item[];
18 | refresh: () => Promise;
19 | }
20 |
21 | export function AllItemsPageHeader({
22 | title = "Items",
23 | ...props
24 | }: AllItemsPageHeaderProps) {
25 | const navigate = useNavigate();
26 | const [showDeleteModal, setShowDeleteModal] = useState(false);
27 |
28 | const onDeleteClick = () => {
29 | setShowDeleteModal(true);
30 | };
31 |
32 | const onDeleteWorksapce = async () => {
33 | setShowDeleteModal(false);
34 |
35 | const apiClient = new ApiClient();
36 | await apiClient.items.deleteItem(props.selectedItems[0].itemId);
37 |
38 | setTimeout(async () => {
39 | await props.refresh();
40 | }, 2500);
41 | };
42 |
43 | return (
44 | <>
45 | setShowDeleteModal(false)}
48 | onDelete={onDeleteWorksapce}
49 | item={props.selectedItems[0]}
50 | />
51 |
55 |
85 | >
86 | );
87 | }
88 |
--------------------------------------------------------------------------------
/fullstack-vite-cdk-cognito-auth/user-interface/src/pages/section1/all-items/all-items-page.tsx:
--------------------------------------------------------------------------------
1 | import { BreadcrumbGroup } from "@cloudscape-design/components";
2 | import { APP_NAME } from "../../../common/constants";
3 | import { useOnFollow } from "../../../common/hooks/use-on-follow";
4 | import BaseAppLayout from "../../../components/base-app-layout";
5 | import AllItemsTable from "./all-items-table";
6 |
7 | export default function AllItemsPage() {
8 | const onFollow = useOnFollow();
9 |
10 | return (
11 |
26 | }
27 | content={}
28 | />
29 | );
30 | }
31 |
--------------------------------------------------------------------------------
/fullstack-vite-cdk-cognito-auth/user-interface/src/styles/app.scss:
--------------------------------------------------------------------------------
1 | * {
2 | box-sizing: border-box;
3 | }
4 |
5 | :root {
6 | --app-color-scheme: light;
7 | color-scheme: var(--app-color-scheme);
8 | }
9 |
10 | html,
11 | body,
12 | #root,
13 | div[data-amplify-authenticator],
14 | div[data-amplify-theme] {
15 | height: 100%;
16 | }
17 |
18 | body {
19 | background-color: #ffffff;
20 | overflow-y: scroll;
21 | }
22 |
23 | body.awsui-dark-mode {
24 | background-color: #0e1b2a;
25 | }
26 |
--------------------------------------------------------------------------------
/fullstack-vite-cdk-cognito-auth/user-interface/src/vite-env.d.ts:
--------------------------------------------------------------------------------
1 | ///
2 |
--------------------------------------------------------------------------------
/fullstack-vite-cdk-cognito-auth/user-interface/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | "target": "ES2020",
4 | "useDefineForClassFields": true,
5 | "lib": ["ES2020", "DOM", "DOM.Iterable"],
6 | "module": "ESNext",
7 | "skipLibCheck": true,
8 |
9 | /* Bundler mode */
10 | "moduleResolution": "bundler",
11 | "allowImportingTsExtensions": true,
12 | "resolveJsonModule": true,
13 | "isolatedModules": true,
14 | "noEmit": true,
15 | "jsx": "react-jsx",
16 |
17 | /* Linting */
18 | "strict": true,
19 | "noUnusedLocals": true,
20 | "noUnusedParameters": true,
21 | "noFallthroughCasesInSwitch": true
22 | },
23 | "include": ["src"],
24 | "references": [{ "path": "./tsconfig.node.json" }]
25 | }
26 |
--------------------------------------------------------------------------------
/fullstack-vite-cdk-cognito-auth/user-interface/tsconfig.node.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | "composite": true,
4 | "skipLibCheck": true,
5 | "module": "ESNext",
6 | "moduleResolution": "bundler",
7 | "allowSyntheticDefaultImports": true,
8 | "strict": true
9 | },
10 | "include": ["vite.config.ts"]
11 | }
12 |
--------------------------------------------------------------------------------
/fullstack-vite-cdk-cognito-auth/user-interface/vite.config.ts:
--------------------------------------------------------------------------------
1 | import { defineConfig } from "vite";
2 | import react from "@vitejs/plugin-react";
3 |
4 | // https://vitejs.dev/config/
5 | export default defineConfig({
6 | plugins: [react()],
7 | server: {
8 | port: 3000,
9 | },
10 | });
11 |
--------------------------------------------------------------------------------