<template>
  <div class="kole-colorpicker">
    <div class="kole-colorpicker-presets">
      <div v-for="(c, i) in presets" :key="i" class="kole-colorpicker-swatch"
           :class="{ 'is-active': c.toLowerCase() === hex.toLowerCase() }"
           :style="{ background: c }" @click="setHex(c)"></div>
    </div>
    <div class="kole-colorpicker-row">
      <div class="kole-colorpicker-preview" :style="{ background: preview }"></div>
      <input type="color" class="kole-colorpicker-native" :value="hex" @input="setHex($event.target.value)" />
      <input class="kole-colorpicker-hex" :value="hex.toUpperCase()" maxlength="7" @input="onHexInput" />
    </div>
    <div class="kole-colorpicker-alpha">
      透明度
      <input type="range" min="0" max="100" :value="Math.round(alpha * 100)" @input="setAlpha($event.target.value / 100)" />
      <span>{{ Math.round(alpha * 100) }}%</span>
    </div>
  </div>
</template>

<script>
export default {
  name: 'KoleColorPicker',
  props: {
    value: { type: String, default: '#2F54EB' },
    presets: {
      type: Array,
      default: function () {
        return ['#2F54EB','#1D39C4','#10239E','#CF1322','#8C5A00','#2E7D0A','#13C2C2','#722ED1',
                '#EB2F96','#8C5A00','#A0D911','#1890FF','#000000','#595959','#6E6E6E','#BFBFBF'];
      }
    }
  },
  data: function () { return { hex: this.value, alpha: 1 }; },
  computed: {
    preview: function () {
      var n = parseInt(this.hex.slice(1), 16);
      return 'rgba(' + ((n >> 16) & 255) + ',' + ((n >> 8) & 255) + ',' + (n & 255) + ',' + this.alpha + ')';
    }
  },
  methods: {
    setHex: function (v) { this.hex = v; this.emit(); },
    onHexInput: function (e) {
      var v = e.target.value;
      if (/^#[0-9a-fA-F]{6}$/.test(v)) { this.hex = v; this.emit(); }
    },
    setAlpha: function (a) { this.alpha = a; this.emit(); },
    emit: function () { this.$emit('change', { hex: this.hex, alpha: this.alpha }); }
  }
};
</script>

<style src="./ColorPicker.css"></style>
