跳转到内容

MediaWiki:Gadget-PrintOptions.js:修订间差异

勤求古训,博采众方
无编辑摘要
无编辑摘要
标签手工回退
 
(未显示同一用户的9个中间版本)
第1行: 第1行:
// ==UserScript==
(function () {
// @name        MediaWiki打印增强
// @description  为MediaWiki添加高级打印选项(优化布局、图片控制等)
// @namespace    https://github.com/yourname/
// @version      1.1
// @license      MIT
// @match        *://*/*
// @grant        none
// ==/UserScript==
 
(function() {
     'use strict';
     'use strict';
 
   
     // ============== 核心配置 ==============
     var windowManager;
    const PrintEnhancer = {
    var printDialog;
         config: {
   
             enhanced: true,
    var printOptions = {
             noimages: false,
        install: function () {
             norefs: false,
            var $printLink = $('#t-print a');
             notoc: false,
            if ($printLink.length === 0) return;
             nobackground: false,
           
             blacktext: true
            $printLink
                .text('可打印版本')
                .off('click')
                .on('click', function (e) {
                    mw.loader.using(['oojs-ui-core', 'oojs-ui-widgets', 'oojs-ui-windows'])
                        .then(printOptions.createWindow)
                        .catch(function (err) {
                            mw.notify('打印功能加载失败: ' + err.message, { type: 'error' });
                        });
                    e.preventDefault();
                });
           
            // 预加载资源
            mw.loader.load(['oojs-ui-core', 'oojs-ui-widgets', 'oojs-ui-windows']);
        },
       
        createWindow: function () {
            function PrintDialog(config) {
                PrintDialog.super.call(this, config);
            }
            OO.inheritClass(PrintDialog, OO.ui.ProcessDialog);
           
            PrintDialog.static.name = 'printdialog';
            PrintDialog.static.title = '打印此页面';
            PrintDialog.static.actions = [
                { action: 'print', label: '打印', flags: ['primary', 'progressive'] },
                { action: 'cancel', label: '取消', flags: 'safe' }
            ];
           
            PrintDialog.prototype.initialize = function () {
                PrintDialog.super.prototype.initialize.apply(this, arguments);
                this.panel = new OO.ui.PanelLayout({ padded: true, expanded: false });
                this.content = new OO.ui.FieldsetLayout();
               
                printOptions.questions.forEach(function (question) {
                    if (question.type === 'checkbox') {
                        var checkbox = new OO.ui.CheckboxInputWidget({
                            selected: question.checked
                        });
                        question.widget = checkbox;
                        this.content.addItems([
                            new OO.ui.FieldLayout(checkbox, {
                                label: question.label,
                                align: 'inline'
                            })
                        ]);
                    }
                }, this);
               
                this.panel.$element.append(this.content.$element);
                this.$body.append(this.panel.$element);
            };
           
            // ✅ 修复点:明确处理取消动作
            PrintDialog.prototype.getActionProcess = function (action) {
                if (action === 'print') {
                    return new OO.ui.Process(function () {
                        printOptions.questions.forEach(function (question) {
                            if (question.widget) {
                                printOptions[question.returnvalue] = question.widget.isSelected();
                            }
                        });
                        return this.close({ action: action }).then(function () {
                            printOptions.changePrintCSS();
                            printOptions.otherEnhancements();
                            setTimeout(window.print, 100);
                        });
                    }.bind(this));
                }
                // 🔥 关键修复:取消时直接关闭对话框
                if (action === 'cancel') {
                    return new OO.ui.Process(function () {
                        return this.close({ action: action });
                    }.bind(this));
                }
                return PrintDialog.super.prototype.getActionProcess.call(this, action);
            };
           
            if (!windowManager) {
                windowManager = new OO.ui.WindowManager();
                $('body').append(windowManager.$element);
            }
            if (!printDialog) {
                printDialog = new PrintDialog({ size: 'medium' });
                windowManager.addWindows([printDialog]);
            }
            windowManager.openWindow(printDialog);
         },
       
        changePrintCSS: function () {
             /* 原有CSS处理逻辑 */
            var printStyle = '';
             if (this.noimages) printStyle += 'img, .thumb { display:none !important; }\n';
             if (this.norefs) printStyle += '.references, .reference { display:none !important; }\n';
             if (this.notoc) printStyle += '#toc, .toc { display:none !important; }\n';
             if (this.nobackground) printStyle += 'body { background: white !important; }\n';
            if (this.blacktext) printStyle += '* { color: black !important; }\n';
           
            $('style[media="print"]').remove(); // 清理旧样式
            if (printStyle) {
                $('head').append('<style media="print">' + printStyle + '</style>');
            }
        },
       
        otherEnhancements: function () {
             var $link = $('div.printfooter a');
            try {
                $link.text(decodeURIComponent($link.text()));
            } catch (e) {
                mw.log.warn('URL解码失败:', e);
            }
         },
         },
 
       
         questions: [
         questions: [
             {
             {
                label: '隐藏界面元素',
                 type: 'checkbox',
                 type: 'checkbox',
                 returnvalue: 'enhanced',
                 checked: true,
label: mw.message('print-option-enhance').plain(),
                 returnvalue: 'enhanced'
                 help: 'print-option-enhance-help'
             },
             },
             {
             {
                label: '隐藏图像',
                 type: 'checkbox',
                 type: 'checkbox',
                 returnvalue: 'noimages',
                 checked: false,
                 label: mw.message('print-option-noimages').plain()
                 returnvalue: 'noimages'
             },
             },
             {
             {
                label: '隐藏引用',
                 type: 'checkbox',
                 type: 'checkbox',
                 returnvalue: 'norefs',
                 checked: false,
                 label: mw.message('print-option-norefs').plain()
                 returnvalue: 'norefs'
             },
             },
             {
             {
                label: '隐藏目录',
                 type: 'checkbox',
                 type: 'checkbox',
                 returnvalue: 'notoc',
                 checked: false,
                 label: mw.message('print-option-notoc').plain()
                 returnvalue: 'notoc'
             },
             },
             {
             {
                label: '删除背景(部分浏览器可能无效)',
                 type: 'checkbox',
                 type: 'checkbox',
                 returnvalue: 'nobackground',
                 checked: false,
                 label: mw.message('print-option-nobg').plain(),
                 returnvalue: 'nobackground'
                help: 'print-option-nobg-help'
             },
             },
             {
             {
                label: '强制文本为黑色',
                 type: 'checkbox',
                 type: 'checkbox',
                 returnvalue: 'blacktext',
                 checked: true,
                 label: mw.message('print-option-blacktext').plain()
                 returnvalue: 'blacktext'
             }
             }
         ],
         ]
 
    };
        // ============== 初始化 ==============
   
        init() {
    // 延迟初始化以避免冲突
            if (!document.getElementById('t-print')) return;
    $(function () {
 
        if (mw.config.get('wgNamespaceNumber') >= 0) {
            mw.loader.using(['oojs-ui', 'oojs-ui-windows']).then(() => {
             setTimeout(printOptions.install, 100);
                const $printLink = $('#t-print a');
                $printLink
                    .text(mw.message('print-version').plain())
                    .off('click')
                    .on('click', (e) => {
                        e.preventDefault();
                        e.stopPropagation();
                        this.createDialog();
                    });
            });
        },
 
        // ============== 对话框 ==============
        createDialog() {
            function PrintDialog(config) {
                PrintDialog.super.call(this, config);
            }
            OO.inheritClass(PrintDialog, OO.ui.ProcessDialog);
 
            PrintDialog.static.name = 'printdialog';
            PrintDialog.static.title = mw.message('print-dialog-title').plain();
            PrintDialog.static.actions = [
                {
                    action: 'print',
                    label: mw.message('print-action-print').plain(),
                    flags: ['primary', 'progressive']
                },
                {
                    action: 'cancel',
                    label: mw.message('print-action-cancel').plain(),
                    flags: 'safe'
                }
            ];
 
            PrintDialog.prototype.initialize = function() {
                PrintDialog.super.prototype.initialize.apply(this, arguments);
                const panel = new OO.ui.PanelLayout({ padded: true });
                const fieldset = new OO.ui.FieldsetLayout({
                    label: mw.message('print-options').plain()
                });
 
                PrintEnhancer.questions.forEach(q => {
                    const checkbox = new OO.ui.CheckboxInputWidget({
                        selected: PrintEnhancer.config[q.returnvalue]
                    });
                    fieldset.addItems([
                        new OO.ui.FieldLayout(checkbox, {
                            label: q.label,
                            align: 'inline',
                            help: q.help ? mw.message(q.help).plain() : null
                        })
                    ]);
                    q.widget = checkbox;
                });
 
                panel.$element.append(fieldset.$element);
                this.$body.append(panel.$element);
            };
 
             PrintDialog.prototype.getActionProcess = function(action) {
                const dialog = this;
                return new OO.ui.Process(() => {
                    if (action === 'print') {
                        PrintEnhancer.questions.forEach(q => {
                            PrintEnhancer.config[q.returnvalue] = q.widget.isSelected();
                        });
                        return dialog.close({ action }).then(() => {
                            PrintEnhancer.applyPrintStyles();
                            setTimeout(() => {
                                window.print();
                                setTimeout(() => location.reload(), 1000);
                            }, 500);
                        });
                    }
                    return dialog.close({ action }); // 处理cancel
                });
            };
 
            if (!this.windowManager) {
                this.windowManager = new OO.ui.WindowManager();
                $('body').append(this.windowManager.$element);
            }
            this.windowManager.addWindows([new PrintDialog({ size: 'medium' })]);
            this.windowManager.openWindow(this.printDialog);
        },
 
        // ============== 打印样式 ==============
        applyPrintStyles() {
            let css = '@media print { ';
            const c = this.config;
 
            if (c.enhanced) css += `
                .noprint, #siteNotice, .mw-indicators,
                .mw-editsection, .firstHeading .mw-headline {
                    display: none !important;
                }
            `;
            if (c.noimages) css += 'img, .video-container { display: none !important; }';
            if (c.norefs) css += 'sup.reference, .references { display: none !important; }';
            if (c.notoc) css += '#toc, .toc { display: none !important; }';
            if (c.nobackground) css += 'body { background: white !important; }';
            if (c.blacktext) css += 'body { color: black !important; }';
 
            css += '}';
           
            const style = document.createElement('style');
            style.media = 'print';
            style.textContent = css;
            document.head.appendChild(style);
         }
         }
    };
    // ============== 消息初始化 ==============
    mw.messages.set({
        'print-version': '可打印版本',
        'print-dialog-title': '打印设置',
        'print-options': '自定义打印选项',
        'print-action-print': '打印',
        'print-action-cancel': '取消',
        'print-option-enhance': '优化打印布局',
        'print-option-enhance-help': '隐藏编辑按钮等非必要元素',
        'print-option-noimages': '隐藏所有图片',
        'print-option-norefs': '隐藏参考文献',
        'print-option-notoc': '隐藏目录',
        'print-option-nobg': '移除背景色',
        'print-option-nobg-help': '节省墨水,但可能影响部分内容可见性',
        'print-option-blacktext': '强制纯黑色文字'
     });
     });
    // ============== 启动 ==============
    mw.hook('wikipage.content').add(() => PrintEnhancer.init());
})();
})();

