Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * @fileoverview This file contains the Google Apps Script to handle the onEdit trigger.
- * The script changes the background colour of the cell where the custom function `=PREVIEWCOLOUR(input)` is used.
- * The background colour is based on a hex colour value found in another referenced cell or a directly provided hex value in quotes.
- * 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.
- *
- * The `PREVIEWCOLOUR` function serves as a placeholder and returns the hex code from the referenced cell or the input,
- * triggering the onEdit event but not directly changing the background colour.
- *
- * @author u/IAmMoonie
- * @version 1.4
- * @license MIT
- * @see {@link https://developers.google.com/apps-script/guides/triggers/events Google Sheets onEdit Event Documentation}
- * @see {@link https://developers.google.com/apps-script/reference/spreadsheet/range Google Apps Script Range Class}
- * @see {@link https://developers.google.com/apps-script/reference/spreadsheet/spreadsheet-app#flush Google Apps Script flush Documentation}
- * @see {@link https://developers.google.com/sheets/api/ Google Sheets API Documentation}
- */
- /**
- * Preview the colour based on the hex colour code in the referenced cell or a directly entered hex code in quotes.
- * This function does not directly change the background colour but acts as a placeholder for triggering onEdit logic.
- *
- * @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").
- * @return {string} The hex colour code as a string, or an empty string if the input is not valid.
- * @customfunction
- */
- function PREVIEWCOLOUR(input) {
- const sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
- if (typeof input === "string" && isValidHexColor_(input.trim())) {
- return input.trim();
- }
- let referencedCell;
- try {
- referencedCell = sheet.getRange(input);
- } catch (err) {
- return "";
- }
- const hexCode = referencedCell.getValue().trim();
- return isValidHexColor_(hexCode) ? hexCode : "";
- }
- /**
- * Handles the onEdit trigger to change the background colour of the cell where `=PREVIEWCOLOUR(input)` is used,
- * based on the hex colour in the referenced cell or direct string input.
- *
- * @param {GoogleAppsScript.Events.SheetsOnEdit} e The onEdit event object with properties `source` and `range`.
- * @returns {void} This function does not return a value.
- * @throws {Error} Throws an error if the referenced cell does not exist or if invalid input is provided.
- */
- function onEdit({ source, range }) {
- try {
- const sheet = source.getActiveSheet();
- const editedCell = range;
- const formula = editedCell.getFormula();
- if (!formula || !formula.startsWith("=PREVIEWCOLOUR(")) return;
- const input = formula.slice(15, -1).trim();
- let hexCode = input;
- if (!(input.startsWith('"') && input.endsWith('"'))) {
- let referencedCell;
- try {
- referencedCell = sheet.getRange(input);
- } catch (err) {
- console.info(
- `onEdit Catch Err: Invalid cell reference or input "${input}".`
- );
- throw new Error(`Invalid cell reference or input "${input}".`);
- }
- hexCode = referencedCell.getValue().trim();
- } else {
- hexCode = input.slice(1, -1);
- }
- const validationResult = getHexColorValidationMessage_(hexCode);
- if (validationResult === "valid") {
- editedCell.setBackground(hexCode).clearContent();
- SpreadsheetApp.flush();
- console.info(
- `Background set to ${hexCode} for cell ${editedCell.getA1Notation()}`
- );
- } else {
- editedCell.setValue(validationResult).setBackground("#FFFFFF");
- SpreadsheetApp.flush();
- console.warn(
- `Invalid hex code in cell ${
- referencedCell ? referencedCell.getA1Notation() : input
- }. ${validationResult}`
- );
- }
- } catch (error) {
- console.error(`Error in onEdit: ${error.message}`);
- SpreadsheetApp.getActiveSpreadsheet().toast(
- `Error: ${error.message}`,
- "Error",
- 5
- );
- }
- }
- /**
- * Validates if the provided hex colour code is valid and returns a validation message.
- *
- * @param {string} hexCode The hex colour code to validate.
- * @returns {string} "valid" if the hex code is valid, or an error message if invalid.
- */
- function getHexColorValidationMessage_(hexCode) {
- if (!hexCode.startsWith("#")) {
- return "Hex code must start with '#'.";
- }
- if (hexCode.length !== 7) {
- return "Hex code must be 7 characters long, including '#'.";
- }
- if (isNaN(parseInt(hexCode.slice(1), 16))) {
- return "Hex code contains invalid characters.";
- }
- return "valid";
- }
- /**
- * Checks if the provided hex colour code is valid.
- *
- * @param {string} hexCode The hex colour code to validate.
- * @returns {boolean} True if the hex code is valid, otherwise false.
- */
- function isValidHexColor_(hexCode) {
- const pattern = /^#[0-9A-F]{6}$/i;
- return pattern.test(hexCode);
- }
Advertisement
Add Comment
Please, Sign In to add comment