Files
breadcrumb-the-shire/web/js/components/app-color-default-toggle.js

69 lines
2.2 KiB
JavaScript
Raw Normal View History

/**
* Toggles color input between custom value and default/inherited color.
*/
import { warnOnce } from '../core/app-dom.js';
import { createConditionalToggleInit } from '../core/app-conditional-controls.js';
2026-02-11 19:28:12 +01:00
const syncToggle = (toggle, scope) => {
2026-02-04 23:31:53 +01:00
const targetSelector = toggle.dataset.colorTarget || '';
if (!targetSelector) {
2026-02-11 19:28:12 +01:00
warnOnce('UI_EL_MISSING', 'Missing data-color-target', { module: 'color-default-toggle' });
2026-02-04 23:31:53 +01:00
return;
}
const target = scope.querySelector(targetSelector);
if (!(target instanceof HTMLInputElement)) {
2026-02-11 19:28:12 +01:00
warnOnce('UI_EL_MISSING', `Missing color target: ${targetSelector}`, { module: 'color-default-toggle' });
2026-02-04 23:31:53 +01:00
return;
}
const defaultValue = toggle.dataset.colorDefault || '#2fa4a4';
if (toggle.checked) {
if (!target.dataset.customValue) {
target.dataset.customValue = target.value;
}
target.value = defaultValue;
target.setAttribute('disabled', 'disabled');
} else {
target.removeAttribute('disabled');
if (target.dataset.customValue) {
target.value = target.dataset.customValue;
}
}
};
const initRoot = (toggle) => {
if (!(toggle instanceof HTMLInputElement)) {
return null;
2026-02-11 19:28:12 +01:00
}
2026-02-04 23:31:53 +01:00
const scope = document;
const targetSelector = toggle.dataset.colorTarget || '';
const target = targetSelector ? scope.querySelector(targetSelector) : null;
if (targetSelector && !target) {
warnOnce('UI_EL_MISSING', `Missing color target: ${targetSelector}`, { module: 'color-default-toggle' });
}
const onToggleChange = () => syncToggle(toggle, scope);
toggle.addEventListener('change', onToggleChange);
const cleanups = [() => toggle.removeEventListener('change', onToggleChange)];
if (target instanceof HTMLInputElement) {
const onTargetInput = () => {
if (toggle.checked) {
toggle.checked = false;
target.removeAttribute('disabled');
}
};
target.addEventListener('input', onTargetInput);
cleanups.push(() => target.removeEventListener('input', onTargetInput));
}
syncToggle(toggle, scope);
return () => cleanups.forEach((fn) => fn());
};
2026-02-04 23:31:53 +01:00
export const initColorDefaultToggle = createConditionalToggleInit({
rootSelector: '[data-color-default-toggle]',
boundKey: 'colorDefaultToggleBound',
initRoot,
});