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

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

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

个编辑

导航菜单