all files / component/color-selector/ color-selector.component.ts

91.53% Statements 162/177
66.25% Branches 53/80
91.53% Functions 54/59
93.13% Lines 149/160
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 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321                                                  14×         14× 14×       14×   14×   14× 14× 14×   14×     14×     14×     14×     14×   14×         21×     21×         14× 14×   14×     14× 152×   14× 27× 27× 27× 26× 26×     19× 19× 19×       19×         192× 192× 13× 13×   179×         14×         14× 14×   14×     12× 209×       70×         14×         14×   16×   14× 17×   16× 20×       14×                     14×                                                           10× 10× 10× 62× 617× 62×   60×             60×   10×                             10× 10×                         13×      
/*
 *  @license
 *  Copyright Hôpitaux Universitaires de Genève. All Rights Reserved.
 *
 *  Use of this source code is governed by an Apache-2.0 license that can be
 *  found in the LICENSE file at https://github.com/DSI-HUG/dejajs-components/blob/master/LICENSE
 */
 
import { coerceBooleanProperty } from '@angular/cdk/coercion';
import { Component, ElementRef, EventEmitter, Input, OnDestroy, Optional, Output, Self } from '@angular/core';
import { ControlValueAccessor, NgControl } from '@angular/forms';
import { BehaviorSubject, combineLatest as observableCombineLatest, from as observableFrom, fromEvent as observableFromEvent, merge as observableMerge, Observable, Subject, timer as observableTimer } from 'rxjs';
import { debounce, debounceTime, distinctUntilChanged, filter, first, map, takeWhile, tap } from 'rxjs/operators';
import { Color } from '../../common/core/graphics/color';
import { MaterialColor } from '../../common/core/style/material-color';
import { DejaColorFab } from './color-fab.class';
 
const noop = () => { };
 
export interface IColorEvent extends CustomEvent {
    color: Color;
}
 
/** Composant de selection d'une couleur. */
@Component({
    selector: 'deja-color-selector',
    styles: [
        require('./color-selector.component.scss'),
    ],
    template: require('./color-selector.component.html'),
})
export class DejaColorSelectorComponent implements ControlValueAccessor, OnDestroy {
    private static indexAttribute = 'index';
 
    /** Evénement déclenché lorsqu'une couleur est survolée par la souris. */
    @Output() public colorhover = new EventEmitter<IColorEvent>();
 
    public _resetcolor: Color;
 
    // ngModel
    public onTouchedCallback: () => void = noop;
    public onChangeCallback: (_: any) => void = noop;
 
    private _value: Color;
 
    private _colors$ = new BehaviorSubject<Color[]>([]);
 
    private _resetcolor$ = new BehaviorSubject<Color>(null);
 
    private _colorFabs = [] as DejaColorFab[];
    private _subColorFabs = [] as DejaColorFab[];
    private _selectedBaseIndex = 0;
    private _selectedSubIndex: number;
    private _disabled = false;
 
    private _colorFabs$: Observable<DejaColorFab[]>;
    private selectedBaseIndex$ = new BehaviorSubject<number>(0);
 
    private _subColorFabs$: Observable<DejaColorFab[]>;
    private selectedSubIndex$ = new BehaviorSubject<number>(0);
 
    private hilightedBaseIndex: number;
    private hilightedBaseIndex$ = new Subject<number>();
 
    private hilightedSubIndex: number;
    private hilightedSubIndex$ = new Subject<number>();
 
    private isAlive = true;
 
    public get subColorFabs() {
        return this._subColorFabs;
    }
 
    public get subColorFabs$() {
        return this._subColorFabs$;
    }
 
    public get colorFabs$() {
        return this._colorFabs$;
    }
 
    @Input() public set resetcolor(value: string | Color) {
        Iif (value === '') { value = new Color(); }
        const color = value && (typeof value === 'string' ? Color.parse(value) : value);
        this._resetcolor$.next(color || null);
    }
 
