Jump to content

User:DreamRimmer/EasyEmailSign.js

From Wikipedia, the free encyclopedia
The printable version is no longer supported and may have rendering errors. Please update your browser bookmarks and please use the default browser print function instead.
Note: After saving, you have to bypass your browser's cache to see the changes. Google Chrome, Firefox, Microsoft Edge and Safari: Hold down the ⇧ Shift key and click the Reload toolbar button. For details and instructions about other browsers, see Wikipedia:Bypass your cache.
//<nowiki>
mw.loader.using(['mediawiki.util', 'oojs-ui'], function () {
    $(document).ready(function() {
        if (!mw.config.get('wgPageName').startsWith('Special:EmailUser')) {
            return;
        }

        mw.util.addPortletLink(
            'p-personal',
            '#',
            'EasyEmailSignature',
            'ca-set-email-signature',
            'Set your email signature'
        );

        function SigDlg(config) {
            SigDlg.super.call(this, config);
        }
        OO.inheritClass(SigDlg, OO.ui.ProcessDialog);

        SigDlg.static.name = 'sigDlg';
        SigDlg.static.title = 'EasyEmailSign';
        SigDlg.static.actions = [
            { action: 'save', label: 'Save', flags: ['primary', 'progressive'] },
            { action: 'cancel', label: 'Cancel', flags: 'safe' }
        ];

        SigDlg.prototype.initialize = function() {
            SigDlg.super.prototype.initialize.call(this);
            this.content = new OO.ui.PanelLayout({ padded: true, expanded: false });
            this.input = new OO.ui.MultilineTextInputWidget({
                value: '',
                placeholder: 'Enter your email signature here',
                rows: 4
            });
            
            this.warningMessage = new OO.ui.MessageWidget({
                type: 'warning',
                label: 'This signature will be saved in your userspace publicly, so please do not include any personal information that you do not want to share.'
            });

            this.warningMessage.$element.css('margin-bottom', '10px');

            this.content.$element.append(this.warningMessage.$element);
            this.content.$element.append(this.input.$element);
            this.$body.append(this.content.$element);

            loadEmailSig().then(sig => {
                this.input.setValue(sig);
            });
        };

        SigDlg.prototype.getActionProcess = function(action) {
            if (action === 'save') {
                saveEmailSig(this.input.getValue().trim());
                this.close({ action: action });
                return new OO.ui.Process();
            } else if (action === 'cancel') {
                this.close({ action: action });
                return new OO.ui.Process();
            }
            return SigDlg.super.prototype.getActionProcess.call(this, action);
        };

        const loadEmailSig = () => {
            const userPage = 'User:' + mw.config.get('wgUserName') + '/email-signature.json';
            return new mw.Api().get({
                action: 'query',
                prop: 'revisions',
                titles: userPage,
                rvslots: '*',
                rvprop: 'content',
                formatversion: 2
            }).then(data => {
                const page = data.query.pages[0];
                if (page.missing) {
                    return '';
                } else {
                    try {
                        const content = JSON.parse(page.revisions[0].slots.main.content);
                        return content.signature || '';
                    } catch (e) {
                        return '';
                    }
                }
            }).catch(() => {
                return '';
            });
        };

        const saveEmailSig = (sig) => {
            const userPage = 'User:' + mw.config.get('wgUserName') + '/email-signature.json';
            const content = JSON.stringify({ signature: sig }, null, 2);
            new mw.Api().postWithToken('csrf', {
                action: 'edit',
                title: userPage,
                text: content,
                contentmodel: 'json',
                summary: 'Updating email signature ([[User:DreamRimmer/EasyEmailSign|EasyEmailSign.js]])',
                minor: true,
                createonly: false
            }).done(() => {
                mw.notify('Signature saved successfully! Reloading...', { type: 'success' });
                setTimeout(() => location.reload(), 1500);
            }).fail(() => {
                mw.notify('Failed to save signature', { type: 'error' });
            });
        };

        const insertEmailSig = (callback) => {
            loadEmailSig().then(sig => {
                const $txt = $('#ooui-php-5');
                if (sig && !$txt.val().endsWith(sig)) {
                    $txt.val($txt.val().trim() + '\n\n\n' + sig);
                }
                if (callback) {
                    callback();
                }
            });
        };

        const winMgr = new OO.ui.WindowManager();
        $(document.body).append(winMgr.$element);
        const dlg = new SigDlg();
        winMgr.addWindows([dlg]);

        $('#ca-set-email-signature').click((e) => {
            e.preventDefault();
            winMgr.openWindow(dlg);
        });

        insertEmailSig();

        $('#wpSend, .mw-htmlform-submit button[type="submit"]').on('click', function(event) {
            event.preventDefault();
            const $button = $(this);
            insertEmailSig(() => {
                $button.closest('form').submit();
            });
        });
    });
});

//</nowiki>