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。
 
/*! PrintDialog v3.0 - 支持多语言&快捷键 */
(function (mw, $) {
    'use strict';
    
    // 🌐 本地化文本库
    var i18n = {
        'title': mw.message('printdialog-title').plain() || '打印选项',
        'print-btn': mw.message('printdialog-print-btn').plain() || '打印',
        'cancel-btn': mw.message('printdialog-cancel-btn').plain() || '取消',
        'loading': mw.message('printdialog-loading').plain() || '准备打印中...',
        'print-error': mw.message('printdialog-error').plain() || '打印失败:$1',
        'no-print-support': mw.message('printdialog-no-support').plain() || '您的浏览器不支持直接打印',
        // 选项文本
        'options': {
            'hideImages': mw.message('printdialog-opt-hide-images').plain() || '隐藏图片',
            'hideRefs': mw.message('printdialog-opt-hide-refs').plain() || '隐藏参考文献'
            // 可继续扩展其他选项...
        },
        'help': {
            'hideImages': mw.message('printdialog-help-hide-images').plain() || '不打印页面中的图片和缩略图'
        }
    };
    var PrintDialog = {
        // ⚙️ 配置项
        config: {
            debug: false,
            dependencies: ['oojs-ui-core', 'oojs-ui-widgets', 'oojs-ui-windows'],
            hotkeys: {
                print: 'ctrl+enter', // 打印快捷键
                cancel: 'esc'        // 取消快捷键
            }
        },
        
        // 🚀 初始化
        init: function () {
            if (!this.shouldInit()) return;
            
            // 绑定打印按钮
            $('#t-print a').first()
                .text(mw.message('printdialog-link-text').plain() || '可打印版本')
                .off('click.print')
                .on('click.print', this.onPrintClick.bind(this));
            
            // 预加载资源
            if (!this.isDepsLoaded()) {
                mw.loader.load(this.config.dependencies);
            }
            
            // 注册全局快捷键(需确保唯一性)
            this.registerHotkeys();
        },
        
        // 🔥 快捷键支持
        registerHotkeys: function () {
            $(document).off('keydown.printdialog')
                .on('keydown.printdialog', function (e) {
                    if (!PrintDialog.dialog || !PrintDialog.windowManager) return;
                    
                    // ESC - 取消
                    if (e.key === 'Escape') {
                        PrintDialog.dialog.executeAction('cancel');
                        e.preventDefault();
                    }
                    
                    // Ctrl+Enter - 打印
                    if (e.ctrlKey && e.key === 'Enter') {
                        PrintDialog.dialog.executeAction('print');
                        e.preventDefault();
                    }
                });
        },
        
        // 🏗️ 创建对话框
        createDialog: function () {
            if (this.dialog) {
                this.windowManager.openWindow(this.dialog);
                return;
            }
            
            // 对话框构造函数
            function Dialog(config) {
                Dialog.super.call(this, config);
            }
            OO.inheritClass(Dialog, OO.ui.ProcessDialog);
            
            // 静态配置(使用本地化文本)
            Dialog.static.name = 'printDialog';
            Dialog.static.title = i18n.title;
            Dialog.static.actions = [
                { 
                    action: 'print', 
                    label: i18n['print-btn'],
                    flags: ['primary', 'progressive'],
                    icon: 'printer'
                },
                { 
                    action: 'cancel', 
                    label: i18n['cancel-btn'], 
                    flags: 'safe',
                    icon: 'close'
                }
            ];
            
            // 初始化内容
            Dialog.prototype.initialize = function () {
                Dialog.super.prototype.initialize.apply(this, arguments);
                this.buildForm();
            };
            
            // 构建表单(本地化选项)
            Dialog.prototype.buildForm = function () {
                var panel = new OO.ui.PanelLayout({ padded: true });
                var fieldset = new OO.ui.FieldsetLayout();
                
                PrintDialog.options.forEach(function (opt) {
                    if (opt.type === 'checkbox') {
                        var widget = new OO.ui.CheckboxInputWidget({
                            selected: !!opt.default
                        });
                        
                        fieldset.addItems([
                            new OO.ui.FieldLayout(widget, {
                                label: i18n.options[opt.id] || opt.id,
                                align: 'inline',
                                help: i18n.help[opt.id] ? 
                                    new OO.ui.LabelWidget({ label: i18n.help[opt.id] }) : null
                            })
                        ]);
                        
                        opt.widget = widget; // 保存引用
                    }
                });
                
                panel.$element.append(fieldset.$element);
                this.$body.append(panel.$element);
            };
            
            // 处理动作(含快捷键支持)
            Dialog.prototype.getActionProcess = function (action) {
                if (action === 'print') {
                    return new OO.ui.Process(function () {
                        return this.executePrintAction();
                    }.bind(this));
                }
                return Dialog.super.prototype.getActionProcess.call(this, action);
            };
            
            // 执行打印(拆分为独立方法)
            Dialog.prototype.executePrintAction = function () {
                // 保存设置
                PrintDialog.options.forEach(function (opt) {
                    PrintDialog.settings[opt.id] = opt.widget.isSelected();
                });
                
                // 关闭窗口并处理打印
                return this.close({ action: 'print' })
                    .then(PrintDialog.applyPrintStyles)
                    .then(function () {
                        if (typeof window.print === 'function') {
                            window.print();
                        } else {
                            mw.notify(i18n['no-print-support'], { type: 'warning' });
                        }
                    })
                    .catch(function (err) {
                        mw.notify(i18n['print-error'].replace('$1', err.message), { type: 'error' });
                    });
            };
            
            // 初始化窗口管理器
            if (!this.windowManager) {
                this.windowManager = new OO.ui.WindowManager();
                $('body').append(this.windowManager.$element);
            }
            
            // 创建对话框实例
            this.dialog = new Dialog({ size: 'medium' });
            this.windowManager.addWindows([this.dialog]);
            this.windowManager.openWindow(this.dialog);
        },
        
        // 🎨 应用打印样式
        applyPrintStyles: function () {
            var style = [];
            
            if (PrintDialog.settings.hideImages) {
                style.push('img, .thumb { display:none !important; }');
            }
            
            // 清理旧样式并添加新样式
            $('style.print-styles').remove();
            if (style.length) {
                $('<style>')
                    .addClass('print-styles')
                    .attr('media', 'print')
                    .text(style.join('\n'))
                    .appendTo('head');
            }
            
            return Promise.resolve();
        },
        
        // ✅ 工具方法
        shouldInit: function () {
            return mw.config.get('wgNamespaceNumber') >= 0;
        },
        
        isDepsLoaded: function () {
            return this.config.dependencies.every(function (dep) {
                return mw.loader.getState(dep) === 'ready';
            });
        },
        
        // 🖨️ 主入口处理
        onPrintClick: function (e) {
            e.preventDefault();
            
            var notification = mw.notify(
                new OO.ui.ProgressBarWidget({ progress: false }).$element, 
                { 
                    title: i18n.loading,
                    autoHide: false
                }
            );
            
            mw.loader.using(this.config.dependencies)
                .then(this.createDialog.bind(this))
                .catch(function (err) {
                    mw.notify(i18n['print-error'].replace('$1', err.message), { type: 'error' });
                })
                .always(function () {
                    notification.close();
                });
        },
        
        // ⚙️ 可配置选项
        options: [
            {
                id: 'hideImages',
                type: 'checkbox',
                default: false
            },
            {
                id: 'hideRefs',
                type: 'checkbox',
                default: false
            }
        ],
        
        // 🗃️ 状态存储
        settings: {},
        
        // ♻️ 清理方法
        destroy: function () {
            $(document).off('keydown.printdialog');
            if (this.windowManager) {
                this.windowManager.destroy();
                this.windowManager = null;
            }
            this.dialog = null;
        }
    };
    
    // 📅 延迟初始化
    mw.hook('wikipage.content').add(function () {
        setTimeout(PrintDialog.init.bind(PrintDialog), 300);
    });
    
    // 🖇️ 暴露到全局(可选)
    window.PrintDialog = PrintDialog;
})(mediaWiki, jQuery);