├── .dockerignore ├── .eslintignore ├── .eslintrc ├── .gitignore ├── .travis.yml ├── CONTRIBUTING.md ├── Dockerfile ├── LICENSE ├── README.md ├── build-documentation.js ├── build-webfundamentals.sh ├── elements ├── howto-accordion │ ├── README.md │ ├── demo.html │ ├── howto-accordion.e2etest.js │ ├── howto-accordion.js │ └── howto-accordion.unittest.js ├── howto-checkbox │ ├── README.md │ ├── demo.html │ ├── howto-checkbox.e2etest.js │ ├── howto-checkbox.js │ ├── howto-checkbox.unittest.js │ └── images │ │ ├── checked-checkbox-disabled.svg │ │ ├── checked-checkbox.svg │ │ ├── unchecked-checkbox-disabled.svg │ │ └── unchecked-checkbox.svg ├── howto-label │ ├── README.md │ ├── demo.html │ ├── fixtures │ │ ├── explicit-for.html │ │ ├── implicit-target.html │ │ └── nested-explicit-target.html │ ├── howto-label.e2etest.js │ ├── howto-label.js │ └── howto-label.unittest.js ├── howto-radio-group │ ├── README.md │ ├── demo.html │ ├── howto-radio-group.e2etest.js │ └── howto-radio-group.js ├── howto-tabs │ ├── README.md │ ├── demo.html │ ├── howto-tabs.e2etest.js │ ├── howto-tabs.js │ └── howto-tabs.unittest.js ├── howto-toggle-button │ ├── README.md │ ├── demo.html │ ├── howto-toggle-button.e2etest.js │ ├── howto-toggle-button.js │ └── howto-toggle-button.unittest.js └── howto-tooltip │ ├── README.md │ ├── demo.html │ ├── howto-tooltip.e2etest.js │ └── howto-tooltip.js ├── karma.conf.js ├── package-lock.json ├── package.json ├── publish.sh ├── run-e2e-tests.js ├── sectionizer.js ├── site-resources ├── demo.tpl.html ├── element.tpl.html ├── element.tpl.md ├── fonts │ ├── RobotoCondensed400.woff2 │ └── RobotoMono400.woff2 ├── index.tpl.html ├── scripts │ ├── bootstrap.js │ └── resizeobserver.min.js ├── static-header.md └── styles │ ├── main.css │ ├── main.devsite.css │ └── prism-solarizedlight.css └── tools ├── pr_preview.sh ├── selenium-helper.js └── testing-helper.js /.dockerignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | docs -------------------------------------------------------------------------------- /.eslintignore: -------------------------------------------------------------------------------- 1 | *.min.js 2 | -------------------------------------------------------------------------------- /.eslintrc: -------------------------------------------------------------------------------- 1 | { 2 | "env": { 3 | "browser": true, 4 | "es6": true, 5 | "mocha": true 6 | }, 7 | "parserOptions": { 8 | "ecmaVersion": "2017" 9 | }, 10 | // "extends": ["eslint:recommended", "google"], 11 | "extends": ["google"], 12 | "rules": { 13 | "max-len": ["error", {"ignoreComments": true}], 14 | "arrow-parens": 0, 15 | "valid-jsdoc": "off", 16 | "require-jsdoc": "off", 17 | "keyword-spacing": ["error"], 18 | "no-console": ["error", {"allow": ["warn", "error"]}], 19 | "no-extra-semi": ["error"], 20 | "nonblock-statement-body-position": ["error", "below"] 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | npm-debug.log.* 2 | node_modules 3 | docs 4 | .vscode 5 | .DS_Store 6 | webfundamentals 7 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | sudo: required 2 | language: node 3 | services: 4 | - docker 5 | 6 | before_install: 7 | - npm run docker-build 8 | 9 | script: 10 | - npm run docker-test 11 | 12 | deploy: 13 | skip_cleanup: true 14 | provider: script 15 | script: "tools/pr_preview.sh" 16 | on: 17 | all_branches: true 18 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # How to become a contributor and submit your own code 2 | 3 | ## Contributor License Agreements 4 | 5 | We'd love to accept your sample apps and patches! Before we can take them, we have to jump a couple of legal hurdles. 6 | 7 | Please fill out either the individual or corporate Contributor License Agreement (CLA). 8 | * If you are an individual writing original source code and you're sure you own the intellectual property, then you'll need to sign an [individual CLA](https://developers.google.com/open-source/cla/individual). 9 | * If you work for a company that wants to allow you to contribute your work, then you'll need to sign a [corporate CLA](https://developers.google.com/open-source/cla/corporate). 10 | 11 | Follow either of the two links above to access the appropriate CLA and instructions for how to sign and return it. Once we receive it, we'll be able to 12 | accept your pull requests. 13 | 14 | ## Contributing A Patch 15 | 16 | 1. Submit an issue describing your proposed change to the repo in question. 17 | 1. The repo owner will respond to your issue promptly. 18 | 1. If your proposed change is accepted, and you haven't already done so, sign a Contributor License Agreement (see details above). 19 | 1. Fork the desired repo, develop and test your code changes. 20 | 1. Ensure that your code adheres to the existing style in the sample to which you are contributing. 21 | 1. Submit a pull request. 22 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM node:8-onbuild 2 | 3 | RUN wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | apt-key add - 4 | RUN sh -c 'echo "deb [arch=amd64] http://dl.google.com/linux/chrome/deb/ stable main" >> /etc/apt/sources.list.d/google.list' 5 | RUN apt-get update 6 | RUN apt-get install -y google-chrome-stable xvfb 7 | ENV INSIDE_DOCKER true 8 | ENV CHROME_BIN /usr/bin/google-chrome 9 | ENV DISPLAY :99.0 10 | CMD Xvfb $DISPLAY & npm run build && npm test 11 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright 2017 Google Inc. 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # HowTo: Components 2 | 3 | ![Travis CI Build status badge](https://travis-ci.org/GoogleChrome/howto-components.svg?branch=master) 4 | 5 | “HowTo: Components” is [a subsection on Web Fundamentals Architecture section](https://developers.google.com/web/fundamentals/web-components/examples/), containing a collection of web components that implement common web UI patterns using modern web technologies like Custom Elements v1 and ESnext with a special focus on accessibility, performance and progressive enhancement. Their purpose is to be an educational resource. Users are supposed to read and learn from their implementations. They are explicitly **NOT** a UI library meant to be used in production. 6 | 7 | ## Demos 8 | 9 | You can run the demos locally, after you build them: 10 | 11 | ``` 12 | npm install # if you haven't already 13 | npm run build 14 | python -m SimpleHTTPServer # or your favourite local server 15 | ``` 16 | 17 | In your browser, navigate to `http://localhost:8000/docs` (or the port that you're running the local server from.) 18 | 19 | You can also run 20 | 21 | ``` 22 | npm run watch 23 | ``` 24 | 25 | to continuously run the build whenever a file changes. 26 | 27 | ### WebFundamentals 28 | 29 | To generate the content for [WebFundamentals](https://github.com/Google/WebFundamentals), run the `build-webfundamentals.sh` script. It will create a `webfundamentals` folder. The contents needs to be moved into the WebFundamentals repository. If new components have been created, they need to be added manually to [WebFundamentals Web Components table of contents](https://github.com/google/WebFundamentals/blob/master/src/content/en/fundamentals/web-components/_toc.yaml). 30 | 31 | ## Testing 32 | 33 | Tests are written using [Mocha](https://mochajs.org/) and [Chai](http://chaijs.com/). Each component has tests. 34 | 35 | ### Local 36 | 37 | Tests run using [Karma](https://karma-runner.github.io/1.0/config/browsers.html). Run the tests with 38 | 39 | ``` 40 | $ npm test 41 | ``` 42 | 43 | This assumes that Chrome, Firefox and Safari are installed as the tests run in all of these browser (using the [Custom Elements v1 Polyfill](https://github.com/webcomponents/custom-elements)). 44 | 45 | ### Local + Docker (or Travis) 46 | 47 | Tests can also run in a [Docker](https://www.docker.com/) container (as we do on Travis): 48 | 49 | ``` 50 | $ npm run docker 51 | ``` 52 | 53 | This builds a docker image `googlechrome/howto-components` and runs it. The dockerized tests use Chrome only. 54 | 55 | ## Staging 56 | 57 | All branches and PRs are built and uploaded on Travis CI. The staged version can be viewed at `http://dash-elements.surma.link/`. 58 | 59 | ## License 60 | 61 | Copyright 2017 Google, Inc. 62 | 63 | Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the “License”); you may not use this file except in compliance with the License. You may obtain a copy of the License at 64 | 65 | http://www.apache.org/licenses/LICENSE-2.0 66 | 67 | Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an “AS IS” BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. 68 | 69 | Please note: this is not a Google product 70 | -------------------------------------------------------------------------------- /build-documentation.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Google Inc. All rights reserved. 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 | /* eslint max-len: ["off"], no-console: ["off"], require-jsdoc: 0 */ 17 | const origFs = require('fs'); 18 | const fs = require('mz/fs'); 19 | const fsExtra = require('fs-extra'); 20 | const dot = require('dot'); 21 | const sectionizer = require('./sectionizer.js').parse; 22 | const prism = require('prismjs'); 23 | const marked = require('marked'); 24 | 25 | // Configs 26 | const dotConfig = { 27 | strip: false, 28 | }; 29 | 30 | Object.assign(dot.templateSettings, dotConfig); 31 | Promise.all([ 32 | generateDocs(), 33 | copyStaticFiles(), 34 | ]) 35 | .then(_ => console.log('done')); 36 | 37 | function generateDocs() { 38 | return fs.mkdir('docs') 39 | .catch(_ => {}) 40 | .then(_ => fs.readdir('elements')) 41 | .then(elements => Promise.all( 42 | elements.map(elem => 43 | fs.mkdir(`docs/${elem}`) 44 | .catch(_ => {}) 45 | .then(_ => parseElement(elem)) 46 | .then(writeElement) 47 | ) 48 | )) 49 | .then(buildIndex); 50 | } 51 | 52 | function copyStaticFiles() { 53 | return Promise.all([ 54 | fs.readdir('site-resources') 55 | .then(files => 56 | Promise.all( 57 | files 58 | .filter(name => !name.includes('.tpl.')) 59 | .map(name => copy(`site-resources/${name}`, `docs/${name}`)) 60 | ) 61 | ), 62 | fs.readdir('elements') 63 | .then(elements => Promise.all( 64 | elements.map(elem => 65 | copy(`elements/${elem}/images`, `docs/images`).catch(_ => {}) 66 | ) 67 | )), 68 | ]); 69 | } 70 | 71 | function parseElement(name) { 72 | const filePath = `elements/${name}/`; 73 | return Promise.all([ 74 | fs.readFile(`${filePath}/${name}.js`), 75 | fs.readFile(`${filePath}/demo.html`), 76 | ]) 77 | .then(([code, demo]) => { 78 | code = code.toString('utf-8'); 79 | code = code.replace(/\{%PATH%\}/g, '..'); 80 | demo = demo.toString('utf-8').replace(/{%[^%]+%}/g, ''); 81 | const data = { 82 | title: name, 83 | source: code, 84 | demo: demo, 85 | demoSections: sectionizer(demo), 86 | sections: sectionizer(code), 87 | }; 88 | return fs.writeFile(`docs/${name}/${name}.js`, code).then(_ => data); 89 | }) 90 | .then(contents => { 91 | // Remove copyright blocks 92 | removeCopyright(contents.sections); 93 | removeCopyright(contents.demoSections); 94 | removeHiddenSections(contents.sections); 95 | contents.sections = 96 | contents.sections 97 | // Make jsdoc blocks only belong to _one_ 98 | // line of code for better visuals 99 | .reduce((accumulator, nextSection) => { 100 | nextSection.commentText = nextSection.commentText.trim(); 101 | // Dismiss empty blocks 102 | if (nextSection.commentText.length === 0 && nextSection.codeText.length === 0) 103 | return accumulator; 104 | // Blocks without a comment get joined with the previous block 105 | if (accumulator.length > 0 && nextSection.commentText.length === 0 && nextSection.codeText.length > 0) { 106 | accumulator[accumulator.length - 1].codeText += nextSection.codeText; 107 | return accumulator; 108 | } 109 | if (nextSection.commentType !== 'BlockComment') 110 | return [...accumulator, nextSection]; 111 | const copy = Object.assign({}, nextSection); 112 | const lines = nextSection.codeText.replace(/^\n*/, '').split('\n'); 113 | nextSection.codeText = lines[0] + '\n'; 114 | accumulator.push(nextSection); 115 | if (lines.length >= 2) { 116 | copy.commentType = 'LineComment'; 117 | copy.commentText = ''; 118 | copy.codeText = lines.slice(1).join('\n'); 119 | accumulator.push(copy); 120 | } 121 | return accumulator; 122 | }, []); 123 | return contents; 124 | }) 125 | .catch(err => console.error(err.toString(), err.stack)); 126 | } 127 | 128 | function removeHiddenSections(sections) { 129 | let removing = false; 130 | for (const section of sections) { 131 | if (section.commentText.trim().startsWith('HIDE')) { 132 | section.commentText = ''; 133 | section.codeText = ''; 134 | removing = true; 135 | } else if (section.commentText.trim().startsWith('/HIDE') && removing) { 136 | section.commentText = section.commentText.replace('/HIDE', ''); 137 | removing = false; 138 | } else if (removing) { 139 | section.commentText = ''; 140 | section.codeText = ''; 141 | } 142 | } 143 | } 144 | 145 | function removeCopyright(sections) { 146 | if (sections[0].commentType === 'BlockComment' 147 | && sections[0].commentText.indexOf('Copyright 2017 Google') !== -1) { 148 | sections[0].commentText = ''; 149 | } 150 | sections.forEach(section => { 151 | section.codeText = section.codeText.replace(//g, ''); 152 | }); 153 | } 154 | 155 | function addHelperFunctionsToContext(context) { 156 | return Object.assign({}, context, { 157 | readFile: file => origFs.readFileSync(file).toString('utf-8'), 158 | highlightJS: text => 159 | prism.highlight(text, prism.languages.javascript) 160 | .replace(/^\n*/, '') 161 | .replace(/\s*$/, '') 162 | .replace(/ /g, '  '), 163 | highlightHTML: text => 164 | prism.highlight(text, prism.languages.markup) 165 | .replace(/^\n*/, '') 166 | .replace(/\s*$/, '') 167 | .replace(/ /g, '  '), 168 | markdown: text => marked(text), 169 | escape: text => 170 | text 171 | .replace(//g, '>'), 173 | indentLines: text => text 174 | .replace(/^\n*/, '') 175 | .replace(/\s*$/, '') 176 | .replace(/ /g, '  '), 177 | isEmpty: text => text.trim().length <= 0, 178 | }); 179 | } 180 | 181 | function writeElement(element) { 182 | const augmentedContext = addHelperFunctionsToContext(element); 183 | return Promise.all([ 184 | template('site-resources/element.tpl.html'), 185 | template('site-resources/demo.tpl.html'), 186 | template('site-resources/element.tpl.md'), 187 | ]) 188 | .then(([elemTpl, demoTpl, devsite]) => Promise.all([ 189 | fs.writeFile(`docs/${element.title}/index.html`, elemTpl(augmentedContext)), 190 | fs.writeFile(`docs/${element.title}/demo.html`, demoTpl(augmentedContext)), 191 | fs.writeFile(`docs/${element.title}/${element.title}.md`, devsite(augmentedContext)), 192 | ])) 193 | .then(_ => element) 194 | .catch(err => console.log(err.toString(), err.stack)); 195 | } 196 | 197 | function buildIndex(elements) { 198 | return template('site-resources/index.tpl.html') 199 | .then(tpl => tpl(elements)) 200 | .then(contents => fs.writeFile('docs/index.html', contents)); 201 | } 202 | 203 | function template(path) { 204 | return fs 205 | .readFile(path) 206 | .then(contents => dot.template(contents.toString('utf-8'))); 207 | } 208 | 209 | function copy(a, b) { 210 | return new Promise((resolve, reject) => 211 | fsExtra.copy(a, b, (err) => { 212 | if (err) 213 | return reject(err); 214 | resolve(); 215 | }) 216 | ); 217 | } 218 | -------------------------------------------------------------------------------- /build-webfundamentals.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | npm run build 4 | rm -rf webfundamentals 5 | mkdir -p webfundamentals/src/content/en/fundamentals/web-components/examples 6 | find docs -type d -name 'howto-*' | while read line; do cp -r $line/*.md webfundamentals/src/content/en/fundamentals/web-components/examples/; done 7 | cp docs/styles/main.devsite.css webfundamentals/src/content/en/fundamentals/web-components/examples/main.css 8 | cp -r docs/images webfundamentals/src/content/en/fundamentals/web-components/examples/ 9 | -------------------------------------------------------------------------------- /elements/howto-accordion/README.md: -------------------------------------------------------------------------------- 1 | Accordions are a pattern to limit visible content by separating 2 | it into multiple panels. Any panel can be expanded or collapsed, giving 3 | the user control over which content is visible. 4 | 5 | By either clicking or by using the arrow keys the user changes the 6 | selection of the active heading. With enter or space the active headings 7 | can be toggled between expanded and collapsed state. 8 | 9 | The headings and the panels have the attributes `expanded` or `collapsed` 10 | assigned to them depending on their state. 11 | 12 | All panels should be styled to be visible if JavaScript is disabled. 13 | 14 | See: https://www.w3.org/TR/wai-aria-practices-1.1/#accordion 15 | -------------------------------------------------------------------------------- /elements/howto-accordion/demo.html: -------------------------------------------------------------------------------- 1 | 13 | 28 | 29 | 30 | Tab 1 31 | Content 1 32 | Tab 2 33 | Content 2 34 | Tab 3 35 | Content 3 36 | 37 | -------------------------------------------------------------------------------- /elements/howto-accordion/howto-accordion.e2etest.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Google Inc. All rights reserved. 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 | /* eslint max-len: ["off"] */ 17 | 18 | const helper = require('../../tools/selenium-helper.js'); 19 | const expect = require('chai').expect; 20 | const {Key} = require('selenium-webdriver'); 21 | 22 | describe('howto-accordion', function() { 23 | let success; 24 | beforeEach(function() { 25 | return this.driver.get(`${this.address}/howto-accordion/demo.html`) 26 | .then(_ => helper.waitForElement(this.driver, 'howto-accordion')) 27 | .then(_ => this.driver.executeScript(_ => { 28 | window.queryShadowAgnosticSelector = function(elem, s) { 29 | return elem.querySelector(s) || (elem.shadowRoot && elem.shadowRoot.querySelector(s)); 30 | }; 31 | 32 | window.isHidden = function(elem) { 33 | return getComputedStyle(elem).display === 'none' || 34 | getComputedStyle(elem).visibility === 'hidden' || 35 | elem.hidden || 36 | (elem.getAttribute('aria-hidden') || '').toLowerCase() === 'true'; 37 | }; 38 | })); 39 | }); 40 | 41 | it('should handle arrow keys', async function() { 42 | await this.driver.executeScript(_ => { 43 | window.expectedFirstHeading = document.querySelector('[role=heading]:nth-of-type(1)'); 44 | window.expectedSecondHeading = document.querySelector('[role=heading]:nth-of-type(2)'); 45 | }); 46 | 47 | success = await helper.pressKeyUntil(this.driver, Key.TAB, _ => document.activeElement === window.expectedFirstHeading); 48 | expect(success).to.be.true; 49 | 50 | await this.driver.actions().sendKeys(Key.ARROW_RIGHT).perform(); 51 | success = await this.driver.executeScript(_ => document.activeElement === window.expectedSecondHeading); 52 | expect(success).to.be.true; 53 | 54 | await this.driver.actions().sendKeys(Key.ARROW_LEFT).perform(); 55 | success = await this.driver.executeScript(_ => document.activeElement === window.expectedFirstHeading); 56 | expect(success).to.be.true; 57 | }); 58 | 59 | it('should focus the last panel on [end]', async function() { 60 | await this.driver.executeScript(_ => { 61 | window.expectedFirstHeading = document.querySelector('[role=heading]:nth-of-type(1)'); 62 | window.expectedLastHeading = document.querySelector('[role=heading]:last-of-type'); 63 | }); 64 | 65 | success = await helper.pressKeyUntil(this.driver, Key.TAB, _ => document.activeElement === window.expectedFirstHeading); 66 | expect(success).to.be.true; 67 | 68 | await this.driver.actions().sendKeys(Key.END).perform(); 69 | success = await this.driver.executeScript(_ => document.activeElement === window.expectedLastHeading); 70 | expect(success).to.be.true; 71 | }); 72 | 73 | it('should focus the first panel on [home]', async function() { 74 | await this.driver.executeScript(_ => { 75 | window.expectedFirstHeading = document.querySelector('[role=heading]:nth-of-type(1)'); 76 | window.expectedLastHeading = document.querySelector('[role=heading]:last-of-type'); 77 | }); 78 | 79 | success = await helper.pressKeyUntil(this.driver, Key.TAB, _ => document.activeElement === window.expectedFirstHeading); 80 | expect(success).to.be.true; 81 | 82 | await this.driver.actions().sendKeys(Key.ARROW_LEFT).perform(); 83 | await helper.pressKeyUntil(this.driver, Key.TAB, _ => document.activeElement === window.expectedLastHeading); 84 | expect(success).to.be.true; 85 | 86 | await this.driver.actions().sendKeys(Key.HOME).perform(); 87 | success = await this.driver.executeScript(_ => document.activeElement === window.expectedFirstHeading); 88 | expect(success).to.be.true; 89 | }); 90 | 91 | it('should expand a panel on click', async function() { 92 | success = await this.driver.executeScript(_ => { 93 | window.lastHeading = document.querySelector('[role=heading]:last-of-type'); 94 | window.lastPanel = document.getElementById(lastHeading.getAttribute('aria-controls')); 95 | window.lastButton = queryShadowAgnosticSelector(lastHeading, 'button'); 96 | return [lastButton.getAttribute('aria-expanded'), isHidden(lastPanel)]; 97 | }); 98 | expect(success).to.deep.equal(['false', true]); 99 | 100 | const lastHeading = await this.driver.executeScript(_ => lastHeading); 101 | await lastHeading.click(); 102 | await helper.sleep(500); 103 | success = await this.driver.executeScript(_ => 104 | [lastButton.getAttribute('aria-expanded'), isHidden(lastPanel)] 105 | ); 106 | expect(success).to.deep.equal(['true', false]); 107 | }); 108 | 109 | it('should toggle a panel on [space]', async function() { 110 | await this.driver.executeScript(_ => { 111 | window.firstHeading = document.querySelector('[role=heading]:nth-of-type(1)'); 112 | }); 113 | success = await helper.pressKeyUntil(this.driver, Key.TAB, _ => document.activeElement === window.firstHeading); 114 | expect(success).to.be.true; 115 | 116 | success = await this.driver.executeScript(_ => { 117 | window.firstPanel = document.getElementById(firstHeading.getAttribute('aria-controls')); 118 | return !!window.firstPanel; 119 | }); 120 | expect(success).to.be.true; 121 | 122 | await this.driver.actions().sendKeys(Key.SPACE).perform(); 123 | await helper.sleep(500); 124 | success = await this.driver.executeScript(_ => isHidden(firstPanel)); 125 | expect(success).to.be.false; 126 | 127 | await this.driver.actions().sendKeys(Key.SPACE).perform(); 128 | await helper.sleep(500); 129 | success = await this.driver.executeScript(_ => isHidden(firstPanel)); 130 | expect(success).to.be.true; 131 | }); 132 | }); 133 | -------------------------------------------------------------------------------- /elements/howto-accordion/howto-accordion.unittest.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Google Inc. All rights reserved. 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 | /* eslint max-len: ["off"] */ 17 | 18 | (function() { 19 | const expect = chai.expect; 20 | 21 | describe('howto-accordion', function() { 22 | before(howtoComponents.before()); 23 | after(howtoComponents.after()); 24 | beforeEach(function() { 25 | this.container.innerHTML = ` 26 | 27 | 28 | Content 1 29 | 30 | Content 2 31 | 32 | Content 3 33 | 34 | `; 35 | return Promise.all([ 36 | howtoComponents.waitForElement('howto-accordion'), 37 | howtoComponents.waitForElement('howto-accordion-heading'), 38 | howtoComponents.waitForElement('howto-accordion-panel'), 39 | ]).then(_ => { 40 | this.accordion = this.container.querySelector('howto-accordion'); 41 | this.headings = Array.from(this.container.querySelectorAll('howto-accordion-heading')); 42 | this.panels = Array.from(this.container.querySelectorAll('howto-accordion-panel')); 43 | }); 44 | }); 45 | 46 | it('should know about all the headings', function() { 47 | expect(this.accordion._allHeadings()).to.have.length(this.headings.length); 48 | }); 49 | 50 | it('should’t overwrite existing IDs with generated ones', function() { 51 | expect(this.headings[0].id).to.equal('lol'); 52 | expect(this.panels[0].getAttribute('aria-labelledby')).to.equal('lol'); 53 | }); 54 | 55 | it('should know about all the panels', function() { 56 | expect(this.accordion._allPanels()).to.have.length(this.panels.length); 57 | }); 58 | 59 | it('should add `aria-labelledby` to panels', function() { 60 | this.panels.forEach(panel => { 61 | expect(panel.getAttribute('aria-labelledby')).to.have.length.above(0); 62 | }); 63 | }); 64 | 65 | it('should ensure IDs to all headings', function() { 66 | this.headings.forEach(heading => { 67 | expect(heading.id).to.have.length.above(0); 68 | }); 69 | }); 70 | 71 | it('should add `role` to panels', function() { 72 | this.panels.forEach(panel => { 73 | expect(panel.getAttribute('role')).to.equal('region'); 74 | }); 75 | }); 76 | }); 77 | })(); 78 | -------------------------------------------------------------------------------- /elements/howto-checkbox/README.md: -------------------------------------------------------------------------------- 1 | ## Summary {: #summary } 2 | 3 | A `` represents a boolean option in a form. The most common type 4 | of checkbox is a dual-type which allows the user to toggle between two 5 | choices -- checked and unchecked. 6 | 7 | The element attempts to self apply the attributes `role="checkbox"` and 8 | `tabindex="0"` when it is first created. The `role` attribute helps assistive 9 | technology like a screen reader tell the user what kind of control this is. 10 | The `tabindex` attribute opts the element into the tab order, making it keyboard 11 | focusable and operable. To learn more about these two topics, check out 12 | [What can ARIA do?][what-aria] and [Using tabindex][using-tabindex]. 13 | 14 | When the checkbox is checked, it adds a `checked` boolean attribute, and sets 15 | a corresponding `checked` property to `true`. In addition, the element sets an 16 | `aria-checked` attribute to either `"true"` or `"false"`, depending on its 17 | state. Clicking on the checkbox with a mouse, or space bar, toggles these 18 | checked states. 19 | 20 | The checkbox also supports a `disabled` state. If either the `disabled` property 21 | is set to true or the `disabled` attribute is applied, the checkbox sets 22 | `aria-disabled="true"`, removes the `tabindex` attribute, and returns focus 23 | to the document if the checkbox is the current `activeElement`. 24 | 25 | Warning: Just because you _can_ build a custom element checkbox, doesn't 26 | necessarily mean that you _should_. As this example shows, you will need to add 27 | your own keyboard, labeling, and ARIA support. It's also important to note that 28 | the native `
` element will NOT submit values from a custom element. You 29 | will need to wire that up yourself using AJAX or a hidden `` field. For 30 | these reasons it can often be preferrable to use the built-in `` instead. 32 | 33 | ## Reference {: #reference } 34 | 35 | - [Checkbox Pattern in ARIA Authoring Practices 1.1][checkbox-pattern] 36 | - [What can ARIA Do?][what-aria] 37 | - [Using tabindex][using-tabindex] 38 | 39 | [checkbox-pattern]: https://www.w3.org/TR/wai-aria-practices-1.1/#checkbox 40 | [what-aria]: https://developers.google.com/web/fundamentals/accessibility/semantics-aria/#what_can_aria_do 41 | [using-tabindex]: https://developers.google.com/web/fundamentals/accessibility/focus/using-tabindex 42 | -------------------------------------------------------------------------------- /elements/howto-checkbox/demo.html: -------------------------------------------------------------------------------- 1 | 13 | 14 | 27 | 28 | 29 | Join Newsletter 30 | -------------------------------------------------------------------------------- /elements/howto-checkbox/howto-checkbox.e2etest.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Google Inc. All rights reserved. 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 | /* eslint max-len: ["off"] */ 17 | 18 | const helper = require('../../tools/selenium-helper.js'); 19 | const expect = require('chai').expect; 20 | const {Key, By} = require('selenium-webdriver'); 21 | 22 | describe('howto-checkbox', function() { 23 | let success; 24 | 25 | const findCheckbox = _ => { 26 | window.expectedCheckbox = document.querySelector('[role=checkbox]'); 27 | }; 28 | 29 | const isUnchecked = _ => { 30 | let isAriaUnchecked = 31 | !window.expectedCheckbox.hasAttribute('aria-checked') || 32 | window.expectedCheckbox.getAttribute('aria-checked') === 'false'; 33 | return isAriaUnchecked && window.expectedCheckbox.checked === false; 34 | }; 35 | 36 | const isChecked = _ => { 37 | let isAriaChecked = window.expectedCheckbox.getAttribute('aria-checked') === 'true'; 38 | return isAriaChecked && window.expectedCheckbox.checked === true; 39 | }; 40 | 41 | beforeEach(function() { 42 | return this.driver.get(`${this.address}/howto-checkbox/demo.html`) 43 | .then(_ => helper.waitForElement(this.driver, 'howto-checkbox')); 44 | }); 45 | 46 | it('should check the checkbox on [space]', async function() { 47 | await this.driver.executeScript(findCheckbox); 48 | success = await helper.pressKeyUntil(this.driver, Key.TAB, _ => document.activeElement === window.expectedCheckbox); 49 | expect(success).to.be.true; 50 | success = await this.driver.executeScript(isUnchecked); 51 | expect(success).to.be.true; 52 | await this.driver.actions().sendKeys(Key.SPACE).perform(); 53 | success = await this.driver.executeScript(isChecked); 54 | expect(success).to.be.true; 55 | }); 56 | 57 | it('should not be focusable when [disabled] is true', async function() { 58 | await this.driver.executeScript(findCheckbox); 59 | success = await helper.pressKeyUntil(this.driver, Key.TAB, _ => document.activeElement === window.expectedCheckbox); 60 | expect(success).to.be.true; 61 | success = await this.driver.executeScript(_ => { 62 | window.expectedCheckbox.disabled = true; 63 | return document.activeElement != window.expectedCheckbox; 64 | }); 65 | expect(success).to.be.true; 66 | }); 67 | 68 | it('should check the checkbox on click', async function() { 69 | await this.driver.executeScript(findCheckbox); 70 | success = await this.driver.executeScript(isUnchecked); 71 | expect(success).to.be.true; 72 | await this.driver.findElement(By.css('[role=checkbox]')).click(); 73 | success = await this.driver.executeScript(isChecked); 74 | expect(success).to.be.true; 75 | }); 76 | }); 77 | 78 | describe('howto-checkbox pre-upgrade', function() { 79 | let success; 80 | 81 | beforeEach(function() { 82 | return this.driver.get(`${this.address}/howto-checkbox/demo.html?nojs`); 83 | }); 84 | 85 | it('should handle attributes set before upgrade', async function() { 86 | await this.driver.executeScript(_ => window.expectedCheckbox = document.querySelector('howto-checkbox')); 87 | await this.driver.executeScript(_ => window.expectedCheckbox.setAttribute('checked', '')); 88 | 89 | await this.driver.executeScript(_ => _loadJavaScript()); 90 | await helper.waitForElement(this.driver, 'howto-checkbox'); 91 | success = await this.driver.executeScript(_ => 92 | window.expectedCheckbox.checked === true && 93 | window.expectedCheckbox.getAttribute('aria-checked') === 'true' 94 | ); 95 | expect(success).to.be.true; 96 | }); 97 | 98 | it('should handle instance properties set before upgrade', async function() { 99 | await this.driver.executeScript(_ => window.expectedCheckbox = document.querySelector('howto-checkbox')); 100 | await this.driver.executeScript(_ => window.expectedCheckbox.checked = true); 101 | 102 | await this.driver.executeScript(_ => _loadJavaScript()); 103 | await helper.waitForElement(this.driver, 'howto-checkbox'); 104 | success = await this.driver.executeScript(_ => 105 | window.expectedCheckbox.hasAttribute('checked') && 106 | window.expectedCheckbox.getAttribute('aria-checked') === 'true' 107 | ); 108 | expect(success).to.be.true; 109 | }); 110 | }); 111 | -------------------------------------------------------------------------------- /elements/howto-checkbox/howto-checkbox.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Google Inc. All rights reserved. 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 | (function() { 17 | /** 18 | * Define key codes to help with handling keyboard events. 19 | */ 20 | const KEYCODE = { 21 | SPACE: 32, 22 | }; 23 | 24 | /** 25 | * Cloning contents from a <template> element is more performant 26 | * than using innerHTML because it avoids addtional HTML parse costs. 27 | */ 28 | const template = document.createElement('template'); 29 | template.innerHTML = ` 30 | 56 | `; 57 | 58 | // HIDE 59 | // ShadyCSS will rename classes as needed to ensure style scoping. 60 | ShadyCSS.prepareTemplate(template, 'howto-checkbox'); 61 | // /HIDE 62 | 63 | class HowToCheckbox extends HTMLElement { 64 | static get observedAttributes() { 65 | return ['checked', 'disabled']; 66 | } 67 | 68 | /** 69 | * The element's constructor is run anytime a new instance is created. 70 | * Instances are created either by parsing HTML, calling 71 | * document.createElement('howto-checkbox'), or calling new HowToCheckbox(); 72 | * The construtor is a good place to create shadow DOM, though you should 73 | * avoid touching any attributes or light DOM children as they may not 74 | * be available yet. 75 | */ 76 | constructor() { 77 | super(); 78 | this.attachShadow({mode: 'open'}); 79 | this.shadowRoot.appendChild(template.content.cloneNode(true)); 80 | } 81 | 82 | /** 83 | * `connectedCallback()` fires when the element is inserted into the DOM. 84 | * It's a good place to set the initial `role`, `tabindex`, internal state, 85 | * and install event listeners. 86 | */ 87 | connectedCallback() { 88 | // HIDE 89 | // Shim Shadow DOM styles. This needs to be run in `connectedCallback()` 90 | // because if you shim Custom Properties (CSS variables) the element 91 | // will need access to its parent node. 92 | ShadyCSS.styleElement(this); 93 | // /HIDE 94 | 95 | if (!this.hasAttribute('role')) 96 | this.setAttribute('role', 'checkbox'); 97 | if (!this.hasAttribute('tabindex')) 98 | this.setAttribute('tabindex', 0); 99 | 100 | // A user may set a property on an _instance_ of an element, 101 | // before its prototype has been connected to this class. 102 | // The `_upgradeProperty()` method will check for any instance properties 103 | // and run them through the proper class setters. 104 | // See the [lazy properites](/web/fundamentals/architecture/building-components/best-practices#lazy-properties) 105 | // section for more details. 106 | this._upgradeProperty('checked'); 107 | this._upgradeProperty('disabled'); 108 | 109 | this.addEventListener('keyup', this._onKeyUp); 110 | this.addEventListener('click', this._onClick); 111 | } 112 | 113 | _upgradeProperty(prop) { 114 | if (this.hasOwnProperty(prop)) { 115 | let value = this[prop]; 116 | delete this[prop]; 117 | this[prop] = value; 118 | } 119 | } 120 | 121 | /** 122 | * `disconnectedCallback()` fires when the element is removed from the DOM. 123 | * It's a good place to do clean up work like releasing references and 124 | * removing event listeners. 125 | */ 126 | disconnectedCallback() { 127 | this.removeEventListener('keyup', this._onKeyUp); 128 | this.removeEventListener('click', this._onClick); 129 | } 130 | 131 | /** 132 | * Properties and their corresponding attributes should mirror one another. 133 | * The property setter for `checked` handles truthy/falsy values and 134 | * reflects those to the state of the attribute. See the [avoid 135 | * reentrancy](/web/fundamentals/architecture/building-components/best-practices#avoid-reentrancy) 136 | * section for more details. 137 | */ 138 | set checked(value) { 139 | const isChecked = Boolean(value); 140 | if (isChecked) 141 | this.setAttribute('checked', ''); 142 | else 143 | this.removeAttribute('checked'); 144 | } 145 | 146 | get checked() { 147 | return this.hasAttribute('checked'); 148 | } 149 | 150 | set disabled(value) { 151 | const isDisabled = Boolean(value); 152 | if (isDisabled) 153 | this.setAttribute('disabled', ''); 154 | else 155 | this.removeAttribute('disabled'); 156 | } 157 | 158 | get disabled() { 159 | return this.hasAttribute('disabled'); 160 | } 161 | 162 | /** 163 | * `attributeChangedCallback()` is called when any of the attributes in the 164 | * `observedAttributes` array are changed. It's a good place to handle 165 | * side effects, like setting ARIA attributes. 166 | */ 167 | attributeChangedCallback(name, oldValue, newValue) { 168 | const hasValue = newValue !== null; 169 | switch (name) { 170 | case 'checked': 171 | this.setAttribute('aria-checked', hasValue); 172 | break; 173 | case 'disabled': 174 | this.setAttribute('aria-disabled', hasValue); 175 | // The `tabindex` attribute does not provide a way to fully remove 176 | // focusability from an element. 177 | // Elements with `tabindex=-1` can still be focused with 178 | // a mouse or by calling `focus()`. 179 | // To make sure an element is disabled and not focusable, remove the 180 | // `tabindex` attribute. 181 | if (hasValue) { 182 | this.removeAttribute('tabindex'); 183 | // If the focus is currently on this element, unfocus it by 184 | // calling the `HTMLElement.blur()` method. 185 | this.blur(); 186 | } else { 187 | this.setAttribute('tabindex', '0'); 188 | } 189 | break; 190 | } 191 | } 192 | 193 | _onKeyUp(event) { 194 | // Don’t handle modifier shortcuts typically used by assistive technology. 195 | if (event.altKey) 196 | return; 197 | 198 | switch (event.keyCode) { 199 | case KEYCODE.SPACE: 200 | event.preventDefault(); 201 | this._toggleChecked(); 202 | break; 203 | // Any other key press is ignored and passed back to the browser. 204 | default: 205 | return; 206 | } 207 | } 208 | 209 | _onClick(event) { 210 | this._toggleChecked(); 211 | } 212 | 213 | /** 214 | * `_toggleChecked()` calls the `checked` setter and flips its state. 215 | * Because `_toggleChecked()` is only caused by a user action, it will 216 | * also dispatch a change event. This event bubbles in order to mimic 217 | * the native behavior of ``. 218 | */ 219 | _toggleChecked() { 220 | if (this.disabled) 221 | return; 222 | this.checked = !this.checked; 223 | this.dispatchEvent(new CustomEvent('change', { 224 | detail: { 225 | checked: this.checked, 226 | }, 227 | bubbles: true, 228 | })); 229 | } 230 | } 231 | 232 | window.customElements.define('howto-checkbox', HowToCheckbox); 233 | })(); 234 | 235 | 236 | -------------------------------------------------------------------------------- /elements/howto-checkbox/howto-checkbox.unittest.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Google Inc. All rights reserved. 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 | /* eslint max-len: ["off"] */ 17 | 18 | (function() { 19 | const expect = chai.expect; 20 | 21 | describe('howto-checkbox', function() { 22 | before(howtoComponents.before()); 23 | after(howtoComponents.after()); 24 | beforeEach(function() { 25 | this.container.innerHTML = ``; 26 | return howtoComponents.waitForElement('howto-checkbox') 27 | .then(_ => { 28 | this.checkbox = this.container.querySelector('howto-checkbox'); 29 | }); 30 | }); 31 | 32 | it('should add a [role] to the checkbox', function() { 33 | expect(this.checkbox.getAttribute('role')).to.equal('checkbox'); 34 | }); 35 | 36 | it('should add a [tabindex] to the checkbox', function() { 37 | expect(this.checkbox.getAttribute('tabindex')).to.equal('0'); 38 | }); 39 | 40 | describe('checked', function() { 41 | it('should toggle [checked] and [aria-checked] when calling ' + 42 | '_toggleChecked()', function() { 43 | expect(this.checkbox.checked).to.be.false; 44 | this.checkbox._toggleChecked(); 45 | expect(this.checkbox.getAttribute('aria-checked')).to.equal('true'); 46 | expect(this.checkbox.checked).to.be.true; 47 | }); 48 | 49 | it('should toggle [checked] and [aria-checked] when setting .checked', function() { 50 | expect(this.checkbox.checked).to.be.false; 51 | this.checkbox.checked = true; 52 | expect(this.checkbox.getAttribute('aria-checked')).to.equal('true'); 53 | expect(this.checkbox.checked).to.be.true; 54 | this.checkbox.checked = false; 55 | expect(this.checkbox.getAttribute('aria-checked')).to.equal('false'); 56 | expect(this.checkbox.checked).to.be.false; 57 | }); 58 | 59 | it('should handle truthy/falsy values for .checked', function() { 60 | expect(this.checkbox.checked).to.be.false; 61 | this.checkbox.checked = '0'; 62 | expect(this.checkbox.getAttribute('aria-checked')).to.equal('true'); 63 | expect(this.checkbox.hasAttribute('checked')).to.be.true; 64 | expect(this.checkbox.checked).to.be.true; 65 | this.checkbox.checked = undefined; 66 | expect(this.checkbox.getAttribute('aria-checked')).to.equal('false'); 67 | expect(this.checkbox.hasAttribute('checked')).to.be.false; 68 | expect(this.checkbox.checked).to.be.false; 69 | this.checkbox.checked = 1; 70 | expect(this.checkbox.getAttribute('aria-checked')).to.equal('true'); 71 | expect(this.checkbox.hasAttribute('checked')).to.be.true; 72 | expect(this.checkbox.checked).to.be.true; 73 | }); 74 | 75 | it('should toggle .checked, [aria-checked] when setting [checked]', function() { 76 | expect(this.checkbox.hasAttribute('checked')).to.be.false; 77 | this.checkbox.setAttribute('checked', ''); 78 | expect(this.checkbox.getAttribute('aria-checked')).to.equal('true'); 79 | expect(this.checkbox.checked).to.be.true; 80 | this.checkbox.removeAttribute('checked'); 81 | expect(this.checkbox.getAttribute('aria-checked')).to.equal('false'); 82 | expect(this.checkbox.checked).to.be.false; 83 | }); 84 | }); 85 | 86 | describe('disabled', function() { 87 | it('should toggle [disabled], [aria-disabled], and [tabindex] when setting .disabled', function() { 88 | expect(this.checkbox.disabled).to.be.false; 89 | this.checkbox.disabled = true; 90 | expect(this.checkbox.getAttribute('aria-disabled')).to.equal('true'); 91 | expect(this.checkbox.hasAttribute('tabindex')).to.be.false; 92 | expect(this.checkbox.disabled).to.be.true; 93 | this.checkbox.disabled = false; 94 | expect(this.checkbox.getAttribute('aria-disabled')).to.equal('false'); 95 | expect(this.checkbox.getAttribute('tabindex')).to.equal('0'); 96 | expect(this.checkbox.disabled).to.be.false; 97 | }); 98 | 99 | it('should handle truthy/falsy values for .disabled', function() { 100 | expect(this.checkbox.disabled).to.be.false; 101 | this.checkbox.disabled = '0'; 102 | expect(this.checkbox.getAttribute('aria-disabled')).to.equal('true'); 103 | expect(this.checkbox.hasAttribute('disabled')).to.be.true; 104 | expect(this.checkbox.disabled).to.be.true; 105 | this.checkbox.disabled = undefined; 106 | expect(this.checkbox.getAttribute('aria-disabled')).to.equal('false'); 107 | expect(this.checkbox.hasAttribute('disabled')).to.be.false; 108 | expect(this.checkbox.disabled).to.be.false; 109 | this.checkbox.disabled = 1; 110 | expect(this.checkbox.getAttribute('aria-disabled')).to.equal('true'); 111 | expect(this.checkbox.hasAttribute('disabled')).to.be.true; 112 | expect(this.checkbox.disabled).to.be.true; 113 | }); 114 | 115 | it('should toggle .disabled, [aria-disabled] when setting [disabled]', function() { 116 | expect(this.checkbox.hasAttribute('disabled')).to.be.false; 117 | this.checkbox.setAttribute('disabled', ''); 118 | expect(this.checkbox.getAttribute('aria-disabled')).to.equal('true'); 119 | expect(this.checkbox.disabled).to.be.true; 120 | this.checkbox.removeAttribute('disabled'); 121 | expect(this.checkbox.getAttribute('aria-disabled')).to.equal('false'); 122 | expect(this.checkbox.disabled).to.be.false; 123 | }); 124 | }); 125 | }); 126 | })(); 127 | -------------------------------------------------------------------------------- /elements/howto-checkbox/images/checked-checkbox-disabled.svg: -------------------------------------------------------------------------------- 1 | checked-checkbox -------------------------------------------------------------------------------- /elements/howto-checkbox/images/checked-checkbox.svg: -------------------------------------------------------------------------------- 1 | checkbox -------------------------------------------------------------------------------- /elements/howto-checkbox/images/unchecked-checkbox-disabled.svg: -------------------------------------------------------------------------------- 1 | unchecked-checkbox -------------------------------------------------------------------------------- /elements/howto-checkbox/images/unchecked-checkbox.svg: -------------------------------------------------------------------------------- 1 | checkbox outline -------------------------------------------------------------------------------- /elements/howto-label/README.md: -------------------------------------------------------------------------------- 1 | ## Summary {: #summary } 2 | 3 | A `` emulates the built-in `