diff --git a/addon/components/color-picker.js b/addon/components/color-picker.js index af2d987..c34c843 100644 --- a/addon/components/color-picker.js +++ b/addon/components/color-picker.js @@ -1,6 +1,9 @@ import Component from '@ember/component'; import layout from '../templates/components/color-picker'; + import mergeDeep from "../utils/mergeDeep"; + +import { computed } from '@ember/object'; import { assert } from '@ember/debug'; import Pickr from 'pickr'; @@ -79,7 +82,7 @@ export default Component.extend({ onSave: (hsva, instance) => { let value = this.formatColor(hsva); - this.set('value', value); + this.set('_value', value); if (this.onSave) { this.onSave(hsva, instance); @@ -93,9 +96,30 @@ export default Component.extend({ } }); - this.set('value', this.formatColor(pickr.getColor())); + this.set('_value', this.formatColor(pickr.getColor())); this._pickr = pickr; - }, + }, + + value: computed('_value', { + get() { + return this.get('_value'); + }, + + set(key, value) { + let pickr = this._pickr; + + if (pickr) { + let currentColor = this.formatColor(pickr.getColor()); + // This check is to avoid setting the same color twice one after another + // Without this check, this will result in two computations for every color change + if (currentColor !== value) { + this._pickr.setColor(value); + } + } + + return value; + } + }), formatColor(hsva) { if (!hsva) { diff --git a/tests/integration/components/color-picker-test.js b/tests/integration/components/color-picker-test.js index ac2910f..00e93ca 100644 --- a/tests/integration/components/color-picker-test.js +++ b/tests/integration/components/color-picker-test.js @@ -1,6 +1,6 @@ import { module, test } from 'qunit'; import { setupRenderingTest } from 'ember-qunit'; -import { click, render } from '@ember/test-helpers'; +import { click, fillIn, render } from '@ember/test-helpers'; import hbs from 'htmlbars-inline-precompile'; module('Integration | Component | color-picker', function(hooks) { @@ -102,4 +102,34 @@ module('Integration | Component | color-picker', function(hooks) { 'none' ); }); + + test('it respects the format option', async function(assert) { + this.set('color', '#123'); + + await render(hbs` + {{color-picker value=color format="hex"}} + `); + assert.equal(this.get('color'), '#123123'); + + await render(hbs` + {{color-picker value=color format="hsva"}} + `); + assert.equal(this.get('color'), 'hsva(153, 64%, 20%, 1.0)'); + + }); + + test('it changes color when the bound value is changed', async function(assert) { + this.set('color', '#123'); + + await render(hbs` + {{input value=color}} + {{color-picker value=color format="hex"}} + `); + + assert.equal(this.get('color'), '#123123'); + assert.equal(this.element.querySelector('input').value, '#123123'); + + await fillIn('input', '#00ff00'); + assert.equal(this.get('color'), '#00ff00'); + }); });