MediaWiki:Gadget-EditDraft.js

来自节奏医生中文百科
跳到导航 跳到搜索

注意:在保存之后,您可能需要清除浏览器缓存才能看到所作出的变更的影响。

  • Firefox或Safari:按住Shift的同时单击刷新,或按Ctrl-F5Ctrl-R(Mac为⌘-R
  • Google Chrome:Ctrl-Shift-R(Mac为⌘-Shift-R
  • Internet Explorer:按住Ctrl的同时单击刷新,或按Ctrl-F5
  • Opera:前往菜单 → 设置(Mac为Opera → Preferences),然后隐私和安全 → 清除浏览数据 → 缓存的图片和文件
//阅读更多:https://zh.moegirl.org/MediaWiki:Gadget-EditDraft.js
//本文引自萌娘百科(https://zh.moegirl.org/),文字内容遵守【知识共享 署名-非商业性使用-相同方式共享 3.0】协议。

/* eslint-disable */
/* jshint ignore:start */
'use strict';

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

if (['edit', 'submit'].indexOf(mw.config.get('wgAction')) !== -1) $.get('https://static.kcwiki.org/QuickSaveDraft.main.css', function (_d) {
    "use strict";

    var QuickSaveDraftUI = function () {
        function QuickSaveDraftUI(buttonArea, textarea, section, timer) {
            _classCallCheck(this, QuickSaveDraftUI);

            var //vscode的缩进还是有问题
            saveButton = this.inputConstruct({
                class: 'QuickSaveDraftSaveButton',
                val: '立即保存草稿',
                attr: {
                    type: 'button'
                }
            }),
                recoverButton = this.inputConstruct({
                class: 'QuickSaveDraftRecoverButton',
                val: '暂无草稿',
                attr: {
                    type: 'button'
                }
            }),
                rollbackButton = this.inputConstruct({
                class: 'QuickSaveDraftRollbackButton',
                val: '回退还原',
                attr: {
                    type: 'button'
                }
            }),
                timerInput = this.inputConstruct({
                class: 'QuickSaveDraftTimerInput',
                val: timer, //默认值
                maxlength: 2
            }),
                timerSave = $('<span/>', {
                id: 'QuickSaveDraftTimerSave'
            }),
                lastRun = $('<div/>', {
                class: 'QuickSaveDraftLastRunDiv',
                text: '上次草稿保存于'
            }).append($('<span/>', {
                class: 'QuickSaveDraftLastRun'
            })),
                pasueButton = this.inputConstruct({
                class: 'QuickSaveDraftPauseButton',
                val: '点击暂停自动保存',
                attr: {
                    type: 'button'
                }
            }),
                sectionList = $('<div/>').append('当前章节号为').append($('<span/>', {
                class: 'QuickSaveDraftSectionNow',
                css: {
                    'font-weight': 'bold'
                },
                text: section
            })).append($('<span/>', {
                class: 'QuickSaveDraftSectionDraftSpan',
                text: ',草稿章节号为'
            }).append($('<span/>', {
                class: 'QuickSaveDraftSectionDraft'
            }))).append($('<span/>', {
                class: 'QuickSaveDraftSame',
                text: ',草稿内容与当前编辑内容一致'
            }));
            recoverButton.disable();
            rollbackButton.disable();
            buttonArea.append(saveButton).append(recoverButton).append(rollbackButton).append('每隔').append(timerInput).append('分钟保存一次').append(timerSave).append(pasueButton).append(lastRun).append(sectionList);
            Object.assign(this, {
                textarea: textarea,
                saveButton: saveButton,
                recoverButton: recoverButton,
                rollbackButton: rollbackButton,
                pasueButton: pasueButton,
                timerInput: timerInput,
                lastRun: lastRun,
                sectionList: sectionList,
                timerSave: timerSave,
                timerSaveCode: null
            });
        }

        _createClass(QuickSaveDraftUI, [{
            key: 'inputConstruct',
            value: function inputConstruct(opt) {
                var r = $('<span/>');
                var input = $('<input/>', opt);
                if (opt.attr && opt.attr.type === "button") {
                    r.addClass('oo-ui-widget oo-ui-widget-enabled oo-ui-inputWidget oo-ui-buttonElement oo-ui-buttonElement-framed oo-ui-labelElement oo-ui-buttonInputWidget');
                    input.addClass('oo-ui-inputWidget-input oo-ui-buttonElement-button');
                } else {
                    r.addClass('oo-ui-widget oo-ui-widget-enabled oo-ui-inputWidget oo-ui-textInputWidget oo-ui-textInputWidget-type-text QuickSaveDraftTimer');
                    input.addClass('oo-ui-inputWidget-input');
                }
                r.append(input);
                ['on', 'val', 'disable', 'enable'].forEach(function (key) {
                    r[key] = input[key].bind(input);
                });
                return r;
            }
        }, {
            key: 'watch',
            value: function watch(callback, _self) {
                var self = this;
                self.timerInput.on('input', function () {
                    var result = callback($(this).val(), _self) ? ',保存成功!' : ',保存失败';
                    self.timerSave.text(result);
                    self.timerSave.removeClass('disapper');
                    if (self.timerSaveCode) window.clearTimeout(self.timerSaveCode);
                    self.timerSaveCode = window.setTimeout(function () {
                        self.timerSave.addClass('disapper');
                    }, 3000);
                });
            }
        }, {
            key: 'complement',
            value: function complement(n, l) {
                n += '';
                if (n.length >= l) return n;
                var b = '<span style="speak:none;visibility:hidden;color:transparent;">',
                    c = '';
                while (l > (n + c).length) {
                    c += '0';
                }return b + c + '</span>' + n;
            }
        }]);

        return QuickSaveDraftUI;
    }();

    var QuickSaveDraft = function () {
        function QuickSaveDraft() {
            _classCallCheck(this, QuickSaveDraft);

            var pagename = mw.config.get('wgPageName'),
                user = mw.config.get('wgUserId');
            //this.clear();
            Object.assign(this, {
                pagename: pagename,
                user: user,
                version: '2.0',
                section: location.search.match(/section=(\d+)/) ? +location.search.match(/section=(\d+)/)[1] : -1,
                pause: false,
                originText: null
            });
            for (var i in localStorage) {
                if (!/^AnnTools-QuickSaveDraft-\d+-timestamp-/.test(i)) continue;
                var pageName = i.replace(/^AnnTools-QuickSaveDraft-\d+-timestamp-/, ''),
                    userId = i.match(/^AnnTools-QuickSaveDraft-(\d+)-timestamp-/)[1];
                if (new Date().getTime() - +localStorage[i] > 86400) {
                    localStorage.removeItem(i);
                    localStorage.removeItem('AnnTools-QuickSaveDraft-' + userId + '-draft-' + pageName);
                    localStorage.removeItem('AnnTools-QuickSaveDraft-' + userId + '-section-' + pageName);
                }
            }
            this.init();
        }

        _createClass(QuickSaveDraft, [{
            key: 'clear',
            value: function clear() {
                for (var i in localStorage) {
                    if (/^AnnTools\-QuickSaveDraft/.test(i)) localStorage.removeItem(i);
                }
            }
        }, {
            key: 'init',
            value: function init() {
                var self = this,
                    textarea = $('#wpTextbox1'),
                    buttonArea = $('<div/>', {
                    css: {
                        'margin-top': '.5em'
                    }
                }).appendTo('#editform .editButtons'),
                    date = self.get('timestamp') ? new Date(+self.get('timestamp')) : undefined;
                this.UI = new QuickSaveDraftUI(buttonArea, textarea, self.getSection(+self.section), self.get('timer') || (self.set('timer', 3), 3));
                self.UI.watch(self.saveTime, self);
                self.UI.rollbackButton.on('click', function () {
                    if ($(this).is(':disabled') || self.originText === null) return;
                    textarea.val(self.originText);
                    self.originText = null;
                    $(this).disable();
                    self.check();
                    return false;
                });
                self.UI.recoverButton.on('click', function () {
                    if ($(this).is(':disabled')) return;
                    if (self.checkCurrentSection()) return;
                    self.originText = textarea.val();
                    textarea.val(self.get('draft'));
                    self.UI.rollbackButton.enable();
                    self.check();
                    return false;
                });
                self.UI.saveButton.on('click', function () {
                    if ($(this).is(':disabled')) return;
                    self.save(false);
                    return false;
                });
                self.UI.pasueButton.on('click', function () {
                    if (self.pause) {
                        $(this).val('点击暂停自动保存');
                        self.pause = false;
                    } else {
                        $(this).val('点击继续自动保存');
                        self.pause = true;
                    }
                });
                self.check();
                /* 下面一行太长了,换一下行 */
                if (date) self.UI.lastRun.fadeIn().find('span').html((date.getDate() === new Date().getDate() ? '今' : self.UI.complement(date.getDate(), 2)) + '\u65E5' + self.UI.complement(date.getHours(), 2) + '\u65F6' + self.UI.complement(date.getMinutes(), 2) + '\u5206 草稿长度为 ' + (self.get('draft').length || '-1(暂无)') + ' 字符');
                self.UI.sectionList.find('.QuickSaveDraftSectionDraft').text(self.get('section') || '【暂无】');
                textarea.on('input change', function () {
                    self.check();
                });
                window.setTimeout(self.loop, self.getTime(), self);
            }
        }, {
            key: 'get',
            value: function get(t) {
                if (t === 'timer') return localStorage.getItem('AnnTools-QuickSaveDraft-' + this.user + '-timer');
                return localStorage.getItem('AnnTools-QuickSaveDraft-' + this.user + '-' + t + '-' + this.pagename);
            }
        }, {
            key: 'set',
            value: function set(t, v) {
                if (t === 'timer') return localStorage.setItem('AnnTools-QuickSaveDraft-' + this.user + '-timer', v);
                return localStorage.setItem('AnnTools-QuickSaveDraft-' + this.user + '-' + t + '-' + this.pagename, v);
            }
        }, {
            key: 'del',
            value: function del(t) {
                if (t === 'timer') return localStorage.removeItem('AnnTools-QuickSaveDraft-' + this.user + '-timer');
                return localStorage.removeItem('AnnTools-QuickSaveDraft-' + this.user + '-' + t + '-' + this.pagename);
            }
        }, {
            key: 'check',
            value: function check() {
                if (this.get('draft') === undefined) return this.UI.sectionList.find('.QuickSaveDraftSectionDraftSpan').fadeOut();
                this.UI.sectionList.find('.QuickSaveDraftSectionDraftDraft').text(this.get('section')).parent().fadeIn();
                if (this.checkCurrentSection()) //检测是否同一章节
                    return this.UI.recoverButton.disable().val('暂无草稿');
                if (this.get('draft') !== this.UI.textarea.val()) {
                    //检测草稿是否一致
                    this.UI.recoverButton.enable().val('立即还原草稿');
                    this.UI.sectionList.find('.QuickSaveDraftSame').fadeOut();
                } else {
                    this.UI.recoverButton.disable().val('暂无草稿');
                    this.UI.sectionList.find('.QuickSaveDraftSame').fadeIn();
                }
            }
        }, {
            key: 'checkCurrentSection',
            value: function checkCurrentSection() {
                return this.section !== (Number.parseInt || Window.parseInt)(this.get('section'));
            }
        }, {
            key: 'getTime',
            value: function getTime() {
                return +this.get('timer') * 60000; //min => millisecond
            }
        }, {
            key: 'saveTime',
            value: function saveTime(time, self) {
                if (!/\D/.test(time) && +time > 0) {
                    self.set('timer', time);
                    return true;
                } else {
                    self.UI.timerInput.val(self.get('timer'));
                    return false;
                }
            }
        }, {
            key: 'save',
            value: function save(s) {
                var date = new Date(),
                    value = this.UI.textarea.val();
                this.set('draft', value);
                if (value !== this.get('draft')) {
                    if (s) alert('当前页面内容过长,无法保存草稿!');
                    this.del('draft');
                    this.UI.recoverButton.fadeOut();
                    this.UI.saveButton.disable().val('无法保存草稿');
                    this.UI.lastRun.fadeIn().text('当前页面内容过长,无法保存草稿!');
                    return window.setTimeout(function (self) {
                        self.save = self.loop = function () {
                            return false;
                        };
                    }, 0, this);
                }
                this.set('section', this.getSection(+this.section));
                this.set('timestamp', date.getTime());
                this.UI.sectionList.find('.QuickSaveDraftSectionDraftSpan').fadeIn().find('.QuickSaveDraftSectionDraft').text(this.getSection(+this.section));
                this.check();
                this.UI.lastRun.fadeIn().find('span').html('\u4ECA\u65E5' + this.UI.complement(date.getHours(), 2) + '\u65F6' + this.UI.complement(date.getMinutes(), 2) + '\u5206 草稿长度为 ' + (this.get('draft').length || '-1(暂无)') + ' 字符');
            }
        }, {
            key: 'loop',
            value: function loop(self) {
                if (!this.pause) self.save(true);
                return window.setTimeout(self.loop, self.getTime(), self);
            }
        }, {
            key: 'getSection',
            value: function getSection(s) {
                return s === -1 ? '-1(全文)' : s;
            }
        }]);

        return QuickSaveDraft;
    }();

    jQuery.fn.extend({
        disable: function disable() {
            return this.each(function () {
                if (!$(this).is('input,button')) return;
                if ($(this).parent().hasClass('oo-ui-widget-enabled')) $(this).parent().toggleClass('oo-ui-widget-enabled oo-ui-widget-disabled');
                this.disabled = true;
            });
        },
        enable: function enable() {
            return this.each(function () {
                if (!$(this).is('input,button')) return;
                if ($(this).parent().hasClass('oo-ui-widget-disabled')) $(this).parent().toggleClass('oo-ui-widget-enabled oo-ui-widget-disabled');
                this.disabled = false;
            });
        }
    });
    $('<style/>', {
        text: _d
    }).appendTo(document.head);
    window.AnnTools = window.AnnTools || {};
    window.AnnTools.QuickSaveDraft = window.AnnTools.QuickSaveDraft || new QuickSaveDraft();
});