<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 setup>
import { ref, computed } from 'vue';
const props = defineProps({
  value: { type: String, default: '#2F54EB' },
  presets: {
    type: Array,
    default: () => ['#2F54EB','#1D39C4','#10239E','#CF1322','#8C5A00','#2E7D0A','#13C2C2','#722ED1',
                   '#EB2F96','#8C5A00','#A0D911','#1890FF','#000000','#595959','#6E6E6E','#BFBFBF']
  }
});
const emit = defineEmits(['change']);
const hex = ref(props.value);
const alpha = ref(1);
const preview = computed(() => {
  const n = parseInt(hex.value.slice(1), 16);
  return `rgba(${(n >> 16) & 255},${(n >> 8) & 255},${n & 255},${alpha.value})`;
});
function setHex(v) { hex.value = v; emitChange(); }
function onHexInput(e) {
  const v = e.target.value;
  if (/^#[0-9a-fA-F]{6}$/.test(v)) { hex.value = v; emitChange(); }
}
function setAlpha(a) { alpha.value = a; emitChange(); }
function emitChange() { emit('change', { hex: hex.value, alpha: alpha.value }); }
</script>

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