diff --git a/apps/static/js/home/index.js b/apps/static/js/home/index.js index acf55ed..8e00c97 100644 --- a/apps/static/js/home/index.js +++ b/apps/static/js/home/index.js @@ -86,11 +86,30 @@ $(".colour-control-text").on("change", function() { }); function updateColourInput(id, hexString) { - hexString = hexString.toUpperCase(); + hexString = normaliseHexString(hexString.toUpperCase()); $(`#${id} .colour-picker`).val(hexString); $(`#${id} .colour-text`).val(hexString); } +function getColourInputVal(id, includeHashtag=true) { + const hexString = $(`#${id}Text`).val(); + return normaliseHexString(hexString, includeHashtag); +} + +function normaliseHexString(hexString, includeHashtag=true) { + console.debug(`normalising hex string '${hexString}' include hashtag '${includeHashtag}'`); + + // Remove any non-hex characters (e.g., additional hashtags) + hexString = hexString.replace(/[^A-F0-9]/gi, ''); + + // Ensure the hex string has a valid length of either 3, 6, or 8 characters + if (![3, 6, 8].includes(hexString.length)) { + throw new Error(`Invalid hex string length. Must be 3, 6, or 8 characters. hexString=${hexString}`); + } + + return includeHashtag ? `#${hexString}` : hexString; +} + $(document).ready(function() { $(".colour-input").each(function() { let id = $(this).attr("data-id")