跳转到内容

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

勤求古训,博采众方
无编辑摘要
无编辑摘要
标签手工回退
 
(未显示同一用户的11个中间版本)
第1行: 第1行:
(function() {
(function () {
     'use strict';
     'use strict';
 
   
     const PrintEnhancer = {
    var windowManager;
         windowManager: null,
     var printDialog;
         printDialog: null,
   
    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']);
         },
          
          
         config: {
         createWindow: function () {
            enhanced: true,
            noimages: false,
            norefs: false,
            notoc: false,
            nobackground: false,
            blacktext: true
        },
 
        init() {
            if (mw.config.get('wgNamespaceNumber') < 0) return;
 
            mw.hook('wikipage.content').add(() => {
                const $printLink = $('#t-print a');
                if (!$printLink.length) return;
 
                $printLink
                    .text(mw.message('print-version').plain())
                    .off('click')
                    .on('click', (e) => {
                        e.preventDefault();
                        mw.loader.using(['oojs-ui', 'oojs-ui-core', 'oojs-ui-windows']).then(() => this.createDialog());
                    });
            });
        },
 
        createDialog() {
             function PrintDialog(config) {
             function PrintDialog(config) {
                 PrintDialog.super.call(this, config);
                 PrintDialog.super.call(this, config);
             }
             }
             OO.inheritClass(PrintDialog, OO.ui.ProcessDialog);
             OO.inheritClass(PrintDialog, OO.ui.ProcessDialog);
 
           
             PrintDialog.static.name = 'printdialog';
             PrintDialog.static.name = 'printdialog';
             PrintDialog.static.title = mw.message('print-dialog-title').plain();
             PrintDialog.static.title = '打印此页面';
             PrintDialog.static.actions = [
             PrintDialog.static.actions = [
                 {  
                 { action: 'print', label: '打印', flags: ['primary', 'progressive'] },
                    action: 'print',  
                 { action: 'cancel', label: '取消', flags: 'safe' }
                    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.prototype.initialize = function () {
                 PrintDialog.super.prototype.initialize.apply(this, arguments);
                 PrintDialog.super.prototype.initialize.apply(this, arguments);
                this.panel = new OO.ui.PanelLayout({ padded: true, expanded: false });
                this.content = new OO.ui.FieldsetLayout();
                  
                  
                 const panel = new OO.ui.PanelLayout({
                 printOptions.questions.forEach(function (question) {
                    padded: true,
                    expanded: false
                });
               
                const fieldset = new OO.ui.FieldsetLayout({
                    label: mw.message('print-options').plain()
                });
 
                PrintEnhancer.questions.forEach(question => {
                     if (question.type === 'checkbox') {
                     if (question.type === 'checkbox') {
                         const checkbox = new OO.ui.CheckboxInputWidget({
                         var checkbox = new OO.ui.CheckboxInputWidget({
                             selected: PrintEnhancer.config[question.returnvalue]
                             selected: question.checked
                         });
                         });
                          
                         question.widget = checkbox;
                         fieldset.addItems([
                         this.content.addItems([
                             new OO.ui.FieldLayout(checkbox, {
                             new OO.ui.FieldLayout(checkbox, {
                                 label: question.label,
                                 label: question.label,
                                 align: 'inline',
                                 align: 'inline'
                                help: question.help ? mw.message(question.help).plain() : null
                             })
                             })
                         ]);
                         ]);
                       
                        question.widget = checkbox;
                     }
                     }
                 });
                 }, this);
 
               
                 panel.$element.append(fieldset.$element);
                 this.panel.$element.append(this.content.$element);
                 this.$body.append(panel.$element);
                 this.$body.append(this.panel.$element);
             };
             };
PrintDialog.prototype.getActionProcess = function(action) {
    if (action === 'print') {
        return new OO.ui.Process(() => {
            // 1. 先保存用户选择的配置
            PrintEnhancer.questions.forEach(q => {
                if (q.type === 'checkbox' && q.widget) {
                    PrintEnhancer.config[q.returnvalue] = q.widget.isSelected();
                }
            });
              
              
             // 2. 关闭对话框
             // ✅ 修复点:明确处理取消动作
             return this.close({ action }).then(() => {
             PrintDialog.prototype.getActionProcess = function (action) {
                // 3. 应用打印样式(必须同步完成)
                if (action === 'print') {
                PrintEnhancer.applyPrintStyles();
                     return new OO.ui.Process(function () {
               
                         printOptions.questions.forEach(function (question) {
                // 4. 延迟确保样式生效后再触发打印
                             if (question.widget) {
                setTimeout(() => {
                                 printOptions[question.returnvalue] = question.widget.isSelected();
                    window.print();
                   
                    // 5. 打印完成后恢复页面
                    setTimeout(() => location.reload(), 1000);
                }, 300); // 300ms足够CSS注入完成
            });
        });
    }
    return PrintDialog.super.prototype.getActionProcess.call(this, action);
};
 
            if (!this.windowManager) {
                this.windowManager = new OO.ui.WindowManager();
                $('body').append(this.windowManager.$element);
            }
 
            this.printDialog = new PrintDialog({ size: 'medium' });
            this.windowManager.addWindows([this.printDialog]);
            this.windowManager.openWindow(this.printDialog);
        },
 
        applyPrintStyles() {
            let printStyle = '';
            const { config } = this;
 
            if (config.enhanced) {
                Array.from(document.styleSheets).forEach(sheet => {
                     if (!sheet.media) return;
                   
                    try {
                        if (sheet.media.mediaText.includes('print') &&
                            !sheet.media.mediaText.includes('screen')) {
                            sheet.disabled = true;
                        }
                       
                        if (sheet.media.mediaText.includes('screen') &&
                            !sheet.media.mediaText.includes('print')) {
                            sheet.media.appendMedium('print');
                        }
                       
                        const rules = sheet.cssRules || sheet.rules;
                        if (!rules) return;
                       
                         Array.from(rules).forEach((rule, index) => {
                             if (rule.type === CSSRule.MEDIA_RULE && rule.media) {
                                 const media = Array.from(rule.media);
                                const hasPrint = media.includes('print');
                                const hasScreen = media.includes('screen');
                               
                                if (hasPrint && !hasScreen) {
                                    sheet.deleteRule(index);
                                } else if (hasScreen && !hasPrint) {
                                    rule.media.appendMedium('print');
                                }
                             }
                             }
                         });
                         });
                      
                        return this.close({ action: action }).then(function () {
                     } catch (e) {
                            printOptions.changePrintCSS();
                         mw.log.warn('PrintEnhancer: Could not process stylesheet', sheet.href, e);
                            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) {
             if (config.noimages) {
                 printDialog = new PrintDialog({ size: 'medium' });
                 printStyle += 'img, .thumb, figure, .gallerybox { display:none !important; }';
                windowManager.addWindows([printDialog]);
             }
             }
             if (config.norefs) {
            windowManager.openWindow(printDialog);
                printStyle += `.references, .reference,
        },
                              .mw-references-wrap,
       
                              .citation, .cite_journal {  
        changePrintCSS: function () {
                                  display:none !important;  
            /* 原有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>');
             }
             }
            if (config.notoc) {
        },
                printStyle += '#toc, .toc, .toccolours { display:none !important; }';
       
             }
        otherEnhancements: function () {
            if (config.nobackground) {
            var $link = $('div.printfooter a');
                 printStyle += '* { background:none !important; }';
             try {
            }
                 $link.text(decodeURIComponent($link.text()));
            if (config.blacktext) {
             } catch (e) {
                printStyle += '* { color:#000 !important; }';
                 mw.log.warn('URL解码失败:', e);
             }
 
            if (printStyle) {
                 const style = document.createElement('style');
                style.setAttribute('media', 'print');
                style.textContent = printStyle;
                document.head.appendChild(style);
             }
             }
         },
         },
 
       
         questions: [
         questions: [
             {
             {
                 label: mw.message('print-option-enhance').plain(),
                 label: '隐藏界面元素',
                 type: 'checkbox',
                 type: 'checkbox',
                 help: 'print-option-enhance-help',
                 checked: true,
                 returnvalue: 'enhanced'
                 returnvalue: 'enhanced'
             },
             },
             {
             {
                 label: mw.message('print-option-noimages').plain(),
                 label: '隐藏图像',
                 type: 'checkbox',
                 type: 'checkbox',
                checked: false,
                 returnvalue: 'noimages'
                 returnvalue: 'noimages'
             },
             },
             {
             {
                 label: mw.message('print-option-norefs').plain(),
                 label: '隐藏引用',
                 type: 'checkbox',
                 type: 'checkbox',
                checked: false,
                 returnvalue: 'norefs'
                 returnvalue: 'norefs'
             },
             },
             {
             {
                 label: mw.message('print-option-notoc').plain(),
                 label: '隐藏目录',
                 type: 'checkbox',
                 type: 'checkbox',
                checked: false,
                 returnvalue: 'notoc'
                 returnvalue: 'notoc'
             },
             },
             {
             {
                 label: mw.message('print-option-nobg').plain(),
                 label: '删除背景(部分浏览器可能无效)',
                 type: 'checkbox',
                 type: 'checkbox',
                 help: 'print-option-nobg-help',
                 checked: false,
                 returnvalue: 'nobackground'
                 returnvalue: 'nobackground'
             },
             },
             {
             {
                 label: mw.message('print-option-blacktext').plain(),
                 label: '强制文本为黑色',
                 type: 'checkbox',
                 type: 'checkbox',
                checked: true,
                 returnvalue: 'blacktext'
                 returnvalue: 'blacktext'
             }
             }
         ]
         ]
     };
     };
 
   
     mw.messages.set({
    // 延迟初始化以避免冲突
        'print-version': '可打印版本',
     $(function () {
        'print-dialog-title': '打印选项',
        if (mw.config.get('wgNamespaceNumber') >= 0) {
         'print-options': '打印设置',
            setTimeout(printOptions.install, 100);
        '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);
        }
    });
})();