    constructor(elementRef: ElementRef, @Self() @Optional() public _control: NgControl) {
        const element = elementRef.nativeElement as HTMLElement;
 
        if (this._control) {
            this._control.valueAccessor = this;
        }
 
        this._colorFabs$ = observableFrom(this._colors$).pipe(
            map((colors) => colors.map((color, index) => new DejaColorFab(color, this._disabled, index === this._selectedBaseIndex))),
            tap((colorFabs) => this._colorFabs = colorFabs));
 
        observableCombineLatest(this._colors$, this._resetcolor$).pipe(
            takeWhile(() => this.isAlive))
            .subscribe(([colors, resetcolor]) => {
                if (!colors || !colors.length || !resetcolor) {
                    this._resetcolor = undefined;
                    return;
                }
 
                const allColors = colors.reduce((acc, color) => {
                    const materialColor = color as MaterialColor;
                    Eif (materialColor.subColors) {
                        acc = [...acc, ...materialColor.subColors];
                    } else {
                        acc.push(color);
                    }
                    return acc;
                }, []);
 
                let bestColor: Color;
                allColors.reduce((bestDiff, color) => {
                    // The best formula we found for our eye
                    const diff = 0.3 * Math.abs(color.r - resetcolor.r) + 0.4 * Math.abs(color.g - resetcolor.g) + 0.25 * Math.abs(color.b - resetcolor.b);
                    if (diff < bestDiff) {
                        bestColor = color;
                        return bestDiff = diff;
                    }
                    return bestDiff;
                }, 3 * 255);
 
                this._resetcolor = bestColor;
            });
 
        const hilightedBaseIndex$ = observableFrom(this.hilightedBaseIndex$).pipe(
            distinctUntilChanged(),
            debounce((colorIndex) => observableTimer(colorIndex !== undefined ? 100 : 1000)),
            tap((colorIndex) => {
                this.hilightedBaseIndex = colorIndex;
                const event = new CustomEvent('ColorEvent', {}) as IColorEvent;
                event.color = colorIndex ? this._colorFabs && this._colorFabs[colorIndex] && this._colorFabs[colorIndex].color : this.value;
                this.colorhover.emit(event);
            }),
            map((colorIndex) => colorIndex !== undefined ? colorIndex : this._selectedBaseIndex || 0));
 
        const selectedBaseIndex$ = observableFrom(this.selectedBaseIndex$).pipe(
            tap((colorIndex) => this._selectedBaseIndex = colorIndex));
 
        this._subColorFabs$ = observableMerge(hilightedBaseIndex$, selectedBaseIndex$).pipe(
            distinctUntilChanged(),
            tap((colorIndex) => {
                Eif (this._colorFabs) {
                    this._colorFabs.forEach((colorFab, index) => colorFab.active = index === colorIndex);
                }
            }),
            debounceTime(100),
            tap(() => element.setAttribute('sub-tr', '')),
            map((baseIndex) => this._colorFabs && this._colorFabs[baseIndex] && (this._colorFabs[baseIndex].color as MaterialColor).subColors),
            map((colors) => colors && colors.map((color, index) => new DejaColorFab(color, this._disabled, index === this._selectedSubIndex))),
            tap((subColorFabs) => {
                this._subColorFabs = subColorFabs;
                observableTimer(100).pipe(first()).subscribe(() => {
                    element.removeAttribute('sub-tr');
                });
            }));
 
        const hilightedSubIndex$ = observableFrom(this.hilightedSubIndex$).pipe(
            distinctUntilChanged(),
            debounce((subColorIndex) => observableTimer(subColorIndex !== undefined ? 200 : 1100)),
            tap((subColorIndex) => {
                this.hilightedSubIndex = subColorIndex;
                const event = new CustomEvent('ColorEvent', {}) as IColorEvent;
                event.color = subColorIndex !== undefined ? this._subColorFabs && this._subColorFabs[subColorIndex] && this._subColorFabs[subColorIndex].color : this.value;
                this.colorhover.emit(event);
            }),
            map((subColorIndex) => subColorIndex !== undefined ? subColorIndex : this._selectedSubIndex || 0));
 
        const selectedSubIndex$ = observableFrom(this.selectedSubIndex$).pipe(
            distinctUntilChanged(),
            tap((subColorIndex) => this._selectedSubIndex = subColorIndex));
 
        observableMerge(hilightedSubIndex$, selectedSubIndex$).pipe(
            takeWhile(() => this.isAlive))
            .subscribe((subColorIndex) => {
                Eif (this._subColorFabs) {
                    this._subColorFabs.forEach((colorFab, index) => colorFab.active = index === subColorIndex);
                }
            });
 
        observableFromEvent(element, 'mousemove').pipe(
            takeWhile(() => this.isAlive),
            filter((_event) => !this._disabled))
            .subscribe((event: Event) => {
                const target = event.target as HTMLElement;
                const targetIndex = (<any>target.attributes)[DejaColorSelectorComponent.indexAttribute];
                Eif (target.hasAttribute('basecolor')) {
                    this.hilightedBaseIndex$.next(+targetIndex.value);
                    this.hilightedSubIndex$.next(this.hilightedSubIndex);
                } else if (target.hasAttribute('subcolor')) {
                    this.hilightedBaseIndex$.next(this.hilightedBaseIndex);
                    this.hilightedSubIndex$.next(+targetIndex.value);
                } else {
                    this.hilightedBaseIndex$.next();
                    this.hilightedSubIndex$.next();
                }
            });
 
        observableFromEvent(element, 'click').pipe(
            takeWhile(() => this.isAlive),
            filter((_event) => !this._disabled))
            .subscribe((event: Event) => {
                const target = event.target as HTMLElement;
                Eif (target.hasAttribute('basecolor') || target.hasAttribute('subcolor')) {
                    this.value = Color.parse(target.style.backgroundColor);
                }
            });
    }
 
