From e30f431dc359c01d682181738dd000ea2f6b3d53 Mon Sep 17 00:00:00 2001 From: Corban-Lee Jones Date: Fri, 16 Aug 2024 18:45:30 +0100 Subject: [PATCH] hex string normalisation and get value from field --- apps/static/js/home/index.js | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) 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")