├── .editorconfig ├── .env.example ├── .eslintrc.js ├── .gcloudignore ├── .gitattributes ├── .github └── workflows │ ├── codeql.yml │ └── copy-to-public.yml ├── .gitignore ├── LICENSE.txt ├── README.md ├── app.yaml ├── cloudbuild.yaml ├── docs ├── creating-custom-content-cards.md └── index.md ├── package-lock.json ├── package.json ├── public ├── favicon.ico ├── index.html ├── logo192.png ├── logo512.png ├── manifest.json └── robots.txt └── src ├── Router.js ├── components ├── CameraPreview.js ├── Captions.js ├── ContentCardDisplay.js ├── ContentCardSwitch.js ├── ContentCards │ ├── Image.js │ ├── ImageCarousel.js │ ├── Link.js │ ├── Markdown.js │ ├── Options.js │ ├── Transcript.js │ └── Video.js ├── Controls.js ├── FeedbackModal.js ├── Header.js ├── PersonaVideo.js ├── STTFeedback.js └── TextInput.js ├── config.js ├── eula.js ├── globalStyle.js ├── img ├── camera-video-fill.svg ├── mic-fill.svg ├── mic.svg ├── placeholder-headshot.png └── sm-logo-retina.webp ├── index.js ├── proxyVideo.js ├── reportWebVitals.js ├── routes ├── ContentCardTest.js ├── DPChat.js ├── Feedback.js ├── FeedbackRoute.js ├── Landing.js └── Loading.js ├── setupTests.js ├── store ├── index.js └── sm │ ├── index.js │ └── meatball.js └── utils ├── Modal.js ├── breakpoints.js ├── camera.js └── roundObject.js /.editorconfig: -------------------------------------------------------------------------------- 1 | # EditorConfig is awesome: https://EditorConfig.org 2 | 3 | # top-most EditorConfig file 4 | root = true 5 | 6 | [*] 7 | indent_style = space 8 | indent_size = 2 9 | end_of_line = lf 10 | charset = utf-8 11 | trim_trailing_whitespace = true 12 | insert_final_newline = true -------------------------------------------------------------------------------- /.env.example: -------------------------------------------------------------------------------- 1 | # there are more configuration values in /src/config.js such as colors and background 2 | 3 | # env vars that are passed in to the react app need to be prefixed with REACT_APP_ 4 | 5 | # this usually doesn't need to be changed for standard projects 6 | REACT_APP_SESSION_SERVER="dh.soulmachines.cloud" 7 | # API key can be configured in DDNA prefs, good for basic auth when using a supported NLP 8 | REACT_APP_API_KEY="" 9 | # endpoint to token server corresponding to project's persona 10 | # token server auth is used when an orchestration server is being used to handle NLP 11 | REACT_APP_TOKEN_URL=https://example.com/auth/authorize 12 | 13 | # you can either use an API key or a token server to connect to your persona. 14 | # 0: API key 15 | # 1: token server 16 | REACT_APP_PERSONA_AUTH_MODE=0 17 | # enable if using an orchestration server (usually for non-native NLP or custom backend logic) 18 | REACT_APP_ORCHESTRATION_MODE=false 19 | 20 | # local development server will serve app from this port 21 | PORT=3000 22 | 23 | # uncomment if using Google Analytics 24 | # REACT_APP_GA_TRACKING_ID=G-XXXXXXXXXXX 25 | 26 | # without this flag, any eslint errors will prevent the app from building 27 | ESLINT_NO_DEV_ERRORS=true 28 | # suppress source map errors present when using react-scripts@5.0.1 29 | GENERATE_SOURCEMAP=false 30 | -------------------------------------------------------------------------------- /.eslintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | env: { 3 | browser: true, 4 | es2021: true, 5 | }, 6 | extends: [ 7 | 'plugin:react/recommended', 8 | 'airbnb', 9 | ], 10 | parser: '@typescript-eslint/parser', 11 | parserOptions: { 12 | ecmaFeatures: { 13 | jsx: true, 14 | }, 15 | ecmaVersion: 12, 16 | sourceType: 'module', 17 | }, 18 | plugins: [ 19 | 'react', 20 | '@typescript-eslint', 21 | ], 22 | rules: { 23 | 'react/jsx-filename-extension': 0, 24 | 'no-console': 0, 25 | 'default-param-last': 0, 26 | 'linebreak-style': ['error', process.platform === 'win32' ? 'windows' : 'unix'], 27 | }, 28 | }; 29 | -------------------------------------------------------------------------------- /.gcloudignore: -------------------------------------------------------------------------------- 1 | # This file specifies files that are *not* uploaded to Google Cloud Platform 2 | # using gcloud. It follows the same syntax as .gitignore, with the addition of 3 | # "#!include" directives (which insert the entries of the given .gitignore-style 4 | # file at that point). 5 | # 6 | # For more information, run: 7 | # $ gcloud topic gcloudignore 8 | # 9 | .gcloudignore 10 | # If you would like to upload your .git directory, .gitignore file or files 11 | # from your .gitignore file, remove the corresponding line 12 | # below: 13 | .git 14 | .gitignore 15 | 16 | # Node.js dependencies: 17 | node_modules/ -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform EOL normalization 2 | * text=auto 3 | -------------------------------------------------------------------------------- /.github/workflows/codeql.yml: -------------------------------------------------------------------------------- 1 | # For most projects, this workflow file will not need changing; you simply need 2 | # to commit it to your repository. 3 | # 4 | # You may wish to alter this file to override the set of languages analyzed, 5 | # or to provide custom queries or build logic. 6 | # 7 | # ******** NOTE ******** 8 | # We have attempted to detect the languages in your repository. Please check 9 | # the `language` matrix defined below to confirm you have the correct set of 10 | # supported CodeQL languages. 11 | # 12 | name: "CodeQL" 13 | 14 | on: 15 | push: 16 | branches: [ "main" ] 17 | pull_request: 18 | # The branches below must be a subset of the branches above 19 | branches: [ "main" ] 20 | schedule: 21 | - cron: '21 6 * * 2' 22 | 23 | jobs: 24 | analyze: 25 | name: Analyze 26 | runs-on: ubuntu-latest 27 | permissions: 28 | actions: read 29 | contents: read 30 | security-events: write 31 | 32 | strategy: 33 | fail-fast: false 34 | matrix: 35 | language: [ 'javascript' ] 36 | # CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python', 'ruby' ] 37 | # Learn more about CodeQL language support at https://aka.ms/codeql-docs/language-support 38 | 39 | steps: 40 | - name: Checkout repository 41 | uses: actions/checkout@v3 42 | 43 | # Initializes the CodeQL tools for scanning. 44 | - name: Initialize CodeQL 45 | uses: github/codeql-action/init@v2 46 | with: 47 | languages: ${{ matrix.language }} 48 | queries: security-and-quality 49 | # If you wish to specify custom queries, you can do so here or in a config file. 50 | # By default, queries listed here will override any specified in a config file. 51 | # Prefix the list here with "+" to use these queries and those in the config file. 52 | 53 | # Details on CodeQL's query packs refer to : https://docs.github.com/en/code-security/code-scanning/automatically-scanning-your-code-for-vulnerabilities-and-errors/configuring-code-scanning#using-queries-in-ql-packs 54 | # queries: security-extended,security-and-quality 55 | 56 | 57 | # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). 58 | # If this step fails, then you should remove it and run the build manually (see below) 59 | - name: Autobuild 60 | uses: github/codeql-action/autobuild@v2 61 | 62 | # ℹ️ Command-line programs to run using the OS shell. 63 | # 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun 64 | 65 | # If the Autobuild fails above, remove it and uncomment the following three lines. 66 | # modify them (or add more) to build your code if your project, please refer to the EXAMPLE below for guidance. 67 | 68 | # - run: | 69 | # echo "Run, Build Application using script" 70 | # ./location_of_script_within_repo/buildscript.sh 71 | 72 | - name: Perform CodeQL Analysis 73 | uses: github/codeql-action/analyze@v2 74 | -------------------------------------------------------------------------------- /.github/workflows/copy-to-public.yml: -------------------------------------------------------------------------------- 1 | name: "copy to react-reference-ui-public" 2 | 3 | on: 4 | push: 5 | branches: ['main'] 6 | 7 | jobs: 8 | copy-to-branches: 9 | runs-on: ubuntu-latest 10 | steps: 11 | - uses: actions/checkout@v2 12 | - name: Pushes to another repository 13 | uses: cpina/github-action-push-to-another-repository@main 14 | env: 15 | SSH_DEPLOY_KEY: ${{ secrets.SSH_PRIVATE_KEY }} 16 | with: 17 | source-directory: '.' 18 | destination-github-username: 'soulmachines' 19 | destination-repository-name: 'react-reference-ui-public' 20 | user-email: jade.fung@soulmachines.com 21 | target-branch: main 22 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | 2 | # Created by https://www.toptal.com/developers/gitignore/api/node,macos,vim 3 | # Edit at https://www.toptal.com/developers/gitignore?templates=node,macos,vim 4 | 5 | ### macOS ### 6 | # General 7 | .DS_Store 8 | .AppleDouble 9 | .LSOverride 10 | 11 | # Icon must end with two \r 12 | Icon 13 | 14 | 15 | # Thumbnails 16 | ._* 17 | 18 | # Files that might appear in the root of a volume 19 | .DocumentRevisions-V100 20 | .fseventsd 21 | .Spotlight-V100 22 | .TemporaryItems 23 | .Trashes 24 | .VolumeIcon.icns 25 | .com.apple.timemachine.donotpresent 26 | 27 | # Directories potentially created on remote AFP share 28 | .AppleDB 29 | .AppleDesktop 30 | Network Trash Folder 31 | Temporary Items 32 | .apdisk 33 | 34 | ### Node ### 35 | # Logs 36 | logs 37 | *.log 38 | npm-debug.log* 39 | yarn-debug.log* 40 | yarn-error.log* 41 | lerna-debug.log* 42 | 43 | # Diagnostic reports (https://nodejs.org/api/report.html) 44 | report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json 45 | 46 | # Runtime data 47 | pids 48 | *.pid 49 | *.seed 50 | *.pid.lock 51 | 52 | # Directory for instrumented libs generated by jscoverage/JSCover 53 | lib-cov 54 | 55 | # Coverage directory used by tools like istanbul 56 | coverage 57 | *.lcov 58 | 59 | # nyc test coverage 60 | .nyc_output 61 | 62 | # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) 63 | .grunt 64 | 65 | # Bower dependency directory (https://bower.io/) 66 | bower_components 67 | 68 | # node-waf configuration 69 | .lock-wscript 70 | 71 | # Compiled binary addons (https://nodejs.org/api/addons.html) 72 | build/Release 73 | 74 | # Dependency directories 75 | node_modules/ 76 | jspm_packages/ 77 | 78 | # TypeScript v1 declaration files 79 | typings/ 80 | 81 | # TypeScript cache 82 | *.tsbuildinfo 83 | 84 | # Optional npm cache directory 85 | .npm 86 | 87 | # Optional eslint cache 88 | .eslintcache 89 | 90 | # Optional stylelint cache 91 | .stylelintcache 92 | 93 | # Microbundle cache 94 | .rpt2_cache/ 95 | .rts2_cache_cjs/ 96 | .rts2_cache_es/ 97 | .rts2_cache_umd/ 98 | 99 | # Optional REPL history 100 | .node_repl_history 101 | 102 | # Output of 'npm pack' 103 | *.tgz 104 | 105 | # Yarn Integrity file 106 | .yarn-integrity 107 | 108 | # dotenv environment variables file 109 | .env 110 | .env.test 111 | .env*.local 112 | 113 | # parcel-bundler cache (https://parceljs.org/) 114 | .cache 115 | .parcel-cache 116 | 117 | # Next.js build output 118 | .next 119 | 120 | # Nuxt.js build / generate output 121 | .nuxt 122 | dist 123 | 124 | # Storybook build outputs 125 | .out 126 | .storybook-out 127 | storybook-static 128 | 129 | # rollup.js default build output 130 | dist/ 131 | 132 | # Gatsby files 133 | .cache/ 134 | # Comment in the public line in if your project uses Gatsby and not Next.js 135 | # https://nextjs.org/blog/next-9-1#public-directory-support 136 | # public 137 | 138 | # vuepress build output 139 | .vuepress/dist 140 | 141 | # Serverless directories 142 | .serverless/ 143 | 144 | # FuseBox cache 145 | .fusebox/ 146 | 147 | # DynamoDB Local files 148 | .dynamodb/ 149 | 150 | # TernJS port file 151 | .tern-port 152 | 153 | # Stores VSCode versions used for testing VSCode extensions 154 | .vscode-test 155 | 156 | # Temporary folders 157 | tmp/ 158 | temp/ 159 | 160 | ### Vim ### 161 | # Swap 162 | [._]*.s[a-v][a-z] 163 | !*.svg # comment out if you don't need vector files 164 | [._]*.sw[a-p] 165 | [._]s[a-rt-v][a-z] 166 | [._]ss[a-gi-z] 167 | [._]sw[a-p] 168 | 169 | # Session 170 | Session.vim 171 | Sessionx.vim 172 | 173 | # Temporary 174 | .netrwhist 175 | *~ 176 | # Auto-generated tag files 177 | tags 178 | # Persistent undo 179 | [._]*.un~ 180 | 181 | # End of https://www.toptal.com/developers/gitignore/api/node,macos,vim 182 | 183 | ### vscode ### 184 | .vscode 185 | .vscode/* 186 | !.vscode/settings.json 187 | !.vscode/tasks.json 188 | !.vscode/launch.json 189 | !.vscode/extensions.json 190 | *.code-workspace 191 | 192 | # End of https://www.toptal.com/developers/gitignore/api/vscode 193 | build 194 | sm-embed.css 195 | sm-embed.js 196 | 197 | .secrets 198 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Soul Machines React Reference UI 2 | 3 | This template succeeds the previous [react-template](https://github.com/soulmachines/react-template). This is re-write is based on [create-react-app](https://github.com/facebook/create-react-app) and is designed mainly to provide a simple and familiar developer experience. 4 | 5 | This template contains functional examples of how the user flow and interaction with the Digital Person should work, and likley require styling chanages to suit branding requirements. 6 | 7 | ## Setup 8 | 9 | In order to run this application, you'll either need an API key or a token server. Most projects will use an API key--token servers are only necessary when interfacing with a non-native NLP through a orchestration server. 10 | 11 | ### Copy `.env.example` contents into `.env` 12 | Create an empty text file called `.env` and copy the contents of `.env.example` into it. These environment variables are required for the UI to run. 13 | 14 | If using an API key, set `REACT_APP_PERSONA_AUTH_MODE` to `0` and populate `REACT_APP_API_KEY` with your key. 15 | 16 | If using an orchestration server, set `REACT_APP_PERSONA_AUTH_MODE` to `1` and populate `REACT_APP_TOKEN_URL` with your token server endpoint and set `REACT_APP_TOKEN_URL` to `true`. 17 | 18 | ### `npm install` 19 | Run to install the project's dependencies. 20 | 21 | ### `npm start` 22 | Starts the development server. Open [http://localhost:3000](http://localhost:3000) to view it in the browser. The page will automatically reload when you make changes. 23 | 24 | ### `npm run build` 25 | Builds the app for production to the `build` folder. The files will be bundled and minified for production. 26 | 27 | ## License 28 | 29 | Soul Machines React Reference UI is available under the Apache License, Version 2.0. See the [LICENSE.txt](./LICENSE.txt) file for more info. 30 | 31 | ## Linting & Code Style 32 | 33 | This project strictly follows [AirBnB's JavaScript style guide](https://github.com/airbnb/javascript). We recommend you install [ESLint](https://eslint.org/) in your editor and adhere to its recommendations. 34 | 35 | We have also provided an `.editorconfig` file that you can use in your editor to match the indentation, whitespace, and other styling rules we used in creating this template. 36 | 37 | ## Support 38 | Our team would love to hear from you. For any additional support, feedback, bugs, feature requests, please [submit a ticket](https://support.soulmachines.com) or reach out to us at [support@soulmachines.com](support@soulmachines.com). 39 | -------------------------------------------------------------------------------- /app.yaml: -------------------------------------------------------------------------------- 1 | # [START appengine_websockets_yaml] 2 | runtime: nodejs16 3 | service: default 4 | 5 | # Use only a single instance, so that this local-memory-only chat app will work 6 | # consistently with multiple users. To work across multiple instances, an 7 | # extra-instance messaging system or data store would be needed. 8 | manual_scaling: 9 | instances: 1 10 | 11 | handlers: 12 | - url: /static 13 | static_dir: build/static 14 | 15 | - url: /(.*\.(json|ico|js))$ 16 | static_files: build/\1 17 | upload: build/.*\.(json|ico|js)$ 18 | 19 | - url: .* 20 | static_files: build/index.html 21 | upload: build/index.html 22 | -------------------------------------------------------------------------------- /cloudbuild.yaml: -------------------------------------------------------------------------------- 1 | steps: 2 | - name: node:14 3 | entrypoint: npm 4 | args: ['install', 'typescript'] 5 | - name: node:14 6 | entrypoint: npm 7 | args: ['install'] 8 | # run webpack prod script to create static files 9 | - name: node:14 10 | entrypoint: npm 11 | args: ['run','build'] 12 | env: 13 | - 'REACT_APP_API_KEY=${_API_KEY}' 14 | - 'REACT_APP_GA_TRACKING_ID=G-G5GWJ2XYRS' 15 | - 'DISABLE_ESLINT_PLUGIN=true' 16 | - 'REACT_APP_SESSION_SERVER=${_SESSION_SERVER}' 17 | - 'REACT_APP_PERSONA_AUTH_MODE=0' 18 | - 'REACT_APP_ORCHESTRATION_MODE=false' 19 | - 'GENERATE_SOURCEMAP=false' 20 | - name: "gcr.io/cloud-builders/gcloud" 21 | args: ["app", "deploy"] 22 | timeout: "1600s" 23 | -------------------------------------------------------------------------------- /docs/creating-custom-content-cards.md: -------------------------------------------------------------------------------- 1 | # Creating custom content cards 2 | 3 | Creating a custom content card is relatively simple and involves two main steps: creating your card component in `src/components/ContentCards/` and adding your card to the map in `src/components/ContentCardSwitch.js`. 4 | 5 | ## Creating a new content card component 6 | 7 | Content cards can be as simple or complex as you need. 8 | 9 | ### Predefined arguments 10 | 11 | Content cards are passed an object as the first arguments that contain at least four key-value pairs: `id`, `data`, `triggerRemoval`, and `inTranscript`. 12 | 13 | `id` is the name of the content card payload as defined in the corpus. When you call `@showCards(cardID)` in your dialog, the persona server will pass the value of `cardID` to the UI at the moment the speech marker is called, allowing you to show a content card at just the right time. 14 | 15 | Your conversation engineer should note that content cards name must be prefixed with `public-`, however this will be truncated by the persona server, and the value for `id` will be everything following the prefix. 16 | 17 | The `data` object contains whatever data payload you've defined in your corpus. For example, here's what a potential payload for an `options` content card could look like: 18 | ```json 19 | { 20 | "public-menuoptions": { 21 | "component": "options", 22 | "data": { 23 | "options": [ 24 | { 25 | "label": "First Option", 26 | "value": "first-option" 27 | }, 28 | { 29 | "label": "Second Option", 30 | "value": "second-option" 31 | } 32 | ] 33 | } 34 | } 35 | } 36 | ``` 37 | 38 | `triggerRemoval` is a function that the component can call if you need it to hide itself at an arbitrary time. For example, in the stock video component, the user is expected to click on the component several times, but we only want a click on "I'm done" to hide the card. 39 | 40 | `inTranscript` is a boolean value that indicates whether the content card is being displayed inside of the transcript. The transcript component will show content cards inline with the conversation history. It's important that content cards that take up a large portion of the screen (e.g. the video component) don't disrupt the experience when the transcript is open. In the case of the video component, when on display in the transcript, it renders itself as a small thumbnail that can be clicked on to open the full-screen video experience. 41 | 42 | ### Sending input to the NLP 43 | 44 | Text data can be sent to the NLP by dispatching events to the Redux store, which will interact with `smwebsdk`. `sendTextMessage` or `sendEvent` can be imported and the `connect` method from `react-redux` can be used to dispatch events to Redux. Here is a complete example of a minimal component that sends text and events when a button is pressed: 45 | 46 | ```jsx 47 | import React from 'react'; 48 | import { connect } from 'react-redux'; 49 | import { sendTextMessage, sendEvent } from '../../store/sm/index'; 50 | 51 | const CardThatSendsThings = ({ dispatchText, dispatchEvent, data }) => { 52 | const { textPayload, eventName, eventPayload } = data; 53 | const handleText = () => dispatchText(textPayload); 54 | const handleEvent = () => dispatchEvent({ eventName: eventName, payload: eventPayload }); 55 | 56 | return( 57 |
58 | Text:
61 | ); 62 | } 63 | 64 | const mapDispatchToProps = (dispatch) => ({ 65 | dispatchText: (text) => sendTextMessage({ text }), 66 | dispatchEvent: ({ eventName, payload }) => sendEvent({ eventName, payload }), 67 | }); 68 | 69 | export default connect(null, mapDispatchToProps)(CardThatSendsThings); 70 | ``` 71 | 72 | ## Connecting your component to `ContentCardSwitch` 73 | 74 | The `ContentCardSwitch` component maps the component key of the card payload to the proper React component. To add your component, add a key to the `componentMap` object with an object defining the component handler. `ContentCardSwitch` can also automatically hide a card once it's been clicked on—in this case, we'll set the value of `removeOnClick` to `true`. Using the previous example, we'll render the example card when the `component` key of the content card payload is set to `demoCard`: 75 | 76 | ```jsx 77 | import React from 'react'; 78 | import CardThatSendsThings from './ContentCards/CardThatSendsThings'; 79 | 80 | const ContentCardSwitch = ({ ... }) => { 81 | const componentMap = { 82 | ..., 83 | demoCard: { 84 | element: CardThatSendsThings, 85 | removeOnClick: true, 86 | }, 87 | }; 88 | ... 89 | ``` 90 | 91 | And to use our card in Dialogflow ES, we could create an utterance: `Here's the demo card we just created! @showCards(firstInstanceOfDemoCard)` and this accompanying payload: 92 | 93 | ```json 94 | { 95 | "soulmachines": { 96 | "public-firstInstanceOfDemoCard": { 97 | "component": "demoCard", 98 | "data": { 99 | "textPayload": "Hello world!", 100 | "eventName": "foo", 101 | "eventPayload": { "foo": "bar" } 102 | } 103 | } 104 | } 105 | } 106 | ``` 107 | When defining content card payloads in Dialogflow ES, the data must be a value of the `soulmachines` key. 108 | 109 | At the moment the `@showCards` marker is called, your content card should appear! -------------------------------------------------------------------------------- /docs/index.md: -------------------------------------------------------------------------------- 1 | This template succeeds the previous [react-template](https://github.com/soulmachines/react-template). This is a complete re-write based off of [create-react-app](https://github.com/facebook/create-react-app) and is designed mainly to provide a simpler and more familiar developer experience. 2 | 3 | This template serves as "opinionated documentation," in that it contains most of the functionality that UI's should have and how to use it. As members of Soul Machines Customer Success engineering, we believe this is a good example of how the user flow and interaction with the Digital Person should work. This template is provided with the expectation that most, if not all, of the styling will be altered. 4 | 5 | ## Setup 6 | 7 | You need a token server to authenticate the UI session with the Soul Machines Persona server. Either Soul Machines will provide an endpoint, or you will have to spin up an instance of [express-token-server](https://github.com/soulmachines/express-token-server) with your credentials from DDNA Studio. 8 | 9 | ### Copy `.env.example` contents into `.env` 10 | Create an empty text file called `.env` and copy the contents of `.env.example` into it. These environment variables are required for the UI to run. Set the value of `REACT_APP_TOKEN_URL` to the endpoint of your token server. Optionally, if you're using an orchestration server, set the value of 11 | 12 | ### `npm install` 13 | Run to install the project's dependencies. 14 | 15 | ### `npm start` 16 | Starts the development server. Open [http://localhost:3000](http://localhost:3000) to view it in the browser. The page will automatically reload when you make changes. 17 | 18 | ### `npm run build` 19 | Builds the app for production to the `build` folder. The files will be bundled and minified for production. 20 | 21 | ## Linting & Code Style 22 | 23 | This project strictly follows [AirBnB's JavaScript style guide](https://github.com/airbnb/javascript). We recommend you install [ESLint](https://eslint.org/) in your editor and adhere to its recommendations. 24 | 25 | We have also provided an `.editorconfig` file that you can use in your editor to match the indentation, whitespace, and other styling rules we used in creating this template. 26 | 27 | ## Docs 28 | - [Creating custom content cards](/creating-custom-content-cards) -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "react-reference-ui", 3 | "version": "1.0.0", 4 | "engines": { 5 | "node": ">=16" 6 | }, 7 | "private": true, 8 | "scripts": { 9 | "start": "npm run build && npx serve -s build", 10 | "dev": "react-scripts start", 11 | "build": "react-scripts build", 12 | "test": "react-scripts test", 13 | "eject": "react-scripts eject", 14 | "deploy:gcp": "npm run build && gcloud app deploy --project ui-test-persona-nhyv app.yaml --stop-previous-version --promote --version baseline --quiet" 15 | }, 16 | "dependencies": { 17 | "@juggle/resize-observer": "^3.3.1", 18 | "@reduxjs/toolkit": "^1.6.0", 19 | "@soulmachines/smwebsdk": "15.7.0", 20 | "@testing-library/jest-dom": "^5.14.1", 21 | "@testing-library/react": "^11.2.7", 22 | "@testing-library/user-event": "^12.8.3", 23 | "await-to-js": "^3.0.0", 24 | "bootstrap": "5.2.0-beta1", 25 | "color": "^4.2.3", 26 | "dotenv": "^8.2.0", 27 | "framer-motion": "^4.1.17", 28 | "prop-types": "^15.7.2", 29 | "react": "^17.0.2", 30 | "react-bootstrap-icons": "^1.10.2", 31 | "react-dom": "^17.0.2", 32 | "react-ga": "^3.3.1", 33 | "react-ga4": "^1.4.1", 34 | "react-markdown": "^6.0.2", 35 | "react-redux": "^7.2.4", 36 | "react-router-dom": "^5.2.0", 37 | "react-scripts": "5.0.1", 38 | "react-tooltip": "^4.2.21", 39 | "react-youtube": "^7.13.1", 40 | "redux": "^4.1.0", 41 | "redux-thunk": "^2.3.0", 42 | "rehype-sanitize": "^5.0.0", 43 | "remark-gfm": "^2.0.0", 44 | "styled-components": "^5.3.0", 45 | "syllable": "^5.0.0", 46 | "web-vitals": "^1.1.2" 47 | }, 48 | "eslintConfig": { 49 | "extends": [ 50 | "react-app", 51 | "react-app/jest" 52 | ] 53 | }, 54 | "browserslist": { 55 | "production": [ 56 | ">0.2%", 57 | "not dead", 58 | "not op_mini all" 59 | ], 60 | "development": [ 61 | "last 1 chrome version", 62 | "last 1 firefox version", 63 | "last 1 safari version" 64 | ] 65 | }, 66 | "devDependencies": { 67 | "@typescript-eslint/eslint-plugin": "^5.29.0", 68 | "@typescript-eslint/parser": "^5.29.0", 69 | "eslint": "^8.18.0", 70 | "eslint-config-airbnb": "^19.0.4", 71 | "eslint-plugin-import": "^2.26.0", 72 | "eslint-plugin-jsx-a11y": "^6.5.1", 73 | "eslint-plugin-react": "^7.30.0", 74 | "eslint-plugin-react-hooks": "^4.6.0" 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/soulmachines/react-reference-ui-public/352672b9df1c4050c15e2d4de4d52cc36a1cd97d/public/favicon.ico -------------------------------------------------------------------------------- /public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 12 | 13 | 17 | 18 | 27 | React Reference UI Template 28 | 29 | 30 | 31 |
32 | 42 | 43 | 44 | 45 | 46 | -------------------------------------------------------------------------------- /public/logo192.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/soulmachines/react-reference-ui-public/352672b9df1c4050c15e2d4de4d52cc36a1cd97d/public/logo192.png -------------------------------------------------------------------------------- /public/logo512.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/soulmachines/react-reference-ui-public/352672b9df1c4050c15e2d4de4d52cc36a1cd97d/public/logo512.png -------------------------------------------------------------------------------- /public/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "short_name": "React App", 3 | "name": "Create React App Sample", 4 | "icons": [ 5 | { 6 | "src": "favicon.ico", 7 | "sizes": "64x64 32x32 24x24 16x16", 8 | "type": "image/x-icon" 9 | }, 10 | { 11 | "src": "logo192.png", 12 | "type": "image/png", 13 | "sizes": "192x192" 14 | }, 15 | { 16 | "src": "logo512.png", 17 | "type": "image/png", 18 | "sizes": "512x512" 19 | } 20 | ], 21 | "start_url": ".", 22 | "display": "standalone", 23 | "theme_color": "#000000", 24 | "background_color": "#ffffff" 25 | } 26 | -------------------------------------------------------------------------------- /public/robots.txt: -------------------------------------------------------------------------------- 1 | # https://www.robotstxt.org/robotstxt.html 2 | User-agent: * 3 | Disallow: 4 | -------------------------------------------------------------------------------- /src/Router.js: -------------------------------------------------------------------------------- 1 | import ReactGA from 'react-ga4'; 2 | import React, { useEffect, useState } from 'react'; 3 | import 'bootstrap/dist/css/bootstrap.min.css'; 4 | import { 5 | BrowserRouter as Router, 6 | Switch, 7 | Route, 8 | withRouter, 9 | Link, 10 | } from 'react-router-dom'; 11 | import { useSelector } from 'react-redux'; 12 | import { XCircle } from 'react-bootstrap-icons'; 13 | import DPChat from './routes/DPChat'; 14 | import Landing from './routes/Landing'; 15 | import Loading from './routes/Loading'; 16 | import Feedback from './routes/FeedbackRoute'; 17 | import ContentCardTest from './routes/ContentCardTest'; 18 | 19 | // only init google analytics if a tracking ID is defined in env 20 | const { REACT_APP_GA_TRACKING_ID } = process.env; 21 | if (REACT_APP_GA_TRACKING_ID) { 22 | ReactGA.initialize(REACT_APP_GA_TRACKING_ID, { debug: true }); 23 | console.log(`initializing google analytics with tracking ID ${REACT_APP_GA_TRACKING_ID}`); 24 | } else console.warn('no google analytics tracking ID provided!'); 25 | 26 | // make GA aware of what pages people navigate to in react router 27 | const LinkGAtoRouter = withRouter(({ history }) => { 28 | history.listen((location) => { 29 | ReactGA.set({ page: location.pathname }); 30 | }); 31 | return null; 32 | }); 33 | 34 | function App() { 35 | const { error } = useSelector(({ sm }) => ({ ...sm })); 36 | const [ignoreError, setIgnoreError] = useState(false); 37 | // every time error changes, set ignore error to false 38 | useEffect(() => setIgnoreError(false), [error]); 39 | 40 | // send SM session ID to google analytics when we connect 41 | if (REACT_APP_GA_TRACKING_ID) { 42 | const sessionID = useSelector(({ sm }) => sm.sessionID); 43 | useEffect(() => { 44 | if (sessionID !== '') ReactGA.gtag('event', 'sm_session_id', { sm_session_id: sessionID }); 45 | }, [sessionID]); 46 | } 47 | 48 | return ( 49 | 50 | { error && !ignoreError 51 | ? ( 52 |
53 |
54 |
55 | 58 |
59 |
60 |