    /** Retourne ou definit si le selecteur est desactivé. */
    @Input()
    public set disabled(value: boolean | string) {
        const disabled = coerceBooleanProperty(value);
        Eif (this._colorFabs) {
            this._colorFabs.forEach((colorFab) => colorFab.disabled = disabled);
        }
        Eif (this._subColorFabs) {
            this._subColorFabs.forEach((colorFab) => colorFab.disabled = disabled);
        }
        this._disabled = disabled || null;
    }
 
    public get disabled() {
        return this._disabled;
    }
 
    /**
     * Retourne la meilleure couleur d'affichage pour une couleur donnée
     */
    public getBestTextColor(value: string) {
        const backColor = Color.fromHex(value);
        return backColor.bestTextColor.toHex();
    }
 
    public resetDefaultColor() {
        this.value = this._resetcolor;
    }
 
    /**
     * Definit les couleurs selectionables affichées.
     *
     * @param colors Structure hierarchique des couleurs selectionablea suivant le modele MaterialColor.
     */
    @Input()
    public set colors(colors: Color[]) {
        this._colors$.next(colors || []);
        this.selectedBaseIndex$.next(0);
    }
 
    public set selectedColor(color: Color) {
        Eif (this._colorFabs) {
            const find = this._colorFabs.find((colorFab, index) => {
                const baseColor = colorFab.color as MaterialColor;
                const subIndex = baseColor.subColors && baseColor.subColors.findIndex((subColor) => Color.equals(subColor, color));
                if (subIndex !== undefined && subIndex >= 0) {
                    this.selectedBaseIndex$.next(index);
                    observableTimer(1).pipe(first()).subscribe(() => this.selectedSubIndex$.next(subIndex));
                    // Break
                    return true;
                } else Iif (Color.equals(baseColor, color)) {
                    this.selectedBaseIndex$.next(index);
                    observableTimer(1).pipe(first()).subscribe(() => this.selectedSubIndex$.next(0));
                    // Break
                    return true;
                }
                // Continue
                return false;
            });
            if (!find) {
                this.selectedBaseIndex$.next(0);
                observableTimer(1).pipe(first()).subscribe(() => this.selectedSubIndex$.next(0));
            }
        }
    }
 
    // ************* ControlValueAccessor Implementation **************
    // set accessor including call the onchange callback
    public set value(value: Color) {
        Eif (!Color.equals(value, this._value)) {
            this.writeValue(value);
            this.onChangeCallback(value);
        }
    }
 
    // get accessor
    public get value(): Color {
        return this._value;
    }
 
    // From ControlValueAccessor interface
    public writeValue(value: Color) {
        this._value = value;
        this.selectedColor = value;
    }
 
    // From ControlValueAccessor interface
    public registerOnChange(fn: any) {
        this.onChangeCallback = fn;
    }
 
    // From ControlValueAccessor interface
    public registerOnTouched(fn: any) {
        this.onTouchedCallback = fn;
    }
 
    public setDisabledState(isDisabled: boolean) {
        this.disabled = isDisabled;
    }
    // ************* End of ControlValueAccessor Implementation **************
 
    public ngOnDestroy() {
        this.isAlive = false;
    }
}