├── .github └── workflows │ ├── deploy.yml │ └── test.yml ├── .gitignore ├── .prettierrc ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── contact-form ├── index.html ├── main.js └── style.css ├── image-comment ├── comment.js ├── index.html ├── main.js ├── state.js └── style.css ├── index.html ├── movie-app-alt-subscribe ├── index.html ├── js │ ├── database.js │ ├── main.js │ ├── movie.js │ └── state.js └── style.css ├── movie-app ├── index.html ├── js │ ├── database.js │ ├── main.js │ ├── movie.js │ └── state.js └── style.css ├── movie-lookup ├── index.html ├── main.js └── style.css ├── package-lock.json ├── package.json ├── picsum ├── index.html ├── main.js └── style.css ├── remembering-state ├── comment.js ├── database.js ├── index.html ├── main.js ├── state.js └── style.css ├── reusable-component ├── index.html └── main.js └── vite.config.js /.github/workflows/deploy.yml: -------------------------------------------------------------------------------- 1 | name: Deploy 2 | 3 | # On pushes to our default branch 4 | on: 5 | push: 6 | branches: 7 | - main 8 | # If we can write to it 9 | permissions: 10 | contents: write 11 | 12 | jobs: 13 | deploy: 14 | concurrency: ci-${{ github.ref }} # Recommended if you intend to make multiple deployments in quick succession. 15 | runs-on: ubuntu-latest 16 | steps: 17 | - name: Checkout 🛎️ 18 | uses: actions/checkout@v3 19 | - name: Use Node.js 16 20 | uses: actions/setup-node@v3 21 | with: 22 | node-version: 16.x 23 | cache: 'npm' 24 | 25 | - name: Install and Build 🔧 # This example project is built using npm and outputs the result to the 'build' folder. Replace with the commands required to build your project, or remove this step entirely if your site is pre-built. 26 | run: | 27 | npm ci 28 | npm run build 29 | 30 | - name: Deploy 🚀 31 | uses: JamesIves/github-pages-deploy-action@v4 32 | with: 33 | folder: dist # The folder the action should deploy. 34 | -------------------------------------------------------------------------------- /.github/workflows/test.yml: -------------------------------------------------------------------------------- 1 | # This workflow will do a clean installation of node dependencies, cache/restore them, build the source code and run tests across different versions of node 2 | # For more information see: https://help.github.com/actions/language-and-framework-guides/using-nodejs-with-github-actions 3 | 4 | name: Test 5 | 6 | # On every code push and pull request, run this 7 | on: [push, pull_request] 8 | 9 | jobs: 10 | test-and-build: 11 | runs-on: ubuntu-latest 12 | steps: 13 | - uses: actions/checkout@v3 # Check out our code 14 | 15 | - name: Use Node.js 16 # Use Node 16 16 | uses: actions/setup-node@v3 17 | with: 18 | node-version: 16.x 19 | cache: 'npm' 20 | 21 | - run: npm ci # Install our node modules 22 | - run: npm test # Run our test script 23 | - run: npm run build # Run our build script 24 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | pnpm-debug.log* 8 | lerna-debug.log* 9 | 10 | node_modules 11 | dist 12 | dist-ssr 13 | *.local 14 | 15 | # Editor directories and files 16 | .vscode/* 17 | !.vscode/extensions.json 18 | .idea 19 | .DS_Store 20 | *.suo 21 | *.ntvs* 22 | *.njsproj 23 | *.sln 24 | *.sw? 25 | -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "singleQuote": true, 3 | "trailingComma": "all" 4 | } 5 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as 6 | contributors and maintainers pledge to making participation in our project and 7 | our community a harassment-free experience for everyone, regardless of age, body 8 | size, disability, ethnicity, gender identity and expression, level of 9 | experience, education, socio-economic status, nationality, personal appearance, 10 | race, religion, or sexual identity and orientation. 11 | 12 | ## Our Standards 13 | 14 | Examples of behavior that contributes to creating a positive environment 15 | include: 16 | 17 | - Using welcoming and inclusive language 18 | - Being respectful of differing viewpoints and experiences 19 | - Gracefully accepting constructive criticism 20 | - Focusing on what is best for the community 21 | - Showing empathy towards other community members 22 | 23 | Examples of unacceptable behavior by participants include: 24 | 25 | - The use of sexualized language or imagery and unwelcome sexual attention or 26 | advances 27 | - Trolling, insulting/derogatory comments, and personal or political attacks 28 | - Public or private harassment 29 | - Publishing others' private information, such as a physical or electronic 30 | address, without explicit permission 31 | - Other conduct which could reasonably be considered inappropriate in a 32 | professional setting 33 | 34 | ## Our Responsibilities 35 | 36 | Project maintainers are responsible for clarifying the standards of acceptable 37 | behavior and are expected to take appropriate and fair corrective action in 38 | response to any instances of unacceptable behavior. 39 | 40 | Project maintainers have the right and responsibility to remove, edit, or reject 41 | comments, commits, code, wiki edits, issues, and other contributions that are 42 | not aligned to this Code of Conduct, or to ban temporarily or permanently any 43 | contributor for other behaviors that they deem inappropriate, threatening, 44 | offensive, or harmful. 45 | 46 | ## Scope 47 | 48 | This Code of Conduct applies both within project spaces and in public spaces 49 | when an individual is representing the project or its community. Examples of 50 | representing a project or community include using an official project e-mail 51 | address, posting via an official social media account, or acting as an appointed 52 | representative at an online or offline event. Representation of a project may be 53 | further defined and clarified by project maintainers. 54 | 55 | This Code of Conduct also applies outside the project spaces when the Project 56 | Steward has a reasonable belief that an individual's behavior may have a 57 | negative impact on the project or its community. 58 | 59 | ## Conflict Resolution 60 | 61 | We do not believe that all conflict is bad; healthy debate and disagreement 62 | often yield positive results. However, it is never okay to be disrespectful or 63 | to engage in behavior that violates the project’s code of conduct. 64 | 65 | If you see someone violating the code of conduct, you are encouraged to address 66 | the behavior directly with those involved. Many issues can be resolved quickly 67 | and easily, and this gives people more control over the outcome of their 68 | dispute. If you are unable to resolve the matter for any reason, or if the 69 | behavior is threatening or harassing, report it. We are dedicated to providing 70 | an environment where participants feel welcome and safe. 71 | 72 | Reports should be directed to _Sam Richard _, the 73 | Project Steward(s) for _TEC Web Assignments_. It is the Project Steward’s duty to 74 | receive and address reported violations of the code of conduct. They will then 75 | work with a committee consisting of representatives from the Open Source 76 | Programs Office and the Google Open Source Strategy team. If for any reason you 77 | are uncomfortable reaching out to the Project Steward, please email 78 | opensource@google.com. 79 | 80 | We will investigate every complaint, but you may not receive a direct response. 81 | We will use our discretion in determining when and how to follow up on reported 82 | incidents, which may range from not taking action to permanent expulsion from 83 | the project and project-sponsored spaces. We will notify the accused of the 84 | report and provide them an opportunity to discuss it before any action is taken. 85 | The identity of the reporter will be omitted from the details of the report 86 | supplied to the accused. In potentially harmful situations, such as ongoing 87 | harassment or threats to anyone's safety, we may take action without notice. 88 | 89 | ## Attribution 90 | 91 | This Code of Conduct is adapted from the Contributor Covenant, version 1.4, 92 | available at 93 | https://www.contributor-covenant.org/version/1/4/code-of-conduct.html 94 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # How to Contribute 2 | 3 | We'd love to accept your patches and contributions to this project. There are 4 | just a few small guidelines you need to follow. 5 | 6 | ## Contributor License Agreement 7 | 8 | Contributions to this project must be accompanied by a Contributor License 9 | Agreement (CLA). You (or your employer) retain the copyright to your 10 | contribution; this simply gives us permission to use and redistribute your 11 | contributions as part of the project. Head over to 12 | to see your current agreements on file or 13 | to sign a new one. 14 | 15 | You generally only need to submit a CLA once, so if you've already submitted one 16 | (even if it was for a different project), you probably don't need to do it 17 | again. 18 | 19 | ## Code Reviews 20 | 21 | All submissions, including submissions by project members, require review. We 22 | use GitHub pull requests for this purpose. Consult 23 | [GitHub Help](https://help.github.com/articles/about-pull-requests/) for more 24 | information on using pull requests. 25 | 26 | ## Community Guidelines 27 | 28 | This project follows 29 | [Google's Open Source Community Guidelines](https://opensource.google/conduct/). 30 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 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 | # TEC Web Assignments 2 | 3 | These are solutions to the TEC Web cohort's assignments. To run the code, first install the dependencies (`npm install`) and then run the development server (`npm run dev`). 4 | 5 | --- 6 | 7 | This is not an officially supported Google product 8 | -------------------------------------------------------------------------------- /contact-form/index.html: -------------------------------------------------------------------------------- 1 | 2 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | Contact Form 26 | 27 | 28 |
29 |
30 |
31 | 32 | 38 |
39 |
40 | 41 | 48 |
49 |
50 | 51 | 52 |
53 |
54 | 55 | 59 |
60 |
61 | 62 | 68 |
69 |
70 | 78 | 86 |
87 |
88 | 92 |
93 |
94 | 95 |
96 |
97 | 98 | 99 | -------------------------------------------------------------------------------- /contact-form/main.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2022 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | const form = document.querySelector('#form'); 18 | const required = document.querySelectorAll('[required]'); 19 | const email = document.querySelector('#email'); 20 | const message = document.querySelector('#message'); 21 | const agree = document.querySelector('#agree'); 22 | 23 | // Add a "required" class to all labels for required fields 24 | for (const input of required) { 25 | input 26 | // Move up the DOM to find the nearest parent that matches the selector 27 | .closest('.form--group') 28 | // Searches within that parent for the first label element 29 | .querySelector('label') 30 | // Adds the "required" class to the found label element 31 | .classList.add('required'); 32 | } 33 | 34 | // Manage email custom validity 35 | email.addEventListener('input', () => { 36 | email.setCustomValidity(''); 37 | email.checkValidity(); 38 | }); 39 | 40 | email.addEventListener('invalid', () => { 41 | if (email.value === '') { 42 | email.setCustomValidity('Please enter your email address'); 43 | } 44 | }); 45 | 46 | // Manage message custom validity 47 | message.addEventListener('input', () => { 48 | message.setCustomValidity(''); 49 | message.checkValidity(); 50 | }); 51 | 52 | message.addEventListener('invalid', () => { 53 | if (message.value === '') { 54 | message.setCustomValidity('Please enter a message'); 55 | } 56 | }); 57 | 58 | // Manage agree custom validity 59 | agree.addEventListener('input', () => { 60 | agree.setCustomValidity(''); 61 | agree.checkValidity(); 62 | }); 63 | 64 | agree.addEventListener('invalid', () => { 65 | if (!agree.checked) { 66 | agree.setCustomValidity('You must agree to the terms and conditions'); 67 | } 68 | }); 69 | 70 | // Listen for the form being submitted 71 | form.addEventListener('submit', (e) => { 72 | e.preventDefault(); 73 | 74 | // Get all inputs from the form 75 | const data = new FormData(e.target); 76 | // Create an object from the entries 77 | const submitted = Object.fromEntries(data.entries()); 78 | 79 | // Turn the object into a JSON string and put it on the page 80 | const content = JSON.stringify(submitted, null, 2); 81 | const output = document.querySelector('#output'); 82 | output.innerText = content; 83 | }); 84 | -------------------------------------------------------------------------------- /contact-form/style.css: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2022 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | label { 18 | display: block; 19 | } 20 | 21 | .form--group { 22 | margin-bottom: 1em; 23 | } 24 | 25 | /* Add an indicator of the field is required */ 26 | .required:after { 27 | content: '*'; 28 | color: red; 29 | } 30 | 31 | /* Give some space if an input is in a label */ 32 | label input { 33 | margin-right: 0.5em; 34 | } 35 | 36 | input:invalid, 37 | textarea:invalid { 38 | border: 1px solid red; 39 | } 40 | -------------------------------------------------------------------------------- /image-comment/comment.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2022 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | // Create a new HTML element 18 | class MyComponent extends HTMLElement { 19 | constructor() { 20 | // Always call super first in constructor 21 | super(); 22 | 23 | // Create a shadow root 24 | const shadow = this.attachShadow({ mode: 'open' }); 25 | // Get our component template from the DOM and ad it to the shadow root 26 | const template = document.querySelector('#comment').content.cloneNode(true); 27 | shadow.append(template); 28 | 29 | // Get the elements from the shadow root where our content will be rendered 30 | this._name = this.shadowRoot.querySelector('.comment--name'); 31 | this._email = this.shadowRoot.querySelector('.comment--email'); 32 | this._body = this.shadowRoot.querySelector('.comment--body'); 33 | this._time = this.shadowRoot.querySelector('.comment--time'); 34 | } 35 | 36 | // Declare what attributes you want to listen for changes to 37 | static get observedAttributes() { 38 | return ['name', 'email', 'body', 'time']; 39 | } 40 | 41 | // Called when an observed attribute changes 42 | attributeChangedCallback(name, oldValue, newValue) { 43 | // If nothing's changed, don't continue 44 | if (oldValue === newValue) return; 45 | 46 | // Check if the changed attribute has a matching area to render the content 47 | if (this[`_${name}`]) { 48 | this[`_${name}`].textContent = newValue; 49 | } 50 | } 51 | } 52 | 53 | // Check to see if the custom element is defined 54 | if (customElements.get('my-comment') === undefined) { 55 | // If not, define the custom element 56 | customElements.define('my-comment', MyComponent); 57 | } 58 | -------------------------------------------------------------------------------- /image-comment/index.html: -------------------------------------------------------------------------------- 1 | 2 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | Reusable Components 24 | 25 | 26 | 27 | 28 | 57 | 58 | A river flowing through rolling hills 62 |
63 |
64 | 65 | 66 |
67 |
68 | 69 | 70 |
71 |
72 | 73 | 74 |
75 |
76 | 80 |
81 | 82 |
83 | 84 |
85 | 86 | 87 | -------------------------------------------------------------------------------- /image-comment/main.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2022 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import './comment.js'; 18 | import { store } from './state.js'; 19 | 20 | // Grab elements from the DOM 21 | const required = document.querySelectorAll('[required]'); 22 | const form = document.querySelector('#comment-form'); 23 | const comments = document.querySelector('#comments'); 24 | 25 | // Add required class to required labels 26 | for (const input of required) { 27 | input 28 | .closest('.form--group') 29 | .querySelector('label') 30 | .classList.add('required'); 31 | } 32 | 33 | // Listen to form submission 34 | form.addEventListener('submit', (e) => { 35 | e.preventDefault(); 36 | // Grab the form data as an object 37 | const data = Object.fromEntries(new FormData(form).entries()); 38 | console.log(data); 39 | 40 | store.addComment(data); 41 | 42 | // Extra Credit: Reset the form and puts the cursor into the first input 43 | // Resets the form 44 | e.target.reset(); 45 | // Finds the first input in the form and focuses it 46 | e.target.querySelector('input, textarea, button').focus(); 47 | }); 48 | 49 | // Subscribe to the store to render comments 50 | store.subscribe((state) => { 51 | // Grab the comments from the store 52 | const allComments = state.comments; 53 | console.log(allComments); 54 | 55 | // Removes all existing comments so we can re-render them 56 | comments.innerHTML = ''; 57 | 58 | // Loops over each comment, creates a custom my-comment element, sets the appropriate attributes, and appends it to the comments section 59 | for (const comment of allComments) { 60 | const myComment = document.createElement('my-comment'); 61 | myComment.setAttribute('name', comment.name); 62 | myComment.setAttribute('email', comment.email); 63 | myComment.setAttribute('body', comment.body); 64 | myComment.setAttribute('time', comment.date); 65 | comments.append(myComment); 66 | } 67 | }); 68 | -------------------------------------------------------------------------------- /image-comment/state.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2022 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | // Create a new state manager 18 | class StoreManager { 19 | constructor(init = {}) { 20 | // Grab the current "this" context 21 | const self = this; 22 | // Create an array for subscribers 23 | this._subscribers = []; 24 | // Create the internal state proxy 25 | this._state = new Proxy(init, { 26 | set(target, key, value) { 27 | // Set the key equal to the value 28 | target[key] = value; 29 | 30 | // Loop through each subscriber and call them 31 | for (const subscriber of self._subscribers) { 32 | subscriber(target); 33 | } 34 | 35 | // Return true to indicate that the set was successful 36 | return true; 37 | }, 38 | }); 39 | } 40 | 41 | // Let things subscribe to the state manager 42 | subscribe(cb) { 43 | if (typeof cb !== 'function') { 44 | throw new Error('Callback is not a function'); 45 | } 46 | this._subscribers.push(cb); 47 | cb(this._state); 48 | } 49 | 50 | // Action to add a comment to the state 51 | addComment(comment) { 52 | if (!comment.date) { 53 | comment.date = new Date(); 54 | } 55 | 56 | this._state.comments.push(comment); 57 | this._state.comments = this._state.comments; 58 | } 59 | } 60 | 61 | export const store = new StoreManager({ comments: [] }); 62 | -------------------------------------------------------------------------------- /image-comment/style.css: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2022 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | label { 18 | display: block; 19 | } 20 | 21 | label input { 22 | margin-right: 0.5rem; 23 | } 24 | 25 | .required:after { 26 | content: '*'; 27 | color: red; 28 | } 29 | -------------------------------------------------------------------------------- /index.html: -------------------------------------------------------------------------------- 1 | 2 | 17 | 18 | 19 | 20 | 21 | 22 | Assignments 23 | 24 | 25 |

