import angular from 'angular' import _ from 'lodash' import template from './color-input.html' angular.module('app').directive('mflyColorInput', ['translateFactory', function mflyColorInput(translateFactory) { return { link: ($scope: ScopeKeyValuePair) => { $scope.validateHex = () => { const hexReg = new RegExp('^([A-Fa-f0-9]{6})$', 'g') $scope.hasColor = false if ($scope.value) { if ($scope.value.match(hexReg) !== null) { $scope.hasColor = true } } if (_.trim($scope.value).length > 0) { $scope.validationForm.mflyColorInput.$setValidity('invalidHexColor', $scope.hasColor) } else { // empty input passes HexColor check ok - represents transparency -- // input could still be invalid if @required = true $scope.validationForm.mflyColorInput.$setValidity('invalidHexColor', true) } } $scope.validateHex() // Every time the value changes we should put it through the validator function $scope.$watch('value', (newValue, oldValue) => { if (newValue !== oldValue) { $scope.validateHex() } }) // necessary to style preceeding add on element (CSS has no prev sibling selector) $scope.$watch('validationForm.mflyColorInput.$valid', (newValue) => { $scope.invalidAddOn = !newValue }) $scope.$watch('validationForm.mflyColorInput.$dirty', (newValue) => { $scope.dirtyAddOn = newValue }) // This is the callback function called from the 3rd party spectrum picker // It is called whenever that picker makes a change to the value, which is bound to both directives. $scope.pickerChangedColor = (newColor) => { // Must be updated here in a $scope.apply because the picker component is jQuery // and outside of the Angular universe. $scope.$apply(() => { // Use $setViewValue to ensure the form is dirtied $scope.validationForm.mflyColorInput.$setViewValue(newColor.substr(1)) // Call $render to force the input to update to the new $scope.value $scope.validationForm.mflyColorInput.$render() }) } $scope.inputWasClicked = function() { $scope.onClick() } // used to set the background ng-style when there is a valid 6-digit hex // without this function check, a valid 3-digit hex would resove in the spectrum // component (but hasColor = false for the mfly component) // visually that results in the transparent square overlay with a color //underneath. $scope.currentBackgroundColor = () => { if ($scope.hasColor) { return {'background-color': '#' + $scope.value } } else { return '' } } $scope.requiredText = translateFactory.instant('JSUI.REQUIRED') $scope.invalidColorText = translateFactory.instant('JSUI.INVALID_COLOR') }, restrict: 'E', scope: { inputId: '@', isDisabled: '=', onClick: '&', required: '@', value: '=' }, template, } }])