跳转到内容

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

勤求古训,博采众方
无编辑摘要
无编辑摘要
标签已被回退
第1行: 第1行:
(function () {
/*! PrintDialog v3.0 - 支持多语言&快捷键 */
(function (mw, $) {
     'use strict';
     'use strict';
      
      
     var windowManager;
    // 🌐 本地化文本库
     var printDialog;
     var i18n = {
   
        'title': mw.message('printdialog-title').plain() || '打印选项',
     var printOptions = {
        'print-btn': mw.message('printdialog-print-btn').plain() || '打印',
         install: function () {
        'cancel-btn': mw.message('printdialog-cancel-btn').plain() || '取消',
             var $printLink = $('#t-print a');
        'loading': mw.message('printdialog-loading').plain() || '准备打印中...',
             if ($printLink.length === 0) return;
        '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;
              
              
             $printLink
            // 绑定打印按钮
                .text('可打印版本')
             $('#t-print a').first()
                .off('click')
                 .text(mw.message('printdialog-link-text').plain() || '可打印版本')
                 .on('click', function (e) {
                .off('click.print')
                    mw.loader.using(['oojs-ui-core', 'oojs-ui-widgets', 'oojs-ui-windows'])
                .on('click.print', this.onPrintClick.bind(this));
                        .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']);
             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();
                    }
                });
         },
         },
          
          
         createWindow: function () {
         // 🏗️ 创建对话框
             function PrintDialog(config) {
        createDialog: function () {
                 PrintDialog.super.call(this, config);
            if (this.dialog) {
                this.windowManager.openWindow(this.dialog);
                return;
            }
           
            // 对话框构造函数
             function Dialog(config) {
                 Dialog.super.call(this, config);
             }
             }
             OO.inheritClass(PrintDialog, OO.ui.ProcessDialog);
             OO.inheritClass(Dialog, OO.ui.ProcessDialog);
              
              
             PrintDialog.static.name = 'printdialog';
             // 静态配置(使用本地化文本)
             PrintDialog.static.title = '打印此页面';
            Dialog.static.name = 'printDialog';
             PrintDialog.static.actions = [
             Dialog.static.title = i18n.title;
                 { action: 'print', label: '打印', flags: ['primary', 'progressive'] },
             Dialog.static.actions = [
                 { action: 'cancel', label: '取消', flags: 'safe' }
                 {  
                    action: 'print',  
                    label: i18n['print-btn'],
                    flags: ['primary', 'progressive'],
                    icon: 'printer'
                },
                 {  
                    action: 'cancel',  
                    label: i18n['cancel-btn'],  
                    flags: 'safe',
                    icon: 'close'
                }
             ];
             ];
              
              
             PrintDialog.prototype.initialize = function () {
             // 初始化内容
                 PrintDialog.super.prototype.initialize.apply(this, arguments);
            Dialog.prototype.initialize = function () {
                 this.panel = new OO.ui.PanelLayout({ padded: true, expanded: false });
                 Dialog.super.prototype.initialize.apply(this, arguments);
                 this.content = new OO.ui.FieldsetLayout();
                 this.buildForm();
            };
           
            // 构建表单(本地化选项)
            Dialog.prototype.buildForm = function () {
                var panel = new OO.ui.PanelLayout({ padded: true });
                 var fieldset = new OO.ui.FieldsetLayout();
                  
                  
                 printOptions.questions.forEach(function (question) {
                 PrintDialog.options.forEach(function (opt) {
                     if (question.type === 'checkbox') {
                     if (opt.type === 'checkbox') {
                         var checkbox = new OO.ui.CheckboxInputWidget({
                         var widget = new OO.ui.CheckboxInputWidget({
                             selected: question.checked
                             selected: !!opt.default
                         });
                         });
                         question.widget = checkbox;
                          
                         this.content.addItems([
                         fieldset.addItems([
                             new OO.ui.FieldLayout(checkbox, {
                             new OO.ui.FieldLayout(widget, {
                                 label: question.label,
                                 label: i18n.options[opt.id] || opt.id,
                                 align: 'inline'
                                 align: 'inline',
                                help: i18n.help[opt.id] ?
                                    new OO.ui.LabelWidget({ label: i18n.help[opt.id] }) : null
                             })
                             })
                         ]);
                         ]);
                       
                        opt.widget = widget; // 保存引用
                     }
                     }
                 }, this);
                 });
                  
                  
                 this.panel.$element.append(this.content.$element);
                 panel.$element.append(fieldset.$element);
                 this.$body.append(this.panel.$element);
                 this.$body.append(panel.$element);
             };
             };
              
              
             // ✅ 修复点:明确处理取消动作
             // 处理动作(含快捷键支持)
             PrintDialog.prototype.getActionProcess = function (action) {
             Dialog.prototype.getActionProcess = function (action) {
                 if (action === 'print') {
                 if (action === 'print') {
                     return new OO.ui.Process(function () {
                     return new OO.ui.Process(function () {
                        printOptions.questions.forEach(function (question) {
                         return this.executePrintAction();
                            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));
                     }.bind(this));
                 }
                 }
                 return PrintDialog.super.prototype.getActionProcess.call(this, action);
                 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 (!windowManager) {
            // 初始化窗口管理器
                 windowManager = new OO.ui.WindowManager();
             if (!this.windowManager) {
                 $('body').append(windowManager.$element);
                 this.windowManager = new OO.ui.WindowManager();
                 $('body').append(this.windowManager.$element);
             }
             }
             if (!printDialog) {
              
                printDialog = new PrintDialog({ size: 'medium' });
            // 创建对话框实例
                windowManager.addWindows([printDialog]);
            this.dialog = new Dialog({ size: 'medium' });
             }
            this.windowManager.addWindows([this.dialog]);
            windowManager.openWindow(printDialog);
             this.windowManager.openWindow(this.dialog);
         },
         },
          
          
         changePrintCSS: function () {
         // 🎨 应用打印样式
            /* 原有CSS处理逻辑 */
        applyPrintStyles: function () {
             var printStyle = '';
             var style = [];
             if (this.noimages) printStyle += 'img, .thumb { display:none !important; }\n';
              
             if (this.norefs) printStyle += '.references, .reference { display:none !important; }\n';
             if (PrintDialog.settings.hideImages) {
            if (this.notoc) printStyle += '#toc, .toc { display:none !important; }\n';
                style.push('img, .thumb { display:none !important; }');
            if (this.nobackground) printStyle += 'body { background: white !important; }\n';
             }
             if (this.blacktext) printStyle += '* { color: black !important; }\n';
              
              
             $('style[media="print"]').remove(); // 清理旧样式
            // 清理旧样式并添加新样式
             if (printStyle) {
             $('style.print-styles').remove();
                 $('head').append('<style media="print">' + printStyle + '</style>');
             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';
            });
         },
         },
          
          
         otherEnhancements: function () {
         // 🖨️ 主入口处理
             var $link = $('div.printfooter a');
        onPrintClick: function (e) {
             try {
            e.preventDefault();
                 $link.text(decodeURIComponent($link.text()));
           
            } catch (e) {
             var notification = mw.notify(
                mw.log.warn('URL解码失败:', e);
                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();
                });
         },
         },
          
          
         questions: [
         // ⚙️ 可配置选项
        options: [
             {
             {
                 label: '隐藏界面元素',
                 id: 'hideImages',
                 type: 'checkbox',
                 type: 'checkbox',
                 checked: true,
                 default: false
                returnvalue: 'enhanced'
             },
             },
             {
             {
                 label: '隐藏图像',
                 id: 'hideRefs',
                 type: 'checkbox',
                 type: 'checkbox',
                 checked: false,
                 default: false
                returnvalue: 'noimages'
             }
             },
        ],
            {
       
                label: '隐藏引用',
        // 🗃️ 状态存储
                type: 'checkbox',
        settings: {},
                checked: false,
       
                returnvalue: 'norefs'
        // ♻️ 清理方法
            },
        destroy: function () {
            {
             $(document).off('keydown.printdialog');
                label: '隐藏目录',
             if (this.windowManager) {
                type: 'checkbox',
                 this.windowManager.destroy();
                checked: false,
                 this.windowManager = null;
                returnvalue: 'notoc'
            },
             {
                label: '删除背景(部分浏览器可能无效)',
                type: 'checkbox',
                checked: false,
                returnvalue: 'nobackground'
             },
            {
                 label: '强制文本为黑色',
                type: 'checkbox',
                checked: true,
                 returnvalue: 'blacktext'
             }
             }
         ]
            this.dialog = null;
         }
     };
     };
      
      
     // 延迟初始化以避免冲突
     // 📅 延迟初始化
     $(function () {
     mw.hook('wikipage.content').add(function () {
         if (mw.config.get('wgNamespaceNumber') >= 0) {
         setTimeout(PrintDialog.init.bind(PrintDialog), 300);
            setTimeout(printOptions.install, 100);
        }
     });
     });
})();
   
    // 🖇️ 暴露到全局(可选)
    window.PrintDialog = PrintDialog;
})(mediaWiki, jQuery);

2025年11月1日 (六) 21:56的版本

/*! 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);