summaryrefslogtreecommitdiffstats
path: root/web_src/js/features/colorpicker.js
blob: 6d00d908c967822bea44a52109a5a0d5b8f78d27 (plain)
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
import {createTippy} from '../modules/tippy.js';

export async function initColorPickers() {
  const els = document.getElementsByClassName('js-color-picker-input');
  if (!els.length) return;

  await Promise.all([
    import(/* webpackChunkName: "colorpicker" */'vanilla-colorful/hex-color-picker.js'),
    import(/* webpackChunkName: "colorpicker" */'../../css/features/colorpicker.css'),
  ]);

  for (const el of els) {
    initPicker(el);
  }
}

function updateSquare(el, newValue) {
  el.style.color = /#[0-9a-f]{6}/i.test(newValue) ? newValue : 'transparent';
}

function updatePicker(el, newValue) {
  el.setAttribute('color', newValue);
}

function initPicker(el) {
  const input = el.querySelector('input');

  const square = document.createElement('div');
  square.classList.add('preview-square');
  updateSquare(square, input.value);
  el.append(square);

  const picker = document.createElement('hex-color-picker');
  picker.addEventListener('color-changed', (e) => {
    input.value = e.detail.value;
    input.focus();
    updateSquare(square, e.detail.value);
  });

  input.addEventListener('input', (e) => {
    updateSquare(square, e.target.value);
    updatePicker(picker, e.target.value);
  });

  createTippy(input, {
    trigger: 'focus click',
    theme: 'bare',
    hideOnClick: true,
    content: picker,
    placement: 'bottom-start',
    interactive: true,
    onShow() {
      updatePicker(picker, input.value);
    },
  });

  // init precolors
  for (const colorEl of el.querySelectorAll('.precolors .color')) {
    colorEl.addEventListener('click', (e) => {
      const newValue = e.target.getAttribute('data-color-hex');
      input.value = newValue;
      input.dispatchEvent(new Event('input', {bubbles: true}));
      updateSquare(square, newValue);
    });
  }
}