Phase 3 Assignments!

26 | 61 | 62 | 63 | -------------------------------------------------------------------------------- /movie-app-alt-subscribe/index.html: -------------------------------------------------------------------------------- 1 | 2 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | Movie Lookup 24 | 25 | 26 | 27 | 28 | 65 |
66 | 67 | 99 | 100 | 101 | -------------------------------------------------------------------------------- /movie-app-alt-subscribe/js/database.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2022 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import { openDB } from 'idb'; 18 | 19 | export const database = openDB('movie-app', 1, { 20 | upgrade(db) { 21 | db.createObjectStore('movies', { keyPath: 'imdbID' }); 22 | db.createObjectStore('settings'); 23 | db.createObjectStore('notes', { keyPath: 'imdbID' }); 24 | }, 25 | }); 26 | -------------------------------------------------------------------------------- /movie-app-alt-subscribe/js/main.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2022 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import { store } from './state.js'; 18 | import { database } from './database.js'; 19 | import './movie.js'; 20 | 21 | const form = document.querySelector('#search'); 22 | const required = document.querySelectorAll('[required]'); 23 | const year = document.querySelector('#year'); 24 | const output = document.querySelector('#output'); 25 | const apikey = document.querySelector('#key'); 26 | 27 | // Add required class to labels 28 | for (const input of required) { 29 | input 30 | .closest('.form--group') 31 | .querySelector('label') 32 | .classList.add('required'); 33 | } 34 | 35 | // Handle custom validation for year 36 | year.setAttribute('max', new Date().getFullYear()); 37 | year.addEventListener('input', (e) => { 38 | year.setCustomValidity(''); 39 | year.checkValidity(); 40 | }); 41 | 42 | // Instead of default error messages, show custom error messages 43 | year.addEventListener('invalid', () => { 44 | if (Number(year.value) < Number(year.getAttribute('min'))) { 45 | year.setCustomValidity( 46 | `Year must be greater than or equal to ${year.getAttribute('min')}`, 47 | ); 48 | } else if (Number(year.value) > Number(year.getAttribute('max'))) { 49 | year.setCustomValidity( 50 | `Year must be less than or equal to ${year.getAttribute('max')}`, 51 | ); 52 | } 53 | }); 54 | 55 | // Manage API Key visibility 56 | store.subscribe( 57 | (state) => { 58 | if (state.key) { 59 | apikey.value = state.key; 60 | apikey.closest('.form--group').style.display = 'none'; 61 | } else { 62 | apikey.closest('.form--group').style.display = 'block'; 63 | } 64 | }, 65 | ['key'], 66 | ); 67 | 68 | function buildMovieElement(movie) { 69 | const movieElement = document.createElement('movie-element'); 70 | movieElement.setAttribute('poster', movie.Poster); 71 | movieElement.setAttribute('title', movie.Title); 72 | movieElement.setAttribute('year', movie.Year); 73 | movieElement.setAttribute('imdb', movie.imdbID); 74 | 75 | return movieElement; 76 | } 77 | 78 | // Manage Movie lookup 79 | store.subscribe( 80 | async (state) => { 81 | const movies = state.movies; 82 | output.innerHTML = ''; 83 | if (movies.length > 0) { 84 | for (const movie of movies) { 85 | output.append(buildMovieElement(movie)); 86 | } 87 | } else if (!state.search && state.favorites) { 88 | if (state.favorites) { 89 | const db = await database; 90 | const movies = await Promise.all( 91 | state.favorites.map((id) => db.get('movies', id)), 92 | ); 93 | if (movies.length > 0) { 94 | for (const movie of movies) { 95 | output.append(buildMovieElement(movie)); 96 | } 97 | } 98 | } 99 | } 100 | }, 101 | ['movies', 'search', 'favorites'], 102 | ); 103 | 104 | form.addEventListener('submit', async (e) => { 105 | e.preventDefault(); 106 | const formData = new FormData(form); 107 | const search = Object.fromEntries(formData.entries()); 108 | const inputs = form.querySelectorAll('input, button, textarea'); 109 | 110 | // Disable all inputs 111 | for (const input of inputs) { 112 | input.disabled = true; 113 | } 114 | 115 | store.search(search); 116 | 117 | // Enable all inputs 118 | for (const input of inputs) { 119 | input.disabled = false; 120 | } 121 | }); 122 | 123 | form.addEventListener('reset', () => { 124 | store.reset(); 125 | }); 126 | -------------------------------------------------------------------------------- /movie-app-alt-subscribe/js/movie.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2022 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import { store } from './state.js'; 18 | 19 | class Movie extends HTMLElement { 20 | constructor() { 21 | super(); 22 | const shadow = this.attachShadow({ mode: 'open' }); 23 | const template = document 24 | .querySelector('#movie-template') 25 | .content.cloneNode(true); 26 | shadow.append(template); 27 | 28 | this._poster = this.shadowRoot.querySelector('.movie--poster'); 29 | this._title = this.shadowRoot.querySelector('.movie--title'); 30 | this._year = this.shadowRoot.querySelector('.movie--year'); 31 | 32 | this._favorite = this.shadowRoot.querySelector('.movie--favorite'); 33 | this._showNotes = this.shadowRoot.querySelector('.movie--show-notes'); 34 | this._notes = this.shadowRoot.querySelector('.movie--notes'); 35 | } 36 | 37 | static get observedAttributes() { 38 | return ['poster', 'title', 'year', 'imdb']; 39 | } 40 | attributeChangedCallback(name, oldValue, newValue) { 41 | if (oldValue === newValue) return; 42 | 43 | if (name === 'poster') { 44 | this._poster.src = newValue; 45 | this._poster.alt = `Poster for ${this.title}`; 46 | } 47 | 48 | if (name === 'title') { 49 | this._title.textContent = newValue; 50 | } 51 | 52 | if (name === 'year') { 53 | this._year.textContent = newValue; 54 | } 55 | } 56 | 57 | connectedCallback() { 58 | const id = this.getAttribute('imdb'); 59 | 60 | this._favorite.addEventListener('click', () => { 61 | store.toggleFavorite(id); 62 | }); 63 | 64 | this._notes.addEventListener('input', (e) => { 65 | store.setNote(id, e.target.value); 66 | }); 67 | 68 | this._showNotes.addEventListener('click', () => { 69 | this._notes.classList.toggle('hidden'); 70 | if (this._notes.classList.contains('hidden')) { 71 | this._showNotes.textContent = 'Show notes'; 72 | } else { 73 | this._showNotes.textContent = 'Hide notes'; 74 | } 75 | }); 76 | 77 | store.subscribe( 78 | (state) => { 79 | // Make sure the notes match what's in the state 80 | if (this._notes.textContent !== state.notes[id]) { 81 | this._notes.textContent = state.notes[id]; 82 | } 83 | 84 | // Manage favoriting 85 | if (state?.favorites?.includes(id)) { 86 | this._favorite.textContent = 'Unfavorite'; 87 | } else { 88 | this._favorite.textContent = 'Favorite'; 89 | } 90 | }, 91 | ['notes', 'favorites'], 92 | ); 93 | } 94 | } 95 | 96 | if (customElements.get('movie-element') === undefined) { 97 | customElements.define('movie-element', Movie); 98 | } 99 | -------------------------------------------------------------------------------- /movie-app-alt-subscribe/js/state.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2022 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | // Import our database 18 | import { database } from './database'; 19 | 20 | // Create a new state manager 21 | class StoreManager { 22 | constructor(init = {}) { 23 | // Grab the current "this" context 24 | const self = this; 25 | // Create an array for subscribers 26 | this._subscribers = {}; 27 | 28 | // // Wait for our database to be ready 29 | database.then(async (db) => { 30 | // When ready, make the database available to the state manager 31 | this.db = db; 32 | 33 | // Get the key from the database 34 | const key = await db.get('settings', 'key'); 35 | if (key) { 36 | this._state.key = key; 37 | } 38 | 39 | // Get favorites from the database 40 | const favorites = await db.get('settings', 'favorites'); 41 | if (favorites) { 42 | this._state.favorites = favorites; 43 | } 44 | 45 | // Get notes from the database 46 | const notes = await db.getAll('notes'); 47 | if (notes.length) { 48 | this._state.notes = 49 | Object.fromEntries(notes.map(({ imdbID, note }) => [imdbID, note])) || 50 | {}; 51 | } 52 | }); 53 | 54 | // Create the internal state proxy 55 | this._state = new Proxy(init, { 56 | // Make set an async function so we can use our database to save it when it's updated 57 | async set(target, key, value) { 58 | // Set the key equal to the value 59 | target[key] = value; 60 | 61 | // Save items to the database, if it's available 62 | if (self.db) { 63 | if (key === 'key') { 64 | await self.db.put('settings', value, 'key'); 65 | } 66 | 67 | if (key === 'favorites') { 68 | await self.db.put('settings', value, 'favorites'); 69 | const movies = target.movies 70 | .filter((movie) => value.includes(movie.imdbID)) 71 | .map((movie) => self.db.put('movies', movie)); 72 | 73 | await Promise.all(movies); 74 | } 75 | 76 | if (key === 'notes') { 77 | await Promise.all( 78 | Object.entries(value).map(([id, note]) => 79 | self.db.put('notes', { note, imdbID: id }), 80 | ), 81 | ); 82 | } 83 | } 84 | 85 | // Loop through each subscriber and call them 86 | if (self._subscribers._all) { 87 | for (const subscriber of self._subscribers._all) { 88 | subscriber(target); 89 | } 90 | } 91 | 92 | if (self._subscribers[key]) { 93 | for (const subscriber of self._subscribers[key]) { 94 | subscriber(target); 95 | } 96 | } 97 | 98 | // Return true to indicate that the set was successful 99 | return true; 100 | }, 101 | }); 102 | } 103 | 104 | // Let things subscribe to the state manager 105 | subscribe(cb, keys = ['_all']) { 106 | if (typeof cb !== 'function') { 107 | throw new Error('Callback is not a function'); 108 | } 109 | 110 | if (!Array.isArray(keys)) { 111 | keys = [keys]; 112 | } 113 | 114 | // Let subscribers subscribe to specific key changes 115 | for (const key of keys) { 116 | if (!this._subscribers[key]) { 117 | this._subscribers[key] = []; 118 | } 119 | this._subscribers[key].push(cb); 120 | } 121 | cb(this._state); 122 | } 123 | 124 | // Get the current state 125 | state(key) { 126 | if (key) { 127 | return this._state[key]; 128 | } 129 | return this._state; 130 | } 131 | 132 | // Action to add a comment to the state 133 | search(lookup) { 134 | if (lookup.key) { 135 | this._state.key = lookup.key; 136 | } 137 | 138 | this._state.search = { 139 | title: lookup.title, 140 | year: lookup.year || '', 141 | }; 142 | 143 | this._state.error = ''; 144 | 145 | this.movieLookup(); 146 | } 147 | 148 | reset() { 149 | this._state.search = null; 150 | this._state.movies = []; 151 | } 152 | 153 | toggleFavorite(id) { 154 | const favorites = this.state('favorites') || []; 155 | 156 | if (favorites.includes(id)) { 157 | favorites.splice(favorites.indexOf(id), 1); 158 | } else { 159 | favorites.push(id); 160 | } 161 | 162 | this._state.favorites = favorites; 163 | } 164 | 165 | setNote(id, note) { 166 | const notes = this.state('notes') || {}; 167 | notes[id] = note; 168 | this._state.notes = notes; 169 | } 170 | 171 | async movieLookup() { 172 | let key = this.state('key'); 173 | let search = this.state('search'); 174 | 175 | if (!key) { 176 | return (this._state.error = 'No API Key'); 177 | } 178 | 179 | let query = `https://www.omdbapi.com/?apikey=${key}&s=${search.title}`; 180 | if (search.year) { 181 | query += `&y=${search.year}`; 182 | } 183 | 184 | try { 185 | const response = await fetch(query); 186 | const data = await response.json(); 187 | if (data.Response === 'False') { 188 | // Show error message 189 | this._state.error = data.Error; 190 | } 191 | 192 | // Make sure this is an array 193 | if (Array.isArray(data.Search)) { 194 | this._state.movies = data.Search; 195 | } else { 196 | this._state.movies = []; 197 | } 198 | } catch (e) { 199 | this._state.error = e.message; 200 | } 201 | } 202 | } 203 | 204 | export const store = new StoreManager({ search: '', movies: [] }); 205 | -------------------------------------------------------------------------------- /movie-app-alt-subscribe/style.css: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2022 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | input:invalid { 18 | border: 1px solid red; 19 | } 20 | 21 | label { 22 | display: block; 23 | } 24 | 25 | .required:after { 26 | content: ' *'; 27 | color: red; 28 | } 29 | 30 | .form--group { 31 | margin-bottom: 1rem; 32 | } 33 | -------------------------------------------------------------------------------- /movie-app/index.html: -------------------------------------------------------------------------------- 1 | 2 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | Movie Lookup 24 | 25 | 26 | 27 | 28 | 65 |
66 | 67 | 99 | 100 | 101 | -------------------------------------------------------------------------------- /movie-app/js/database.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2022 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import { openDB } from 'idb'; 18 | 19 | export const database = openDB('movie-app', 1, { 20 | upgrade(db) { 21 | db.createObjectStore('movies', { keyPath: 'imdbID' }); 22 | db.createObjectStore('settings'); 23 | db.createObjectStore('notes', { keyPath: 'imdbID' }); 24 | }, 25 | }); 26 | -------------------------------------------------------------------------------- /movie-app/js/main.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2022 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import { store } from './state.js'; 18 | import { database } from './database.js'; 19 | import './movie.js'; 20 | 21 | const form = document.querySelector('#search'); 22 | const required = document.querySelectorAll('[required]'); 23 | const year = document.querySelector('#year'); 24 | const output = document.querySelector('#output'); 25 | const apikey = document.querySelector('#key'); 26 | 27 | // Add required class to labels 28 | for (const input of required) { 29 | input 30 | .closest('.form--group') 31 | .querySelector('label') 32 | .classList.add('required'); 33 | } 34 | 35 | // Handle custom validation for year 36 | year.setAttribute('max', new Date().getFullYear()); 37 | year.addEventListener('input', (e) => { 38 | year.setCustomValidity(''); 39 | year.checkValidity(); 40 | }); 41 | 42 | // Instead of default error messages, show custom error messages 43 | year.addEventListener('invalid', () => { 44 | if (Number(year.value) < Number(year.getAttribute('min'))) { 45 | year.setCustomValidity( 46 | `Year must be greater than or equal to ${year.getAttribute('min')}`, 47 | ); 48 | } else if (Number(year.value) > Number(year.getAttribute('max'))) { 49 | year.setCustomValidity( 50 | `Year must be less than or equal to ${year.getAttribute('max')}`, 51 | ); 52 | } 53 | }); 54 | 55 | // Manage API Key visibility 56 | store.subscribe((state) => { 57 | console.log(state); 58 | if (state.key) { 59 | apikey.value = state.key; 60 | apikey.closest('.form--group').style.display = 'none'; 61 | } else { 62 | apikey.closest('.form--group').style.display = 'block'; 63 | } 64 | }); 65 | 66 | // Manage Movie lookup 67 | store.subscribe(async (state) => { 68 | const movies = state.movies; 69 | output.innerHTML = ''; 70 | if (movies.length > 0) { 71 | for (const movie of movies) { 72 | const movieElement = document.createElement('movie-element'); 73 | movieElement.setAttribute('poster', movie.Poster); 74 | movieElement.setAttribute('title', movie.Title); 75 | movieElement.setAttribute('year', movie.Year); 76 | movieElement.setAttribute('imdb', movie.imdbID); 77 | movieElement.setAttribute('notes', state?.notes[movie.imdbID] || ''); 78 | output.append(movieElement); 79 | } 80 | } else if (!state.search && state.favorites) { 81 | if (state.favorites) { 82 | const db = await database; 83 | const movies = await Promise.all( 84 | state.favorites.map((id) => db.get('movies', id)), 85 | ); 86 | if (movies.length > 0) { 87 | for (const movie of movies) { 88 | const movieElement = document.createElement('movie-element'); 89 | movieElement.setAttribute('poster', movie.Poster); 90 | movieElement.setAttribute('title', movie.Title); 91 | movieElement.setAttribute('year', movie.Year); 92 | movieElement.setAttribute('imdb', movie.imdbID); 93 | movieElement.setAttribute('notes', state?.notes[movie.imdbID] || ''); 94 | output.append(movieElement); 95 | } 96 | } 97 | } 98 | } 99 | }); 100 | 101 | form.addEventListener('submit', async (e) => { 102 | e.preventDefault(); 103 | const formData = new FormData(form); 104 | const search = Object.fromEntries(formData.entries()); 105 | const inputs = form.querySelectorAll('input, button, textarea'); 106 | 107 | // Disable all inputs 108 | for (const input of inputs) { 109 | input.disabled = true; 110 | } 111 | 112 | store.search(search); 113 | 114 | // Enable all inputs 115 | for (const input of inputs) { 116 | input.disabled = false; 117 | } 118 | }); 119 | 120 | form.addEventListener('reset', () => { 121 | store.reset(); 122 | }); 123 | -------------------------------------------------------------------------------- /movie-app/js/movie.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2022 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import { store } from './state.js'; 18 | 19 | class Movie extends HTMLElement { 20 | constructor() { 21 | super(); 22 | const shadow = this.attachShadow({ mode: 'open' }); 23 | const template = document 24 | .querySelector('#movie-template') 25 | .content.cloneNode(true); 26 | shadow.append(template); 27 | 28 | this._poster = this.shadowRoot.querySelector('.movie--poster'); 29 | this._title = this.shadowRoot.querySelector('.movie--title'); 30 | this._year = this.shadowRoot.querySelector('.movie--year'); 31 | 32 | this._favorite = this.shadowRoot.querySelector('.movie--favorite'); 33 | this._showNotes = this.shadowRoot.querySelector('.movie--show-notes'); 34 | this._notes = this.shadowRoot.querySelector('.movie--notes'); 35 | } 36 | 37 | static get observedAttributes() { 38 | return ['poster', 'title', 'year', 'imdb', 'notes', 'visible-notes']; 39 | } 40 | attributeChangedCallback(name, oldValue, newValue) { 41 | if (oldValue === newValue) return; 42 | 43 | if (name === 'poster') { 44 | this._poster.src = newValue; 45 | this._poster.alt = `Poster for ${this.title}`; 46 | } 47 | 48 | if (name === 'title') { 49 | this._title.textContent = newValue; 50 | } 51 | 52 | if (name === 'year') { 53 | this._year.textContent = newValue; 54 | } 55 | 56 | if (name === 'notes') { 57 | this._notes.textContent = newValue; 58 | } 59 | 60 | if (name === 'visible-notes') { 61 | console.log('Hello'); 62 | } 63 | } 64 | 65 | connectedCallback() { 66 | const id = this.getAttribute('imdb'); 67 | 68 | this._favorite.addEventListener('click', () => { 69 | store.toggleFavorite(id); 70 | }); 71 | 72 | this._notes.addEventListener('input', (e) => { 73 | store.setNote(id, e.target.value); 74 | }); 75 | 76 | this._showNotes.addEventListener('click', () => { 77 | store.toggleNoteVisibility(id); 78 | }); 79 | 80 | store.subscribe((state) => { 81 | // Manage notes visibility 82 | if (state.visibleNotes) { 83 | if (state.visibleNotes[id]) { 84 | this._showNotes.textContent = 'Hide notes'; 85 | this._notes.classList.remove('hidden'); 86 | 87 | // Set the cursor at the end of the text area's length 88 | const end = this._notes.value.length; 89 | this._notes.setSelectionRange(end, end); 90 | this._notes.focus(); 91 | } else { 92 | this._showNotes.textContent = 'Show notes'; 93 | this._notes.classList.add('hidden'); 94 | } 95 | } 96 | 97 | // Manage favoriting 98 | if (state?.favorites?.includes(id)) { 99 | this._favorite.textContent = 'Unfavorite'; 100 | } else { 101 | this._favorite.textContent = 'Favorite'; 102 | } 103 | }); 104 | } 105 | } 106 | 107 | if (customElements.get('movie-element') === undefined) { 108 | customElements.define('movie-element', Movie); 109 | } 110 | -------------------------------------------------------------------------------- /movie-app/js/state.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2022 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | // Import our database 18 | import { database } from './database'; 19 | 20 | // Create a new state manager 21 | class StoreManager { 22 | constructor(init = {}) { 23 | // Grab the current "this" context 24 | const self = this; 25 | // Create an array for subscribers 26 | this._subscribers = []; 27 | 28 | // // Wait for our database to be ready 29 | database.then(async (db) => { 30 | // When ready, make the database available to the state manager 31 | this.db = db; 32 | 33 | // Get the key from the database 34 | const key = await db.get('settings', 'key'); 35 | if (key) { 36 | this._state.key = key; 37 | } 38 | 39 | // Get favorites from the database 40 | const favorites = await db.get('settings', 'favorites'); 41 | if (favorites) { 42 | this._state.favorites = favorites; 43 | } 44 | 45 | // Get notes from the database 46 | const notes = await db.getAll('notes'); 47 | if (notes.length) { 48 | this._state.notes = 49 | Object.fromEntries(notes.map(({ imdbID, note }) => [imdbID, note])) || 50 | {}; 51 | } 52 | }); 53 | 54 | // Create the internal state proxy 55 | this._state = new Proxy(init, { 56 | // Make set an async function so we can use our database to save it when it's updated 57 | async set(target, key, value) { 58 | // Set the key equal to the value 59 | target[key] = value; 60 | 61 | // Save items to the database, if it's available 62 | if (self.db) { 63 | if (key === 'key') { 64 | await self.db.put('settings', value, 'key'); 65 | } 66 | 67 | if (key === 'favorites') { 68 | await self.db.put('settings', value, 'favorites'); 69 | const movies = target.movies 70 | .filter((movie) => value.includes(movie.imdbID)) 71 | .map((movie) => self.db.put('movies', movie)); 72 | 73 | await Promise.all(movies); 74 | } 75 | 76 | if (key === 'notes') { 77 | await Promise.all( 78 | Object.entries(value).map(([id, note]) => 79 | self.db.put('notes', { note, imdbID: id }), 80 | ), 81 | ); 82 | } 83 | } 84 | 85 | // Loop through each subscriber and call them 86 | for (const subscriber of self._subscribers) { 87 | subscriber(target); 88 | } 89 | 90 | // Return true to indicate that the set was successful 91 | return true; 92 | }, 93 | }); 94 | } 95 | 96 | // Let things subscribe to the state manager 97 | subscribe(cb) { 98 | if (typeof cb !== 'function') { 99 | throw new Error('Callback is not a function'); 100 | } 101 | this._subscribers.push(cb); 102 | cb(this._state); 103 | } 104 | 105 | // Get the current state 106 | state(key) { 107 | if (key) { 108 | return this._state[key]; 109 | } 110 | return this._state; 111 | } 112 | 113 | // Action to add a comment to the state 114 | search(lookup) { 115 | if (lookup.key) { 116 | this._state.key = lookup.key; 117 | } 118 | 119 | this._state.search = { 120 | title: lookup.title, 121 | year: lookup.year || '', 122 | }; 123 | 124 | this._state.error = ''; 125 | 126 | this.movieLookup(); 127 | } 128 | 129 | reset() { 130 | this._state.search = null; 131 | this._state.movies = []; 132 | } 133 | 134 | toggleNoteVisibility(id) { 135 | const visibility = this.state('visibleNotes') || {}; 136 | if (visibility[id] === true) { 137 | visibility[id] = false; 138 | } else { 139 | visibility[id] = true; 140 | } 141 | this._state.visibleNotes = visibility; 142 | } 143 | 144 | toggleFavorite(id) { 145 | const favorites = this.state('favorites') || []; 146 | 147 | if (favorites.includes(id)) { 148 | favorites.splice(favorites.indexOf(id), 1); 149 | } else { 150 | favorites.push(id); 151 | } 152 | 153 | this._state.favorites = favorites; 154 | } 155 | 156 | setNote(id, note) { 157 | const notes = this.state('notes') || {}; 158 | notes[id] = note; 159 | this._state.notes = notes; 160 | } 161 | 162 | async movieLookup() { 163 | let key = this.state('key'); 164 | let search = this.state('search'); 165 | 166 | if (!key) { 167 | return (this._state.error = 'No API Key'); 168 | } 169 | 170 | let query = `https://www.omdbapi.com/?apikey=${key}&s=${search.title}`; 171 | if (search.year) { 172 | query += `&y=${search.year}`; 173 | } 174 | 175 | try { 176 | const response = await fetch(query); 177 | const data = await response.json(); 178 | if (data.Response === 'False') { 179 | // Show error message 180 | this._state.error = data.Error; 181 | } 182 | 183 | // Make sure this is an array 184 | if (Array.isArray(data.Search)) { 185 | this._state.movies = data.Search; 186 | } else { 187 | this._state.movies = []; 188 | } 189 | } catch (e) { 190 | this._state.error = e.message; 191 | } 192 | } 193 | } 194 | 195 | export const store = new StoreManager({ search: '', movies: [] }); 196 | -------------------------------------------------------------------------------- /movie-app/style.css: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2022 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | input:invalid { 18 | border: 1px solid red; 19 | } 20 | 21 | label { 22 | display: block; 23 | } 24 | 25 | .required:after { 26 | content: ' *'; 27 | color: red; 28 | } 29 | 30 | .form--group { 31 | margin-bottom: 1rem; 32 | } 33 | -------------------------------------------------------------------------------- /movie-lookup/index.html: -------------------------------------------------------------------------------- 1 | 2 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | Movie Lookup 24 | 25 | 26 | 27 | 28 | 71 |
72 | 73 | 74 | -------------------------------------------------------------------------------- /movie-lookup/main.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2022 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | const form = document.querySelector('#search'); 18 | const required = document.querySelectorAll('[required]'); 19 | const year = document.querySelector('#year'); 20 | const output = document.querySelector('#output'); 21 | 22 | // Add required class to labels 23 | for (const input of required) { 24 | input 25 | .closest('.form--group') 26 | .querySelector('label') 27 | .classList.add('required'); 28 | } 29 | 30 | // Handle custom validation for year 31 | year.setAttribute('max', new Date().getFullYear()); 32 | year.addEventListener('input', (e) => { 33 | year.setCustomValidity(''); 34 | year.checkValidity(); 35 | }); 36 | 37 | // Instead of default error messages, show custom error messages 38 | year.addEventListener('invalid', () => { 39 | if (Number(year.value) < Number(year.getAttribute('min'))) { 40 | year.setCustomValidity( 41 | `Year must be greater than or equal to ${year.getAttribute('min')}`, 42 | ); 43 | } else if (Number(year.value) > Number(year.getAttribute('max'))) { 44 | year.setCustomValidity( 45 | `Year must be less than or equal to ${year.getAttribute('max')}`, 46 | ); 47 | } 48 | }); 49 | 50 | form.addEventListener('submit', async (e) => { 51 | e.preventDefault(); 52 | const formData = new FormData(form); 53 | const search = Object.fromEntries(formData.entries()); 54 | const inputs = form.querySelectorAll('input, button, textarea'); 55 | 56 | // Remove all previous results. innerHTML is OK here because we're replacing it with an empty string so not potential issue with XSS 57 | output.innerHTML = ''; 58 | 59 | // Disable all inputs 60 | for (const input of inputs) { 61 | input.disabled = true; 62 | } 63 | 64 | try { 65 | let query = `https://www.omdbapi.com/?apikey=${search.key}&t=${search.title}`; 66 | if (search.year) { 67 | query += `&y=${search.year}`; 68 | } 69 | if (search.plot) { 70 | query += `&plot=${search.plot}`; 71 | } 72 | const response = await fetch(query); 73 | const data = await response.json(); 74 | if (data.Response === 'False') { 75 | // Show error message 76 | const error = document.createElement('p'); 77 | error.innerText = 'No results found'; 78 | output.append(error); 79 | } 80 | 81 | // Create an element to hold the movie results 82 | const movie = document.createElement('figure'); 83 | movie.classList.add('movie'); 84 | // Create an image element for the poster 85 | const img = document.createElement('img'); 86 | img.src = data.Poster; 87 | img.alt = `Poster for ${data.Title}`; // Include alt text for screen readers whenever including an image 88 | movie.append(img); // Add it to the movie results element 89 | 90 | // Create a holder for the movie details 91 | const caption = document.createElement('figcaption'); 92 | // Create a heading for the movie title 93 | const title = document.createElement('h2'); 94 | title.innerText = data.Title; 95 | caption.append(title); 96 | // Display the year the movie was released 97 | const year = document.createElement('p'); 98 | year.innerText = data.Year; 99 | caption.append(year); 100 | // Display the movie's rating 101 | const rating = document.createElement('p'); 102 | rating.innerText = data.Rated; 103 | caption.append(rating); 104 | // Display the movie's plot 105 | const plot = document.createElement('p'); 106 | plot.innerText = data.Plot; 107 | caption.append(plot); 108 | 109 | // Add the caption to the movie results 110 | movie.append(caption); 111 | 112 | // Add the movie results to the page 113 | output.append(movie); 114 | } catch (e) { 115 | // Show error message 116 | const error = document.createElement('p'); 117 | error.innerText = 118 | 'There was an error with your search, please check your API key and try again in a few minutes'; 119 | output.append(error); 120 | } 121 | 122 | // Enable all inputs 123 | for (const input of inputs) { 124 | input.disabled = false; 125 | } 126 | }); 127 | -------------------------------------------------------------------------------- /movie-lookup/style.css: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2022 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | input:invalid { 18 | border: 1px solid red; 19 | } 20 | 21 | label { 22 | display: block; 23 | } 24 | 25 | .required:after { 26 | content: ' *'; 27 | color: red; 28 | } 29 | 30 | .form--group { 31 | margin-bottom: 1rem; 32 | } 33 | -------------------------------------------------------------------------------- /package-lock.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "assignments", 3 | "version": "0.0.0", 4 | "lockfileVersion": 1, 5 | "requires": true, 6 | "dependencies": { 7 | "@esbuild/linux-loong64": { 8 | "version": "0.14.54", 9 | "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.14.54.tgz", 10 | "integrity": "sha512-bZBrLAIX1kpWelV0XemxBZllyRmM6vgFQQG2GdNb+r3Fkp0FOh1NJSvekXDs7jq70k4euu1cryLMfU+mTXlEpw==", 11 | "dev": true, 12 | "optional": true 13 | }, 14 | "esbuild": { 15 | "version": "0.14.54", 16 | "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.14.54.tgz", 17 | "integrity": "sha512-Cy9llcy8DvET5uznocPyqL3BFRrFXSVqbgpMJ9Wz8oVjZlh/zUSNbPRbov0VX7VxN2JH1Oa0uNxZ7eLRb62pJA==", 18 | "dev": true, 19 | "requires": { 20 | "@esbuild/linux-loong64": "0.14.54", 21 | "esbuild-android-64": "0.14.54", 22 | "esbuild-android-arm64": "0.14.54", 23 | "esbuild-darwin-64": "0.14.54", 24 | "esbuild-darwin-arm64": "0.14.54", 25 | "esbuild-freebsd-64": "0.14.54", 26 | "esbuild-freebsd-arm64": "0.14.54", 27 | "esbuild-linux-32": "0.14.54", 28 | "esbuild-linux-64": "0.14.54", 29 | "esbuild-linux-arm": "0.14.54", 30 | "esbuild-linux-arm64": "0.14.54", 31 | "esbuild-linux-mips64le": "0.14.54", 32 | "esbuild-linux-ppc64le": "0.14.54", 33 | "esbuild-linux-riscv64": "0.14.54", 34 | "esbuild-linux-s390x": "0.14.54", 35 | "esbuild-netbsd-64": "0.14.54", 36 | "esbuild-openbsd-64": "0.14.54", 37 | "esbuild-sunos-64": "0.14.54", 38 | "esbuild-windows-32": "0.14.54", 39 | "esbuild-windows-64": "0.14.54", 40 | "esbuild-windows-arm64": "0.14.54" 41 | } 42 | }, 43 | "esbuild-android-64": { 44 | "version": "0.14.54", 45 | "resolved": "https://registry.npmjs.org/esbuild-android-64/-/esbuild-android-64-0.14.54.tgz", 46 | "integrity": "sha512-Tz2++Aqqz0rJ7kYBfz+iqyE3QMycD4vk7LBRyWaAVFgFtQ/O8EJOnVmTOiDWYZ/uYzB4kvP+bqejYdVKzE5lAQ==", 47 | "dev": true, 48 | "optional": true 49 | }, 50 | "esbuild-android-arm64": { 51 | "version": "0.14.54", 52 | "resolved": "https://registry.npmjs.org/esbuild-android-arm64/-/esbuild-android-arm64-0.14.54.tgz", 53 | "integrity": "sha512-F9E+/QDi9sSkLaClO8SOV6etqPd+5DgJje1F9lOWoNncDdOBL2YF59IhsWATSt0TLZbYCf3pNlTHvVV5VfHdvg==", 54 | "dev": true, 55 | "optional": true 56 | }, 57 | "esbuild-darwin-64": { 58 | "version": "0.14.54", 59 | "resolved": "https://registry.npmjs.org/esbuild-darwin-64/-/esbuild-darwin-64-0.14.54.tgz", 60 | "integrity": "sha512-jtdKWV3nBviOd5v4hOpkVmpxsBy90CGzebpbO9beiqUYVMBtSc0AL9zGftFuBon7PNDcdvNCEuQqw2x0wP9yug==", 61 | "dev": true, 62 | "optional": true 63 | }, 64 | "esbuild-darwin-arm64": { 65 | "version": "0.14.54", 66 | "resolved": "https://registry.npmjs.org/esbuild-darwin-arm64/-/esbuild-darwin-arm64-0.14.54.tgz", 67 | "integrity": "sha512-OPafJHD2oUPyvJMrsCvDGkRrVCar5aVyHfWGQzY1dWnzErjrDuSETxwA2HSsyg2jORLY8yBfzc1MIpUkXlctmw==", 68 | "dev": true, 69 | "optional": true 70 | }, 71 | "esbuild-freebsd-64": { 72 | "version": "0.14.54", 73 | "resolved": "https://registry.npmjs.org/esbuild-freebsd-64/-/esbuild-freebsd-64-0.14.54.tgz", 74 | "integrity": "sha512-OKwd4gmwHqOTp4mOGZKe/XUlbDJ4Q9TjX0hMPIDBUWWu/kwhBAudJdBoxnjNf9ocIB6GN6CPowYpR/hRCbSYAg==", 75 | "dev": true, 76 | "optional": true 77 | }, 78 | "esbuild-freebsd-arm64": { 79 | "version": "0.14.54", 80 | "resolved": "https://registry.npmjs.org/esbuild-freebsd-arm64/-/esbuild-freebsd-arm64-0.14.54.tgz", 81 | "integrity": "sha512-sFwueGr7OvIFiQT6WeG0jRLjkjdqWWSrfbVwZp8iMP+8UHEHRBvlaxL6IuKNDwAozNUmbb8nIMXa7oAOARGs1Q==", 82 | "dev": true, 83 | "optional": true 84 | }, 85 | "esbuild-linux-32": { 86 | "version": "0.14.54", 87 | "resolved": "https://registry.npmjs.org/esbuild-linux-32/-/esbuild-linux-32-0.14.54.tgz", 88 | "integrity": "sha512-1ZuY+JDI//WmklKlBgJnglpUL1owm2OX+8E1syCD6UAxcMM/XoWd76OHSjl/0MR0LisSAXDqgjT3uJqT67O3qw==", 89 | "dev": true, 90 | "optional": true 91 | }, 92 | "esbuild-linux-64": { 93 | "version": "0.14.54", 94 | "resolved": "https://registry.npmjs.org/esbuild-linux-64/-/esbuild-linux-64-0.14.54.tgz", 95 | "integrity": "sha512-EgjAgH5HwTbtNsTqQOXWApBaPVdDn7XcK+/PtJwZLT1UmpLoznPd8c5CxqsH2dQK3j05YsB3L17T8vE7cp4cCg==", 96 | "dev": true, 97 | "optional": true 98 | }, 99 | "esbuild-linux-arm": { 100 | "version": "0.14.54", 101 | "resolved": "https://registry.npmjs.org/esbuild-linux-arm/-/esbuild-linux-arm-0.14.54.tgz", 102 | "integrity": "sha512-qqz/SjemQhVMTnvcLGoLOdFpCYbz4v4fUo+TfsWG+1aOu70/80RV6bgNpR2JCrppV2moUQkww+6bWxXRL9YMGw==", 103 | "dev": true, 104 | "optional": true 105 | }, 106 | "esbuild-linux-arm64": { 107 | "version": "0.14.54", 108 | "resolved": "https://registry.npmjs.org/esbuild-linux-arm64/-/esbuild-linux-arm64-0.14.54.tgz", 109 | "integrity": "sha512-WL71L+0Rwv+Gv/HTmxTEmpv0UgmxYa5ftZILVi2QmZBgX3q7+tDeOQNqGtdXSdsL8TQi1vIaVFHUPDe0O0kdig==", 110 | "dev": true, 111 | "optional": true 112 | }, 113 | "esbuild-linux-mips64le": { 114 | "version": "0.14.54", 115 | "resolved": "https://registry.npmjs.org/esbuild-linux-mips64le/-/esbuild-linux-mips64le-0.14.54.tgz", 116 | "integrity": "sha512-qTHGQB8D1etd0u1+sB6p0ikLKRVuCWhYQhAHRPkO+OF3I/iSlTKNNS0Lh2Oc0g0UFGguaFZZiPJdJey3AGpAlw==", 117 | "dev": true, 118 | "optional": true 119 | }, 120 | "esbuild-linux-ppc64le": { 121 | "version": "0.14.54", 122 | "resolved": "https://registry.npmjs.org/esbuild-linux-ppc64le/-/esbuild-linux-ppc64le-0.14.54.tgz", 123 | "integrity": "sha512-j3OMlzHiqwZBDPRCDFKcx595XVfOfOnv68Ax3U4UKZ3MTYQB5Yz3X1mn5GnodEVYzhtZgxEBidLWeIs8FDSfrQ==", 124 | "dev": true, 125 | "optional": true 126 | }, 127 | "esbuild-linux-riscv64": { 128 | "version": "0.14.54", 129 | "resolved": "https://registry.npmjs.org/esbuild-linux-riscv64/-/esbuild-linux-riscv64-0.14.54.tgz", 130 | "integrity": "sha512-y7Vt7Wl9dkOGZjxQZnDAqqn+XOqFD7IMWiewY5SPlNlzMX39ocPQlOaoxvT4FllA5viyV26/QzHtvTjVNOxHZg==", 131 | "dev": true, 132 | "optional": true 133 | }, 134 | "esbuild-linux-s390x": { 135 | "version": "0.14.54", 136 | "resolved": "https://registry.npmjs.org/esbuild-linux-s390x/-/esbuild-linux-s390x-0.14.54.tgz", 137 | "integrity": "sha512-zaHpW9dziAsi7lRcyV4r8dhfG1qBidQWUXweUjnw+lliChJqQr+6XD71K41oEIC3Mx1KStovEmlzm+MkGZHnHA==", 138 | "dev": true, 139 | "optional": true 140 | }, 141 | "esbuild-netbsd-64": { 142 | "version": "0.14.54", 143 | "resolved": "https://registry.npmjs.org/esbuild-netbsd-64/-/esbuild-netbsd-64-0.14.54.tgz", 144 | "integrity": "sha512-PR01lmIMnfJTgeU9VJTDY9ZerDWVFIUzAtJuDHwwceppW7cQWjBBqP48NdeRtoP04/AtO9a7w3viI+PIDr6d+w==", 145 | "dev": true, 146 | "optional": true 147 | }, 148 | "esbuild-openbsd-64": { 149 | "version": "0.14.54", 150 | "resolved": "https://registry.npmjs.org/esbuild-openbsd-64/-/esbuild-openbsd-64-0.14.54.tgz", 151 | "integrity": "sha512-Qyk7ikT2o7Wu76UsvvDS5q0amJvmRzDyVlL0qf5VLsLchjCa1+IAvd8kTBgUxD7VBUUVgItLkk609ZHUc1oCaw==", 152 | "dev": true, 153 | "optional": true 154 | }, 155 | "esbuild-sunos-64": { 156 | "version": "0.14.54", 157 | "resolved": "https://registry.npmjs.org/esbuild-sunos-64/-/esbuild-sunos-64-0.14.54.tgz", 158 | "integrity": "sha512-28GZ24KmMSeKi5ueWzMcco6EBHStL3B6ubM7M51RmPwXQGLe0teBGJocmWhgwccA1GeFXqxzILIxXpHbl9Q/Kw==", 159 | "dev": true, 160 | "optional": true 161 | }, 162 | "esbuild-windows-32": { 163 | "version": "0.14.54", 164 | "resolved": "https://registry.npmjs.org/esbuild-windows-32/-/esbuild-windows-32-0.14.54.tgz", 165 | "integrity": "sha512-T+rdZW19ql9MjS7pixmZYVObd9G7kcaZo+sETqNH4RCkuuYSuv9AGHUVnPoP9hhuE1WM1ZimHz1CIBHBboLU7w==", 166 | "dev": true, 167 | "optional": true 168 | }, 169 | "esbuild-windows-64": { 170 | "version": "0.14.54", 171 | "resolved": "https://registry.npmjs.org/esbuild-windows-64/-/esbuild-windows-64-0.14.54.tgz", 172 | "integrity": "sha512-AoHTRBUuYwXtZhjXZbA1pGfTo8cJo3vZIcWGLiUcTNgHpJJMC1rVA44ZereBHMJtotyN71S8Qw0npiCIkW96cQ==", 173 | "dev": true, 174 | "optional": true 175 | }, 176 | "esbuild-windows-arm64": { 177 | "version": "0.14.54", 178 | "resolved": "https://registry.npmjs.org/esbuild-windows-arm64/-/esbuild-windows-arm64-0.14.54.tgz", 179 | "integrity": "sha512-M0kuUvXhot1zOISQGXwWn6YtS+Y/1RT9WrVIOywZnJHo3jCDyewAc79aKNQWFCQm+xNHVTq9h8dZKvygoXQQRg==", 180 | "dev": true, 181 | "optional": true 182 | }, 183 | "fsevents": { 184 | "version": "2.3.2", 185 | "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz", 186 | "integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==", 187 | "dev": true, 188 | "optional": true 189 | }, 190 | "function-bind": { 191 | "version": "1.1.1", 192 | "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.1.tgz", 193 | "integrity": "sha512-yIovAzMX49sF8Yl58fSCWJ5svSLuaibPxXQJFLmBObTuCr0Mf1KiPopGM9NiFjiYBCbfaa2Fh6breQ6ANVTI0A==", 194 | "dev": true 195 | }, 196 | "has": { 197 | "version": "1.0.3", 198 | "resolved": "https://registry.npmjs.org/has/-/has-1.0.3.tgz", 199 | "integrity": "sha512-f2dvO0VU6Oej7RkWJGrehjbzMAjFp5/VKPp5tTpWIV4JHHZK1/BxbFRtf/siA2SWTe09caDmVtYYzWEIbBS4zw==", 200 | "dev": true, 201 | "requires": { 202 | "function-bind": "^1.1.1" 203 | } 204 | }, 205 | "idb": { 206 | "version": "7.0.2", 207 | "resolved": "https://registry.npmjs.org/idb/-/idb-7.0.2.tgz", 208 | "integrity": "sha512-jjKrT1EnyZewQ/gCBb/eyiYrhGzws2FeY92Yx8qT9S9GeQAmo4JFVIiWRIfKW/6Ob9A+UDAOW9j9jn58fy2HIg==" 209 | }, 210 | "is-core-module": { 211 | "version": "2.10.0", 212 | "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.10.0.tgz", 213 | "integrity": "sha512-Erxj2n/LDAZ7H8WNJXd9tw38GYM3dv8rk8Zcs+jJuxYTW7sozH+SS8NtrSjVL1/vpLvWi1hxy96IzjJ3EHTJJg==", 214 | "dev": true, 215 | "requires": { 216 | "has": "^1.0.3" 217 | } 218 | }, 219 | "nanoid": { 220 | "version": "3.3.4", 221 | "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.4.tgz", 222 | "integrity": "sha512-MqBkQh/OHTS2egovRtLk45wEyNXwF+cokD+1YPf9u5VfJiRdAiRwB2froX5Co9Rh20xs4siNPm8naNotSD6RBw==", 223 | "dev": true 224 | }, 225 | "path-parse": { 226 | "version": "1.0.7", 227 | "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.7.tgz", 228 | "integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==", 229 | "dev": true 230 | }, 231 | "picocolors": { 232 | "version": "1.0.0", 233 | "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.0.0.tgz", 234 | "integrity": "sha512-1fygroTLlHu66zi26VoTDv8yRgm0Fccecssto+MhsZ0D/DGW2sm8E8AjW7NU5VVTRt5GxbeZ5qBuJr+HyLYkjQ==", 235 | "dev": true 236 | }, 237 | "postcss": { 238 | "version": "8.4.16", 239 | "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.4.16.tgz", 240 | "integrity": "sha512-ipHE1XBvKzm5xI7hiHCZJCSugxvsdq2mPnsq5+UF+VHCjiBvtDrlxJfMBToWaP9D5XlgNmcFGqoHmUn0EYEaRQ==", 241 | "dev": true, 242 | "requires": { 243 | "nanoid": "^3.3.4", 244 | "picocolors": "^1.0.0", 245 | "source-map-js": "^1.0.2" 246 | } 247 | }, 248 | "prettier": { 249 | "version": "2.7.1", 250 | "resolved": "https://registry.npmjs.org/prettier/-/prettier-2.7.1.tgz", 251 | "integrity": "sha512-ujppO+MkdPqoVINuDFDRLClm7D78qbDt0/NR+wp5FqEZOoTNAjPHWj17QRhu7geIHJfcNhRk1XVQmF8Bp3ye+g==", 252 | "dev": true 253 | }, 254 | "resolve": { 255 | "version": "1.22.1", 256 | "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.1.tgz", 257 | "integrity": "sha512-nBpuuYuY5jFsli/JIs1oldw6fOQCBioohqWZg/2hiaOybXOft4lonv85uDOKXdf8rhyK159cxU5cDcK/NKk8zw==", 258 | "dev": true, 259 | "requires": { 260 | "is-core-module": "^2.9.0", 261 | "path-parse": "^1.0.7", 262 | "supports-preserve-symlinks-flag": "^1.0.0" 263 | } 264 | }, 265 | "rollup": { 266 | "version": "2.77.3", 267 | "resolved": "https://registry.npmjs.org/rollup/-/rollup-2.77.3.tgz", 268 | "integrity": "sha512-/qxNTG7FbmefJWoeeYJFbHehJ2HNWnjkAFRKzWN/45eNBBF/r8lo992CwcJXEzyVxs5FmfId+vTSTQDb+bxA+g==", 269 | "dev": true, 270 | "requires": { 271 | "fsevents": "~2.3.2" 272 | } 273 | }, 274 | "source-map-js": { 275 | "version": "1.0.2", 276 | "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.0.2.tgz", 277 | "integrity": "sha512-R0XvVJ9WusLiqTCEiGCmICCMplcCkIwwR11mOSD9CR5u+IXYdiseeEuXCVAjS54zqwkLcPNnmU4OeJ6tUrWhDw==", 278 | "dev": true 279 | }, 280 | "supports-preserve-symlinks-flag": { 281 | "version": "1.0.0", 282 | "resolved": "https://registry.npmjs.org/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz", 283 | "integrity": "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==", 284 | "dev": true 285 | }, 286 | "vite": { 287 | "version": "3.0.9", 288 | "resolved": "https://registry.npmjs.org/vite/-/vite-3.0.9.tgz", 289 | "integrity": "sha512-waYABTM+G6DBTCpYAxvevpG50UOlZuynR0ckTK5PawNVt7ebX6X7wNXHaGIO6wYYFXSM7/WcuFuO2QzhBB6aMw==", 290 | "dev": true, 291 | "requires": { 292 | "esbuild": "^0.14.47", 293 | "fsevents": "~2.3.2", 294 | "postcss": "^8.4.16", 295 | "resolve": "^1.22.1", 296 | "rollup": ">=2.75.6 <2.77.0 || ~2.77.0" 297 | } 298 | } 299 | } 300 | } 301 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "assignments", 3 | "private": true, 4 | "version": "0.0.0", 5 | "type": "module", 6 | "scripts": { 7 | "start": "vite", 8 | "dev": "vite", 9 | "build": "vite build", 10 | "preview": "vite preview", 11 | "test": "prettier -c .", 12 | "fix": "prettier --write ." 13 | }, 14 | "devDependencies": { 15 | "prettier": "^2.7.1", 16 | "vite": "^3.0.7" 17 | }, 18 | "dependencies": { 19 | "idb": "^7.0.2" 20 | }, 21 | "license": "Apache-2.0" 22 | } 23 | -------------------------------------------------------------------------------- /picsum/index.html: -------------------------------------------------------------------------------- 1 | 2 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | Picsum 24 | 25 | 26 | 27 | 28 | 29 | -------------------------------------------------------------------------------- /picsum/main.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2022 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | window.addEventListener('load', async () => { 18 | // Because there may be errors with `await`, we wrap our code in a try/catch block. 19 | try { 20 | // Await a list of image from Picsum, but limit it to 100 images 21 | const images = await fetch('https://picsum.photos/v2/list?limit=100'); 22 | // Fetch will give us a response, but not usable JSON. We need to await the response's JSON.to have something to work with 23 | const imageData = await images.json(); 24 | // Math.random() will return a random number between 0 and 1. We multiply it by 100 to get a number between 0 and 100, and round it down to get a number between 0 and 99. 25 | const number = Math.floor(Math.random() * 100); 26 | // Get the image at the random number's index in the imageData array 27 | const image = imageData[number]; 28 | // Create an element to put everything inside 29 | const output = document.createElement('figure'); 30 | // For ease of use, we set the element's innerHTML, using JavaScript template string to put in the pieces we need. 31 | // We need to use download_url instead of url because url points to a webpage to view the image, but we want the URL of the actual image 32 | output.innerHTML = `${image.author}

