Untitled

 avatar
unknown
plain_text
2 years ago
8.7 kB
8
Indexable
// ==UserScript==
// @name         Telus - Task Script
// @namespace    Scripts->Telus->Raters
// @version      2022.02.07.1
// @description  Do some super interesting stuff for Tig.
// @author       Snowey Ohioan, INC
// @include      https://www.raterhub.com/evaluation/rater/task/show*
// ==/UserScript==
/* jshint esnext: true */
/* jshint expr: true */ // Make JSHint shut up about short circuiting
/* eslint no-undef: 0*/

const domReady = cb=>{
    (document.readyState === "interactive" || document.readyState === "complete") ? cb() : document.addEventListener("DOMContentLoaded", cb);
};

// Set data to a valid value if it doesn't exist (not in a task)
if (typeof(data) == "undefined") data = 0;

// some custom styling for pages.
const styles = `
body { background-color: #c3c3c3;}
[data-helpme=obscured] {display: none !important;}
[data-helpme=visible] { display: inherit;}
#customInstructionButton { box-shadow: 0 8px 16px 0 rgba(0,0,0,0.2), 0 6px 20px 0 rgba(0,0,0,0.19); border-radius: 10px; background-color: rgba(197, 181, 197, 0.69); font-size: 11px; width: 100px; outline:none; z-index: 128; position:absolute; top:50px; right:1px;}
:focus {background: #EAFDF5 !important; color:black !important;}
.button:focus {background: #771D64 !important; color:black !important;}
.hidden-scrollbar::-webkit-scrollbar { visibility: hidden; }
textarea:focus { background: #EAFDF5 !important;}
input:focus { background: #EAFDF5 !important;}
input:blur { background: #FFEFFF !important;}`;

// Quick macro to check all radio buttons to no or whatever
const radioClicks = queryval => {  document.querySelectorAll(`input[type=radio][value="${queryval}"]`).forEach(i=>i.click()); }

// Same for checkboxes
const checkClicks = queryval => {  document.querySelectorAll(`input[type=checkbox][value="${queryval}"]`).forEach(i=>i.click()); }
const blankClicker = queryValArray => {
    queryValArray.forEach(query=> {
        document.querySelectorAll(query).forEach(element=> {
            if (! element.checked) element.click()
        });
    });
}
// A better version - takes an array of query to go through
const radClicker = queryValArray => {
    queryValArray.forEach(query=> {
        document.querySelectorAll(query).forEach(element=>element.click());
    });
}

// Function to modify the task header to include the templateID and projectID.
const fancyTaskHeader = (myPID = "ERR", myTID = "ERR", flipSign = "") => {
   const tidConf  = { "29603274":["#2c4ea2", "#085463"], "28991227":["#631708", "#584c0a"]};
   let debugContainer = document.createElement("LI");
   let ewokHead = document.getElementsByClassName('ewok-task-action-header'); // Gives us the main container DIV for the list items.

   if (myTID == "29603274" || myTID == "28991227" ) { // NM = 29603274, SxS = 28991227
      let flipCheck = (popped = populateTask.toString().match('"flipped":(true|false)') ) && popped[1] || 0;
      if (flipCheck) {
         flipSign = (flipCheck == "true") ? "⟸Я " : "🔮 ";
         document.querySelector('.ewok-rater-header').style.backgroundColor = ( flipCheck == "true") ? tidConf[myTID][1] : tidConf[myTID][0];
      }
   }

   debugContainer.innerHTML = `<span id="flipper">${flipSign}</span><span id="surfaceTemplate">Template: <b id="theTID">${myTID}</b></span>
    <span id="surfaceProject">Project: <b id="thePID">${myPID}</b></span>`;
   if (ewokHead.length) {
      ewokHead[0].appendChild(debugContainer);
   } else {
      document.body.appendChild(debugContainer);
   }

   // Let's stylize it a little bit.
   debugContainer.style.marginLeft = "4em";
   document.getElementById("theTID").style.color = "#ffd8a8";
   document.getElementById("thePID").style.color = "#8df1cc";

   if (flipSign) {
      let flippy = document.getElementById("flipper");
      flippy.style.color = "#ffc7c7";
      flippy.style.fontWeight = "900";
      flippy.style.fontSize= "medium";
   }

   // And hide our email while we're at it, to make sharing screenshots less privacy invasive.
   // ~~~~~~~ WARNING!!! ~~~~~~~~
   // comment this out before doing a Report Problem and including a screenshot!
   // ~~~~~~~ WARNING!!! ~~~~~~~~
   let emailElement = document.querySelector('.ewok-rater-header-user>li');
   if ( emailElement.innerText.includes("gmail.com")) emailElement.innerText = "Rater";
} // end of fancyTaskHeader

