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

勤求古训,博采众方
跳转到导航 跳转到搜索
删除的内容 添加的内容
无编辑摘要
小无编辑摘要
第1行: 第1行:
// ==UserScript==
// ==UserScript==
// @name MediaWiki打印增强
// @name MediaWiki打印增强
// @description 为MediaWiki添加高级打印选项(优化布局、图片控制等)
// @description 高级打印选项(优化布局/隐藏图片等)
// @namespace https://github.com/yourname/
// @namespace https://github.com/yourname/
// @version 1.1
// @version 2.0
// @license MIT
// @match *://*/*
// @match *://*/*
// @grant none
// @grant none
// @require https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js
// ==/UserScript==
// ==/UserScript==


第14行: 第14行:
// ============== 核心配置 ==============
// ============== 核心配置 ==============
const PrintEnhancer = {
const PrintEnhancer = {
// 默认配置
config: {
config: {
enhanced: true,
enhanced: true,
第23行: 第24行:
},
},


// 对话框选项
questions: [
questions: [
{
{
type: 'checkbox',
type: 'checkbox',
returnvalue: 'enhanced',
name: 'enhanced',
⚫
label: '优化打印布局',
label: mw.message('print-option-enhance').plain(),
help: 'print-option-enhance-help'
help: '隐藏编辑按钮等非必要元素'
},
},
{
{
type: 'checkbox',
type: 'checkbox',
returnvalue: 'noimages',
name: 'noimages',
label: mw.message('print-option-noimages').plain()
label: '隐藏所有图片'
},
},
{
{
type: 'checkbox',
type: 'checkbox',
returnvalue: 'norefs',
name: 'norefs',
label: mw.message('print-option-norefs').plain()
label: '隐藏参考文献'
},
},
{
{
type: 'checkbox',
type: 'checkbox',
returnvalue: 'notoc',
name: 'notoc',
label: mw.message('print-option-notoc').plain()
label: '隐藏目录'
},
},
{
{
type: 'checkbox',
type: 'checkbox',
returnvalue: 'nobackground',
name: 'nobackground',
label: mw.message('print-option-nobg').plain(),
label: '移除背景色',
help: 'print-option-nobg-help'
help: '节省墨水,但可能影响部分内容可见性'
},
},
{
{
type: 'checkbox',
type: 'checkbox',
returnvalue: 'blacktext',
name: 'blacktext',
label: mw.message('print-option-blacktext').plain()
label: '强制纯黑色文字'
}
}
],
],
第60行: 第62行:
// ============== 初始化 ==============
// ============== 初始化 ==============
init() {
init() {
if (!document.getElementById('t-print')) return;
const $printLink = $('#t-print a, .vector-menu-tabs a[href*="printable=yes"]').first();
if (!$printLink.length) {
console.warn('找不到打印链接');
⚫
return;
⚫
}


⚫
$printLink
⚫
mw.loader.using(['oojs-ui', 'oojs-ui-windows']).then(() => {
const $printLink = $('#t-print a');
.text('可打印版本')
$printLink
.off('click.mwprint')
.text(mw.message('print-version').plain())
.on('click.mwprint', (e) => {
.off('click')
e.preventDefault();
.on('click', (e) => {
this.openDialog();
e.preventDefault();
});
},
⚫
e.stopPropagation();

⚫
this.createDialog();
⚫
// ============== 对话框控制 ==============
⚫
});
});
openDialog() {
// 动态加载OOUI库
⚫
if (!window.OO) {
⚫
mw.loader.using(['oojs-ui', 'oojs-ui-windows']).then(() => {
⚫
this._createDialog();
⚫
}).catch(err => {
console.error('加载OOUI失败:', err);
alert('打印功能初始化失败,请刷新页面重试');
⚫
});
⚫
} else {
this._createDialog();
}
},
},


_createDialog() {
⚫
// ============== 对话框 ==============
// 1. 创建对话框类
⚫
createDialog() {
function PrintDialog(config) {
function PrintDialog(config) {
PrintDialog.super.call(this, config);
PrintDialog.super.call(this, config);
第82行: 第99行:
OO.inheritClass(PrintDialog, OO.ui.ProcessDialog);
OO.inheritClass(PrintDialog, OO.ui.ProcessDialog);


PrintDialog.static.name = 'printdialog';
// 2. 对话框配置
PrintDialog.static.title = mw.message('print-dialog-title').plain();
PrintDialog.static.name = 'PrintEnhancerDialog';
⚫
PrintDialog.static.title = '打印设置';
PrintDialog.static.actions = [
PrintDialog.static.actions = [
{
{
action: 'print',
action: 'print',
label: '打印',
label: mw.message('print-action-print').plain(),
flags: ['primary', 'progressive']
flags: ['primary', 'progressive']
},
},
{
{
action: 'cancel',
action: 'cancel',
label: mw.message('print-action-cancel').plain(),
label: '取消',
flags: 'safe'
flags: 'safe'
}
}
];
];


// 3. 构建对话框内容
PrintDialog.prototype.initialize = function() {
PrintDialog.prototype.initialize = function() {
PrintDialog.super.prototype.initialize.apply(this, arguments);
PrintDialog.super.prototype.initialize.apply(this, arguments);
const panel = new OO.ui.PanelLayout({ padded: true });
const panel = new OO.ui.PanelLayout({
⚫
padded: true,
⚫
expanded: false
⚫
});
const fieldset = new OO.ui.FieldsetLayout({
const fieldset = new OO.ui.FieldsetLayout({
label: mw.message('print-options').plain()
label: '打印选项'
});
});


// 添加所有复选框
PrintEnhancer.questions.forEach(q => {
PrintEnhancer.questions.forEach(q => {
const checkbox = new OO.ui.CheckboxInputWidget({
const checkbox = new OO.ui.CheckboxInputWidget({
selected: PrintEnhancer.config[q.returnvalue]
selected: PrintEnhancer.config[q.name]
});
const field = new OO.ui.FieldLayout(checkbox, {
label: q.label,
align: 'inline',
⚫
help: q.help ? new OO.ui.HtmlSnippet(q.help) : null
});
});
fieldset.addItems([
new OO.ui.FieldLayout(checkbox, {
fieldset.addItems([field]);
label: q.label,
this[q.name] = checkbox; // 保存引用
⚫
align: 'inline',
⚫
help: q.help ? mw.message(q.help).plain() : null
⚫
})
⚫
]);
⚫
q.widget = checkbox;
});
});


第122行: 第148行:
};
};


// 4. 处理按钮动作
PrintDialog.prototype.getActionProcess = function(action) {
PrintDialog.prototype.getActionProcess = function(action) {
const dialog = this;
const dialog = this;
return new OO.ui.Process(() => {
return new OO.ui.Process(() => {
if (action === 'print') {
if (action === 'print') {
// 保存用户选择
PrintEnhancer.questions.forEach(q => {
PrintEnhancer.questions.forEach(q => {
PrintEnhancer.config[q.returnvalue] = q.widget.isSelected();
PrintEnhancer.config[q.name] = dialog[q.name].isSelected();
⚫
});
⚫
return dialog.close({ action }).then(() => {
⚫
PrintEnhancer.applyPrintStyles();
⚫
setTimeout(() => {
⚫
window.print();
⚫
setTimeout(() => location.reload(), 1000);
⚫
}, 500);
});
});
}
}
return dialog.close({ action }); // 处理cancel
dialog.close({ action });
});
});
};
};


// 5. 创建窗口管理器
if (!this.windowManager) {
if (!this.windowManager) {
this.windowManager = new OO.ui.WindowManager();
this.windowManager = new OO.ui.WindowManager();
$('body').append(this.windowManager.$element);
$(document.body).append(this.windowManager.$element);
}
}

⚫
this.windowManager.addWindows([new PrintDialog({ size: 'medium' })]);
this.windowManager.openWindow(this.printDialog);
// 6. 显示对话框
⚫
const dialog = new PrintDialog({ size: 'medium' });
this.windowManager.addWindows([dialog]);
this.windowManager.openWindow(dialog).then(() => {
⚫
if (dialog.action === 'print') {
⚫
this.applyPrintStyles();
⚫
setTimeout(() => window.print(), 300);
}
});
},
},


// ============== 打印样式 ==============
// ============== 打印样式应用 ==============
applyPrintStyles() {
applyPrintStyles() {
let css = '@media print { ';
const cssRules = [];
const c = this.config;
const c = this.config;


if (c.enhanced) css += `
if (c.enhanced) cssRules.push(`
.noprint, #siteNotice, .mw-indicators,
.noprint, #siteNotice, .mw-editsection,
.mw-editsection, .firstHeading .mw-headline {
.mw-indicators, .firstHeading .mw-headline {
display: none !important;
display: none !important;
}
}
`;
`);
if (c.noimages) css += 'img, .video-container { display: none !important; }';
if (c.noimages) cssRules.push('img, video, .video-container { display: none !important; }');
if (c.norefs) css += 'sup.reference, .references { display: none !important; }';
if (c.norefs) cssRules.push('sup.reference, .references { display: none !important; }');
if (c.notoc) css += '#toc, .toc { display: none !important; }';
if (c.notoc) cssRules.push('#toc, .toc { display: none !important; }');
if (c.nobackground) css += 'body { background: white !important; }';
if (c.nobackground) cssRules.push('body { background: white !important; }');
if (c.blacktext) css += 'body { color: black !important; }';
if (c.blacktext) cssRules.push('body, body * { color: black !important; }');


css += '}';
const styleId = 'mw-print-styles';
let style = document.getElementById(styleId);
const style = document.createElement('style');
if (!style) {
style.media = 'print';
style = document.createElement('style');
style.textContent = css;
style.id = styleId;
document.head.appendChild(style);
document.head.appendChild(style);
}
style.textContent = `@media print { ${cssRules.join('')} }`;
}
}
};
};


// ============== 消息初始化 ==============
// ============== 自动启动 ==============
mw.messages.set({
$(document).ready(function() {
// 确保在DOM加载后运行
'print-version': '可打印版本',
setTimeout(() => PrintEnhancer.init(), 300);
⚫
'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());
mw.hook('wikipage.content').add(function() {
⚫
PrintEnhancer.init();
});
})();
})();

2025年11月1日 (六) 20:26的版本

// ==UserScript==
// @name         MediaWiki打印增强
// @description  高级打印选项(优化布局/隐藏图片等)
// @namespace    https://github.com/yourname/
// @version      2.0
// @match        *://*/*
// @grant        none
// @require      https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js
// ==/UserScript==

(function() {
    'use strict';

    // ============== 核心配置 ==============
    const PrintEnhancer = {
        // 默认配置
        config: {
            enhanced: true,
            noimages: false,
            norefs: false,
            notoc: false,
            nobackground: false,
            blacktext: true
        },

        // 对话框选项
        questions: [
            {
                type: 'checkbox',
                name: 'enhanced',
                label: '优化打印布局',
                help: '隐藏编辑按钮等非必要元素'
            },
            {
                type: 'checkbox',
                name: 'noimages',
                label: '隐藏所有图片'
            },
            {
                type: 'checkbox',
                name: 'norefs',
                label: '隐藏参考文献'
            },
            {
                type: 'checkbox',
                name: 'notoc',
                label: '隐藏目录'
            },
            {
                type: 'checkbox',
                name: 'nobackground',
                label: '移除背景色',
                help: '节省墨水,但可能影响部分内容可见性'
            },
            {
                type: 'checkbox',
                name: 'blacktext',
                label: '强制纯黑色文字'
            }
        ],

        // ============== 初始化 ==============
        init() {
            const $printLink = $('#t-print a, .vector-menu-tabs a[href*="printable=yes"]').first();
            if (!$printLink.length) {
                console.warn('找不到打印链接');
                return;
            }

            $printLink
                .text('可打印版本')
                .off('click.mwprint')
                .on('click.mwprint', (e) => {
                    e.preventDefault();
                    this.openDialog();
                });
        },

        // ============== 对话框控制 ==============
        openDialog() {
            // 动态加载OOUI库
            if (!window.OO) {
                mw.loader.using(['oojs-ui', 'oojs-ui-windows']).then(() => {
                    this._createDialog();
                }).catch(err => {
                    console.error('加载OOUI失败:', err);
                    alert('打印功能初始化失败,请刷新页面重试');
                });
            } else {
                this._createDialog();
            }
        },

        _createDialog() {
            // 1. 创建对话框类
            function PrintDialog(config) {
                PrintDialog.super.call(this, config);
            }
            OO.inheritClass(PrintDialog, OO.ui.ProcessDialog);

            // 2. 对话框配置
            PrintDialog.static.name = 'PrintEnhancerDialog';
            PrintDialog.static.title = '打印设置';
            PrintDialog.static.actions = [
                { 
                    action: 'print', 
 label: '打印', 
                    flags: ['primary', 'progressive'] 
                },
                { 
                    action: 'cancel', 
                    label: '取消', 
                    flags: 'safe' 
                }
            ];

            // 3. 构建对话框内容
            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: '打印选项'
                });

                // 添加所有复选框
                PrintEnhancer.questions.forEach(q => {
                    const checkbox = new OO.ui.CheckboxInputWidget({
                        selected: PrintEnhancer.config[q.name]
                    });
                    
                    const field = new OO.ui.FieldLayout(checkbox, {
                        label: q.label,
                        align: 'inline',
                        help: q.help ? new OO.ui.HtmlSnippet(q.help) : null
                    });
                    
                    fieldset.addItems([field]);
                    this[q.name] = checkbox; // 保存引用
                });

                panel.$element.append(fieldset.$element);
                this.$body.append(panel.$element);
            };

            // 4. 处理按钮动作
            PrintDialog.prototype.getActionProcess = function(action) {
                const dialog = this;
                return new OO.ui.Process(() => {
                    if (action === 'print') {
                        // 保存用户选择
                        PrintEnhancer.questions.forEach(q => {
                            PrintEnhancer.config[q.name] = dialog[q.name].isSelected();
                        });
                    }
                    dialog.close({ action });
                });
            };

            // 5. 创建窗口管理器
            if (!this.windowManager) {
                this.windowManager = new OO.ui.WindowManager();
                $(document.body).append(this.windowManager.$element);
            }

            // 6. 显示对话框
            const dialog = new PrintDialog({ size: 'medium' });
            this.windowManager.addWindows([dialog]);
            this.windowManager.openWindow(dialog).then(() => {
                if (dialog.action === 'print') {
                    this.applyPrintStyles();
                    setTimeout(() => window.print(), 300);
                }
            });
        },

        // ============== 打印样式应用 ==============
        applyPrintStyles() {
            const cssRules = [];
            const c = this.config;

            if (c.enhanced) cssRules.push(`
                .noprint, #siteNotice, .mw-editsection,
                .mw-indicators, .firstHeading .mw-headline {
                    display: none !important;
                }
            `);
            if (c.noimages) cssRules.push('img, video, .video-container { display: none !important; }');
            if (c.norefs) cssRules.push('sup.reference, .references { display: none !important; }');
            if (c.notoc) cssRules.push('#toc, .toc { display: none !important; }');
            if (c.nobackground) cssRules.push('body { background: white !important; }');
            if (c.blacktext) cssRules.push('body, body * { color: black !important; }');

            const styleId = 'mw-print-styles';
            let style = document.getElementById(styleId);
            if (!style) {
                style = document.createElement('style');
                style.id = styleId;
                document.head.appendChild(style);
            }
            style.textContent = `@media print { ${cssRules.join('')} }`;
        }
    };

    // ============== 自动启动 ==============
    $(document).ready(function() {
        // 确保在DOM加载后运行
        setTimeout(() => PrintEnhancer.init(), 300);
    });

    // 兼容皮肤动态加载
    mw.hook('wikipage.content').add(function() {
        PrintEnhancer.init();
    });
})();