Skip to content
Snippets Groups Projects

allow 3-character hexadecimal color inputs

Files

@@ -27,6 +27,31 @@
@@ -27,6 +27,31 @@
Drupal.announce(announcement);
Drupal.announce(announcement);
}
}
 
/**
 
* Formats hexcode to full 6-character string for HTMLColorInput.
 
*
 
* @param {string} hex The hex code input.
 
* @returns {string} The same hex code, formatted.
 
*/
 
function formatHex(hex) {
 
// Temporarily remove hash
 
if (hex.startsWith('#')) {
 
hex = hex.substring(1);
 
}
 
 
// Convert three-value to six-value syntax.
 
if (hex.length === 3) {
 
hex = hex
 
.split('')
 
.flatMap((character) => [character, character])
 
.join('');
 
}
 
 
hex = `#${hex}`;
 
 
return hex;
 
}
 
/**
/**
* `input` event callback to keep text & color inputs in sync.
* `input` event callback to keep text & color inputs in sync.
*
*
@@ -34,10 +59,16 @@
@@ -34,10 +59,16 @@
* @param {HTMLElement} inputToSync input element to synchronize
* @param {HTMLElement} inputToSync input element to synchronize
*/
*/
function synchronizeInputs(changedInput, inputToSync) {
function synchronizeInputs(changedInput, inputToSync) {
inputToSync.value = changedInput.value;
inputToSync.value = formatHex(changedInput.value);
changedInput.setAttribute('data-olivero-custom-color', changedInput.value);
changedInput.setAttribute(
inputToSync.setAttribute('data-olivero-custom-color', changedInput.value);
'data-olivero-custom-color',
 
formatHex(changedInput.value),
 
);
 
inputToSync.setAttribute(
 
'data-olivero-custom-color',
 
formatHex(changedInput.value),
 
);
const colorSchemeSelect = document.querySelector(
const colorSchemeSelect = document.querySelector(
'[data-drupal-selector="edit-color-scheme"]',
'[data-drupal-selector="edit-color-scheme"]',
@@ -130,7 +161,7 @@
@@ -130,7 +161,7 @@
'form-element--type-color',
'form-element--type-color',
'form-element--api-color',
'form-element--api-color',
);
);
colorInput.value = textInput.value;
colorInput.value = formatHex(textInput.value);
colorInput.setAttribute('name', `${textInput.name}_visual`);
colorInput.setAttribute('name', `${textInput.name}_visual`);
colorInput.setAttribute(
colorInput.setAttribute(
'data-olivero-custom-color',
'data-olivero-custom-color',
Loading