LLWiki正在建设中,欢迎加入我们

“MediaWiki:Gadget-inspect.js”的版本间差异

跳转到导航 跳转到搜索
删除1,117字节 、​ 2023年3月27日 (一) 13:11
无编辑摘要
 
(未显示2个用户的13个中间版本)
* @Function: 在页面内快速编辑和预览
* @Author: [[User:Bhsd]]
* @Translation: [[User:Lakejason0]]
*/
"use strict";
let nextid, list = mw.storage.getObject( 'inspect-category' ), flag;
const id = mw.config.get( 'wgArticleId' ),
curRevid = mw.config.get( 'wgCurRevisionId' ),
page = mw.config.get( 'wgPageName' ), // 这里未转义,后面应用时需要注意
isCode = mw.config.get( 'wgPageContentModel' ) != 'wikitext', // javascript/css/Scribunto/json
gadgets = mw.gadgets || {},
charInsert = gadgets.charinsert || {},
src = charInsert.src || 'special:我的用户页mypage/edittools',
// 由于resizable,left, top, height必须加!important,width不可加!important
cssHide = mw.util.addCSS( `#inspector { position:fixed; bottom:0; right:24px; left:auto !important;
flag = pages[0] == id || ctn && pages.includes(id); // &&的优先级高于||
list = [pages, flag ? pages.indexOf(id) + 1 : 0];
if (ctn && !flag) { mw.notify(wgULS('当前页面并不属于该分类或空间!', '頁面並不屬於分類或空間!'),
{type: 'warn'}); }
mw.storage.setObject( 'inspect-category', [pages, list[1] - flag] );
textInput = new OO.ui.TextInputWidget(),
fromHere = new OO.ui.CheckboxInputWidget(),
message = [ $('<p>', {text: wgULS('请输入分类名或空间编号:', '請輸入分類名或空間編號:')}),
textInput.$element,
new OO.ui.FieldLayout(fromHere, {label: wgULS('从当前页面继续', '從頁面繼續'), align: 'inline'}).$element
],
updateCat = function(cat, ctn) {
return;
}
// 输入数字对应空间
if (!isNaN(cat)) {
if (!Object.keys( mw.config.get( 'wgFormattedNamespaces' ) ).includes(cat)) {
mw.notify(wgULS('错误的空间编号!', '錯誤的空間編號!'), {type: 'error'});
return;
}
mw.timedQuery(api, {list: 'allpages', apnamespace: cat, apfilterredir: 'nonredirects', aplimit: 'max'},
wgULS('该空间的页面列表', '此命空間的頁面列表清單')).then(ap => {
const pages = ap.query.allpages.map(ele => ele.pageid).sort((a, b) => a < b); // 由新到旧排列
if (pages.length === 0) {
mw.notify( wgULS('该空间沒有非重定向的页面!', '此命空間沒有非重新導向的頁面!'), {type: 'warn'} );
return;
}
}
mw.timedQuery(api, {list: 'categorymembers', cmtitle: target.title, cmprop: 'ids', cmlimit: 'max',
cmsort: 'timestamp', cmdir: 'older'}, wgULS('分类下的页面列表', '分類下的頁面列表清單')).then(cm => {
const pages = cm.query.categorymembers.map(ele => ele.pageid);
if (pages.length === 0) {
mw.notify( wgULS('该分类下无页面!', '分類下無頁面!'), {type: 'warn'} );
return;
}
}
// 先提交Ajax请求,这里手动设置cache: true
const getJSON = $mw.getloader.using({ dataType: 'jsonext.CodeMirror.data', cache: true),
url: '//cdn.jsdelivr.net/gh/bhsd-harry/LLWiki@1.6/json/gadget-CodeMirror.json' }),
getExt = mw.loader.using(['ext.CodeMirror.lib', 'ext.CodeMirror.mode.mediawiki']);
// 生成通用的API请求
mw.sectionQuery(api, section).then(r => {
editor.setValue( r.parse.wikitext );
secTitle = r.parse.sections[0].lineanchor.replaceAll(' ', '_'); // 此处有bug,Wikitext可接受的HTML标记应被剥离
}, () => {});
});
const backupContent = (backupObj[id] || [])[1];
if (!backupContent) {
mw.notify(wgULS('当前页面尚未备份!', '頁面尚未備份!'), {type: 'warn'});
return;
}
mw.confirm( wgULS('要加载备份吗?', '要備份嗎?'), 'progressive' ).then(confirm => {
if (!confirm) { return; }
editor.setValue( backupContent );
mw.notify(wgULS('已还原备份!', '已原備份!'), {type: 'success'});
});
},
$('.mw-indicators')
], // 用于替换时保留原始数据
$warning = $('<div>', {html: [wgULS("确定要还原为未编辑的状态吗?", "確認要原為未編輯的狀態嗎?"), '<br>',
wgULS("建议您做好编辑内容备份。", "建議您做好編輯內容備份。")]}),
$heading = $('#firstHeading'),
// 改变CSS样式表示提交中
btns[0].setDisabled( true );
mw.safeEdit(api, curRevid, {pageid: id, text: editor.getValue(), section: section,
summary: (section === undefined ? '' : `/* ${secTitle} */ `) + (summary ? `${summary} //` : '//') +
wgULS( '使用[[help:小工具/页面文本对比查看器|页面/文本对比查看器]]快速编辑',
'使用[[help:小工具/页面文本对比查看器|頁面/文對比察看檢視器]]快速編輯')}, isBackup)
.then(() => { location.href = mw.util.getUrl( page ); },
reason => { btns[0].setDisabled( reason == 'editConflict' ); }); // 编辑冲突必须刷新页面,不应重复提交
// 改变CSS样式表示预览中
btns[1].setDisabled( true );
mw.timedParse(api, {text: editor.getValue(), uselang: lang, prop: 'text|categories|displaytitle|indicators'},
prop: 'text|categorieshtml|displaytitle|indicators|modules|headitems'
}, wgULS('预览', '預覽')).then(r => {
mw.loader.load( r.parse.modulestyles );
const tabsStyles = r.parse.headitems.find(function(ele) { return ele.tag === 'TabsStyles'; });
if (tabsStyles) {
$('head').append(tabsStyles.content); // 可能重复,但重复也没关系
}
if ($.contains( $content[0], $original[0] )) {
$original.after( placeholder[0] ).detach();
if (mw.resizeLyrics) { mw.resizeLyrics(); }
mw.hook( 'wikipage.content' ).fire($content);
$('#catlinks').replaceWith( $parseCatr.parse.categorieshtml );
placeholder[1].html( r.parse.displaytitle );
placeholder[3].html( Object.entries( r.parse.indicators ).map(ele =>
$('<div>', {class: 'mw-indicator', id: `mw-indicator-${ele[0]}`, html: ele[1]})) );
const showhidden = mw.user.options.get( 'showhiddencats' ),
normalCats = r.parse.categories.filter(ele => !ele.hidden).map(ele => ele.category),
hiddenCats = (showhidden ? r.parse.categories.filter(ele => ele.hidden) : []).map(ele => ele.category);
if (normalCats.length + hiddenCats.length === 0) { return; }
const $parseCat = $('<div>', {id: 'catlinks', class: 'catlinks', 'data-mw': 'interface'});
if (normalCats.length) {
$parseCat.append( $('<div>', {id: 'mw-normal-catlinks', class: 'mw-normal-catlinks', html: [
$('<a>', {title: wgULS('页面分类', '頁面分類'), text: wgULS('分类', '分類'),
href: '/zh/special:页面分类'}),
':',
$('<ul>', {html: normalCats.map(ele => $('<li>', {html: $('<a>',
{href: mw.util.getUrl( `Category:${ele}` ), title: `Category:${ele}`, text: ele})
}))})
]}) );
}
if (hiddenCats.length) {
$parseCat.append( $('<div>', {id: 'mw-hidden-catlinks',
class: 'mw-hidden-catlinks mw-hidden-cats-user-shown', html: [
wgULS('隐藏分类:', '隱藏分類:'),
$('<ul>', {html: hiddenCats.map(ele => $('<li>', {html: $('<a>', {href: mw.util.getUrl(ele),
title: `Category:${ele}`, text: ele})}))})
]}) );
}
$('#catlinks').replaceWith( $parseCat );
}, () => {}).then(() => { btns[1].setDisabled( false ); });
}), new OO.ui.ButtonWidget({label: wgULS('还原', '原'), flags: 'destructive', disabled: true}).on('click', () => {
mw.confirm($warning, ['primary', 'destructive']).then(confirm => {
if (!confirm) { return; }
if (mw.resizeLyrics) { mw.resizeLyrics(); }
}), btnGo],
options = $('<div>', {text: wgULS('查找替换', '替換取代')}).click(() => {
if ($replace) {
$replace.show();
regex = new OO.ui.CheckboxInputWidget().on('change', enable),
modifier = new OO.ui.CheckboxInputWidget().on('change', enable),
undoBtn = new OO.ui.ButtonWidget({label: wgULS('撤销', '撤銷復原'), disabled: true, flags: ['destructive']})
.on('click', () => {
editor.setValue( replaceBackup );
enable();
}),
replaceBtn = new OO.ui.ButtonWidget({label: wgULS('替换', '替換取代'), flags: ['progressive']})
.on('click', () => {
const pattern = ptn.getValue(),
});
$replace = $('<div>', {class: 'inspector-field', html: [
$('<div>', {html: [wgULS('查找:', '尋找:' ), ptn.$element]}),
$('<div>', {html: [wgULS('替换:', '替換取代:'), val.$element]}),
$('<div>', {html: [
new OO.ui.FieldLayout(regex, {label: wgULS('正则', '正規表達式'), align: 'inline'}).$element,
new OO.ui.FieldLayout(modifier, {label: $('<i>', {text: 'i'}), align: 'inline'}).$element,
replaceBtn.$element, undoBtn.$element, hideBtn.$element
}, () => {
mw.notify([
wgULS('无法加载', '無法'),
$('<a>', {text: src, href: mw.util.getUrl(src)}),
wgULS('!请检查该页面是否存在。', '!請檢查頁面是否存在。')
], {type: 'error', autoHideSeconds: 'long'});
}).then(() => { $charinsert.removeClass( 'mw-ajax-loader' ); });
actionD = new OO.ui.ActionWidget({label: '否'}),
$url = $('<a>'), // 桌面版CSS不必需href
label = [wgULS('要在新标签页打开', '要在新標籤頁打開'), $url, wgULS('吗?', '嗎?')];
$outer.on('contextmenu', '.cm-mw-template-name', function() {
const template = '模板:' + $(this).text();
btns[0].$element.contextmenu(e => {
e.preventDefault();
OO.ui.prompt( wgULS('请输入编辑摘要:', '請輸入編輯摘要:') , {textInput: {value: summary}} ).then(input => {
if (input !== null) { summary = input; }
});
if (isGadget( 'PreviewWithVariant' ) ) {
const options = [{label: "大陆简体", data: "zh-cn"}, {label: "香港繁體", data: "zh-hk"},
{label: "澳門繁體", data: "zh-mo"}, {label: "来西亚简体", data: "zh-my"},
{label: "新加坡简体", data: "zh-sg"}, {label: "臺灣體", data: "zh-tw"}],
select = new OO.ui.DropdownInputWidget({classes: ['inspector-variant'], options: options, value: lang})
.on('change', () => { lang = select.getValue(); }),
// $.when很容易出错,这里保险起见用Promise.all
Promise.all([getJSON, mw.request, getExt]).then(data => {
mw.config.set('extCodeMirrorConfig', data[0]);
mw.hook( 'codemirror.config' ).fire();
text = data[1].query.pages[0].revisions[0].content;
editor = new CodeMirror($outer[0], {value: text, mode: 'text/mediawiki', mwConfig: data[0],
mwConfig: mw.config.setget('extCodeMirrorConfig'), data[0]);lineWrapping: true, lineNumbers: true
lineWrapping: true, lineNumbers: true, resetSelectionOnContextMenu: false});
]}) );
$wrapper = $( editor.getWrapperElement() ).toggle().append( [$dropdown, $hints] );
$('<div>', {id: 'inspector-btns', html: btns.map(ele => ele.$element)}).appendTo( $outer );
editor.scrollIntoView(n);
}
else { mw.notify( wgULS('当前不存在该行!', '前不存在行!'), {type: 'warn'} ); }
});
}, reason => { mw.apiFailure(reason, `CodeMirror${wgULS('设置或页面', '設或頁面')}Wikitext`); })
.then(() => { $outer.removeClass( 'mw-ajax-loader' ); });
});
6,698

个编辑

导航菜单