leobm / Deepl SaveTrans

/**
  The MIT License (MIT)

  Copyright (c) 2023 Jan-Felix Wittmann

  Permission is hereby granted, free of charge, to any person obtaining a copy of
  this software and associated documentation files (the "Software"), to deal in
  the Software without restriction, including without limitation the rights to
  use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
  the Software, and to permit persons to whom the Software is furnished to do so,
  subject to the following conditions:

  The above copyright notice and this permission notice shall be included in all
  copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
  FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
  COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
  IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
**/
// ==UserScript==
// @id           DeeplSaveTrans
// @name         Deepl SaveTrans
// @description  Have you also had the problem that when you have entered a long text in DeepL Trans or Write and then accidentally closed the tab? Then the whole text was gone and you had to rewrite everything again. Now the input is saved in the localstorage of the browser. If you close the browser and open it again, the old text will appear in the input window.
// @version      1.0
// @author       Jan-Felix Wittmann <jfwittmann7@gmail.com>
// @copyright    2023, leobm (https://openuserjs.org/users/leobm)
// @license      MIT
// @match        https://www.deepl.com/*
// @require      https://openuserjs.org/src/libs/sizzle/GM_config.js
// @icon         https://www.google.com/s2/favicons?domain=deepl.com
// @grant       GM_getValue
// @grant       GM_setValue
// @run-at      document-start
// ==/UserScript==

(function (d, w) {
  'use strict';

  d.addEventListener("keydown", (e) => {
    let key = e.keyCode || e.charCode;

    if (key == 8 || key == 46) {
      GM.getValue("___translator-source-input").then((loadText) => {
        let foundNodes = query(d, '[data-testid="translator-source-input"] .sentence_highlight');
        let selectedTexts = [];
        getText(foundNodes[0], selectedTexts);
        if (selectedTexts.join('') == loadText) {
          GM.setValue("___translator-source-input", '');
        }
      });
    }

  });

  watchForQuerySelector(d, '#translator-source-clear-button', ({
    foundNodes,
    stop,
    restart
  }) => {
    if (!foundNodes[0].__clickEvent) {
      foundNodes[0].addEventListener("click", (e) => {
        GM.setValue("___translator-source-input", '');
      });
      foundNodes[0].__clickEvent = true;
    }
  });

  watchForQuerySelector(d, '[data-testid="translator-source-input"] div', ({
    foundNodes,
    stop,
    restart
  }) => {

    GM.getValue("___translator-source-input").then((loadText) => {
      let allTexts = [];
      getText(foundNodes[0], allTexts);
      let saveText = allTexts.join('');
      if (saveText != '') {
        GM.setValue("___translator-source-input", saveText);
      }
      else {
        if (loadText != '' && loadText != 'undefined') {
          foundNodes[0].innerHTML = loadText;
        }
      }
    });
  });

  function getText(node, accumulator) {
    if (node.nodeType === 3) // 3 == text node
      accumulator.push(node.nodeValue)
    else
      for (let child of node.childNodes)
        getText(child, accumulator)
  }

  function watchForQuerySelector(targetNode, selector, callback, options) {
    let obsCallback = (obs) => {
      let foundNodes = query(targetNode, selector);
      if (foundNodes.length > 0) {
        callback({
          foundNodes,
          ...obs
        });
      }
    };
    observeNode(targetNode, obsCallback, options);
  }

  function observeNode(targetNode, callback, options) {
    let meOptions = options || {
      childList: true,
      subtree: true,
    };
    let observer = new MutationObserver((mutations, me) => {
      let obs = {
        restart: () => me.observe(targetNode, meOptions),
        stop: () => me.disconnect(),
        get mutations() {
          return mutations;
        },
      };
      callback(obs);
    });
    observer.observe(targetNode, meOptions);
    return observer;
  }

  function query(startNode, selector) {
    try {
      var nodes = Array.from(startNode.querySelectorAll(selector));
      return nodes;
    }
    catch (e) {}
    return [];
  }

})(document, window);