Author: ${image.author}

ID: ${image.id}

`; 33 | // We add the image to our page 34 | document.body.append(output); 35 | } catch (e) { 36 | // If there is an error, we log it to the console 37 | console.error(e); 38 | } 39 | }); 40 | -------------------------------------------------------------------------------- /picsum/style.css: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2022 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | img { 18 | max-height: 50vh; 19 | max-width: 50vw; 20 | } 21 | -------------------------------------------------------------------------------- /remembering-state/comment.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2022 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | // Create a new HTML element 18 | class MyComponent extends HTMLElement { 19 | constructor() { 20 | // Always call super first in constructor 21 | super(); 22 | 23 | // Create a shadow root 24 | const shadow = this.attachShadow({ mode: 'open' }); 25 | // Get our component template from the DOM and ad it to the shadow root 26 | const template = document.querySelector('#comment').content.cloneNode(true); 27 | shadow.append(template); 28 | 29 | // Get the elements from the shadow root where our content will be rendered 30 | this._name = this.shadowRoot.querySelector('.comment--name'); 31 | this._email = this.shadowRoot.querySelector('.comment--email'); 32 | this._body = this.shadowRoot.querySelector('.comment--body'); 33 | this._time = this.shadowRoot.querySelector('.comment--time'); 34 | } 35 | 36 | // Declare what attributes you want to listen for changes to 37 | static get observedAttributes() { 38 | return ['name', 'email', 'body', 'time']; 39 | } 40 | 41 | // Called when an observed attribute changes 42 | attributeChangedCallback(name, oldValue, newValue) { 43 | // If nothing's changed, don't continue 44 | if (oldValue === newValue) return; 45 | 46 | // Check if the changed attribute has a matching area to render the content 47 | if (this[`_${name}`]) { 48 | this[`_${name}`].textContent = newValue; 49 | } 50 | } 51 | } 52 | 53 | // Check to see if the custom element is defined 54 | if (customElements.get('my-comment') === undefined) { 55 | // If not, define the custom element 56 | customElements.define('my-comment', MyComponent); 57 | } 58 | -------------------------------------------------------------------------------- /remembering-state/database.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2022 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | // Import the Promise IndexedDB helper from IDB 18 | import { openDB } from 'idb'; 19 | 20 | // Open a database and export it so it can be used elsewhere 21 | export const database = openDB('my-db', 1, { 22 | upgrade(db) { 23 | // Create a "comments" object store, with "_id" as the key, and let that key automatically get added (and increment) if it's not already present when being inserted 24 | db.createObjectStore('comments', { 25 | keyPath: '_id', 26 | autoIncrement: true, 27 | }); 28 | }, 29 | }); 30 | -------------------------------------------------------------------------------- /remembering-state/index.html: -------------------------------------------------------------------------------- 1 | 2 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | Reusable Components 24 | 25 | 26 | 27 | 28 | 57 | 58 | A river flowing through rolling hills 62 |
63 |
64 | 65 | 66 |
67 |
68 | 69 | 70 |
71 |
72 | 73 | 74 |
75 |
76 | 80 |
81 | 82 |
83 | 84 |
85 |

Filter Comments

86 |
87 | 88 | 89 |
90 |
91 | 92 | 93 |
94 |
95 | 96 | 97 |
98 | 99 | 100 |
101 | 102 |
103 | 104 | 105 | -------------------------------------------------------------------------------- /remembering-state/main.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2022 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import './comment.js'; 18 | import { store } from './state.js'; 19 | 20 | // Grab elements from the DOM 21 | const required = document.querySelectorAll('[required]'); 22 | const form = document.querySelector('#comment-form'); 23 | const comments = document.querySelector('#comments'); 24 | 25 | // Add required class to required labels 26 | for (const input of required) { 27 | input 28 | .closest('.form--group') 29 | .querySelector('label') 30 | .classList.add('required'); 31 | } 32 | 33 | // Listen to form submission 34 | form.addEventListener('submit', (e) => { 35 | e.preventDefault(); 36 | // Grab the form data as an object 37 | const data = Object.fromEntries(new FormData(form).entries()); 38 | console.log(data); 39 | 40 | store.addComment(data); 41 | 42 | // Extra Credit: Reset the form and puts the cursor into the first input 43 | // Resets the form 44 | e.target.reset(); 45 | // Finds the first input in the form and focuses it 46 | e.target.querySelector('input, textarea, button').focus(); 47 | }); 48 | 49 | // Subscribe to the store to render comments 50 | store.subscribe((state) => { 51 | // Grab the comments from the store 52 | const allComments = state.filtered; 53 | console.log(allComments); 54 | 55 | // Removes all existing comments so we can re-render them 56 | comments.innerHTML = ''; 57 | 58 | // Loops over each comment, creates a custom my-comment element, sets the appropriate attributes, and appends it to the comments section 59 | for (const comment of allComments) { 60 | const myComment = document.createElement('my-comment'); 61 | myComment.setAttribute('name', comment.name); 62 | myComment.setAttribute('email', comment.email); 63 | myComment.setAttribute('body', comment.body); 64 | myComment.setAttribute('time', comment.date); 65 | comments.append(myComment); 66 | } 67 | }); 68 | 69 | // Manage Filters 70 | const filters = document.querySelector('#filters'); 71 | // Listen for the submit event on the filter form 72 | filters.addEventListener('submit', (e) => { 73 | e.preventDefault(); 74 | // Grab the form data as an object 75 | const data = Object.fromEntries(new FormData(filters).entries()); 76 | // Format it into a filter options object 77 | const options = { 78 | name: data['name-filter'], 79 | email: data['email-filter'], 80 | length: data['length-filter'], 81 | }; 82 | // Call the filter 83 | store.filter(options); 84 | }); 85 | 86 | // On form reset, also reset the filters in the state manager 87 | filters.addEventListener('reset', (e) => { 88 | store.filterReset(); 89 | e.target.querySelector('input, textarea, button').focus(); 90 | }); 91 | 92 | // Super bonus! Filter while someone types! 93 | // filters.addEventListener('input', (e) => { 94 | // e.preventDefault(); 95 | // // Grab the form data as an object 96 | // const data = Object.fromEntries(new FormData(filters).entries()); 97 | // // Format it into a filter options object 98 | // const options = { 99 | // name: data['name-filter'], 100 | // email: data['email-filter'], 101 | // length: data['length-filter'], 102 | // }; 103 | // // Call the filter 104 | // store.filter(options); 105 | // }); 106 | -------------------------------------------------------------------------------- /remembering-state/state.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2022 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | // Import our database 18 | import { database } from './database'; 19 | 20 | // Create a new state manager 21 | class StoreManager { 22 | constructor(init = {}) { 23 | // Grab the current "this" context 24 | const self = this; 25 | // Create an array for subscribers 26 | this._subscribers = []; 27 | 28 | // Wait for our database to be ready 29 | database.then(async (db) => { 30 | // When ready, make the database available to the state manager 31 | this.db = db; 32 | 33 | // Get all the comments in the database 34 | const comments = await db.getAll('comments'); 35 | // Set the comments state to the comments in the database 36 | this._state.comments = comments; 37 | 38 | // Call the filter function to make sure we get our properly filtered list 39 | this.filter(); 40 | }); 41 | 42 | // Create the internal state proxy 43 | this._state = new Proxy(init, { 44 | // Make set an async function so we can use our database to save it when it's updated 45 | async set(target, key, value) { 46 | // Set the key equal to the value 47 | target[key] = value; 48 | 49 | // If our database is available, save the state to the database 50 | if (self.db) { 51 | // If the key is "comments", save it to IndexedDB 52 | if (key === 'comments') { 53 | // Get the last comment in the array, which will be the one most recently added 54 | const item = value[value.length - 1]; 55 | 56 | // _id comes from the database. Don't try to save it if it already has one 57 | if (item && !item?._id) { 58 | // Save the item to the database 59 | await self.db.add('comments', item); 60 | } 61 | } 62 | } 63 | 64 | // Loop through each subscriber and call them 65 | for (const subscriber of self._subscribers) { 66 | subscriber(target); 67 | } 68 | 69 | // Return true to indicate that the set was successful 70 | return true; 71 | }, 72 | }); 73 | } 74 | 75 | // Let things subscribe to the state manager 76 | subscribe(cb) { 77 | if (typeof cb !== 'function') { 78 | throw new Error('Callback is not a function'); 79 | } 80 | this._subscribers.push(cb); 81 | cb(this._state); 82 | } 83 | 84 | // Action to add a comment to the state 85 | addComment(comment) { 86 | if (!comment.date) { 87 | comment.date = new Date(); 88 | } 89 | 90 | this._state.comments.push(comment); 91 | this._state.comments = this._state.comments; 92 | 93 | // Call the filter function to update the filtered state 94 | this.filter(); 95 | } 96 | 97 | // Action to filter the list of comments 98 | filter(options = {}) { 99 | // Get the current filter state, and merge it with the passed in options 100 | const filters = Object.assign(this._state.filters || {}, options); 101 | 102 | // Update the current filter state 103 | this._state.filters = filters; 104 | 105 | // Filter the comments based on the filters 106 | this._state.filtered = this._state.comments.filter((comment) => { 107 | // If there is a name filter, return whether the comment's name includes the filter's name, otherwise return true 108 | const name = filters.name 109 | ? comment.name.toLowerCase().includes(filters.name.toLowerCase()) 110 | : true; 111 | // If there is an email filter, return whether the comment's email includes the filter's email, otherwise return true 112 | const email = filters.email 113 | ? comment.email.toLowerCase().includes(filters.email.toLowerCase()) 114 | : true; 115 | // If there is a length filter, return whether the comment's length is greater than or equal to the filter's length, otherwise return true 116 | const length = !isNaN(Number(filters.length)) 117 | ? comment.body.length >= Number(filters.length) 118 | : true; 119 | 120 | // Return whether all of the above are true 121 | return name && email && length; 122 | }); 123 | } 124 | 125 | // Reset the filter 126 | filterReset() { 127 | // Reset the filter state 128 | this._state.filters = {}; 129 | // Call the filter function to update the filtered state 130 | this.filter(); 131 | } 132 | } 133 | 134 | export const store = new StoreManager({ comments: [], filtered: [] }); 135 | -------------------------------------------------------------------------------- /remembering-state/style.css: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2022 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | label { 18 | display: block; 19 | } 20 | 21 | label input { 22 | margin-right: 0.5rem; 23 | } 24 | 25 | .required:after { 26 | content: '*'; 27 | color: red; 28 | } 29 | -------------------------------------------------------------------------------- /reusable-component/index.html: -------------------------------------------------------------------------------- 1 | 2 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | Reusable Components 24 | 25 | 26 | 27 | 55 | 56 | 61 | 66 | 71 | 72 | 73 | -------------------------------------------------------------------------------- /reusable-component/main.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2022 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | // Create a new HTML element 18 | class MyComponent extends HTMLElement { 19 | constructor() { 20 | // Always call super first in constructor 21 | super(); 22 | 23 | // Create a shadow root 24 | const shadow = this.attachShadow({ mode: 'open' }); 25 | // Get our component template from the DOM and ad it to the shadow root 26 | const template = document.querySelector('#comment').content.cloneNode(true); 27 | shadow.append(template); 28 | 29 | // Get the elements from the shadow root where our content will be rendered 30 | this._name = this.shadowRoot.querySelector('.comment--name'); 31 | this._email = this.shadowRoot.querySelector('.comment--email'); 32 | this._body = this.shadowRoot.querySelector('.comment--body'); 33 | } 34 | 35 | // Declare what attributes you want to listen for changes to 36 | static get observedAttributes() { 37 | return ['name', 'email', 'body']; 38 | } 39 | 40 | // Called when an observed attribute changes 41 | attributeChangedCallback(name, oldValue, newValue) { 42 | // If nothing's changed, don't continue 43 | if (oldValue === newValue) return; 44 | 45 | // Check if the changed attribute has a matching area to render the content 46 | if (this[`_${name}`]) { 47 | this[`_${name}`].textContent = newValue; 48 | } 49 | } 50 | } 51 | 52 | // Check to see if the custom element is defined 53 | if (customElements.get('my-comment') === undefined) { 54 | // If not, define the custom element 55 | customElements.define('my-comment', MyComponent); 56 | } 57 | -------------------------------------------------------------------------------- /vite.config.js: -------------------------------------------------------------------------------- 1 | import { resolve } from 'path'; 2 | import { defineConfig } from 'vite'; 3 | 4 | export default defineConfig({ 5 | build: { 6 | rollupOptions: { 7 | input: { 8 | index: resolve(__dirname, 'index.html'), 9 | 'contact-form/index': resolve(__dirname, 'contact-form/index.html'), 10 | 'image-comment/index': resolve(__dirname, 'image-comment/index.html'), 11 | 'movie-app/index': resolve(__dirname, 'movie-app/index.html'), 12 | 'movie-app-alt-subscribe/index': resolve( 13 | __dirname, 14 | 'movie-app-alt-subscribe/index.html', 15 | ), 16 | 'movie-lookup/index': resolve(__dirname, 'movie-lookup/index.html'), 17 | picsum: resolve(__dirname, 'picsum/index.html'), 18 | 'remembering-state/index': resolve( 19 | __dirname, 20 | 'remembering-state/index.html', 21 | ), 22 | 'reusable-component/index': resolve( 23 | __dirname, 24 | 'reusable-component/index.html', 25 | ), 26 | }, 27 | }, 28 | }, 29 | }); 30 | --------------------------------------------------------------------------------