All files / src/NodeLike/ParentNodeLike/ElementLike/ClassListLike ClassListLike.ts

5.41% Statements 2/37
0% Branches 0/14
0% Functions 0/15
5.41% Lines 2/37
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    2x                                                                                                                                                                                           2x
import IClassListLike from './IClassListLike';
import IElementLike from '../IElementLike';
import { List, } from 'immutable';
class ClassListLike implements IClassListLike {
  private element: IElementLike;
  private classes: List<string>;
 
  get length(): number {
    return this.classes.count();
  }
 
  get value(): string {
    return this.classes.join(' ');
  }
 
  constructor(element: IElementLike) {
    this.element = element;
    this.__pullFromParent();
  }
 
  add(...classes: Array<string>): void {
    let updated = false;
    classes.forEach((cls:string) => {
      if (classes.indexOf(cls) === -1) {
        this.classes = this.classes.push(cls);
        updated = true;
      }
    });
 
    if (updated) {
      this.__pushToParent();
    }
  }
 
  remove(...classes: Array<string>): void {
    let updated: boolean = false;
    classes.forEach((cls: string) => {
      const index: number = this.classes.indexOf(cls);
      if (index !== -1) {
        this.classes = this.classes.delete(index);
        updated = true;
      }
    });
 
    if (updated) {
      this.__pushToParent();
    }
  }
 
  item(index: number): string {
    return this.classes.get(index) || '';
  }
 
  toggle(...classes: Array<string>): void {
    classes.forEach((cls: string) => {
      const index = this.classes.indexOf(cls);
      if (index === -1) {
        this.classes = this.classes.delete(index);
      } else {
        this.classes = this.classes.push(cls);
      }
    });
 
    this.__pushToParent();
  }
 
  replace(oldClass: string, newClass: string): void {
    const index = this.classes.indexOf(oldClass);
    if (index !== -1) {
      this.classes = this.classes.set(index, newClass);
      this.__pushToParent();
    }
  }
 
  contains(cls: string): boolean {
    return this.classes.indexOf(cls) !== -1;
  }
 
  __pushToParent(): void {
    this.element.setAttribute('class', this.value);
  }
 
  __pullFromParent(): void {
    const classes = this.element.className
      /* Use the space as a delimiter. */
      .split(' ')
      /* Throw away all empty strings. */
      .filter((cls: string) => {
          return cls.length > 0;
      });
 
    /* Make the class list immutable. */
    this.classes = List(classes);
  }
}
 
export default ClassListLike;