Advertisement
AlvinSeville7cf

InterpolateTextColor - Code.gs

Aug 6th, 2021
251
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function hexToRgb(hex) {
  2.   var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
  3.   return result ? {
  4.     r: parseInt(result[1], 16),
  5.     g: parseInt(result[2], 16),
  6.     b: parseInt(result[3], 16)
  7.   } : null;
  8. }
  9.  
  10. function rgbToHex(color) {
  11.   return "#" + ((1 << 24) + (Math.trunc(color.r) << 16) + (Math.trunc(color.g) << 8) + Math.trunc(color.b)).toString(16).slice(1);
  12. }
  13.  
  14. function interpolate(from, to, influence) {
  15.   if (influence < 0)
  16.     influence = 0;
  17.   if (influence > 1)
  18.     influence = 1;
  19.  
  20.   return from + (to - from) * influence;
  21. }
  22.  
  23. function interpolateRgb(from, to, influence) {
  24.   if (!from || !to)
  25.     return null;
  26.  
  27.   return {
  28.     r: interpolate(from.r, to.r, influence),
  29.     g: interpolate(from.g, to.g, influence),
  30.     b: interpolate(from.b, to.b, influence)
  31.   }
  32. }
  33.  
  34. function rgbToString(color) {
  35.   return `(${color.r}, ${color.g}, ${color.b})`;
  36. }
  37.  
  38. function colorizeSelection(from, to) {
  39.   let rgbFrom = hexToRgb(from);
  40.   let rgbTo = hexToRgb(to);
  41.  
  42.   let selection = DocumentApp.getActiveDocument().getSelection();
  43.  
  44.   if (selection) {
  45.     var elements = selection.getRangeElements();
  46.     for (var i = 0; i < elements.length; i++) {
  47.       var element = elements[i];
  48.  
  49.       if (element.getElement().editAsText) {
  50.         var text = element.getElement().editAsText();
  51.  
  52.         let fromPosition = element.getStartOffset();
  53.         let toPosition = element.getEndOffsetInclusive();
  54.         let difference = toPosition - fromPosition + 1;
  55.  
  56.         for (var j = fromPosition; j <= toPosition; j++) {
  57.           let color = rgbToHex(interpolateRgb(rgbFrom, rgbTo, (j - fromPosition) / difference));
  58.           text.setForegroundColor(j, j, color);
  59.         }
  60.       }
  61.     }
  62.   }
  63. }
  64.  
  65. function openSidebar() {
  66.   DocumentApp.getUi().showSidebar(HtmlService.createHtmlOutputFromFile('Index'));
  67. }
  68.  
  69. function onOpen() {
  70.   DocumentApp.getUi().createMenu("Colorize").addItem("Run", "openSidebar").addToUi();
  71. }
  72.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement