|
| 1 | +import { LitElement, html } from "lit"; |
| 2 | +import { customElement, property, state } from "lit/decorators.js"; |
| 3 | +import { map } from "lit/directives/map.js"; |
| 4 | + |
| 5 | +@customElement("multi-select") |
| 6 | +export class MultiSelect extends LitElement { |
| 7 | + @property({ type: String }) |
| 8 | + label: string = "Select options"; |
| 9 | + |
| 10 | + @property({ type: Array }) |
| 11 | + options: string[] = []; |
| 12 | + |
| 13 | + @state() |
| 14 | + selectedItems: string[] = []; |
| 15 | + |
| 16 | + createRenderRoot() { |
| 17 | + return this; |
| 18 | + } |
| 19 | + |
| 20 | + _handleSelect(e: Event) { |
| 21 | + const selectEl = e.target as HTMLSelectElement; |
| 22 | + const value = selectEl.value; |
| 23 | + |
| 24 | + if (value && !this.selectedItems.includes(value)) { |
| 25 | + this.selectedItems = [...this.selectedItems, value]; |
| 26 | + } |
| 27 | + selectEl.value = ""; |
| 28 | + } |
| 29 | + |
| 30 | + _handleRemove(itemToRemove: string) { |
| 31 | + this.selectedItems = this.selectedItems.filter( |
| 32 | + (item) => item !== itemToRemove, |
| 33 | + ); |
| 34 | + } |
| 35 | + |
| 36 | + render() { |
| 37 | + const availableOptions = this.options.filter( |
| 38 | + (opt) => !this.selectedItems.includes(opt), |
| 39 | + ); |
| 40 | + |
| 41 | + return html` |
| 42 | + <div class="iati-select"> |
| 43 | + <label for="iati-multi-select" class="iati-select__label" |
| 44 | + >${this.label}</label |
| 45 | + > |
| 46 | +
|
| 47 | + <div class="iati-select__control-wrapper"> |
| 48 | + <select |
| 49 | + id="iati-multi-select" |
| 50 | + class="iati-select__control" |
| 51 | + @change=${this._handleSelect} |
| 52 | + > |
| 53 | + <option value="">---</option> |
| 54 | + ${map( |
| 55 | + availableOptions, |
| 56 | + (opt) => html`<option value=${opt}>${opt}</option>`, |
| 57 | + )} |
| 58 | + </select> |
| 59 | + </div> |
| 60 | + </div> |
| 61 | +
|
| 62 | + <ul class="iati-multi-select"> |
| 63 | + ${map( |
| 64 | + this.selectedItems, |
| 65 | + (item) => html` |
| 66 | + <li class="iati-multi-select__item"> |
| 67 | + <button |
| 68 | + class="iati-button iati-button--pill iati-button--remove" |
| 69 | + @click=${() => this._handleRemove(item)} |
| 70 | + title="Remove ${item}" |
| 71 | + > |
| 72 | + ${item} |
| 73 | + </button> |
| 74 | + </li> |
| 75 | + `, |
| 76 | + )} |
| 77 | + </ul> |
| 78 | + `; |
| 79 | + } |
| 80 | +} |
| 81 | + |
| 82 | +declare global { |
| 83 | + interface HTMLElementTagNameMap { |
| 84 | + "multi-select": MultiSelect; |
| 85 | + } |
| 86 | +} |
0 commit comments