all files / src/ ng-selector.component.ts

86.84% Statements 99/114
72.73% Branches 48/66
75.86% Functions 22/29
90.38% Lines 94/104
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233                                                     10×     10×   10×                     28×         18× 18× 18× 18×                                                                             16× 15×     12× 11×           32×   32×   29×                             10×                                                                      
import {
  AfterViewInit,
  Attribute,
  Component,
  ElementRef,
  EventEmitter,
  forwardRef,
  Input,
  Output,
  ViewChild
} from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
 
// rollup dirty fix : https://github.com/rollup/rollup/issues/1267
import * as jqueryProxy from 'jquery';
const jQuery: JQueryStatic = (<any> jqueryProxy).default || jqueryProxy
 
import 'selectize';
 
@Component({
  selector: 'ng-selector',
  template: `<select #selector></select>`,
  providers: [{ provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => NgSelectorComponent), multi: true }]
})
export class NgSelectorComponent implements AfterViewInit, ControlValueAccessor {
 
  // select element
  @ViewChild('selector') selector: ElementRef;
 
  @Input() set readonly (disabled: boolean) {
    this._disabled = disabled;
    this.checkDisabled();
  };
 
  // array of data
  @Input() set options (values: Array<any>) {
    this.optionsChanged(values)
  };
 
  @Input() plugins = new Array<string>()
 
  // async input options (function which provide data)
  @Output() loadValues = new EventEmitter<{ query: string, result: (options: Array<any>) => void }>();
  // rendering method to change display of item and options
  @Output() renderer = new EventEmitter<{ val: any, html: (html: string) => void, type: string }>();
 
  private _disabled = false;
 
  // actual selectize component
  selectize: any;
 
  // keep data until tagsComponent is initialized
  private data: any;
  private tmpOptions: any;
 
  private _mutiple = false
  @Input('multiple')
  get multiple () { return this._mutiple; }
  set multiple (value) {
    this._mutiple = value;
    // this.selectize.maxItems = this.multiple ? null : 1,
    Iif (this.selectize) this.selectize.maxItems = this.checkMultipleFalsy();
  }
 
  constructor (@Attribute('placeholder') public Iplaceholder = '',
               @Attribute('id-field') public IidField = 'id',
               @Attribute('label-field') public IlabelField = 'label',
               @Attribute('allow-creation') public IallowCreation = true) {}
 
  ngAfterViewInit (): any {
    // initialize with default values
    this.placeholder = this.placeholder || '';
    this.idField = this.idField || 'id';
    this.labelField = this.labelField || 'label';
    this.multiple = this.multiple === undefined ? false : this.multiple;
    this.allowCreation = this.allowCreation === undefined ? true : this.allowCreation;
 
    let render;
    Iif (this.renderer.observers.length === 1) {
      render = {
        option: this.rendering('option'),
        item: this.rendering('item'),
      };
    }
 
    // prepare selectize compatible method to fetch data
    let load = null;
    if (this.loadValues.observers.length === 1) {
      load = (query: string, callback: (data: Array<any>) => void) => {
        // TODO find a way to display it to user
        // disabled async search if search string is below 3 characters long
        Iif (query.length < 3) {
          return callback([]);
        }
        this.loadValues.emit({ query, result: callback });
      };
    }
 
    const plugins = [].concat(this.plugins)
 
    // configure Selectize
    this.selectize = jQuery(this.selector.nativeElement).selectize({
      valueField: this.idField,
      labelField: this.labelField,
      searchField: this.labelField,
      placeholder: this.placeholder,
      maxItems: this.checkMultipleFalsy(),
      create: this.allowCreation,
      selectOnTab: true,
      persist: true,
      load: load,
      render: render,
      plugins: plugins,
      onChange: this.dataChanged.bind(this)
    } as Selectize.IOptions<any, any>)[0].selectize;
 
    // force form-control on
    jQuery(this.selector.nativeElement).siblings().find('.selectize-input').addClass('form-control');
 
    // force refresh data when Selectize is initialized
    this.optionsChanged(this.tmpOptions);
    this.updateData(this.data);
    this.checkDisabled();
  }
 
  optionsChanged (options) {
    if (!options || !Object.keys(options).length) {
      return this.selectize && this.selectize.clearOptions();
    }
 
    if (this.selectize) {
      Object.keys(this.selectize.options).forEach(id => {
        if (!options.find(elem => elem[this.idField] === this.selectize.options[id][this.idField])) {
          this.selectize.removeOption(id);
        }
      });
 
 
      // this.tagsComponent.options = options;
      options.forEach(option => {
        const value = option[this.idField];
        // check if option exist to call the right method ... sorry ... -_-
        if (this.selectize.options[value]) {
          this.selectize.updateOption(value, option);
        } else {
          this.selectize.addOption(option);
        }
      });
      this.selectize.refreshOptions(false);
    } else {
      this.tmpOptions = options;
    }
  }
 
  dataChanged (value) {
    Iif (!value || !value.length) {
      return this.onChange(this.multiple ? [] : null);
    }
 
    if (this.multiple) {
      const selectedValues = value
        .map(id => this.selectize.options[id])
        .filter(item => !!item)
        .map(this.cleanOrder);
      this.onChange(selectedValues);
    } else {
      this.onChange(this.cleanOrder(this.selectize.options[value]));
    }
  }
 
  updateData (data) {
    // component not initialized yet
    Iif (!this.selectize) return;
 
    if (!data) {
      this.selectize.clear();
      return;
    }
 
    this.selectize.addOption(data);
    Iif (Array.isArray(data)) {
      this.selectize.setValue(data.map(item => item[this.idField]));
    } else Eif (data && typeof data === 'object') {
      this.selectize.setValue(data[this.idField]);
    }
  }
 
  checkDisabled () {
    Iif (!this.selectize) return;
 
    if (this._disabled === true) {
      this.selectize.disable();
    } else Eif (this._disabled === false) {
      this.selectize.enable();
    }
  }
 
  rendering (type) {
    return i => {
      let html = i[this.labelField];
      this.renderer.emit({ val: i, html: htmlContent => html = htmlContent, type });
      return html;
    }
  }
 
  onChange = (_) => { };
 
  onTouched = () => { };
 
  writeValue (value: any): void {
    this.updateData(value);
  }
 
  registerOnChange (fn: (_: any) => void): void {
    this.onChange = fn;
  }
 
  registerOnTouched (fn: () => void): void {
    this.onTouched = fn;
  }
 
  // function to clean object from selectize modifications
  private cleanOrder (item: any) {
    delete item.$order;
    return item;
  }
 
  private checkMultipleFalsy () {
    return (this.multiple) ? null : 1;
  }
 
}