all files / addon/components/polaris-color-picker/ hue-picker.js

55% Statements 11/20
0% Branches 0/2
60% Functions 3/5
55% Lines 11/20
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                                                                                                                                                 
import Component from '@ember/component';
import { computed } from '@ember/object';
import { typeOf } from '@ember/utils';
import layout from '../../templates/components/polaris-color-picker/hue-picker';
import { clamp } from '../../utils/math';
 
const VERTICAL_PADDING = 13;
 
function offsetForHue(hue, sliderHeight, draggerHeight) {
  const slidableArea = sliderHeight - (draggerHeight + VERTICAL_PADDING);
  return clamp((hue / 360 * slidableArea) + VERTICAL_PADDING, 0, sliderHeight - draggerHeight);
}
 
function hueForOffset(offset, sliderHeight) {
  const selectionHeight = (offset - VERTICAL_PADDING);
  const slidableArea = sliderHeight - (2 * VERTICAL_PADDING);
  return clamp((selectionHeight / slidableArea) * 360, 0, 360);
}
 
export default Component.extend({
  classNames: ['Polaris-ColorPicker__HuePicker'],
 
  layout,
 
  /*
   * Public attributes.
   */
  /**
   * The current hue value
   *
   * @property hue
   * @type {Number}
   * @default 0
   */
  hue: 0,
 
  /**
   * Callback when hue is changed
   *
   * @property onChange
   * @type {function}
   * @default null
   */
  onChange: null,
 
  /*
   * Internal properties.
   */
  sliderHeight: null,
  draggerHeight: null,
 
  draggerY: computed('hue', 'sliderHeight', function() {
    const { hue, sliderHeight, draggerHeight } = this.getProperties('hue', 'sliderHeight', 'draggerHeight');
    const offset = offsetForHue(hue, sliderHeight, draggerHeight);
    return clamp(offset, 0, sliderHeight);
  }).readOnly(),
 
  /*
   * Lifecycle hooks.
   */
  didRender() {
    this._super(...arguments);
 
    // Grab the size of the component for positioning the draggable marker.
    const huePickerElement = this.$()[0];
    this.set('sliderHeight', huePickerElement.clientHeight);
  },
 
  actions: {
    handleChange({y}) {
      const { sliderHeight, onChange } = this.getProperties('sliderHeight', 'onChange');
      if (typeOf(onChange) !== 'function') {
        return;
      }
 
      const offsetY = clamp(y, 0, sliderHeight);
      const hue = hueForOffset(offsetY, sliderHeight);
 
      onChange(hue);
    },
  }
});