leobm / Mastodon DeepL translate button

/**
  The MIT License (MIT)

  Copyright (c) 2022 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==
// @name         Mastodon DeepL translate button
// @description  This Greasemonkey script displays a translation button below a toot if the toot contains text that is not in your native language or the other languages you set in your settings.
// @namespace    https://openuserjs.org/users/leobm
// @version      1.4
// @author       Jan-Felix Wittmann <jfwittmann7@gmail.com>
// @copyright    2022, leobm (https://openuserjs.org/users/leobm)
// @license      MIT
// @match        https://*/web/*
// @require      https://cdn.jsdelivr.net/gh/richtr/guessLanguage.js/lib/_languageData.js
// @require      https://cdn.jsdelivr.net/gh/richtr/guessLanguage.js/lib/guessLanguage.js
// @require	     https://openuserjs.org/src/libs/sizzle/GM_config.js
// @grant        GM_getValue
// @grant        GM_setValue
// @icon         https://www.google.com/s2/favicons?domain=mastodon.social
// @updateURL    https://openuserjs.org/meta/leobm/Mastodon_DeepL_translate_button.meta.js
// @downloadURL  https://openuserjs.org/install/leobm/Mastodon_DeepL_translate_button.user.js
// ==/UserScript==
/*jshint esversion: 9 */
(function(d, w) {

    const init = () => {
        // Are we in the mastodon web application?
        if (!$(d, '#mastodon')) {
            return;
        }

        const languages = Object.keys(_languageData);
        const config = new GM_configStruct({
            'id': 'mastodon_deepl_translate',
            'title': 'Translation Settings',
            'fields': {
                'your_native_lang': {
                    'label': 'Your Primary Native Language ',
                    'type': 'select',
                    'options': languages,
                    'default': navigator.language
                },
                'your_lang2': {
                    'label': 'Your Second Language',
                    'type': 'select',
                    'options': ['', ...languages],
                    'default': ''
                },
                'your_lang3': {
                    'label': 'Your Third Language',
                    'type': 'select',
                    'options': ['', ...languages],
                    'default': ''
                },
                'deepl_auth_key': {
                    'label': 'DeepL Auth Key',
                    'type': 'text',
                    'default': ''
                }
            },
            'events': {
                save() {
                    config.close(true);
                    w.location.reload();
                },
                close() {},
                open() {
                    this.frame.style.height = '40%';
                    this.frame.style.width = '50%';
                    this.frame.style.marginTop = '-10%';
                    this.center();
                },
                reset() {
                    w.location.reload();
                }
            }
        });

        const stripUsers = (text) => text.replace(/(?<=^|(?<=[^a-zA-Z0-9-_\.]))@([A-Za-z]+[A-Za-z0-9-_]+)(@([a-zA-Z0-9](?:(?:[a-zA-Z0-9-]*|(?<!-)\.(?![-.]))*[a-zA-Z0-9]+)?))?/, '');
        let yourNativeLang = config.get('your_native_lang');
        let yourLang2 = config.get('your_lang2');
        let yourLang3 = config.get('your_lang3');

        let deeplAuthKey = config.get('deepl_auth_key');
        const notYourLang = (detectedLang) => (yourLang) => detectedLang != 'unknown' && detectedLang != yourLang;
        initSlideoutMenu(config);

        if (!deeplAuthKey || !yourNativeLang) {
            config.open();
            return;
        }

        watchForQuerySelector(d, '.status__content__text', ({
            foundNodes,
            stop,
            restart
        }) => {
            foundNodes.forEach(node => {
                if (!node.getAttribute('data-lang')) {

                    let html = node.innerHTML;
                    html = html.replace(/<br\s*[\/]?>/gi, "\n");
                    html = html.replace(/<\/p>/gi, "\n\n");
                    let text = stripHtml(html);
                    text = stripUsers(text);
                    guessLanguage.detect(text, (lang) => {
                        node.setAttribute("data-lang", lang);
                        let showTransBtn = [yourNativeLang, yourLang2, yourLang3].every(notYourLang(lang));
                        if (showTransBtn) {
                            let transBtn = d.createElement('button');
                            transBtn.setAttribute('class', 'status__content__spoiler-link');
                            transBtn.textContent = (yourNativeLang == 'de') ? 'Übersetzen' : 'Translate';
                            node.appendChild(transBtn);
                            transBtn.addEventListener("click", (evt) => {
                                fetch(`https://api-free.deepl.com/v2/translate?text=${encodeURIComponent(text)}&target_lang=${yourNativeLang}&auth_key=${deeplAuthKey}`)
                                    .then((res) => res.json())
                                    .then((data) => {
                                        const pre = d.createElement('pre');
                                        pre.setAttribute('style', `
                                          white-space: pre-wrap;
                                          white-space: -moz-pre-wrap;
                                          white-space: -pre-wrap;
                                          white-space: -o-pre-wrap;
                                          word-wrap: break-word;`);
                                        pre.textContent = data.translations[0].text;
                                        node.appendChild(pre);
                                    });
                            });
                        }
                    });
                }
            });
        });
    };


    function initSlideoutMenu(config) {
        let slideoutOpen = false;
        let slideOutEl = $(d, '#deepl_slideout');
        if (!slideOutEl) {
            let tmpl = d.createElement('div');
            tmpl.innerHTML = `
                <div id="deepl_slideout">
                  <div class="deepl_slideout__sticky-button">
                    <div class="deepl_slideout__hand">
                        <svg  width="16" height="16" fill="currentColor" class="bi bi-plus-circle-fill" viewBox="0 0 16 16">
                            <path d="M16 8A8 8 0 1 1 0 8a8 8 0 0 1 16 0zM8.5 4.5a.5.5 0 0 0-1 0v3h-3a.5.5 0 0 0 0 1h3v3a.5.5 0 0 0 1 0v-3h3a.5.5 0 0 0 0-1h-3v-3z"/>
                        </svg>
                        <svg width="0" height="0" fill="currentColor" class="bi bi-dash-circle-fill" viewBox="0 0 16 16">
                            <path d="M16 8A8 8 0 1 1 0 8a8 8 0 0 1 16 0zM4.5 7.5a.5.5 0 0 0 0 1h7a.5.5 0 0 0 0-1h-7z"/>
                        </svg>
                    </div>
                    <ul class="deepl_slideout__settings">
                    </ul>
                  </div>
                </div>`;

            slideOutEl = $(tmpl, '#deepl_slideout');
            slideOutEl.style.cssText = `
               position: fixed;
               right: 0;
               top: 0;
               z-index:1000;
            `;

            $(slideOutEl, '.deepl_slideout__sticky-button').style.cssText = `
                background: indigo;
                margin-right: -130px;
                transition: margin 0.2s ease-out;
                position: relative;
                width: 165px;
			    display:flex;
                padding: 4px 0;

            `;
            $(slideOutEl, '.deepl_slideout__hand').style.cssText = `
                color: white;
                cursor: pointer;
                display: flex;
                width: 20px;
                padding: 2px 10px;
            `;
            let iconBtn = $(slideOutEl, '.deepl_slideout__sticky-button');

            let openSlide = () => {
                $(iconBtn, '.bi-plus-circle-fill').style = 'width:0; height:0;';
                $(iconBtn, '.bi-dash-circle-fill').style = 'width:16px; height:16px;';

                iconBtn.style.marginRight = '0';
                slideoutOpen = true;
            };
            let closeSlide = () => {
                $(iconBtn, '.bi-plus-circle-fill').style = 'width:16px; height:16px;';
                $(iconBtn, '.bi-dash-circle-fill').style = 'width:0; height:0;';
                iconBtn.style.marginRight = '-130px';
                slideoutOpen = false;
            };
            $(slideOutEl, '.deepl_slideout__hand').addEventListener("click", (evt) => {
                evt.stopPropagation();
                (slideoutOpen) ? closeSlide(): openSlide();
            }, false);
            d.addEventListener("click", (evt) => {
                if (slideoutOpen && !slideOutEl.contains(evt.target)) {
                    closeSlide()
                }
            }, true);

            d.body.appendChild(slideOutEl)
        }

        let tmpl = d.createElement('div');
        tmpl.innerHTML = `<li><a href="#" id="deepl_slideout__trans_settings_link">${config.title}</a></li>`;
        let ul = $(slideOutEl, '.deepl_slideout__settings');
        ul.appendChild(tmpl.firstChild);
        ul.style.cssText = `padding:0; margin:0; list-style:none; line-height:1rem;`;
        $(slideOutEl, '#deepl_slideout__trans_settings_link').style.cssText = `
          color: white;
          display: block;
      `;
        $(slideOutEl, '#deepl_slideout__trans_settings_link').addEventListener("click", (evt) => {
            config.open();
            evt.stopPropagation();
        }, false);
    }


    //**********************************************************************************
    // DOM Utilities
    //**********************************************************************************

    const $ = (el, sel) => el.querySelector(sel);
    const $$ = (startEl, sel) => query(startEl, sel);

    function stripHtml(html) {
        let doc = new DOMParser().parseFromString(html, 'text/html');
        return doc.body.textContent || "";
    }

    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 [];
    }

    w.setTimeout(init, 1000);
})(document, window);