1 import { Component, Input, OnChanges, OnInit } from '@angular/core';
2 import { FormControl, ValidatorFn } from '@angular/forms';
4 import { I18n } from '@ngx-translate/i18n-polyfill';
5 import * as _ from 'lodash';
7 import { CdFormGroup } from '../../forms/cd-form-group';
8 import { SelectBadgesMessages } from './select-badges-messages.model';
9 import { SelectBadgesOption } from './select-badges-option.model';
12 selector: 'cd-select-badges',
13 templateUrl: './select-badges.component.html',
14 styleUrls: ['./select-badges.component.scss']
16 export class SelectBadgesComponent implements OnInit, OnChanges {
18 data: Array<string> = [];
20 options: Array<SelectBadgesOption> = [];
22 messages = new SelectBadgesMessages({}, this.i18n);
24 selectionLimit: number;
28 customBadgeValidators: ValidatorFn[] = [];
32 filteredOptions: Array<SelectBadgesOption> = [];
34 constructor(private i18n: I18n) {}
38 if (this.data.length > 0) {
39 this.initMissingOptions();
41 this.options = _.sortBy(this.options, ['name']);
45 private initFilter() {
46 this.filter = new FormControl('', { validators: this.customBadgeValidators });
47 this.form = new CdFormGroup({ filter: this.filter });
48 this.filteredOptions = [...this.options];
51 private initMissingOptions() {
52 const options = this.options.map((option) => option.name);
53 const needToCreate = this.data.filter((option) => options.indexOf(option) === -1);
54 needToCreate.forEach((option) => this.addOption(option));
55 this.forceOptionsToReflectData();
58 private addOption(name: string) {
59 this.options.push(new SelectBadgesOption(false, name, ''));
60 this.options = _.sortBy(this.options, ['name']);
61 this.triggerSelection(this.options.find((option) => option.name === name));
64 triggerSelection(option: SelectBadgesOption) {
67 (this.selectionLimit && !option.selected && this.data.length >= this.selectionLimit)
71 option.selected = !option.selected;
75 private updateOptions() {
76 this.data.splice(0, this.data.length);
77 this.options.forEach((option: SelectBadgesOption) => {
78 if (option.selected) {
79 this.data.push(option.name);
86 this.filteredOptions = this.options.filter((option) => option.name.includes(this.filter.value));
89 private forceOptionsToReflectData() {
90 this.options.forEach((option) => {
91 if (this.data.indexOf(option.name) !== -1) {
92 option.selected = true;
98 if (!this.options || !this.data || this.data.length === 0) {
101 this.forceOptionsToReflectData();
105 if (this.filteredOptions.length === 0) {
106 this.addCustomOption();
108 this.triggerSelection(this.filteredOptions[0]);
114 if (!this.isCreatable()) {
117 this.addOption(this.filter.value);
125 this.filter.value.length > 0 &&
126 this.filteredOptions.every((option) => option.name !== this.filter.value)
130 private resetFilter() {
131 this.filter.setValue('');
135 removeItem(item: string) {
136 this.triggerSelection(
137 this.options.find((option: SelectBadgesOption) => option.name === item && option.selected)