import { Component, OnInit, Input, SimpleChanges, Renderer2, Inject, ElementRef, Output, EventEmitter, ViewChild, HostBinding, HostListener } from '@angular/core' import { DOCUMENT } from '@angular/common' import { BaseComponent } from '../base-component' import { Color } from '../../helpers/color.class' @Component({ selector: 'sv-panel', templateUrl: './sv-panel.component.html', styleUrls: [`./sv-panel.component.scss`] }) export class SvPanelComponent extends BaseComponent implements OnInit { @Input() public hue: Color @Input() public color: Color @Output() public colorChange = new EventEmitter(false) @ViewChild('cursor') public cursor: ElementRef constructor( renderer: Renderer2, @Inject(DOCUMENT) document, elementRef: ElementRef ) { super(document, elementRef, renderer) } @HostBinding('style.backgroundColor') public get backgroundColor(): string { return this.hue ? this.hue.toRgbaString() : '#3f51b5' } @HostListener('mousedown', ['$event']) @HostListener('touchstart', ['$event']) public onClick(event: any): void { this.onEventChange(event) } ngOnInit(): void { // if (!this.hue) { // this.hue = Color.from(this.color.getHsva()) // } // this.renderer.setStyle( // this.elementRef.nativeElement, // 'backgroundColor', // this.backgroundColor // ) } // color 改变时更改 cursor 位置 public ngOnChanges(changes: SimpleChanges): void { if ( changes.color && changes.color.previousValue !== changes.color.currentValue ) { const hsva = this.color.getHsva() this.changePointerPosition(hsva.saturation, hsva.value) } } public movePointer({ x, y, height, width }): void { const saturation = (x * 100) / width const bright = -((y * 100) / height) + 100 this.changePointerPosition(saturation, bright) const hsva = this.hue.getHsva() const color = this.color.getHsva() const newColor = new Color().setHsva( hsva.hue, saturation, bright, color.alpha ) this.colorChange.emit(newColor) } private changePointerPosition(x: number, y: number): void { x = Math.max(0, Math.min(x, 100)) y = Math.max(0, Math.min(y, 100)) this.renderer.setStyle(this.cursor.nativeElement, 'top', `${100 - y}%`) this.renderer.setStyle(this.cursor.nativeElement, 'left', `${x}%`) } }