const strToNode = s=>{let template = document.createElement('template'); template.innerHTML = s; return template.content.firstChild;}

const addStyleSheet = styleConst=>{let head = document.head;let style = strToNode(`<style type='text/css' class='globalstyle'>${styleConst}</style>`); head.appendChild(style);}

const instructionButton = (a=[], siv=1, foc=0, arrayIsElements=0)=> {
   if (a.length) {
      const toggleHelpMe = el=>{el.dataset.helpme = ( el.dataset.helpme === 'obscured' ) ? 'visible' : 'obscured';}
      const i = ' Instructions';
      document.getElementsByTagName('body')[0].prepend(strToNode(`<button id="customInstructionButton" type="button">-${i}</button>`));
      b = document.getElementById('customInstructionButton');
      b.addEventListener('click', ev=>{ev.target.innerText = ((ev.target.innerText.slice(0,1) === '+')?'-':'+')+i;
         if (arrayIsElements) a.forEach(v=>toggleHelpMe(v));
         else a.forEach(v=>{els = document.querySelectorAll(v); els.forEach(el=>toggleHelpMe(el));});
      });
      b.click();
      b.tabIndex = -1; // Keep out of tab chain
      if (siv) b.scrollIntoView();
      if (foc) b.focus(); // Make sure we're always focused in frame.
   }
}
// Involved function to deal with the evidence/target type tasks (template 87385617)
   const process_target_evidence = ()=>{
   const magic_color = "#eef9f1";
   const magic_color_two = "#b1ebc1";
   const full_match_color = "#889EF6";
   const noevidence = "No evidence was cited.";
   const unsupported = document.querySelectorAll('[value="unsupported"]');
   const unsupported_comment = document.querySelectorAll('[name^="comment_attribution_sentence"]');
   const markwords = (elid, keyphrase, highlight="#A380EE") => {
      let evidence_text = elid.innerHTML;
      let re = new RegExp(`(?![^\\<\\>]*\\>)\\b${escapeRegExp(keyphrase)}[\\b]*`, 'gi');
      let marked = evidence_text.replace(re, `<mark style="background-color: ${highlight};">`+"$&"+'</mark>');
      elid.innerHTML = marked;
   }
   let evidences = document.querySelectorAll('tr>td>div>h5');
   let trows = document.querySelectorAll('table[id="editable-45"]>tbody>tr');
   evidences.forEach( (evidence,evidence_index)=> {
      toprow = trows[evidence_index+1]; // offset the header row with question a, question b
      evidence_container = evidence.parentElement;
      evidence_blocks = evidence_container.querySelectorAll('p');
      if (! evidence_blocks.length) { // no paragraphs, this should be no evidence
         if (evidence_container.innerText.includes(noevidence)) {
            unsupported[evidence_index].click();
            unsupported_comment[evidence_index].value = noevidence;
            toprow.style.backgroundColor = magic_color_two;
         }
      } else {
            let keyphrase = toprow.querySelector('mark')?.innerText.replace(/\s*\[[\d, ]*\]\s*/g, '').toLowerCase()
            evidence_blocks.forEach(eblock=>{
            let evidenceText = eblock.innerText;
            let phrase_idx = evidenceText.toLowerCase().indexOf(keyphrase);
            if (phrase_idx != -1) {
               let phrase_len = keyphrase.length;
               eblock.innerHTML = `${evidenceText.slice(0, phrase_idx)}<mark style="background-color: ${full_match_color};">
               ${evidenceText.slice(phrase_idx,phrase_idx+phrase_len)}</mark>${evidenceText.slice(phrase_idx+phrase_len)}`;
               toprow.style.backgroundColor = magic_color;
            } else {
               let phrases = keyphrase.match(/\b(\w+){4}[\b]*/g);
               let tossdupes = new Set(phrases);
               tossdupes.forEach(i=>markwords(eblock, i));
            }
         })
      }
   })
}

// Run this when page has completed loading
domReady(()=>{
    console.info(`${GM_info.script.name} ${GM_info.script.version}`);
    if (data) {
        addStyleSheet(styles);
        // Log task info to console
        console.info('Project: ', data.projectId, ' templateId: ', data.templateId);
        fancyTaskHeader(data.projectId, data.templateId);

        // force templateId to number
        let templateIdNumber = +data.templateId;
        // Checks the box named "nomoredupes".
function checkNoMoreDupesBox() {
  // Get the box named "nomoredupes".
  var box = document.querySelector('input[name="nomoredupes"]');

  // Check the box.
  box.checked = true;
}

// Run the function when the page loads.
Editor is loading...
Leave a Comment