diff options
Diffstat (limited to 'web_src/js/features/colorpicker.ts')
-rw-r--r-- | web_src/js/features/colorpicker.ts | 36 |
1 files changed, 22 insertions, 14 deletions
diff --git a/web_src/js/features/colorpicker.ts b/web_src/js/features/colorpicker.ts index b99e2f8c45..66d1fcb72a 100644 --- a/web_src/js/features/colorpicker.ts +++ b/web_src/js/features/colorpicker.ts @@ -1,18 +1,19 @@ import {createTippy} from '../modules/tippy.ts'; import type {DOMEvent} from '../utils/dom.ts'; +import {registerGlobalInitFunc} from '../modules/observer.ts'; export async function initColorPickers() { - const els = document.querySelectorAll<HTMLElement>('.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) { + let imported = false; + registerGlobalInitFunc('initColorPicker', async (el) => { + if (!imported) { + await Promise.all([ + import(/* webpackChunkName: "colorpicker" */'vanilla-colorful/hex-color-picker.js'), + import(/* webpackChunkName: "colorpicker" */'../../css/features/colorpicker.css'), + ]); + imported = true; + } initPicker(el); - } + }); } function updateSquare(el: HTMLElement, newValue: string): void { @@ -55,13 +56,20 @@ function initPicker(el: HTMLElement): void { }, }); - // init precolors + // init random color & precolors + const setSelectedColor = (color: string) => { + input.value = color; + input.dispatchEvent(new Event('input', {bubbles: true})); + updateSquare(square, color); + }; + el.querySelector('.generate-random-color').addEventListener('click', () => { + const newValue = `#${Math.floor(Math.random() * 0xFFFFFF).toString(16).padStart(6, '0')}`; + setSelectedColor(newValue); + }); for (const colorEl of el.querySelectorAll<HTMLElement>('.precolors .color')) { colorEl.addEventListener('click', (e: DOMEvent<MouseEvent, HTMLAnchorElement>) => { const newValue = e.target.getAttribute('data-color-hex'); - input.value = newValue; - input.dispatchEvent(new Event('input', {bubbles: true})); - updateSquare(square, newValue); + setSelectedColor(newValue); }); } } |