Twitter image viewing enhancement

Make Twitter photo viewing more humane

Fra og med 11.09.2020. Se den nyeste version.

// ==UserScript==
// @name         Twitter image viewing enhancement
// @name:zh-CN   Twitter 图片查看增强
// @name:zh-TW   Twitter 圖像查看增強
// @icon         https://twitter.com/favicon.ico
// @namespace    https://moe.best/
// @version      0.6.3
// @description        Make Twitter photo viewing more humane
// @description:zh-CN  让推特图片浏览更加人性化
// @description:zh-TW  讓 Twitter 照片瀏覽更人性化
// @author       Jindai Kirin
// @include      https://twitter.com/*
// @license      MIT
// @grant        GM_getValue
// @grant        GM_setValue
// @grant        GM_registerMenuCommand
// @grant        GM_openInTab
// @grant        GM_addStyle
// @grant        GM_getResourceText
// @run-at       document-end
// @require      https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.min.js
// @require      https://cdn.jsdelivr.net/npm/[email protected]/jquery.mousewheel.min.js
// @require      https://cdn.jsdelivr.net/npm/[email protected]/dist/snackbar.min.js
// @resource     snackbarcss https://cdn.jsdelivr.net/npm/[email protected]/dist/snackbar.min.css
// ==/UserScript==

// 注意 NOTICE
// v0.5.1 开始包含一些重大更新,如果你的推特界面语言不是简体中文/繁体中文/英语/日语,请访问脚本主页以了解这一变更,否则你可能无法正常使用。
// There are some significant changes in v0.5.1, please visit the homepage of this script for more information if your twitter display language is not one of English, Japanese, Simplified Chinese, Traditional Chinese.

(function () {
    'use strict';
    GM_addStyle(GM_getResourceText('snackbarcss'));
    GM_addStyle('.tive-snackbar>p{line-height:1.2em!important}');

    const safelyParseJSON = str => {
        try {
            return JSON.parse(str);
        } catch (error) {}
    };

    const defaultLabelsByLang = {
        zh: { close: '关闭', prev: '上一张幻灯片', next: '下一张幻灯片' },
        'zh-Hant': { close: '關閉', prev: '上一張投影片', next: '下一張投影片' },
        en: { close: 'Close', prev: 'Previous slide', next: 'Next slide' },
        ja: { close: '閉じる', prev: '前のスライド', next: '次のスライド' },
        default: { close: 'Close', prev: 'Previous slide', next: 'Next slide' },
    };

    const defaultLabels = defaultLabelsByLang[$('html').attr('lang')] || defaultLabelsByLang.default;
    const labels = (() => {
        const setting = GM_getValue('labels', '');
        return setting ? safelyParseJSON(setting) || defaultLabels : defaultLabels;
    })();
    console.log('aria-labels', labels);
    GM_registerMenuCommand('Set aria-labels', () => {
        let input, list;
        let error = false;
        do {
            const current = GM_getValue('labels', '');
            input = prompt(`Please input the aria-label of Close, Previous, Next button and join them by comma (,). Submit an empty string will reset it to default.${error ? '\n\nINPUT ERROR' : ''}`, input || current ? Object.values(safelyParseJSON(current) || {}).join(',') : '');
            if (input === null) return;
            input = input.trim();
            if (input.length === 0) list = Object.values(defaultLabels);
            else list = input.split(',').map(label => label.trim());
            error = list.length !== Object.keys(labels).length;
        } while (error);
        Object.keys(labels).forEach((key, index) => {
            labels[key] = list[index];
        });
        GM_setValue('labels', input.length ? JSON.stringify(labels) : '');
        console.log('aria-labels-setting', GM_getValue('labels'));
        console.log('aria-labels', labels);
    });

    const getBtnByLabel = label => $(`div[aria-labelledby="modal-header"] div[aria-label="${label}"]`);
    const clickBtn = name => {
        const btnLables = [labels[name], defaultLabelsByLang.default[name]];
        for (const label of btnLables) {
            if (!label) continue;
            const $btn = getBtnByLabel(label);
            if ($btn.length) {
                $btn.click();
                return true;
            }
        }
        return false;
    };

    const closeImgView = () => {
        if (!clickBtn('close')) {
            Snackbar.show({
                pos: 'bottom-center',
                text: `It seems that you haven't set the right aria-labels yet.<br>Please visit the homepage of "Twitter image viewing enhancement" script for more information.`,
                actionText: 'visit',
                actionTextColor: '#f66496',
                duration: 0,
                customClass: 'tive-snackbar',
                onActionClick: ele => {
                    $(ele).css('opacity', 0);
                    GM_openInTab('https://greasyfork.org/scripts/387918', false);
                },
            });
        }
    };
    const prevImg = () => clickBtn('prev');
    const nextImg = () => clickBtn('next');

    $(document).mousewheel(({ deltaY, target: { tagName, baseURI } }) => {
        if (tagName == 'IMG' && /\/photo\//.test(baseURI)) {
            switch (deltaY) {
                case 1:
                    prevImg();
                    break;
                case -1:
                    nextImg();
                    break;
            }
        }
    });

    let x = 0;
    let y = 0;
    $(document).mousedown(({ clientX, clientY }) => {
        x = clientX;
        y = clientY;
    });
    $(document).mouseup(({ button, clientX, clientY, target: { tagName, baseURI } }) => {
        if (button !== 0 || !(tagName == 'IMG' && /\/photo\//.test(baseURI))) return;
        const [sx, sy] = [clientX - x, clientY - y].map(Math.abs);
        const mx = clientX - x;
        if (sx <= 10 && sy <= 10) closeImgView();
        if (sy <= sx) {
            if (mx > 0) prevImg();
            else if (mx < 0) nextImg();
        }
    });
})();