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

勤求古训,博采众方
跳转到导航 跳转到搜索
删除的内容 添加的内容
小无编辑摘要
标签:已被回退
小无编辑摘要
标签:手工回退
第1行: 第1行:
(function () {
/*! PrintDialog v3.0 - 支持多语言&快捷键 */
(function (mw, $) {
'use strict';
'use strict';
var windowManager;
// 🌐 本地化文本库
var i18n = {
var printDialog;
'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() || '不打印页面中的图片和缩略图',
'hideRefs': mw.message('printdialog-help-hide-refs').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
if (!this.isDepsLoaded()) {
.text('可打印版本')
mw.loader.load(this.config.dependencies);
.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']);
$('#t-print a').first()
.text(mw.message('printdialog-link-text').plain() || '可打印版本')
.off('click.print')
.on('click.print', this.onPrintClick.bind(this));
this.registerHotkeys();
if (this.config.debug) {
console.log('PrintDialog initialized');
}
},
},
// 🔥 快捷键支持
createWindow: function () {
registerHotkeys: function () {
function PrintDialog(config) {
$(document).off('keydown.printdialog')
PrintDialog.super.call(this, config);
.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();
}
});
},
// 🏗️ 创建对话框类
createDialogClass: function () {
var self = this;
function Dialog(config) {
Dialog.super.call(this, config);
}
}
OO.inheritClass(Dialog, OO.ui.ProcessDialog);
OO.inheritClass(PrintDialog, OO.ui.ProcessDialog);
// 静态配置
PrintDialog.static.name = 'printdialog';
Dialog.static.name = 'printDialog';
PrintDialog.static.title = '打印此页面';
Dialog.static.title = i18n.title;
PrintDialog.static.actions = [
{ 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 () {
Dialog.prototype.initialize = function () {
PrintDialog.super.prototype.initialize.apply(this, arguments);
Dialog.super.prototype.initialize.apply(this, arguments);
this.panel = new OO.ui.PanelLayout({ padded: true, expanded: false });
this.buildForm();
this.content = new OO.ui.FieldsetLayout();
if (self.config.debug) {
printOptions.questions.forEach(function (question) {
console.log('PrintDialog: Dialog initialized');
if (question.type === 'checkbox') {
}
var checkbox = new OO.ui.CheckboxInputWidget({
};
selected: question.checked
// 构建表单
Dialog.prototype.buildForm = function () {
var panel = new OO.ui.PanelLayout({ padded: true });
var fieldset = new OO.ui.FieldsetLayout({
label: mw.message('printdialog-options-title').plain() || '打印选项'
});
// 初始化选项部件存储
self.optionWidgets = {};
self.options.forEach(function (opt) {
if (opt.type === 'checkbox') {
var widget = new OO.ui.CheckboxInputWidget({
selected: !!opt.default
});
});
question.widget = checkbox;
// 保存部件引用
this.content.addItems([
self.optionWidgets[opt.id] = widget;
new OO.ui.FieldLayout(checkbox, {
label: question.label,
var fieldLayout = new OO.ui.FieldLayout(widget, {
align: 'inline'
label: i18n.options[opt.id] || opt.id,
})
align: 'inline',
]);
help: i18n.help[opt.id] ?
new OO.ui.LabelWidget({
label: i18n.help[opt.id]
}) : null
});
fieldset.addItems([fieldLayout]);
}
}
});
}, this);
panel.$element.append(fieldset.$element);
this.panel.$element.append(this.content.$element);
this.$body.append(panel.$element);
this.$body.append(this.panel.$element);
if (self.config.debug) {
console.log('PrintDialog: Form built with options', self.options);
}
};
};
// 处理动作
// ✅ 修复点:明确处理取消动作
Dialog.prototype.getActionProcess = function (action) {
PrintDialog.prototype.getActionProcess = function (action) {
if (action === 'print') {
if (action === 'print') {
return new OO.ui.Process(function () {
return new OO.ui.Process(function () {
return this.executePrintAction();
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));
}.bind(this));
}
}
// 🔥 关键修复:取消时直接关闭对话框
return Dialog.super.prototype.getActionProcess.call(this, action);
};
if (action === 'cancel') {
return new OO.ui.Process(function () {
// 执行打印
return this.close({ action: action });
Dialog.prototype.executePrintAction = function () {
}.bind(this));
var process = new OO.ui.Process();
// 保存设置
if (self.optionWidgets) {
Object.keys(self.optionWidgets).forEach(function (key) {
self.settings[key] = self.optionWidgets[key].isSelected();
});
}
}
return PrintDialog.super.prototype.getActionProcess.call(this, action);
if (self.config.debug) {
console.log('PrintDialog: Settings saved', self.settings);
}
// 关闭窗口
return this.close({ action: 'print' })
.then(function () {
return self.applyPrintStyles();
})
.then(function () {
// 延迟确保样式已应用
return new Promise(function (resolve) {
setTimeout(function () {
if (typeof window.print === 'function') {
window.print();
resolve();
} else {
throw new Error(i18n['no-print-support']);
}
}, 100);
});
})
.catch(function (err) {
mw.notify(
i18n['print-error'].replace('$1', err.message),
{ type: 'error', tag: 'printdialog' }
);
throw err; // 重新抛出以保持错误链
});
};
};
return Dialog;
if (!windowManager) {
windowManager = new OO.ui.WindowManager();
},
$('body').append(windowManager.$element);
// 🏗️ 创建对话框实例
createDialog: function () {
if (this.dialog && this.windowManager) {
this.windowManager.openWindow(this.dialog);
return Promise.resolve();
}
}
if (!printDialog) {
printDialog = new PrintDialog({ size: 'medium' });
// 初始化窗口管理器
if (!this.windowManager) {
windowManager.addWindows([printDialog]);
this.windowManager = new OO.ui.WindowManager();
$('body').append(this.windowManager.$element);
}
}
windowManager.openWindow(printDialog);
// 创建对话框类(如果不存在)
if (!this.DialogClass) {
this.DialogClass = this.createDialogClass();
}
// 创建对话框实例
this.dialog = new this.DialogClass({
size: 'medium'
});
this.windowManager.addWindows([this.dialog]);
return this.windowManager.openWindow(this.dialog);
},
},
changePrintCSS: function () {
// 🎨 应用打印样式
/* 原有CSS处理逻辑 */
applyPrintStyles: function () {
var style = [];
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 (this.settings.hideImages) {
if (printStyle) {
style.push(
$('head').append('<style media="print">' + printStyle + '</style>');
'img, .thumb, .gallery, .image, .thumbinner, .thumbimage { ' +
'display:none !important; }'
);
}
}
// 隐藏参考文献
if (this.settings.hideRefs) {
style.push(
'.references, .ref-list, #References, .reflist, .citation { ' +
'display:none !important; }'
);
}
// 清理旧样式
$('style.print-styles').remove();
// 添加新样式
if (style.length > 0) {
$('<style>')
.addClass('print-styles')
.attr('media', 'print')
.attr('type', 'text/css')
.text(style.join('\n'))
.appendTo('head');
if (this.config.debug) {
console.log('PrintDialog: Applied print styles', style);
}
}
return Promise.resolve();
},
},
otherEnhancements: function () {
// 🖨️ 主入口处理
var $link = $('div.printfooter a');
onPrintClick: function (e) {
e.preventDefault();
try {
$link.text(decodeURIComponent($link.text()));
if (this.config.debug) {
} catch (e) {
console.log('PrintDialog: Print button clicked');
mw.log.warn('URL解码失败:', e);
}
}
// 创建加载通知
var progressBar = new OO.ui.ProgressBarWidget({ progress: false });
var notification = mw.notify(progressBar.$element, {
title: i18n.loading,
autoHide: false,
tag: 'printdialog-loading'
});
// 确保依赖已加载并创建对话框
mw.loader.using(this.config.dependencies)
.then(this.createDialog.bind(this))
.catch(function (err) {
console.error('PrintDialog: Error creating dialog', err);
mw.notify(
i18n['print-error'].replace('$1', err.message),
{ type: 'error', tag: 'printdialog' }
);
})
.always(function () {
notification.close();
});
},
},
// ✅ 工具方法
questions: [
shouldInit: function () {
// 只在内容命名空间显示
return mw.config.get('wgNamespaceNumber') >= 0 &&
$('#t-print').length > 0;
},
isDepsLoaded: function () {
return this.config.dependencies.every(function (dep) {
var state = mw.loader.getState(dep);
return state === 'ready' || state === 'loaded';
});
},
// ⚙️ 可配置选项
options: [
{
{
id: 'hideImages',
label: '隐藏界面元素',
type: 'checkbox',
type: 'checkbox',
default: false,
checked: true,
description: 'Hide images and thumbnails in print'
returnvalue: 'enhanced'
},
},
{
{
id: 'hideRefs',
label: '隐藏图像',
type: 'checkbox',
type: 'checkbox',
default: false,
checked: false,
description: 'Hide references and citations in print'
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'
}
}
],
]
// 🗃️ 状态存储
settings: {},
optionWidgets: null,
// ♻️ 清理方法
destroy: function () {
$(document).off('keydown.printdialog');
if (this.windowManager) {
this.windowManager.destroy();
this.windowManager = null;
}
$('style.print-styles').remove();
this.dialog = null;
this.DialogClass = null;
this.optionWidgets = null;
if (this.config.debug) {
console.log('PrintDialog: Destroyed');
}
}
};
};
// 📅 延迟初始化
// 延迟初始化以避免冲突
mw.hook('wikipage.content').add(function () {
$(function () {
if (mw.config.get('wgNamespaceNumber') >= 0) {
// 等待页面完全加载后再初始化
setTimeout(printOptions.install, 100);
if (document.readyState === 'loading') {
$(document).ready(function () {
setTimeout(PrintDialog.init.bind(PrintDialog), 300);
});
} else {
setTimeout(PrintDialog.init.bind(PrintDialog), 300);
}
}
});
});
})();
// 🖇️ 暴露到全局
window.PrintDialog = PrintDialog;
if (PrintDialog.config.debug) {
console.log('PrintDialog: Module loaded');
}
})(mediaWiki, jQuery);

2025年11月1日 (六) 22:28的版本

(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);
        }
    });
})();