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

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

跳转到导航 跳转到搜索
删除4,660字节 、​ 2023年3月27日 (一) 13:11
无编辑摘要
 
(未显示2个用户的14个中间版本)
* @Function: 在页面内快速编辑和预览
* @Author: [[User:Bhsd]]
* @Translation: [[User:Lakejason0]]
*/
"use strict";
/*global OO, CodeMirror, wgULS*/
$(() => { // 避免全局变量
let nextid, list = mw.storage.getObject( 'inspect-category' ), flag;
const id = mw.config.get( 'wgArticleId' ),
curRevid page = mw.config.get( 'wgCurRevisionIdwgPageName' ), // 这里未转义,后面应用时需要注意
page isCode = mw.config.get( 'wgPageNamewgPageContentModel' ) != 'wikitext', // 这里未转义,后面应用时需要注意javascript/css/Scribunto/json
gadgets = mw.gadgets || {},
isCode = mw.config.get( 'wgPageContentModel' ) != 'wikitext', // javascript/css/Scribunto/json
charInsert = gadgets = mw.gadgetscharinsert || {},
src = charInsert = gadgets.charinsertsrc || {}'special:mypage/edittools',
// 由于resizable,left, top, height必须加!important,width不可加!important
src = charInsert.src || 'special:我的用户页/edittools',
cssHide = mw.util.addCSS( `#inspector { position:fixed; bottom:0; right:24px; left:auto !important;
// 由于resizable,left, top, height必须加!important,width不可加!important
top:auto !important; height:auto !important; width:calc(50% - 7rem - 0.5px); }
cssHide = mw.util.addCSS( `#inspector { position:fixed; bottom:0; right:24px; left:auto !important;
div.start-screen { bottom:40px; }` ),
top:auto !important; height:auto !important; width:calc(50% - 7rem - 0.5px); }
$content = $('#mw-content-text, #mw-imagepage-content').last(),
div.start-screen { bottom:40px; }` ),
// wikitext/Scribunto对应.mw-parser-output,javascript/css对应.mw-code,json对应.mw-json
$content = $('#mw-content-text, #mw-imagepage-content').last(),
$original = $content.children('.mw-json, .mw-code, .mw-parser-output'),
// wikitext/Scribunto对应.mw-parser-output,javascript/css对应.mw-code,json对应.mw-json
$outer = $('<div>', {id: 'inspector', class: 'mw-ajax-loader'}).insertBefore( $original ),
$original = $content.children('.mw-json, .mw-code, .mw-parser-output'),
api = new mw.Api();
$outer = $('<div>', {id: 'inspector', class: 'mw-ajax-loader'}).insertBefore( $original ),
if (!list) { nextid = id + 1; }
api = new mw.Api();
else {
if (!list) { nextid = id + 1; }
flag = list[0][ list[1] ] == id;
else {
if (flag) = list[0][{ list[1]++; ] == id;}
nextid = if (flag) {list[0][ list[1]++ ]; }
}
nextid = list[0][ list[1] ];
const btnGo = new OO.ui.ButtonWidget({flags: 'progressive', icon: 'next', href: `/zh?redirect=no&curid=${nextid}`,
}
disabled: !nextid}),
const btnGo = new OO.ui.ButtonWidget({flags: 'progressive', icon: 'next', href: `/zh?redirect=no&curid=${nextid}`,
initList = (pages, ctn) => {
disabled: !nextid}),
initList = console.info({pages: pages, ctn): =>ctn, {id: id});
flag = pages[0] == id || ctn && pages.includes(id); // &&的优先级高于||
console.info({pages: pages, ctn: ctn, id: id});
flag list = [pages[0], ==flag id || ctn &&? pages.includesindexOf(id); //+ &&的优先级高于||1 : 0];
if (ctn && !flag) { mw.notify(wgULS('当前页面并不属于该分类或命名空间!', '目前的頁面並不屬於此分類或命名空間!'),
list = [pages, flag ? pages.indexOf(id) + 1 : 0];
{type: 'warn'}); }
if (ctn && !flag) { mw.notify(wgULS('当前页面并不属于该分类或名字空间!', '當前頁面並不屬於該分類或名字空間!'),
mw.storage.setObject( 'inspect-category', [pages, list[1] - flag] );
{type: 'warn'}); }
btnGo.setHref( `/zh?redirect=no&curid=${pages[ list[1] ]}` ).setDisabled( false );
mw.storage.setObject( 'inspect-category', [pages, list[1] - flag] );
},
btnGo.setHref( `/zh?redirect=no&curid=${pages[ list[1] ]}` ).setDisabled( false );
dialog = new OO.ui.MessageDialog(),
},
dialog actionC = new OO.ui.MessageDialogActionWidget({action: 'cancel', label: '取消'}),
actionC actionG = new OO.ui.ActionWidget({action: 'cancelgo', label: wgULS('确定', '確認'), flags: '取消progressive'}),
textInput = new OO.ui.TextInputWidget(),
actionG = new OO.ui.ActionWidget({action: 'go', label: wgULS('确定', '確認'), flags: 'progressive'}),
textInput fromHere = new OO.ui.TextInputWidgetCheckboxInputWidget(),
message = [ $('<p>', {text: wgULS('请输入分类名或命名空间编号:', '請輸入分類名或命名空間編號:')}),
fromHere = new OO.ui.CheckboxInputWidget(),
textInput.$element,
message = [ $('<p>', {text: wgULS('请输入分类名或名字空间编号:', '請輸入分類名或名字空間編號:')}),
new OO.ui.FieldLayout(fromHere, {label: wgULS('从当前页面继续', '從目前的頁面繼續'), align: 'inline'}).$element
textInput.$element,
],
new OO.ui.FieldLayout(fromHere, {label: wgULS('从当前页面继续', '從當前頁面繼續'), align: 'inline'}).$element
updateCat = function(cat, ctn) {
],
// 输入空白则清除分类
updateCat = function(cat, ctn) {
if (cat === '') {
// 输入空白则清除分类
mw.storage.remove( 'inspect-category' );
if (cat === '') {
btnGo.setHref( `/zh?redirect=no&curid=${id + 1}` ).setDisabled( false );
mw.storage.remove( 'inspect-category' );
return;
btnGo.setHref( `/zh?redirect=no&curid=${id + 1}` ).setDisabled( false );
}
return;
// 输入数字对应命名空间
}
if (!isNaN(cat)) {
// 输入数字对应名字空间
if (!Object.keys( mw.config.get( 'wgFormattedNamespaces' ) ).includes(cat)) {
if (!isNaN(cat)) {
mw.notify(wgULS('错误的命名空间编号!', '錯誤的命名空間編號!'), {type: 'error'});
if (!Object.keys( mw.config.get( 'wgFormattedNamespaces' ) ).includes(cat)) {
return;
mw.notify(wgULS('错误的名字空间编号!', '錯誤的名字空間編號!'), {type: 'error'});
}
return;
mw.timedQuery(api, {list: 'allpages', apnamespace: cat, apfilterredir: 'nonredirects', aplimit: 'max'},
}
wgULS('该命名空间的页面列表', '此命名空間的頁面清單')).then(ap => {
mw.timedQuery(api, {list: 'allpages', apnamespace: cat, apfilterredir: 'nonredirects', aplimit: 'max'},
const pages = ap.query.allpages.map(ele => ele.pageid).sort((a, b) => a < b); // 由新到旧排列
wgULS('该名字空间的页面列表', '該名字空間的頁面列表')).then(ap => {
if (pages.length === 0) {
const pages = ap.query.allpages.map(ele => ele.pageid).sort((a, b) => a < b); // 由新到旧排列
mw.notify( wgULS('该命名空间沒有非重定向的页面!', '此命名空間沒有非重新導向的頁面!'), {type: 'warn'} );
if (pages.length === 0) {
return;
mw.notify( wgULS('该名字空间沒有非重定向的页面!', '該名字空間沒有非重定向的頁面!'), {type: 'warn'} );
}
return;
initList(pages, ctn);
}
}, () => {}); // mw.timedQuery已经通知过错误信息,这里只要一个空函数处理reject,下同
initList(pages, ctn);
return;
}, () => {}); // mw.timedQuery已经通知过错误信息,这里只要一个空函数处理reject,下同
}
return;
if (!/^(category|分[类類]):/i.test( cat )) { cat = `Category:${cat}`; }
}
// cmtitle参数不可自动转换,所以需要先获得转换后的正确标题
if (!/^(category|分[类類]):/i.test( cat )) { cat = `Category:${cat}`; }
mw.timedQuery(api, {titles: cat, converttitles: 1}, wgULS('标准页面名称', '標準頁面名稱')).then(r => {
// cmtitle参数不可自动转换,所以需要先获得转换后的正确标题
const target = r.query.pages[0];
mw.timedQuery(api, {titles: cat, converttitles: 1}, wgULS('标准页面名称', '標準頁面名稱')).then(r => {
if (target.missing) {
const target = r.query.pages[0];
mw.notify(wgULS('错误的分类名!', '錯誤的分類名!'), {type: 'error'});
if (target.missing) {
return;
mw.notify(wgULS('错误的分类名!', '錯誤的分類名!'), {type: 'error'});
}
return;
mw.timedQuery(api, {list: 'categorymembers', cmtitle: target.title, cmprop: 'ids', cmlimit: 'max',
}
cmsort: 'timestamp', cmdir: 'older'}, wgULS('分类下的页面列表', '分類下的頁面清單')).then(cm => {
mw.timedQuery(api, {list: 'categorymembers', cmtitle: target.title, cmprop: 'ids', cmlimit: 'max',
const pages = cm.query.categorymembers.map(ele => ele.pageid);
cmsort: 'timestamp', cmdir: 'older'}, wgULS('分类下的页面列表', '分類下的頁面列表')).then(cm => {
if (pages.length === 0) {
const pages = cm.query.categorymembers.map(ele => ele.pageid);
mw.notify( wgULS('该分类下无页面!', '此分類下無頁面!'), {type: 'warn'} );
if (pages.length === 0) {
return;
mw.notify( wgULS('该分类下无页面!', '該分類下無頁面!'), {type: 'warn'} );
}
return;
initList(pages, ctn);
}
}, () => {});
initList(pages, ctn);
}, () => {});
};
}, () => {});
// 这个click事件不能绑到btnGo上,否则会禁用href跳转
};
btnGo.$element.click(() => { if (list && flag) { mw.storage.setObject( 'inspect-category', list ); } })
// 这个click事件不能绑到btnGo上,否则会禁用href跳转
.contextmenu(e => {
btnGo.$element.click(() => { if (list && flag) { mw.storage.setObject( 'inspect-category', list ); } })
e.preventDefault();
.contextmenu(e => {
mw.dialog(dialog, [actionC, actionG], message).then(action => {
e.preventDefault();
if (action == 'go') { updateCat( textInput.getValue(), fromHere.isSelected() ); }
mw.dialog(dialog, [actionC, actionG], message).then(action => {
});
if (action == 'go') { updateCat( textInput.getValue(), fromHere.isSelected() ); }
});
// 模板、JavaScript、CSS、Lua、JSON只需要箭头按钮
});
if (mw.config.get( 'wgNamespaceNumber' ) == 10 && !page.endsWith( '/doc' ) || isCode) {
// 模板、JavaScript、CSS、Lua、JSON只需要箭头按钮
$outer.removeClass( 'mw-ajax-loader' ).append( $('<div>', {id: 'inspector-btns', html: btnGo.$element}) );
if (mw.config.get( 'wgNamespaceNumber' ) == 10 && !page.endsWith( '/doc' ) || isCode) {
$outer mw.removeClass( 'mw-ajax-loader' ).appendaddStyleTag( $('<div>', {id: '#inspector-btns', html{ width:auto; btnGo.$element})' );
return;
mw.loader.addStyleTag( '#inspector-btns { width:auto; }' );
}
return;
// 先提交Ajax请求,这里手动设置cache: true
}
const getJSON = mw.loader.using('ext.CodeMirror.data'),
// 先提交Ajax请求,这里手动设置cache: true
getExt = mw.loader.using(['ext.CodeMirror.lib', 'ext.CodeMirror.mode.mediawiki']);
const getJSON = $.get({ dataType: 'json', cache: true,
// 生成通用的API请求
url: '//cdn.jsdelivr.net/gh/bhsd-harry/LLWiki@1.6/json/gadget-CodeMirror.json' }),
mw.standardQuery(api);
getExt = mw.loader.using(['ext.CodeMirror.lib', 'ext.CodeMirror.mode.mediawiki']);
let text, editor, $wrapper, $replace, $charinsert, prefix, ns, section, secTitle, summary,
// 生成通用的API请求
lang = mw.config.get( 'wgUserVariant' );
mw.standardQuery(api);
$original.find( ':header:has(.mw-editsection)' ).dblclick(function() {
let text, editor, $wrapper, $replace, $charinsert, prefix, ns, section, secTitle, summary,
section = mw.util.getParamValue( 'section', $(this).find( '.mw-editsection > a' ).attr('href') );
lang = mw.config.get( 'wgUserVariant' );
mw.sectionQuery(api, section).then(r => {
$original.find( ':header:has(.mw-editsection)' ).dblclick(function() {
editor.setValue( r.parse.wikitext );
section = mw.util.getParamValue( 'section', $(this).find( '.mw-editsection > a' ).attr('href') );
secTitle = r.parse.sections[0].anchor.replaceAll(' ', '_');
mw.sectionQuery(api, section).then(r => {
}, () => {});
editor.setValue( r.parse.wikitext );
});
secTitle = r.parse.sections[0].line.replaceAll(' ', '_'); // 此处有bug,Wikitext可接受的HTML标记应被剥离
// 标注<p>标签
}, () => {});
const css = mw.util.addCSS( `.empty { border:1px solid rgba(253,220,154,0.5); box-shadow:0 0 0.5em #fddc9a; }
});
#mw-content-text .mw-parser-output { display:flow-root; max-height:100vh; overflow:auto;
// 标注<p>标签
word-wrap:break-word; }` );
const css = mw.util.addCSS( `.empty { border:1px solid rgba(253,220,154,0.5); box-shadow:0 0 0.5em #fddc9a; }
css.disabled = true;
#mw-content-text .mw-parser-output { display:flow-root; max-height:100vh; overflow:auto;
// 也可以使用user.options,这里使用其他方法绕过
word-wrap:break-word; }` );
const isGadget = (name) => ['loaded', 'loading', 'ready'].includes( mw.loader.getState(`ext.gadget.${name}`) ),
css.disabled = true;
isBackup = isGadget('contentBackup'),
// 也可以使用user.options,这里使用其他方法绕过
backupObj = isBackup ? Object.fromEntries( mw.storage.getObject( 'LLWiki-contentBackup' ) || [] ) : {},
const isGadget = (name) => ['loaded', 'loading', 'ready'].includes( mw.loader.getState(`ext.gadget.${name}`) ),
backup = isBackup ? () => {
isBackup = isGadget('contentBackup'),
backupObj[id] = [mw.now(), editor.getValue()];
backupObj = isBackup ? Object.fromEntries( mw.storage.getObject( 'LLWiki-contentBackup' ) || [] ) : {},
mw.storage.setObject( 'LLWiki-contentBackup', Object.entries(backupObj) );
backup = isBackup ? () => {
} : () => {},
backupObj[id] = [mw.now(), editor.getValue()];
loadBackup = () => {
mw.storage.setObject( 'LLWiki-contentBackup', Object.entries(backupObj) );
const backupContent = (backupObj[id] || [])[1];
} : () => {},
if (!backupContent) {
loadBackup = () => {
mw.notify(wgULS('当前页面尚未备份!', '目前的頁面尚未備份!'), {type: 'warn'});
const backupContent = (backupObj[id] || [])[1];
return;
if (!backupContent) {
}
mw.notify(wgULS('当前页面尚未备份!', '當前頁面尚未備份!'), {type: 'warn'});
mw.confirm( wgULS('要加载备份吗?', '要載入備份嗎?'), 'progressive' ).then(confirm => {
return;
if (!confirm) { return; }
}
editor.setValue( backupContent );
mw.confirm( wgULS('要加载备份吗?', '要加載備份嗎?'), 'progressive' ).then(confirm => {
mw.notify(wgULS('已还原备份!', '已還原備份!'), {type: 'success'});
if (!confirm) { return; }
});
editor.setValue( backupContent );
},
mw.notify(wgULS('已还原备份!', '已復原備份!'), {type: 'success'});
pEmpty = ($div) => {
});
$div.find( 'p:not(:has(script))' ).filter(function() { return !/\S/.test( this.textContent ); })
},
.addClass('empty');
pEmpty = ($div) => {
},
$div.find( 'p:not(:has(script))' ).filter(function() { return !/\S/.test( this.textContent ); })
placeholder = [
.addClass('empty');
$('<div>', {class: "mw-parser-output"}).css('display', 'none'),
},
$('<h1>', {id: 'firstHeading', class: 'firstHeading'}),
placeholder = [
$('<div>', {classid: "mw-parser-output"'catlinks'}).css('display', 'none'),
$('.mw-indicators')
$('<h1>', {id: 'firstHeading', class: 'firstHeading'}),
], // 用于替换时保留原始数据
$('<div>', {id: 'catlinks'}).css('display', 'none'),
$warning = $('<div>', {html: [wgULS("确定要还原为未编辑的状态吗?", "確認要還原為未編輯的狀態嗎?"), '<br>',
$('.mw-indicators')
wgULS("建议您做好编辑内容备份。", "建議您做好編輯內容備份。")]}),
], // 用于替换时保留原始数据
$heading = $('#firstHeading'),
$warning = $('<div>', {html: [wgULS("确定要还原为未编辑的状态吗?", "確認要復原為未編輯的狀態嗎?"), '<br>',
$cat = $('#catlinks'),
wgULS("建议您做好编辑内容备份。", "建議您做好編輯內容備份。")]}),
$headingindicator = $('#firstHeading.mw-indicator'),
btns = [new OO.ui.ButtonWidget({label: '提交', flags: ['primary', 'progressive']}).on('click', () => {
$cat = $('#catlinks'),
backup();
$indicator = $('.mw-indicator'),
// 改变CSS样式表示提交中
btns = [new OO.ui.ButtonWidget({label: '提交', flags: ['primary', 'progressive']}).on('click', () => {
btns[0].setDisabled( true );
backup();
mw.safeEdit(api, {pageid: id, text: editor.getValue(), section: section,
// 改变CSS样式表示提交中
summary: (section === undefined ? '' : `/* ${secTitle} */ `) + (summary ? `${summary} //` : '//') +
btns[0].setDisabled( true );
wgULS( '使用[[help:小工具/页面文本对比查看器|页面/文本对比查看器]]快速编辑',
mw.safeEdit(api, curRevid, {pageid: id, text: editor.getValue(), section: section,
'使用[[help:小工具/页面文本对比查看器|頁面/文字對比檢視器]]快速編輯')}, isBackup)
summary: (section === undefined ? '' : `/* ${secTitle} */ `) + (summary ? `${summary} //` : '//') +
.then(() => { location.href = mw.util.getUrl( page ); },
wgULS( '使用[[help:小工具/页面文本对比查看器|页面/文本对比查看器]]快速编辑',
reason => { btns[0].setDisabled( reason == 'editConflict' ); }); // 编辑冲突必须刷新页面,不应重复提交
'使用[[help:小工具/页面文本对比查看器|頁面/文本對比察看器]]快速編輯')}, isBackup)
}), new OO.ui.ButtonWidget({label: wgULS('预览', '預覽')}).on('click', () => {
.then(() => { location.href = mw.util.getUrl( page ); },
backup();
reason => { btns[0].setDisabled( reason == 'editConflict' ); }); // 编辑冲突必须刷新页面,不应重复提交
// 改变CSS样式表示预览中
}), new OO.ui.ButtonWidget({label: wgULS('预览', '預覽')}).on('click', () => {
btns[1].setDisabled( true );
backup();
mw.timedParse(api, {text: editor.getValue(), uselang: lang,
// 改变CSS样式表示预览中
prop: 'text|categorieshtml|displaytitle|indicators|modules|headitems'
btns[1].setDisabled( true );
}, wgULS('预览', '預覽')).then(r => {
mw.timedParse(api, {text: editor.getValue(), uselang: lang, prop: 'text|categories|displaytitle|indicators'},
mw.loader.load( r.parse.modulestyles );
wgULS('预览', '預覽')).then(r => {
const tabsStyles = r.parse.headitems.find(function(ele) { return ele.tag === 'TabsStyles'; });
if ($.contains( $content[0], $original[0] )) {
if (tabsStyles) {
$original.after( placeholder[0] ).detach();
$('head').append(tabsStyles.content); // 可能重复,但重复也没关系
$heading.after( placeholder[1] ).detach();
}
$cat.after( placeholder[2] ).detach();
if ($.contains( $content[0], $original[0] )) {
$indicator.detach();
$original.after( placeholder[0] ).detach();
}
$heading.after( placeholder[1] ).detach();
$content.children( '.mw-parser-output' ).replaceWith( r.parse.text );
$cat.after( placeholder[2] ).detach();
pEmpty( $content.children( '.mw-parser-output' ) );
$indicator.detach();
if (mw.resizeLyrics) { mw.resizeLyrics(); }
}
mw.hook( 'wikipage.content' ).fire($content);
$content.children( '.mw-parser-output' ).replaceWith( r.parse.text );
placeholder[1].html( r.parse.displaytitle );
pEmpty( $content.children( '.mw-parser-output' ) );
placeholder[3].html( Object.entries( r.parse.indicators ).map(ele =>
if (mw.resizeLyrics) { mw.resizeLyrics(); }
$('<div>', {class: 'mw-indicator', id: `mw-indicator-${ele[0]}`, html: ele[1]})) );
mw.hook( 'wikipage.content' ).fire($content);
const showhidden = mw.user.options.get( 'showhiddencats' ),
$('#catlinks').replaceWith( r.parse.categorieshtml );
normalCats = r.parse.categories.filter(ele => !ele.hidden).map(ele => ele.category),
placeholder[1].html( r.parse.displaytitle );
hiddenCats = (showhidden ? r.parse.categories.filter(ele => ele.hidden) : []).map(ele => ele.category);
placeholder[3].html( Object.entries( r.parse.indicators ).map(ele =>
if (normalCats.length + hiddenCats.length === 0) { return; }
const $parseCat = $('<div>', {idclass: 'catlinksmw-indicator', classid: 'catlinks'`mw-indicator-${ele[0]}`, 'data-mw'html: 'interface'ele[1]})) );
}, () => {}).then(() => { btns[1].setDisabled( false ); });
if (normalCats.length) {
}), new OO.ui.ButtonWidget({label: wgULS('还原', '還原'), flags: 'destructive', disabled: true}).on('click', () => {
$parseCat.append( $('<div>', {id: 'mw-normal-catlinks', class: 'mw-normal-catlinks', html: [
mw.confirm($warning, ['primary', 'destructive']).then(confirm => {
$('<a>', {title: wgULS('页面分类', '頁面分類'), text: wgULS('分类', '分類'),
if (!confirm) { return; }
href: '/zh/special:页面分类'}),
section = undefined;
':',
editor.setValue( text );
$('<ul>', {html: normalCats.map(ele => $('<li>', {html: $('<a>',
if ($.contains( $content[0], $original[0] )) { return; } // 无事发生
{href: mw.util.getUrl( `Category:${ele}` ), title: `Category:${ele}`, text: ele})
$content.children( '.mw-parser-output' ).replaceWith( $original );
}))})
placeholder[1].replaceWith( $heading );
]}) );
$('#catlinks').replaceWith( $cat );
}
placeholder[3].html( $indicator );
if (hiddenCats.length) {
if (mw.resizeLyrics) { mw.resizeLyrics(); }
$parseCat.append( $('<div>', {id: 'mw-hidden-catlinks',
});
class: 'mw-hidden-catlinks mw-hidden-cats-user-shown', html: [
}), new OO.ui.ButtonWidget({label: wgULS('显示', '顯示')}).on('click', () => {
wgULS('隐藏分类:', '隱藏分類:'),
css.disabled = !css.disabled;
$('<ul>', {html: hiddenCats.map(ele => $('<li>', {html: $('<a>', {href: mw.util.getUrl(ele),
cssHide.disabled = !cssHide.disabled;
title: `Category:${ele}`, text: ele})}))})
$wrapper.toggle();
]}) );
editor.setSize();
}
btns[3].setLabel( css.disabled ? wgULS('显示', '顯示') : wgULS('隐藏', '隱藏'));
$('#catlinks').replaceWith( $parseCat );
}, () => {}).then(() => { btns[12].setDisabled( falsecss.disabled ); });// 折叠时无法更新textarea
if (mw.resizeLyrics) { mw.resizeLyrics(); }
}), new OO.ui.ButtonWidget({label: wgULS('还原', '復原'), flags: 'destructive', disabled: true}).on('click', () => {
}), btnGo],
mw.confirm($warning, ['primary', 'destructive']).then(confirm => {
options = $('<div>', {text: wgULS('查找替换', '尋找取代')}).click(() => {
if (!confirm) { return; }
if ($replace) {
section = undefined;
$replace.show();
editor.setValue( text );
return;
if ($.contains( $content[0], $original[0] )) { return; } // 无事发生
}
$content.children( '.mw-parser-output' ).replaceWith( $original );
let replaceBackup;
placeholder[1].replaceWith( $heading );
const enable = () => { replaceBtn.setDisabled( false ); },
$('#catlinks').replaceWith( $cat );
ptn = new OO.ui.TextInputWidget().on('change', enable),
placeholder[3].html( $indicator );
val = new OO.ui.MultilineTextInputWidget({autosize: true, maxRows: 3}).on('change', enable),
if (mw.resizeLyrics) { mw.resizeLyrics(); }
regex = new OO.ui.CheckboxInputWidget().on('change', enable),
});
modifier }),= new OO.ui.ButtonWidgetCheckboxInputWidget({label: wgULS('显示', '顯示')}).on('clickchange', (enable) => {,
undoBtn = new OO.ui.ButtonWidget({label: wgULS('撤销', '復原'), disabled: true, flags: ['destructive']})
css.disabled = !css.disabled;
.on('click', () => {
cssHide.disabled = !cssHide.disabled;
editor.setValue( replaceBackup );
$wrapper.toggle();
enable();
editor.setSize();
}),
btns[3].setLabel( css.disabled ? wgULS('显示', '顯示') : wgULS('隐藏', '隱藏'));
replaceBtn = new OO.ui.ButtonWidget({label: wgULS('替换', '取代'), flags: ['progressive']})
btns[2].setDisabled( css.disabled ); // 折叠时无法更新textarea
.on('click', () => {
if (mw.resizeLyrics) { mw.resizeLyrics(); }
const pattern = ptn.getValue(),
}), btnGo],
regexp = new RegExp(regex.isSelected() ? pattern : mw.util.escapeRegExp(pattern),
options = $('<div>', {text: wgULS('查找替换', '查找替換')}).click(() => {
'g' + (modifier.isSelected() ? 'i' : ''));
if ($replace) {
replaceBackup = editor.getValue();
$replace.show();
undoBtn.setDisabled( false );
return;
replaceBtn.setDisabled( true ); // 防止连续点击造成无法撤销
}
editor.setValue( replaceBackup.replace(regexp, val.getValue()) );
let replaceBackup;
}),
const enable = () => { replaceBtn.setDisabled( false ); },
ptn hideBtn = new OO.ui.TextInputWidgetButtonWidget().on{label: wgULS('change关闭', enable'關閉')}),
.on('click', () => {
val = new OO.ui.MultilineTextInputWidget({autosize: true, maxRows: 3}).on('change', enable),
$replace.hide();
regex = new OO.ui.CheckboxInputWidget().on('change', enable),
enable();
modifier = new OO.ui.CheckboxInputWidget().on('change', enable),
});
undoBtn = new OO.ui.ButtonWidget({label: wgULS('撤销', '撤銷'), disabled: true, flags: ['destructive']})
$replace = $('<div>', {class: 'inspector-field', html: [
.on('click', () => {
$('<div>', {html: [wgULS('查找:', '尋找:' ), ptn.$element]}),
editor.setValue( replaceBackup );
$('<div>', {html: [wgULS('替换:', '取代:'), val.$element]}),
enable();
$('<div>', {html: [
}),
replaceBtn = new OO.ui.ButtonWidgetFieldLayout(regex, {label: wgULS('替换正则', '替換正規表達式'), flagsalign: ['progressiveinline']}).$element,
new OO.ui.FieldLayout(modifier, {label: $('<i>', {text: 'i'}), align: 'inline'}).$element,
.on('click', () => {
replaceBtn.$element, undoBtn.$element, hideBtn.$element
const pattern = ptn.getValue(),
]})
regexp = new RegExp(regex.isSelected() ? pattern : mw.util.escapeRegExp(pattern),
]}).appendTo( 'body' ).draggable();
'g' + (modifier.isSelected() ? 'i' : ''));
}).add(isGadget('charinsert') ? $('<div>', {text: '快速插入'}).click(() => {
replaceBackup = editor.getValue();
if ($charinsert) {
undoBtn.setDisabled( false );
$charinsert.show();
replaceBtn.setDisabled( true ); // 防止连续点击造成无法撤销
return;
editor.setValue( replaceBackup.replace(regexp, val.getValue()) );
}
}),
$charinsert = $('<div>', {html: $('<div>', {text: '快速插入工具', id: 'inspector-field-title'}),
hideBtn = new OO.ui.ButtonWidget({label: wgULS('关闭', '關閉')})
class: 'inspector-field mw-ajax-loader'}).appendTo('body').draggable().contextmenu(e => {
.on('click', () => {
e.preventDefault();
$replace.hide();
$charinsert.hide();
enable();
}).on('click', '.mw-charinsert-item', function() {
});
const $this = $(this),
$replace = $('<div>', {class: 'inspector-field', html: [
start = $this.data('mw-charinsert-start') || $this.data('start') || '',
$('<div>', {html: ['查找:', ptn.$element]}),
end = $this.data('mw-charinsert-end') || $this.data('end') || '';
$('<div>', {html: [wgULS('替换:', '替換:'), val.$element]}),
editor.replaceSelection( start + editor.getSelection() + end );
$('<div>', {html: [
editor.focus();
new OO.ui.FieldLayout(regex, {label: wgULS('正则', '正則'), align: 'inline'}).$element,
});
new OO.ui.FieldLayout(modifier, {label: $('<i>', {text: 'i'}), align: 'inline'}).$element,
// 为了充分利用浏览器缓存,这里不使用API;注意url转义,这里不需要简化'/mediawiki/index.php'
replaceBtn.$element, undoBtn.$element, hideBtn.$element
$.get({url: mw.util.getUrl(src, {variant: mw.config.get( 'wgUserLanguage' )}),
]})
cache: charInsert.cache !== false, dataType: 'text'}).then(doc => {
]}).appendTo( 'body' ).draggable();
$charinsert.append( $( doc.match(/<body[\s\S]+<\/body>/)[0] ).find( '.mw-parser-output' ) );
}).add(isGadget('charinsert') ? $('<div>', {text: '快速插入'}).click(() => {
}, () => {
if ($charinsert) {
mw.notify([
$charinsert.show();
wgULS('无法加载', '無法載入'),
return;
$('<a>', {text: src, href: mw.util.getUrl(src)}),
}
wgULS('!请检查该页面是否存在。', '!請檢查此頁面是否存在。')
$charinsert = $('<div>', {html: $('<div>', {text: '快速插入工具', id: 'inspector-field-title'}),
], {type: 'error', autoHideSeconds: 'long'});
class: 'inspector-field mw-ajax-loader'}).appendTo('body').draggable().contextmenu(e => {
}).then(() => { $charinsert.removeClass( 'mw-ajax-loader' ); });
e.preventDefault();
}) : null),
$charinsert.hide();
$dropdown = $('<div>', {class: "inspector-menu", html: options}),
}).on('click', '.mw-charinsert-item', function() {
$hints = $('<div>', {class: "inspector-menu"}).on('click', '.inspector-hint', function() {
const $this = $(this),
const cursor = editor.getCursor();
start = $this.data('mw-charinsert-start') || $this.data('start') || '',
editor.replaceRange(this.textContent + (ns > 0 ? '}}' : ']]'),
end = $this.data('mw-charinsert-end') || $this.data('end') || '';
{line: cursor.line, ch: cursor.ch - prefix.length + 1}, cursor);
editor.replaceSelection( start + editor.getSelection() + end );
// 随后再次执行updateHints时会自行stop
editor.focus();
editor.focus();
});
}),
// 为了充分利用浏览器缓存,这里不使用API;注意url转义,这里不需要简化'/mediawiki/index.php'
// 判别模板时可能会误处理解析器函数
$.get({url: mw.util.getUrl(src, {variant: mw.config.get( 'wgUserLanguage' )}),
regexps = {0: /\[\[\s*:?([^|[\]{}<>]*)$/i, 10: /{{\s*([^|[\]{}<>#]*)$/i,
cache: charInsert.cache !== false, dataType: 'text'}).then(doc => {
828: /{{\s*#invoke:\s*([^|[\]{}<>#:]*)$/i, 274: /{{\s*#widget:\s*([^|[\]{}<>#:]*)$/i},
$charinsert.append( $( doc.match(/<body[\s\S]+<\/body>/)[0] ).find( '.mw-parser-output' ) );
$noHint = $('<span>', {class: 'error'}),
}, () => {
nsPrefixes = {0: '', 10: 'Template:', 828: '模块:', 274: 'Widget:'},
mw.notify([
autocomplete = isGadget('autocomplete') ? e => {
wgULS('无法加载', '無法加載'),
if (![9, 27].includes( e.keyCode )) { return; } // tab和esc
$('<a>', {text: src, href: mw.util.getUrl(src)}),
let $cursor, before, sections, title;
wgULS('!请检查该页面是否存在。', '!請檢查該頁面是否存在。')
const cursor = editor.getCursor(),
], {type: 'error', autoHideSeconds: 'long'});
line = editor.getLine( cursor.line ),
}).then(() => { $charinsert.removeClass( 'mw-ajax-loader' ); });
after = line.slice( cursor.ch );
}) : null),
before = line.slice(0, cursor.ch);
$dropdown = $('<div>', {class: "inspector-menu", html: options}),
const cursorActivity = () => {
$hints = $('<div>', {class: "inspector-menu"}).on('click', '.inspector-hint', function() {
const cursornewCursor = editor.getCursor();,
newLine = editor.getLine( newCursor.line ),
editor.replaceRange(this.textContent + (ns > 0 ? '}}' : ']]'),
newAfter = newLine.slice( newCursor.ch );
{line: cursor.line, ch: cursor.ch - prefix.length + 1}, cursor);
// 如果光标改变过位置
// 随后再次执行updateHints时会自行stop
if (newCursor.line != cursor.line || newAfter != after) {
editor.focus();
stop();
}),
return;
// 判别模板时可能会误处理解析器函数
}
regexps = {0: /\[\[\s*:?([^|[\]{}<>]*)$/i, 10: /{{\s*([^|[\]{}<>#]*)$/i,
before = newLine.slice(0, newCursor.ch);
828: /{{\s*#invoke:\s*([^|[\]{}<>#:]*)$/i, 274: /{{\s*#widget:\s*([^|[\]{}<>#:]*)$/i},
updateHints();
$noHint = $('<span>', {class: 'error'}),
},
nsPrefixes = {0: '', 10: 'Template:', 828: '模块:', 274: 'Widget:'},
stop = () => {
autocomplete = isGadget('autocomplete') ? e => {
$hints.slideUp('fast');
if (![9, 27].includes( e.keyCode )) { return; } // tab和esc
editor.off('cursorActivity', cursorActivity);
let $cursor, before, sections, title;
},
const cursor = editor.getCursor(),
updateHints = mw.util.debounce(500, () => {
line = editor.getLine( cursor.line ),
if (!regexps[ns].test( before )) {
after = line.slice( cursor.ch );
stop();
before = line.slice(0, cursor.ch);
return;
const cursorActivity = () => {
}
const newCursor = editor.getCursor(),
$cursor = $wrapper.find( '.CodeMirror-cursor' );
newLine = editor.getLine( newCursor.line ),
prefix = before.match( regexps[ns] )[1];
newAfter = newLine.slice( newCursor.ch );
if (prefix === "" || prefix.startsWith('#')) { return; }
// 如果光标改变过位置
if (ns == '0' && prefix.includes('#')) {
if (newCursor.line != cursor.line || newAfter != after) {
const capture = prefix.match(/^(.+)#(.*)$/);
stop();
prefix = capture[2];
return;
(title == capture[1] ? Promise.resolve() : mw.timedQuery(api, {action: 'parse', page: capture[1],
}
prop: 'sections'}, wgULS('段落标题', '段落標題')).then(r => {
before = newLine.slice(0, newCursor.ch);
title = capture[1];
updateHints();
sections = r.parse.sections.map(ele => $('<div>', {class: 'inspector-hint', text: ele.line}));
},
}, () => { throw null; stop = })).then(() => {
$hints.html( sections.filter(ele => ele.text().startsWith( prefix )) )
$hints.slideUp('fast');
.show().position({my: 'left top', of: $cursor, within: $wrapper, collision: 'fit'});
editor.off('cursorActivity', cursorActivity);
if ($hints.children().length === 0) {
},
$noHint.text(wgULS('不存在对应段落!', '不存在對應段落!')).appendTo( $hints );
updateHints = mw.util.debounce(500, () => {
}
if (!regexps[ns].test( before )) {
}, stop();
return;
}
}
mw.timedQuery(api, {list: 'prefixsearch', pssearch: prefix, psnamespace: ns},
$cursor = $wrapper.find( '.CodeMirror-cursor' );
wgULS('前缀相符的页面', '前綴相符的頁面')).then(r => {
prefix = before.match( regexps[ns] )[1];
$hints.html( r.query.prefixsearch.map(ele =>
if (prefix === "" || prefix.startsWith('#')) { return; }
$('<div>', {class: 'inspector-hint', text: ele.title.slice( nsPrefixes[ns].length )})
if (ns == '0' && prefix.includes('#')) {
) ).show().position({my: 'left top', of: $cursor, within: $wrapper, collision: 'fit'});
const capture = prefix.match(/^(.+)#(.*)$/);
if ($hints.children().length === 0) {
prefix = capture[2];
$noHint.text(wgULS('不存在对应页面!', '不存在對應頁面!')).appendTo( $hints );
(title == capture[1] ? Promise.resolve() : mw.timedQuery(api, {action: 'parse', page: capture[1],
}
prop: 'sections'}, wgULS('段落标题', '段落標題')).then(r => {
}, stop);
title = capture[1];
});
sections = r.parse.sections.map(ele => $('<div>', {class: 'inspector-hint', text: ele.line}));
if (e.keyCode == 27) {
}, () => { throw null; })).then(() => {
stop();
$hints.html( sections.filter(ele => ele.text().startsWith( prefix )) )
return;
.show().position({my: 'left top', of: $cursor, within: $wrapper, collision: 'fit'});
}
if ($hints.children().length === 0) {
editor.execCommand( 'delCharBefore' ); // 删掉新增的\t
$noHint.text(wgULS('不存在对应段落!', '不存在對應段落!')).appendTo( $hints );
$.each(regexps, (k, v) => { if (v.test(before)) { ns = k; } });
}
if (!ns) { return; }
}, stop);
mw.notify(wgULS('开启自动补全提示。', '開啟自動補全提示。'), {tag: 'autocomplete'});
return;
editor.on('cursorActivity', cursorActivity);
}
// 实际上updateHints总是延迟500ms执行,因此下一行代码的位置影响不大
mw.timedQuery(api, {list: 'prefixsearch', pssearch: prefix, psnamespace: ns},
updateHints();
wgULS('前缀相符的页面', '前綴相符的頁面')).then(r => {
} : () => {};
$hints.html( r.query.prefixsearch.map(ele =>
mw.loader.using(['jquery.ui', 'user.options']).then(() => {
$('<div>', {class: 'inspector-hint', text: ele.title.slice( nsPrefixes[ns].length )})
const actionP = new OO.ui.ActionWidget({label: '是', target: '_blank', flags: 'progressive'}),
) ).show().position({my: 'left top', of: $cursor, within: $wrapper, collision: 'fit'});
actionD = new OO.ui.ActionWidget({label: '否'}),
if ($hints.children().length === 0) {
$url = $('<a>'), // 桌面版CSS不必需href
$noHint.text(wgULS('不存在对应页面!', '不存在對應頁面!')).appendTo( $hints );
label = [wgULS('要在新标签页打开', '要在新分頁打開'), $url, wgULS('吗?', '嗎?')];
}
$outer.on('contextmenu', '.cm-mw-template-name', function() {
}, stop);
const template = '模板:' + $(this).text();
});
// 这里增加一次确认界面是因为部分浏览器不允许JS直接打开新标签页。
if (e.keyCode == 27) {
$url.text( template );
stop();
actionP.setHref( mw.util.getUrl(template) ); // 注意url转义
return;
mw.dialog(dialog, [actionD, actionP], label).catch(() => {});
}
return false; // 这里需要同时执行stopImmediatePropagation()和preventDefault()
editor.execCommand( 'delCharBefore' ); // 删掉新增的\t
}).on('contextmenu', '.CodeMirror', e => {
$.each(regexps, (k, v) => { if (v.test(before)) { ns = k; } });
e.preventDefault();
if (!ns) { return; }
// 使用jquery.ui让菜单总是落在CodeMirror内,此时slideDown效果不生效
mw.notify(wgULS('开启自动补全提示。', '開啟自動補全提示。'), {tag: 'autocomplete'});
$dropdown.show().position({my: 'left top', of: e, within: $wrapper, collision: 'fit'});
editor.on('cursorActivity', cursorActivity);
}).on('keydown', '.CodeMirror', autocomplete).resizable( {handles: 'w', minWidth: 350} );
// 实际上updateHints总是延迟500ms执行,因此下一行代码的位置影响不大
});
updateHints();
$('body').click(() => { $dropdown.slideUp('fast'); });
} : () => {};
btns[0].$element.contextmenu(e => {
mw.loader.using(['jquery.ui', 'user.options']).then(() => {
e.preventDefault();
const actionP = new OO.ui.ActionWidget({label: '是', target: '_blank', flags: 'progressive'}),
OO.ui.prompt( wgULS('请输入编辑摘要:', '請輸入編輯摘要:') , {textInput: {value: summary}} ).then(input => {
actionD = new OO.ui.ActionWidget({label: '否'}),
if (input !== null) { summary = input; }
$url = $('<a>'), // 桌面版CSS不必需href
});
label = [wgULS('要在新标签页打开', '要在新標籤頁打開'), $url, wgULS('吗?', '嗎?')];
});
$outer.on('contextmenu', '.cm-mw-template-name', function() {
if (isBackup) {
const template = '模板:' + $(this).text();
btns[2].$element.contextmenu(e => {
// 这里增加一次确认界面是因为部分浏览器不允许JS直接打开新标签页。
e.preventDefault();
$url.text( template );
loadBackup();
actionP.setHref( mw.util.getUrl(template) ); // 注意url转义
});
mw.dialog(dialog, [actionD, actionP], label).catch(() => {});
}
return false; // 这里需要同时执行stopImmediatePropagation()和preventDefault()
if (isGadget( 'PreviewWithVariant' ) ) {
}).on('contextmenu', '.CodeMirror', e => {
const options = [{label: "大陆简体", data: "zh-cn"}, {label: "香港繁體", data: "zh-hk"},
e.preventDefault();
{label: "澳門繁體", data: "zh-mo"}, {label: "大马简体", data: "zh-my"},
// 使用jquery.ui让菜单总是落在CodeMirror内,此时slideDown效果不生效
{label: "新加坡简体", data: "zh-sg"}, {label: "臺灣正體", data: "zh-tw"}],
$dropdown.show().position({my: 'left top', of: e, within: $wrapper, collision: 'fit'});
select = new OO.ui.DropdownInputWidget({classes: ['inspector-variant'], options: options, value: lang})
}).on('keydown', '.CodeMirror', autocomplete).resizable( {handles: 'w', minWidth: 350} );
.on('change', () => { lang = select.getValue(); }),
});
menu = select.$element.find( '.oo-ui-menuSelectWidget' )
$('body').click(() => { $dropdown.slideUp('fast'); });
.click(() => { menu.addClass( 'oo-ui-element-hidden' ); });
btns[0].$element.contextmenu(e => {
select.$element.prependTo( btns[1].$element );
e.preventDefault();
btns[1].$element.contextmenu(e => {
OO.ui.prompt( '请输入编辑摘要:' , {textInput: {value: summary}} ).then(input => {
e.preventDefault();
if (input !== null) { summary = input; }
menu.removeClass( 'oo-ui-element-hidden' );
});
}).children('a').blur(() => { menu.addClass( 'oo-ui-element-hidden' ); });
});
}
if (isBackup) {
pEmpty( $original );
btns[2].$element.contextmenu(e => {
// $.when很容易出错,这里保险起见用Promise.all
e.preventDefault();
Promise.all([getJSON, mw.request, getExt]).then(data => {
loadBackup();
mw.hook( 'codemirror.config' ).fire();
});
text = data[1].query.pages[0].revisions[0].content;
}
editor = new CodeMirror($outer[0], {value: text, mode: 'text/mediawiki',
if (isGadget( 'PreviewWithVariant' ) ) {
mwConfig: mw.config.get('extCodeMirrorConfig'), lineWrapping: true, lineNumbers: true
const options = [{label: "大陆简体", data: "zh-cn"}, {label: "香港繁體", data: "zh-hk"},
});
{label: "澳門繁體", data: "zh-mo"}, {label: "马来西亚简体", data: "zh-my"},
$wrapper = $( editor.getWrapperElement() ).toggle().append( [$dropdown, $hints] );
{label: "新加坡简体", data: "zh-sg"}, {label: "臺灣繁體", data: "zh-tw"}],
$('<div>', {id: 'inspector-btns', html: btns.map(ele => ele.$element)}).appendTo( $outer );
select = new OO.ui.DropdownInputWidget({classes: ['inspector-variant'], options: options, value: lang})
// 处理页面上方的差异
.on('change', () => { lang = select.getValue(); }),
$('.diff').click(e => {
menu = select.$element.find( '.oo-ui-menuSelectWidget' )
const row = $( e.target ).closest('tr');
.click(() => { menu.addClass( 'oo-ui-element-hidden' ); });
if (row.hasClass( 'diff-title' )) { return; }
select.$element.prependTo( btns[1].$element );
const isLineno = row.children( '.diff-lineno' ).length ? 1 : 0,
btns[1].$element.contextmenu(e => {
rowLineno = isLineno ? row : row.prevAll( ':has(.diff-lineno)' ).first(),
e.preventDefault();
n = parseInt( rowLineno.children().last().text().match(/\d+/) ) + row.index() - rowLineno.index()
menu.removeClass( 'oo-ui-element-hidden' );
- 2 + isLineno, // 使用parseInt规避可能的程序错误,注意CodeMirror的行号从0开始
}).children('a').blur(() => { menu.addClass( 'oo-ui-element-hidden' ); });
nLine = editor.lastLine();
}
if (nLine >= n) {
pEmpty( $original );
editor.scrollIntoView(nLine);
// $.when很容易出错,这里保险起见用Promise.all
editor.scrollIntoView(n);
Promise.all([getJSON, mw.request, getExt]).then(data => {
}
mw.config.set('extCodeMirrorConfig', data[0]);
else { mw.notify( wgULS('当前不存在该行!', '目前不存在此行!'), {type: 'warn'} ); }
mw.hook( 'codemirror.config' ).fire();
});
text = data[1].query.pages[0].revisions[0].content;
}, reason => { mw.apiFailure(reason, `CodeMirror${wgULS('设置或页面', '設定或頁面')}Wikitext`); })
editor = new CodeMirror($outer[0], {value: text, mode: 'text/mediawiki', mwConfig: data[0],
.then(() => { $outer.removeClass( 'mw-ajax-loader' ); });
lineWrapping: true, lineNumbers: true});
$wrapper = $( editor.getWrapperElement() ).toggle().append( [$dropdown, $hints] );
$('<div>', {id: 'inspector-btns', html: btns.map(ele => ele.$element)}).appendTo( $outer );
// 处理页面上方的差异
$('.diff').click(e => {
const row = $( e.target ).closest('tr');
if (row.hasClass( 'diff-title' )) { return; }
const isLineno = row.children( '.diff-lineno' ).length ? 1 : 0,
rowLineno = isLineno ? row : row.prevAll( ':has(.diff-lineno)' ).first(),
n = parseInt( rowLineno.children().last().text().match(/\d+/) ) + row.index() - rowLineno.index()
- 2 + isLineno, // 使用parseInt规避可能的程序错误,注意CodeMirror的行号从0开始
nLine = editor.lastLine();
if (nLine >= n) {
editor.scrollIntoView(nLine);
editor.scrollIntoView(n);
}
else { mw.notify( wgULS('当前不存在该行!', '當前不存在該行!'), {type: 'warn'} ); }
});
}, reason => { mw.apiFailure(reason, `CodeMirror${wgULS('设置或页面', '設置或頁面')}Wikitext`); })
.then(() => { $outer.removeClass( 'mw-ajax-loader' ); });
});
//</nowiki>
6,698

个编辑

导航菜单