61 | Something has gone wrong! 62 |

63 |

64 | Sorry for the interruption. 65 | Feel free to start again, or give us some feedback to help us improve! 66 |

67 |
68 | Reconnect 69 | Return to Main Page 70 |
71 |
72 | {error.msg} 73 |
74 |
75 |
76 |
77 | ) : null} 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | {/* / goes at the bottom */} 92 | 93 | 94 | 95 | 96 | 97 |
98 | ); 99 | } 100 | 101 | export default App; 102 | -------------------------------------------------------------------------------- /src/components/CameraPreview.js: -------------------------------------------------------------------------------- 1 | import React, { useEffect } from 'react'; 2 | import { connect } from 'react-redux'; 3 | import styled from 'styled-components'; 4 | import PropTypes from 'prop-types'; 5 | // import { CameraVideoOff } from 'react-bootstrap-icons'; 6 | import { mediaStreamProxy } from '../proxyVideo'; 7 | 8 | function CameraPreview({ connected, className, cameraOn }) { 9 | const videoRef = React.createRef(); 10 | const stream = mediaStreamProxy.getUserMediaStream(); 11 | 12 | useEffect(() => { 13 | if (stream !== null && mediaStreamProxy.videoOff === false) { 14 | // display webcam preview in video elem 15 | videoRef.current.srcObject = stream; 16 | } 17 | }, [connected]); 18 | 19 | // disable camera preview if camera is off 20 | // in the future, if smwebsdk supports toggling the camera on and off, remove this line 21 | if (cameraOn === false) return null; 22 | 23 | return ( 24 |
25 | {/* NOTE: toggleVideo behavior is not supported by smwebsdk so it's not recommended */} 26 | {/* */} 37 |
38 | 39 | ); 40 | } 41 | 42 | CameraPreview.propTypes = { 43 | connected: PropTypes.bool.isRequired, 44 | className: PropTypes.string.isRequired, 45 | cameraOn: PropTypes.bool.isRequired, 46 | }; 47 | 48 | const StyledCameraPreview = styled(CameraPreview)` 49 | display: ${({ connected }) => (connected ? '' : 'none')}; 50 | align-items: center; 51 | height: ${({ size }) => size || 4}rem; 52 | 53 | .video-button { 54 | display: flex; 55 | justify-content: center; 56 | align-items: center; 57 | 58 | padding: 0; 59 | height: ${({ size }) => size || 4}rem; 60 | aspect-ratio: ${({ cameraWidth, cameraHeight }) => cameraWidth / cameraHeight}; 61 | 62 | border-radius: 3px; 63 | background: rgba(0,0,0,0.2); 64 | border: ${({ cameraOn }) => (cameraOn ? 'none' : '1px solid gray')}; 65 | } 66 | 67 | video { 68 | height: ${({ size }) => size || 4}rem; 69 | transform: rotateY(180deg); 70 | aspect-ratio: ${({ cameraWidth, cameraHeight }) => cameraWidth / cameraHeight}; 71 | border-radius: 3px; 72 | z-index: 20; 73 | } 74 | `; 75 | 76 | const mapStateToProps = ({ sm }) => ({ 77 | connected: sm.connected, 78 | cameraOn: sm.cameraOn, 79 | cameraWidth: sm.cameraWidth, 80 | cameraHeight: sm.cameraHeight, 81 | }); 82 | 83 | export default connect(mapStateToProps)(StyledCameraPreview); 84 | -------------------------------------------------------------------------------- /src/components/Captions.js: -------------------------------------------------------------------------------- 1 | import React, { useState, useEffect } from 'react'; 2 | import { connect } from 'react-redux'; 3 | import styled from 'styled-components'; 4 | import PropTypes from 'prop-types'; 5 | import { syllable } from 'syllable'; 6 | 7 | function Captions({ 8 | speechState, lastPersonaUtterance, className, connected, 9 | }) { 10 | const [showCaptions, setShowCaptions] = useState(false); 11 | // if we have a very long response, we need to cycle the displayed content 12 | const [captionText, setCaptionText] = useState(''); 13 | // keep track of when we first showed this caption. captions should be on screen min 1.5s 14 | const [captionStartTimestamp, setCaptionStartTimestamp] = useState(); 15 | const [captionTimeout, setCaptionsTimeout] = useState(); 16 | const minCaptionDuration = 1500; 17 | 18 | useEffect(() => { 19 | if (connected === false) setShowCaptions(false); 20 | else if (speechState === 'speaking') { 21 | // when a new utterance starts, show captions 22 | setShowCaptions(true); 23 | const sentences = lastPersonaUtterance.split('. '); 24 | // estimate how long each caption should be displayed based on # of syllables and punctuation 25 | const sentencesWithDurationEstimate = sentences.map((s) => { 26 | const millisPerSyllable = 210; 27 | const millisPerPunct = 330; 28 | 29 | const syllableCount = syllable(s); 30 | 31 | const regex = /[^\w ]/gm; 32 | const punctCount = [...s.matchAll(regex)].length; 33 | 34 | const durationEstimate = (syllableCount * millisPerSyllable) 35 | + (punctCount * millisPerPunct) 36 | // add one punct delay for the period that gets stripped when splitting the sentences 37 | + millisPerPunct; 38 | return { text: s, durationEstimate }; 39 | }); 40 | 41 | // recursively cycle through sentences on very long captions 42 | const displayCaption = (i) => { 43 | const { text, durationEstimate } = sentencesWithDurationEstimate[i]; 44 | setCaptionText(text); 45 | if (sentencesWithDurationEstimate[i + 1]) { 46 | setTimeout(() => displayCaption(i + 1), durationEstimate); 47 | } 48 | }; 49 | displayCaption(0); 50 | 51 | // record when we put captions on the screen 52 | setCaptionStartTimestamp(Date.now()); 53 | // clear any previous timeout from previous captions. 54 | // this won't make the captions disappear, since we're overwriting the content 55 | clearTimeout(captionTimeout); 56 | } else { 57 | // when the utterance ends: 58 | const captionsDisplayedFor = Date.now() - captionStartTimestamp; 59 | // check to see if the captions have been displayed for the min. amount of time 60 | if (captionsDisplayedFor > minCaptionDuration) setShowCaptions(false); 61 | // if not, set a timeout to hide them when it has elapsed 62 | else { 63 | const newCaptionTimeout = setTimeout(() => { 64 | setShowCaptions(false); 65 | }, minCaptionDuration - captionsDisplayedFor); 66 | setCaptionsTimeout(newCaptionTimeout); 67 | } 68 | // sometimes we get blank input, hide that when it happens 69 | if (captionText === '') setShowCaptions(false); 70 | } 71 | }, [speechState, connected]); 72 | 73 | if (showCaptions === false) return null; 74 | 75 | return ( 76 |
77 |
78 | { showCaptions ? captionText : null } 79 |
80 |
81 | ); 82 | } 83 | 84 | Captions.propTypes = { 85 | speechState: PropTypes.string.isRequired, 86 | lastPersonaUtterance: PropTypes.string.isRequired, 87 | className: PropTypes.string.isRequired, 88 | connected: PropTypes.bool.isRequired, 89 | }; 90 | 91 | const StyledCaptions = styled(Captions)` 92 | display: inline-block; 93 | .captions { 94 | margin-bottom: .3rem; 95 | 96 | padding-top: 0.3rem; 97 | padding-bottom: 0.3rem; 98 | padding-left: 0.6rem; 99 | padding-right: 0.6rem; 100 | 101 | background-color: rgba(0, 0, 0, 0.7); 102 | color: #FFF; 103 | 104 | border-radius: 2px; 105 | 106 | display: flex; 107 | align-items: center; 108 | 109 | min-height: 35px; 110 | transition: height 0.3s; 111 | } 112 | `; 113 | 114 | const mapStateToProps = (state) => ({ 115 | speechState: state.sm.speechState, 116 | lastPersonaUtterance: state.sm.lastPersonaUtterance, 117 | connected: state.sm.connected, 118 | }); 119 | 120 | export default connect(mapStateToProps)(StyledCaptions); 121 | -------------------------------------------------------------------------------- /src/components/ContentCardDisplay.js: -------------------------------------------------------------------------------- 1 | import React, { useEffect } from 'react'; 2 | import { connect } from 'react-redux'; 3 | import PropTypes from 'prop-types'; 4 | import styled from 'styled-components'; 5 | import { setActiveCards, animateCamera } from '../store/sm/index'; 6 | // uncomment if using manual camera moves 7 | // import { calculateCameraPosition } from '../utils/camera'; 8 | import Transcript from './ContentCards/Transcript'; 9 | import ContentCardSwitch from './ContentCardSwitch'; 10 | import breakpoints from '../utils/breakpoints'; 11 | 12 | function ContentCardDisplay({ 13 | activeCards, 14 | // uncomment if using manual camera moves 15 | // dispatchAnimateCamera, 16 | // videoWidth, 17 | // videoHeight, 18 | showTranscript, 19 | className, 20 | connected, 21 | inTranscript, 22 | }) { 23 | if (!activeCards) return null; 24 | const CardDisplay = activeCards.map((c, index) => ( 25 |
26 | 27 |
28 | )); 29 | 30 | const animateCameraToFitCards = () => { 31 | if (connected) { 32 | // uncomment if using manual camera moves 33 | // if ((activeCards.length > 0 || showTranscript === true) && videoWidth >= breakpoints.md) { 34 | // dispatchAnimateCamera(calculateCameraPosition(videoWidth, videoHeight, 0.7)); 35 | // } else dispatchAnimateCamera(calculateCameraPosition(videoWidth, videoHeight, 0.5)); 36 | } 37 | }; 38 | 39 | useEffect(() => { 40 | animateCameraToFitCards(); 41 | }, [showTranscript, activeCards]); 42 | 43 | useEffect(() => { 44 | window.addEventListener('resize', animateCameraToFitCards); 45 | return () => window.removeEventListener('resize', animateCameraToFitCards); 46 | }); 47 | 48 | return ( 49 |
50 | {showTranscript ? ( 51 |
52 | 53 |
54 | ) : ( 55 | CardDisplay 56 | )} 57 |
58 | ); 59 | } 60 | 61 | ContentCardDisplay.propTypes = { 62 | // eslint-disable-next-line react/forbid-prop-types 63 | activeCards: PropTypes.arrayOf(PropTypes.object).isRequired, 64 | // uncomment if using manual camera moves 65 | // dispatchAnimateCamera: PropTypes.func.isRequired, 66 | // videoWidth: PropTypes.number.isRequired, 67 | // videoHeight: PropTypes.number.isRequired, 68 | showTranscript: PropTypes.bool.isRequired, 69 | className: PropTypes.string.isRequired, 70 | connected: PropTypes.bool.isRequired, 71 | inTranscript: PropTypes.bool, 72 | }; 73 | 74 | ContentCardDisplay.defaultProps = { 75 | inTranscript: false, 76 | }; 77 | 78 | const StyledContentCardDisplay = styled(ContentCardDisplay)` 79 | overflow-y: scroll; 80 | margin-bottom: 0.9rem; 81 | 82 | scrollbar-width: none; 83 | &::-webkit-scrollbar { 84 | display: none; 85 | } 86 | 87 | // make this smaller 88 | max-height: 40vh; 89 | @media(min-width: ${breakpoints.md}px) { 90 | max-height: 100%; 91 | background: none; 92 | outline: none; 93 | margin-bottom: auto; 94 | } 95 | width: 100%; 96 | `; 97 | 98 | const mapStateToProps = ({ sm }) => ({ 99 | activeCards: sm.activeCards, 100 | videoWidth: sm.videoWidth, 101 | videoHeight: sm.videoHeight, 102 | showTranscript: sm.showTranscript, 103 | connected: sm.connected, 104 | }); 105 | 106 | const mapDispatchToProps = (dispatch) => ({ 107 | dispatchActiveCards: (activeCards) => dispatch( 108 | // the next time the persona speaks, if the cards are stale, it will clear them. 109 | // if this value isn't desired, don't set this value to true. 110 | setActiveCards({ activeCards, cardsAreStale: true }), 111 | ), 112 | dispatchAnimateCamera: (options, duration = 1) => dispatch(animateCamera({ options, duration })), 113 | }); 114 | 115 | export default connect(mapStateToProps, mapDispatchToProps)(StyledContentCardDisplay); 116 | -------------------------------------------------------------------------------- /src/components/ContentCardSwitch.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { connect } from 'react-redux'; 3 | import PropTypes from 'prop-types'; 4 | import Options from './ContentCards/Options'; 5 | import Markdown from './ContentCards/Markdown'; 6 | import Link from './ContentCards/Link'; 7 | import Image from './ContentCards/Image'; 8 | import Video from './ContentCards/Video'; 9 | import { setActiveCards, animateCamera } from '../store/sm/index'; 10 | import ImageCarousel from './ContentCards/ImageCarousel'; 11 | 12 | const returnCardError = (errMsg) => { 13 | console.error(errMsg); 14 | return
{errMsg}
; 15 | }; 16 | 17 | function ContentCardSwitch({ 18 | activeCards, 19 | dispatchActiveCards, 20 | card, 21 | index, 22 | inTranscript, 23 | triggerScrollIntoView, 24 | }) { 25 | const componentMap = { 26 | options: { 27 | element: Options, 28 | removeOnClick: true, 29 | }, 30 | markdown: { 31 | element: Markdown, 32 | removeOnClick: false, 33 | }, 34 | externalLink: { 35 | element: Link, 36 | removeOnClick: false, 37 | }, 38 | image: { 39 | element: Image, 40 | removeOnClick: false, 41 | }, 42 | imageCarousel: { 43 | element: ImageCarousel, 44 | removeOnClick: false, 45 | }, 46 | video: { 47 | element: Video, 48 | removeOnClick: false, 49 | }, 50 | }; 51 | 52 | if ('type' in card === false) { 53 | return returnCardError( 54 | 'payload missing type key! component key has been depreciated.', 55 | ); 56 | } 57 | if (card === undefined) { 58 | return returnCardError( 59 | 'unknown content card name! did you make a typo in @showCards()?', 60 | ); 61 | } 62 | const { data, id, type: componentName } = card; 63 | 64 | if (componentName in componentMap === false) { 65 | return returnCardError( 66 | `component ${componentName} not found in componentMap!`, 67 | ); 68 | } 69 | const { element: Element, removeOnClick } = componentMap[componentName]; 70 | 71 | let removeElem; 72 | if (index) { 73 | // for some cards, we want them to be hidden after the user interacts w/ them 74 | // for others, we don't 75 | removeElem = (e) => { 76 | // we need to write our own handler, since this is not an interactive element by default 77 | if (e.type === 'click' || e.code === 'enter') { 78 | const newActiveCards = [ 79 | ...activeCards.slice(0, index), 80 | ...activeCards.slice(index + 1), 81 | ]; 82 | dispatchActiveCards(newActiveCards); 83 | } 84 | }; 85 | } else { 86 | removeElem = null; 87 | } 88 | const elem = ( 89 | // disable no static element interactions bc if removeOnClick is true, 90 | // elem should have interactive children 91 | // eslint-disable-next-line jsx-a11y/no-static-element-interactions 92 |
98 | {/* elements that are interactive but shouldn't be removed immediately 99 | can use triggerRemoval to have the card removed */} 100 | 107 |
108 | ); 109 | return elem; 110 | } 111 | 112 | ContentCardSwitch.propTypes = { 113 | activeCards: PropTypes.arrayOf( 114 | PropTypes.shape({ 115 | type: PropTypes.string, 116 | // eslint-disable-next-line react/forbid-prop-types 117 | data: PropTypes.object, 118 | }), 119 | ).isRequired, 120 | dispatchActiveCards: PropTypes.func.isRequired, 121 | inTranscript: PropTypes.bool, 122 | // eslint-disable-next-line react/forbid-prop-types 123 | card: PropTypes.object.isRequired, 124 | index: PropTypes.number.isRequired, 125 | triggerScrollIntoView: PropTypes.func, 126 | }; 127 | 128 | ContentCardSwitch.defaultProps = { 129 | inTranscript: false, 130 | triggerScrollIntoView: () => console.warn('triggerScrollIntoView is not passed in as a prop—this content card will not be able to influence transcript scrolling!'), 131 | }; 132 | 133 | const mapStateToProps = ({ sm }) => ({ 134 | activeCards: sm.activeCards, 135 | videoWidth: sm.videoWidth, 136 | videoHeight: sm.videoHeight, 137 | showTranscript: sm.showTranscript, 138 | }); 139 | 140 | const mapDispatchToProps = (dispatch) => ({ 141 | dispatchActiveCards: (activeCards) => dispatch( 142 | setActiveCards({ activeCards, cardsAreStale: true }), 143 | ), 144 | dispatchAnimateCamera: (options, duration = 1) => dispatch(animateCamera({ options, duration })), 145 | }); 146 | export default connect(mapStateToProps, mapDispatchToProps)(ContentCardSwitch); 147 | -------------------------------------------------------------------------------- /src/components/ContentCards/Image.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import PropTypes from 'prop-types'; 3 | import styled from 'styled-components'; 4 | 5 | function Image({ data, className, triggerScrollIntoView }) { 6 | const { url, alt, caption } = data; 7 | return ( 8 |
9 |
10 | {alt} 16 | {caption ?
{caption}
: null} 17 |
18 |
19 | ); 20 | } 21 | 22 | Image.propTypes = { 23 | data: PropTypes.shape({ 24 | url: PropTypes.string, 25 | alt: PropTypes.string, 26 | caption: PropTypes.string, 27 | }).isRequired, 28 | className: PropTypes.string.isRequired, 29 | triggerScrollIntoView: PropTypes.func.isRequired, 30 | }; 31 | 32 | export default styled(Image)` 33 | border-radius: 10px; 34 | border: 1px solid rgba(0,0,0,0.2); 35 | overflow: hidden; 36 | 37 | background: #393939; 38 | color: #FFF; 39 | `; 40 | -------------------------------------------------------------------------------- /src/components/ContentCards/ImageCarousel.js: -------------------------------------------------------------------------------- 1 | import React, { createRef, useEffect, useState } from 'react'; 2 | import PropTypes from 'prop-types'; 3 | import styled from 'styled-components'; 4 | import { ArrowLeftCircle, ArrowRightCircle } from 'react-bootstrap-icons'; 5 | import Image from './Image'; 6 | 7 | function ImageCarousel({ 8 | data, 9 | className, 10 | inTranscript, 11 | triggerScrollIntoView, 12 | }) { 13 | const { images } = data; 14 | const refs = []; 15 | const [viewIndex, setViewIndex] = useState(0); 16 | 17 | if (images.length <= 0) { 18 | return ( 19 |
20 | image carousel payload contains no images! 21 |
{JSON.stringify(data, null, 2)}
22 |
23 | ); 24 | } 25 | 26 | useEffect(() => { 27 | if (refs[viewIndex]?.current) { 28 | refs[viewIndex].current.scrollIntoView({ behavior: 'smooth' }); 29 | } else { 30 | console.error("can't find ref! check your payload."); 31 | } 32 | }, [viewIndex]); 33 | 34 | const carousel = images.map((imData) => { 35 | const imgRef = createRef(); 36 | refs.push(imgRef); 37 | return ( 38 |
39 | 40 |
41 | ); 42 | }); 43 | 44 | return ( 45 |
46 |
{carousel}
47 |
48 | 56 |
57 |
58 |
62 |
70 |
71 | {/* make position absolute so it takes up zero height, 72 | makes vertical centering progress bar easier */} 73 | {inTranscript ? null : ( 74 |
75 | {`${viewIndex + 1}`} 76 | {` of ${images.length} images`} 77 |
78 | )} 79 |
80 | 88 |
89 |
90 | ); 91 | } 92 | 93 | ImageCarousel.propTypes = { 94 | data: PropTypes.shape({ 95 | images: PropTypes.arrayOf( 96 | PropTypes.shape({ 97 | data: { 98 | url: PropTypes.string, 99 | alt: PropTypes.string, 100 | caption: PropTypes.string, 101 | }, 102 | }), 103 | ), 104 | }).isRequired, 105 | className: PropTypes.string.isRequired, 106 | inTranscript: PropTypes.bool.isRequired, 107 | triggerScrollIntoView: PropTypes.func.isRequired, 108 | }; 109 | 110 | export default styled(ImageCarousel)` 111 | .image-carousel-wrapper { 112 | display: flex; 113 | min-height: 100%; 114 | overflow-x: hidden; 115 | } 116 | 117 | .image-carousel-item { 118 | min-width: 90%; 119 | position: relative; 120 | &>div { 121 | margin-right: 1rem; 122 | height: 100%; 123 | width: auto; 124 | } 125 | } 126 | 127 | .progress-bar { 128 | border-top: 2px solid; 129 | border-radius: 1px; 130 | } 131 | .progress-bar-dark { 132 | border-color: rgba(0,0,0,0.9); 133 | } 134 | .progress-bar-light { 135 | border-color: rgba(0,0,0,0.18); 136 | } 137 | `; 138 | -------------------------------------------------------------------------------- /src/components/ContentCards/Link.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import PropTypes from 'prop-types'; 3 | import styled from 'styled-components'; 4 | import { ArrowUpRightSquare } from 'react-bootstrap-icons'; 5 | 6 | function Link({ data, className }) { 7 | const { 8 | title, url, imageUrl, description, imageAltText, 9 | } = data; 10 | return ( 11 |
12 |
13 |
14 | {imageAltText 15 |
16 |
17 |
{title}
18 |

{description}

19 |
20 | {/* open link in new tab */} 21 | 22 | Visit Link 23 | 24 | 25 |
26 |
27 |
28 |
29 | ); 30 | } 31 | 32 | Link.propTypes = { 33 | data: PropTypes.objectOf({ 34 | url: PropTypes.string.isRequired, 35 | title: PropTypes.string.isRequired, 36 | imageUrl: PropTypes.string.isRequired, 37 | description: PropTypes.string.isRequired, 38 | imageAltText: PropTypes.string, 39 | }).isRequired, 40 | className: PropTypes.string.isRequired, 41 | }; 42 | 43 | export default styled(Link)` 44 | width: 20rem; 45 | 46 | img { 47 | width: 100%; 48 | height: auto; 49 | } 50 | `; 51 | -------------------------------------------------------------------------------- /src/components/ContentCards/Markdown.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import ReactMarkdown from 'react-markdown'; 3 | import PropTypes from 'prop-types'; 4 | 5 | function Markdown({ data }) { 6 | const { text } = data; 7 | return ( 8 |
9 |
10 | {text} 11 |
12 |
13 | ); 14 | } 15 | 16 | Markdown.propTypes = { 17 | data: PropTypes.shape({ 18 | text: PropTypes.string.isRequired, 19 | }).isRequired, 20 | }; 21 | 22 | export default Markdown; 23 | -------------------------------------------------------------------------------- /src/components/ContentCards/Options.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { connect, useSelector } from 'react-redux'; 3 | import PropTypes from 'prop-types'; 4 | import { BoxArrowUpRight } from 'react-bootstrap-icons'; 5 | import { sendTextMessage } from '../../store/sm/index'; 6 | 7 | function Options({ 8 | data, dispatchTextFromData, transcriptIndex, inTranscript, 9 | }) { 10 | const { options, title } = data; 11 | const { transcript } = useSelector(({ sm }) => ({ ...sm })); 12 | 13 | if (options?.length <= 0 || options === undefined) return 'missing values for options!'; 14 | 15 | const isStaleOptionsCardInTranscript = inTranscript === true 16 | && transcriptIndex < transcript.length - 1; 17 | 18 | try { 19 | const optionsDisplay = options.map(({ label, value }) => { 20 | const isLink = value?.indexOf('://') > -1; 21 | if (isLink) { 22 | return ( 23 | 30 | {label} 31 | 32 | 33 | ); 34 | } 35 | return ( 36 | 46 | ); 47 | }); 48 | return ( 49 |
50 | { 51 | title ?

{title}

: null 52 | } 53 |
54 | {optionsDisplay} 55 |
56 |
57 | ); 58 | } catch { 59 | return 'options card error—check console for more info!'; 60 | } 61 | } 62 | 63 | Options.propTypes = { 64 | data: PropTypes.shape({ 65 | title: PropTypes.string, 66 | options: PropTypes.arrayOf(PropTypes.shape({ 67 | label: PropTypes.string, 68 | value: PropTypes.string, 69 | })), 70 | }).isRequired, 71 | dispatchTextFromData: PropTypes.func.isRequired, 72 | transcriptIndex: PropTypes.number.isRequired, 73 | inTranscript: PropTypes.bool.isRequired, 74 | }; 75 | 76 | const mapDispatchToProps = (dispatch) => ({ 77 | dispatchTextFromData: (e) => dispatch(sendTextMessage({ text: e.target.dataset.triggerText })), 78 | }); 79 | 80 | export default connect(null, mapDispatchToProps)(Options); 81 | -------------------------------------------------------------------------------- /src/components/ContentCards/Transcript.js: -------------------------------------------------------------------------------- 1 | import React, { useEffect, useState } from 'react'; 2 | import { connect } from 'react-redux'; 3 | import styled from 'styled-components'; 4 | import PropTypes from 'prop-types'; 5 | import ContentCardSwitch from '../ContentCardSwitch'; 6 | import { primaryAccent } from '../../globalStyle'; 7 | 8 | function Transcript({ className, transcript }) { 9 | // scroll to bottom of transcript whenever it updates 10 | let scrollRef; 11 | const [isMounting, setIsMounting] = useState(true); 12 | useEffect(() => { 13 | setIsMounting(false); 14 | return () => setIsMounting(true); 15 | }); 16 | // state value is arbitrary, we just need it to change to trigger the effect hook 17 | const [triggerScrollIntoView, setTriggerScroll] = useState(false); 18 | useEffect(() => { 19 | scrollRef.scrollIntoView({ behavior: isMounting ? 'auto' : 'smooth' }); 20 | setTriggerScroll(false); 21 | }, [transcript, triggerScrollIntoView]); 22 | 23 | const transcriptDisplay = transcript.map(({ 24 | source, text, card, timestamp, 25 | }, index) => { 26 | // we don't want to wrap cards in a bubble, return as is w/ a key added 27 | if (card) { 28 | return ( 29 | setTriggerScroll(true)} 34 | inTranscript 35 | /> 36 | ); 37 | } 38 | if (!text || text?.length === 0) return null; 39 | return ( 40 |
41 |
42 |
43 | 44 | {source === 'user' ? 'You' : 'Digital Person A'} 45 | 46 |
47 |
48 | {text} 49 |
50 |
51 |
52 | ); 53 | }); 54 | 55 | return ( 56 |
57 |
58 | {transcriptDisplay.length > 0 59 | ? transcriptDisplay 60 | : ( 61 |
  • 62 | No items to show, say something! 63 |
  • 64 | )} 65 | {/* height added because safari doesn't display zero height elems, 66 | so the scroll behavior doesn't work */} 67 |
    { scrollRef = el; }} style={{ clear: 'both', height: '1px' }} /> 68 |
    69 |
    70 | ); 71 | } 72 | 73 | Transcript.propTypes = { 74 | className: PropTypes.string.isRequired, 75 | transcript: PropTypes.arrayOf(PropTypes.shape({ 76 | source: PropTypes.string, 77 | text: PropTypes.string, 78 | timestamp: PropTypes.string, 79 | })).isRequired, 80 | }; 81 | 82 | const StyledTranscript = styled(Transcript)` 83 | width: 100%; 84 | 85 | .transcript-list-group { 86 | flex-shrink: 1; 87 | display: flex; 88 | flex-direction: column; 89 | overflow-y: scroll; 90 | scrollbar-width: none; 91 | 92 | &::-webkit-scrollbar { 93 | display: none; 94 | } 95 | } 96 | 97 | .transcript-entry { 98 | margin-bottom: 0.8rem; 99 | small { 100 | display: block; 101 | color: #B2B2B2; 102 | padding-bottom: 0.2rem; 103 | } 104 | } 105 | 106 | .transcript-entry-content { 107 | padding: 24px 20px; 108 | } 109 | 110 | .transcript-entry-persona { 111 | float: left; 112 | 113 | .transcript-entry-content { 114 | border-top-right-radius: 1.1rem; 115 | border-top-left-radius: 1.1rem; 116 | border-bottom-right-radius: 1.1rem; 117 | 118 | background: ${primaryAccent}; 119 | color: #FFF; 120 | } 121 | } 122 | .transcript-entry-user { 123 | float: right; 124 | 125 | small { 126 | text-align: right; 127 | } 128 | .transcript-entry-content { 129 | border-top-right-radius: 1.1rem; 130 | border-top-left-radius: 1.1rem; 131 | border-bottom-left-radius: 1.1rem; 132 | 133 | background: #FFF; 134 | border: 1px solid rgba(0,0,0,0.3); 135 | } 136 | } 137 | `; 138 | 139 | const mapStateToProps = ({ sm }) => ({ 140 | transcript: sm.transcript, 141 | }); 142 | 143 | export default connect(mapStateToProps)(StyledTranscript); 144 | -------------------------------------------------------------------------------- /src/components/ContentCards/Video.js: -------------------------------------------------------------------------------- 1 | import React, { useState, useEffect } from 'react'; 2 | import YouTube from 'react-youtube'; 3 | import PropTypes from 'prop-types'; 4 | import styled from 'styled-components'; 5 | import { useDispatch, useSelector } from 'react-redux'; 6 | import { 7 | setMicOn, sendTextMessage, keepAlive, setShowTranscript, setActiveCards, stopSpeaking, 8 | } from '../../store/sm/index'; 9 | 10 | function Video({ 11 | data, 12 | className, 13 | inTranscript, 14 | }) { 15 | const { videoId } = data; 16 | if (videoId === undefined) return
    no value for videoId!
    ; 17 | 18 | const thumbnailURL = `http://img.youtube.com/vi/${videoId}/0.jpg`; 19 | 20 | const dispatch = useDispatch(); 21 | 22 | const { showTranscript, micOn, activeCards } = useSelector(({ sm }) => ( 23 | { 24 | showTranscript: sm.showTranscript, 25 | micOn: sm.micOn, 26 | activeCards: sm.activeCards, 27 | })); 28 | const [playPushed, setPlayPushed] = useState(false); 29 | // in order to most easily let the application pull up the video when the user wants to 30 | // watch something again, we just modify activeCards. 31 | // this could be a problem if we need to know if it's actually a part of the conversation, 32 | // so we prevent this by checking separately if the videoID matches and if it's being rewatched 33 | const isActiveCard = activeCards[0]?.data?.videoId === videoId; 34 | const isRewatch = activeCards[0]?.data?.isRewatch === true; 35 | 36 | // we need to store if the transcript is open and if the mic is on while the video plays 37 | const captureStateAndPrepForPlay = (lockWrites = false) => { 38 | const rawStored = sessionStorage.getItem('uiStateBeforeVideo'); 39 | const stored = JSON.parse(rawStored); 40 | const writesLocked = 'writesLocked' in stored ? stored.writesLocked : false; 41 | // store UI state data only if it wasn't recently stored by another hook call/component remount 42 | if (writesLocked !== true 43 | || (isActiveCard && !isRewatch && !writesLocked)) { 44 | sessionStorage.setItem( 45 | 'uiStateBeforeVideo', 46 | JSON.stringify({ showTranscript, micOn, writesLocked: lockWrites }), 47 | ); 48 | } else setPlayPushed(true); 49 | dispatch(setShowTranscript(false)); 50 | dispatch(setMicOn({ micOn: false })); 51 | }; 52 | 53 | useEffect(() => { 54 | let prevWritesLocked = false; 55 | try { 56 | const stored = JSON.parse( 57 | sessionStorage.getItem('uiStateBeforeVideo'), 58 | ); 59 | prevWritesLocked = 'writesLocked' in stored ? stored.writesLocked : false; 60 | } catch { 61 | sessionStorage.setItem( 62 | 'uiStateBeforeVideo', 63 | JSON.stringify({ }), 64 | ); 65 | } 66 | 67 | let keepAliveInterval; 68 | if (isActiveCard && !isRewatch && !prevWritesLocked) { 69 | captureStateAndPrepForPlay(true); 70 | keepAliveInterval = setInterval(() => dispatch(keepAlive()), 30000); 71 | } 72 | return () => (keepAliveInterval ? clearInterval(keepAliveInterval) : null); 73 | }, []); 74 | 75 | // then, when the video ends, return to the state it was at 76 | const resetState = () => { 77 | const { 78 | showTranscript: oldShowTranscript, 79 | micOn: oldMicOn, 80 | } = JSON.parse(sessionStorage.getItem('uiStateBeforeVideo')); 81 | sessionStorage.setItem( 82 | 'uiStateBeforeVideo', 83 | JSON.stringify({ }), 84 | ); 85 | dispatch(setShowTranscript(oldShowTranscript)); 86 | dispatch(setMicOn({ micOn: oldMicOn })); 87 | dispatch(setActiveCards({ activeCards: [] })); 88 | }; 89 | 90 | const handleEnd = () => { 91 | if (isRewatch === false) { 92 | setPlayPushed(false); 93 | dispatch(sendTextMessage({ text: 'I\'m done watching!' })); 94 | } else resetState(); 95 | }; 96 | 97 | const activeVideo = () => (playPushed === true || isRewatch === true ? ( 98 |
    99 |
    100 | { 108 | captureStateAndPrepForPlay(); 109 | }} 110 | onEnd={handleEnd} 111 | /> 112 |
    113 | 114 | The Digital Person is paused while you watch this video and will not 115 | respond to your voice. 116 | 117 | 124 |
    125 |
    126 |
    127 | ) : ( 128 |
    132 | 142 |
    143 | )); 144 | 145 | return ( 146 |
    147 | {inTranscript === true ? ( 148 |
    152 | 168 |
    169 | ) : activeVideo()} 170 |
    171 | ); 172 | } 173 | 174 | Video.propTypes = { 175 | data: PropTypes.shape({ 176 | videoId: PropTypes.string.isRequired, 177 | autoplay: PropTypes.string, 178 | }).isRequired, 179 | className: PropTypes.string.isRequired, 180 | inTranscript: PropTypes.bool, 181 | }; 182 | 183 | Video.defaultProps = { 184 | inTranscript: false, 185 | }; 186 | 187 | export default styled(Video)` 188 | .video-thumbnail { 189 | width: 25rem; 190 | aspect-ratio: 16 / 9; 191 | background-size: cover; 192 | background-position: center; 193 | 194 | display: flex; 195 | justify-content: center; 196 | align-items: center; 197 | } 198 | .video-play-button { 199 | background-color: #f00; 200 | color: #FFF; 201 | height: 2.5rem; 202 | aspect-ratio: 1; 203 | } 204 | 205 | .lightbox { 206 | position: absolute; 207 | top: 0; 208 | left: 0; 209 | width: 100vw; 210 | height: 100vh; 211 | 212 | display: flex; 213 | align-items: center; 214 | justify-content: center; 215 | 216 | background: rgba(0, 0, 0, 0.1); 217 | backdrop-filter: blur(3px); 218 | } 219 | `; 220 | -------------------------------------------------------------------------------- /src/components/Controls.js: -------------------------------------------------------------------------------- 1 | import React, { useEffect, useState } from 'react'; 2 | import { useDispatch, useSelector } from 'react-redux'; 3 | import styled from 'styled-components'; 4 | import PropTypes from 'prop-types'; 5 | import { 6 | CameraVideoFill, 7 | CameraVideoOffFill, 8 | ChatSquareTextFill, 9 | Escape, 10 | Link45deg, 11 | Megaphone, 12 | MicFill, 13 | MicMuteFill, 14 | Share, 15 | SkipEndFill, 16 | ThreeDotsVertical, 17 | VolumeMuteFill, 18 | VolumeUpFill, 19 | X, 20 | } from 'react-bootstrap-icons'; 21 | import ReactTooltip from 'react-tooltip'; 22 | import { 23 | stopSpeaking, 24 | setShowTranscript, 25 | disconnect, 26 | setOutputMute, 27 | setMicOn, 28 | setCameraOn, 29 | } from '../store/sm/index'; 30 | import mic from '../img/mic.svg'; 31 | import micFill from '../img/mic-fill.svg'; 32 | import breakpoints from '../utils/breakpoints'; 33 | import { primaryAccent } from '../globalStyle'; 34 | import FeedbackModal from './FeedbackModal'; 35 | 36 | const volumeMeterHeight = 24; 37 | const volumeMeterMultiplier = 1.2; 38 | const smallHeight = volumeMeterHeight; 39 | const largeHeight = volumeMeterHeight * volumeMeterMultiplier; 40 | 41 | function Controls({ 42 | className, 43 | }) { 44 | const { 45 | micOn, 46 | cameraOn, 47 | isOutputMuted, 48 | speechState, 49 | showTranscript, 50 | transcript, 51 | requestedMediaPerms, 52 | highlightMic, 53 | highlightMute, 54 | highlightChat, 55 | highlightCamera, 56 | highlightSkip, 57 | highlightMenu, 58 | } = useSelector((state) => ({ ...state.sm })); 59 | 60 | const dispatch = useDispatch(); 61 | 62 | const [showFeedback, setShowFeedback] = useState(false); 63 | 64 | // mic level visualizer 65 | // TODO: fix this 66 | // const typingOnly = requestedMediaPerms.mic !== true; 67 | // const [volume, setVolume] = useState(0); 68 | // useEffect(async () => { 69 | // if (connected && typingOnly === false) { 70 | // // credit: https://stackoverflow.com/a/64650826 71 | // let volumeCallback = null; 72 | // let audioStream; 73 | // let audioContext; 74 | // let audioSource; 75 | // let unmounted = false; 76 | // // Initialize 77 | // try { 78 | // audioStream = mediaStreamProxy.getUserMediaStream(); 79 | // audioContext = new AudioContext(); 80 | // audioSource = audioContext.createMediaStreamSource(audioStream); 81 | // const analyser = audioContext.createAnalyser(); 82 | // analyser.fftSize = 512; 83 | // analyser.minDecibels = -127; 84 | // analyser.maxDecibels = 0; 85 | // analyser.smoothingTimeConstant = 0.4; 86 | // audioSource.connect(analyser); 87 | // const volumes = new Uint8Array(analyser.frequencyBinCount); 88 | // volumeCallback = () => { 89 | // analyser.getByteFrequencyData(volumes); 90 | // let volumeSum = 0; 91 | // volumes.forEach((v) => { volumeSum += v; }); 92 | // // multiply value by 2 so the volume meter appears more responsive 93 | // // (otherwise the fill doesn't always show) 94 | // const averageVolume = (volumeSum / volumes.length) * 2; 95 | // // Value range: 127 = analyser.maxDecibels - analyser.minDecibels; 96 | // setVolume(averageVolume > 127 ? 127 : averageVolume); 97 | // }; 98 | // // runs every time the window paints 99 | // const volumeDisplay = () => { 100 | // window.requestAnimationFrame(() => { 101 | // if (!unmounted) { 102 | // volumeCallback(); 103 | // volumeDisplay(); 104 | // } 105 | // }); 106 | // }; 107 | // volumeDisplay(); 108 | // } catch (e) { 109 | // console.error('Failed to initialize volume visualizer!', e); 110 | // } 111 | 112 | // return () => { 113 | // console.log('closing down the audio stuff'); 114 | // // FIXME: tracking #79 115 | // unmounted = true; 116 | // audioContext.close(); 117 | // audioSource.close(); 118 | // }; 119 | // } return false; 120 | // }, [connected]); 121 | 122 | // bind transcrpt open and mute func to each other, so that 123 | // when we open the transcript we mute the mic 124 | const toggleKeyboardInput = () => { 125 | dispatch(setShowTranscript(!showTranscript)); 126 | dispatch(setMicOn({ micOn: showTranscript })); 127 | }; 128 | 129 | useEffect(() => { 130 | ReactTooltip.rebuild(); 131 | }); 132 | 133 | const iconSize = 24; 134 | 135 | const [showContextMenu, setShowContextMenu] = useState(false); 136 | 137 | const originalShareCopy = 'Share Experience'; 138 | const [shareCopy, setShareCopy] = useState(originalShareCopy); 139 | 140 | const shareDP = async () => { 141 | const url = window.location; 142 | try { 143 | await navigator.share({ url }); 144 | } catch { 145 | const type = 'text/plain'; 146 | const blob = new Blob([url], { type }); 147 | const data = [new window.ClipboardItem({ [type]: blob })]; 148 | navigator.clipboard.write(data); 149 | setShareCopy('Link copied!'); 150 | setTimeout(() => setShareCopy(originalShareCopy), 3000); 151 | } 152 | }; 153 | 154 | return ( 155 |
    156 | {showFeedback ? ( 157 |
    158 |
    159 | { 161 | setShowFeedback(false); 162 | }} 163 | closeText="Resume Conversation" 164 | denyFeedbackText="Close" 165 | denyFeedback={() => { 166 | setShowFeedback(false); 167 | }} 168 | /> 169 |
    170 |
    171 | ) : null} 172 |
    173 |
    174 | {/* mute dp sound */} 175 | 188 |
    189 |
    190 | {/* skip through whatever dp is currently speaking */} 191 | 201 |
    202 |
    203 | {/* show transcript */} 204 | 218 |
    219 |
    220 | {/* toggle user mic */} 221 | 235 |
    236 |
    237 | {/* toggle user camera */} 238 | 256 |
    257 |
    258 | 272 | {showContextMenu ? ( 273 |
    274 |
    275 |
      276 |
    • 277 | 286 |
    • 287 |
    • 288 | 300 |
    • 301 |
    • 302 | 311 |
    • 312 |
    • 313 | 319 | 320 | {' '} 321 | Visit Soul Machines 322 | 323 |
    • 324 |
    325 |
    326 |
    327 | ) : null} 328 |
    329 |
    330 |
    331 | ); 332 | } 333 | 334 | Controls.propTypes = { className: PropTypes.string.isRequired }; 335 | 336 | export default styled(Controls)` 337 | .context-controls { 338 | position: absolute; 339 | z-index: 100; 340 | background: rgba(0,0,0,0.3); 341 | left: 0; 342 | top: 0; 343 | 344 | &>div { 345 | width: 100vw; 346 | height: 100vh; 347 | 348 | margin-top: 4rem; 349 | } 350 | 351 | ul { 352 | padding: 1rem; 353 | 354 | list-style-type: none; 355 | 356 | background: #FFF; 357 | border: 1px solid rgba(0,0,0,0.1); 358 | border-radius: 5px; 359 | border-top-right-radius: 0; 360 | border-bottom-right-radius: 0; 361 | border-right: none; 362 | 363 | &>li { 364 | border-bottom: 1px solid rgba(0,0,0,0.4); 365 | padding: 0.5rem; 366 | } 367 | &>li:last-child { 368 | border: none; 369 | padding-bottom: 0; 370 | } 371 | } 372 | } 373 | .context-controls-trigger { 374 | position: relative; 375 | border: 1px solid red; 376 | z-index: 105; 377 | } 378 | .control-icon { 379 | border: none; 380 | background: none; 381 | 382 | padding: .4rem; 383 | } 384 | .form-control { 385 | opacity: 0.8; 386 | &:focus { 387 | opacity: 1; 388 | } 389 | } 390 | 391 | .interrupt { 392 | opacity: 1; 393 | transition: opacity 0.1s; 394 | } 395 | .interrupt-active { 396 | opacity: 0; 397 | } 398 | 399 | .volume-display { 400 | position: relative; 401 | top: ${volumeMeterHeight * 0.5}px; 402 | display: flex; 403 | align-items: flex-end; 404 | justify-content: start; 405 | min-width: ${({ videoWidth }) => (videoWidth <= breakpoints.md ? 21 : 32)}px; 406 | .meter-component { 407 | /* don't use media queries for this since we need to write the value 408 | in the body of the component */ 409 | height: ${({ videoWidth }) => (videoWidth >= breakpoints.md ? largeHeight : smallHeight)}px; 410 | background-size: ${({ videoWidth }) => (videoWidth >= breakpoints.md ? largeHeight : smallHeight)}px; 411 | background-position: bottom; 412 | background-repeat: no-repeat; 413 | min-width: ${({ videoWidth }) => (videoWidth <= breakpoints.md ? 21 : 28)}px; 414 | position: absolute; 415 | } 416 | .meter-component-1 { 417 | background-image: url(${mic}); 418 | z-index: 10; 419 | } 420 | .meter-component-2 { 421 | background-image: url(${micFill}); 422 | z-index: 20; 423 | } 424 | } 425 | .alert-modal { 426 | position: absolute; 427 | z-index: 1000; 428 | display: flex; 429 | top: 0; 430 | left: 0; 431 | justify-content: center; 432 | align-items: center; 433 | width: 100vw; 434 | min-height: 100vh; 435 | background: rgba(0,0,0,0.3); 436 | } 437 | .alert-modal-card { 438 | background: #FFF; 439 | padding: 1.3rem; 440 | border-radius: 5px; 441 | } 442 | `; 443 | -------------------------------------------------------------------------------- /src/components/FeedbackModal.js: -------------------------------------------------------------------------------- 1 | import React, { useState } from 'react'; 2 | import PropTypes from 'prop-types'; 3 | import { Star, StarFill } from 'react-bootstrap-icons'; 4 | import { Link, useHistory } from 'react-router-dom'; 5 | import styled from 'styled-components'; 6 | import breakpoints from '../utils/breakpoints'; 7 | import { landingBackgroundImage } from '../config'; 8 | 9 | function FeedbackModal({ 10 | className, onClose, closeText, denyFeedbackText, denyFeedback, 11 | }) { 12 | const nStars = 5; 13 | const [rating, setRating] = useState(-1); 14 | const [ratingSelected, setRatingSelected] = useState(false); 15 | const [submitted, setSubmitted] = useState(false); 16 | 17 | const history = useHistory(); 18 | 19 | // generate array of clickable stars for rating 20 | const stars = Array.from(Array(nStars)).map((_, i) => { 21 | const handleHover = () => { 22 | if (!ratingSelected) setRating(i); 23 | }; 24 | return ( 25 | 43 | ); 44 | }); 45 | 46 | // allow for custom input 47 | const [customField, setCustomField] = useState(''); 48 | // default tags 49 | const tagItems = ['Easy', 'Intuitive', 'Slow', 'Helpful', 'Personable', 'Laggy']; 50 | const [selectedTags, setSelectedTags] = useState([]); 51 | const handleSelectTag = (t) => { 52 | const tagIsSelected = selectedTags.indexOf(t) > -1; 53 | if (tagIsSelected === false) setSelectedTags([...selectedTags, t]); 54 | else setSelectedTags([...selectedTags.filter((v) => v !== t)]); 55 | }; 56 | 57 | return ( 58 |
    59 |
    60 |
    61 |
    62 |
    63 | {submitted ? ( 64 |
    65 |
    66 |

    Thank you for your feedback.

    67 |

    Want to keep chatting? If not, we can end our conversation.

    68 |
    69 |
    70 |
    71 | 78 | 79 | I'm Done 80 | 81 |
    82 |
    83 |
    84 | ) : ( 85 |
    86 |
    87 |

    88 | Can you rate your experience with Digital Persona A? 89 |

    90 |
    91 |
    92 |
    { 95 | if (!ratingSelected) setRating(-1); 96 | }} 97 | > 98 | {stars} 99 |
    100 |
    101 |
    102 |
    103 |

    How would you describe your experience?

    104 |
    (Select all that apply)
    105 |
    106 | {/* combine default tags and custom ones to display as one list */} 107 | {/* user can click on default tags to deselect and custom ones to edit */} 108 | {tagItems.map((t) => ( 109 | 119 | ))} 120 |
    121 |
    122 |
    123 |

    Can you tell us more?

    124 | {/* field for custom tags, limited to 20 chars */} 125 |
    129 |