2025年11月1日 (六) 22:56的最新版本

(function () {
    'use strict';
    
    var windowManager;
    var printDialog;
    
    var printOptions = {
        install: function () {
            var $printLink = $('#t-print a');
            if ($printLink.length === 0) return;
            
            $printLink
                .text('可打印版本')
                .off('click')
                .on('click', function (e) {
                    mw.loader.using(['oojs-ui-core', 'oojs-ui-widgets', 'oojs-ui-windows'])
                        .then(printOptions.createWindow)
                        .catch(function (err) {
                            mw.notify('打印功能加载失败: ' + err.message, { type: 'error' });
                        });
                    e.preventDefault();
                });
            
            // 预加载资源
            mw.loader.load(['oojs-ui-core', 'oojs-ui-widgets', 'oojs-ui-windows']);
        },
        
        createWindow: function () {
            function PrintDialog(config) {
                PrintDialog.super.call(this, config);
            }
            OO.inheritClass(PrintDialog, OO.ui.ProcessDialog);
            
            PrintDialog.static.name = 'printdialog';
            PrintDialog.static.title = '打印此页面';
            PrintDialog.static.actions = [
                { action: 'print', label: '打印', flags: ['primary', 'progressive'] },
                { action: 'cancel', label: '取消', flags: 'safe' }
            ];
            
            PrintDialog.prototype.initialize = function () {
                PrintDialog.super.prototype.initialize.apply(this, arguments);
                this.panel = new OO.ui.PanelLayout({ padded: true, expanded: false });
                this.content = new OO.ui.FieldsetLayout();
                
                printOptions.questions.forEach(function (question) {
                    if (question.type === 'checkbox') {
                        var checkbox = new OO.ui.CheckboxInputWidget({
                            selected: question.checked
                        });
                        question.widget = checkbox;
                        this.content.addItems([
                            new OO.ui.FieldLayout(checkbox, {
                                label: question.label,
                                align: 'inline'
                            })
                        ]);
                    }
                }, this);
                
                this.panel.$element.append(this.content.$element);
                this.$body.append(this.panel.$element);
            };
            
            // ✅ 修复点:明确处理取消动作
            PrintDialog.prototype.getActionProcess = function (action) {
                if (action === 'print') {
                    return new OO.ui.Process(function () {
                        printOptions.questions.forEach(function (question) {
                            if (question.widget) {
                                printOptions[question.returnvalue] = question.widget.isSelected();
                            }
                        });
                        return this.close({ action: action }).then(function () {
                            printOptions.changePrintCSS();
                            printOptions.otherEnhancements();
                            setTimeout(window.print, 100);
                        });
                    }.bind(this));
                }
                // 🔥 关键修复:取消时直接关闭对话框
                if (action === 'cancel') {
                    return new OO.ui.Process(function () {
                        return this.close({ action: action });
                    }.bind(this));
                }
                return PrintDialog.super.prototype.getActionProcess.call(this, action);
            };
            
            if (!windowManager) {
                windowManager = new OO.ui.WindowManager();
                $('body').append(windowManager.$element);
            }
            if (!printDialog) {
                printDialog = new PrintDialog({ size: 'medium' });
                windowManager.addWindows([printDialog]);
            }
            windowManager.openWindow(printDialog);
        },
        
        changePrintCSS: function () {
            /* 原有CSS处理逻辑 */
            var printStyle = '';
            if (this.noimages) printStyle += 'img, .thumb { display:none !important; }\n';
            if (this.norefs) printStyle += '.references, .reference { display:none !important; }\n';
            if (this.notoc) printStyle += '#toc, .toc { display:none !important; }\n';
            if (this.nobackground) printStyle += 'body { background: white !important; }\n';
            if (this.blacktext) printStyle += '* { color: black !important; }\n';
            
            $('style[media="print"]').remove(); // 清理旧样式
            if (printStyle) {
                $('head').append('<style media="print">' + printStyle + '</style>');
            }
        },
        
        otherEnhancements: function () {
            var $link = $('div.printfooter a');
            try {
                $link.text(decodeURIComponent($link.text()));
            } catch (e) {
                mw.log.warn('URL解码失败:', e);
            }
        },
        
        questions: [
            {
                label: '隐藏界面元素',
                type: 'checkbox',
                checked: true,
                returnvalue: 'enhanced'
            },
            {
                label: '隐藏图像',
                type: 'checkbox',
                checked: false,
                returnvalue: 'noimages'
            },
            {
                label: '隐藏引用',
                type: 'checkbox',
                checked: false,
                returnvalue: 'norefs'
            },
            {
                label: '隐藏目录',
                type: 'checkbox',
                checked: false,
                returnvalue: 'notoc'
            },
            {
                label: '删除背景(部分浏览器可能无效)',
                type: 'checkbox',
                checked: false,
                returnvalue: 'nobackground'
            },
            {
                label: '强制文本为黑色',
                type: 'checkbox',
                checked: true,
                returnvalue: 'blacktext'
            }
        ]
    };
    
    // 延迟初始化以避免冲突
    $(function () {
        if (mw.config.get('wgNamespaceNumber') >= 0) {
            setTimeout(printOptions.install, 100);
        }
    });
})();