IAmMoonie

Update cell background colour to reflect Hex Colour

Oct 3rd, 2024 (edited)
154
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
JavaScript 5.10 KB | Source Code | 0 0
  1. /**
  2.  * @fileoverview This file contains the Google Apps Script to handle the onEdit trigger.
  3.  * The script changes the background colour of the cell where the custom function `=PREVIEWCOLOUR(input)` is used.
  4.  * The background colour is based on a hex colour value found in another referenced cell or a directly provided hex value in quotes.
  5.  * If the hex code is invalid or not passed as a string in quotes, the background colour defaults to white, and the cell will display an appropriate error message.
  6.  *
  7.  * The `PREVIEWCOLOUR` function serves as a placeholder and returns the hex code from the referenced cell or the input,
  8.  * triggering the onEdit event but not directly changing the background colour.
  9.  *
  10.  * @author u/IAmMoonie
  11.  * @version 1.4
  12.  * @license MIT
  13.  * @see {@link https://developers.google.com/apps-script/guides/triggers/events Google Sheets onEdit Event Documentation}
  14.  * @see {@link https://developers.google.com/apps-script/reference/spreadsheet/range Google Apps Script Range Class}
  15.  * @see {@link https://developers.google.com/apps-script/reference/spreadsheet/spreadsheet-app#flush Google Apps Script flush Documentation}
  16.  * @see {@link https://developers.google.com/sheets/api/ Google Sheets API Documentation}
  17.  */
  18.  
  19. /**
  20.  * Preview the colour based on the hex colour code in the referenced cell or a directly entered hex code in quotes.
  21.  * This function does not directly change the background colour but acts as a placeholder for triggering onEdit logic.
  22.  *
  23.  * @param {string} input A reference to a cell that contains a valid hex colour code (e.g., A1) or a direct hex colour code string (e.g., "#FF0000").
  24.  * @return {string} The hex colour code as a string, or an empty string if the input is not valid.
  25.  * @customfunction
  26.  */
  27. function PREVIEWCOLOUR(input) {
  28.   const sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  29.   if (typeof input === "string" && isValidHexColor_(input.trim())) {
  30.     return input.trim();
  31.   }
  32.   let referencedCell;
  33.   try {
  34.     referencedCell = sheet.getRange(input);
  35.   } catch (err) {
  36.     return "";
  37.   }
  38.   const hexCode = referencedCell.getValue().trim();
  39.   return isValidHexColor_(hexCode) ? hexCode : "";
  40. }
  41.  
  42. /**
  43.  * Handles the onEdit trigger to change the background colour of the cell where `=PREVIEWCOLOUR(input)` is used,
  44.  * based on the hex colour in the referenced cell or direct string input.
  45.  *
  46.  * @param {GoogleAppsScript.Events.SheetsOnEdit} e The onEdit event object with properties `source` and `range`.
  47.  * @returns {void} This function does not return a value.
  48.  * @throws {Error} Throws an error if the referenced cell does not exist or if invalid input is provided.
  49.  */
  50. function onEdit({ source, range }) {
  51.   try {
  52.     const sheet = source.getActiveSheet();
  53.     const editedCell = range;
  54.     const formula = editedCell.getFormula();
  55.     if (!formula || !formula.startsWith("=PREVIEWCOLOUR(")) return;
  56.     const input = formula.slice(15, -1).trim();
  57.     let hexCode = input;
  58.     if (!(input.startsWith('"') && input.endsWith('"'))) {
  59.       let referencedCell;
  60.       try {
  61.         referencedCell = sheet.getRange(input);
  62.       } catch (err) {
  63.         console.info(
  64.           `onEdit Catch Err: Invalid cell reference or input "${input}".`
  65.         );
  66.         throw new Error(`Invalid cell reference or input "${input}".`);
  67.       }
  68.       hexCode = referencedCell.getValue().trim();
  69.     } else {
  70.       hexCode = input.slice(1, -1);
  71.     }
  72.     const validationResult = getHexColorValidationMessage_(hexCode);
  73.     if (validationResult === "valid") {
  74.       editedCell.setBackground(hexCode).clearContent();
  75.       SpreadsheetApp.flush();
  76.       console.info(
  77.         `Background set to ${hexCode} for cell ${editedCell.getA1Notation()}`
  78.       );
  79.     } else {
  80.       editedCell.setValue(validationResult).setBackground("#FFFFFF");
  81.       SpreadsheetApp.flush();
  82.       console.warn(
  83.         `Invalid hex code in cell ${
  84.           referencedCell ? referencedCell.getA1Notation() : input
  85.         }. ${validationResult}`
  86.       );
  87.     }
  88.   } catch (error) {
  89.     console.error(`Error in onEdit: ${error.message}`);
  90.     SpreadsheetApp.getActiveSpreadsheet().toast(
  91.       `Error: ${error.message}`,
  92.       "Error",
  93.       5
  94.     );
  95.   }
  96. }
  97.  
  98. /**
  99.  * Validates if the provided hex colour code is valid and returns a validation message.
  100.  *
  101.  * @param {string} hexCode The hex colour code to validate.
  102.  * @returns {string} "valid" if the hex code is valid, or an error message if invalid.
  103.  */
  104. function getHexColorValidationMessage_(hexCode) {
  105.   if (!hexCode.startsWith("#")) {
  106.     return "Hex code must start with '#'.";
  107.   }
  108.   if (hexCode.length !== 7) {
  109.     return "Hex code must be 7 characters long, including '#'.";
  110.   }
  111.   if (isNaN(parseInt(hexCode.slice(1), 16))) {
  112.     return "Hex code contains invalid characters.";
  113.   }
  114.   return "valid";
  115. }
  116.  
  117. /**
  118.  * Checks if the provided hex colour code is valid.
  119.  *
  120.  * @param {string} hexCode The hex colour code to validate.
  121.  * @returns {boolean} True if the hex code is valid, otherwise false.
  122.  */
  123. function isValidHexColor_(hexCode) {
  124.   const pattern = /^#[0-9A-F]{6}$/i;
  125.   return pattern.test(hexCode);
  126. }
  127.  
Advertisement
Add Comment
Please, Sign In to add comment