Copybara | 854996b | 2021-09-07 19:36:02 +0000 | [diff] [blame] | 1 | // Copyright 2019 The Chromium Authors. All rights reserved. |
| 2 | // Use of this source code is governed by a BSD-style license that can be |
| 3 | // found in the LICENSE file. |
| 4 | |
| 5 | import {LitElement, html, css} from 'lit-element'; |
| 6 | |
| 7 | /** |
| 8 | * `<mr-multi-checkbox>` |
| 9 | * |
| 10 | * A web component for managing values in a set of checkboxes. |
| 11 | * |
| 12 | */ |
| 13 | export class MrMultiCheckbox extends LitElement { |
| 14 | /** @override */ |
| 15 | static get styles() { |
| 16 | return css` |
| 17 | input[type="checkbox"] { |
| 18 | width: auto; |
| 19 | height: auto; |
| 20 | } |
| 21 | `; |
| 22 | } |
| 23 | |
| 24 | /** @override */ |
| 25 | render() { |
| 26 | return html` |
| 27 | ${this.options.map((option) => html` |
| 28 | <label title=${option.docstring}> |
| 29 | <input |
| 30 | type="checkbox" |
| 31 | name=${this.name} |
| 32 | value=${option.optionName} |
| 33 | ?checked=${this.values.includes(option.optionName)} |
| 34 | @change=${this._changeHandler} |
| 35 | /> |
| 36 | ${option.optionName} |
| 37 | </label> |
| 38 | `)} |
| 39 | `; |
| 40 | } |
| 41 | |
| 42 | /** @override */ |
| 43 | static get properties() { |
| 44 | return { |
| 45 | values: {type: Array}, |
| 46 | options: {type: Array}, |
| 47 | _inputRefs: {type: Object}, |
| 48 | }; |
| 49 | } |
| 50 | |
| 51 | |
| 52 | /** @override */ |
| 53 | updated(changedProperties) { |
| 54 | if (changedProperties.has('options')) { |
| 55 | this._inputRefs = this.shadowRoot.querySelectorAll('input'); |
| 56 | } |
| 57 | |
| 58 | if (changedProperties.has('values')) { |
| 59 | this.reset(); |
| 60 | } |
| 61 | } |
| 62 | |
| 63 | reset() { |
| 64 | this.setValues(this.values); |
| 65 | } |
| 66 | |
| 67 | getValues() { |
| 68 | if (!this._inputRefs) return; |
| 69 | const valueList = []; |
| 70 | this._inputRefs.forEach((c) => { |
| 71 | if (c.checked) { |
| 72 | valueList.push(c.value.trim()); |
| 73 | } |
| 74 | }); |
| 75 | return valueList; |
| 76 | } |
| 77 | |
| 78 | setValues(values) { |
| 79 | if (!this._inputRefs) return; |
| 80 | this._inputRefs.forEach( |
| 81 | (checkbox) => { |
| 82 | checkbox.checked = values.includes(checkbox.value); |
| 83 | }, |
| 84 | ); |
| 85 | } |
| 86 | |
| 87 | /** |
| 88 | * @fires CustomEvent#change |
| 89 | * @private |
| 90 | */ |
| 91 | _changeHandler() { |
| 92 | this.dispatchEvent(new CustomEvent('change')); |
| 93 | } |
| 94 | } |
| 95 | |
| 96 | customElements.define('mr-multi-checkbox', MrMultiCheckbox); |