@radial-color-picker/angular-color-picker
Version:
Radial Color Picker - Angular
1,028 lines (1,015 loc) • 37.7 kB
JavaScript
import { __decorate } from 'tslib';
import { coerceBooleanProperty } from '@angular/cdk/coercion';
import { Platform } from '@angular/cdk/platform';
import { EventEmitter, ElementRef, Renderer2, Input, Output, Directive, forwardRef, ViewChild, HostBinding, Component, HostListener, NgModule } from '@angular/core';
import { fromEvent, merge } from 'rxjs';
import { filter, takeUntil, tap } from 'rxjs/operators';
import { trigger, state, style, transition, animate, keyframes, query, AnimationBuilder } from '@angular/animations';
import { NG_VALUE_ACCESSOR, FormsModule } from '@angular/forms';
import { DomSanitizer, BrowserModule } from '@angular/platform-browser';
import { CommonModule } from '@angular/common';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
const hexToRgb = (hex) => {
const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
const r = parseInt(result[1], 16);
const g = parseInt(result[2], 16);
const b = parseInt(result[3], 16);
return { r, g, b };
};
const extractRGB = (rgb) => {
const result = /^(?:rgb\((\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\))$/i.exec(rgb);
const r = parseInt(result[1], 10);
const g = parseInt(result[2], 10);
const b = parseInt(result[3], 10);
return { r, g, b };
};
const extractHSL = (hsl) => {
const result = /^(?:hsl\((\d{1,3})\s*,\s*(\d{1,3})%\s*,\s*(\d{1,3})%\))$/i.exec(hsl);
const h = parseInt(result[1], 10);
const s = parseInt(result[2], 10);
const l = parseInt(result[3], 10);
return { h, s, l };
};
/**
* Converts RGB color model to hexadecimal string.
*
* @memberOf Utilities
*
* @param r Integer between 0 and 255
* @param g Integer between 0 and 255
* @param b Integer between 0 and 255
*
* @return 6 char long hex string
*/
const rgbToHex = (r, g, b) => {
// tslint:disable-next-line:no-bitwise
return ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
};
/**
* Converts RGB color model to HSL model.
*
* @memberOf Utilities
*
* @param r Integer between 0 and 255
* @param g Integer between 0 and 255
* @param Integer between 0 and 255
*
* @return The HSL representation containing the hue (in degrees),
* saturation (in percentage) and luminosity (in percentage) fields.
*/
const rgbToHsl = (r, g, b) => {
r = r / 255;
g = g / 255;
b = b / 255;
let h, s;
const max = Math.max(r, g, b);
const min = Math.min(r, g, b);
const l = (max + min) / 2;
if (max === min) {
h = s = 0; // achromatic
}
else {
const d = max - min;
s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
if (max === r) {
h = (g - b) / d + (g < b ? 6 : 0);
}
if (max === g) {
h = (b - r) / d + 2;
}
if (max === b) {
h = (r - g) / d + 4;
}
}
return {
hue: h * 60,
saturation: s * 100,
luminosity: l * 100
};
};
/**
* Converts HSL color model to hexademical string.
*
* @memberOf Utilities
*
* @param h Integer between 0 and 360
* @param s Integer between 0 and 100
* @param l Integer between 0 and 50
*
* @return 6 char long hex string
*/
const hslToHex = (h, s, l) => {
const colorModel = hslToRgb(h, s, l);
return rgbToHex(colorModel.red, colorModel.green, colorModel.blue);
};
/**
* Converts HSL color model to RGB model.
* Shamelessly taken from http://axonflux.com/handy-rgb-to-hsl-and-rgb-to-hsv-color-model-c
*
* @memberOf Utilities
*
* @param h The hue. Number in the 0-360 range
* @param s The saturation. Number in the 0-100 range
* @param l The luminosity. Number in the 0-100 range
*
* @return The RGB representation containing the red, green and blue fields
*/
const hslToRgb = (h, s, l) => {
let r, g, b;
h = h / 360;
s = s / 100;
l = l / 100;
if (s === 0) {
r = g = b = l; // achromatic
}
else {
const q = l < 0.5 ? l * (1 + s) : l + s - l * s;
const p = 2 * l - q;
r = _hue2rgb(p, q, h + 1 / 3);
g = _hue2rgb(p, q, h);
b = _hue2rgb(p, q, h - 1 / 3);
}
return {
red: Math.round(r * 255),
green: Math.round(g * 255),
blue: Math.round(b * 255)
};
};
const _hue2rgb = (p, q, t) => {
if (t < 0) {
t += 1;
}
if (t > 1) {
t -= 1;
}
if (t < 1 / 6) {
return p + (q - p) * 6 * t;
}
if (t < 1 / 2) {
return q;
}
if (t < 2 / 3) {
return p + (q - p) * (2 / 3 - t) * 6;
}
return p;
};
/**
* Modified version of Lea Verou's
* {@link https://github.com/leaverou/conic-gradient conic-gradient}.
*
* @example
* paintColorWheelToCanvas(document.querySelector('#canvas'), 250);
*
* @param canvas Canvas to paint the color wheel
* @param size Color wheel diameter in pixels
* @returns canvas The passed canvas for easier chaining
*/
const paintColorWheelToCanvas = (canvas, size) => {
const half = size / 2;
const radius = Math.sqrt(2) * half;
const deg = Math.PI / 180;
const pi2 = Math.PI * 2;
canvas.width = canvas.height = size;
const ctx = canvas.getContext('2d');
// .02: To prevent empty blank line and corresponding moire
// only non-alpha colors are cared now
const thetaOffset = 0.5 * deg + 0.02;
// Transform coordinate system so that angles start from the top left, like in CSS
ctx.translate(half, half);
ctx.rotate(-Math.PI / 2);
ctx.translate(-half, -half);
for (let i = 0; i < 360; i += 0.5) {
ctx.fillStyle = `hsl(${i}, 100%, 50%)`;
ctx.beginPath();
ctx.moveTo(half, half);
const beginArg = i * deg;
const endArg = Math.min(pi2, beginArg + thetaOffset);
ctx.arc(half, half, radius, beginArg, endArg);
ctx.closePath();
ctx.fill();
}
return canvas;
};
/**
*
* @param canvas Canvas to paint the color wheel
* @param diameter Color wheel diameter in pixels
* @param coefficient Relation between inner white circle outer border and color circle outer border, controls the width of the color gradient path
* @returns canvas The passed canvas for easier chaining
*/
const renderColorMap = (canvas, diameter, coefficient = 0.77) => {
canvas.width = canvas.height = diameter;
const radius = diameter / 2;
const toRad = (2 * Math.PI) / 360;
const step = 0.2;
const aliasing = 1;
const ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, diameter, diameter);
for (let i = 0; i < 360; i += step) {
const sRad = (i - aliasing) * toRad;
const eRad = (i + step) * toRad;
ctx.beginPath();
ctx.arc(radius, radius, radius / 2, sRad, eRad, false);
ctx.strokeStyle = 'hsl(' + i + ', 100%, 50%)';
ctx.lineWidth = radius;
ctx.closePath();
ctx.stroke();
}
ctx.fillStyle = 'rgb(255, 255, 255)';
ctx.beginPath();
ctx.arc(radius, radius, radius * coefficient, 0, Math.PI * 2, true);
ctx.closePath();
ctx.fill();
ctx.strokeStyle = 'rgb(255, 255, 255)';
ctx.lineWidth = 2;
ctx.beginPath();
ctx.arc(radius, radius, radius, 0, 2 * Math.PI);
ctx.stroke();
return canvas;
};
const Cache = {
sin90: Math.sin(270 * Math.PI / 180),
sin180: Math.sin(180 * Math.PI / 180),
sin270: Math.sin(90 * Math.PI / 180),
cos90: Math.cos(270 * Math.PI / 180),
cos180: Math.cos(180 * Math.PI / 180),
cos270: Math.cos(90 * Math.PI / 180)
};
const Quadrant = {
I: 'q1',
II: 'q2',
III: 'q3',
IV: 'q4'
};
const bezierCurves = {
// Standard easing puts subtle attention at the end of an animation,
// by giving more time to deceleration than acceleration.It is the most common form of easing.
standard: 'cubic-bezier(0.4, 0.0, 0.2, 1)',
// Elements exiting a screen use acceleration easing, where they start at rest and end at peak velocity.
acc: 'cubic-bezier(0.4, 0.0, 1, 1)',
// Incoming elements are animated using deceleration easing,
// which starts a transition at peak velocity(the fastest point of an element’s movement) and ends at rest.
dec: 'cubic-bezier(0.0, 0.0, 0.2, 1)'
};
const timings = {
simpleMicro: '100ms',
simpleEnter: '150ms',
simpleExit: '75ms',
complexEnter: '250ms',
complexExit: '200ms',
largeEnter: '300ms',
largeExit: '250ms'
};
/**
* Calculates in which quadrant is the point, serves for calculating the right angle.
*
* @param point x,y coordinates of client's pointer position
*/
const calculateQuadrant = (point) => {
if (point.x > 0) {
if (point.y > 0) {
return Quadrant.I;
}
else {
return Quadrant.IV;
}
}
else {
if (point.y > 0) {
return Quadrant.II;
}
else {
return Quadrant.III;
}
}
};
/**
* Calculates the distance between two points.
*
* This variant expects separate x/y values for each point. If you already have
* the points as array or object use the corresponding methods.
*
* @param x1 The X value of the first point.
* @param y1 The Y value of the first point.
* @param x2 The X value of the second point.
* @param y2 The Y value of the second point.
* @return The distance between the two points.
*/
const distanceOfSegmentByXYValues = (x1, y1, x2, y2) => {
return Math.sqrt(((x1 - x2) * (x1 - x2)) + ((y1 - y2) * (y1 - y2)));
};
/**
* Calculates the angle of rotation
*
* @param point x,y coordinates of client's pointer position
* @param quadrant one of four quarters of the coordinate plane
*/
const determineCSSRotationAngle = (point, quadrant) => {
let cx = point.x;
let cy = point.y;
let add = 0;
switch (quadrant) {
case Quadrant.II:
add = 270;
cx = ((point.x * Cache.cos90) - (point.y * Cache.sin90));
cy = ((point.x * Cache.sin90) + (point.y * Cache.cos90));
break;
case Quadrant.III:
add = 180;
cx = ((point.x * Cache.cos180) - (point.y * Cache.sin180));
cy = ((point.x * Cache.sin180) + (point.y * Cache.cos180));
break;
case Quadrant.IV:
add = 90;
cx = ((point.x * Cache.cos270) - (point.y * Cache.sin270));
cy = ((point.x * Cache.sin270) + (point.y * Cache.cos270));
break;
}
const rotation = Math.atan((distanceOfSegmentByXYValues(0, cy, cx, cy)) / (distanceOfSegmentByXYValues(0, cy, 0, 0)));
return (rotation * (180 / Math.PI)) + add;
};
let RotatableDirective = class RotatableDirective {
constructor(el, renderer, platform) {
this.el = el;
this.renderer = renderer;
this.platform = platform;
this.dragging = false;
this.rotateStart = new EventEmitter();
this.rotating = new EventEmitter();
this.rotateStop = new EventEmitter();
if (this.platform.IOS || this.platform.ANDROID) {
this.mouseDownEv = 'touchstart';
this.mouseUpEv = 'touchend';
this.mouseMoveEv = 'touchmove';
this.cancelEv = 'touchcancel';
}
else {
this.mouseDownEv = 'mousedown';
this.mouseUpEv = 'mouseup';
this.mouseMoveEv = 'mousemove';
this.cancelEv = 'mouseout';
}
}
get isDisabled() {
return this.disable ? coerceBooleanProperty(this.disable) : false;
}
ngOnInit() {
}
ngOnChanges(changes) {
if (changes.angle && changes.angle.currentValue) {
// console.log(changes.angle.currentValue);
const angle = changes.angle.currentValue + 90;
this.renderer.setStyle(this.el.nativeElement, 'transform', `rotate(${angle}deg)`);
}
}
ngAfterViewInit() {
// console.log(this.isDisabled);
requestAnimationFrame(this.initialRender.bind(this));
this.rect = this.el.nativeElement.getBoundingClientRect();
this.mouseUp$ = fromEvent(this.el.nativeElement, this.mouseUpEv, { passive: true });
this.mouseOut$ = fromEvent(this.el.nativeElement, this.cancelEv, { passive: true });
this.mouseDownSub = fromEvent(this.el.nativeElement, this.mouseDownEv, { passive: true })
.pipe(filter((val) => {
return this.active && !this.isDisabled;
}))
.subscribe((downEvent) => {
this.dragging = true;
this.rect = this.el.nativeElement.getBoundingClientRect();
// console.log('mouse down', downEvent, this.rect);
this.point = this.createPoint(downEvent);
this.rotateStart.emit(this.point);
this.applyRotation();
this.mouseMoveSub = fromEvent(this.el.nativeElement, this.mouseMoveEv).pipe(takeUntil(merge(this.mouseOut$, this.mouseUp$).pipe(tap((upEvent) => {
this.rect = this.el.nativeElement.getBoundingClientRect();
// console.log('mouse up', upEvent, this.rect);
this.dragging = false;
this.mouseMoveSub.unsubscribe();
this.rotateStop.emit(this.point);
})))).subscribe((moveEvent) => {
this.rect = this.el.nativeElement.getBoundingClientRect();
// console.log('mouse move', moveEvent, this.rect);
this.point = this.createPoint(moveEvent);
// console.log(this.point);
this.applyRotation();
});
});
}
initialRender() {
const angle = this.angle + 90;
this.renderer.setStyle(this.el.nativeElement, 'transform', `rotate(${angle}deg)`);
}
rotationRender() {
// console.log(this.rotation);
this.renderer.setStyle(this.el.nativeElement, 'transform', `rotate(${this.rotation}deg)`);
}
ngOnDestroy() {
if (this.mouseDownSub) {
this.mouseDownSub.unsubscribe();
}
if (this.mouseMoveSub) {
this.mouseMoveSub.unsubscribe();
}
if (this.mouseUpSub) {
this.mouseUpSub.unsubscribe();
}
// console.log('directive destroy');
}
applyRotation() {
const quadrant = calculateQuadrant(this.point);
const rotation = determineCSSRotationAngle(this.point, quadrant);
// console.log(rotation);
this.rotating.emit(rotation);
this.rotation = rotation;
requestAnimationFrame(this.rotationRender.bind(this));
}
createPoint(mouseEvent) {
let point;
if (mouseEvent.targetTouches) {
point = {
x: this._normalizeX(mouseEvent.targetTouches[0].clientX),
y: this._normalizeY(mouseEvent.targetTouches[0].clientY)
};
}
else {
point = {
x: this._normalizeX(mouseEvent.clientX),
y: this._normalizeY(mouseEvent.clientY)
};
}
// console.log('point', point);
return point;
}
_normalizeX(coordX) {
return coordX - this.rect.left - this.rect.width / 2;
}
_normalizeY(coordY) {
return ((coordY - this.rect.top) * -1) + this.rect.height / 2;
}
};
RotatableDirective.ctorParameters = () => [
{ type: ElementRef },
{ type: Renderer2 },
{ type: Platform }
];
__decorate([
Input()
], RotatableDirective.prototype, "angle", void 0);
__decorate([
Input()
], RotatableDirective.prototype, "disable", void 0);
__decorate([
Input()
], RotatableDirective.prototype, "active", void 0);
__decorate([
Output()
], RotatableDirective.prototype, "rotateStart", void 0);
__decorate([
Output()
], RotatableDirective.prototype, "rotating", void 0);
__decorate([
Output()
], RotatableDirective.prototype, "rotateStop", void 0);
RotatableDirective = __decorate([
Directive({
selector: '[rcpRotatable]'
})
], RotatableDirective);
const Animations = {
buttonAnimation: trigger('buttonAnimation', [
state('void', style({ transform: 'scale3d(1, 1, 1)' })),
state('false', style({ transform: 'scale3d(1, 1, 1)' })),
state('true', style({ transform: 'scale3d(1, 1, 1)' })),
transition('* => 1', [
animate('400ms cubic-bezier(0.35, 0, 0.25, 1)', keyframes([
style({ transform: 'scale3d(1, 1, 1)', offset: 0 }),
style({ transform: 'scale3d(0.8, 0.8, 1)', offset: 0.25 }),
style({ transform: 'scale3d(1, 1, 1)', offset: 0.5 }),
style({ transform: 'scale3d(1, 1, 1)', offset: 1.0 }),
])),
])
]),
rippleAnimation: trigger('rippleAnimation', [
state('void', style({ opacity: 0, transform: 'scale3d(0.8, 0.8, 1)' })),
state('false', style({ opacity: 0, transform: 'scale3d(0.8, 0.8, 1)' })),
state('true', style({ opacity: 0, transform: 'scale3d(0.8, 0.8, 1)' })),
transition('* => 1', [
query(':self', animate('400ms cubic-bezier(0.35, 0, 0.25, 1)', keyframes([
style({ opacity: 0.2, transform: 'scale3d(0.8, 0.8, 1)', offset: 0 }),
style({ opacity: 0.2, transform: 'scale3d(0.8, 0.8, 1)', offset: 0.20 }),
style({ opacity: 0, borderWidth: 0, transform: 'scale3d({{scale}}, {{scale}}, 1)', offset: 1.0 }),
])), {
params: {
scale: '3.8'
}
})
])
])
};
const AnimationsMeta = {
knobAnimationEnter: [
style({ opacity: 1, transform: 'scale3d(1, 1, 1)' }),
animate('150ms cubic-bezier(0.4, 0.0, 1, 1)', keyframes([
style({ opacity: 1, transform: 'scale3d(0, 0, 1)', offset: 0 }),
style({ opacity: 1, transform: 'scale3d(1, 1, 1)', offset: 1.0 }),
]))
],
knobAnimationExit: [
style({ opacity: 0, transform: 'scale3d(0, 0, 1)' }),
animate('100ms cubic-bezier(0.0, 0.0, 0.2, 1)', keyframes([
style({ opacity: 1, transform: 'scale3d(1, 1, 1)', offset: 0 }),
style({ opacity: 1, transform: 'scale3d(0, 0, 1)', offset: 1.0 }),
]))
],
gradientAnimationEnter: [
style({ opacity: 1, transform: 'scale3d(1, 1, 1)' }),
animate('200ms cubic-bezier(0.4, 0.0, 1, 1)', keyframes([
style({ opacity: 1, transform: 'scale3d(0, 0, 1)', offset: 0 }),
style({ opacity: 1, transform: 'scale3d(1, 1, 1)', offset: 1.0 }),
]))
],
gradientAnimationExit: [
style({ opacity: 0, transform: 'scale3d(0, 0, 1)' }),
animate('150ms cubic-bezier(0.0, 0.0, 0.2, 1)', keyframes([
style({ opacity: 1, transform: 'scale3d(1, 1, 1)', offset: 0 }),
style({ opacity: 1, transform: 'scale3d(0, 0, 1)', offset: 1.0 }),
]))
],
};
const RADIAL_COLOR_PICKER_VALUE_ACCESSOR = {
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => RadialColorPickerComponent),
multi: true
};
let nextUniqueId = 0;
const rgbRegex = /rgb\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)$/;
const hslRegex = /hsl\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)$/;
var RCPLifecycleEvents;
(function (RCPLifecycleEvents) {
RCPLifecycleEvents["show"] = "show";
RCPLifecycleEvents["shown"] = "shown";
RCPLifecycleEvents["selected"] = "selected";
RCPLifecycleEvents["hide"] = "hide";
RCPLifecycleEvents["hidden"] = "hidden";
})(RCPLifecycleEvents || (RCPLifecycleEvents = {}));
let RadialColorPickerComponent = class RadialColorPickerComponent {
constructor(el, renderer, animationBuilder) {
this.el = el;
this.renderer = renderer;
this.animationBuilder = animationBuilder;
this._uid = `rcp-${nextUniqueId++}`;
this.coefficient = 0.77;
this.hueValue = 266;
this.disabled = false;
this.active = false;
this.knobState = false;
this.gradientState = false;
this._value = 'FF0000';
this.defaultSize = 300;
this.colorType = 'hex';
this.enterAnimation = true;
this.exitAnimation = true;
this.selectToChange = false;
this.collapsed = true;
this.collapsible = true;
this.selected = new EventEmitter();
this.colorChange = new EventEmitter();
this.lifecycle = new EventEmitter();
}
get isExplicit() {
return coerceBooleanProperty(this.selectToChange);
}
get hasEnterAnimation() {
return coerceBooleanProperty(this.enterAnimation);
}
get hasExitAnimation() {
return coerceBooleanProperty(this.exitAnimation);
}
get isCollapsible() {
return coerceBooleanProperty(this.collapsible);
}
get isCollapsed() {
return coerceBooleanProperty(this.collapsed);
}
get getSize() {
return this.size ? this.size : this.defaultSize;
}
set value(value) {
let val = value;
if (value) {
if (value instanceof Object) {
val = value.value;
}
this._value = val;
if (val.includes('#')) {
this._value = val.substring(1);
const rgb = hexToRgb(this._value);
const hsl = rgbToHsl(rgb.r, rgb.g, rgb.b);
this.hueValue = hsl.hue;
}
else if (val.includes('rgb')) {
const color = extractRGB(val);
const hsl = rgbToHsl(color.r, color.g, color.b);
this._value = rgbToHex(color.r, color.g, color.b);
this.hueValue = hsl.hue;
}
else if (val.includes('hsl')) {
const color = extractHSL(val);
this._value = hslToHex(color.h, 100, 50);
this.hueValue = color.h;
}
// console.log('set value hue', this.hueValue);
}
if (!this.isExplicit) {
this.notifyValueChange();
}
}
get value() {
let color = this._value;
color = '#' + this._value;
return color;
}
get width() {
return this.size ? this.size : this.defaultSize;
}
get height() {
return this.size ? this.size : this.defaultSize;
}
notifyValueChange() {
if (this.onChange) {
let color = this.value;
const rgb = hexToRgb(this._value);
const hsl = rgbToHsl(rgb.r, rgb.g, rgb.b);
switch (this.colorType) {
case 'hex':
color = '#' + this._value;
break;
case 'rgb':
color = `rgb(${rgb.r}, ${rgb.g}, ${rgb.b})`;
break;
case 'hsl':
color = `hsl(${hsl.hue}, ${hsl.saturation}%, ${hsl.luminosity}%)`;
break;
default:
color = '#' + this._value;
}
this.onChange(color);
}
}
writeValue(obj) {
// console.log(obj);
this.value = obj;
}
registerOnChange(fn) {
this.onChange = fn;
}
registerOnTouched(fn) {
this.onTouched = fn;
}
setDisabledState(isDisabled) {
this.disabled = isDisabled;
}
ngOnInit() {
const rgb = hexToRgb(this._value);
const hsl = rgbToHsl(rgb.r, rgb.g, rgb.b);
this.hueValue = hsl.hue;
}
ngOnChanges(changes) {
// console.log(changes);
if (changes.color && changes.color.currentValue) {
this.value = changes.color.currentValue;
}
if (changes.size && changes.size.currentValue) {
this.recalculateKnobPosition();
}
}
ngAfterViewInit() {
this.recalculateKnobPosition();
this.rect = this.el.nativeElement.getBoundingClientRect();
// console.log(this.rect);
renderColorMap(this.canvas.nativeElement, this.getSize);
// console.log(this.collapsed);
if (this.isCollapsed) {
this.introAnimation();
}
}
open() {
this.introAnimation();
}
close() {
this.outroAnimation();
}
introAnimation() {
this.lifecycle.emit(RCPLifecycleEvents.show);
this.gradientState = true;
this.createPlayerForGradient(this.hasEnterAnimation);
this.gradientPlayer.onDone(() => {
this.knobState = true;
this.createPlayerForKnob(this.hasEnterAnimation);
this.knobPlayer.onDone(() => {
this.active = true;
this.lifecycle.emit(RCPLifecycleEvents.shown);
});
if (this.hasEnterAnimation) {
this.knobPlayer.play();
}
else {
this.knobPlayer.finish();
}
});
if (this.hasEnterAnimation) {
this.gradientPlayer.play();
}
else {
this.gradientPlayer.finish();
}
}
outroAnimation() {
this.lifecycle.emit(RCPLifecycleEvents.hide);
this.knobState = false;
this.createPlayerForKnob();
this.knobPlayer.onDone(() => {
this.gradientState = false;
this.createPlayerForGradient();
this.gradientPlayer.onDone(() => {
this.active = false;
this.lifecycle.emit(RCPLifecycleEvents.hidden);
});
if (this.hasExitAnimation) {
this.gradientPlayer.play();
}
else {
this.gradientPlayer.finish();
}
});
if (this.hasExitAnimation) {
this.knobPlayer.play();
}
else {
this.knobPlayer.finish();
}
}
onRotate(rotation) {
const hex = hslToHex(this.angleToHue(rotation), 100, 50);
this.value = hex;
// console.log('on rotate', this.isExplicit);
if (!this.isExplicit) {
this.colorChange.emit(`#${hex}`);
}
}
angleToHue(rotation) {
return rotation - 90;
}
recalculateKnobPosition() {
const radius = (this.getSize / 2);
const innerCircle = radius * this.coefficient;
const areaSize = radius - innerCircle;
if (this.knob) {
const knobRect = this.knob.nativeElement.getBoundingClientRect();
const knobPosition = radius - (areaSize / 2 + innerCircle) - knobRect.width / 2;
this.renderer.setStyle(this.knob.nativeElement, 'top', knobPosition + 'px');
}
}
confirmColor($event) {
// console.log('confirm color', $event);
if (!this.isCollapsible) {
this.selected.emit($event.color);
this.lifecycle.emit(RCPLifecycleEvents.selected);
this.notifyValueChange();
return;
}
// is color picker collapsed
if (this.knobState) {
this.selected.emit($event.color);
this.lifecycle.emit(RCPLifecycleEvents.selected);
this.notifyValueChange();
this.outroAnimation();
}
else {
this.introAnimation();
}
}
createPlayerForGradient(hasAnimation = true) {
if (this.gradientPlayer) {
this.gradientPlayer.destroy();
}
let animationFactory;
if (this.gradientState) {
animationFactory = this.animationBuilder
.build(AnimationsMeta.gradientAnimationEnter);
}
else {
animationFactory = this.animationBuilder
.build(AnimationsMeta.gradientAnimationExit);
}
this.gradientPlayer = animationFactory.create(this.canvas.nativeElement);
}
createPlayerForKnob(hasAnimation = true) {
if (this.knobPlayer) {
this.knobPlayer.destroy();
}
let animationFactory;
if (this.knobState) {
animationFactory = this.animationBuilder
.build(AnimationsMeta.knobAnimationEnter);
}
else {
animationFactory = this.animationBuilder
.build(AnimationsMeta.knobAnimationExit);
}
this.knobPlayer = animationFactory.create(this.knob.nativeElement);
}
ngOnDestroy() {
if (this.knobPlayer) {
this.knobPlayer.destroy();
}
if (this.gradientPlayer) {
this.gradientPlayer.destroy();
}
// console.log('color picker destroy');
}
};
RadialColorPickerComponent.ctorParameters = () => [
{ type: ElementRef },
{ type: Renderer2 },
{ type: AnimationBuilder }
];
__decorate([
Input()
], RadialColorPickerComponent.prototype, "color", void 0);
__decorate([
Input()
], RadialColorPickerComponent.prototype, "colorType", void 0);
__decorate([
Input()
], RadialColorPickerComponent.prototype, "size", void 0);
__decorate([
Input()
], RadialColorPickerComponent.prototype, "enterAnimation", void 0);
__decorate([
Input()
], RadialColorPickerComponent.prototype, "exitAnimation", void 0);
__decorate([
Input()
], RadialColorPickerComponent.prototype, "selectToChange", void 0);
__decorate([
Input()
], RadialColorPickerComponent.prototype, "collapsed", void 0);
__decorate([
Input()
], RadialColorPickerComponent.prototype, "collapsible", void 0);
__decorate([
Output()
], RadialColorPickerComponent.prototype, "selected", void 0);
__decorate([
Output()
], RadialColorPickerComponent.prototype, "colorChange", void 0);
__decorate([
Output()
], RadialColorPickerComponent.prototype, "lifecycle", void 0);
__decorate([
ViewChild('canvas', { static: false, read: ElementRef })
], RadialColorPickerComponent.prototype, "canvas", void 0);
__decorate([
ViewChild('knob', { static: false, read: ElementRef })
], RadialColorPickerComponent.prototype, "knob", void 0);
__decorate([
ViewChild('rotator', { static: false, read: ElementRef })
], RadialColorPickerComponent.prototype, "rotator", void 0);
__decorate([
HostBinding('style.width.px')
], RadialColorPickerComponent.prototype, "width", null);
__decorate([
HostBinding('style.height.px')
], RadialColorPickerComponent.prototype, "height", null);
RadialColorPickerComponent = __decorate([
Component({
selector: 'rcp-radial-color-picker',
template: "<div class=\"wrapper\">\r\n <canvas #canvas ></canvas>\r\n <div class=\"rotator\" #rotator rcpRotatable [disable]=\"disabled\" [angle]=\"hueValue\" (rotating)=\"onRotate($event)\" [active]=\"active\">\r\n <div class=\"knob\" #knob></div>\r\n </div>\r\n <rcp-color-preview [color]=\"value\" [size]=\"size\" [coefficient]=\"coefficient\" (confirm)=\"confirmColor($event)\"></rcp-color-preview>\r\n</div>\r\n",
providers: [RADIAL_COLOR_PICKER_VALUE_ACCESSOR],
styles: ["*{box-sizing:border-box}:host{box-sizing:border-box;display:block;overflow:hidden;border-radius:50%}:host *{box-sizing:border-box}:host .wrapper{position:relative;display:-webkit-box;display:flex;-webkit-box-align:center;align-items:center;-webkit-box-pack:center;justify-content:center;width:100%;height:100%;border-radius:50%}:host .wrapper canvas{position:absolute;z-index:1;top:0;right:0;bottom:0;left:0;opacity:0;border-radius:50%;box-shadow:0 0 5px 0 rgba(0,0,0,.6)}:host .wrapper .rotator{position:absolute;z-index:2;display:-webkit-box;display:flex;-webkit-box-align:center;align-items:center;-webkit-box-flex:0;flex:0 0 100%;-webkit-box-orient:vertical;-webkit-box-direction:normal;flex-direction:column;-webkit-box-pack:center;justify-content:center;width:100%;height:100%;-webkit-transform:translate3d(0,0,0);transform:translate3d(0,0,0);border-radius:50%;-webkit-backface-visibility:hidden;backface-visibility:hidden}:host .wrapper .rotator .knob{position:absolute;z-index:11;width:20px;height:20px;pointer-events:none;opacity:0;border-radius:50%;background-color:#fff;box-shadow:0 0 3px 0 rgba(0,0,0,.6)}"]
})
], RadialColorPickerComponent);
let ColorPreviewComponent = class ColorPreviewComponent {
constructor(sanitizer, el) {
this.sanitizer = sanitizer;
this.el = el;
this.confirm = new EventEmitter();
}
get width() {
return (this.size && this.size < 200) ? '36px' : '70px';
}
get height() {
return (this.size && this.size < 200) ? '36px' : '70px';
}
onClick() {
this.buttonState = {
value: true,
params: {
scale: this.relation
}
};
this.rippleState = {
value: true,
params: {
scale: this.relation
}
};
}
ngOnInit() {
}
ngAfterViewInit() {
// console.log(this.size);
const rect = this.el.nativeElement.getBoundingClientRect();
const innerCircle = this.size * this.coefficient;
this.relation = innerCircle / rect.width;
// console.log('relation', relation);
}
ngOnChanges(changes) {
if (changes.color && changes.color.currentValue) {
this.background = this.sanitizer.bypassSecurityTrustStyle(this.color);
}
}
rippleAnimationDone($event) {
// console.log($event);
if ($event.toState) {
this.rippleState = false;
this.confirm.emit({
color: this.color
});
}
}
buttonAnimationDone($event) {
// console.log($event);
if ($event.toState) {
this.buttonState = false;
}
}
ngOnDestroy() {
// console.log('color preview destroy');
}
};
ColorPreviewComponent.ctorParameters = () => [
{ type: DomSanitizer },
{ type: ElementRef }
];
__decorate([
Input()
], ColorPreviewComponent.prototype, "coefficient", void 0);
__decorate([
Input()
], ColorPreviewComponent.prototype, "color", void 0);
__decorate([
Input()
], ColorPreviewComponent.prototype, "size", void 0);
__decorate([
Output()
], ColorPreviewComponent.prototype, "confirm", void 0);
__decorate([
HostBinding('style.width')
], ColorPreviewComponent.prototype, "width", null);
__decorate([
HostBinding('style.height')
], ColorPreviewComponent.prototype, "height", null);
__decorate([
HostListener('click')
], ColorPreviewComponent.prototype, "onClick", null);
ColorPreviewComponent = __decorate([
Component({
selector: 'rcp-color-preview',
template: "\r\n<div class=\"color\" [style.background-color]=\"background\" [@buttonAnimation]=\"buttonState\" (@buttonAnimation.done)=\"buttonAnimationDone($event)\"></div>\r\n<div class=\"color-shadow\" [style.border-color]=\"background\" [@rippleAnimation]=\"rippleState\" (@rippleAnimation.done)=\"rippleAnimationDone($event)\"></div>\r\n",
animations: [
Animations.rippleAnimation,
Animations.buttonAnimation
],
styles: ["*{box-sizing:border-box}:host{box-sizing:border-box;position:relative;z-index:10}:host *{box-sizing:border-box}:host .color{position:absolute;z-index:12;display:block;width:100%;height:100%;border:6px solid #fff;border-radius:50%;box-shadow:0 0 0 1px #b2b2b2}:host .color-shadow{position:absolute;z-index:11;width:100%;height:100%;border-width:10px;border-style:solid;border-radius:50%}:host.final-state-1{-webkit-transform:translate3d(0,0,0) scale3d(1,1,1);transform:translate3d(0,0,0) scale3d(1,1,1);box-shadow:0 0 1px 6px #fff,0 0 0 7px #b2b2b2}"]
})
], ColorPreviewComponent);
let RadialColorPickerModule = class RadialColorPickerModule {
};
RadialColorPickerModule = __decorate([
NgModule({
imports: [
CommonModule,
FormsModule,
BrowserModule,
BrowserAnimationsModule
],
declarations: [
RotatableDirective,
ColorPreviewComponent,
RadialColorPickerComponent
],
exports: [
RotatableDirective,
RadialColorPickerComponent
]
})
], RadialColorPickerModule);
/*
* Public API Surface of radial-color-picker
*/
/**
* Generated bundle index. Do not edit.
*/
export { Cache, ColorPreviewComponent, Quadrant, RADIAL_COLOR_PICKER_VALUE_ACCESSOR, RadialColorPickerComponent, RadialColorPickerModule, RotatableDirective, _hue2rgb, bezierCurves, calculateQuadrant, determineCSSRotationAngle, distanceOfSegmentByXYValues, extractHSL, extractRGB, hexToRgb, hslToHex, hslToRgb, paintColorWheelToCanvas, renderColorMap, rgbToHex, rgbToHsl, timings, Animations as ɵa };
//# sourceMappingURL=radial-color-picker-angular-color-picker.js.map