MediaWiki:Gadget-PrintOptions.js
外观
	
	
注意:在发布之后,您可能需要清除浏览器缓存才能看到所作出的更改的影响。
- Firefox或Safari:按住Shift的同时单击刷新,或按Ctrl-F5或Ctrl-R(Mac为⌘-R)
 - Google Chrome:按Ctrl-Shift-R(Mac为⌘-Shift-R)
 - Edge:按住Ctrl的同时单击刷新,或按Ctrl-F5。
 
(function() {
    'use strict';
    const PrintEnhancer = {
        windowManager: null,
        printDialog: null,
        
        config: {
            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) {
                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, 
                    expanded: false 
                });
                
                const fieldset = new OO.ui.FieldsetLayout({
                    label: mw.message('print-options').plain()
                });
                PrintEnhancer.questions.forEach(question => {
                    if (question.type === 'checkbox') {
                        const checkbox = new OO.ui.CheckboxInputWidget({
                            selected: PrintEnhancer.config[question.returnvalue]
                        });
                        
                        fieldset.addItems([
                            new OO.ui.FieldLayout(checkbox, {
                                label: question.label,
                                align: 'inline',
                                help: question.help ? mw.message(question.help).plain() : null
                            })
                        ]);
                        
                        question.widget = checkbox;
                    }
                });
                panel.$element.append(fieldset.$element);
                this.$body.append(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(() => {
                // 3. 应用打印样式(必须同步完成)
                PrintEnhancer.applyPrintStyles();
                
                // 4. 延迟确保样式生效后再触发打印
                setTimeout(() => {
                    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');
                                }
                            }
                        });
                    
                    } catch (e) {
                        mw.log.warn('PrintEnhancer: Could not process stylesheet', sheet.href, e);
                    }
                });
            }
            if (config.noimages) {
                printStyle += 'img, .thumb, figure, .gallerybox { display:none !important; }';
            }
            if (config.norefs) {
                printStyle += `.references, .reference, 
                              .mw-references-wrap, 
                              .citation, .cite_journal { 
                                  display:none !important; 
                              }`;
            }
            if (config.notoc) {
                printStyle += '#toc, .toc, .toccolours { display:none !important; }';
            }
            if (config.nobackground) {
                printStyle += '* { background:none !important; }';
            }
            if (config.blacktext) {
                printStyle += '* { color:#000 !important; }';
            }
            if (printStyle) {
                const style = document.createElement('style');
                style.setAttribute('media', 'print');
                style.textContent = printStyle;
                document.head.appendChild(style);
            }
        },
        questions: [
            {
                label: mw.message('print-option-enhance').plain(),
                type: 'checkbox',
                help: 'print-option-enhance-help',
                returnvalue: 'enhanced'
            },
            {
                label: mw.message('print-option-noimages').plain(),
                type: 'checkbox',
                returnvalue: 'noimages'
            },
            {
                label: mw.message('print-option-norefs').plain(),
                type: 'checkbox',
                returnvalue: 'norefs'
            },
            {
                label: mw.message('print-option-notoc').plain(),
                type: 'checkbox',
                returnvalue: 'notoc'
            },
            {
                label: mw.message('print-option-nobg').plain(),
                type: 'checkbox',
                help: 'print-option-nobg-help',
                returnvalue: 'nobackground'
            },
            {
                label: mw.message('print-option-blacktext').plain(),
                type: 'checkbox',
                returnvalue: 'blacktext'
            }
        ]
    };
    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());
}());